├── .gitignore
├── .idea
├── .gitignore
├── Deep-Object-Search-With-Hash.iml
├── inspectionProfiles
│ ├── Project_Default.xml
│ └── profiles_settings.xml
├── misc.xml
├── modules.xml
└── vcs.xml
├── Demo_Video
├── Screenshot from query_result.mp4 - 3.png
├── Shotwell query_result.mp4 - 3.jpg
└── test.txt
├── LICENSE
├── README.md
├── create_folder.py
├── lshash
├── PCA_Discrete.py
├── __init__.py
├── lshash.py
├── lshash_2.py
├── lshash_2_py3.py
├── storage.py
└── utils.py
├── objFeature
└── features_vgg-19
│ └── features_vgg-19.npy
├── objSr
├── bin
│ ├── activate
│ ├── activate.csh
│ ├── activate.fish
│ ├── chardetect
│ ├── easy_install
│ ├── easy_install-3.6
│ ├── estimator_ckpt_converter
│ ├── f2py
│ ├── f2py3
│ ├── f2py3.6
│ ├── flask
│ ├── freeze_graph
│ ├── google-oauthlib-tool
│ ├── imageio_download_bin
│ ├── imageio_remove_bin
│ ├── markdown_py
│ ├── pip
│ ├── pip3
│ ├── pip3.6
│ ├── pyrsa-decrypt
│ ├── pyrsa-encrypt
│ ├── pyrsa-keygen
│ ├── pyrsa-priv2pub
│ ├── pyrsa-sign
│ ├── pyrsa-verify
│ ├── pytesseract
│ ├── python
│ ├── python3
│ ├── python3.6
│ ├── range-detector
│ ├── saved_model_cli
│ ├── skivi
│ ├── tensorboard
│ ├── tf_upgrade_v2
│ ├── tflite_convert
│ ├── toco
│ ├── toco_from_protos
│ └── wheel
├── lib64
├── pyvenv.cfg
└── share
│ ├── doc
│ └── networkx-2.4
│ │ ├── LICENSE.txt
│ │ ├── examples
│ │ ├── 3d_drawing
│ │ │ ├── README.txt
│ │ │ └── mayavi2_spring.py
│ │ ├── README.txt
│ │ ├── advanced
│ │ │ ├── README.txt
│ │ │ ├── plot_eigenvalues.py
│ │ │ ├── plot_heavy_metal_umlaut.py
│ │ │ ├── plot_iterated_dynamical_systems.py
│ │ │ └── plot_parallel_betweenness.py
│ │ ├── algorithms
│ │ │ ├── README.txt
│ │ │ ├── hartford_drug.edgelist
│ │ │ ├── plot_beam_search.py
│ │ │ ├── plot_blockmodel.py
│ │ │ ├── plot_davis_club.py
│ │ │ ├── plot_krackhardt_centrality.py
│ │ │ └── plot_rcm.py
│ │ ├── basic
│ │ │ ├── README.txt
│ │ │ ├── plot_properties.py
│ │ │ └── plot_read_write.py
│ │ ├── drawing
│ │ │ ├── README.txt
│ │ │ ├── chess_masters_WCC.pgn.bz2
│ │ │ ├── knuth_miles.txt.gz
│ │ │ ├── lanl_routes.edgelist
│ │ │ ├── plot_atlas.py
│ │ │ ├── plot_chess_masters.py
│ │ │ ├── plot_circular_tree.py
│ │ │ ├── plot_degree_histogram.py
│ │ │ ├── plot_degree_rank.py
│ │ │ ├── plot_directed.py
│ │ │ ├── plot_edge_colormap.py
│ │ │ ├── plot_ego_graph.py
│ │ │ ├── plot_four_grids.py
│ │ │ ├── plot_giant_component.py
│ │ │ ├── plot_house_with_colors.py
│ │ │ ├── plot_knuth_miles.py
│ │ │ ├── plot_labels_and_colors.py
│ │ │ ├── plot_lanl_routes.py
│ │ │ ├── plot_node_colormap.py
│ │ │ ├── plot_random_geometric_graph.py
│ │ │ ├── plot_sampson.py
│ │ │ ├── plot_simple_path.py
│ │ │ ├── plot_spectral_grid.py
│ │ │ ├── plot_unix_email.py
│ │ │ ├── plot_weighted_graph.py
│ │ │ └── unix_email.mbox
│ │ ├── graph
│ │ │ ├── README.txt
│ │ │ ├── dot_atlas.py
│ │ │ ├── plot_degree_sequence.py
│ │ │ ├── plot_erdos_renyi.py
│ │ │ ├── plot_expected_degree_sequence.py
│ │ │ ├── plot_football.py
│ │ │ ├── plot_karate_club.py
│ │ │ ├── plot_napoleon_russian_campaign.py
│ │ │ ├── plot_roget.py
│ │ │ ├── plot_words.py
│ │ │ ├── roget_dat.txt.gz
│ │ │ └── words_dat.txt.gz
│ │ ├── javascript
│ │ │ ├── README.txt
│ │ │ ├── force.py
│ │ │ └── force
│ │ │ │ ├── README.txt
│ │ │ │ ├── force.css
│ │ │ │ ├── force.html
│ │ │ │ └── force.js
│ │ ├── jit
│ │ │ ├── README.txt
│ │ │ └── plot_rgraph.py
│ │ ├── pygraphviz
│ │ │ ├── README.txt
│ │ │ ├── plot_pygraphviz_attributes.py
│ │ │ ├── plot_pygraphviz_draw.py
│ │ │ ├── plot_pygraphviz_simple.py
│ │ │ └── plot_write_dotfile.py
│ │ └── subclass
│ │ │ ├── README.txt
│ │ │ ├── plot_antigraph.py
│ │ │ └── plot_printgraph.py
│ │ └── requirements.txt
│ └── python-wheels
│ ├── CacheControl-0.11.7-py2.py3-none-any.whl
│ ├── appdirs-1.4.3-py2.py3-none-any.whl
│ ├── certifi-2018.1.18-py2.py3-none-any.whl
│ ├── chardet-3.0.4-py2.py3-none-any.whl
│ ├── colorama-0.3.7-py2.py3-none-any.whl
│ ├── distlib-0.2.6-py2.py3-none-any.whl
│ ├── distro-1.0.1-py2.py3-none-any.whl
│ ├── html5lib-0.999999999-py2.py3-none-any.whl
│ ├── idna-2.6-py2.py3-none-any.whl
│ ├── ipaddress-0.0.0-py2.py3-none-any.whl
│ ├── lockfile-0.12.2-py2.py3-none-any.whl
│ ├── packaging-17.1-py2.py3-none-any.whl
│ ├── pip-9.0.1-py2.py3-none-any.whl
│ ├── pkg_resources-0.0.0-py2.py3-none-any.whl
│ ├── progress-1.2-py2.py3-none-any.whl
│ ├── pyparsing-2.2.0-py2.py3-none-any.whl
│ ├── requests-2.18.4-py2.py3-none-any.whl
│ ├── retrying-1.3.3-py2.py3-none-any.whl
│ ├── setuptools-39.0.1-py2.py3-none-any.whl
│ ├── six-1.11.0-py2.py3-none-any.whl
│ ├── urllib3-1.22-py2.py3-none-any.whl
│ ├── webencodings-0.5-py2.py3-none-any.whl
│ └── wheel-0.30.0-py2.py3-none-any.whl
├── object_detection_YOLO.py
├── requirements.txt
└── start.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | /venv/
7 | /temp/
8 | objFeature/
9 | /Cropped_Images/
10 |
11 | *.npy
12 | # C extensions
13 | *.so
14 |
15 | # Distribution / packaging
16 | .Python
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | .eggs/
23 | lib/
24 | lib64/
25 | parts/
26 | sdist/
27 | var/
28 | wheels/
29 | pip-wheel-metadata/
30 | share/python-wheels/
31 | *.egg-info/
32 | .installed.cfg
33 | *.egg
34 | MANIFEST
35 |
36 | # PyInstaller
37 | # Usually these files are written by a python script from a template
38 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
39 | *.manifest
40 | *.spec
41 |
42 | # Installer logs
43 | pip-log.txt
44 | pip-delete-this-directory.txt
45 |
46 | # Unit test / coverage reports
47 | htmlcov/
48 | .tox/
49 | .nox/
50 | .coverage
51 | .coverage.*
52 | .cache
53 | nosetests.xml
54 | coverage.xml
55 | *.cover
56 | *.py,cover
57 | .hypothesis/
58 | .pytest_cache/
59 |
60 | # Translations
61 | *.mo
62 | *.pot
63 |
64 | # Django stuff:
65 | *.log
66 | local_settings.py
67 | db.sqlite3
68 | db.sqlite3-journal
69 |
70 | # Flask stuff:
71 | instance/
72 | .webassets-cache
73 |
74 | # Scrapy stuff:
75 | .scrapy
76 |
77 | # Sphinx documentation
78 | docs/_build/
79 |
80 | # PyBuilder
81 | target/
82 |
83 | # Jupyter Notebook
84 | .ipynb_checkpoints
85 |
86 | # IPython
87 | profile_default/
88 | ipython_config.py
89 |
90 | # pyenv
91 | .python-version
92 |
93 | # pipenv
94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
97 | # install all needed dependencies.
98 | #Pipfile.lock
99 |
100 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
101 | __pypackages__/
102 |
103 | # Celery stuff
104 | celerybeat-schedule
105 | celerybeat.pid
106 |
107 | # SageMath parsed files
108 | *.sage.py
109 |
110 | # Environments
111 | .env
112 | .venv
113 | env/
114 | venv/
115 | ENV/
116 | objSr/
117 | env.bak/
118 | venv.bak/
119 |
120 | # Spyder project settings
121 | .spyderproject
122 | .spyproject
123 |
124 | # Rope project settings
125 | .ropeproject
126 |
127 | # mkdocs documentation
128 | /site
129 |
130 | # mypy
131 | .mypy_cache/
132 | .dmypy.json
133 | dmypy.json
134 |
135 | # Pyre type checker
136 | .pyre/
137 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.idea/Deep-Object-Search-With-Hash.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | <<<<<<< HEAD
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | =======
14 |
15 |
16 |
17 | >>>>>>> 6c2bc56858d0b33ff9dfe8ced594253f2a9a0289
18 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <<<<<<< HEAD
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 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 | >>>>>>> 6c2bc56858d0b33ff9dfe8ced594253f2a9a0289
88 |
89 |
90 |
91 |
92 | <<<<<<< HEAD
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 | =======
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 | >>>>>>> 6c2bc56858d0b33ff9dfe8ced594253f2a9a0289
121 |
122 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | <<<<<<< HEAD
4 |
5 | =======
6 |
7 | >>>>>>> 6c2bc56858d0b33ff9dfe8ced594253f2a9a0289
8 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Demo_Video/Screenshot from query_result.mp4 - 3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/Demo_Video/Screenshot from query_result.mp4 - 3.png
--------------------------------------------------------------------------------
/Demo_Video/Shotwell query_result.mp4 - 3.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/Demo_Video/Shotwell query_result.mp4 - 3.jpg
--------------------------------------------------------------------------------
/Demo_Video/test.txt:
--------------------------------------------------------------------------------
1 | text
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Faisal Ahmed Siddiqi, Anis-Ul-Islam Rafid
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Deep-Object-Search-With-Hash
2 |
3 | ## A Short Description Of Project
4 |
5 | This repo contains an object search mechanism with hashing techniques using deep features of available pretrained object detection models. It can detect multiple objects from a given video then read features of those objects from a chosen feature extractor. Afterwards those features are transformed into hash codes using LSH(Locality Sensitive Hashing) technique and indexed into a python “Dictionary”.Finally for a given video it takes objects from the video as a query image and displays the close matched images which features have been previously indexed with hash codes.
6 |
7 | 
8 |
9 | ## Demo Video Link
10 |
11 | [click here](https://youtu.be/Cxnqk-bWPCc)
12 |
13 | ## Acknowledgements
14 |
15 | To learn more about LSH(Locality Sensitive Hashing)
16 |
17 | visit:
18 |
19 | https://github.com/kayzhu/LSHash
20 |
21 | and
22 |
23 | https://github.com/pixelogik/NearPy
24 |
25 |
26 | ## Environment Setup:
27 |
28 |
29 | ### Installation instructions
30 |
31 | _Run the commands in a terminal or command-prompt.
32 |
33 | - Install `Python 3.6 or >3.6` for your operating system, if it does not already exist.
34 |
35 | - For [Mac](https://www.python.org/ftp/python/3.6.8/python-3.6.8-macosx10.9.pkg)
36 |
37 | - For [Windows](https://www.python.org/ftp/python/3.6.8/python-3.6.8-amd64.exe)
38 |
39 | - For Ubuntu/Debian
40 |
41 | ```bash
42 | sudo apt-get install python3.6
43 | ```
44 |
45 | Check if the correct version of Python (3.6) is installed.
46 |
47 | ```bash
48 | python --version
49 | ```
50 |
51 | **Make sure your terminal is at the root of the project i.e. where 'README.md' is located.**
52 |
53 | * Get `virtualenv`.
54 |
55 | ```bash
56 | pip install virtualenv
57 | ```
58 |
59 | * Create a virtual environment named `.env` using python `3.6` and activate the environment.
60 |
61 | ```bash
62 | # command for gnu/linux systems
63 | virtualenv -p $(which python3.6) .env
64 |
65 | source .env/bin/activate
66 | ```
67 | * If any error occurs to install a virtual environment you can see this [link](https://github.com/anisrfd/Python-Virtualenv-Setup/blob/master/Python_virtualenv_setup.md)
68 |
69 |
70 | * Install python dependencies from requirements.txt.
71 | ```bash
72 | pip install -r requirements.txt
73 | ```
74 |
75 |
76 | ## How to run
77 |
78 | After installing all the required libraries run the following commands in the terminal. The details of required input parameters have been described in the following section.
79 |
80 |
81 |
82 | * Step 1:
83 | First run object detection script from terminal using following command
84 |
85 | ```bash
86 | python object_detection_YOLO.py --video_dir
87 | ```
88 | Example :
89 | ```bash
90 | python object_detection_YOLO.py --video_dir VideoFileDirectory
91 | ```
92 | This will create a directory named “temp” in your project directory and under this directory, subdirectories will also be created according to object class or category.
93 | Object class wise cropped images will be saved into those subdirectories.
94 |
95 | Currently 7 object classes are available. You can use other object classes by changing the parameter name and value.
96 |
97 | Person
98 | Bicycle
99 | Car
100 | Bike
101 | Bus
102 | truck
103 | Chair
104 |
105 |
106 | * Step 2 :
107 | After the completion of step 1 , run the the following command from terminal
108 |
109 | Example :
110 | ```bash
111 | python start.py --range 350 --hash_length 48 --type discrete --function pca --n_of_HPT 5 --n_of_NN 20 --DSF 16 --QOC person --RNF True --TVD VideoFileDirectory
112 | ```
113 | Options for feature extraction from pretrained models will appear on terminal.
114 |
115 | Currently 3 pretrained models are available:
116 |
117 | Resnet-50
118 | VGG-19
119 | MobileNet-SSD
120 |
121 | For the first time select Resnet-50 and hit Enter Button then you will see features of object images saved in “temp/person” being extracted and indexed.
122 |
123 | After indexing all features a video(path given in the input arguments) will start to play and press 'Q' to pause the video you will see another gallery window showing Query Image and corresponding Query Results. Then again press 'Q' to continue.
124 |
125 | ## Description of Input arguments
126 |
127 | ##### range :
128 | Number of images to be read from directory
129 |
130 | ##### hash_length :
131 | Length of hash key to be generated from features
132 | ##### type :
133 | Type of hash keys, currently "Binary and Discrete" hash types are available
134 |
135 | ##### functions :
136 | Type of hash functions
137 |
138 | --n_of_HPT :
139 | Number of hash function per table (Python dictionary object)
140 |
141 | --n_of_NN
142 | Number of nearest neighbour for NN search
143 |
144 | --RNF
145 | Read New Features (RNF) from object image directory
146 |
147 | --DSF
148 | Downsampling Factor
149 |
150 | --QOC
151 | Query Object Class
152 |
153 | --TVD
154 | Test Video Directory/Path
155 |
156 | --OID
157 | Object Image Directory
158 |
159 | --OFD
160 | Object Features Directory
161 |
162 |
163 | ## Contacts
164 |
165 | 1. Md. Faisal Ahmed Siddiqi (ahmedfaisal.fa21@gmail.com)
166 |
167 | 2. Anis-Ul-Isalm Rafid (au.i.rafid15@gmail.com)
168 | [linkedin Profile](https://www.linkedin.com/in/anis-ul-islam-rafid-54s18m/)
169 |
170 |
171 |
172 |
173 |
--------------------------------------------------------------------------------
/create_folder.py:
--------------------------------------------------------------------------------
1 | import os
2 | dir = os.path.dirname(__file__)
3 | filename = os.path.join(dir, 'temp/')
4 |
5 | def createFolder(directory):
6 | try:
7 | if not os.path.exists(directory):
8 | os.makedirs(directory)
9 | except OSError:
10 | print('Error: Creating directory. ' + directory)
11 |
12 |
13 |
14 | # createFolder(filename+'faces/')
--------------------------------------------------------------------------------
/lshash/PCA_Discrete.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright (c) 2013 Ole Krause-Sparmann
4 |
5 | # Permission is hereby granted, free of charge, to any person obtaining a copy
6 | # of this software and associated documentation files (the "Software"), to deal
7 | # in the Software without restriction, including without limitation the rights
8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | # copies of the Software, and to permit persons to whom the Software is
10 | # furnished to do so, subject to the following conditions:
11 |
12 | # The above copyright notice and this permission notice shall be included in
13 | # all copies or substantial portions of the Software.
14 |
15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | # THE SOFTWARE.
22 |
23 | import numpy
24 | import scipy
25 | import scipy.sparse
26 |
27 | from nearpy.hashes.lshash import LSHash
28 |
29 | from nearpy.utils import numpy_array_from_list_or_numpy_array, perform_pca
30 |
31 |
32 | class PCADiscretizedProjections(LSHash):
33 | """
34 | Projects a vector on n first principal components and assigns
35 | a discrete value to each projection depending on the bin.
36 | """
37 |
38 | def __init__(self, hash_name, projection_count, training_set, bin_width):
39 | """
40 | Computes principal components for training vector set. Uses
41 | first projection_count principal components for projections.
42 | Training set must be either a numpy matrix or a list of
43 | numpy vectors.
44 | """
45 | super(PCADiscretizedProjections, self).__init__(hash_name)
46 | self.projection_count = projection_count
47 | self.bin_width = bin_width
48 |
49 | # Only do training if training set was specified
50 | if not training_set is None:
51 | # Get numpy array representation of input
52 | training_set = numpy_array_from_list_or_numpy_array(training_set)
53 |
54 | # Get subspace size from training matrix
55 | self.dim = training_set.shape[0]
56 |
57 | # Get transposed training set matrix for PCA
58 | training_set_t = numpy.transpose(training_set)
59 |
60 | # Compute principal components
61 | (eigenvalues, eigenvectors) = perform_pca(training_set_t)
62 |
63 | # Get largest N eigenvalue/eigenvector indices
64 | largest_eigenvalue_indices = numpy.flipud(
65 | scipy.argsort(eigenvalues))[:projection_count]
66 |
67 | # Create matrix for first N principal components
68 | self.components = numpy.zeros((self.dim,
69 | len(largest_eigenvalue_indices)))
70 |
71 | # Put first N principal components into matrix
72 | for index in range(len(largest_eigenvalue_indices)):
73 | self.components[:, index] = \
74 | eigenvectors[:, largest_eigenvalue_indices[index]]
75 |
76 | # We need the component vectors to be in the rows
77 | self.components = numpy.transpose(self.components)
78 |
79 | # This is only used in case we need to process sparse vectors
80 | self.components_csr = None
81 |
82 | def reset(self, dim):
83 | """ Resets / Initializes the hash for the specified dimension. """
84 | if self.dim != dim:
85 | raise Exception('PCA hash is trained for specific dimension!')
86 |
87 | def hash_vector(self, v, querying=False):
88 | """
89 | Hashes the vector and returns the binary bucket key as string.
90 | """
91 | if scipy.sparse.issparse(v):
92 | # If vector is sparse, make sure we have the CSR representation
93 | # of the projection matrix
94 | if self.components_csr == None:
95 | self.components_csr = scipy.sparse.csr_matrix(self.components)
96 | # Make sure that we are using CSR format for multiplication
97 | if not scipy.sparse.isspmatrix_csr(v):
98 | v = scipy.sparse.csr_matrix(v)
99 | # Project vector onto all hyperplane normals
100 | projection = (self.components_csr.dot(v) / self.bin_width).floor().toarray()
101 | else:
102 | # Project vector onto components
103 | projection = numpy.dot(self.components, v)
104 | projection = numpy.floor(projection / self.bin_width)
105 | # Return key
106 | return ['_'.join([str(int(x)) for x in projection])]
107 |
108 | def get_config(self):
109 | """
110 | Returns pickle-serializable configuration struct for storage.
111 | """
112 | # Fill this dict with config data
113 | return {
114 | 'hash_name': self.hash_name,
115 | 'dim': self.dim,
116 | 'bin_width': self.bin_width,
117 | 'projection_count': self.projection_count,
118 | 'components': self.components
119 | }
120 |
121 | def apply_config(self, config):
122 | """
123 | Applies config
124 | """
125 | self.hash_name = config['hash_name']
126 | self.dim = config['dim']
127 | self.bin_width = config['bin_width']
128 | self.projection_count = config['projection_count']
129 | self.components = config['components']
--------------------------------------------------------------------------------
/lshash/__init__.py:
--------------------------------------------------------------------------------
1 | # lshash/__init__.py
2 | # Copyright 2012 Kay Zhu (a.k.a He Zhu) and contributors (see CONTRIBUTORS.txt)
3 | #
4 | # This module is part of lshash and is released under
5 | # the MIT License: http://www.opensource.org/licenses/mit-license.php
6 |
7 | __title__ = 'lshash'
8 | __author__ = 'Kay Zhu (me@kayzhu.com)'
9 | __license__ = 'MIT'
10 | __version__ = '0.0.4dev'
11 |
12 | #from lshash import LSHash
13 |
--------------------------------------------------------------------------------
/lshash/lshash.py:
--------------------------------------------------------------------------------
1 | # lshash/lshash.py
2 | # Copyright 2012 Kay Zhu (a.k.a He Zhu) and contributors (see CONTRIBUTORS.txt)
3 | #
4 | # This module is part of lshash and is released under
5 | # the MIT License: http://www.opensource.org/licenses/mit-license.php
6 |
7 | import os
8 | import json
9 | import numpy as np
10 |
11 | from storage import storage
12 |
13 | try:
14 | from bitarray import bitarray
15 | except ImportError:
16 | bitarray = None
17 |
18 |
19 | class LSHash(object):
20 | """ LSHash implments locality sensitive hashing using random projection for
21 | input vectors of dimension `input_dim`.
22 |
23 | Attributes:
24 |
25 | :param hash_size:
26 | The length of the resulting binary hash in integer. E.g., 32 means the
27 | resulting binary hash will be 32-bit long.
28 | :param input_dim:
29 | The dimension of the input vector. E.g., a grey-scale picture of 30x30
30 | pixels will have an input dimension of 900.
31 | :param num_hashtables:
32 | (optional) The number of hash tables used for multiple lookups.
33 | :param storage_config:
34 | (optional) A dictionary of the form `{backend_name: config}` where
35 | `backend_name` is the either `dict` or `redis`, and `config` is the
36 | configuration used by the backend. For `redis` it should be in the
37 | format of `{"redis": {"host": hostname, "port": port_num}}`, where
38 | `hostname` is normally `localhost` and `port` is normally 6379.
39 | :param matrices_filename:
40 | (optional) Specify the path to the compressed numpy file ending with
41 | extension `.npz`, where the uniform random planes are stored, or to be
42 | stored if the file does not exist yet.
43 | :param overwrite:
44 | (optional) Whether to overwrite the matrices file if it already exist
45 | """
46 |
47 | def __init__(self, hash_size, input_dim, num_hashtables= 1,
48 | storage_config=None, matrices_filename=None, overwrite=False):
49 |
50 | self.hash_size = hash_size
51 | self.input_dim = input_dim
52 | self.num_hashtables = num_hashtables
53 |
54 | if storage_config is None:
55 | storage_config = {'dict': None}
56 | self.storage_config = storage_config
57 |
58 | if matrices_filename and not matrices_filename.endswith('.npz'):
59 | raise ValueError("The specified file name must end with .npz")
60 | self.matrices_filename = matrices_filename
61 | self.overwrite = overwrite
62 |
63 | self._init_uniform_planes()
64 | self._init_hashtables()
65 |
66 | def _init_uniform_planes(self):
67 |
68 |
69 | """ Initialize uniform planes used to calculate the hashes
70 |
71 | if file `self.matrices_filename` exist and `self.overwrite` is
72 | selected, save the uniform planes to the specified file.
73 |
74 | if file `self.matrices_filename` exist and `self.overwrite` is not
75 | selected, load the matrix with `np.load`.
76 |
77 | if file `self.matrices_filename` does not exist and regardless of
78 | `self.overwrite`, only set `self.uniform_planes`.
79 | """
80 |
81 | if "uniform_planes" in self.__dict__:
82 | return
83 |
84 | if self.matrices_filename:
85 |
86 | file_exist = os.path.isfile(self.matrices_filename)
87 |
88 | if file_exist and not self.overwrite:
89 | try:
90 | npzfiles = np.load(self.matrices_filename)
91 | except IOError:
92 | print("Cannot load specified file as a numpy array")
93 | raise
94 | else:
95 | npzfiles = sorted(npzfiles.items(), key=lambda x: x[0])
96 | self.uniform_planes = [t[1] for t in npzfiles]
97 |
98 | else:
99 | self.uniform_planes = [self._generate_uniform_planes()
100 | for _ in xrange(self.num_hashtables)]
101 | try:
102 | np.savez_compressed(self.matrices_filename,
103 | *self.uniform_planes)
104 | except IOError:
105 | print("IOError when saving matrices to specificed path")
106 | raise
107 | else:
108 | self.uniform_planes = [self._generate_uniform_planes()
109 | for _ in xrange(self.num_hashtables)]
110 |
111 | def _init_hashtables(self):
112 | """ Initialize the hash tables such that each record will be in the
113 | form of "[storage1, storage2, ...]" """
114 |
115 | self.hash_tables = [storage(self.storage_config, i)
116 | for i in xrange(self.num_hashtables)]
117 |
118 | def _generate_uniform_planes(self):
119 |
120 |
121 | """ Generate uniformly distributed hyperplanes and return it as a 2D
122 | numpy array.
123 | """
124 |
125 | return np.random.randn(self.hash_size, self.input_dim)
126 |
127 | def _hash(self, planes, input_point):
128 |
129 | """ Generates the binary hash for `input_point` and returns it.
130 |
131 | :param planes:
132 | The planes are random uniform planes with a dimension of
133 | `hash_size` * `input_dim`.
134 | :param input_point:
135 | A Python tuple or list object that contains only numbers.
136 | The dimension needs to be 1 * `input_dim`.
137 | """
138 |
139 | try:
140 | input_point = np.array(input_point) # for faster dot product
141 | projections = np.dot(planes, input_point)
142 |
143 |
144 | # print " \n "
145 | #
146 | # print projections
147 | #
148 | # print "\n "
149 |
150 |
151 | except TypeError as e:
152 | print("""The input point needs to be an array-like object with
153 | numbers only elements""")
154 | raise
155 |
156 | except ValueError as e:
157 | print("""The input point needs to be of the same dimension as
158 | `input_dim` when initializing this LSHash instance""", e)
159 | raise
160 |
161 | else:
162 | return "".join(['1' if i > 0 else '0' for i in projections])
163 |
164 | def _as_np_array(self, json_or_tuple):
165 | """ Takes either a JSON-serialized data structure or a tuple that has
166 | the original input points stored, and returns the original input point
167 | in numpy array format.
168 | """
169 | if isinstance(json_or_tuple, basestring):
170 | # JSON-serialized in the case of Redis
171 | try:
172 | # Return the point stored as list, without the extra data
173 | tuples = json.loads(json_or_tuple)[0]
174 | except TypeError:
175 | print("The value stored is not JSON-serilizable")
176 | raise
177 | else:
178 | # If extra_data exists, `tuples` is the entire
179 | # (point:tuple, extra_data). Otherwise (i.e., extra_data=None),
180 | # return the point stored as a tuple
181 | tuples = json_or_tuple
182 |
183 | if isinstance(tuples[0], tuple):
184 | # in this case extra data exists
185 | return np.asarray(tuples[0])
186 |
187 | elif isinstance(tuples, (tuple, list)):
188 | try:
189 | return np.asarray(tuples)
190 | except ValueError as e:
191 | print("The input needs to be an array-like object", e)
192 | raise
193 | else:
194 | raise TypeError("query data is not supported")
195 |
196 | def index(self, input_point, extra_data=None):
197 | """ Index a single input point by adding it to the selected storage.
198 |
199 | If `extra_data` is provided, it will become the value of the dictionary
200 | {input_point: extra_data}, which in turn will become the value of the
201 | hash table. `extra_data` needs to be JSON serializable if in-memory
202 | dict is not used as storage.
203 |
204 | :param input_point:
205 | A list, or tuple, or numpy ndarray object that contains numbers
206 | only. The dimension needs to be 1 * `input_dim`.
207 | This object will be converted to Python tuple and stored in the
208 | selected storage.
209 | :param extra_data:
210 | (optional) Needs to be a JSON-serializable object: list, dicts and
211 | basic types such as strings and integers.
212 | """
213 |
214 | if isinstance(input_point, np.ndarray):
215 | input_point = input_point.tolist()
216 |
217 | if extra_data:
218 | value = (tuple(input_point), extra_data)
219 | else:
220 | value = tuple(input_point)
221 |
222 | for i, table in enumerate(self.hash_tables):
223 | table.append_val(self._hash(self.uniform_planes[i], input_point),
224 | value)
225 |
226 | def query(self, query_point, num_results=None, distance_func=None):
227 | """ Takes `query_point` which is either a tuple or a list of numbers,
228 | returns `num_results` of results as a list of tuples that are ranked
229 | based on the supplied metric function `distance_func`.
230 |
231 | :param query_point:
232 | A list, or tuple, or numpy ndarray that only contains numbers.
233 | The dimension needs to be 1 * `input_dim`.
234 | Used by :meth:`._hash`.
235 | :param num_results:
236 | (optional) Integer, specifies the max amount of results to be
237 | returned. If not specified all candidates will be returned as a
238 | list in ranked order.
239 | :param distance_func:
240 | (optional) The distance function to be used. Currently it needs to
241 | be one of ("hamming", "euclidean", "true_euclidean",
242 | "centred_euclidean", "cosine", "l1norm"). By default "euclidean"
243 | will used.
244 | """
245 |
246 | candidates = set()
247 | if not distance_func:
248 | distance_func = "euclidean"
249 |
250 | if distance_func == "hamming":
251 | if not bitarray:
252 | raise ImportError(" Bitarray is required for hamming distance")
253 |
254 | for i, table in enumerate(self.hash_tables):
255 |
256 | binary_hash = self._hash(self.uniform_planes[i], query_point)
257 |
258 | for key in table.keys():
259 |
260 | distance = LSHash.hamming_dist(key, binary_hash)
261 | if distance < 2:
262 | candidates.update(table.get_list(key))
263 |
264 | d_func = LSHash.euclidean_dist_square
265 |
266 | else:
267 |
268 | if distance_func == "euclidean":
269 | d_func = LSHash.euclidean_dist_square
270 | elif distance_func == "true_euclidean":
271 | d_func = LSHash.euclidean_dist
272 | elif distance_func == "centred_euclidean":
273 | d_func = LSHash.euclidean_dist_centred
274 | elif distance_func == "cosine":
275 | d_func = LSHash.cosine_dist
276 | elif distance_func == "l1norm":
277 | d_func = LSHash.l1norm_dist
278 | else:
279 | raise ValueError("The distance function name is invalid.")
280 |
281 |
282 |
283 | for i, table in enumerate(self.hash_tables):
284 |
285 | binary_hash = self._hash(self.uniform_planes[i], query_point)
286 | #print " \n \n " ,binary_hash, len(self.uniform_planes[i])
287 | candidates.update(table.get_list(binary_hash))
288 |
289 |
290 | #print(candidates)
291 |
292 | # rank candidates by distance function
293 |
294 | candidates = [(ix, d_func(query_point, self._as_np_array(ix)))
295 | for ix in candidates]
296 |
297 | candidates.sort(key=lambda x: x[1])
298 |
299 |
300 | return candidates[:num_results] if num_results else candidates
301 |
302 | ### distance functions
303 |
304 | @staticmethod
305 | def hamming_dist(bitarray1, bitarray2):
306 | xor_result = bitarray(bitarray1) ^ bitarray(bitarray2)
307 | return xor_result.count()
308 |
309 | @staticmethod
310 | def euclidean_dist(x, y):
311 | """ This is a hot function, hence some optimizations are made. """
312 | diff = np.array(x) - y
313 | return np.sqrt(np.dot(diff, diff))
314 |
315 | @staticmethod
316 | def euclidean_dist_square(x, y):
317 | """ This is a hot function, hence some optimizations are made. """
318 | diff = np.array(x) - y
319 | return np.dot(diff, diff)
320 |
321 | @staticmethod
322 | def euclidean_dist_centred(x, y):
323 | """ This is a hot function, hence some optimizations are made. """
324 | diff = np.mean(x) - np.mean(y)
325 | return np.dot(diff, diff)
326 |
327 | @staticmethod
328 | def l1norm_dist(x, y):
329 | return sum(abs(x - y))
330 |
331 | @staticmethod
332 | def cosine_dist(x, y):
333 | return 1 - np.dot(x, y) / ((np.dot(x, x) * np.dot(y, y)) ** 0.5)
334 |
--------------------------------------------------------------------------------
/lshash/lshash_2.py:
--------------------------------------------------------------------------------
1 | # lshash/lshash.py
2 | # Copyright 2012 Kay Zhu (a.k.a He Zhu) and contributors (see CONTRIBUTORS.txt)
3 | #
4 | # This module is part of lshash and is released under
5 | # the MIT License: http://www.opensource.org/licenses/mit-license.php
6 |
7 | import os
8 | import json
9 | import numpy as np
10 |
11 | from lshash import storage
12 |
13 | try:
14 | from bitarray import bitarray
15 | except ImportError:
16 | bitarray = None
17 |
18 |
19 | class LSHash(object):
20 | """ LSHash implments locality sensitive hashing using random projection for
21 | input vectors of dimension `input_dim`.
22 |
23 | Attributes:
24 |
25 | :param hash_size:
26 | The length of the resulting binary hash in integer. E.g., 32 means the
27 | resulting binary hash will be 32-bit long.
28 | :param input_dim:
29 | The dimension of the input vector. E.g., a grey-scale picture of 30x30
30 | pixels will have an input dimension of 900.
31 | :param num_hashtables:
32 | (optional) The number of hash tables used for multiple lookups.
33 | :param storage_config:
34 | (optional) A dictionary of the form `{backend_name: config}` where
35 | `backend_name` is the either `dict` or `redis`, and `config` is the
36 | configuration used by the backend. For `redis` it should be in the
37 | format of `{"redis": {"host": hostname, "port": port_num}}`, where
38 | `hostname` is normally `localhost` and `port` is normally 6379.
39 | :param matrices_filename:
40 | (optional) Specify the path to the compressed numpy file ending with
41 | extension `.npz`, where the uniform random planes are stored, or to be
42 | stored if the file does not exist yet.
43 | :param overwrite:
44 | (optional) Whether to overwrite the matrices file if it already exist
45 | """
46 |
47 | def __init__(self, hash_size, input_dim, num_hashtables= 1,num_hash_per_tables=1,
48 | storage_config=None, matrices_filename=None, overwrite=False):
49 |
50 | self.hash_size = hash_size
51 | self.input_dim = input_dim
52 | self.num_hashtables = num_hashtables
53 | self.num_hash_per_tables = num_hash_per_tables
54 |
55 | if storage_config is None:
56 | storage_config = {'dict': None}
57 | self.storage_config = storage_config
58 |
59 | if matrices_filename and not matrices_filename.endswith('.npz'):
60 | raise ValueError("The specified file name must end with .npz")
61 | self.matrices_filename = matrices_filename
62 | self.overwrite = overwrite
63 |
64 | self._init_uniform_planes()
65 | self._init_hashtables()
66 |
67 | def _init_uniform_planes(self):
68 |
69 |
70 | """ Initialize uniform planes used to calculate the hashes
71 |
72 | if file `self.matrices_filename` exist and `self.overwrite` is
73 | selected, save the uniform planes to the specified file.
74 |
75 | if file `self.matrices_filename` exist and `self.overwrite` is not
76 | selected, load the matrix with `np.load`.
77 |
78 | if file `self.matrices_filename` does not exist and regardless of
79 | `self.overwrite`, only set `self.uniform_planes`.
80 | """
81 |
82 | if "uniform_planes" in self.__dict__:
83 | return
84 |
85 | if self.matrices_filename:
86 |
87 | file_exist = os.path.isfile(self.matrices_filename)
88 |
89 | if file_exist and not self.overwrite:
90 | try:
91 | npzfiles = np.load(self.matrices_filename)
92 | except IOError:
93 | print("Cannot load specified file as a numpy array")
94 | raise
95 | else:
96 | npzfiles = sorted(npzfiles.items(), key=lambda x: x[0])
97 | self.uniform_planes = [t[1] for t in npzfiles]
98 |
99 | else:
100 |
101 | self.uniform_planes = [self._generate_uniform_planes()
102 | for _ in xrange(self.num_hash_per_tables)]
103 | try:
104 | np.savez_compressed(self.matrices_filename,
105 | *self.uniform_planes)
106 | except IOError:
107 | print("IOError when saving matrices to specificed path")
108 | raise
109 | else:
110 | self.uniform_planes = [self._generate_uniform_planes()
111 | for _ in xrange(self.num_hash_per_tables)]
112 |
113 | def _init_hashtables(self):
114 | """ Initialize the hash tables such that each record will be in the
115 | form of "[storage1, storage2, ...]" """
116 |
117 | self.hash_tables = [storage(self.storage_config, i)
118 | for i in xrange(self.num_hashtables)]
119 |
120 | def _generate_uniform_planes(self):
121 |
122 |
123 | """ Generate uniformly distributed hyperplanes and return it as a 2D
124 | numpy array.
125 | """
126 |
127 | return np.random.randn(self.hash_size, self.input_dim)
128 |
129 | def _hash(self, planes, input_point):
130 |
131 | """ Generates the binary hash for `input_point` and returns it.
132 |
133 | :param planes:
134 | The planes are random uniform planes with a dimension of
135 | `hash_size` * `input_dim`.
136 | :param input_point:
137 | A Python tuple or list object that contains only numbers.
138 | The dimension needs to be 1 * `input_dim`.
139 | """
140 |
141 | try:
142 | input_point = np.array(input_point) # for faster dot product
143 | projections = np.dot(planes, input_point)
144 |
145 |
146 | # print " \n "
147 | #
148 | # print projections
149 | #
150 | # print "\n "
151 |
152 |
153 | except TypeError as e:
154 | print("""The input point needs to be an array-like object with
155 | numbers only elements""")
156 | raise
157 |
158 | except ValueError as e:
159 | print("""The input point needs to be of the same dimension as
160 | `input_dim` when initializing this LSHash instance""", e)
161 | raise
162 |
163 | else:
164 | return "".join(['1' if i > 0 else '0' for i in projections])
165 |
166 | def _as_np_array(self, json_or_tuple):
167 | """ Takes either a JSON-serialized data structure or a tuple that has
168 | the original input points stored, and returns the original input point
169 | in numpy array format.
170 | """
171 | if isinstance(json_or_tuple, basestring):
172 | # JSON-serialized in the case of Redis
173 | try:
174 | # Return the point stored as list, without the extra data
175 | tuples = json.loads(json_or_tuple)[0]
176 | except TypeError:
177 | print("The value stored is not JSON-serilizable")
178 | raise
179 | else:
180 | # If extra_data exists, `tuples` is the entire
181 | # (point:tuple, extra_data). Otherwise (i.e., extra_data=None),
182 | # return the point stored as a tuple
183 | tuples = json_or_tuple
184 |
185 | if isinstance(tuples[0], tuple):
186 | # in this case extra data exists
187 | return np.asarray(tuples[0])
188 |
189 | elif isinstance(tuples, (tuple, list)):
190 | try:
191 | return np.asarray(tuples)
192 | except ValueError as e:
193 | print("The input needs to be an array-like object", e)
194 | raise
195 | else:
196 | raise TypeError("query data is not supported")
197 |
198 | def index(self, input_point, extra_data=None):
199 | """ Index a single input point by adding it to the selected storage.
200 |
201 | If `extra_data` is provided, it will become the value of the dictionary
202 | {input_point: extra_data}, which in turn will become the value of the
203 | hash table. `extra_data` needs to be JSON serializable if in-memory
204 | dict is not used as storage.
205 |
206 | :param input_point:
207 | A list, or tuple, or numpy ndarray object that contains numbers
208 | only. The dimension needs to be 1 * `input_dim`.
209 | This object will be converted to Python tuple and stored in the
210 | selected storage.
211 | :param extra_data:
212 | (optional) Needs to be a JSON-serializable object: list, dicts and
213 | basic types such as strings and integers.
214 | """
215 |
216 | if isinstance(input_point, np.ndarray):
217 | input_point = input_point.tolist()
218 |
219 | if extra_data:
220 | value = (tuple(input_point), extra_data)
221 | else:
222 | value = tuple(input_point)
223 |
224 |
225 | for i, hash in enumerate(self.uniform_planes):
226 |
227 |
228 | for table in self.hash_tables:
229 |
230 | table.append_val(self._hash(self.uniform_planes[i], input_point),value)
231 |
232 |
233 |
234 |
235 | def query(self, query_point, num_results=None, distance_func=None):
236 |
237 | """ Takes `query_point` which is either a tuple or a list of numbers,
238 | returns `num_results` of results as a list of tuples that are ranked
239 | based on the supplied metric function `distance_func`.
240 |
241 | :param query_point:
242 | A list, or tuple, or numpy ndarray that only contains numbers.
243 | The dimension needs to be 1 * `input_dim`.
244 | Used by :meth:`._hash`.
245 | :param num_results:
246 | (optional) Integer, specifies the max amount of results to be
247 | returned. If not specified all candidates will be returned as a
248 | list in ranked order.
249 | :param distance_func:
250 | (optional) The distance function to be used. Currently it needs to
251 | be one of ("hamming", "euclidean", "true_euclidean",
252 | "centred_euclidean", "cosine", "l1norm"). By default "euclidean"
253 | will used.
254 | """
255 |
256 | candidates = set()
257 |
258 | if not distance_func:
259 | distance_func = "euclidean"
260 |
261 | if distance_func == "hamming":
262 | if not bitarray:
263 | raise ImportError(" Bitarray is required for hamming distance")
264 |
265 | for i, table in enumerate(self.hash_tables):
266 |
267 | binary_hash = self._hash(self.uniform_planes[i], query_point)
268 |
269 | for key in table.keys():
270 |
271 | distance = LSHash.hamming_dist(key, binary_hash)
272 | if distance < 2:
273 | candidates.update(table.get_list(key))
274 |
275 | d_func = LSHash.euclidean_dist_square
276 |
277 | else:
278 |
279 | if distance_func == "euclidean":
280 | d_func = LSHash.euclidean_dist_square
281 | elif distance_func == "true_euclidean":
282 | d_func = LSHash.euclidean_dist
283 | elif distance_func == "centred_euclidean":
284 | d_func = LSHash.euclidean_dist_centred
285 | elif distance_func == "cosine":
286 | d_func = LSHash.cosine_dist
287 | elif distance_func == "l1norm":
288 | d_func = LSHash.l1norm_dist
289 | else:
290 | raise ValueError("The distance function name is invalid.")
291 |
292 |
293 |
294 | for i ,hash in enumerate(self.uniform_planes):
295 |
296 | for table in self.hash_tables:
297 |
298 | binary_hash = self._hash(self.uniform_planes[i], query_point)
299 | #print " \n \n " ,binary_hash, len(self.uniform_planes[i])
300 | candidates.update(table.get_list(binary_hash))
301 |
302 |
303 | #print(candidates)
304 |
305 | # rank candidates by distance function
306 |
307 | candidates = [(ix, d_func(query_point, self._as_np_array(ix)))
308 | for ix in candidates]
309 |
310 | candidates.sort(key=lambda x: x[1])
311 |
312 |
313 | return candidates[:num_results] if num_results else candidates
314 |
315 | ### distance functions
316 |
317 | @staticmethod
318 | def hamming_dist(bitarray1, bitarray2):
319 | xor_result = bitarray(bitarray1) ^ bitarray(bitarray2)
320 | return xor_result.count()
321 |
322 | @staticmethod
323 | def euclidean_dist(x, y):
324 | """ This is a hot function, hence some optimizations are made. """
325 | diff = np.array(x) - y
326 | return np.sqrt(np.dot(diff, diff))
327 |
328 | @staticmethod
329 | def euclidean_dist_square(x, y):
330 | """ This is a hot function, hence some optimizations are made. """
331 | diff = np.array(x) - y
332 | return np.dot(diff, diff)
333 |
334 | @staticmethod
335 | def euclidean_dist_centred(x, y):
336 | """ This is a hot function, hence some optimizations are made. """
337 | diff = np.mean(x) - np.mean(y)
338 | return np.dot(diff, diff)
339 |
340 | @staticmethod
341 | def l1norm_dist(x, y):
342 | return sum(abs(x - y))
343 |
344 | @staticmethod
345 | def cosine_dist(x, y):
346 | return 1 - np.dot(x, y) / ((np.dot(x, x) * np.dot(y, y)) ** 0.5)
347 |
--------------------------------------------------------------------------------
/lshash/storage.py:
--------------------------------------------------------------------------------
1 | # lshash/storage.py
2 | # Copyright 2012 Kay Zhu (a.k.a He Zhu) and contributors (see CONTRIBUTORS.txt)
3 | #
4 | # This module is part of lshash and is released under
5 | # the MIT License: http://www.opensource.org/licenses/mit-license.php
6 |
7 | import json
8 |
9 | try:
10 | import redis
11 | except ImportError:
12 | redis = None
13 |
14 | __all__ = ['storage']
15 |
16 |
17 | def storage(storage_config, index):
18 | """ Given the configuration for storage and the index, return the
19 | configured storage instance.
20 | """
21 | if 'dict' in storage_config:
22 | return InMemoryStorage(storage_config['dict'])
23 | elif 'redis' in storage_config:
24 | storage_config['redis']['db'] = index
25 | return RedisStorage(storage_config['redis'])
26 | else:
27 | raise ValueError("Only in-memory dictionary and Redis are supported.")
28 |
29 |
30 | class BaseStorage(object):
31 |
32 | def __init__(self, config):
33 | """ An abstract class used as an adapter for storages. """
34 | raise NotImplementedError
35 |
36 | def keys(self):
37 | """ Returns a list of binary hashes that are used as dict keys. """
38 | raise NotImplementedError
39 |
40 | def set_val(self, key, val):
41 | """ Set `val` at `key`, note that the `val` must be a string. """
42 | raise NotImplementedError
43 |
44 | def get_val(self, key):
45 | """ Return `val` at `key`, note that the `val` must be a string. """
46 | raise NotImplementedError
47 |
48 | def append_val(self, key, val):
49 | """ Append `val` to the list stored at `key`.
50 |
51 | If the key is not yet present in storage, create a list with `val` at
52 | `key`.
53 | """
54 | raise NotImplementedError
55 |
56 | def get_list(self, key):
57 | """ Returns a list stored in storage at `key`.
58 |
59 | This method should return a list of values stored at `key`. `[]` should
60 | be returned if the list is empty or if `key` is not present in storage.
61 | """
62 | raise NotImplementedError
63 |
64 |
65 | class InMemoryStorage(BaseStorage):
66 |
67 | def __init__(self, config):
68 | self.name = 'dict'
69 | self.storage = dict()
70 |
71 | def keys(self):
72 | return self.storage.keys()
73 |
74 | def set_val(self, key, val):
75 | self.storage[key] = val
76 |
77 | def get_val(self, key):
78 | return self.storage[key]
79 |
80 | def append_val(self, key, val):
81 | self.storage.setdefault(key, []).append(val)
82 |
83 | def get_list(self, key):
84 | return self.storage.get(key, [])
85 |
86 |
87 | class RedisStorage(BaseStorage):
88 |
89 | def __init__(self, config):
90 | if not redis:
91 | raise ImportError("redis-py is required to use Redis as storage.")
92 | self.name = 'redis'
93 | self.storage = redis.StrictRedis(**config)
94 |
95 | def keys(self, pattern="*"):
96 | return self.storage.keys(pattern)
97 |
98 | def set_val(self, key, val):
99 | self.storage.set(key, val)
100 |
101 | def get_val(self, key):
102 | return self.storage.get(key)
103 |
104 | def append_val(self, key, val):
105 | self.storage.rpush(key, json.dumps(val))
106 |
107 | def get_list(self, key):
108 | return self.storage.lrange(key, 0, -1)
109 |
--------------------------------------------------------------------------------
/lshash/utils.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import numpy
3 | import scipy
4 | from scipy.sparse import csr_matrix, isspmatrix
5 |
6 | def numpy_array_from_list_or_numpy_array(vectors):
7 | """
8 | Returns numpy array representation of argument.
9 | Argument maybe numpy array (input is returned)
10 | or a list of numpy vectors.
11 | """
12 | # If vectors is not a numpy matrix, create one
13 | if not isinstance(vectors, numpy.ndarray):
14 | V = numpy.zeros((vectors[0].shape[0], len(vectors)))
15 | for index in range(len(vectors)):
16 | vector = vectors[index]
17 | V[:, index] = vector
18 | return V
19 |
20 | return vectors
21 |
22 |
23 | def unitvec(vec):
24 | """
25 | Scale a vector to unit length. The only exception is the zero vector, which
26 | is returned back unchanged.
27 | """
28 | if scipy.sparse.issparse(vec): # convert scipy.sparse to standard numpy array
29 | vec = vec.tocsr()
30 | veclen = numpy.sqrt(numpy.sum(vec.data ** 2))
31 | if veclen > 0.0:
32 | return vec / veclen
33 | else:
34 | return vec
35 |
36 | if isinstance(vec, numpy.ndarray):
37 | vec = numpy.asarray(vec, dtype=float)
38 | veclen = numpy.linalg.norm(vec)
39 | if veclen > 0.0:
40 | return vec / veclen
41 | else:
42 | return vec
43 |
44 |
45 | def perform_pca(A):
46 | """
47 | Computes eigenvalues and eigenvectors of covariance matrix of A.
48 | The rows of a correspond to observations, the columns to variables.
49 | """
50 | # First subtract the mean
51 | M = (A-numpy.mean(A.T, axis=1)).T
52 | # Get eigenvectors and values of covariance matrix
53 | return numpy.linalg.eig(numpy.cov(M))
54 |
55 |
56 | PY2 = sys.version_info[0] == 2
57 | if PY2:
58 | bytes_type = str
59 | else:
60 | bytes_type = bytes
61 |
62 |
63 | def want_string(arg, encoding='utf-8'):
64 | if isinstance(arg, bytes_type):
65 | rv = arg.decode(encoding)
66 | else:
67 | rv = arg
68 | return rv
--------------------------------------------------------------------------------
/objFeature/features_vgg-19/features_vgg-19.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objFeature/features_vgg-19/features_vgg-19.npy
--------------------------------------------------------------------------------
/objSr/bin/activate:
--------------------------------------------------------------------------------
1 | # This file must be used with "source bin/activate" *from bash*
2 | # you cannot run it directly
3 |
4 | deactivate () {
5 | # reset old environment variables
6 | if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
7 | PATH="${_OLD_VIRTUAL_PATH:-}"
8 | export PATH
9 | unset _OLD_VIRTUAL_PATH
10 | fi
11 | if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
12 | PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
13 | export PYTHONHOME
14 | unset _OLD_VIRTUAL_PYTHONHOME
15 | fi
16 |
17 | # This should detect bash and zsh, which have a hash command that must
18 | # be called to get it to forget past commands. Without forgetting
19 | # past commands the $PATH changes we made may not be respected
20 | if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
21 | hash -r
22 | fi
23 |
24 | if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
25 | PS1="${_OLD_VIRTUAL_PS1:-}"
26 | export PS1
27 | unset _OLD_VIRTUAL_PS1
28 | fi
29 |
30 | unset VIRTUAL_ENV
31 | if [ ! "$1" = "nondestructive" ] ; then
32 | # Self destruct!
33 | unset -f deactivate
34 | fi
35 | }
36 |
37 | # unset irrelevant variables
38 | deactivate nondestructive
39 |
40 | VIRTUAL_ENV="/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr"
41 | export VIRTUAL_ENV
42 |
43 | _OLD_VIRTUAL_PATH="$PATH"
44 | PATH="$VIRTUAL_ENV/bin:$PATH"
45 | export PATH
46 |
47 | # unset PYTHONHOME if set
48 | # this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
49 | # could use `if (set -u; : $PYTHONHOME) ;` in bash
50 | if [ -n "${PYTHONHOME:-}" ] ; then
51 | _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
52 | unset PYTHONHOME
53 | fi
54 |
55 | if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
56 | _OLD_VIRTUAL_PS1="${PS1:-}"
57 | if [ "x(objSr) " != x ] ; then
58 | PS1="(objSr) ${PS1:-}"
59 | else
60 | if [ "`basename \"$VIRTUAL_ENV\"`" = "__" ] ; then
61 | # special case for Aspen magic directories
62 | # see http://www.zetadev.com/software/aspen/
63 | PS1="[`basename \`dirname \"$VIRTUAL_ENV\"\``] $PS1"
64 | else
65 | PS1="(`basename \"$VIRTUAL_ENV\"`)$PS1"
66 | fi
67 | fi
68 | export PS1
69 | fi
70 |
71 | # This should detect bash and zsh, which have a hash command that must
72 | # be called to get it to forget past commands. Without forgetting
73 | # past commands the $PATH changes we made may not be respected
74 | if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
75 | hash -r
76 | fi
77 |
--------------------------------------------------------------------------------
/objSr/bin/activate.csh:
--------------------------------------------------------------------------------
1 | # This file must be used with "source bin/activate.csh" *from csh*.
2 | # You cannot run it directly.
3 | # Created by Davide Di Blasi .
4 | # Ported to Python 3.3 venv by Andrew Svetlov
5 |
6 | alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate'
7 |
8 | # Unset irrelevant variables.
9 | deactivate nondestructive
10 |
11 | setenv VIRTUAL_ENV "/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr"
12 |
13 | set _OLD_VIRTUAL_PATH="$PATH"
14 | setenv PATH "$VIRTUAL_ENV/bin:$PATH"
15 |
16 |
17 | set _OLD_VIRTUAL_PROMPT="$prompt"
18 |
19 | if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
20 | if ("objSr" != "") then
21 | set env_name = "objSr"
22 | else
23 | if (`basename "VIRTUAL_ENV"` == "__") then
24 | # special case for Aspen magic directories
25 | # see http://www.zetadev.com/software/aspen/
26 | set env_name = `basename \`dirname "$VIRTUAL_ENV"\``
27 | else
28 | set env_name = `basename "$VIRTUAL_ENV"`
29 | endif
30 | endif
31 | set prompt = "[$env_name] $prompt"
32 | unset env_name
33 | endif
34 |
35 | alias pydoc python -m pydoc
36 |
37 | rehash
38 |
--------------------------------------------------------------------------------
/objSr/bin/activate.fish:
--------------------------------------------------------------------------------
1 | # This file must be used with ". bin/activate.fish" *from fish* (http://fishshell.org)
2 | # you cannot run it directly
3 |
4 | function deactivate -d "Exit virtualenv and return to normal shell environment"
5 | # reset old environment variables
6 | if test -n "$_OLD_VIRTUAL_PATH"
7 | set -gx PATH $_OLD_VIRTUAL_PATH
8 | set -e _OLD_VIRTUAL_PATH
9 | end
10 | if test -n "$_OLD_VIRTUAL_PYTHONHOME"
11 | set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
12 | set -e _OLD_VIRTUAL_PYTHONHOME
13 | end
14 |
15 | if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
16 | functions -e fish_prompt
17 | set -e _OLD_FISH_PROMPT_OVERRIDE
18 | functions -c _old_fish_prompt fish_prompt
19 | functions -e _old_fish_prompt
20 | end
21 |
22 | set -e VIRTUAL_ENV
23 | if test "$argv[1]" != "nondestructive"
24 | # Self destruct!
25 | functions -e deactivate
26 | end
27 | end
28 |
29 | # unset irrelevant variables
30 | deactivate nondestructive
31 |
32 | set -gx VIRTUAL_ENV "/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr"
33 |
34 | set -gx _OLD_VIRTUAL_PATH $PATH
35 | set -gx PATH "$VIRTUAL_ENV/bin" $PATH
36 |
37 | # unset PYTHONHOME if set
38 | if set -q PYTHONHOME
39 | set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
40 | set -e PYTHONHOME
41 | end
42 |
43 | if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
44 | # fish uses a function instead of an env var to generate the prompt.
45 |
46 | # save the current fish_prompt function as the function _old_fish_prompt
47 | functions -c fish_prompt _old_fish_prompt
48 |
49 | # with the original prompt function renamed, we can override with our own.
50 | function fish_prompt
51 | # Save the return status of the last command
52 | set -l old_status $status
53 |
54 | # Prompt override?
55 | if test -n "(objSr) "
56 | printf "%s%s" "(objSr) " (set_color normal)
57 | else
58 | # ...Otherwise, prepend env
59 | set -l _checkbase (basename "$VIRTUAL_ENV")
60 | if test $_checkbase = "__"
61 | # special case for Aspen magic directories
62 | # see http://www.zetadev.com/software/aspen/
63 | printf "%s[%s]%s " (set_color -b blue white) (basename (dirname "$VIRTUAL_ENV")) (set_color normal)
64 | else
65 | printf "%s(%s)%s" (set_color -b blue white) (basename "$VIRTUAL_ENV") (set_color normal)
66 | end
67 | end
68 |
69 | # Restore the return status of the previous command.
70 | echo "exit $old_status" | .
71 | _old_fish_prompt
72 | end
73 |
74 | set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
75 | end
76 |
--------------------------------------------------------------------------------
/objSr/bin/chardetect:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from chardet.cli.chardetect import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/easy_install:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from setuptools.command.easy_install import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/easy_install-3.6:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from setuptools.command.easy_install import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/estimator_ckpt_converter:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from tensorflow_estimator.python.estimator.tools.checkpoint_converter import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/f2py:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from numpy.f2py.f2py2e import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/f2py3:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from numpy.f2py.f2py2e import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/f2py3.6:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from numpy.f2py.f2py2e import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/flask:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from flask.cli import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/freeze_graph:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from tensorflow.python.tools.freeze_graph import run_main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(run_main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/google-oauthlib-tool:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from google_auth_oauthlib.tool.__main__ import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/imageio_download_bin:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from imageio.__main__ import download_bin_main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(download_bin_main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/imageio_remove_bin:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from imageio.__main__ import remove_bin_main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(remove_bin_main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/markdown_py:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from markdown.__main__ import run
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(run())
9 |
--------------------------------------------------------------------------------
/objSr/bin/pip:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from pip._internal.cli.main import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/pip3:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from pip._internal.cli.main import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/pip3.6:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from pip._internal.cli.main import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/pyrsa-decrypt:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from rsa.cli import decrypt
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(decrypt())
9 |
--------------------------------------------------------------------------------
/objSr/bin/pyrsa-encrypt:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from rsa.cli import encrypt
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(encrypt())
9 |
--------------------------------------------------------------------------------
/objSr/bin/pyrsa-keygen:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from rsa.cli import keygen
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(keygen())
9 |
--------------------------------------------------------------------------------
/objSr/bin/pyrsa-priv2pub:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from rsa.util import private_to_public
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(private_to_public())
9 |
--------------------------------------------------------------------------------
/objSr/bin/pyrsa-sign:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from rsa.cli import sign
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(sign())
9 |
--------------------------------------------------------------------------------
/objSr/bin/pyrsa-verify:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from rsa.cli import verify
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(verify())
9 |
--------------------------------------------------------------------------------
/objSr/bin/pytesseract:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from pytesseract.pytesseract import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/python:
--------------------------------------------------------------------------------
1 | python3.6
--------------------------------------------------------------------------------
/objSr/bin/python3:
--------------------------------------------------------------------------------
1 | python3.6
--------------------------------------------------------------------------------
/objSr/bin/python3.6:
--------------------------------------------------------------------------------
1 | /usr/bin/python3.6
--------------------------------------------------------------------------------
/objSr/bin/range-detector:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | # USAGE: You need to specify a filter and "only one" image source
5 | #
6 | # (python) range-detector --filter RGB --image /path/to/image.png
7 | # or
8 | # (python) range-detector --filter HSV --webcam
9 |
10 | import cv2
11 | import argparse
12 | from operator import xor
13 |
14 |
15 | def callback(value):
16 | pass
17 |
18 |
19 | def setup_trackbars(range_filter):
20 | cv2.namedWindow("Trackbars", 0)
21 |
22 | for i in ["MIN", "MAX"]:
23 | v = 0 if i == "MIN" else 255
24 |
25 | for j in range_filter:
26 | cv2.createTrackbar("%s_%s" % (j, i), "Trackbars", v, 255, callback)
27 |
28 |
29 | def get_arguments():
30 | ap = argparse.ArgumentParser()
31 | ap.add_argument('-f', '--filter', required=True,
32 | help='Range filter. RGB or HSV')
33 | ap.add_argument('-i', '--image', required=False,
34 | help='Path to the image')
35 | ap.add_argument('-w', '--webcam', required=False,
36 | help='Use webcam', action='store_true')
37 | ap.add_argument('-p', '--preview', required=False,
38 | help='Show a preview of the image after applying the mask',
39 | action='store_true')
40 | args = vars(ap.parse_args())
41 |
42 | if not xor(bool(args['image']), bool(args['webcam'])):
43 | ap.error("Please specify only one image source")
44 |
45 | if not args['filter'].upper() in ['RGB', 'HSV']:
46 | ap.error("Please speciy a correct filter.")
47 |
48 | return args
49 |
50 |
51 | def get_trackbar_values(range_filter):
52 | values = []
53 |
54 | for i in ["MIN", "MAX"]:
55 | for j in range_filter:
56 | v = cv2.getTrackbarPos("%s_%s" % (j, i), "Trackbars")
57 | values.append(v)
58 |
59 | return values
60 |
61 |
62 | def main():
63 | args = get_arguments()
64 |
65 | range_filter = args['filter'].upper()
66 |
67 | if args['image']:
68 | image = cv2.imread(args['image'])
69 |
70 | if range_filter == 'RGB':
71 | frame_to_thresh = image.copy()
72 | else:
73 | frame_to_thresh = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
74 | else:
75 | camera = cv2.VideoCapture(0)
76 |
77 | setup_trackbars(range_filter)
78 |
79 | while True:
80 | if args['webcam']:
81 | ret, image = camera.read()
82 |
83 | if not ret:
84 | break
85 |
86 | if range_filter == 'RGB':
87 | frame_to_thresh = image.copy()
88 | else:
89 | frame_to_thresh = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
90 |
91 | v1_min, v2_min, v3_min, v1_max, v2_max, v3_max = get_trackbar_values(range_filter)
92 |
93 | thresh = cv2.inRange(frame_to_thresh, (v1_min, v2_min, v3_min), (v1_max, v2_max, v3_max))
94 |
95 | if args['preview']:
96 | preview = cv2.bitwise_and(image, image, mask=thresh)
97 | cv2.imshow("Preview", preview)
98 | else:
99 | cv2.imshow("Original", image)
100 | cv2.imshow("Thresh", thresh)
101 |
102 | if cv2.waitKey(1) & 0xFF is ord('q'):
103 | break
104 |
105 |
106 | if __name__ == '__main__':
107 | main()
108 |
--------------------------------------------------------------------------------
/objSr/bin/saved_model_cli:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from tensorflow.python.tools.saved_model_cli import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/skivi:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from skimage.scripts.skivi import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/tensorboard:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from tensorboard.main import run_main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(run_main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/tf_upgrade_v2:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from tensorflow.tools.compatibility.tf_upgrade_v2_main import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/tflite_convert:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from tensorflow.lite.python.tflite_convert import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/toco:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from tensorflow.lite.python.tflite_convert import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/toco_from_protos:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from tensorflow.lite.toco.python.toco_from_protos import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/bin/wheel:
--------------------------------------------------------------------------------
1 | #!/home/rafid/Documents/Object_search_engine/Deep-Object-Search-With-Hash/objSr/bin/python
2 | # -*- coding: utf-8 -*-
3 | import re
4 | import sys
5 | from wheel.cli import main
6 | if __name__ == '__main__':
7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8 | sys.exit(main())
9 |
--------------------------------------------------------------------------------
/objSr/lib64:
--------------------------------------------------------------------------------
1 | lib
--------------------------------------------------------------------------------
/objSr/pyvenv.cfg:
--------------------------------------------------------------------------------
1 | home = /usr/bin
2 | include-system-site-packages = false
3 | version = 3.6.9
4 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/LICENSE.txt:
--------------------------------------------------------------------------------
1 | License
2 | =======
3 |
4 | NetworkX is distributed with the 3-clause BSD license.
5 |
6 | ::
7 |
8 | Copyright (C) 2004-2019, NetworkX Developers
9 | Aric Hagberg
10 | Dan Schult
11 | Pieter Swart
12 | All rights reserved.
13 |
14 | Redistribution and use in source and binary forms, with or without
15 | modification, are permitted provided that the following conditions are
16 | met:
17 |
18 | * Redistributions of source code must retain the above copyright
19 | notice, this list of conditions and the following disclaimer.
20 |
21 | * Redistributions in binary form must reproduce the above
22 | copyright notice, this list of conditions and the following
23 | disclaimer in the documentation and/or other materials provided
24 | with the distribution.
25 |
26 | * Neither the name of the NetworkX Developers nor the names of its
27 | contributors may be used to endorse or promote products derived
28 | from this software without specific prior written permission.
29 |
30 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
31 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
32 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
33 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
34 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
36 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
40 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/3d_drawing/README.txt:
--------------------------------------------------------------------------------
1 | 3D Drawing
2 | ----------
3 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/3d_drawing/mayavi2_spring.py:
--------------------------------------------------------------------------------
1 | """
2 | =======
3 | Mayavi2
4 | =======
5 |
6 | This is
7 | """
8 |
9 | # needs mayavi2
10 | # run with ipython -wthread
11 | import networkx as nx
12 | import numpy as np
13 | from mayavi import mlab
14 | mlab.options.offscreen = True
15 |
16 | # some graphs to try
17 | # H=nx.krackhardt_kite_graph()
18 | # H=nx.Graph();H.add_edge('a','b');H.add_edge('a','c');H.add_edge('a','d')
19 | # H=nx.grid_2d_graph(4,5)
20 | H = nx.cycle_graph(20)
21 |
22 | # reorder nodes from 0,len(G)-1
23 | G = nx.convert_node_labels_to_integers(H)
24 | # 3d spring layout
25 | pos = nx.spring_layout(G, dim=3)
26 | # numpy array of x,y,z positions in sorted node order
27 | xyz = np.array([pos[v] for v in sorted(G)])
28 | # scalar colors
29 | scalars = np.array(list(G.nodes())) + 5
30 |
31 | mlab.figure(1, bgcolor=(0, 0, 0))
32 | mlab.clf()
33 |
34 | pts = mlab.points3d(xyz[:, 0], xyz[:, 1], xyz[:, 2],
35 | scalars,
36 | scale_factor=0.1,
37 | scale_mode='none',
38 | colormap='Blues',
39 | resolution=20)
40 |
41 | pts.mlab_source.dataset.lines = np.array(list(G.edges()))
42 | tube = mlab.pipeline.tube(pts, tube_radius=0.01)
43 | mlab.pipeline.surface(tube, color=(0.8, 0.8, 0.8))
44 |
45 | mlab.savefig('mayavi2_spring.png')
46 | # mlab.show() # interactive window
47 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/README.txt:
--------------------------------------------------------------------------------
1 | .. _examples_gallery:
2 |
3 | Examples
4 | ========
5 |
6 | General-purpose and introductory examples for NetworkX.
7 | The `tutorial <../tutorial.html>`_ introduces conventions and basic graph
8 | manipulations.
9 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/advanced/README.txt:
--------------------------------------------------------------------------------
1 | Advanced
2 | --------
3 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/advanced/plot_eigenvalues.py:
--------------------------------------------------------------------------------
1 | """
2 | ===========
3 | Eigenvalues
4 | ===========
5 |
6 | Create an G{n,m} random graph and compute the eigenvalues.
7 | """
8 | import matplotlib.pyplot as plt
9 | import networkx as nx
10 | import numpy.linalg
11 |
12 | n = 1000 # 1000 nodes
13 | m = 5000 # 5000 edges
14 | G = nx.gnm_random_graph(n, m)
15 |
16 | L = nx.normalized_laplacian_matrix(G)
17 | e = numpy.linalg.eigvals(L.A)
18 | print("Largest eigenvalue:", max(e))
19 | print("Smallest eigenvalue:", min(e))
20 | plt.hist(e, bins=100) # histogram with 100 bins
21 | plt.xlim(0, 2) # eigenvalues between 0 and 2
22 | plt.show()
23 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/advanced/plot_heavy_metal_umlaut.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | ==================
5 | Heavy Metal Umlaut
6 | ==================
7 |
8 | Example using unicode strings as graph labels.
9 |
10 | Also shows creative use of the Heavy Metal Umlaut:
11 | https://en.wikipedia.org/wiki/Heavy_metal_umlaut
12 | """
13 | # Author: Aric Hagberg (hagberg@lanl.gov)
14 |
15 | # Copyright (C) 2006-2019 by
16 | # Aric Hagberg
17 | # Dan Schult
18 | # Pieter Swart
19 | # All rights reserved.
20 | # BSD license.
21 |
22 | import matplotlib.pyplot as plt
23 | import networkx as nx
24 |
25 | try:
26 | hd = 'H' + unichr(252) + 'sker D' + unichr(252)
27 | mh = 'Mot' + unichr(246) + 'rhead'
28 | mc = 'M' + unichr(246) + 'tley Cr' + unichr(252) + 'e'
29 | st = 'Sp' + unichr(305) + 'n' + unichr(776) + 'al Tap'
30 | q = 'Queensr' + unichr(255) + 'che'
31 | boc = 'Blue ' + unichr(214) + 'yster Cult'
32 | dt = 'Deatht' + unichr(246) + 'ngue'
33 | except NameError:
34 | hd = 'H' + chr(252) + 'sker D' + chr(252)
35 | mh = 'Mot' + chr(246) + 'rhead'
36 | mc = 'M' + chr(246) + 'tley Cr' + chr(252) + 'e'
37 | st = 'Sp' + chr(305) + 'n' + chr(776) + 'al Tap'
38 | q = 'Queensr' + chr(255) + 'che'
39 | boc = 'Blue ' + chr(214) + 'yster Cult'
40 | dt = 'Deatht' + chr(246) + 'ngue'
41 |
42 | G = nx.Graph()
43 | G.add_edge(hd, mh)
44 | G.add_edge(mc, st)
45 | G.add_edge(boc, mc)
46 | G.add_edge(boc, dt)
47 | G.add_edge(st, dt)
48 | G.add_edge(q, st)
49 | G.add_edge(dt, mh)
50 | G.add_edge(st, mh)
51 |
52 | # write in UTF-8 encoding
53 | fh = open('edgelist.utf-8', 'wb')
54 | fh.write('# -*- coding: utf-8 -*-\n'.encode('utf-8')) # encoding hint for emacs
55 | nx.write_multiline_adjlist(G, fh, delimiter='\t', encoding='utf-8')
56 |
57 | # read and store in UTF-8
58 | fh = open('edgelist.utf-8', 'rb')
59 | H = nx.read_multiline_adjlist(fh, delimiter='\t', encoding='utf-8')
60 |
61 | for n in G.nodes():
62 | if n not in H:
63 | print(False)
64 |
65 | print(list(G.nodes()))
66 |
67 | pos = nx.spring_layout(G)
68 | nx.draw(G, pos, font_size=16, with_labels=False)
69 | for p in pos: # raise text positions
70 | pos[p][1] += 0.07
71 | nx.draw_networkx_labels(G, pos)
72 | plt.show()
73 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/advanced/plot_iterated_dynamical_systems.py:
--------------------------------------------------------------------------------
1 | """
2 | ==========================
3 | Iterated Dynamical Systems
4 | ==========================
5 |
6 | Digraphs from Integer-valued Iterated Functions
7 |
8 | Sums of cubes on 3N
9 | -------------------
10 |
11 | The number 153 has a curious property.
12 |
13 | Let 3N={3,6,9,12,...} be the set of positive multiples of 3. Define an
14 | iterative process f:3N->3N as follows: for a given n, take each digit
15 | of n (in base 10), cube it and then sum the cubes to obtain f(n).
16 |
17 | When this process is repeated, the resulting series n, f(n), f(f(n)),...
18 | terminate in 153 after a finite number of iterations (the process ends
19 | because 153 = 1**3 + 5**3 + 3**3).
20 |
21 | In the language of discrete dynamical systems, 153 is the global
22 | attractor for the iterated map f restricted to the set 3N.
23 |
24 | For example: take the number 108
25 |
26 | f(108) = 1**3 + 0**3 + 8**3 = 513
27 |
28 | and
29 |
30 | f(513) = 5**3 + 1**3 + 3**3 = 153
31 |
32 | So, starting at 108 we reach 153 in two iterations,
33 | represented as:
34 |
35 | 108->513->153
36 |
37 | Computing all orbits of 3N up to 10**5 reveals that the attractor
38 | 153 is reached in a maximum of 14 iterations. In this code we
39 | show that 13 cycles is the maximum required for all integers (in 3N)
40 | less than 10,000.
41 |
42 | The smallest number that requires 13 iterations to reach 153, is 177, i.e.,
43 |
44 | 177->687->1071->345->216->225->141->66->432->99->1458->702->351->153
45 |
46 | The resulting large digraphs are useful for testing network software.
47 |
48 | The general problem
49 | -------------------
50 |
51 | Given numbers n, a power p and base b, define F(n; p, b) as the sum of
52 | the digits of n (in base b) raised to the power p. The above example
53 | corresponds to f(n)=F(n; 3,10), and below F(n; p, b) is implemented as
54 | the function powersum(n,p,b). The iterative dynamical system defined by
55 | the mapping n:->f(n) above (over 3N) converges to a single fixed point;
56 | 153. Applying the map to all positive integers N, leads to a discrete
57 | dynamical process with 5 fixed points: 1, 153, 370, 371, 407. Modulo 3
58 | those numbers are 1, 0, 1, 2, 2. The function f above has the added
59 | property that it maps a multiple of 3 to another multiple of 3; i.e. it
60 | is invariant on the subset 3N.
61 |
62 |
63 | The squaring of digits (in base 10) result in cycles and the
64 | single fixed point 1. I.e., from a certain point on, the process
65 | starts repeating itself.
66 |
67 | keywords: "Recurring Digital Invariant", "Narcissistic Number",
68 | "Happy Number"
69 |
70 | The 3n+1 problem
71 | ----------------
72 |
73 | There is a rich history of mathematical recreations
74 | associated with discrete dynamical systems. The most famous
75 | is the Collatz 3n+1 problem. See the function
76 | collatz_problem_digraph below. The Collatz conjecture
77 | --- that every orbit returrns to the fixed point 1 in finite time
78 | --- is still unproven. Even the great Paul Erdos said "Mathematics
79 | is not yet ready for such problems", and offered $500
80 | for its solution.
81 |
82 | keywords: "3n+1", "3x+1", "Collatz problem", "Thwaite's conjecture"
83 | """
84 |
85 | import networkx as nx
86 |
87 | nmax = 10000
88 | p = 3
89 |
90 |
91 | def digitsrep(n, b=10):
92 | """Return list of digits comprising n represented in base b.
93 | n must be a nonnegative integer"""
94 |
95 | if n <= 0:
96 | return [0]
97 |
98 | dlist = []
99 | while (n > 0):
100 | # Prepend next least-significant digit
101 | dlist = [n % b] + dlist
102 | # Floor-division
103 | n = n // b
104 | return dlist
105 |
106 |
107 | def powersum(n, p, b=10):
108 | """Return sum of digits of n (in base b) raised to the power p."""
109 | dlist = digitsrep(n, b)
110 | sum = 0
111 | for k in dlist:
112 | sum += k**p
113 | return sum
114 |
115 |
116 | def attractor153_graph(n, p, multiple=3, b=10):
117 | """Return digraph of iterations of powersum(n,3,10)."""
118 | G = nx.DiGraph()
119 | for k in range(1, n + 1):
120 | if k % multiple == 0 and k not in G:
121 | k1 = k
122 | knext = powersum(k1, p, b)
123 | while k1 != knext:
124 | G.add_edge(k1, knext)
125 | k1 = knext
126 | knext = powersum(k1, p, b)
127 | return G
128 |
129 |
130 | def squaring_cycle_graph_old(n, b=10):
131 | """Return digraph of iterations of powersum(n,2,10)."""
132 | G = nx.DiGraph()
133 | for k in range(1, n + 1):
134 | k1 = k
135 | G.add_node(k1) # case k1==knext, at least add node
136 | knext = powersum(k1, 2, b)
137 | G.add_edge(k1, knext)
138 | while k1 != knext: # stop if fixed point
139 | k1 = knext
140 | knext = powersum(k1, 2, b)
141 | G.add_edge(k1, knext)
142 | if G.out_degree(knext) >= 1:
143 | # knext has already been iterated in and out
144 | break
145 | return G
146 |
147 |
148 | def sum_of_digits_graph(nmax, b=10):
149 | def f(n): return powersum(n, 1, b)
150 | return discrete_dynamics_digraph(nmax, f)
151 |
152 |
153 | def squaring_cycle_digraph(nmax, b=10):
154 | def f(n): return powersum(n, 2, b)
155 | return discrete_dynamics_digraph(nmax, f)
156 |
157 |
158 | def cubing_153_digraph(nmax):
159 | def f(n): return powersum(n, 3, 10)
160 | return discrete_dynamics_digraph(nmax, f)
161 |
162 |
163 | def discrete_dynamics_digraph(nmax, f, itermax=50000):
164 | G = nx.DiGraph()
165 | for k in range(1, nmax + 1):
166 | kold = k
167 | G.add_node(kold)
168 | knew = f(kold)
169 | G.add_edge(kold, knew)
170 | while kold != knew and kold << itermax:
171 | # iterate until fixed point reached or itermax is exceeded
172 | kold = knew
173 | knew = f(kold)
174 | G.add_edge(kold, knew)
175 | if G.out_degree(knew) >= 1:
176 | # knew has already been iterated in and out
177 | break
178 | return G
179 |
180 |
181 | def collatz_problem_digraph(nmax):
182 | def f(n):
183 | if n % 2 == 0:
184 | return n // 2
185 | else:
186 | return 3 * n + 1
187 | return discrete_dynamics_digraph(nmax, f)
188 |
189 |
190 | def fixed_points(G):
191 | """Return a list of fixed points for the discrete dynamical
192 | system represented by the digraph G.
193 | """
194 | return [n for n in G if G.out_degree(n) == 0]
195 |
196 |
197 | if __name__ == "__main__":
198 | nmax = 10000
199 | print("Building cubing_153_digraph(%d)" % nmax)
200 | G = cubing_153_digraph(nmax)
201 | print("Resulting digraph has", len(G), "nodes and",
202 | G.size(), " edges")
203 | print("Shortest path from 177 to 153 is:")
204 | print(nx.shortest_path(G, 177, 153))
205 | print("fixed points are %s" % fixed_points(G))
206 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/advanced/plot_parallel_betweenness.py:
--------------------------------------------------------------------------------
1 | """
2 | ====================
3 | Parallel Betweenness
4 | ====================
5 |
6 | Example of parallel implementation of betweenness centrality using the
7 | multiprocessing module from Python Standard Library.
8 |
9 | The function betweenness centrality accepts a bunch of nodes and computes
10 | the contribution of those nodes to the betweenness centrality of the whole
11 | network. Here we divide the network in chunks of nodes and we compute their
12 | contribution to the betweenness centrality of the whole network.
13 |
14 | This doesn't work in python2.7.13. It does work in 3.6, 3.5, 3.4, and 3.3.
15 |
16 | It may be related to this:
17 | https://stackoverflow.com/questions/1816958/cant-pickle-type-instancemethod-when-using-multiprocessing-pool-map
18 | """
19 |
20 | from multiprocessing import Pool
21 | import time
22 | import itertools
23 |
24 | import matplotlib.pyplot as plt
25 | import networkx as nx
26 |
27 |
28 | def chunks(l, n):
29 | """Divide a list of nodes `l` in `n` chunks"""
30 | l_c = iter(l)
31 | while 1:
32 | x = tuple(itertools.islice(l_c, n))
33 | if not x:
34 | return
35 | yield x
36 |
37 |
38 | def _betmap(G_normalized_weight_sources_tuple):
39 | """Pool for multiprocess only accepts functions with one argument.
40 | This function uses a tuple as its only argument. We use a named tuple for
41 | python 3 compatibility, and then unpack it when we send it to
42 | `betweenness_centrality_source`
43 | """
44 | return nx.betweenness_centrality_source(*G_normalized_weight_sources_tuple)
45 |
46 |
47 | def betweenness_centrality_parallel(G, processes=None):
48 | """Parallel betweenness centrality function"""
49 | p = Pool(processes=processes)
50 | node_divisor = len(p._pool) * 4
51 | node_chunks = list(chunks(G.nodes(), int(G.order() / node_divisor)))
52 | num_chunks = len(node_chunks)
53 | bt_sc = p.map(_betmap,
54 | zip([G] * num_chunks,
55 | [True] * num_chunks,
56 | [None] * num_chunks,
57 | node_chunks))
58 |
59 | # Reduce the partial solutions
60 | bt_c = bt_sc[0]
61 | for bt in bt_sc[1:]:
62 | for n in bt:
63 | bt_c[n] += bt[n]
64 | return bt_c
65 |
66 |
67 | if __name__ == "__main__":
68 | G_ba = nx.barabasi_albert_graph(1000, 3)
69 | G_er = nx.gnp_random_graph(1000, 0.01)
70 | G_ws = nx.connected_watts_strogatz_graph(1000, 4, 0.1)
71 | for G in [G_ba, G_er, G_ws]:
72 | print("")
73 | print("Computing betweenness centrality for:")
74 | print(nx.info(G))
75 | print("\tParallel version")
76 | start = time.time()
77 | bt = betweenness_centrality_parallel(G)
78 | print("\t\tTime: %.4F" % (time.time() - start))
79 | print("\t\tBetweenness centrality for node 0: %.5f" % (bt[0]))
80 | print("\tNon-Parallel version")
81 | start = time.time()
82 | bt = nx.betweenness_centrality(G)
83 | print("\t\tTime: %.4F seconds" % (time.time() - start))
84 | print("\t\tBetweenness centrality for node 0: %.5f" % (bt[0]))
85 | print("")
86 |
87 | nx.draw(G_ba)
88 | plt.show()
89 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/algorithms/README.txt:
--------------------------------------------------------------------------------
1 | Algorithms
2 | ----------
3 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/algorithms/hartford_drug.edgelist:
--------------------------------------------------------------------------------
1 | # source target
2 | 1 2
3 | 1 10
4 | 2 1
5 | 2 10
6 | 3 7
7 | 4 7
8 | 4 209
9 | 5 132
10 | 6 150
11 | 7 3
12 | 7 4
13 | 7 9
14 | 8 106
15 | 8 115
16 | 9 1
17 | 9 2
18 | 9 7
19 | 10 1
20 | 10 2
21 | 11 133
22 | 11 218
23 | 12 88
24 | 13 214
25 | 14 24
26 | 14 52
27 | 16 10
28 | 16 19
29 | 17 64
30 | 17 78
31 | 18 55
32 | 18 103
33 | 18 163
34 | 19 18
35 | 20 64
36 | 20 180
37 | 21 16
38 | 21 22
39 | 22 21
40 | 22 64
41 | 22 106
42 | 23 20
43 | 23 22
44 | 23 64
45 | 24 14
46 | 24 31
47 | 24 122
48 | 27 115
49 | 28 29
50 | 29 28
51 | 30 19
52 | 31 24
53 | 31 32
54 | 31 122
55 | 31 147
56 | 31 233
57 | 32 31
58 | 32 86
59 | 34 35
60 | 34 37
61 | 35 34
62 | 35 43
63 | 36 132
64 | 36 187
65 | 37 38
66 | 37 90
67 | 37 282
68 | 38 42
69 | 38 43
70 | 38 210
71 | 40 20
72 | 42 15
73 | 42 38
74 | 43 34
75 | 43 35
76 | 43 38
77 | 45 107
78 | 46 61
79 | 46 72
80 | 48 23
81 | 49 30
82 | 49 64
83 | 49 108
84 | 49 115
85 | 49 243
86 | 50 30
87 | 50 47
88 | 50 55
89 | 50 125
90 | 50 163
91 | 52 218
92 | 52 224
93 | 54 111
94 | 54 210
95 | 55 65
96 | 55 67
97 | 55 105
98 | 55 108
99 | 55 222
100 | 56 18
101 | 56 64
102 | 57 65
103 | 57 125
104 | 58 20
105 | 58 30
106 | 58 50
107 | 58 103
108 | 58 180
109 | 59 164
110 | 63 125
111 | 64 8
112 | 64 50
113 | 64 70
114 | 64 256
115 | 66 20
116 | 66 84
117 | 66 106
118 | 66 125
119 | 67 22
120 | 67 50
121 | 67 113
122 | 68 50
123 | 70 50
124 | 70 64
125 | 71 72
126 | 74 29
127 | 74 75
128 | 74 215
129 | 75 74
130 | 75 215
131 | 76 58
132 | 76 104
133 | 77 103
134 | 78 64
135 | 78 68
136 | 80 207
137 | 80 210
138 | 82 8
139 | 82 77
140 | 82 83
141 | 82 97
142 | 82 163
143 | 83 82
144 | 83 226
145 | 83 243
146 | 84 29
147 | 84 154
148 | 87 101
149 | 87 189
150 | 89 90
151 | 90 89
152 | 90 94
153 | 91 86
154 | 92 19
155 | 92 30
156 | 92 106
157 | 94 72
158 | 94 89
159 | 94 90
160 | 95 30
161 | 96 75
162 | 96 256
163 | 97 80
164 | 97 128
165 | 98 86
166 | 100 86
167 | 101 87
168 | 103 77
169 | 103 104
170 | 104 58
171 | 104 77
172 | 104 103
173 | 106 22
174 | 107 38
175 | 107 114
176 | 107 122
177 | 108 49
178 | 108 55
179 | 111 121
180 | 111 128
181 | 111 210
182 | 113 253
183 | 114 107
184 | 116 30
185 | 116 140
186 | 118 129
187 | 118 138
188 | 120 88
189 | 121 128
190 | 122 31
191 | 123 32
192 | 124 244
193 | 125 132
194 | 126 163
195 | 126 180
196 | 128 38
197 | 128 111
198 | 129 118
199 | 132 29
200 | 132 30
201 | 133 30
202 | 134 135
203 | 134 150
204 | 135 134
205 | 137 144
206 | 138 118
207 | 138 129
208 | 139 142
209 | 141 157
210 | 141 163
211 | 142 139
212 | 143 2
213 | 144 137
214 | 145 151
215 | 146 137
216 | 146 165
217 | 146 169
218 | 146 171
219 | 147 31
220 | 147 128
221 | 148 146
222 | 148 169
223 | 148 171
224 | 148 282
225 | 149 128
226 | 149 148
227 | 149 172
228 | 150 86
229 | 151 145
230 | 152 4
231 | 153 134
232 | 154 155
233 | 156 161
234 | 157 141
235 | 161 156
236 | 165 144
237 | 165 148
238 | 167 149
239 | 169 15
240 | 169 148
241 | 169 171
242 | 170 115
243 | 170 173
244 | 170 183
245 | 170 202
246 | 171 72
247 | 171 148
248 | 171 169
249 | 173 170
250 | 175 100
251 | 176 10
252 | 178 181
253 | 181 178
254 | 182 38
255 | 182 171
256 | 183 96
257 | 185 50
258 | 186 127
259 | 187 50
260 | 187 65
261 | 188 30
262 | 188 50
263 | 189 87
264 | 189 89
265 | 190 35
266 | 190 38
267 | 190 122
268 | 190 182
269 | 191 54
270 | 191 118
271 | 191 129
272 | 191 172
273 | 192 149
274 | 192 167
275 | 195 75
276 | 197 50
277 | 197 188
278 | 198 218
279 | 198 221
280 | 198 222
281 | 200 65
282 | 200 220
283 | 201 113
284 | 202 156
285 | 203 232
286 | 204 194
287 | 207 38
288 | 207 122
289 | 207 124
290 | 208 30
291 | 208 50
292 | 210 38
293 | 210 207
294 | 211 37
295 | 213 35
296 | 213 38
297 | 214 13
298 | 214 14
299 | 214 171
300 | 214 213
301 | 215 75
302 | 217 39
303 | 218 68
304 | 218 222
305 | 221 198
306 | 222 198
307 | 222 218
308 | 223 39
309 | 225 3
310 | 226 22
311 | 229 65
312 | 230 68
313 | 231 43
314 | 232 95
315 | 232 203
316 | 233 99
317 | 234 68
318 | 234 230
319 | 237 244
320 | 238 145
321 | 242 3
322 | 242 113
323 | 244 237
324 | 249 96
325 | 250 156
326 | 252 65
327 | 254 65
328 | 258 113
329 | 268 4
330 | 270 183
331 | 272 6
332 | 275 96
333 | 280 183
334 | 280 206
335 | 282 37
336 | 285 75
337 | 290 285
338 | 293 290
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/algorithms/plot_beam_search.py:
--------------------------------------------------------------------------------
1 | # beam_search.py - progressive widening beam search
2 | #
3 | # Copyright 2016-2019 NetworkX developers.
4 | """
5 | ===========
6 | Beam Search
7 | ===========
8 |
9 | Beam search with dynamic beam width.
10 |
11 | The progressive widening beam search repeatedly executes a beam search
12 | with increasing beam width until the target node is found.
13 | """
14 | import math
15 |
16 | import networkx as nx
17 |
18 |
19 | def progressive_widening_search(G, source, value, condition, initial_width=1):
20 | """Progressive widening beam search to find a node.
21 |
22 | The progressive widening beam search involves a repeated beam
23 | search, starting with a small beam width then extending to
24 | progressively larger beam widths if the target node is not
25 | found. This implementation simply returns the first node found that
26 | matches the termination condition.
27 |
28 | `G` is a NetworkX graph.
29 |
30 | `source` is a node in the graph. The search for the node of interest
31 | begins here and extends only to those nodes in the (weakly)
32 | connected component of this node.
33 |
34 | `value` is a function that returns a real number indicating how good
35 | a potential neighbor node is when deciding which neighbor nodes to
36 | enqueue in the breadth-first search. Only the best nodes within the
37 | current beam width will be enqueued at each step.
38 |
39 | `condition` is the termination condition for the search. This is a
40 | function that takes a node as input and return a Boolean indicating
41 | whether the node is the target. If no node matches the termination
42 | condition, this function raises :exc:`NodeNotFound`.
43 |
44 | `initial_width` is the starting beam width for the beam search (the
45 | default is one). If no node matching the `condition` is found with
46 | this beam width, the beam search is restarted from the `source` node
47 | with a beam width that is twice as large (so the beam width
48 | increases exponentially). The search terminates after the beam width
49 | exceeds the number of nodes in the graph.
50 |
51 | """
52 | # Check for the special case in which the source node satisfies the
53 | # termination condition.
54 | if condition(source):
55 | return source
56 | # The largest possible value of `i` in this range yields a width at
57 | # least the number of nodes in the graph, so the final invocation of
58 | # `bfs_beam_edges` is equivalent to a plain old breadth-first
59 | # search. Therefore, all nodes will eventually be visited.
60 | #
61 | # TODO In Python 3.3+, this should be `math.log2(len(G))`.
62 | log_m = math.ceil(math.log(len(G), 2))
63 | for i in range(log_m):
64 | width = initial_width * pow(2, i)
65 | # Since we are always starting from the same source node, this
66 | # search may visit the same nodes many times (depending on the
67 | # implementation of the `value` function).
68 | for u, v in nx.bfs_beam_edges(G, source, value, width):
69 | if condition(v):
70 | return v
71 | # At this point, since all nodes have been visited, we know that
72 | # none of the nodes satisfied the termination condition.
73 | raise nx.NodeNotFound('no node satisfied the termination condition')
74 |
75 |
76 | def main():
77 | """Search for a node with high centrality.
78 |
79 | In this example, we generate a random graph, compute the centrality
80 | of each node, then perform the progressive widening search in order
81 | to find a node of high centrality.
82 |
83 | """
84 | G = nx.gnp_random_graph(100, 0.5)
85 | centrality = nx.eigenvector_centrality(G)
86 | avg_centrality = sum(centrality.values()) / len(G)
87 |
88 | def has_high_centrality(v):
89 | return centrality[v] >= avg_centrality
90 |
91 | source = 0
92 | value = centrality.get
93 | condition = has_high_centrality
94 |
95 | found_node = progressive_widening_search(G, source, value, condition)
96 | c = centrality[found_node]
97 | print('found node {0} with centrality {1}'.format(found_node, c))
98 |
99 |
100 | if __name__ == '__main__':
101 | main()
102 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/algorithms/plot_blockmodel.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # encoding: utf-8
3 | """
4 | ==========
5 | Blockmodel
6 | ==========
7 |
8 | Example of creating a block model using the quotient_graph function in NX. Data
9 | used is the Hartford, CT drug users network::
10 |
11 | @article{weeks2002social,
12 | title={Social networks of drug users in high-risk sites: Finding the connections},
13 | url = {https://doi.org/10.1023/A:1015457400897},
14 | doi = {10.1023/A:1015457400897},
15 | author={Weeks, Margaret R and Clair, Scott and Borgatti, Stephen P and Radda, Kim and Schensul, Jean J},
16 | journal={{AIDS and Behavior}},
17 | volume={6},
18 | number={2},
19 | pages={193--206},
20 | year={2002},
21 | publisher={Springer}
22 | }
23 |
24 | """
25 | # Authors: Drew Conway , Aric Hagberg
26 |
27 | from collections import defaultdict
28 |
29 | import matplotlib.pyplot as plt
30 | import networkx as nx
31 | import numpy
32 | from scipy.cluster import hierarchy
33 | from scipy.spatial import distance
34 |
35 |
36 | def create_hc(G):
37 | """Creates hierarchical cluster of graph G from distance matrix"""
38 | path_length = nx.all_pairs_shortest_path_length(G)
39 | distances = numpy.zeros((len(G), len(G)))
40 | for u, p in path_length:
41 | for v, d in p.items():
42 | distances[u][v] = d
43 | # Create hierarchical cluster
44 | Y = distance.squareform(distances)
45 | Z = hierarchy.complete(Y) # Creates HC using farthest point linkage
46 | # This partition selection is arbitrary, for illustrive purposes
47 | membership = list(hierarchy.fcluster(Z, t=1.15))
48 | # Create collection of lists for blockmodel
49 | partition = defaultdict(list)
50 | for n, p in zip(list(range(len(G))), membership):
51 | partition[p].append(n)
52 | return list(partition.values())
53 |
54 |
55 | if __name__ == '__main__':
56 | G = nx.read_edgelist("hartford_drug.edgelist")
57 |
58 | # Extract largest connected component into graph H
59 | H = G.subgraph(next(nx.connected_components(G)))
60 | # Makes life easier to have consecutively labeled integer nodes
61 | H = nx.convert_node_labels_to_integers(H)
62 | # Create parititions with hierarchical clustering
63 | partitions = create_hc(H)
64 | # Build blockmodel graph
65 | BM = nx.quotient_graph(H, partitions, relabel=True)
66 |
67 | # Draw original graph
68 | pos = nx.spring_layout(H, iterations=100)
69 | plt.subplot(211)
70 | nx.draw(H, pos, with_labels=False, node_size=10)
71 |
72 | # Draw block model with weighted edges and nodes sized by number of internal nodes
73 | node_size = [BM.nodes[x]['nnodes'] * 10 for x in BM.nodes()]
74 | edge_width = [(2 * d['weight']) for (u, v, d) in BM.edges(data=True)]
75 | # Set positions to mean of positions of internal nodes from original graph
76 | posBM = {}
77 | for n in BM:
78 | xy = numpy.array([pos[u] for u in BM.nodes[n]['graph']])
79 | posBM[n] = xy.mean(axis=0)
80 | plt.subplot(212)
81 | nx.draw(BM, posBM, node_size=node_size, width=edge_width, with_labels=False)
82 | plt.axis('off')
83 | plt.show()
84 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/algorithms/plot_davis_club.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ==========
4 | Davis Club
5 | ==========
6 |
7 | Davis Southern Club Women
8 |
9 | Shows how to make unipartite projections of the graph and compute the
10 | properties of those graphs.
11 |
12 | These data were collected by Davis et al. in the 1930s.
13 | They represent observed attendance at 14 social events by 18 Southern women.
14 | The graph is bipartite (clubs, women).
15 | """
16 | import matplotlib.pyplot as plt
17 | import networkx as nx
18 | import networkx.algorithms.bipartite as bipartite
19 |
20 | G = nx.davis_southern_women_graph()
21 | women = G.graph['top']
22 | clubs = G.graph['bottom']
23 |
24 | print("Biadjacency matrix")
25 | print(bipartite.biadjacency_matrix(G, women, clubs))
26 |
27 | # project bipartite graph onto women nodes
28 | W = bipartite.projected_graph(G, women)
29 | print('')
30 | print("#Friends, Member")
31 | for w in women:
32 | print('%d %s' % (W.degree(w), w))
33 |
34 | # project bipartite graph onto women nodes keeping number of co-occurence
35 | # the degree computed is weighted and counts the total number of shared contacts
36 | W = bipartite.weighted_projected_graph(G, women)
37 | print('')
38 | print("#Friend meetings, Member")
39 | for w in women:
40 | print('%d %s' % (W.degree(w, weight='weight'), w))
41 |
42 | nx.draw(G)
43 | plt.show()
44 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/algorithms/plot_krackhardt_centrality.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | =====================
4 | Krackhardt Centrality
5 | =====================
6 |
7 | Centrality measures of Krackhardt social network.
8 | """
9 | # Author: Aric Hagberg (hagberg@lanl.gov)
10 | # Date: 2005-05-12 14:33:11 -0600 (Thu, 12 May 2005)
11 | # Revision: 998
12 |
13 | # Copyright (C) 2004-2019 by
14 | # Aric Hagberg
15 | # Dan Schult
16 | # Pieter Swart
17 | # All rights reserved.
18 | # BSD license.
19 |
20 | import matplotlib.pyplot as plt
21 | import networkx as nx
22 |
23 | G = nx.krackhardt_kite_graph()
24 |
25 | print("Betweenness")
26 | b = nx.betweenness_centrality(G)
27 | for v in G.nodes():
28 | print("%0.2d %5.3f" % (v, b[v]))
29 |
30 | print("Degree centrality")
31 | d = nx.degree_centrality(G)
32 | for v in G.nodes():
33 | print("%0.2d %5.3f" % (v, d[v]))
34 |
35 | print("Closeness centrality")
36 | c = nx.closeness_centrality(G)
37 | for v in G.nodes():
38 | print("%0.2d %5.3f" % (v, c[v]))
39 |
40 | nx.draw(G)
41 | plt.show()
42 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/algorithms/plot_rcm.py:
--------------------------------------------------------------------------------
1 | """
2 | ===
3 | Rcm
4 | ===
5 |
6 | Cuthill-McKee ordering of matrices
7 |
8 | The reverse Cuthill-McKee algorithm gives a sparse matrix ordering that
9 | reduces the matrix bandwidth.
10 | """
11 |
12 | # Copyright (C) 2011-2019 by
13 | # Author: Aric Hagberg
14 | # BSD License
15 | import networkx as nx
16 | from networkx.utils import reverse_cuthill_mckee_ordering
17 | import numpy as np
18 |
19 | # build low-bandwidth numpy matrix
20 | G = nx.grid_2d_graph(3, 3)
21 | rcm = list(reverse_cuthill_mckee_ordering(G))
22 | print("ordering", rcm)
23 |
24 | print("unordered Laplacian matrix")
25 | A = nx.laplacian_matrix(G)
26 | x, y = np.nonzero(A)
27 | #print("lower bandwidth:",(y-x).max())
28 | #print("upper bandwidth:",(x-y).max())
29 | print("bandwidth: %d" % ((y - x).max() + (x - y).max() + 1))
30 | print(A)
31 |
32 | B = nx.laplacian_matrix(G, nodelist=rcm)
33 | print("low-bandwidth Laplacian matrix")
34 | x, y = np.nonzero(B)
35 | #print("lower bandwidth:",(y-x).max())
36 | #print("upper bandwidth:",(x-y).max())
37 | print("bandwidth: %d" % ((y - x).max() + (x - y).max() + 1))
38 | print(B)
39 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/basic/README.txt:
--------------------------------------------------------------------------------
1 | Basic
2 | -----
3 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/basic/plot_properties.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ==========
4 | Properties
5 | ==========
6 |
7 | Compute some network properties for the lollipop graph.
8 | """
9 | # Copyright (C) 2004-2019 by
10 | # Aric Hagberg
11 | # Dan Schult
12 | # Pieter Swart
13 | # All rights reserved.
14 | # BSD license.
15 |
16 | import matplotlib.pyplot as plt
17 | from networkx import nx
18 |
19 | G = nx.lollipop_graph(4, 6)
20 |
21 | pathlengths = []
22 |
23 | print("source vertex {target:length, }")
24 | for v in G.nodes():
25 | spl = dict(nx.single_source_shortest_path_length(G, v))
26 | print('{} {} '.format(v, spl))
27 | for p in spl:
28 | pathlengths.append(spl[p])
29 |
30 | print('')
31 | print("average shortest path length %s" % (sum(pathlengths) / len(pathlengths)))
32 |
33 | # histogram of path lengths
34 | dist = {}
35 | for p in pathlengths:
36 | if p in dist:
37 | dist[p] += 1
38 | else:
39 | dist[p] = 1
40 |
41 | print('')
42 | print("length #paths")
43 | verts = dist.keys()
44 | for d in sorted(verts):
45 | print('%s %d' % (d, dist[d]))
46 |
47 | print("radius: %d" % nx.radius(G))
48 | print("diameter: %d" % nx.diameter(G))
49 | print("eccentricity: %s" % nx.eccentricity(G))
50 | print("center: %s" % nx.center(G))
51 | print("periphery: %s" % nx.periphery(G))
52 | print("density: %s" % nx.density(G))
53 |
54 | nx.draw(G, with_labels=True)
55 | plt.show()
56 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/basic/plot_read_write.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ======================
4 | Read and write graphs.
5 | ======================
6 |
7 | Read and write graphs.
8 | """
9 | # Author: Aric Hagberg (hagberg@lanl.gov)
10 |
11 | # Copyright (C) 2004-2019 by
12 | # Aric Hagberg
13 | # Dan Schult
14 | # Pieter Swart
15 | # All rights reserved.
16 | # BSD license.
17 |
18 | import sys
19 |
20 | import matplotlib.pyplot as plt
21 | import networkx as nx
22 |
23 | G = nx.grid_2d_graph(5, 5) # 5x5 grid
24 |
25 | # print the adjacency list
26 | for line in nx.generate_adjlist(G):
27 | print(line)
28 | # write edgelist to grid.edgelist
29 | nx.write_edgelist(G, path="grid.edgelist", delimiter=":")
30 | # read edgelist from grid.edgelist
31 | H = nx.read_edgelist(path="grid.edgelist", delimiter=":")
32 |
33 | nx.draw(H)
34 | plt.show()
35 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/README.txt:
--------------------------------------------------------------------------------
1 | Drawing
2 | -------
3 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/chess_masters_WCC.pgn.bz2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/doc/networkx-2.4/examples/drawing/chess_masters_WCC.pgn.bz2
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/knuth_miles.txt.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/doc/networkx-2.4/examples/drawing/knuth_miles.txt.gz
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_atlas.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | =====
4 | Atlas
5 | =====
6 |
7 | Atlas of all graphs of 6 nodes or less.
8 |
9 | """
10 | # Author: Aric Hagberg (hagberg@lanl.gov)
11 |
12 | # Copyright (C) 2004-2019 by
13 | # Aric Hagberg
14 | # Dan Schult
15 | # Pieter Swart
16 | # All rights reserved.
17 | # BSD license.
18 |
19 | import random
20 |
21 | try:
22 | import pygraphviz
23 | from networkx.drawing.nx_agraph import graphviz_layout
24 | except ImportError:
25 | try:
26 | import pydot
27 | from networkx.drawing.nx_pydot import graphviz_layout
28 | except ImportError:
29 | raise ImportError("This example needs Graphviz and either "
30 | "PyGraphviz or pydot.")
31 |
32 | import matplotlib.pyplot as plt
33 |
34 | import networkx as nx
35 | from networkx.algorithms.isomorphism.isomorph import graph_could_be_isomorphic as isomorphic
36 | from networkx.generators.atlas import graph_atlas_g
37 |
38 |
39 | def atlas6():
40 | """ Return the atlas of all connected graphs of 6 nodes or less.
41 | Attempt to check for isomorphisms and remove.
42 | """
43 |
44 | Atlas = graph_atlas_g()[0:208] # 208
45 | # remove isolated nodes, only connected graphs are left
46 | U = nx.Graph() # graph for union of all graphs in atlas
47 | for G in Atlas:
48 | zerodegree = [n for n in G if G.degree(n) == 0]
49 | for n in zerodegree:
50 | G.remove_node(n)
51 | U = nx.disjoint_union(U, G)
52 |
53 | # iterator of graphs of all connected components
54 | C = (U.subgraph(c) for c in nx.connected_components(U))
55 |
56 | UU = nx.Graph()
57 | # do quick isomorphic-like check, not a true isomorphism checker
58 | nlist = [] # list of nonisomorphic graphs
59 | for G in C:
60 | # check against all nonisomorphic graphs so far
61 | if not iso(G, nlist):
62 | nlist.append(G)
63 | UU = nx.disjoint_union(UU, G) # union the nonisomorphic graphs
64 | return UU
65 |
66 |
67 | def iso(G1, glist):
68 | """Quick and dirty nonisomorphism checker used to check isomorphisms."""
69 | for G2 in glist:
70 | if isomorphic(G1, G2):
71 | return True
72 | return False
73 |
74 |
75 | if __name__ == '__main__':
76 | G = atlas6()
77 |
78 | print("graph has %d nodes with %d edges"
79 | % (nx.number_of_nodes(G), nx.number_of_edges(G)))
80 | print(nx.number_connected_components(G), "connected components")
81 |
82 | plt.figure(1, figsize=(8, 8))
83 | # layout graphs with positions using graphviz neato
84 | pos = graphviz_layout(G, prog="neato")
85 | # color nodes the same in each connected subgraph
86 | C = (G.subgraph(c) for c in nx.connected_components(G))
87 | for g in C:
88 | c = [random.random()] * nx.number_of_nodes(g) # random color...
89 | nx.draw(g,
90 | pos,
91 | node_size=40,
92 | node_color=c,
93 | vmin=0.0,
94 | vmax=1.0,
95 | with_labels=False
96 | )
97 | plt.show()
98 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_chess_masters.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | """
4 | =============
5 | Chess Masters
6 | =============
7 |
8 | An example of the MultiDiGraph clas
9 |
10 | The function chess_pgn_graph reads a collection of chess matches stored in the
11 | specified PGN file (PGN ="Portable Game Notation"). Here the (compressed)
12 | default file::
13 |
14 | chess_masters_WCC.pgn.bz2
15 |
16 | contains all 685 World Chess Championship matches from 1886--1985.
17 | (data from http://chessproblem.my-free-games.com/chess/games/Download-PGN.php)
18 |
19 | The `chess_pgn_graph()` function returns a `MultiDiGraph` with multiple edges.
20 | Each node is the last name of a chess master. Each edge is directed from white
21 | to black and contains selected game info.
22 |
23 | The key statement in `chess_pgn_graph` below is::
24 |
25 | G.add_edge(white, black, game_info)
26 |
27 | where `game_info` is a `dict` describing each game.
28 | """
29 | # Copyright (C) 2006-2019 by
30 | # Aric Hagberg
31 | # Dan Schult
32 | # Pieter Swart
33 | # All rights reserved.
34 | # BSD license.
35 |
36 | import matplotlib.pyplot as plt
37 | import networkx as nx
38 |
39 | # tag names specifying what game info should be
40 | # stored in the dict on each digraph edge
41 | game_details = ["Event",
42 | "Date",
43 | "Result",
44 | "ECO",
45 | "Site"]
46 |
47 |
48 | def chess_pgn_graph(pgn_file="chess_masters_WCC.pgn.bz2"):
49 | """Read chess games in pgn format in pgn_file.
50 |
51 | Filenames ending in .gz or .bz2 will be uncompressed.
52 |
53 | Return the MultiDiGraph of players connected by a chess game.
54 | Edges contain game data in a dict.
55 |
56 | """
57 | import bz2
58 | G = nx.MultiDiGraph()
59 | game = {}
60 | datafile = bz2.BZ2File(pgn_file)
61 | lines = (line.decode().rstrip('\r\n') for line in datafile)
62 | for line in lines:
63 | if line.startswith('['):
64 | tag, value = line[1:-1].split(' ', 1)
65 | game[str(tag)] = value.strip('"')
66 | else:
67 | # empty line after tag set indicates
68 | # we finished reading game info
69 | if game:
70 | white = game.pop('White')
71 | black = game.pop('Black')
72 | G.add_edge(white, black, **game)
73 | game = {}
74 | return G
75 |
76 |
77 | if __name__ == '__main__':
78 | G = chess_pgn_graph()
79 |
80 | ngames = G.number_of_edges()
81 | nplayers = G.number_of_nodes()
82 |
83 | print("Loaded %d chess games between %d players\n"
84 | % (ngames, nplayers))
85 |
86 | # identify connected components
87 | # of the undirected version
88 | H = G.to_undirected()
89 | Gcc = [H.subgraph(c) for c in nx.connected_components(H)]
90 | if len(Gcc) > 1:
91 | print("Note the disconnected component consisting of:")
92 | print(Gcc[1].nodes())
93 |
94 | # find all games with B97 opening (as described in ECO)
95 | openings = set([game_info['ECO']
96 | for (white, black, game_info) in G.edges(data=True)])
97 | print("\nFrom a total of %d different openings," % len(openings))
98 | print('the following games used the Sicilian opening')
99 | print('with the Najdorff 7...Qb6 "Poisoned Pawn" variation.\n')
100 |
101 | for (white, black, game_info) in G.edges(data=True):
102 | if game_info['ECO'] == 'B97':
103 | print(white, "vs", black)
104 | for k, v in game_info.items():
105 | print(" ", k, ": ", v)
106 | print("\n")
107 |
108 | # make new undirected graph H without multi-edges
109 | H = nx.Graph(G)
110 |
111 | # edge width is proportional number of games played
112 | edgewidth = []
113 | for (u, v, d) in H.edges(data=True):
114 | edgewidth.append(len(G.get_edge_data(u, v)))
115 |
116 | # node size is proportional to number of games won
117 | wins = dict.fromkeys(G.nodes(), 0.0)
118 | for (u, v, d) in G.edges(data=True):
119 | r = d['Result'].split('-')
120 | if r[0] == '1':
121 | wins[u] += 1.0
122 | elif r[0] == '1/2':
123 | wins[u] += 0.5
124 | wins[v] += 0.5
125 | else:
126 | wins[v] += 1.0
127 | try:
128 | pos = nx.nx_agraph.graphviz_layout(H)
129 | except:
130 | pos = nx.spring_layout(H, iterations=20)
131 |
132 | plt.rcParams['text.usetex'] = False
133 | plt.figure(figsize=(8, 8))
134 | nx.draw_networkx_edges(H, pos, alpha=0.3, width=edgewidth, edge_color='m')
135 | nodesize = [wins[v] * 50 for v in H]
136 | nx.draw_networkx_nodes(H, pos, node_size=nodesize, node_color='w', alpha=0.4)
137 | nx.draw_networkx_edges(H, pos, alpha=0.4, node_size=0, width=1, edge_color='k')
138 | nx.draw_networkx_labels(H, pos, fontsize=14)
139 | font = {'fontname': 'Helvetica',
140 | 'color': 'k',
141 | 'fontweight': 'bold',
142 | 'fontsize': 14}
143 | plt.title("World Chess Championship Games: 1886 - 1985", font)
144 |
145 | # change font and write text (using data coordinates)
146 | font = {'fontname': 'Helvetica',
147 | 'color': 'r',
148 | 'fontweight': 'bold',
149 | 'fontsize': 14}
150 |
151 | plt.text(0.5, 0.97, "edge width = # games played",
152 | horizontalalignment='center',
153 | transform=plt.gca().transAxes)
154 | plt.text(0.5, 0.94, "node size = # games won",
155 | horizontalalignment='center',
156 | transform=plt.gca().transAxes)
157 |
158 | plt.axis('off')
159 | plt.show()
160 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_circular_tree.py:
--------------------------------------------------------------------------------
1 | """
2 | =============
3 | Circular Tree
4 | =============
5 |
6 | This
7 | """
8 | import matplotlib.pyplot as plt
9 | import networkx as nx
10 |
11 | try:
12 | import pygraphviz
13 | from networkx.drawing.nx_agraph import graphviz_layout
14 | except ImportError:
15 | try:
16 | import pydot
17 | from networkx.drawing.nx_pydot import graphviz_layout
18 | except ImportError:
19 | raise ImportError("This example needs Graphviz and either "
20 | "PyGraphviz or pydot")
21 |
22 | G = nx.balanced_tree(3, 5)
23 | pos = graphviz_layout(G, prog='twopi', args='')
24 | plt.figure(figsize=(8, 8))
25 | nx.draw(G, pos, node_size=20, alpha=0.5, node_color="blue", with_labels=False)
26 | plt.axis('equal')
27 | plt.show()
28 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_degree_histogram.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ================
4 | Degree histogram
5 | ================
6 |
7 | Draw degree histogram with matplotlib.
8 | Random graph shown as inset
9 | """
10 | import collections
11 | import matplotlib.pyplot as plt
12 | import networkx as nx
13 |
14 | G = nx.gnp_random_graph(100, 0.02)
15 |
16 | degree_sequence = sorted([d for n, d in G.degree()], reverse=True) # degree sequence
17 | # print "Degree sequence", degree_sequence
18 | degreeCount = collections.Counter(degree_sequence)
19 | deg, cnt = zip(*degreeCount.items())
20 |
21 | fig, ax = plt.subplots()
22 | plt.bar(deg, cnt, width=0.80, color='b')
23 |
24 | plt.title("Degree Histogram")
25 | plt.ylabel("Count")
26 | plt.xlabel("Degree")
27 | ax.set_xticks([d + 0.4 for d in deg])
28 | ax.set_xticklabels(deg)
29 |
30 | # draw graph in inset
31 | plt.axes([0.4, 0.4, 0.5, 0.5])
32 | Gcc = G.subgraph(sorted(nx.connected_components(G), key=len, reverse=True)[0])
33 | pos = nx.spring_layout(G)
34 | plt.axis('off')
35 | nx.draw_networkx_nodes(G, pos, node_size=20)
36 | nx.draw_networkx_edges(G, pos, alpha=0.4)
37 |
38 | plt.show()
39 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_degree_rank.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ===========
4 | Degree Rank
5 | ===========
6 |
7 | Random graph from given degree sequence.
8 | Draw degree rank plot and graph with matplotlib.
9 | """
10 | # Author: Aric Hagberg
11 | import networkx as nx
12 | import matplotlib.pyplot as plt
13 |
14 | G = nx.gnp_random_graph(100, 0.02)
15 |
16 | degree_sequence = sorted([d for n, d in G.degree()], reverse=True)
17 | # print "Degree sequence", degree_sequence
18 | dmax = max(degree_sequence)
19 |
20 | plt.loglog(degree_sequence, 'b-', marker='o')
21 | plt.title("Degree rank plot")
22 | plt.ylabel("degree")
23 | plt.xlabel("rank")
24 |
25 | # draw graph in inset
26 | plt.axes([0.45, 0.45, 0.45, 0.45])
27 | Gcc = G.subgraph(sorted(nx.connected_components(G), key=len, reverse=True)[0])
28 | pos = nx.spring_layout(Gcc)
29 | plt.axis('off')
30 | nx.draw_networkx_nodes(Gcc, pos, node_size=20)
31 | nx.draw_networkx_edges(Gcc, pos, alpha=0.4)
32 |
33 | plt.show()
34 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_directed.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | """
3 | ==============
4 | Directed Graph
5 | ==============
6 |
7 | Draw a graph with directed edges using a colormap and different node sizes.
8 |
9 | Edges have different colors and alphas (opacity). Drawn using matplotlib.
10 | """
11 | # Author: Rodrigo Dorantes-Gilardi (rodgdor@gmail.com)
12 |
13 | import matplotlib as mpl
14 | import matplotlib.pyplot as plt
15 | import networkx as nx
16 |
17 | G = nx.generators.directed.random_k_out_graph(10, 3, 0.5)
18 | pos = nx.layout.spring_layout(G)
19 |
20 | node_sizes = [3 + 10 * i for i in range(len(G))]
21 | M = G.number_of_edges()
22 | edge_colors = range(2, M + 2)
23 | edge_alphas = [(5 + i) / (M + 4) for i in range(M)]
24 |
25 | nodes = nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color='blue')
26 | edges = nx.draw_networkx_edges(G, pos, node_size=node_sizes, arrowstyle='->',
27 | arrowsize=10, edge_color=edge_colors,
28 | edge_cmap=plt.cm.Blues, width=2)
29 | # set alpha value for each edge
30 | for i in range(M):
31 | edges[i].set_alpha(edge_alphas[i])
32 |
33 | pc = mpl.collections.PatchCollection(edges, cmap=plt.cm.Blues)
34 | pc.set_array(edge_colors)
35 | plt.colorbar(pc)
36 |
37 | ax = plt.gca()
38 | ax.set_axis_off()
39 | plt.show()
40 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_edge_colormap.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | =============
4 | Edge Colormap
5 | =============
6 |
7 | Draw a graph with matplotlib, color edges.
8 | You must have matplotlib>=87.7 for this to work.
9 | """
10 | # Author: Aric Hagberg (hagberg@lanl.gov)
11 |
12 | import matplotlib.pyplot as plt
13 | import networkx as nx
14 |
15 | G = nx.star_graph(20)
16 | pos = nx.spring_layout(G)
17 | colors = range(20)
18 | nx.draw(G, pos, node_color='#A0CBE2', edge_color=colors,
19 | width=4, edge_cmap=plt.cm.Blues, with_labels=False)
20 | plt.show()
21 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_ego_graph.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | =========
5 | Ego Graph
6 | =========
7 |
8 | Example using the NetworkX ego_graph() function to return the main egonet of
9 | the largest hub in a Barabási-Albert network.
10 | """
11 | # Author: Drew Conway (drew.conway@nyu.edu)
12 |
13 | from operator import itemgetter
14 |
15 | import matplotlib.pyplot as plt
16 | import networkx as nx
17 |
18 | if __name__ == '__main__':
19 | # Create a BA model graph
20 | n = 1000
21 | m = 2
22 | G = nx.generators.barabasi_albert_graph(n, m)
23 | # find node with largest degree
24 | node_and_degree = G.degree()
25 | (largest_hub, degree) = sorted(node_and_degree, key=itemgetter(1))[-1]
26 | # Create ego graph of main hub
27 | hub_ego = nx.ego_graph(G, largest_hub)
28 | # Draw graph
29 | pos = nx.spring_layout(hub_ego)
30 | nx.draw(hub_ego, pos, node_color='b', node_size=50, with_labels=False)
31 | # Draw ego as large and red
32 | nx.draw_networkx_nodes(hub_ego, pos, nodelist=[largest_hub], node_size=300, node_color='r')
33 | plt.show()
34 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_four_grids.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ==========
4 | Four Grids
5 | ==========
6 |
7 | Draw a graph with matplotlib.
8 | You must have matplotlib for this to work.
9 | """
10 | # Author: Aric Hagberg (hagberg@lanl.gov)
11 |
12 | # Copyright (C) 2004-2019
13 | # Aric Hagberg
14 | # Dan Schult
15 | # Pieter Swart
16 | # All rights reserved.
17 | # BSD license.
18 |
19 | import matplotlib.pyplot as plt
20 | import networkx as nx
21 |
22 | G = nx.grid_2d_graph(4, 4) # 4x4 grid
23 |
24 | pos = nx.spring_layout(G, iterations=100)
25 |
26 | plt.subplot(221)
27 | nx.draw(G, pos, font_size=8)
28 |
29 | plt.subplot(222)
30 | nx.draw(G, pos, node_color='k', node_size=0, with_labels=False)
31 |
32 | plt.subplot(223)
33 | nx.draw(G, pos, node_color='g', node_size=250, with_labels=False, width=6)
34 |
35 | plt.subplot(224)
36 | H = G.to_directed()
37 | nx.draw(H, pos, node_color='b', node_size=20, with_labels=False)
38 |
39 | plt.show()
40 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_giant_component.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ===============
4 | Giant Component
5 | ===============
6 |
7 | This example illustrates the sudden appearance of a
8 | giant connected component in a binomial random graph.
9 | """
10 | # Copyright (C) 2006-2019
11 | # Aric Hagberg
12 | # Dan Schult
13 | # Pieter Swart
14 | # All rights reserved.
15 | # BSD license.
16 |
17 | import math
18 |
19 | import matplotlib.pyplot as plt
20 | import networkx as nx
21 |
22 | try:
23 | import pygraphviz
24 | from networkx.drawing.nx_agraph import graphviz_layout
25 | layout = graphviz_layout
26 | except ImportError:
27 | try:
28 | import pydot
29 | from networkx.drawing.nx_pydot import graphviz_layout
30 | layout = graphviz_layout
31 | except ImportError:
32 | print("PyGraphviz and pydot not found;\n"
33 | "drawing with spring layout;\n"
34 | "will be slow.")
35 | layout = nx.spring_layout
36 |
37 |
38 | n = 150 # 150 nodes
39 | # p value at which giant component (of size log(n) nodes) is expected
40 | p_giant = 1.0 / (n - 1)
41 | # p value at which graph is expected to become completely connected
42 | p_conn = math.log(n) / float(n)
43 |
44 | # the following range of p values should be close to the threshold
45 | pvals = [0.003, 0.006, 0.008, 0.015]
46 |
47 | region = 220 # for pylab 2x2 subplot layout
48 | plt.subplots_adjust(left=0, right=1, bottom=0, top=0.95, wspace=0.01, hspace=0.01)
49 | for p in pvals:
50 | G = nx.binomial_graph(n, p)
51 | pos = layout(G)
52 | region += 1
53 | plt.subplot(region)
54 | plt.title("p = %6.3f" % (p))
55 | nx.draw(G, pos,
56 | with_labels=False,
57 | node_size=10
58 | )
59 | # identify largest connected component
60 | Gcc = sorted(nx.connected_components(G), key=len, reverse=True)
61 | G0 = G.subgraph(Gcc[0])
62 | nx.draw_networkx_edges(G0, pos,
63 | with_labels=False,
64 | edge_color='r',
65 | width=6.0
66 | )
67 | # show other connected components
68 | for Gi in Gcc[1:]:
69 | if len(Gi) > 1:
70 | nx.draw_networkx_edges(G.subgraph(Gi), pos,
71 | with_labels=False,
72 | edge_color='r',
73 | alpha=0.3,
74 | width=5.0
75 | )
76 | plt.show()
77 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_house_with_colors.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | =================
4 | House With Colors
5 | =================
6 |
7 | Draw a graph with matplotlib.
8 | You must have matplotlib for this to work.
9 | """
10 | # Author: Aric Hagberg (hagberg@lanl.gov)
11 | import matplotlib.pyplot as plt
12 | import networkx as nx
13 |
14 | G = nx.house_graph()
15 | # explicitly set positions
16 | pos = {0: (0, 0),
17 | 1: (1, 0),
18 | 2: (0, 1),
19 | 3: (1, 1),
20 | 4: (0.5, 2.0)}
21 |
22 | nx.draw_networkx_nodes(G, pos, node_size=2000, nodelist=[4])
23 | nx.draw_networkx_nodes(G, pos, node_size=3000, nodelist=[0, 1, 2, 3], node_color='b')
24 | nx.draw_networkx_edges(G, pos, alpha=0.5, width=6)
25 | plt.axis('off')
26 | plt.show()
27 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_knuth_miles.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ===========
4 | Knuth Miles
5 | ===========
6 |
7 | `miles_graph()` returns an undirected graph over the 128 US cities from
8 | the datafile `miles_dat.txt`. The cities each have location and population
9 | data. The edges are labeled with the distance between the two cities.
10 |
11 | This example is described in Section 1.1 in Knuth's book (see [1]_ and [2]_).
12 |
13 | The data file can be found at:
14 | https://github.com/networkx/networkx/blob/master/examples/drawing/knuth_miles.txt.gz
15 |
16 | References.
17 | -----------
18 |
19 | .. [1] Donald E. Knuth,
20 | "The Stanford GraphBase: A Platform for Combinatorial Computing",
21 | ACM Press, New York, 1993.
22 | .. [2] http://www-cs-faculty.stanford.edu/~knuth/sgb.html
23 |
24 | """
25 | # Author: Aric Hagberg (hagberg@lanl.gov)
26 |
27 | # Copyright (C) 2004-2019 by
28 | # Aric Hagberg
29 | # Dan Schult
30 | # Pieter Swart
31 | # All rights reserved.
32 | # BSD license.
33 |
34 | import re
35 | import sys
36 |
37 | import matplotlib.pyplot as plt
38 | import networkx as nx
39 |
40 |
41 | def miles_graph():
42 | """ Return the cites example graph in miles_dat.txt
43 | from the Stanford GraphBase.
44 | """
45 | # open file miles_dat.txt.gz (or miles_dat.txt)
46 | import gzip
47 | fh = gzip.open('knuth_miles.txt.gz', 'r')
48 |
49 | G = nx.Graph()
50 | G.position = {}
51 | G.population = {}
52 |
53 | cities = []
54 | for line in fh.readlines():
55 | line = line.decode()
56 | if line.startswith("*"): # skip comments
57 | continue
58 |
59 | numfind = re.compile("^\d+")
60 |
61 | if numfind.match(line): # this line is distances
62 | dist = line.split()
63 | for d in dist:
64 | G.add_edge(city, cities[i], weight=int(d))
65 | i = i + 1
66 | else: # this line is a city, position, population
67 | i = 1
68 | (city, coordpop) = line.split("[")
69 | cities.insert(0, city)
70 | (coord, pop) = coordpop.split("]")
71 | (y, x) = coord.split(",")
72 |
73 | G.add_node(city)
74 | # assign position - flip x axis for matplotlib, shift origin
75 | G.position[city] = (-int(x) + 7500, int(y) - 3000)
76 | G.population[city] = float(pop) / 1000.0
77 | return G
78 |
79 |
80 | if __name__ == '__main__':
81 |
82 | G = miles_graph()
83 |
84 | print("Loaded miles_dat.txt containing 128 cities.")
85 | print("digraph has %d nodes with %d edges"
86 | % (nx.number_of_nodes(G), nx.number_of_edges(G)))
87 |
88 | # make new graph of cites, edge if less then 300 miles between them
89 | H = nx.Graph()
90 | for v in G:
91 | H.add_node(v)
92 | for (u, v, d) in G.edges(data=True):
93 | if d['weight'] < 300:
94 | H.add_edge(u, v)
95 |
96 | # draw with matplotlib/pylab
97 | plt.figure(figsize=(8, 8))
98 | # with nodes colored by degree sized by population
99 | node_color = [float(H.degree(v)) for v in H]
100 | nx.draw(H, G.position,
101 | node_size=[G.population[v] for v in H],
102 | node_color=node_color,
103 | with_labels=False)
104 |
105 | # scale the axes equally
106 | plt.xlim(-5000, 500)
107 | plt.ylim(-2000, 3500)
108 |
109 | plt.show()
110 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_labels_and_colors.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | =================
4 | Labels And Colors
5 | =================
6 |
7 | Draw a graph with matplotlib, color by degree.
8 |
9 | You must have matplotlib for this to work.
10 | """
11 | # Author: Aric Hagberg (hagberg@lanl.gov)
12 | import matplotlib.pyplot as plt
13 | import networkx as nx
14 |
15 | G = nx.cubical_graph()
16 | pos = nx.spring_layout(G) # positions for all nodes
17 |
18 | # nodes
19 | nx.draw_networkx_nodes(G, pos,
20 | nodelist=[0, 1, 2, 3],
21 | node_color='r',
22 | node_size=500,
23 | alpha=0.8)
24 | nx.draw_networkx_nodes(G, pos,
25 | nodelist=[4, 5, 6, 7],
26 | node_color='b',
27 | node_size=500,
28 | alpha=0.8)
29 |
30 | # edges
31 | nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
32 | nx.draw_networkx_edges(G, pos,
33 | edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
34 | width=8, alpha=0.5, edge_color='r')
35 | nx.draw_networkx_edges(G, pos,
36 | edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
37 | width=8, alpha=0.5, edge_color='b')
38 |
39 |
40 | # some math labels
41 | labels = {}
42 | labels[0] = r'$a$'
43 | labels[1] = r'$b$'
44 | labels[2] = r'$c$'
45 | labels[3] = r'$d$'
46 | labels[4] = r'$\alpha$'
47 | labels[5] = r'$\beta$'
48 | labels[6] = r'$\gamma$'
49 | labels[7] = r'$\delta$'
50 | nx.draw_networkx_labels(G, pos, labels, font_size=16)
51 |
52 | plt.axis('off')
53 | plt.show()
54 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_lanl_routes.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ===========
4 | Lanl Routes
5 | ===========
6 |
7 | Routes to LANL from 186 sites on the Internet.
8 |
9 | This uses Graphviz for layout so you need PyGraphviz or pydot.
10 |
11 | """
12 | # Author: Aric Hagberg (hagberg@lanl.gov)
13 |
14 | # Copyright (C) 2004-2019
15 | # Aric Hagberg
16 | # Dan Schult
17 | # Pieter Swart
18 | # All rights reserved.
19 | # BSD license.
20 |
21 |
22 | import matplotlib.pyplot as plt
23 | import networkx as nx
24 | try:
25 | import pygraphviz
26 | from networkx.drawing.nx_agraph import graphviz_layout
27 | except ImportError:
28 | try:
29 | import pydot
30 | from networkx.drawing.nx_pydot import graphviz_layout
31 | except ImportError:
32 | raise ImportError("This example needs Graphviz and either "
33 | "PyGraphviz or pydot")
34 |
35 | def lanl_graph():
36 | """ Return the lanl internet view graph from lanl.edges
37 | """
38 | try:
39 | fh = open('lanl_routes.edgelist', 'r')
40 | except IOError:
41 | print("lanl.edges not found")
42 | raise
43 |
44 | G = nx.Graph()
45 |
46 | time = {}
47 | time[0] = 0 # assign 0 to center node
48 | for line in fh.readlines():
49 | (head, tail, rtt) = line.split()
50 | G.add_edge(int(head), int(tail))
51 | time[int(head)] = float(rtt)
52 |
53 | # get largest component and assign ping times to G0time dictionary
54 | Gcc = sorted(nx.connected_components(G), key=len, reverse=True)[0]
55 | G0 = G.subgraph(Gcc)
56 | G0.rtt = {}
57 | for n in G0:
58 | G0.rtt[n] = time[n]
59 |
60 | return G0
61 |
62 |
63 | if __name__ == '__main__':
64 |
65 | G = lanl_graph()
66 |
67 | print("graph has %d nodes with %d edges"
68 | % (nx.number_of_nodes(G), nx.number_of_edges(G)))
69 | print(nx.number_connected_components(G), "connected components")
70 |
71 | plt.figure(figsize=(8, 8))
72 | # use graphviz to find radial layout
73 | pos = graphviz_layout(G, prog="twopi", root=0)
74 | # draw nodes, coloring by rtt ping time
75 | nx.draw(G, pos,
76 | node_color=[G.rtt[v] for v in G],
77 | with_labels=False,
78 | alpha=0.5,
79 | node_size=15)
80 | # adjust the plot limits
81 | xmax = 1.02 * max(xx for xx, yy in pos.values())
82 | ymax = 1.02 * max(yy for xx, yy in pos.values())
83 | plt.xlim(0, xmax)
84 | plt.ylim(0, ymax)
85 | plt.show()
86 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_node_colormap.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | =============
4 | Node Colormap
5 | =============
6 |
7 | Draw a graph with matplotlib, color by degree.
8 | You must have matplotlib for this to work.
9 | """
10 | # Author: Aric Hagberg (hagberg@lanl.gov)
11 |
12 | import matplotlib.pyplot as plt
13 | import networkx as nx
14 |
15 | G = nx.cycle_graph(24)
16 | pos = nx.spring_layout(G, iterations=200)
17 | nx.draw(G, pos, node_color=range(24), node_size=800, cmap=plt.cm.Blues)
18 | plt.show()
19 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_random_geometric_graph.py:
--------------------------------------------------------------------------------
1 | """
2 | ======================
3 | Random Geometric Graph
4 | ======================
5 |
6 | Example
7 | """
8 |
9 | import matplotlib.pyplot as plt
10 | import networkx as nx
11 |
12 | G = nx.random_geometric_graph(200, 0.125)
13 | # position is stored as node attribute data for random_geometric_graph
14 | pos = nx.get_node_attributes(G, 'pos')
15 |
16 | # find node near center (0.5,0.5)
17 | dmin = 1
18 | ncenter = 0
19 | for n in pos:
20 | x, y = pos[n]
21 | d = (x - 0.5)**2 + (y - 0.5)**2
22 | if d < dmin:
23 | ncenter = n
24 | dmin = d
25 |
26 | # color by path length from node near center
27 | p = dict(nx.single_source_shortest_path_length(G, ncenter))
28 |
29 | plt.figure(figsize=(8, 8))
30 | nx.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4)
31 | nx.draw_networkx_nodes(G, pos, nodelist=list(p.keys()),
32 | node_size=80,
33 | node_color=list(p.values()),
34 | cmap=plt.cm.Reds_r)
35 |
36 | plt.xlim(-0.05, 1.05)
37 | plt.ylim(-0.05, 1.05)
38 | plt.axis('off')
39 | plt.show()
40 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_sampson.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | =======
4 | Sampson
5 | =======
6 |
7 | Sampson's monastery data.
8 |
9 | Shows how to read data from a zip file and plot multiple frames.
10 |
11 | """
12 | # Author: Aric Hagberg (hagberg@lanl.gov)
13 |
14 | # Copyright (C) 2010-2019 by
15 | # Aric Hagberg
16 | # Dan Schult
17 | # Pieter Swart
18 | # All rights reserved.
19 | # BSD license.
20 |
21 | import zipfile
22 | try:
23 | from cStringIO import StringIO
24 | except ImportError:
25 | from io import BytesIO as StringIO
26 |
27 | import matplotlib.pyplot as plt
28 | import networkx as nx
29 |
30 | zf = zipfile.ZipFile('sampson_data.zip') # zipfile object
31 | e1 = StringIO(zf.read('samplike1.txt')) # read info file
32 | e2 = StringIO(zf.read('samplike2.txt')) # read info file
33 | e3 = StringIO(zf.read('samplike3.txt')) # read info file
34 | G1 = nx.read_edgelist(e1, delimiter='\t')
35 | G2 = nx.read_edgelist(e2, delimiter='\t')
36 | G3 = nx.read_edgelist(e3, delimiter='\t')
37 | pos = nx.spring_layout(G3, iterations=100)
38 | plt.clf()
39 |
40 | plt.subplot(221)
41 | plt.title('samplike1')
42 | nx.draw(G1, pos, node_size=50, with_labels=False)
43 | plt.subplot(222)
44 | plt.title('samplike2')
45 | nx.draw(G2, pos, node_size=50, with_labels=False)
46 | plt.subplot(223)
47 | plt.title('samplike3')
48 | nx.draw(G3, pos, node_size=50, with_labels=False)
49 | plt.subplot(224)
50 | plt.title('samplike1,2,3')
51 | nx.draw(G3, pos, edgelist=list(G3.edges()), node_size=50, with_labels=False)
52 | nx.draw_networkx_edges(G1, pos, alpha=0.25)
53 | nx.draw_networkx_edges(G2, pos, alpha=0.25)
54 | plt.show()
55 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_simple_path.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ===========
4 | Simple Path
5 | ===========
6 |
7 | Draw a graph with matplotlib.
8 | """
9 | import matplotlib.pyplot as plt
10 | import networkx as nx
11 |
12 | G = nx.path_graph(8)
13 | nx.draw(G)
14 | plt.show()
15 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_spectral_grid.py:
--------------------------------------------------------------------------------
1 | """
2 | ==================
3 | Spectral Embedding
4 | ==================
5 |
6 | The spectral layout positions the nodes of the graph based on the
7 | eigenvectors of the graph Laplacian $L = D - A$, where $A$ is the
8 | adjacency matrix and $D$ is the degree matrix of the graph.
9 | By default, the spectral layout will embed the graph in two
10 | dimensions (you can embed your graph in other dimensions using the
11 | ``dim`` argument to either :func:`~drawing.nx_pylab.draw_spectral` or
12 | :func:`~drawing.layout.spectral_layout`).
13 |
14 | When the edges of the graph represent similarity between the incident
15 | nodes, the spectral embedding will place highly similar nodes closer
16 | to one another than nodes which are less similar.
17 |
18 | This is particularly striking when you spectrally embed a grid
19 | graph. In the full grid graph, the nodes in the center of the
20 | graph are pulled apart more than nodes on the periphery.
21 | As you remove internal nodes, this effect increases.
22 | """
23 |
24 | import matplotlib.pyplot as plt
25 | import networkx as nx
26 |
27 |
28 | options = {
29 | 'node_color': 'C0',
30 | 'node_size': 100,
31 | }
32 |
33 | G = nx.grid_2d_graph(6, 6)
34 | plt.subplot(332)
35 | nx.draw_spectral(G, **options)
36 |
37 | G.remove_edge((2, 2), (2, 3))
38 | plt.subplot(334)
39 | nx.draw_spectral(G, **options)
40 |
41 | G.remove_edge((3, 2), (3, 3))
42 | plt.subplot(335)
43 | nx.draw_spectral(G, **options)
44 |
45 | G.remove_edge((2, 2), (3, 2))
46 | plt.subplot(336)
47 | nx.draw_spectral(G, **options)
48 |
49 | G.remove_edge((2, 3), (3, 3))
50 | plt.subplot(337)
51 | nx.draw_spectral(G, **options)
52 |
53 | G.remove_edge((1, 2), (1, 3))
54 | plt.subplot(338)
55 | nx.draw_spectral(G, **options)
56 |
57 | G.remove_edge((4, 2), (4, 3))
58 | plt.subplot(339)
59 | nx.draw_spectral(G, **options)
60 |
61 | plt.show()
62 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_unix_email.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ==========
4 | Unix Email
5 | ==========
6 |
7 | Create a directed graph, allowing multiple edges and self loops, from
8 | a unix mailbox. The nodes are email addresses with links
9 | that point from the sender to the receivers. The edge data
10 | is a Python email.Message object which contains all of
11 | the email message data.
12 |
13 | This example shows the power of `DiGraph` to hold edge data
14 | of arbitrary Python objects (in this case a list of email messages).
15 |
16 | The sample unix email mailbox called "unix_email.mbox" may be found here:
17 | https://raw.githubusercontent.com/networkx/networkx/master/examples/drawing/unix_email.mbox
18 |
19 | """
20 | # Author: Aric Hagberg (hagberg@lanl.gov)
21 |
22 | # Copyright (C) 2005-2019 by
23 | # Aric Hagberg
24 | # Dan Schult
25 | # Pieter Swart
26 | # All rights reserved.
27 | # BSD license.
28 |
29 | from email.utils import getaddresses, parseaddr
30 | import mailbox
31 | import sys
32 |
33 | import matplotlib.pyplot as plt
34 | import networkx as nx
35 |
36 | # unix mailbox recipe
37 | # see https://docs.python.org/3/library/mailbox.html
38 |
39 | def mbox_graph():
40 | mbox = mailbox.mbox("unix_email.mbox") # parse unix mailbox
41 |
42 | G = nx.MultiDiGraph() # create empty graph
43 |
44 | # parse each messages and build graph
45 | for msg in mbox: # msg is python email.Message.Message object
46 | (source_name, source_addr) = parseaddr(msg['From']) # sender
47 | # get all recipients
48 | # see https://docs.python.org/3/library/email.html
49 | tos = msg.get_all('to', [])
50 | ccs = msg.get_all('cc', [])
51 | resent_tos = msg.get_all('resent-to', [])
52 | resent_ccs = msg.get_all('resent-cc', [])
53 | all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)
54 | # now add the edges for this mail message
55 | for (target_name, target_addr) in all_recipients:
56 | G.add_edge(source_addr, target_addr, message=msg)
57 |
58 | return G
59 |
60 |
61 | if __name__ == '__main__':
62 |
63 | G = mbox_graph()
64 |
65 | # print edges with message subject
66 | for (u, v, d) in G.edges(data=True):
67 | print("From: %s To: %s Subject: %s" % (u, v, d['message']["Subject"]))
68 |
69 | pos = nx.spring_layout(G, iterations=10)
70 | nx.draw(G, pos, node_size=0, alpha=0.4, edge_color='r', font_size=16, with_labels=True)
71 | plt.show()
72 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/plot_weighted_graph.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ==============
4 | Weighted Graph
5 | ==============
6 |
7 | An example using Graph as a weighted network.
8 | """
9 | # Author: Aric Hagberg (hagberg@lanl.gov)
10 | import matplotlib.pyplot as plt
11 | import networkx as nx
12 |
13 | G = nx.Graph()
14 |
15 | G.add_edge('a', 'b', weight=0.6)
16 | G.add_edge('a', 'c', weight=0.2)
17 | G.add_edge('c', 'd', weight=0.1)
18 | G.add_edge('c', 'e', weight=0.7)
19 | G.add_edge('c', 'f', weight=0.9)
20 | G.add_edge('a', 'd', weight=0.3)
21 |
22 | elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 0.5]
23 | esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] <= 0.5]
24 |
25 | pos = nx.spring_layout(G) # positions for all nodes
26 |
27 | # nodes
28 | nx.draw_networkx_nodes(G, pos, node_size=700)
29 |
30 | # edges
31 | nx.draw_networkx_edges(G, pos, edgelist=elarge,
32 | width=6)
33 | nx.draw_networkx_edges(G, pos, edgelist=esmall,
34 | width=6, alpha=0.5, edge_color='b', style='dashed')
35 |
36 | # labels
37 | nx.draw_networkx_labels(G, pos, font_size=20, font_family='sans-serif')
38 |
39 | plt.axis('off')
40 | plt.show()
41 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/drawing/unix_email.mbox:
--------------------------------------------------------------------------------
1 | From alice@edu Thu Jun 16 16:12:12 2005
2 | From: Alice
3 | Subject: NetworkX
4 | Date: Thu, 16 Jun 2005 16:12:13 -0700
5 | To: Bob
6 | Status: RO
7 | Content-Length: 86
8 | Lines: 5
9 |
10 | Bob, check out the new networkx release - you and
11 | Carol might really like it.
12 |
13 | Alice
14 |
15 |
16 | From bob@gov Thu Jun 16 18:13:12 2005
17 | Return-Path:
18 | Subject: Re: NetworkX
19 | From: Bob
20 | To: Alice
21 | Content-Type: text/plain
22 | Date: Thu, 16 Jun 2005 18:13:12 -0700
23 | Status: RO
24 | Content-Length: 26
25 | Lines: 4
26 |
27 | Thanks for the tip.
28 |
29 | Bob
30 |
31 |
32 | From ted@com Thu Jul 28 09:53:31 2005
33 | Return-Path:
34 | Subject: Graph package in Python?
35 | From: Ted
36 | To: Bob
37 | Content-Type: text/plain
38 | Date: Thu, 28 Jul 2005 09:47:03 -0700
39 | Status: RO
40 | Content-Length: 90
41 | Lines: 3
42 |
43 | Hey Ted - I'm looking for a Python package for
44 | graphs and networks. Do you know of any?
45 |
46 |
47 | From bob@gov Thu Jul 28 09:59:31 2005
48 | Return-Path:
49 | Subject: Re: Graph package in Python?
50 | From: Bob
51 | To: Ted
52 | Content-Type: text/plain
53 | Date: Thu, 28 Jul 2005 09:59:03 -0700
54 | Status: RO
55 | Content-Length: 180
56 | Lines: 9
57 |
58 |
59 | Check out the NetworkX package - Alice sent me the tip!
60 |
61 | Bob
62 |
63 | >> bob@gov scrawled:
64 | >> Hey Ted - I'm looking for a Python package for
65 | >> graphs and networks. Do you know of any?
66 |
67 |
68 | From ted@com Thu Jul 28 15:53:31 2005
69 | Return-Path:
70 | Subject: get together for lunch to discuss Networks?
71 | From: Ted
72 | To: Bob , Carol , Alice
73 | Content-Type: text/plain
74 | Date: Thu, 28 Jul 2005 15:47:03 -0700
75 | Status: RO
76 | Content-Length: 139
77 | Lines: 5
78 |
79 | Hey everyrone! Want to meet at that restaurant on the
80 | island in Konigsburg tonight? Bring your laptops
81 | and we can install NetworkX.
82 |
83 | Ted
84 |
85 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/graph/README.txt:
--------------------------------------------------------------------------------
1 | Graph
2 | -----
3 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/graph/dot_atlas.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ======
4 | Atlas2
5 | ======
6 |
7 | Write first 20 graphs from the graph atlas as graphviz dot files
8 | Gn.dot where n=0,19.
9 | """
10 | # Author: Aric Hagberg (hagberg@lanl.gov)
11 | # Date: 2005-05-19 14:23:02 -0600 (Thu, 19 May 2005)
12 |
13 | # Copyright (C) 2006-2019 by
14 | # Aric Hagberg
15 | # Dan Schult
16 | # Pieter Swart
17 | # All rights reserved.
18 | # BSD license.
19 |
20 | import networkx as nx
21 | from networkx.generators.atlas import graph_atlas_g
22 |
23 | atlas = graph_atlas_g()[0:20]
24 |
25 | for G in atlas:
26 | print("graph %s has %d nodes with %d edges"
27 | % (G.name, nx.number_of_nodes(G), nx.number_of_edges(G)))
28 | A = nx.nx_agraph.to_agraph(G)
29 | A.graph_attr['label'] = G.name
30 | # set default node attributes
31 | A.node_attr['color'] = 'red'
32 | A.node_attr['style'] = 'filled'
33 | A.node_attr['shape'] = 'circle'
34 | A.write(G.name + '.dot')
35 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/graph/plot_degree_sequence.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ===============
4 | Degree Sequence
5 | ===============
6 |
7 | Random graph from given degree sequence.
8 | """
9 | # Author: Aric Hagberg (hagberg@lanl.gov)
10 | # Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004)
11 | # Revision: 503
12 |
13 | # Copyright (C) 2004-2019 by
14 | # Aric Hagberg
15 | # Dan Schult
16 | # Pieter Swart
17 | # All rights reserved.
18 | # BSD license.
19 |
20 | import matplotlib.pyplot as plt
21 | from networkx import nx
22 |
23 | z = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
24 | print(nx.is_graphical(z))
25 |
26 | print("Configuration model")
27 | G = nx.configuration_model(z) # configuration model
28 | degree_sequence = [d for n, d in G.degree()] # degree sequence
29 | print("Degree sequence %s" % degree_sequence)
30 | print("Degree histogram")
31 | hist = {}
32 | for d in degree_sequence:
33 | if d in hist:
34 | hist[d] += 1
35 | else:
36 | hist[d] = 1
37 | print("degree #nodes")
38 | for d in hist:
39 | print('%d %d' % (d, hist[d]))
40 |
41 | nx.draw(G)
42 | plt.show()
43 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/graph/plot_erdos_renyi.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #!/usr/bin/env python
3 | """
4 | ===========
5 | Erdos Renyi
6 | ===========
7 |
8 | Create an G{n,m} random graph with n nodes and m edges
9 | and report some properties.
10 |
11 | This graph is sometimes called the Erdős-Rényi graph
12 | but is different from G{n,p} or binomial_graph which is also
13 | sometimes called the Erdős-Rényi graph.
14 | """
15 | # Author: Aric Hagberg (hagberg@lanl.gov)
16 |
17 | # Copyright (C) 2004-2019 by
18 | # Aric Hagberg
19 | # Dan Schult
20 | # Pieter Swart
21 | # All rights reserved.
22 | # BSD license.
23 |
24 | import matplotlib.pyplot as plt
25 | from networkx import nx
26 |
27 | n = 10 # 10 nodes
28 | m = 20 # 20 edges
29 |
30 | G = nx.gnm_random_graph(n, m)
31 |
32 | # some properties
33 | print("node degree clustering")
34 | for v in nx.nodes(G):
35 | print('%s %d %f' % (v, nx.degree(G, v), nx.clustering(G, v)))
36 |
37 | # print the adjacency list
38 | for line in nx.generate_adjlist(G):
39 | print(line)
40 |
41 | nx.draw(G)
42 | plt.show()
43 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/graph/plot_expected_degree_sequence.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ========================
4 | Expected Degree Sequence
5 | ========================
6 |
7 | Random graph from given degree sequence.
8 | """
9 | # Author: Aric Hagberg (hagberg@lanl.gov)
10 |
11 | # Copyright (C) 2006-2019 by
12 | # Aric Hagberg
13 | # Dan Schult
14 | # Pieter Swart
15 | # All rights reserved.
16 | # BSD license.
17 |
18 | import networkx as nx
19 | from networkx.generators.degree_seq import expected_degree_graph
20 |
21 | # make a random graph of 500 nodes with expected degrees of 50
22 | n = 500 # n nodes
23 | p = 0.1
24 | w = [p * n for i in range(n)] # w = p*n for all nodes
25 | G = expected_degree_graph(w) # configuration model
26 | print("Degree histogram")
27 | print("degree (#nodes) ****")
28 | dh = nx.degree_histogram(G)
29 | for i, d in enumerate(dh):
30 | print("%2s (%2s) %s" % (i, d, '*'*d))
31 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/graph/plot_football.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ========
4 | Football
5 | ========
6 |
7 | Load football network in GML format and compute some network statistcs.
8 |
9 | Shows how to download GML graph in a zipped file, unpack it, and load
10 | into a NetworkX graph.
11 |
12 | Requires Internet connection to download the URL
13 | http://www-personal.umich.edu/~mejn/netdata/football.zip
14 | """
15 | # Author: Aric Hagberg (hagberg@lanl.gov)
16 |
17 | # Copyright (C) 2007-2019 by
18 | # Aric Hagberg
19 | # Dan Schult
20 | # Pieter Swart
21 | # All rights reserved.
22 | # BSD license.
23 |
24 | try: # Python 3.x
25 | import urllib.request as urllib
26 | except ImportError: # Python 2.x
27 | import urllib
28 | import io
29 | import zipfile
30 |
31 | import matplotlib.pyplot as plt
32 | import networkx as nx
33 |
34 | url = "http://www-personal.umich.edu/~mejn/netdata/football.zip"
35 |
36 | sock = urllib.urlopen(url) # open URL
37 | s = io.BytesIO(sock.read()) # read into BytesIO "file"
38 | sock.close()
39 |
40 | zf = zipfile.ZipFile(s) # zipfile object
41 | txt = zf.read('football.txt').decode() # read info file
42 | gml = zf.read('football.gml').decode() # read gml data
43 | # throw away bogus first line with # from mejn files
44 | gml = gml.split('\n')[1:]
45 | G = nx.parse_gml(gml) # parse gml data
46 |
47 | print(txt)
48 | # print degree for each team - number of games
49 | for n, d in G.degree():
50 | print('%s %d' % (n, d))
51 |
52 | options = {
53 | 'node_color': 'black',
54 | 'node_size': 50,
55 | 'line_color': 'grey',
56 | 'linewidths': 0,
57 | 'width': 0.1,
58 | }
59 | nx.draw(G, **options)
60 | plt.show()
61 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/graph/plot_karate_club.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ===========
4 | Karate Club
5 | ===========
6 |
7 | Zachary's Karate Club graph
8 |
9 | Data file from:
10 | http://vlado.fmf.uni-lj.si/pub/networks/data/Ucinet/UciData.htm
11 |
12 | Reference:
13 | Zachary W. (1977).
14 | An information flow model for conflict and fission in small groups.
15 | Journal of Anthropological Research, 33, 452-473.
16 | """
17 |
18 | import matplotlib.pyplot as plt
19 | import networkx as nx
20 |
21 | G = nx.karate_club_graph()
22 | print("Node Degree")
23 | for v in G:
24 | print('%s %s' % (v, G.degree(v)))
25 |
26 | nx.draw_circular(G, with_labels=True)
27 | plt.show()
28 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/graph/plot_napoleon_russian_campaign.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | =========================
4 | Napoleon Russian Campaign
5 | =========================
6 |
7 | Minard's data from Napoleon's 1812-1813 Russian Campaign.
8 | http://www.math.yorku.ca/SCS/Gallery/minard/minard.txt
9 |
10 | """
11 | # Author: Aric Hagberg (hagberg@lanl.gov)
12 |
13 | # Copyright (C) 2006-2019 by
14 | # Aric Hagberg
15 | # Dan Schult
16 | # Pieter Swart
17 | # All rights reserved.
18 | # BSD license.
19 |
20 | import matplotlib.pyplot as plt
21 | import networkx as nx
22 |
23 |
24 | def minard_graph():
25 | data1 = """\
26 | 24.0,54.9,340000,A,1
27 | 24.5,55.0,340000,A,1
28 | 25.5,54.5,340000,A,1
29 | 26.0,54.7,320000,A,1
30 | 27.0,54.8,300000,A,1
31 | 28.0,54.9,280000,A,1
32 | 28.5,55.0,240000,A,1
33 | 29.0,55.1,210000,A,1
34 | 30.0,55.2,180000,A,1
35 | 30.3,55.3,175000,A,1
36 | 32.0,54.8,145000,A,1
37 | 33.2,54.9,140000,A,1
38 | 34.4,55.5,127100,A,1
39 | 35.5,55.4,100000,A,1
40 | 36.0,55.5,100000,A,1
41 | 37.6,55.8,100000,A,1
42 | 37.7,55.7,100000,R,1
43 | 37.5,55.7,98000,R,1
44 | 37.0,55.0,97000,R,1
45 | 36.8,55.0,96000,R,1
46 | 35.4,55.3,87000,R,1
47 | 34.3,55.2,55000,R,1
48 | 33.3,54.8,37000,R,1
49 | 32.0,54.6,24000,R,1
50 | 30.4,54.4,20000,R,1
51 | 29.2,54.3,20000,R,1
52 | 28.5,54.2,20000,R,1
53 | 28.3,54.3,20000,R,1
54 | 27.5,54.5,20000,R,1
55 | 26.8,54.3,12000,R,1
56 | 26.4,54.4,14000,R,1
57 | 25.0,54.4,8000,R,1
58 | 24.4,54.4,4000,R,1
59 | 24.2,54.4,4000,R,1
60 | 24.1,54.4,4000,R,1"""
61 | data2 = """\
62 | 24.0,55.1,60000,A,2
63 | 24.5,55.2,60000,A,2
64 | 25.5,54.7,60000,A,2
65 | 26.6,55.7,40000,A,2
66 | 27.4,55.6,33000,A,2
67 | 28.7,55.5,33000,R,2
68 | 29.2,54.2,30000,R,2
69 | 28.5,54.1,30000,R,2
70 | 28.3,54.2,28000,R,2"""
71 | data3 = """\
72 | 24.0,55.2,22000,A,3
73 | 24.5,55.3,22000,A,3
74 | 24.6,55.8,6000,A,3
75 | 24.6,55.8,6000,R,3
76 | 24.2,54.4,6000,R,3
77 | 24.1,54.4,6000,R,3"""
78 | cities = """\
79 | 24.0,55.0,Kowno
80 | 25.3,54.7,Wilna
81 | 26.4,54.4,Smorgoni
82 | 26.8,54.3,Moiodexno
83 | 27.7,55.2,Gloubokoe
84 | 27.6,53.9,Minsk
85 | 28.5,54.3,Studienska
86 | 28.7,55.5,Polotzk
87 | 29.2,54.4,Bobr
88 | 30.2,55.3,Witebsk
89 | 30.4,54.5,Orscha
90 | 30.4,53.9,Mohilow
91 | 32.0,54.8,Smolensk
92 | 33.2,54.9,Dorogobouge
93 | 34.3,55.2,Wixma
94 | 34.4,55.5,Chjat
95 | 36.0,55.5,Mojaisk
96 | 37.6,55.8,Moscou
97 | 36.6,55.3,Tarantino
98 | 36.5,55.0,Malo-Jarosewii"""
99 |
100 | c = {}
101 | for line in cities.split('\n'):
102 | x, y, name = line.split(',')
103 | c[name] = (float(x), float(y))
104 |
105 | g = []
106 |
107 | for data in [data1, data2, data3]:
108 | G = nx.Graph()
109 | i = 0
110 | G.pos = {} # location
111 | G.pop = {} # size
112 | last = None
113 | for line in data.split('\n'):
114 | x, y, p, r, n = line.split(',')
115 | G.pos[i] = (float(x), float(y))
116 | G.pop[i] = int(p)
117 | if last is None:
118 | last = i
119 | else:
120 | G.add_edge(i, last, **{r: int(n)})
121 | last = i
122 | i = i + 1
123 | g.append(G)
124 |
125 | return g, c
126 |
127 |
128 | if __name__ == "__main__":
129 |
130 | (g, city) = minard_graph()
131 |
132 | plt.figure(1, figsize=(11, 5))
133 | plt.clf()
134 | colors = ['b', 'g', 'r']
135 | for G in g:
136 | c = colors.pop(0)
137 | node_size = [int(G.pop[n] / 300.0) for n in G]
138 | nx.draw_networkx_edges(G, G.pos, edge_color=c, width=4, alpha=0.5)
139 | nx.draw_networkx_nodes(G, G.pos, node_size=node_size, node_color=c, alpha=0.5)
140 | nx.draw_networkx_nodes(G, G.pos, node_size=5, node_color='k')
141 |
142 | for c in city:
143 | x, y = city[c]
144 | plt.text(x, y + 0.1, c)
145 | plt.show()
146 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/graph/plot_roget.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | =====
4 | Roget
5 | =====
6 |
7 | Build a directed graph of 1022 categories and
8 | 5075 cross-references as defined in the 1879 version of Roget's Thesaurus
9 | contained in the datafile roget_dat.txt. This example is described in
10 | Section 1.2 in Knuth's book (see [1]_ and [2]_).
11 |
12 | Note that one of the 5075 cross references is a self loop yet
13 | it is included in the graph built here because
14 | the standard networkx `DiGraph` class allows self loops.
15 | (cf. 400pungency:400 401 403 405).
16 |
17 | References
18 | ----------
19 |
20 | .. [1] Donald E. Knuth,
21 | "The Stanford GraphBase: A Platform for Combinatorial Computing",
22 | ACM Press, New York, 1993.
23 | .. [2] http://www-cs-faculty.stanford.edu/~knuth/sgb.html
24 | """
25 |
26 | # Authors: Brendt Wohlberg, Aric Hagberg (hagberg@lanl.gov)
27 | # Date: 2005-04-01 07:56:22 -0700 (Fri, 01 Apr 2005)
28 |
29 | # Copyright (C) 2004-2019 by
30 | # Aric Hagberg
31 | # Dan Schult
32 | # Pieter Swart
33 | # All rights reserved.
34 | # BSD license.
35 |
36 | import gzip
37 | import re
38 | import sys
39 |
40 | import matplotlib.pyplot as plt
41 | from networkx import nx
42 |
43 | def roget_graph():
44 | """ Return the thesaurus graph from the roget.dat example in
45 | the Stanford Graph Base.
46 | """
47 | # open file roget_dat.txt.gz (or roget_dat.txt)
48 | fh = gzip.open('roget_dat.txt.gz', 'r')
49 |
50 | G = nx.DiGraph()
51 |
52 | for line in fh.readlines():
53 | line = line.decode()
54 | if line.startswith("*"): # skip comments
55 | continue
56 | if line.startswith(" "): # this is a continuation line, append
57 | line = oldline + line
58 | if line.endswith("\\\n"): # continuation line, buffer, goto next
59 | oldline = line.strip("\\\n")
60 | continue
61 |
62 | (headname, tails) = line.split(":")
63 |
64 | # head
65 | numfind = re.compile("^\d+") # re to find the number of this word
66 | head = numfind.findall(headname)[0] # get the number
67 |
68 | G.add_node(head)
69 |
70 | for tail in tails.split():
71 | if head == tail:
72 | print("skipping self loop", head, tail, file=sys.stderr)
73 | G.add_edge(head, tail)
74 |
75 | return G
76 |
77 |
78 | if __name__ == '__main__':
79 | G = roget_graph()
80 | print("Loaded roget_dat.txt containing 1022 categories.")
81 | print("digraph has %d nodes with %d edges"
82 | % (nx.number_of_nodes(G), nx.number_of_edges(G)))
83 | UG = G.to_undirected()
84 | print(nx.number_connected_components(UG), "connected components")
85 |
86 | options = {
87 | 'node_color': 'black',
88 | 'node_size': 1,
89 | 'line_color': 'grey',
90 | 'linewidths': 0,
91 | 'width': 0.1,
92 | }
93 | nx.draw_circular(UG, **options)
94 | plt.show()
95 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/graph/plot_words.py:
--------------------------------------------------------------------------------
1 | """
2 | =====
3 | Words
4 | =====
5 |
6 | Words/Ladder Graph
7 | ------------------
8 | Generate an undirected graph over the 5757 5-letter words in the
9 | datafile `words_dat.txt.gz`. Two words are connected by an edge
10 | if they differ in one letter, resulting in 14,135 edges. This example
11 | is described in Section 1.1 in Knuth's book (see [1]_ and [2]_).
12 |
13 | References
14 | ----------
15 | .. [1] Donald E. Knuth,
16 | "The Stanford GraphBase: A Platform for Combinatorial Computing",
17 | ACM Press, New York, 1993.
18 | .. [2] http://www-cs-faculty.stanford.edu/~knuth/sgb.html
19 | """
20 | # Authors: Aric Hagberg (hagberg@lanl.gov),
21 | # Brendt Wohlberg,
22 | # hughdbrown@yahoo.com
23 |
24 | # Copyright (C) 2004-2019 by
25 | # Aric Hagberg
26 | # Dan Schult
27 | # Pieter Swart
28 | # All rights reserved.
29 | # BSD license.
30 |
31 | import gzip
32 | from string import ascii_lowercase as lowercase
33 |
34 | import networkx as nx
35 |
36 | #-------------------------------------------------------------------
37 | # The Words/Ladder graph of Section 1.1
38 | #-------------------------------------------------------------------
39 |
40 |
41 | def generate_graph(words):
42 | G = nx.Graph(name="words")
43 | lookup = dict((c, lowercase.index(c)) for c in lowercase)
44 |
45 | def edit_distance_one(word):
46 | for i in range(len(word)):
47 | left, c, right = word[0:i], word[i], word[i + 1:]
48 | j = lookup[c] # lowercase.index(c)
49 | for cc in lowercase[j + 1:]:
50 | yield left + cc + right
51 | candgen = ((word, cand) for word in sorted(words)
52 | for cand in edit_distance_one(word) if cand in words)
53 | G.add_nodes_from(words)
54 | for word, cand in candgen:
55 | G.add_edge(word, cand)
56 | return G
57 |
58 |
59 | def words_graph():
60 | """Return the words example graph from the Stanford GraphBase"""
61 | fh = gzip.open('words_dat.txt.gz', 'r')
62 | words = set()
63 | for line in fh.readlines():
64 | line = line.decode()
65 | if line.startswith('*'):
66 | continue
67 | w = str(line[0:5])
68 | words.add(w)
69 | return generate_graph(words)
70 |
71 |
72 | if __name__ == '__main__':
73 | G = words_graph()
74 | print("Loaded words_dat.txt containing 5757 five-letter English words.")
75 | print("Two words are connected if they differ in one letter.")
76 | print("Graph has %d nodes with %d edges"
77 | % (nx.number_of_nodes(G), nx.number_of_edges(G)))
78 | print("%d connected components" % nx.number_connected_components(G))
79 |
80 | for (source, target) in [('chaos', 'order'),
81 | ('nodes', 'graph'),
82 | ('pound', 'marks')]:
83 | print("Shortest path between %s and %s is" % (source, target))
84 | try:
85 | sp = nx.shortest_path(G, source, target)
86 | for n in sp:
87 | print(n)
88 | except nx.NetworkXNoPath:
89 | print("None")
90 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/graph/roget_dat.txt.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/doc/networkx-2.4/examples/graph/roget_dat.txt.gz
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/graph/words_dat.txt.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/doc/networkx-2.4/examples/graph/words_dat.txt.gz
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/javascript/README.txt:
--------------------------------------------------------------------------------
1 | Javascript
2 | ----------
3 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/javascript/force.py:
--------------------------------------------------------------------------------
1 | """
2 | ==========
3 | Javascript
4 | ==========
5 |
6 | Example of writing JSON format graph data and using the D3 Javascript library to produce an HTML/Javascript drawing.
7 | """
8 | # Author: Aric Hagberg
9 |
10 | # Copyright (C) 2011-2019 by
11 | # Aric Hagberg
12 | # Dan Schult
13 | # Pieter Swart
14 | # All rights reserved.
15 | # BSD license.
16 | import json
17 |
18 | import flask
19 | import networkx as nx
20 | from networkx.readwrite import json_graph
21 |
22 | G = nx.barbell_graph(6, 3)
23 | # this d3 example uses the name attribute for the mouse-hover value,
24 | # so add a name to each node
25 | for n in G:
26 | G.nodes[n]['name'] = n
27 | # write json formatted data
28 | d = json_graph.node_link_data(G) # node-link format to serialize
29 | # write json
30 | json.dump(d, open('force/force.json', 'w'))
31 | print('Wrote node-link JSON data to force/force.json')
32 |
33 | # Serve the file over http to allow for cross origin requests
34 | app = flask.Flask(__name__, static_folder="force")
35 |
36 | @app.route('/')
37 | def static_proxy():
38 | return app.send_static_file('force.html')
39 |
40 | print('\nGo to http://localhost:8000 to see the example\n')
41 | app.run(port=8000)
42 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/javascript/force/README.txt:
--------------------------------------------------------------------------------
1 | Modified from the example at of D3
2 | http://mbostock.github.com/d3/ex/force.html
3 |
4 | Run the file force.py to generate the force.json data file needed for this to work.
5 |
6 | Then copy all of the files in this directory to a webserver and load force.html.
7 |
8 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/javascript/force/force.css:
--------------------------------------------------------------------------------
1 | .nodes circle {
2 | cursor: pointer;
3 | fill: #ff3399;
4 | stroke: #000;
5 | stroke-width: .5px;
6 | }
7 |
8 | .links line {
9 | fill: none;
10 | stroke: #9ecae1;
11 | stroke-width: .5px;
12 | }
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/javascript/force/force.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Force-Directed Layout
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/javascript/force/force.js:
--------------------------------------------------------------------------------
1 | // This is adapted from https://bl.ocks.org/mbostock/2675ff61ea5e063ede2b5d63c08020c7
2 |
3 | var svg = d3.select("svg"),
4 | width = +svg.attr("width"),
5 | height = +svg.attr("height");
6 |
7 | var simulation = d3.forceSimulation()
8 | .force("link", d3.forceLink().id(function (d) {
9 | return d.id;
10 | }))
11 | .force("charge", d3.forceManyBody())
12 | .force("center", d3.forceCenter(width / 2, height / 2));
13 |
14 | d3.json("force/force.json", function (error, graph) {
15 | if (error) throw error;
16 |
17 | var link = svg.append("g")
18 | .attr("class", "links")
19 | .selectAll("line")
20 | .data(graph.links)
21 | .enter().append("line");
22 |
23 | var node = svg.append("g")
24 | .attr("class", "nodes")
25 | .selectAll("circle")
26 | .data(graph.nodes)
27 | .enter().append("circle")
28 | .attr("r", 5)
29 | .call(d3.drag()
30 | .on("start", dragstarted)
31 | .on("drag", dragged)
32 | .on("end", dragended));
33 |
34 | node.append("title")
35 | .text(function (d) {
36 | return d.id;
37 | });
38 |
39 | simulation
40 | .nodes(graph.nodes)
41 | .on("tick", ticked);
42 |
43 | simulation.force("link")
44 | .links(graph.links);
45 |
46 | function ticked() {
47 | link
48 | .attr("x1", function (d) {
49 | return d.source.x;
50 | })
51 | .attr("y1", function (d) {
52 | return d.source.y;
53 | })
54 | .attr("x2", function (d) {
55 | return d.target.x;
56 | })
57 | .attr("y2", function (d) {
58 | return d.target.y;
59 | });
60 |
61 | node
62 | .attr("cx", function (d) {
63 | return d.x;
64 | })
65 | .attr("cy", function (d) {
66 | return d.y;
67 | });
68 | }
69 | });
70 |
71 | function dragstarted(d) {
72 | if (!d3.event.active) simulation.alphaTarget(0.3).restart();
73 | d.fx = d.x;
74 | d.fy = d.y;
75 | }
76 |
77 | function dragged(d) {
78 | d.fx = d3.event.x;
79 | d.fy = d3.event.y;
80 | }
81 |
82 | function dragended(d) {
83 | if (!d3.event.active) simulation.alphaTarget(0);
84 | d.fx = null;
85 | d.fy = null;
86 | }
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/jit/README.txt:
--------------------------------------------------------------------------------
1 | JIT
2 | ---
3 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/jit/plot_rgraph.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ======
4 | Rgraph
5 | ======
6 |
7 | An example showing how to use the JavaScript InfoVis Toolkit (JIT)
8 | JSON export
9 |
10 | See the JIT documentation and examples at http://thejit.org
11 |
12 | """
13 | __author__ = """Ollie Glass (ollieglaskovik@gmail.com)"""
14 |
15 | import json
16 |
17 | import matplotlib.pyplot as plt
18 | import networkx as nx
19 | from networkx.readwrite.json_graph import jit_data, jit_graph
20 |
21 | # add some nodes to a graph
22 | G = nx.Graph()
23 |
24 | G.add_node("one", type="normal")
25 | G.add_node("two", type="special")
26 | G.add_node("solo")
27 |
28 | # add edges
29 | G.add_edge("one", "two")
30 | G.add_edge("two", 3, type="extra special")
31 |
32 | # convert to JIT JSON
33 | jit_json = jit_data(G, indent=4)
34 | print(jit_json)
35 |
36 | X = jit_graph(json.loads(jit_json))
37 | print("Nodes: %s" % list(X.nodes(data=True)))
38 | print("Edges: %s" % list(X.edges(data=True)))
39 |
40 | nx.draw(G, with_labels=True)
41 | plt.show()
42 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/pygraphviz/README.txt:
--------------------------------------------------------------------------------
1 | Pygraphviz
2 | ----------
3 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/pygraphviz/plot_pygraphviz_attributes.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | =====================
4 | Pygraphviz Attributes
5 | =====================
6 |
7 | An example showing how to use the interface to the pygraphviz
8 | AGraph class to convert to and from graphviz.
9 |
10 | Also see the pygraphviz documentation and examples at
11 | http://pygraphviz.github.io/
12 | """
13 | # Author: Aric Hagberg (hagberg@lanl.gov)
14 |
15 | # Copyright (C) 2006-2019 by
16 | # Aric Hagberg
17 | # Dan Schult
18 | # Pieter Swart
19 | # All rights reserved.
20 | # BSD license.
21 |
22 | import networkx as nx
23 |
24 | # networkx graph
25 | G = nx.Graph()
26 | # ad edges with red color
27 | G.add_edge(1, 2, color='red')
28 | G.add_edge(2, 3, color='red')
29 | # add nodes 3 and 4
30 | G.add_node(3)
31 | G.add_node(4)
32 |
33 | # convert to a graphviz agraph
34 | A = nx.nx_agraph.to_agraph(G)
35 |
36 | # write to dot file
37 | A.write('k5_attributes.dot')
38 |
39 | # convert back to networkx Graph with attributes on edges and
40 | # default attributes as dictionary data
41 | X = nx.nx_agraph.from_agraph(A)
42 | print("edges")
43 | print(list(X.edges(data=True)))
44 | print("default graph attributes")
45 | print(X.graph)
46 | print("node node attributes")
47 | print(X.nodes.data(True))
48 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/pygraphviz/plot_pygraphviz_draw.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | ===============
4 | Pygraphviz Draw
5 | ===============
6 |
7 | An example showing how to use the interface to the pygraphviz
8 | AGraph class to draw a graph.
9 |
10 | Also see the pygraphviz documentation and examples at
11 | http://pygraphviz.github.io/
12 | """
13 | # Author: Aric Hagberg (hagberg@lanl.gov)
14 |
15 | # Copyright (C) 2006-2019 by
16 | # Aric Hagberg
17 | # Dan Schult
18 | # Pieter Swart
19 | # All rights reserved.
20 | # BSD license.
21 |
22 | import networkx as nx
23 |
24 | # plain graph
25 |
26 | G = nx.complete_graph(5) # start with K5 in networkx
27 | A = nx.nx_agraph.to_agraph(G) # convert to a graphviz graph
28 | A.layout() # neato layout
29 | A.draw("k5.ps") # write postscript in k5.ps with neato layout
30 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/pygraphviz/plot_pygraphviz_simple.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | =================
4 | Pygraphviz Simple
5 | =================
6 |
7 | An example showing how to use the interface to the pygraphviz
8 | AGraph class to convert to and from graphviz.
9 |
10 | Also see the pygraphviz documentation and examples at
11 | http://pygraphviz.github.io/
12 | """
13 | # Author: Aric Hagberg (hagberg@lanl.gov)
14 |
15 | # Copyright (C) 2006-2019 by
16 | # Aric Hagberg
17 | # Dan Schult
18 | # Pieter Swart
19 | # All rights reserved.
20 | # BSD license.
21 |
22 | import networkx as nx
23 |
24 | # plain graph
25 |
26 | G = nx.complete_graph(5) # start with K5 in networkx
27 | A = nx.nx_agraph.to_agraph(G) # convert to a graphviz graph
28 | X1 = nx.nx_agraph.from_agraph(A) # convert back to networkx (but as Graph)
29 | X2 = nx.Graph(A) # fancy way to do conversion
30 | G1 = nx.Graph(X1) # now make it a Graph
31 |
32 | A.write('k5.dot') # write to dot file
33 | X3 = nx.nx_agraph.read_dot('k5.dot') # read from dotfile
34 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/pygraphviz/plot_write_dotfile.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | =============
4 | Write Dotfile
5 | =============
6 |
7 |
8 | Write a dot file from a networkx graph for further processing with graphviz.
9 |
10 | You need to have either pygraphviz or pydot for this example.
11 |
12 | See https://networkx.github.io/documentation/latest/reference/drawing.html
13 | for more info.
14 |
15 | """
16 | # Author: Aric Hagberg (hagberg@lanl.gov)
17 |
18 | # Copyright (C) 2004-2019 by
19 | # Aric Hagberg
20 | # Dan Schult
21 | # Pieter Swart
22 | # All rights reserved.
23 | # BSD license.
24 |
25 | import networkx as nx
26 |
27 | # and the following code block is not needed
28 | # but we want to see which module is used and
29 | # if and why it fails
30 | try:
31 | import pygraphviz
32 | from networkx.drawing.nx_agraph import write_dot
33 | print("using package pygraphviz")
34 | except ImportError:
35 | try:
36 | import pydot
37 | from networkx.drawing.nx_pydot import write_dot
38 | print("using package pydot")
39 | except ImportError:
40 | print()
41 | print("Both pygraphviz and pydot were not found ")
42 | print("see https://networkx.github.io/documentation/latest/reference/drawing.html")
43 | print()
44 | raise
45 |
46 | G = nx.grid_2d_graph(5, 5) # 5x5 grid
47 | write_dot(G, "grid.dot")
48 | print("Now run: neato -Tps grid.dot >grid.ps")
49 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/subclass/README.txt:
--------------------------------------------------------------------------------
1 | Subclass
2 | --------
3 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/subclass/plot_antigraph.py:
--------------------------------------------------------------------------------
1 | """
2 | =========
3 | Antigraph
4 | =========
5 |
6 | Complement graph class for small footprint when working on dense graphs.
7 |
8 | This class allows you to add the edges that *do not exist* in the dense
9 | graph. However, when applying algorithms to this complement graph data
10 | structure, it behaves as if it were the dense version. So it can be used
11 | directly in several NetworkX algorithms.
12 |
13 | This subclass has only been tested for k-core, connected_components,
14 | and biconnected_components algorithms but might also work for other
15 | algorithms.
16 |
17 | """
18 | # Author: Jordi Torrents
19 |
20 | # Copyright (C) 2015-2019 by
21 | # Jordi Torrents
22 | # All rights reserved.
23 | # BSD license.
24 | import networkx as nx
25 | from networkx.exception import NetworkXError
26 | import matplotlib.pyplot as plt
27 |
28 | __all__ = ['AntiGraph']
29 |
30 |
31 | class AntiGraph(nx.Graph):
32 | """
33 | Class for complement graphs.
34 |
35 | The main goal is to be able to work with big and dense graphs with
36 | a low memory footprint.
37 |
38 | In this class you add the edges that *do not exist* in the dense graph,
39 | the report methods of the class return the neighbors, the edges and
40 | the degree as if it was the dense graph. Thus it's possible to use
41 | an instance of this class with some of NetworkX functions.
42 | """
43 |
44 | all_edge_dict = {'weight': 1}
45 |
46 | def single_edge_dict(self):
47 | return self.all_edge_dict
48 | edge_attr_dict_factory = single_edge_dict
49 |
50 | def __getitem__(self, n):
51 | """Return a dict of neighbors of node n in the dense graph.
52 |
53 | Parameters
54 | ----------
55 | n : node
56 | A node in the graph.
57 |
58 | Returns
59 | -------
60 | adj_dict : dictionary
61 | The adjacency dictionary for nodes connected to n.
62 |
63 | """
64 | return dict((node, self.all_edge_dict) for node in
65 | set(self.adj) - set(self.adj[n]) - set([n]))
66 |
67 | def neighbors(self, n):
68 | """Return an iterator over all neighbors of node n in the
69 | dense graph.
70 |
71 | """
72 | try:
73 | return iter(set(self.adj) - set(self.adj[n]) - set([n]))
74 | except KeyError:
75 | raise NetworkXError("The node %s is not in the graph." % (n,))
76 |
77 | def degree(self, nbunch=None, weight=None):
78 | """Return an iterator for (node, degree) in the dense graph.
79 |
80 | The node degree is the number of edges adjacent to the node.
81 |
82 | Parameters
83 | ----------
84 | nbunch : iterable container, optional (default=all nodes)
85 | A container of nodes. The container will be iterated
86 | through once.
87 |
88 | weight : string or None, optional (default=None)
89 | The edge attribute that holds the numerical value used
90 | as a weight. If None, then each edge has weight 1.
91 | The degree is the sum of the edge weights adjacent to the node.
92 |
93 | Returns
94 | -------
95 | nd_iter : iterator
96 | The iterator returns two-tuples of (node, degree).
97 |
98 | See Also
99 | --------
100 | degree
101 |
102 | Examples
103 | --------
104 | >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
105 | >>> list(G.degree(0)) # node 0 with degree 1
106 | [(0, 1)]
107 | >>> list(G.degree([0, 1]))
108 | [(0, 1), (1, 2)]
109 |
110 | """
111 | if nbunch is None:
112 | nodes_nbrs = ((n, {v: self.all_edge_dict for v in
113 | set(self.adj) - set(self.adj[n]) - set([n])})
114 | for n in self.nodes())
115 | elif nbunch in self:
116 | nbrs = set(self.nodes()) - set(self.adj[nbunch]) - {nbunch}
117 | return len(nbrs)
118 | else:
119 | nodes_nbrs = ((n, {v: self.all_edge_dict for v in
120 | set(self.nodes()) - set(self.adj[n]) - set([n])})
121 | for n in self.nbunch_iter(nbunch))
122 |
123 | if weight is None:
124 | return ((n, len(nbrs)) for n, nbrs in nodes_nbrs)
125 | else:
126 | # AntiGraph is a ThinGraph so all edges have weight 1
127 | return ((n, sum((nbrs[nbr].get(weight, 1)) for nbr in nbrs))
128 | for n, nbrs in nodes_nbrs)
129 |
130 | def adjacency_iter(self):
131 | """Return an iterator of (node, adjacency set) tuples for all nodes
132 | in the dense graph.
133 |
134 | This is the fastest way to look at every edge.
135 | For directed graphs, only outgoing adjacencies are included.
136 |
137 | Returns
138 | -------
139 | adj_iter : iterator
140 | An iterator of (node, adjacency set) for all nodes in
141 | the graph.
142 |
143 | """
144 | for n in self.adj:
145 | yield (n, set(self.adj) - set(self.adj[n]) - set([n]))
146 |
147 |
148 | if __name__ == '__main__':
149 | # Build several pairs of graphs, a regular graph
150 | # and the AntiGraph of it's complement, which behaves
151 | # as if it were the original graph.
152 | Gnp = nx.gnp_random_graph(20, 0.8, seed=42)
153 | Anp = AntiGraph(nx.complement(Gnp))
154 | Gd = nx.davis_southern_women_graph()
155 | Ad = AntiGraph(nx.complement(Gd))
156 | Gk = nx.karate_club_graph()
157 | Ak = AntiGraph(nx.complement(Gk))
158 | pairs = [(Gnp, Anp), (Gd, Ad), (Gk, Ak)]
159 | # test connected components
160 | for G, A in pairs:
161 | gc = [set(c) for c in nx.connected_components(G)]
162 | ac = [set(c) for c in nx.connected_components(A)]
163 | for comp in ac:
164 | assert comp in gc
165 | # test biconnected components
166 | for G, A in pairs:
167 | gc = [set(c) for c in nx.biconnected_components(G)]
168 | ac = [set(c) for c in nx.biconnected_components(A)]
169 | for comp in ac:
170 | assert comp in gc
171 | # test degree
172 | for G, A in pairs:
173 | node = list(G.nodes())[0]
174 | nodes = list(G.nodes())[1:4]
175 | assert G.degree(node) == A.degree(node)
176 | assert sum(d for n, d in G.degree()) == sum(d for n, d in A.degree())
177 | # AntiGraph is a ThinGraph, so all the weights are 1
178 | assert sum(d for n, d in A.degree()) == sum(d for n, d in A.degree(weight='weight'))
179 | assert sum(d for n, d in G.degree(nodes)) == sum(d for n, d in A.degree(nodes))
180 |
181 | nx.draw(Gnp)
182 | plt.show()
183 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/examples/subclass/plot_printgraph.py:
--------------------------------------------------------------------------------
1 | """
2 | ===========
3 | Print Graph
4 | ===========
5 |
6 | Example subclass of the Graph class.
7 | """
8 | # Author: Aric Hagberg (hagberg@lanl.gov)
9 |
10 | # Copyright (C) 2004-2019 by
11 | # Aric Hagberg
12 | # Dan Schult
13 | # Pieter Swart
14 | # All rights reserved.
15 | # BSD license.
16 | #
17 | __docformat__ = "restructuredtext en"
18 |
19 | from copy import deepcopy
20 |
21 | import matplotlib.pyplot as plt
22 | import networkx as nx
23 | from networkx import Graph
24 |
25 | class PrintGraph(Graph):
26 | """
27 | Example subclass of the Graph class.
28 |
29 | Prints activity log to file or standard output.
30 | """
31 |
32 | def __init__(self, data=None, name='', file=None, **attr):
33 | Graph.__init__(self, data=data, name=name, **attr)
34 | if file is None:
35 | import sys
36 | self.fh = sys.stdout
37 | else:
38 | self.fh = open(file, 'w')
39 |
40 | def add_node(self, n, attr_dict=None, **attr):
41 | Graph.add_node(self, n, attr_dict=attr_dict, **attr)
42 | self.fh.write("Add node: %s\n" % n)
43 |
44 | def add_nodes_from(self, nodes, **attr):
45 | for n in nodes:
46 | self.add_node(n, **attr)
47 |
48 | def remove_node(self, n):
49 | Graph.remove_node(self, n)
50 | self.fh.write("Remove node: %s\n" % n)
51 |
52 | def remove_nodes_from(self, nodes):
53 | for n in nodes:
54 | self.remove_node(n)
55 |
56 | def add_edge(self, u, v, attr_dict=None, **attr):
57 | Graph.add_edge(self, u, v, attr_dict=attr_dict, **attr)
58 | self.fh.write("Add edge: %s-%s\n" % (u, v))
59 |
60 | def add_edges_from(self, ebunch, attr_dict=None, **attr):
61 | for e in ebunch:
62 | u, v = e[0:2]
63 | self.add_edge(u, v, attr_dict=attr_dict, **attr)
64 |
65 | def remove_edge(self, u, v):
66 | Graph.remove_edge(self, u, v)
67 | self.fh.write("Remove edge: %s-%s\n" % (u, v))
68 |
69 | def remove_edges_from(self, ebunch):
70 | for e in ebunch:
71 | u, v = e[0:2]
72 | self.remove_edge(u, v)
73 |
74 | def clear(self):
75 | Graph.clear(self)
76 | self.fh.write("Clear graph\n")
77 |
78 |
79 | if __name__ == '__main__':
80 | G = PrintGraph()
81 | G.add_node('foo')
82 | G.add_nodes_from('bar', weight=8)
83 | G.remove_node('b')
84 | G.remove_nodes_from('ar')
85 | print("Nodes in G: ", G.nodes(data=True))
86 | G.add_edge(0, 1, weight=10)
87 | print("Edges in G: ", G.edges(data=True))
88 | G.remove_edge(0, 1)
89 | G.add_edges_from(zip(range(0, 3), range(1, 4)), weight=10)
90 | print("Edges in G: ", G.edges(data=True))
91 | G.remove_edges_from(zip(range(0, 3), range(1, 4)))
92 | print("Edges in G: ", G.edges(data=True))
93 |
94 | G = PrintGraph()
95 | nx.add_path(G, range(10))
96 | nx.add_star(G, range(9, 13))
97 | nx.draw(G)
98 | plt.show()
99 |
--------------------------------------------------------------------------------
/objSr/share/doc/networkx-2.4/requirements.txt:
--------------------------------------------------------------------------------
1 | -r requirements/default.txt
2 | -r requirements/test.txt
3 |
--------------------------------------------------------------------------------
/objSr/share/python-wheels/CacheControl-0.11.7-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/CacheControl-0.11.7-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/appdirs-1.4.3-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/appdirs-1.4.3-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/certifi-2018.1.18-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/certifi-2018.1.18-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/chardet-3.0.4-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/chardet-3.0.4-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/colorama-0.3.7-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/colorama-0.3.7-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/distlib-0.2.6-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/distlib-0.2.6-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/distro-1.0.1-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/distro-1.0.1-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/html5lib-0.999999999-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/html5lib-0.999999999-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/idna-2.6-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/idna-2.6-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/ipaddress-0.0.0-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/ipaddress-0.0.0-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/lockfile-0.12.2-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/lockfile-0.12.2-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/packaging-17.1-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/packaging-17.1-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/pip-9.0.1-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/pip-9.0.1-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/progress-1.2-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/progress-1.2-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/pyparsing-2.2.0-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/pyparsing-2.2.0-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/requests-2.18.4-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/requests-2.18.4-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/retrying-1.3.3-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/retrying-1.3.3-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/setuptools-39.0.1-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/setuptools-39.0.1-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/six-1.11.0-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/six-1.11.0-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/urllib3-1.22-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/urllib3-1.22-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/webencodings-0.5-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/webencodings-0.5-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/objSr/share/python-wheels/wheel-0.30.0-py2.py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/munnafaisal/Deep-Object-Search-With-Hash/b8840f55289ede2f442f7420d6960d58b539ed60/objSr/share/python-wheels/wheel-0.30.0-py2.py3-none-any.whl
--------------------------------------------------------------------------------
/object_detection_YOLO.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 |
3 | k= int(tf.__version__.split('.')[0])
4 | if k >=2:
5 | import tensorflow.compat.v1 as tf
6 |
7 | tf.disable_v2_behavior()
8 |
9 | import tensornets as nets
10 | import cv2
11 | import numpy as np
12 | import time
13 | import argparse
14 | import sys
15 | from create_folder import createFolder
16 |
17 | tf.disable_v2_behavior()
18 |
19 | class YoloObjectDetection():
20 |
21 | def __init__(self):
22 |
23 | self.url1 = []
24 | self.inputs = tf.placeholder(tf.float32, [None, 416, 416, 3])
25 | self.model = nets.YOLOv3COCO(self.inputs, nets.Darknet19)
26 | self.cap = []
27 | self.query_obj_type = []
28 | # model = nets.YOLOv2(inputs, nets.Darknet19)
29 |
30 | # frame=cv2.imread("D://pyworks//yolo//truck.jpg",1)
31 | self.count = 0
32 | self.classes = {'0': 'person', '1': 'bicycle', '2': 'car', '3': 'bike', '5': 'bus', '7': 'truck', '8': 'chair'}
33 | self.list_of_classes = [0, 1, 2, 3, 5, 7, 8]
34 |
35 | def init_tf_session(self):
36 |
37 | with tf.Session().as_default() as self.sess:
38 |
39 | self.sess.run(self.model.pretrained())
40 |
41 | def get_cropped_image(self):
42 |
43 |
44 | ret, frame = self.cap.read()
45 | img = cv2.resize(frame, (416, 416))
46 | copy_img = img.copy()
47 | imge = np.array(img).reshape(-1, 416, 416, 3)
48 |
49 | start_time = time.time()
50 | preds = self.sess.run(self.model.preds, {self.inputs: self.model.preprocess(imge)})
51 |
52 | #print("--- %s seconds ---" % (time.time() - start_time))
53 | boxes = self.model.get_boxes(preds, imge.shape[1:3])
54 |
55 | # cv2.namedWindow('image', cv2.WINDOW_NORMAL)
56 | #
57 | # cv2.resizeWindow('image', 700, 700)
58 | # print("--- %s seconds ---" % (time.time() - start_time))
59 | boxes1 = np.array(boxes)
60 |
61 | img_list = []
62 | box_list = []
63 |
64 | for j in self.list_of_classes:
65 | count = 0
66 |
67 | if str(j) in self.classes:
68 | lab = self.classes[str(j)]
69 |
70 | if lab == self.query_obj_type:
71 |
72 | if len(boxes1) != 0:
73 |
74 | for i in range(len(boxes1[j])):
75 |
76 | box = boxes1[j][i]
77 |
78 | if boxes1[j][i][4] >= 0.5:
79 | count += 1
80 |
81 |
82 | crop_img = copy_img[int(box[1]):int(box[3]), int(box[0]):int(box[2])]
83 | # cv2.rectangle(img, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 1)
84 | # cv2.putText(img, lab, (box[0], box[1]), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 0, 255),
85 | # lineType=cv2.LINE_AA)
86 |
87 | img_list.append(crop_img)
88 | box_list.append(box)
89 |
90 |
91 | return box_list,img_list, img
92 |
93 | def crop_and_save(self):
94 |
95 |
96 | with tf.Session() as sess:
97 |
98 | sess.run(self.model.pretrained())
99 | # "D://pyworks//yolo//videoplayback.mp4"
100 | cap = cv2.VideoCapture(self.url1)
101 |
102 | while (cap.isOpened()):
103 |
104 | ret, frame = cap.read()
105 | img = cv2.resize(frame, (416, 416))
106 | copy_img = img.copy()
107 | imge = np.array(img).reshape(-1, 416, 416, 3)
108 |
109 | start_time = time.time()
110 | preds = sess.run(self.model.preds, {self.inputs: self.model.preprocess(imge)})
111 |
112 | print("--- %s seconds ---" % (time.time() - start_time))
113 | boxes = self.model.get_boxes(preds, imge.shape[1:3])
114 |
115 | cv2.namedWindow('image', cv2.WINDOW_NORMAL)
116 |
117 | cv2.resizeWindow('image', 700, 700)
118 | # print("--- %s seconds ---" % (time.time() - start_time))
119 | boxes1 = np.array(boxes)
120 |
121 | for j in self.list_of_classes:
122 | count = 0
123 | if str(j) in self.classes:
124 | lab = self.classes[str(j)]
125 | if len(boxes1) != 0:
126 |
127 | for i in range(len(boxes1[j])):
128 |
129 | box = boxes1[j][i]
130 |
131 | if boxes1[j][i][4] >= 0.5:
132 |
133 | count += 1
134 |
135 | crop_img = copy_img[int(box[1]):int(box[3] ), int(box[0]):int(box[2])]
136 |
137 | cv2.rectangle(img, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 1)
138 | cv2.putText(img, lab, (box[0], box[1]), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 0, 255),
139 | lineType=cv2.LINE_AA)
140 |
141 |
142 |
143 | cv2.imshow("cropped_image", crop_img)
144 | cv2.waitKey(1)
145 |
146 | dir = "temp/" + lab + "/"
147 | createFolder(dir)
148 | s1 = dir + '{}.jpg'.format(self.count)
149 | self.count = self.count + 1
150 | print("\n object_count :", self.count)
151 | cv2.imwrite(s1, crop_img)
152 |
153 | #print(lab, ": ", count)
154 |
155 | cv2.imshow("image", img)
156 | if cv2.waitKey(1) & 0xFF == ord('q'):
157 | break
158 |
159 | cap.release()
160 | cv2.destroyAllWindows()
161 |
162 |
163 | def main(args):
164 |
165 | objectDetetcion = YoloObjectDetection()
166 | objectDetetcion.url1 = args.video_dir
167 | objectDetetcion.cap = cv2.VideoCapture(objectDetetcion.url1)
168 |
169 | objectDetetcion.crop_and_save()
170 |
171 |
172 | def parse_arguments(argv):
173 |
174 | parser = argparse.ArgumentParser()
175 |
176 |
177 | parser.add_argument('--video_dir', type=str,
178 | help='Path to the data directory containing aligned LFW face patches.')
179 |
180 | return parser.parse_args(argv)
181 |
182 | if __name__ == '__main__':
183 | main(parse_arguments(sys.argv[1:]))
184 |
185 | #objectDetetcion.init_tf_session()
186 |
187 | # for i in range(1000):
188 | # print("Press Enter ")
189 | # imgs = objectDetetcion.get_cropped_image()
190 | #
191 | # for index, img in enumerate(imgs) :
192 | # cv2.waitKey(0)
193 | #
194 | # if index == 3:
195 | # break
196 | #
197 | # cv2.imshow(str(index), img)
198 | #
199 | # print(len(imgs))
200 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | absl-py==0.8.1
2 | APScheduler==3.6.3
3 | astor==0.8.1
4 | cachetools==3.1.1
5 | certifi==2019.9.11
6 | chardet==3.0.4
7 | Click==7.0
8 | config==0.4.2
9 | cycler==0.10.0
10 | decorator==4.4.2
11 | Flask==1.0.2
12 | gast==0.2.2
13 | google-auth==1.8.2
14 | google-auth-oauthlib==0.4.1
15 | google-pasta==0.1.8
16 | grpcio==1.25.0
17 | h5py==2.10.0
18 | idna==2.8
19 | imageio==2.8.0
20 | imutils==0.5.3
21 | itsdangerous==1.1.0
22 | Jinja2==2.10.3
23 | joblib==0.14.1
24 | Keras==2.1.2
25 | Keras-Applications==1.0.8
26 | Keras-Preprocessing==1.1.0
27 | kiwisolver==1.1.0
28 | Markdown==3.1.1
29 | MarkupSafe==1.1.1
30 | matplotlib==3.1.2
31 | networkx==2.4
32 | numpy==1.17.4
33 | oauthlib==3.1.0
34 | opencv-python==3.4.3.18
35 | opt-einsum==3.1.0
36 | pandas==1.0.3
37 | protobuf==3.11.1
38 | pyasn1==0.4.8
39 | pyasn1-modules==0.2.7
40 | pyparsing==2.4.5
41 | pytesseract==0.3.4
42 | python-dateutil==2.8.1
43 | pytz==2019.3
44 | PyWavelets==1.1.1
45 | PyYAML==5.2
46 | requests==2.22.0
47 | requests-oauthlib==1.3.0
48 | rsa==4.0
49 | scikit-image==0.16.2
50 | scikit-learn==0.22
51 | scipy==1.3.3
52 | six==1.13.0
53 | tb-nightly==1.15.0a20190806
54 | tensorboard==1.15.0
55 | tensorflow==1.15.0
56 | tensorflow-estimator==1.15.1
57 | tensornets==0.4.6
58 | termcolor==1.1.0
59 | tf-estimator-nightly==1.14.0.dev2019080601
60 | tzlocal==2.0.0
61 | urllib3==1.25.7
62 | Werkzeug==0.16.0
63 | wrapt==1.11.2
64 |
--------------------------------------------------------------------------------