├── .gitignore ├── LICENSE ├── README.md ├── Traclus_Debug.ipynb ├── Traclus_Driver.ipynb ├── requirements.txt ├── setup.cfg ├── setup.py └── src ├── __init__.py └── traclus ├── __init__.py └── traclus.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TRACLUS 2 | 3 | Implemented for Python 3 4 | 5 | This is an implementation of the TRACLUS algorithm as described in the paper: 6 | "Trajectory Clustering: A Partition-and-Group Framework" 7 | by Lee, Han, & Whang (2007) [http://hanj.cs.illinois.edu/pdf/sigmod07_jglee.pdf] 8 | 9 | Implementation Author: Adriel Isaiah V. Amoguis (De La Salle University) 10 | Implementation Date: 2023-03-19 11 | 12 | This implementation was done as part of the algorithms required for the implementation author's 13 | undergraduate thesis. The implementation is not guaranteed to be bug-free and may not be optimized 14 | for certain use-cases. The implementation author is not responsible for any damages caused by the 15 | use of this implementation. Use at your own risk. End-users are encouraged to examine the code 16 | in the case of any issues. If you find any bugs, please report them to the implementation author 17 | via the repository's issues page on GitHub. 18 | 19 | --- 20 | 21 | ## Installation 22 | 23 | This implementation requires Python 3.6 or higher. It is recommended to use a virtual environment to avoid 24 | dependency conflicts. 25 | 26 | Optionally, create a Conda Virtual Environment: 27 | 28 | ```bash 29 | conda create -n traclus python=3.6 30 | conda activate traclus 31 | ``` 32 | 33 | Install the package from pip: 34 | 35 | ```bash 36 | pip install traclus-python==1.0.1 37 | ``` 38 | 39 | --- 40 | 41 | ## Usage 42 | 43 | ### Preparing Your Trajectory Data 44 | 45 | The TRACLUS algorithm requires a Python list of trajectories. Each trajectory is a 2-Dimensional Numpy Array 46 | with the following format: 47 | 48 | ```python 49 | [[x1, y1], 50 | [x2, y2], 51 | ... 52 | [xn, yn]] 53 | ``` 54 | 55 | where `x` is the x-coordinate, and `y` is the y-coordinate for each point `n`. 56 | 57 | ### Running the Algorithm in Your Own Script File 58 | 59 | ```python 60 | from traclus import traclus as tr 61 | 62 | # Your Trajectory Data 63 | trajectories = ... 64 | 65 | # Run the TRACLUS Algorithm 66 | partitions, segments, dist_matrix, clusters, cluster_assignments, representative_trajectories = tr.traclus(trajectories) 67 | ``` 68 | 69 | The `partitions` variable will contain all the trajectories that are partitioned by the algorithm into their characteristic points (cp). 70 | The `segments` variable will contain all the generated partitions split into segments. 71 | The `dist_matrix` variable will contain the distance matrix generated by the distance function as defined in the paper. 72 | The `clusters` variable will contain the line segment clusters generated by the algorithm. 73 | The `cluster_assignments` variable will contain the cluster assignments for each line segment. 74 | The `representative_trajectories` variable will contain the representative trajectories generated by the algorithm. 75 | 76 | ### Distance Weights and Trajectory Direction 77 | 78 | This implementation uses three smaller distance function that computes the overall distance between two points in the trajectory. 79 | These are the _Perpendicular Distance_, _Parallel Distance_, and _Angular Distance_. To compute the overall distance, these three distances 80 | are weighted and added together as shown below: 81 | 82 | $distance = w_{perpendicular} * d_{perpendicular} + w_{parallel} * d_{parallel} + w_{angular} * d_{angular}$ 83 | 84 | The weights for each distance function can be adjusted by providing a `weights` list to the `traclus` function. The default weights are: 85 | 86 | ```python 87 | weights = [1, 1, 1] 88 | ``` 89 | 90 | Additionally, the _Perpendicular Distance_ is computed differently depending on whether or not the trajectories are direction-sensitive. 91 | Trajectories are treated as directional by default, but this can be changed by providing the `directional` parameter to the `traclus` function. 92 | Such as: 93 | 94 | ```python 95 | partitions, segments, dist_matrix, clusters, cluster_assignments, representative_trajectories = tr.traclus(trajectories, directional=False) 96 | ``` 97 | 98 | ### Clustering Parameters 99 | 100 | The `traclus` function takes in a `clustering_algorithm` parameter that can be used to specify the clustering algorithm to use. This is set to 101 | DBSCAN from Scipy by default. The `traclus` function also accepts two parameters for DBSCAN: `eps` and `min_samples`. These are set to 1 and 10 by default. 102 | 103 | ### Supporting Functions 104 | 105 | The `sub_sample_trajectory` function can be used to sub-sample a trajectory into a trajectory of the same profile but with lesser points. 106 | It takes `sample_n` as a parameter, which is the number of points to sub-sample the trajectory into. 107 | 108 | ```python 109 | 110 | from traclus.traclus import sub_sample_trajectory 111 | 112 | # Your Trajectory Data 113 | trajectories = ... 114 | 115 | # Sub-Sample the Trajectories 116 | sub_sampled_trajectories = [sub_sample_trajectory(trajectory, sample_n=100) for trajectory in trajectories] 117 | ``` 118 | 119 | In the example above, the trajectories will be sub-sampled into 100 points each. This is useful for reducing the number of points processed by the algorithm, decreasing its runtime. However, this may also reduce the accuracy of the results. It is recommended to experiment with different values of `sample_n` to find the best value for your use-case. 120 | 121 | The `smooth_trajectory` function can be used to smooth the representative trajectories generated by the algorithm. 122 | 123 | ```python 124 | from traclus.traclus import traclus, smooth_trajectory 125 | 126 | # Your Trajectory Data 127 | trajectories = ... 128 | 129 | # Run the TRACLUS Algorithm 130 | partitions, segments, dist_matrix, clusters, cluster_assignments, representative_trajectories = traclus(trajectories) 131 | 132 | # Smooth the Representative Trajectories 133 | smoothed_representative_trajectories = [smooth_trajectory(trajectory, window_size=21) for trajectory in representative_trajectories] 134 | ``` 135 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | matplotlib 3 | scikit-learn 4 | seaborn -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file=README.md 3 | license_files=LICENSE -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | 4 | setup( 5 | name='traclus-python', 6 | version='1.0.2', 7 | license='apache-2.0', 8 | author="Adriel Isaiah Amoguis", 9 | author_email='adriel.isaiah.amoguis@gmail.com', 10 | packages=find_packages('src'), 11 | package_dir={'': 'src'}, 12 | url='https://github.com/AdrielAmoguis/TRACLUS', 13 | keywords='Trajectory Clustering', 14 | install_requires=[ 15 | 'scikit-learn', 16 | 'numpy', 17 | ], 18 | long_description=open('README.md').read(), 19 | long_description_content_type='text/markdown', 20 | ) -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrielAmoguis/TRACLUS/895ab17a8718637a45d331e3af1c546cd7b0612b/src/__init__.py -------------------------------------------------------------------------------- /src/traclus/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdrielAmoguis/TRACLUS/895ab17a8718637a45d331e3af1c546cd7b0612b/src/traclus/__init__.py -------------------------------------------------------------------------------- /src/traclus/traclus.py: -------------------------------------------------------------------------------- 1 | """ 2 | TRACLUS: A Trajectory Clustering Algorithm (A Partition and Group Framework) 3 | Implemented for Python 3 4 | 5 | This is an implementation of the TRACLUS algorithm as described in the paper: 6 | "Trajectory Clustering: A Partition-and-Group Framework" 7 | by Lee, Han, & Whang (2007) [http://hanj.cs.illinois.edu/pdf/sigmod07_jglee.pdf] 8 | 9 | Implementation Author: Adriel Isaiah V. Amoguis (De La Salle University) 10 | Implementation Date: 2023-03-19 11 | 12 | This implementation was done as part of the algorithms required for the implementation author's 13 | undergraduate thesis. The implementation is not guaranteed to be bug-free and may not be optimized 14 | for certain use-cases. The implementation author is not responsible for any damages caused by the 15 | use of this implementation. Use at your own risk. End-users are encouraged to examine the code 16 | in the case of any issues. If you find any bugs, please report them to the implementation author 17 | via the repository's issues page on GitHub. 18 | """ 19 | 20 | import argparse 21 | import numpy as np 22 | from sklearn.cluster import OPTICS 23 | from scipy.spatial.distance import euclidean as d_euclidean 24 | 25 | import pickle 26 | import os 27 | import warnings 28 | 29 | # UTILITY FUNCTIONS 30 | 31 | def load_trajectories(filepath): 32 | """ 33 | Load the trajectories from a pickle file. 34 | """ 35 | if not os.path.exists(filepath): 36 | raise FileNotFoundError("File not found at {}".format(filepath)) 37 | 38 | with open(filepath, 'rb') as f: 39 | trajectories = pickle.load(f) 40 | 41 | return trajectories 42 | 43 | def save_results(trajectories, partitions, segments, dist_matrix, clusters, cluster_assignments, representative_trajectories, filepath): 44 | """ 45 | Save the results to a pickle file. 46 | """ 47 | results = { 48 | 'trajectories': trajectories, 49 | 'partitions': partitions, 50 | 'segments': segments, 51 | 'dist_matrix': dist_matrix, 52 | 'clusters': clusters, 53 | 'cluster_assignments': cluster_assignments, 54 | 'representative_trajectories': representative_trajectories 55 | } 56 | with open(filepath, 'wb') as f: 57 | pickle.dump(results, f) 58 | 59 | def sub_sample_trajectory(trajectory, sample_n=30): 60 | """ 61 | Sub sample a trajectory to a given number of points. 62 | """ 63 | if not isinstance(trajectory, np.ndarray): 64 | raise TypeError("Trajectory must be of type np.ndarray") 65 | elif trajectory.shape[1] != 2: 66 | raise ValueError("Trajectory must be of shape (n, 2)") 67 | 68 | include = np.linspace(0, trajectory.shape[0]-1, sample_n, dtype=np.int32) 69 | return trajectory[include] 70 | 71 | def calculate_line_euclidean_length(line): 72 | """ 73 | Calculate the euclidean length of a all points in the line. 74 | """ 75 | total_length = 0 76 | for i in range(0, line.shape[0]): 77 | if i == 0: 78 | continue 79 | total_length += d_euclidean(line[i-1], line[i]) 80 | 81 | return total_length 82 | 83 | def get_point_projection_on_line(point, line): 84 | """ 85 | Get the projection of a point on a line. 86 | """ 87 | 88 | # Get the slope of the line using the start and end points 89 | line_slope = (line[-1, 1] - line[0, 1]) / (line[-1, 0] - line[0, 0]) if line[-1, 0] != line[0, 0] else np.inf 90 | 91 | # In case the slope is infinite, we can directly get the projection 92 | if np.isinf(line_slope): 93 | return np.array([line[0,0], point[1]]) 94 | 95 | # Convert the slope to a rotation matrix 96 | R = slope_to_rotation_matrix(line_slope) 97 | 98 | # Rotate the line and point 99 | rot_line = np.matmul(line, R.T) 100 | rot_point = np.matmul(point, R.T) 101 | 102 | # Get the projection 103 | proj = np.array([rot_point[0], rot_line[0,1]]) 104 | 105 | # Undo the rotation for the projection 106 | R_inverse = np.linalg.inv(R) 107 | proj = np.matmul(proj, R_inverse.T) 108 | 109 | return proj 110 | 111 | def partition2segments(partition): 112 | """ 113 | Convert a partition to a list of segments. 114 | """ 115 | 116 | if not isinstance(partition, np.ndarray): 117 | raise TypeError("partition must be of type np.ndarray") 118 | elif partition.shape[1] != 2: 119 | raise ValueError("partition must be of shape (n, 2)") 120 | 121 | segments = [] 122 | for i in range(partition.shape[0]-1): 123 | segments.append(np.array([[partition[i, 0], partition[i, 1]], [partition[i+1, 0], partition[i+1, 1]]])) 124 | 125 | return segments 126 | 127 | ################# EQUATIONS ################# 128 | 129 | # Euclidean Distance : Accepts two points of type np.ndarray([x,y]) 130 | # DEPRECATED IN FAVOR OF THE SCIPY IMPLEMENTATION OF THE EUCLIDEAN DISTANCE 131 | # d_euclidean = lambda p1, p2: np.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) 132 | 133 | # Perpendicular Distance 134 | def d_perpendicular(l1, l2): 135 | """ 136 | Calculate the perpendicular distance between two lines. 137 | """ 138 | # Find the shorter line and assign that as l_shorter 139 | l_shorter = l_longer = None 140 | l1_len, l2_len = d_euclidean(l1[0], l1[-1]), d_euclidean(l2[0], l2[-1]) 141 | if l1_len < l2_len: 142 | l_shorter = l1 143 | l_longer = l2 144 | else: 145 | l_shorter = l2 146 | l_longer = l1 147 | 148 | ps = get_point_projection_on_line(l_shorter[0], l_longer) 149 | pe = get_point_projection_on_line(l_shorter[-1], l_longer) 150 | 151 | lehmer_1 = d_euclidean(l_shorter[0], ps) 152 | lehmer_2 = d_euclidean(l_shorter[-1], pe) 153 | 154 | if lehmer_1 == 0 and lehmer_2 == 0: 155 | return 0 156 | return (lehmer_1**2 + lehmer_2**2) / (lehmer_1 + lehmer_2)#, ps, pe, l_shorter[0], l_shorter[-1] 157 | 158 | # Parallel Distance 159 | def d_parallel(l1, l2): 160 | """ 161 | Calculate the parallel distance between two lines. 162 | """ 163 | # Find the shorter line and assign that as l_shorter 164 | l_shorter = l_longer = None 165 | l1_len, l2_len = d_euclidean(l1[0], l1[-1]), d_euclidean(l2[0], l2[-1]) 166 | if l1_len < l2_len: 167 | l_shorter = l1 168 | l_longer = l2 169 | else: 170 | l_shorter = l2 171 | l_longer = l1 172 | 173 | ps = get_point_projection_on_line(l_shorter[0], l_longer) 174 | pe = get_point_projection_on_line(l_shorter[-1], l_longer) 175 | 176 | parallel_1 = min(d_euclidean(l_longer[0], ps), d_euclidean(l_longer[-1], ps)) 177 | parallel_2 = min(d_euclidean(l_longer[0], pe), d_euclidean(l_longer[-1], pe)) 178 | 179 | return min(parallel_1, parallel_2) 180 | 181 | # Angular Distance 182 | def d_angular(l1, l2, directional=True): 183 | """ 184 | Calculate the angular distance between two lines. 185 | """ 186 | 187 | # Find the shorter line and assign that as l_shorter 188 | l_shorter = l_longer = None 189 | l1_len, l2_len = d_euclidean(l1[0], l1[-1]), d_euclidean(l2[0], l2[-1]) 190 | if l1_len < l2_len: 191 | l_shorter = l1 192 | l_longer = l2 193 | else: 194 | l_shorter = l2 195 | l_longer = l1 196 | 197 | # Get the minimum intersecting angle between both lines 198 | shorter_slope = (l_shorter[-1,1] - l_shorter[0,1]) / (l_shorter[-1,0] - l_shorter[0,0]) if l_shorter[-1,0] - l_shorter[0,0] != 0 else np.inf 199 | longer_slope = (l_longer[-1,1] - l_longer[0,1]) / (l_longer[-1,0] - l_longer[0,0]) if l_longer[-1,0] - l_longer[0,0] != 0 else np.inf 200 | 201 | # The case of a vertical line 202 | theta = None 203 | if np.isinf(shorter_slope): 204 | # Get the angle of the longer line with the x-axis and subtract it from 90 degrees 205 | tan_theta0 = longer_slope 206 | tan_theta1 = tan_theta0 * -1 207 | theta0 = np.abs(np.arctan(tan_theta0)) 208 | theta1 = np.abs(np.arctan(tan_theta1)) 209 | theta = min(theta0, theta1) 210 | elif np.isinf(longer_slope): 211 | # Get the angle of the shorter line with the x-axis and subtract it from 90 degrees 212 | tan_theta0 = shorter_slope 213 | tan_theta1 = tan_theta0 * -1 214 | theta0 = np.abs(np.arctan(tan_theta0)) 215 | theta1 = np.abs(np.arctan(tan_theta1)) 216 | theta = min(theta0, theta1) 217 | else: 218 | tan_theta0 = (shorter_slope - longer_slope) / (1 + shorter_slope * longer_slope) 219 | tan_theta1 = tan_theta0 * -1 220 | 221 | theta0 = np.abs(np.arctan(tan_theta0)) 222 | theta1 = np.abs(np.arctan(tan_theta1)) 223 | 224 | theta = min(theta0, theta1) 225 | 226 | if directional: 227 | return np.sin(theta) * d_euclidean(l_longer[0], l_longer[-1]) 228 | 229 | if 0 <= theta < (90 * np.pi / 180): 230 | return np.sin(theta) * d_euclidean(l_longer[0], l_longer[-1]) 231 | elif (90 * np.pi / 180) <= theta <= np.pi: 232 | return np.sin(theta) 233 | else: 234 | raise ValueError("Theta is not in the range of 0 to 180 degrees.") 235 | 236 | # Total Trajectory Distance 237 | def distance(l1, l2, directional=True, w_perpendicular=1, w_parallel=1, w_angular=1): 238 | """ 239 | Get the total trajectory distance using all three distance formulas. 240 | """ 241 | 242 | perpendicular_distance = d_perpendicular(l1, l2) 243 | parallel_distance = d_parallel(l1, l2) 244 | angular_distance = d_angular(l1, l2, directional=directional) 245 | 246 | return (w_perpendicular * perpendicular_distance) + (w_parallel * parallel_distance) + (w_angular * angular_distance) 247 | 248 | # Minimum Description Length 249 | def minimum_desription_length(start_idx, curr_idx, trajectory, w_angular=1, w_perpendicular=1, par=True, directional=True): 250 | """ 251 | Calculate the minimum description length. 252 | """ 253 | LH = LDH = 0 254 | for i in range(start_idx, curr_idx-1): 255 | ed = d_euclidean(trajectory[i], trajectory[i+1]) 256 | LH += max(0, np.log2(ed, where=ed>0)) 257 | if par: 258 | for j in range(start_idx, i-1): 259 | # print() 260 | # print(np.array([trajectory[start_idx], trajectory[i]])) 261 | # print(np.array([trajectory[j], trajectory[j+1]])) 262 | LDH += w_perpendicular * d_perpendicular(np.array([trajectory[start_idx], trajectory[i]]), np.array([trajectory[j], trajectory[j+1]])) 263 | LDH += w_angular * d_angular(np.array([trajectory[start_idx], trajectory[i]]), np.array([trajectory[j], trajectory[j+1]]), directional=directional) 264 | if par: 265 | return LH + LDH 266 | return LH 267 | 268 | # Slope to angle in degrees 269 | def slope_to_angle(slope, degrees=True): 270 | """ 271 | Convert slope to angle in degrees. 272 | """ 273 | if not degrees: 274 | return np.arctan(slope) 275 | return np.arctan(slope) * 180 / np.pi 276 | 277 | # Slope to rotation matrix 278 | def slope_to_rotation_matrix(slope): 279 | """ 280 | Convert slope to rotation matrix. 281 | """ 282 | return np.array([[1, slope], [-slope, 1]]) 283 | 284 | # Get cluster majority line orientation 285 | def get_average_direction_slope(line_list): 286 | """ 287 | Get the cluster majority line orientation. 288 | Returns 1 if the lines are mostly vertical, 0 otherwise. 289 | """ 290 | # Get the average slopes of all the lines 291 | slopes = [] 292 | for line in line_list: 293 | slopes.append((line[-1, 1] - line[0, 1]) / (line[-1, 0] - line[0, 0]) if (line[-1, 0] - line[0, 0]) != 0 else 0) 294 | slopes = np.array(slopes) 295 | 296 | # Get the average slope 297 | return np.mean(slopes) 298 | 299 | # Trajectory Smoothing 300 | def smooth_trajectory(trajectory, window_size=5): 301 | """ 302 | Smooth a trajectory using a moving average filter. 303 | """ 304 | # Ensure that the trajectory is a numpy array of shape (n, 2) 305 | if not isinstance(trajectory, np.ndarray): 306 | raise TypeError("Trajectory must be a numpy array") 307 | elif trajectory.shape[1] != 2: 308 | raise ValueError("Trajectory must be a numpy array of shape (n, 2)") 309 | 310 | # Ensure that the window size is an odd integer 311 | if not isinstance(window_size, int): 312 | raise TypeError("Window size must be an integer") 313 | elif window_size % 2 == 0: 314 | raise ValueError("Window size must be an odd integer") 315 | 316 | # Pad the trajectory with the first and last points 317 | padded_trajectory = np.zeros((trajectory.shape[0] + (window_size - 1), 2)) 318 | padded_trajectory[window_size // 2:window_size // 2 + trajectory.shape[0]] = trajectory 319 | padded_trajectory[:window_size // 2] = trajectory[0] 320 | padded_trajectory[-window_size // 2:] = trajectory[-1] 321 | 322 | # Apply the moving average filter 323 | smoothed_trajectory = np.zeros(trajectory.shape) 324 | for i in range(trajectory.shape[0]): 325 | smoothed_trajectory[i] = np.mean(padded_trajectory[i:i + window_size], axis=0) 326 | 327 | return smoothed_trajectory 328 | 329 | # Get Distance Matrix 330 | def get_distance_matrix(partitions, directional=True, w_perpendicular=1, w_parallel=1, w_angular=1, progress_bar=False): 331 | # Create Distance Matrix between all trajectories 332 | n_partitions = len(partitions) 333 | dist_matrix = np.zeros((n_partitions, n_partitions)) 334 | for i in range(n_partitions): 335 | if progress_bar: print(f'Progress: {i+1}/{n_partitions}', end='\r') 336 | for j in range(i+1): 337 | dist_matrix[i,j] = dist_matrix[j,i] = distance(partitions[i], partitions[j], directional=directional, w_perpendicular=w_perpendicular, w_parallel=w_parallel, w_angular=w_angular) 338 | print(f'Progress: {i+1}/{n_partitions}', end='\r') 339 | 340 | # Main Diagonal 341 | for i in range(n_partitions): 342 | dist_matrix[i,i] = 0 343 | 344 | # Check for nans and warn if any are found 345 | if np.isnan(dist_matrix).any(): 346 | warnings.warn("Distance matrix contains NaN values") 347 | 348 | # Replace the nans with the maximum value 349 | dist_matrix[np.isnan(dist_matrix)] = 9999999 350 | 351 | return dist_matrix 352 | 353 | ############################################# 354 | 355 | def partition(trajectory, directional=True, progress_bar=False, w_perpendicular=1, w_angular=1): 356 | """ 357 | Partition a trajectory into segments. 358 | """ 359 | 360 | # Ensure that the trajectory is a numpy array of shape (n, 2) 361 | if not isinstance(trajectory, np.ndarray): 362 | raise TypeError("Trajectory must be a numpy array") 363 | elif trajectory.shape[1] != 2: 364 | raise ValueError("Trajectory must be a numpy array of shape (n, 2)") 365 | 366 | # Initialize the characteristic points, add the first point as a characteristic point 367 | cp_indices = [] 368 | cp_indices.append(0) 369 | 370 | traj_len = trajectory.shape[0] 371 | start_idx = 0 372 | 373 | length = 1 374 | while start_idx + length < traj_len: 375 | if progress_bar: 376 | print(f'\r{round(((start_idx + length) / traj_len) * 100, 2)}%', end='') 377 | # print(f'Current Index: {start_idx + length}, Trajectory Length: {traj_len}') 378 | curr_idx = start_idx + length 379 | # print(start_idx, curr_idx) 380 | # print(f"Current Index: {curr_idx}, Current point: {trajectory[curr_idx]}") 381 | cost_par = minimum_desription_length(start_idx, curr_idx, trajectory, w_angular=w_angular, w_perpendicular=w_perpendicular, directional=directional) 382 | cost_nopar = minimum_desription_length(start_idx, curr_idx, trajectory, par=False, directional=directional) 383 | # print(f'Cost with partition: {cost_par}, Cost without partition: {cost_nopar}') 384 | if cost_par > cost_nopar: 385 | # print(f"Added characteristic point: {trajectory[curr_idx-1]} with index {curr_idx-1}") 386 | cp_indices.append(curr_idx-1) 387 | start_idx = curr_idx-1 388 | length = 1 389 | else: 390 | length += 1 391 | 392 | # Add last point to characteristic points 393 | cp_indices.append(len(trajectory) - 1) 394 | # print(cp_indices) 395 | 396 | return np.array([trajectory[i] for i in cp_indices]) 397 | 398 | # Get Representative Trajectory 399 | def get_representative_trajectory(lines, min_lines=3): 400 | """ 401 | Get the sweeping line vector average. 402 | """ 403 | # Get the average rotation matrix for all the lines 404 | average_slope = get_average_direction_slope(lines) 405 | rotation_matrix = slope_to_rotation_matrix(average_slope) 406 | 407 | # Rotate all lines such that they are parallel to the x-axis 408 | rotated_lines = [] 409 | for line in lines: 410 | rotated_lines.append(np.matmul(line, rotation_matrix.T)) 411 | 412 | # Let starting_and_ending_points be the set of all starting and ending points of the lines 413 | starting_and_ending_points = [] 414 | for line in rotated_lines: 415 | starting_and_ending_points.append(line[0]) 416 | starting_and_ending_points.append(line[-1]) 417 | starting_and_ending_points = np.array(starting_and_ending_points) 418 | 419 | # Sort the starting and ending points by their x-coordinate 420 | starting_and_ending_points = starting_and_ending_points[starting_and_ending_points[:, 0].argsort()] 421 | 422 | # Perform the sweeping line algorithm 423 | representative_points = [] 424 | for p in starting_and_ending_points: 425 | # Let num_p be the number of lines that contain the x-value of p 426 | num_p = 0 427 | for line in rotated_lines: 428 | # Sort the line points by their x-coordinate 429 | point_sorted_line = line[line[:, 0].argsort()] 430 | # print(line[0, 0], p[0], line[-1, 0]) 431 | if point_sorted_line[0, 0] <= p[0] <= point_sorted_line[-1, 0]: 432 | num_p += 1 433 | 434 | # If num_p is greater than or equal to min_lines, then add p to representative_points 435 | if num_p >= min_lines: 436 | # Compute the average y-value of all lines that contain the x-value of p 437 | y_avg = 0 438 | for line in rotated_lines: 439 | point_sorted_line = line[line[:, 0].argsort()] 440 | if point_sorted_line[0, 0] <= p[0] <= point_sorted_line[-1, 0]: 441 | y_avg += (point_sorted_line[0, 1] + point_sorted_line[-1, 1]) / 2 442 | # print((point_sorted_line[0, 1] + point_sorted_line[-1, 1]) / 2) 443 | # y_avg += line[np.argmin(np.abs(line[:, 0] - p[0])), 1] 444 | y_avg /= num_p 445 | # Add the p and its average y-value to representative_points 446 | representative_points.append(np.array([p[0], y_avg])) 447 | 448 | # Early return if there are no representative points 449 | if len(representative_points) == 0: 450 | warnings.warn("WARNING: No representative points were found.") 451 | return np.array([]) 452 | 453 | # Undo the rotation for the generated representative points 454 | representative_points = np.array(representative_points) 455 | representative_points = np.matmul(representative_points, np.linalg.inv(rotation_matrix).T) 456 | 457 | return representative_points 458 | 459 | 460 | def traclus(trajectories, max_eps=None, min_samples=10, directional=True, use_segments=True, clustering_algorithm=OPTICS, mdl_weights=[1,1,1], d_weights=[1,1,1], progress_bar=False): 461 | """ 462 | Trajectory Clustering Algorithm 463 | """ 464 | # Ensure that the trajectories are a list of numpy arrays of shape (n, 2) 465 | if not isinstance(trajectories, list): 466 | raise TypeError("Trajectories must be a list") 467 | for trajectory in trajectories: 468 | if not isinstance(trajectory, np.ndarray): 469 | raise TypeError("Trajectories must be a list of numpy arrays") 470 | elif len(trajectory.shape) != 2: 471 | raise ValueError("Trajectories must be a list of numpy arrays of shape (n, 2)") 472 | elif trajectory.shape[1] != 2: 473 | raise ValueError("Trajectories must be a list of numpy arrays of shape (n, 2)") 474 | 475 | # Partition the trajectories 476 | if progress_bar: 477 | print("Partitioning trajectories...") 478 | partitions = [] 479 | i = 0 480 | for trajectory in trajectories: 481 | if progress_bar: 482 | print(f"\rTrajectory {i + 1}/{len(trajectories)}", end='') 483 | i += 1 484 | partitions.append(partition(trajectory, directional=directional, progress_bar=False, w_perpendicular=mdl_weights[0], w_angular=mdl_weights[2])) 485 | if progress_bar: 486 | print() 487 | 488 | # Get the segments for each partition 489 | segments = [] 490 | if use_segments: 491 | if progress_bar: 492 | print("Converting partitioned trajectories to segments...") 493 | i = 0 494 | for parts in partitions: 495 | if progress_bar: 496 | print(f"\rPartition {i + 1}/{len(parts)}", end='') 497 | segments += partition2segments(parts) 498 | else: 499 | segments = partitions 500 | 501 | # Get distance matrix 502 | dist_matrix = get_distance_matrix(segments, directional=directional, w_perpendicular=d_weights[0], w_parallel=d_weights[1], w_angular=d_weights[2], progress_bar=progress_bar) 503 | 504 | # Group the partitions 505 | if progress_bar: 506 | print("Grouping partitions...") 507 | clusters = [] 508 | clustering_model = None 509 | if max_eps is not None: 510 | clustering_model = clustering_algorithm(max_eps=max_eps, min_samples=min_samples) 511 | else: 512 | clustering_model = clustering_algorithm(min_samples=min_samples) 513 | cluster_assignments = clustering_model.fit_predict(dist_matrix) 514 | for c in range(min(cluster_assignments), max(cluster_assignments) + 1): 515 | clusters.append([segments[i] for i in range(len(segments)) if cluster_assignments[i] == c]) 516 | 517 | if progress_bar: 518 | print() 519 | 520 | # Get the representative trajectories 521 | if progress_bar: 522 | print("Getting representative trajectories...") 523 | representative_trajectories = [] 524 | for cluster in clusters: 525 | representative_trajectories.append(get_representative_trajectory(cluster)) 526 | if progress_bar: 527 | print() 528 | 529 | return partitions, segments, dist_matrix, clusters, cluster_assignments, representative_trajectories 530 | 531 | # Create the script version that takes in a file path for inputs 532 | if __name__ == "__main__": 533 | # Parse the arguments 534 | parser = argparse.ArgumentParser(description="Trajectory Clustering Algorithm") 535 | parser.add_argument("input_file", help="The input file path (pickle format)") 536 | parser.add_argument("output_file", help="The output file path (pickle format)") 537 | parser.add_argument("-e", "--eps", help="The epsilon value for the clustering algorithm", type=float, default=2) 538 | parser.add_argument("-m", "--min_samples", help="The minimum samples value for the clustering algorithm", type=int, default=3) 539 | parser.add_argument("-p", "--progress_bar", help="Show the progress bar", action="store_true") 540 | args = parser.parse_args() 541 | 542 | # Load the trajectories 543 | trajectories = load_trajectories(args.input_file) 544 | 545 | # Run the TraClus algorithm 546 | partitions, segments, dist_matrix, clusters, cluster_assignments, representative_trajectories = traclus(trajectories, eps=args.eps, min_samples=args.min_samples, progress_bar=args.progress_bar) 547 | 548 | # Save the results 549 | save_results(args.output_file, trajectories, partitions, segments, dist_matrix, clusters, cluster_assignments, representative_trajectories) --------------------------------------------------------------------------------