Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • coregraphie/ptspar
  • grossi/ptspar
2 results
Show changes
Commits on Source (19)
Copyright (c) 2012 Vladimir Keleshev, <vladimir@keleshev.com>
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.
\ No newline at end of file
#include <iostream>
#include <chrono>
#include "p_k_compression.h"
#include <boost/program_options.hpp>
#include "graph.h"
#include "io.h"
#include <sstream>
#include <string>
#include <fstream>
#include "hash.h"
#include <omp.h>
#define NUM_TRIALS 10
using namespace std;
namespace po = boost::program_options;
......@@ -51,45 +51,59 @@ int main(int argc, char *argv[]) {
vector<int> s ;
vector<double> c ;
// perform 30 experiments
for (int i =0; i<30;i++) {
cout << i << endl;
string file_name = var["input"].as<string>() + to_string(i) + ".txt";
double compression_rate = 0;
auto[g, e_s] = read_graph_from_file(file_name, var["directed"].as<bool>());
auto start = chrono::steady_clock::now();
if (var["algorithm"].as<string>() == "Random") {
g2 = compress_graph_basic(g, var["depth"].as<int>(), var["proportions"].as<vector<double>>(),
int edges_compressed = 0;
string file_name = var["input"].as<string>();
double compression_rate = 0;
double elapsed_time = 0;
auto[g, e_s] = read_graph_from_file(file_name, var["directed"].as<bool>());
auto start = chrono::steady_clock::now();
string execMode=var["algorithm"].as<string>();
#pragma omp parallel for num_threads(NUM_TRIALS)
for (int i = 0; i < NUM_TRIALS; i++) {
auto start = std::chrono::steady_clock::now();
if (execMode == "Random") {
g2 = compress_graph_basic(g, var["depth"].as<int>(), var["proportions"].as<std::vector<double>>(),
var["directed"].as<bool>());
} else if (var["algorithm"].as<string>() == "LP") {
g2 = compress_graph_LP(g, e_s, var["depth"].as<int>(), var["proportions"].as<vector<double>>(),
var["directed"].as<bool>());
} else if (execMode == "LP") {
g2 = compress_graph_LP(g, e_s, var["depth"].as<int>(), var["proportions"].as<std::vector<double>>(),
var["directed"].as<bool>());
} else if (var["algorithm"].as<string>() == "SA") {
} else if (execMode == "SA") {
g2 = Simulated_annealing(1000, 10, 0.99, g, var["directed"].as<bool>(), var["depth"].as<int>(),
var["proportions"].as<vector<double>>());
}else if (var["algorithm"].as<string>() == "Greedy") {
g2 = compress_graph_greedy(g, var["depth"].as<int>(), var["proportions"].as<vector<double>>(),
var["directed"].as<bool>());
var["proportions"].as<std::vector<double>>());
} else if (execMode == "Greedy") {
g2 = compress_graph_greedy(g, var["depth"].as<int>(), var["proportions"].as<std::vector<double>>(),
var["directed"].as<bool>());
}
auto finish = std::chrono::steady_clock::now();
// Update edges_compressed and elapsed_time in a thread-safe manner
#pragma omp critical
{
vector<edge> edges_original = get_edges(g, var["directed"].as<bool>());
edges_compressed += get_edges(g2, var["directed"].as<bool>()).size();
elapsed_time += std::chrono::duration_cast<std::chrono::duration<double>>(finish - start).count();
}
auto finish = chrono::steady_clock::now();
vector<edge> edges_original = get_edges(g, var["directed"].as<bool>());
vector<edge> edges_compressed = get_edges(g2, var["directed"].as<bool>());
double elapsed_time = chrono::duration_cast<chrono::duration<double>>(finish - start).count();
compression_rate = ((double) (edges_original.size() - edges_compressed.size()) /
edges_original.size());
c.push_back(compression_rate);
s.push_back(edges_compressed.size());
//graph_to_file(var, elapsed_time, compression_rate, edges_compressed);
cout << "compression time " << elapsed_time << endl;
cout << "compression rate " << compression_rate << endl;
}
for (int i = 0 ; i<30;i++) cout << c.at(i) << '\t' << s.at(i) << endl;
return 0;
// graph_to_file(var, elapsed_time, compression_rate, edges_compressed);
// cout << "compression rate: " << compression_rate << endl;
cout <<endl << "compression time: " << elapsed_time/NUM_TRIALS << endl;
cout << "Average of compressed edges: " << edges_compressed/NUM_TRIALS;
}
File added
import numpy as np
from cylp.cy import CyClpSimplex
from cylp.py.modeling.CyLPModel import CyLPModel, CyLPArray
from cylp.py.mip import SimpleNodeCompare
from cylp.cy.CyCgl import CyCglGomory, CyCglClique, CyCglKnapsackCover
from cylp.py.utils.sparseUtil import csr_matrixPlus
import networkx as nx
import numpy as np
import time
import sys
from scipy.sparse import csc_matrix
def load_graph(file_path, isdirected):
f = open(file_path,"r")
if isdirected :
G = nx.DiGraph() # the graph is directed
else:
G = nx.Graph() # the graph is undirected
lines = f.readlines()
for line in lines :
nodes = line.split('\t')
if int(nodes[0])!=int(nodes[1]):
#G.add_node(int(nodes[0]))
#G.add_node(int(nodes[1]))
G.add_edge(int(nodes[0]),int(nodes[1]))
return G
def PL_variables(G,t,pr):
all_paths = []
edges_dict ={} # key : edge , value : edge index
dict_paths ={} # key : edge , value : path index
# init
for n in G.nodes() :
for n2 in list(G.neighbors(n)):
dict_paths[(n,n2)] = []
#dict_paths[(n2,n)] = []
# Extract all simple path with length <= t
edges= list(G.edges())
i = 0
nodes = list(G.nodes())
for i1 in range(len(nodes)-1):
n = nodes[i1]
for i2 in range(i1+1,len(nodes)) :
l = nodes[i2]
paths = nx.all_simple_paths(G,source =n ,target = l, cutoff= t)
l_path = [ list(p) for p in map(nx.utils.pairwise, paths)]
for p in l_path :
all_paths.append(p)
if l in list(G.neighbors(n)) :
dict_paths[(n,l)].append(len(edges)+i)
dict_paths[(l,n)].append(len(edges)+i)
i+=1
print("The number of paths : " + str(len(all_paths)))
# creating edges dict
edges_dict ={}
i = 0
for e in edges :
u = e[0]
v = e[1]
edges_dict[(u,v)] = i
edges_dict[(v,u)] = i
i+=1
# creating pl variables
objs = [1 for i in range(len(edges))] + [0 for j in range(len(all_paths))]
lhs_ineqs_r = []
lhs_ineqs_c = []
lhs_ineqs_d = []
lhs_ineqs2_r = []
lhs_ineqs2_c = []
lhs_ineqs2_d = []
rhs_ineqs = []
rhs_ineqs2 = []
# inequality (3)
r_i = 0
path_index = len(edges)
for path in all_paths :
for e in path :
lhs_ineqs_r.append(r_i)
lhs_ineqs_c.append(edges_dict[e])
lhs_ineqs_d.append(-1)
lhs_ineqs_r.append(r_i)
lhs_ineqs_c.append(path_index)
lhs_ineqs_d.append(1)
rhs_ineqs.append(0)
r_i+=1
path_index+=1
# inequality (4)
for e in edges :
u,v = e
if v < u:
e =(v,u)
find =False
for i in dict_paths[e] :
find = True
lhs_ineqs_r.append(r_i)
lhs_ineqs_c.append(i)
lhs_ineqs_d.append(1)
if find :
r_i+=1
rhs_ineqs.append(1)
# inequality (5)
r_i2 = 0
for i in range(1,t+1):
for u in G.nodes():
find = False
for v in list(G.neighbors(u)):
pis = dict_paths[(u,v)]
if v < u :
pis = dict_paths[(v,u)]
for pi in pis:
if (len(all_paths[pi-len(edges)])<= i):
find = True
lhs_ineqs2_r.append(r_i2)
lhs_ineqs2_c.append(pi)
lhs_ineqs2_d.append(1)
if find :
r_i2+=1
prsn = pr[i]*len(list(G.neighbors(u)))
rhs_ineqs2.append(prsn)
row = np.array(lhs_ineqs_r)
col = np.array(lhs_ineqs_c)
data = np.array(lhs_ineqs_d)
lhs_ineqs = csc_matrix((data, (row, col)), shape=(r_i, len(objs)))
row = np.array(lhs_ineqs2_r)
col = np.array(lhs_ineqs2_c)
data = np.array(lhs_ineqs2_d)
lhs_ineqs2 = csc_matrix((data, (row, col)), shape=(r_i2, len(objs)))
return objs,lhs_ineqs,rhs_ineqs,lhs_ineqs2,rhs_ineqs2
def save_graph(G,filename):
file = open(file_name,"w")
for e in G.edges():
file.write(str(e[0])+'\t'+str(e[1])+ "\n")
file.close()
if __name__ == "__main__":
np.set_printoptions(threshold=sys.maxsize)
for i in range(30):
file_name = sys.argv[1] + str(i) + ".txt"
file_name_o = sys.argv[2] + str(i) + "_PL.txt"
algo = sys.argv[3]
G = load_graph( file_name , False)
t = 2
p = [0,0.0,0.5]
print ("Computing variables . . . ")
start = time.time()
objs,lhs_ineqs,rhs_ineqs,lhs_ineqs2,rhs_ineqs2 = PL_variables(G,t,p)
end = time.time()
print("Runtime : " + str( end-start ))
print("Solving the linear problem . . . ")
s = CyClpSimplex()
x = s.addVariable('x',len(objs),isInt=True)
#s.setInteger(x[0:len(objs)])
# Create coefficients and bounds
A = lhs_ineqs
a = CyLPArray(rhs_ineqs)
B = lhs_ineqs2
b = CyLPArray(rhs_ineqs2)
# Add constraints
s += A * x <= a
s += 0 <= x <= 1
s += B * x >= b
# Set the objective function
c = CyLPArray(objs)
s.objective = c * x
if ( algo == '1' ) :
print("Relaxed problem")
s.primal()
sol = s.primalVariableSolution['x']
else :
print("Integer linear programming")
s.copyInIntegerInformation(np.array ( s.nCols * [ True ], np.uint8 ))
cbcModel = s.getCbcModel ()
cbcModel.solve()
sol = cbcModel.primalVariableSolution['x']
end = time.time()
print("Runtime : " + str( end-start ))
data = np.asarray(sol)
score_list = list(data)
scores = score_list[0:len(list(G.edges()))]
edges = list(G.edges())
for i in range(len(scores)) :
if scores[i] < 0 :
scores[i] = 0
# sorting the edges
dict_edges_scores = {}
for i in range(len(scores)) :
dict_edges_scores[i] = scores[i]
sorted_edges = list({k: v for k, v in sorted(dict_edges_scores.items(), key=lambda item: item[1],reverse=True)}.keys())
file = open(file_name_o,"w")
for s in sorted_edges:
file.write(str(edges[s][0])+'\t'+str(edges[s][1])+'\t'+ str(dict_edges_scores[s])+ "\n")
file.close()
\ No newline at end of file
# ptSpar
# README for ptSpar
## Introduction
ptSpar is a C++ program implementing a Neighborhood-Preserving Graph Sparsification technique. This tool reduces graph sizes while maintaining essential neighborhood information, aiding in various graph analysis tasks.
## Getting started
## Requirements
- C++11 compliant compiler (e.g., GCC)
- Boost Program Options Library
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.liris.cnrs.fr/coregraphie/ptspar.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.liris.cnrs.fr/coregraphie/ptspar/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Compilation
1. **Install Boost Library:** Ensure the Boost Program Options library is installed on your system.
2. **Compilation Command:** In the source directory, compile using `g++ -std=c++11 main.cpp -o ptSpar -lboost_program_options`.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
- **Basic Command Structure:**
```bash
./ptSpar --input [input file] --output_file [output file] [additional options]
```
- **Key Options:**
- `--input`: Path to the input graph file.
- `--output_file`: Path for the output (compressed graph).
- `--directed`: Specify if the graph is directed (true/false).
- `--algorithm`: Choose the compression algorithm (e.g., Random, LP, SA, Greedy).
- `--depth`: Define the depth of the compression.
- `--proportions`: Set preserving proportions.
## Example
```bash
./ptSpar --input myGraph.txt --output_file compressedGraph.txt --directed true --algorithm Random --depth 2 --proportions 0.5 0.5
```
File added