├── .Rbuildignore ├── .github ├── FUNDING.yml └── workflows │ └── R-CMD-check.yaml ├── .gitignore ├── DESCRIPTION ├── LICENSE ├── NAMESPACE ├── R ├── RcppExports.R └── parDist.R ├── README.md ├── inst └── NEWS.Rd ├── man └── parDist.Rd ├── src ├── BinaryCount.h ├── CPPLINT.cfg ├── DistanceBinary.h ├── DistanceDTWFactory.cpp ├── DistanceDTWFactory.h ├── DistanceDTWGeneric.h ├── DistanceDist.h ├── DistanceFactory.cpp ├── DistanceFactory.h ├── IDistance.h ├── Makevars ├── Makevars.win ├── RcppExports.cpp ├── StepPattern.h ├── Util.cpp ├── Util.h └── parallelDist.cpp ├── tests ├── testthat.R └── testthat │ ├── helper.R │ ├── testMatrixCustomDistances.R │ ├── testMatrixDTWDistances.R │ ├── testMatrixDistances.R │ ├── testMatrixListDTWDistances.R │ └── testMatrixListDistances.R └── vignettes ├── .gitignore ├── parallelDist.Rnw └── parallelDist.bib /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^misc$ 3 | LICENSE 4 | .github 5 | CPPLINT.cfg 6 | ^src\CPPLINT.cfg 7 | ^\.Rproj\.user$ 8 | .vscode 9 | install.sh -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: alexeckert 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: alexeckert 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.github/workflows/R-CMD-check.yaml: -------------------------------------------------------------------------------- 1 | on: 2 | workflow_dispatch: 3 | push: 4 | branches: 5 | - master 6 | pull_request: 7 | branches: 8 | - master 9 | 10 | name: R-CMD-check 11 | 12 | # Increment this version when we want to clear cache 13 | env: 14 | cache-version: v4 15 | R_RELEASE_VERSION: "release" 16 | R_TEST_OS: "ubuntu-20.04" 17 | 18 | jobs: 19 | R-CMD-check: 20 | runs-on: ${{ matrix.config.os }} 21 | 22 | name: ${{ matrix.config.os }} (${{ matrix.config.r }}) 23 | env: 24 | R_KEEP_PKG_SOURCE: yes 25 | R_REMOTES_NO_ERRORS_FROM_WARNINGS: true 26 | RSPM: ${{ matrix.config.rspm }} 27 | # don't treat missing suggested packages as error 28 | _R_CHECK_FORCE_SUGGESTS_: false 29 | # Some packages might unavailable on the older versions, so let's ignore xref warnings 30 | _R_CHECK_RD_XREFS_: ${{ matrix.config.xref }} 31 | # Runs vdiffr test only on the latest version of R 32 | VDIFFR_RUN_TESTS: ${{ matrix.config.vdiffr }} 33 | VDIFFR_LOG_PATH: "../vdiffr.Rout.fail" 34 | strategy: 35 | fail-fast: false 36 | matrix: 37 | config: 38 | - { os: windows-latest, r: "release", xref: true } 39 | - { os: macOS-latest, r: "release", xref: true } 40 | - { 41 | os: "ubuntu-20.04", 42 | r: "devel", 43 | vdiffr: false, 44 | xref: true, 45 | http-user-agent: 'release', 46 | rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest", 47 | } 48 | - { 49 | os: "ubuntu-20.04", 50 | r: "release", 51 | vdiffr: true, 52 | xref: true, 53 | rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest", 54 | } 55 | steps: 56 | - uses: actions/checkout@v2 57 | 58 | - uses: r-lib/actions/setup-pandoc@v2 59 | 60 | - uses: r-lib/actions/setup-r@v2 61 | with: 62 | r-version: ${{ matrix.config.r }} 63 | http-user-agent: ${{ matrix.config.http-user-agent }} 64 | use-public-rspm: true 65 | 66 | - uses: r-lib/actions/setup-tinytex@v2 67 | - name: Install tlmgr 68 | run: tlmgr install ly1 mathdesign charter microtype ae grfext 69 | 70 | - name: Query dependencies 71 | run: | 72 | install.packages('remotes') 73 | saveRDS(remotes::dev_package_deps(dependencies = TRUE), "depends.Rds", version = 2) 74 | shell: Rscript {0} 75 | 76 | - name: Cache R packages 77 | if: runner.os != 'Windows' 78 | uses: actions/cache@v1 79 | with: 80 | path: ${{ env.R_LIBS_USER }} 81 | key: ${{ env.cache-version }}-${{ runner.os }}-r-${{ matrix.config.r }}-${{ hashFiles('depends.Rds') }} 82 | restore-keys: ${{ env.cache-version }}-${{ runner.os }}-r-${{ matrix.config.r }}- 83 | 84 | - name: Install system dependencies on Linux 85 | if: runner.os == 'Linux' 86 | run: | 87 | sudo apt-get install -y libcurl4-openssl-dev 88 | while read -r cmd 89 | do 90 | eval sudo $cmd 91 | done < <(Rscript -e 'writeLines(remotes::system_requirements("ubuntu", "20.04"))') 92 | 93 | - name: Install system dependencies on macOS 94 | if: runner.os == 'macOS' 95 | run: | 96 | # XQuartz is needed by vdiffr 97 | brew install --cask xquartz 98 | # Use only binary packages 99 | echo 'options(pkgType = "binary")' >> ~/.Rprofile 100 | 101 | - name: Install package dependencies 102 | run: | 103 | remotes::install_deps(dependencies = TRUE) 104 | remotes::install_cran("rcmdcheck") 105 | shell: Rscript {0} 106 | 107 | - name: Check 108 | run: rcmdcheck::rcmdcheck(args = "--no-manual", error_on = "warning", check_dir = "check") 109 | shell: Rscript {0} 110 | 111 | - name: Upload check results 112 | if: failure() 113 | uses: actions/upload-artifact@master 114 | with: 115 | name: ${{ runner.os }}-r${{ matrix.config.r }}-results 116 | path: check 117 | 118 | - name: Install test dependencies 119 | if: matrix.config.os == env.R_TEST_OS && matrix.config.r == env.R_RELEASE_VERSION 120 | run: | 121 | remotes::install_cran("covr") 122 | shell: Rscript {0} 123 | 124 | - name: Test coverage 125 | if: matrix.config.os == env.R_TEST_OS && matrix.config.r == env.R_RELEASE_VERSION 126 | run: | 127 | R CMD INSTALL . 128 | Rscript -e 'covr::codecov()' 129 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | .Ruserdata 5 | src/*.o 6 | src/*.so 7 | src/*.dll 8 | src-*/ 9 | -.Rproj.user 10 | *.Rproj 11 | misc/* 12 | .vscode/settings.json 13 | src/symbols.rds 14 | ..Rcheck/ 15 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: parallelDist 2 | Type: Package 3 | Title: Parallel Distance Matrix Computation using Multiple Threads 4 | Version: 0.2.6 5 | Author: Alexander Eckert [aut, cre], Lucas Godoy [ctb], Srikanth KS [ctb] 6 | Authors@R: c( 7 | person("Alexander", "Eckert", role = c("aut", "cre"), email = "info@alexandereckert.com"), 8 | person("Lucas", "Godoy", role = "ctb", email = "lucasdac.godoy@gmail.com"), 9 | person("Srikanth", "KS", role = "ctb", email = "sri.teach@gmail.com") 10 | ) 11 | Maintainer: Alexander Eckert 12 | Description: A fast parallelized alternative to R's native 'dist' function to 13 | calculate distance matrices for continuous, binary, and multi-dimensional 14 | input matrices, which supports a broad variety of 41 predefined distance 15 | functions from the 'stats', 'proxy' and 'dtw' R packages, as well as user- 16 | defined functions written in C++. For ease of use, the 'parDist' function 17 | extends the signature of the 'dist' function and uses the same parameter 18 | naming conventions as distance methods of existing R packages. The package 19 | is mainly implemented in C++ and leverages the 'RcppParallel' package to 20 | parallelize the distance computations with the help of the 'TinyThread' 21 | library. Furthermore, the 'Armadillo' linear algebra library is used for 22 | optimized matrix operations during distance calculations. The curiously 23 | recurring template pattern (CRTP) technique is applied to avoid virtual 24 | functions, which improves the Dynamic Time Warping calculations while 25 | the implementation stays flexible enough to support different DTW step 26 | patterns and normalization methods. 27 | License: GPL (>= 2) 28 | URL: https://github.com/alexeckert/parallelDist, https://www.alexandereckert.com/projects/#r-packages 29 | BugReports: https://github.com/alexeckert/parallelDist/issues 30 | NeedsCompilation: yes 31 | Depends: 32 | R (>= 3.0.2) 33 | Imports: 34 | Rcpp (>= 0.12.6), 35 | RcppParallel (>= 4.3.20) 36 | LinkingTo: Rcpp, 37 | RcppParallel, 38 | RcppArmadillo 39 | SystemRequirements: C++11 40 | Suggests: 41 | dtw, 42 | ggplot2, 43 | proxy, 44 | testthat, 45 | RcppArmadillo, 46 | RcppXPtrUtils 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | useDynLib(parallelDist, .registration=TRUE) 2 | importFrom(Rcpp, evalCpp) 3 | importFrom(RcppParallel, RcppParallelLibs) 4 | export(parallelDist, parDist) 5 | -------------------------------------------------------------------------------- /R/RcppExports.R: -------------------------------------------------------------------------------- 1 | # Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | cpp_parallelDistVec <- function(dataList, attrs, arguments) { 5 | .Call(`_parallelDist_cpp_parallelDistVec`, dataList, attrs, arguments) 6 | } 7 | 8 | cpp_parallelDistMatrixVec <- function(dataMatrix, attrs, arguments) { 9 | .Call(`_parallelDist_cpp_parallelDistMatrixVec`, dataMatrix, attrs, arguments) 10 | } 11 | 12 | -------------------------------------------------------------------------------- /R/parDist.R: -------------------------------------------------------------------------------- 1 | ## parDist.R 2 | ## 3 | ## Copyright (C) 2017, 2021 Alexander Eckert 4 | ## 5 | ## This file is part of parallelDist. 6 | ## 7 | ## parallelDist is free software: you can redistribute it and/or modify it 8 | ## under the terms of the GNU General Public License as published by 9 | ## the Free Software Foundation, either version 2 of the License, or 10 | ## (at your option) any later version. 11 | ## 12 | ## parallelDist is distributed in the hope that it will be useful, but 13 | ## WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ## GNU General Public License for more details. 16 | ## 17 | ## You should have received a copy of the GNU General Public License 18 | ## along with parallelDist. If not, see . 19 | 20 | # 21 | # Calculates distance matrices in parallel 22 | # 23 | parDist <- parallelDist <- function(x, method = "euclidean", diag = FALSE, upper = FALSE, threads = NULL, ...) { 24 | METHODS <- c( 25 | "bhjattacharyya", "bray", "canberra", "chord", "divergence", 26 | "dtw", "euclidean", "fJaccard", "geodesic", "hellinger", 27 | "kullback", "mahalanobis", "manhattan", "maximum", "minkowski", 28 | "podani", "soergel", "wave", "whittaker", 29 | "binary", "braun-blanquet", "dice", "fager", "faith", 30 | "hamman", "kulczynski1", "kulczynski2", "michael", "mountford", 31 | "mozley", "ochiai", "phi", "russel", "simple matching", 32 | "simpson", "stiles", "tanimoto", "yule", "yule2", "cosine", 33 | "hamming", 34 | "custom" 35 | ) # w/o "levenshtein" 36 | methodIdx <- pmatch(method, METHODS) 37 | if (is.na(methodIdx)) { 38 | stop("Invalid distance method") 39 | } 40 | method <- METHODS[methodIdx] 41 | 42 | arguments <- list(...) 43 | # set step pattern (for dtw distances) 44 | step.pattern.name <- getStepPatternName(arguments) 45 | if (!any(is.na(step.pattern.name))) { 46 | arguments[["step.pattern"]] <- step.pattern.name[1] 47 | } 48 | 49 | # check funct argument for custom distance measure 50 | if (method == "custom") { 51 | funcPtr <- arguments[["func"]] 52 | if (is.null(funcPtr)) { 53 | stop("Parameter 'func' is missing.") 54 | } 55 | checkPtr(funcPtr) 56 | } 57 | 58 | # set number of threads 59 | if (!is.null(threads)) { 60 | RcppParallel::setThreadOptions(numThreads = threads) 61 | } 62 | 63 | N <- ifelse(is.list(x), length(x), nrow(x)) 64 | attrs <- list( 65 | Size = N, Labels = dimnames(x)[[1L]], Diag = diag, Upper = upper, 66 | method = METHODS[methodIdx], call = match.call(), class = "dist" 67 | ) 68 | 69 | # check data type 70 | if (is.list(x) && inherits(x, "list")) { 71 | methods.first.row.only <- c("chord", "geodesic", "podani") 72 | if (method %in% methods.first.row.only) { 73 | warning("Only first row of each matrix is used for distance calculation.") 74 | } 75 | return(.Call("_parallelDist_cpp_parallelDistVec", PACKAGE = "parallelDist", x, attrs, arguments = arguments)) 76 | } else { 77 | if (is.matrix(x)) { 78 | return(.Call("_parallelDist_cpp_parallelDistMatrixVec", PACKAGE = "parallelDist", x, attrs, arguments = arguments)) 79 | } else { 80 | stop("x must be a matrix or a list of matrices.") 81 | } 82 | } 83 | } 84 | 85 | getType <- function(code) { 86 | tokenize <- strsplit(code, "[[:space:]]*(\\(|\\)){1}[[:space:]]*")[[1]] 87 | tokens <- strsplit(tokenize[[1]], "[[:space:]]+")[[1]] 88 | tokens <- tokens[seq_len(length(tokens) - 1)] 89 | paste(tokens[tokens != ""], collapse = " ") 90 | } 91 | 92 | getStepPatternName <- function(arguments) { 93 | step.pattern.name <- NA 94 | supported.patterns.names <- c( 95 | "asymmetric", "asymmetricP0", "asymmetricP05", "asymmetricP1", "asymmetricP2", 96 | "symmetric1", "symmetric2", "symmetricP0", "symmetricP05", "symmetricP1", "symmetricP2" 97 | ) 98 | sp.candidate <- arguments[["step.pattern"]] 99 | 100 | if (!is.null(sp.candidate)) { 101 | if (class(sp.candidate) == "stepPattern" && requireNamespace("dtw", quietly = TRUE)) { 102 | supported.patterns <- list( 103 | dtw::asymmetric, dtw::asymmetricP0, dtw::asymmetricP05, dtw::asymmetricP1, dtw::asymmetricP2, 104 | dtw::symmetric1, dtw::symmetric2, dtw::symmetricP0, dtw::symmetricP05, dtw::symmetricP1, dtw::symmetricP2 105 | ) 106 | # check if step pattern is supported (using object) 107 | sp.found <- sapply(supported.patterns, FUN = function(x) { 108 | if (identical(dim(x), dim(sp.candidate))) { 109 | all(x == sp.candidate) 110 | } else { 111 | FALSE 112 | } 113 | }) 114 | } else { 115 | if (is.character(sp.candidate)) { 116 | # check if step pattern is supported (using name) 117 | sp.found <- supported.patterns.names == sp.candidate 118 | } 119 | } 120 | if (any(sp.found)) { 121 | step.pattern.name <- supported.patterns.names[which(sp.found)] 122 | } else { 123 | stop("Step pattern is not supported.") 124 | } 125 | } 126 | step.pattern.name 127 | } 128 | 129 | checkPtr <- function(ptr) { 130 | stopifnot(inherits(ptr, "XPtr")) 131 | 132 | actualReturnType <- attr(ptr, "type") 133 | expectedReturnType <- "double" 134 | 135 | actualArgTypes <- sapply(attr(ptr, "args"), getType, USE.NAMES = FALSE) 136 | expectedArgTypes <- rep("const arma::mat&", 2) 137 | 138 | msg <- character() 139 | # check return type 140 | if (actualReturnType != expectedReturnType) { 141 | msg <- paste(c(msg, paste0(" Wrong return type '", actualReturnType, "', should be '", expectedReturnType, "'.")), collapse = "\n") 142 | } 143 | # check number of arguments 144 | if (length(actualArgTypes) != 2) { 145 | msg <- paste(c(msg, paste0(" Wrong number of arguments ('", length(actualArgTypes), "'), should be 2.")), collapse = "\n") 146 | } else { 147 | # check argument types 148 | for (i in which(!(expectedArgTypes == actualArgTypes))) { 149 | msg <- paste(c(msg, paste0(" Wrong argument type '", actualArgTypes[[i]], "', should be '", expectedArgTypes[[i]], "'.")), collapse = "\n") 150 | } 151 | } 152 | 153 | if (length(msg)) { 154 | stop("Bad XPtr signature:\n", msg) 155 | } 156 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## parallelDist [![CRAN](http://www.r-pkg.org/badges/version/parallelDist)](https://CRAN.R-project.org/package=parallelDist) [![codecov](https://codecov.io/gh/alexeckert/parallelDist/branch/master/graph/badge.svg)](https://app.codecov.io/gh/alexeckert/parallelDist) [![R-CMD-check](https://github.com/alexeckert/parallelDist/actions/workflows/R-CMD-check.yaml/badge.svg?branch=master)](https://github.com/alexeckert/parallelDist/actions/workflows/R-CMD-check.yaml) 2 | 3 | ### Introduction 4 | 5 | The [parallelDist](https://CRAN.R-project.org/package=parallelDist) package provides a fast parallelized alternative to R's native 'dist' function to calculate distance matrices for continuous, binary, and multi-dimensional input matrices and offers a broad variety of predefined distance functions from the 'stats', 'proxy' and 'dtw' R packages, as well as support for user-defined distance functions written in C++. For ease of use, the 'parDist' function extends the signature of the 'dist' function and uses the same parameter naming conventions as distance methods of existing R packages. Currently 41 different distance methods are supported. 6 | 7 | The package is mainly implemented in C++ and leverages the '[Rcpp](https://CRAN.R-project.org/package=Rcpp)' and '[RcppParallel](https://CRAN.R-project.org/package=RcppParallel)' package to parallelize the distance computations with the help of the 'TinyThread' library. Furthermore, the Armadillo linear algebra library is used via '[RcppArmadillo](https://CRAN.R-project.org/package=RcppArmadillo)' for optimized matrix operations for distance calculations. The curiously recurring template pattern (CRTP) technique is applied to avoid virtual functions, which improves the Dynamic Time Warping calculations while keeping the implementation flexible enough to support different step patterns and normalization methods. 8 | 9 | ### Documentation and Usage Examples 10 | 11 | Usage examples and performance benchmarks can be found in the included vignette. 12 | 13 | Details about the 41 supported distance methods and their parameters are described on the help page of the 'parDist' function. The help page can be displayed with the following command: 14 | 15 | ```R 16 | ?parDist 17 | ``` 18 | 19 | #### User-defined distance functions 20 | 21 | Since version 0.2.0, parallelDist supports fast parallel distance matrix computations for user-defined distance functions written in C++. 22 | 23 | A user-defined function needs to have the following signature (also see the [Armadillo documentation](http://arma.sourceforge.net/docs.html)): 24 | 25 | ```Cpp 26 | double customDist(const arma::mat &A, const arma::mat &B) 27 | ``` 28 | 29 | Defining and compiling the function, as well as creating an external pointer to the user-defined function can easily be achieved with the *cppXPtr* function of the '[RcppXPtrUtils](https://CRAN.R-project.org/package=RcppXPtrUtils)' package. The following code shows a full example of defining and using a user-defined euclidean distance function: 30 | 31 | ```R 32 | # RcppArmadillo is used as dependency 33 | library(RcppArmadillo) 34 | # RcppXPtrUtils is used for simple handling of C++ external pointers 35 | library(RcppXPtrUtils) 36 | 37 | # compile user-defined function and return pointer (RcppArmadillo is used as dependency) 38 | euclideanFuncPtr <- cppXPtr("double customDist(const arma::mat &A, const arma::mat &B) { return sqrt(arma::accu(arma::square(A - B))); }", 39 | depends = c("RcppArmadillo")) 40 | 41 | # distance matrix for user-defined euclidean distance function 42 | # (note that method is set to "custom") 43 | parDist(matrix(1:16, ncol=2), method="custom", func = euclideanFuncPtr) 44 | ``` 45 | 46 | More information can be found in the vignette and the help pages. 47 | 48 | ### Installation 49 | 50 | `parallelDist` is available on [CRAN](https://CRAN.R-project.org/package=parallelDist) and can be installed with the following command: 51 | 52 | ```R 53 | install.packages("parallelDist") 54 | ``` 55 | 56 | The current version from github can be installed using the 'devtools' package: 57 | 58 | ```R 59 | library(devtools) 60 | install_github("alexeckert/parallelDist") 61 | ``` 62 | 63 | ### Authors 64 | 65 | Alexander Eckert 66 | 67 | ### License 68 | 69 | GPL (>= 2) 70 | -------------------------------------------------------------------------------- /inst/NEWS.Rd: -------------------------------------------------------------------------------- 1 | \name{NEWS} 2 | \title{NEWS for Package \pkg{parallelDist}} 3 | \section{Changes in parallelDist version 0.2.6}{ 4 | \itemize{ 5 | \item Remove LazyData from DESCRIPTION 6 | \item Switch vignette font 7 | } 8 | } 9 | \section{Changes in parallelDist version 0.2.5}{ 10 | \itemize{ 11 | \item Reflect changes in proxy 0.4-26: Change coercion function for cosine similarity to distance to 1-x instead of 1-abs(x) 12 | } 13 | } 14 | \section{Changes in parallelDist version 0.2.4}{ 15 | \itemize{ 16 | \item Fixed build on Solaris using explicit casts. 17 | } 18 | } 19 | \section{Changes in parallelDist version 0.2.3}{ 20 | \itemize{ 21 | \item Preserve label attribute of dist class. 22 | \item Allow double values for Minkowski distance. 23 | \item Added hamming distance (contributed by Srikanth KS). 24 | \item Added cosine similarity (contributed by Lucas Godoy). 25 | } 26 | } 27 | \section{Changes in parallelDist version 0.2.2}{ 28 | \itemize{ 29 | \item Fixed DTW calculation errors for matrices of different length when using multiple threads. 30 | \item Reduced number of tests executed on CRAN. 31 | } 32 | } 33 | \section{Changes in parallelDist version 0.2.1}{ 34 | \itemize{ 35 | \item Fixed vignette generation errors for upcoming R releases. 36 | \item Removed highlight as vignette builder and dependency. 37 | } 38 | } 39 | \section{Changes in parallelDist version 0.2.0}{ 40 | \itemize{ 41 | \item Added support for user-defined distance functions. 42 | \item Added R 3.0.2 as requirement. 43 | \item Fixed clang UBSAN downcast warning. 44 | } 45 | } 46 | \section{Changes in parallelDist version 0.1.1}{ 47 | \itemize{ 48 | \item Missing include statement of the string library in Utility.h 49 | caused compile error when clang++ was used. 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /man/parDist.Rd: -------------------------------------------------------------------------------- 1 | \name{parDist} 2 | \alias{parDist} 3 | \alias{parallelDist} 4 | \title{Parallel Distance Matrix Computation using multiple Threads} 5 | \usage{ 6 | parDist(x, method = "euclidean", diag = FALSE, upper = FALSE, threads = NULL, ...) 7 | parallelDist(x, method = "euclidean", diag = FALSE, upper = FALSE, threads = NULL, ...) 8 | } 9 | \arguments{ 10 | \item{x}{a numeric matrix (each row is one series) or list of numeric matrices for multidimensional series (each matrix is one series, a row is a dimension of a series)} 11 | 12 | \item{method}{the distance measure to be used. A list of all available distance methods can be found in the details section below.} 13 | 14 | \item{diag}{logical value indicating whether the diagonal of the distance matrix should be printed by print.dist.} 15 | 16 | \item{upper}{logical value indicating whether the upper triangle of the distance matrix should be printed by print.dist} 17 | 18 | \item{threads}{number of cpu threads for calculating a distance matrix. Default is the maximum amount of cpu threads available on the system.} 19 | 20 | \item{...}{additional parameters which will be passed to the distance methods. See details section below.} 21 | 22 | } 23 | \description{ 24 | Calculates distance matrices in parallel using multiple threads. Supports 41 predefined distance measures and user-defined distance functions. 25 | } 26 | 27 | \details{ 28 | \subsection{User-defined distance functions}{ 29 | \describe{ 30 | \item{\code{custom}}{ 31 | Defining and compiling a user-defined C++ distance function, as well as creating an external pointer to the function can easily be achieved with the \code{\link[RcppXPtrUtils]{cppXPtr}} function of the \pkg{RcppXPtrUtils} package. The resulting \verb{Xptr} external pointer object needs to be passed to \code{\link[parallelDist]{parDist}} using the \code{func} parameter. 32 | 33 | Parameters: 34 | \itemize{ 35 | \item{ 36 | \describe{ 37 | \item{\code{func} (Xptr)}{External pointer to a user-defined distance function with the following signature: \cr \code{double customDist(const arma::mat &A, const arma::mat &B)} \cr Note that the return value must be a \verb{double} and the two parameters must be of type \verb{const arma::mat ¶m}. \cr \cr 38 | More information about the Armadillo library can be found at \url{http://arma.sourceforge.net/docs.html} or as part of the documentation of the \pkg{RcppArmadillo} package.} 39 | } 40 | } 41 | } 42 | An exemplary definition and usage of an user-defined euclidean distance function can be found in the examples section below. 43 | } 44 | } 45 | } 46 | 47 | \subsection{Available predefined distance measures (written for two vectors \eqn{x} and \eqn{y})}{ 48 | 49 | \bold{Distance methods for continuous input variables} 50 | 51 | \describe{ 52 | \item{\code{bhjattacharyya}}{ 53 | The Bhjattacharyya distance.\cr Type: continuous\cr Formula: \eqn{sqrt(sum_i (sqrt(x_i) - sqrt(y_i))^2))}.\cr Details: See \command{pr_DB$get_entry("bhjattacharyya")} in \pkg{proxy}. 54 | } 55 | \item{\code{bray}}{ 56 | The Bray/Curtis dissimilarity.\cr Type: continuous\cr Formula: \eqn{sum_i |x_i - y_i| / sum_i (x_i + y_i)}.\cr Details: See \command{pr_DB$get_entry("bray")} in \pkg{proxy}. 57 | } 58 | \item{\code{canberra}}{ 59 | The Canberra distance (with compensation for excluded components). Terms with zero numerator and denominator are omitted from the sum and treated as if the values were missing. \cr Type: continuous\cr Formula: \eqn{sum_i |x_i - y_i| / |x_i + y_i|}.\cr Details: See \command{pr_DB$get_entry("canberra")} in \pkg{proxy}. 60 | } 61 | \item{\code{chord}}{ 62 | The Chord distance.\cr Type: continuous\cr Formula: \eqn{sqrt(2 * (1 - xy / sqrt(xx * yy)))}.\cr Details: See \command{pr_DB$get_entry("chord")} in \pkg{proxy}. 63 | } 64 | \item{\code{divergence}}{ 65 | The Divergence distance.\cr Type: continuous\cr Formula: \eqn{sum_i (x_i - y_i)^2 / (x_i + y_i)^2}.\cr Details: See \command{pr_DB$get_entry("divergence")} in \pkg{proxy}. 66 | } 67 | 68 | \item{\code{dtw}}{Implementation of a multi-dimensional Dynamic Time Warping algorithm.\cr Type: continuous\cr Formula: Euclidean distance \eqn{sqrt(sum_i (x_i - y_i)^2)}.\cr 69 | Parameters: 70 | \itemize{ 71 | \item{ 72 | \describe{ 73 | \item{\code{window.size} (integer, optional)}{Size of the window of the Sakoe-Chiba band. If the absolute length difference of two series x and y is larger than the window.size, the window.size is set to the length difference.} 74 | } 75 | } 76 | \item{ 77 | \describe{ 78 | \item{\code{norm.method} (character, optional)}{Normalization method for DTW distances. 79 | \itemize{ 80 | \item{\code{path.length} Normalization with the length of the warping path.} 81 | \item{\code{n} Normalization with n. n is the length of series x.} 82 | \item{\code{n+m} Normalization with n + m. n is the length of series x, m is the length of series y.} 83 | } 84 | } 85 | } 86 | } 87 | \item{ 88 | \describe{ 89 | \item{\code{step.pattern} (character or stepPattern of \pkg{dtw} package, default: \code{symmetric1})}{ 90 | The following step patterns of the \pkg{dtw} package are supported: 91 | 92 | \itemize{ 93 | \item{ 94 | \code{asymmetric} (Normalization hint: n) 95 | } 96 | \item{ 97 | \code{asymmetricP0} (Normalization hint: n) 98 | } 99 | \item{ 100 | \code{asymmetricP05} (Normalization hint: n) 101 | } 102 | \item{ 103 | \code{asymmetricP1} (Normalization hint: n) 104 | } 105 | \item{ 106 | \code{asymmetricP2} (Normalization hint: n) 107 | } 108 | \item{ 109 | \code{symmetric1} (Normalization hint: path.length) 110 | } 111 | \item{ 112 | \code{symmetric2} or \code{symmetricP0} (Normalization hint: n+m) 113 | } 114 | \item{ 115 | \code{symmetricP05} (Normalization hint: n+m) 116 | } 117 | \item{ 118 | \code{symmetricP1} (Normalization hint: n+m) 119 | } 120 | \item{ 121 | \code{symmetricP2} (Normalization hint: n+m) 122 | } 123 | } 124 | For a detailed description see \code{\link[dtw]{stepPattern}} of the \pkg{dtw} package. 125 | } 126 | } 127 | } 128 | } 129 | } 130 | 131 | \item{\code{euclidean}}{ 132 | The Euclidean distance/L_2-norm (with compensation for excluded components).\cr Type: continuous\cr Formula: \eqn{sqrt(sum_i (x_i - y_i)^2))}.\cr Details: See \command{pr_DB$get_entry("euclidean")} in \pkg{proxy}. 133 | } 134 | \item{\code{fJaccard}}{ 135 | The fuzzy Jaccard distance.\cr Type: binary\cr Formula: \eqn{sum_i (min{x_i, y_i}) / sum_i(max{x_i, y_i})}.\cr Details: See \command{pr_DB$get_entry("fJaccard")} in \pkg{proxy}. 136 | } 137 | \item{\code{geodesic}}{ 138 | The geoedesic distance, i.e. the angle between x and y.\cr Type: continuous\cr Formula: \eqn{arccos(xy / sqrt(xx * yy))}.\cr Details: See \command{pr_DB$get_entry("geodesic")} in \pkg{proxy}. 139 | } 140 | \item{\code{hellinger}}{ 141 | The Hellinger distance.\cr Type: continuous\cr Formula: \eqn{sqrt(sum_i (sqrt(x_i / sum_i x) - sqrt(y_i / sum_i y)) ^ 2)}.\cr Details: See \command{pr_DB$get_entry("hellinger")} in \pkg{proxy}. 142 | } 143 | \item{\code{kullback}}{ 144 | The Kullback-Leibler distance.\cr Type: continuous\cr Formula: \eqn{sum_i [x_i * log((x_i / sum_j x_j) / (y_i / sum_j y_j)) / sum_j x_j)]}.\cr Details: See \command{pr_DB$get_entry("kullback")} in \pkg{proxy}. 145 | } 146 | \item{\code{mahalanobis}}{ 147 | The Mahalanobis distance. The Variance-Covariance-Matrix is estimated from the input data if unspecified.\cr Type: continuous\cr Formula: \eqn{sqrt((x - y) Sigma^(-1) (x - y))}.\cr Parameters: 148 | \itemize{ 149 | \item{ 150 | \describe{ 151 | \item{\code{cov} (numeric matrix, optional)}{The covariance matrix (p x p) of the distribution.} 152 | } 153 | } 154 | \item{ 155 | \describe{ 156 | \item{\code{inverted} (logical, optional)}{If TRUE, cov is supposed to contain the inverse of the covariance matrix.} 157 | } 158 | } 159 | } 160 | Details: See \command{pr_DB$get_entry("mahalanobis")} in \pkg{proxy} or \command{mahalanobis} in \pkg{stats}. 161 | } 162 | \item{\code{manhattan}}{ 163 | The Manhattan/City-Block/Taxi/L_1-norm distance (with compensation for excluded components).\cr Type: continuous\cr Formula: \eqn{sum_i |x_i - y_i|}.\cr Details: See \command{pr_DB$get_entry("manhattan")} in \pkg{proxy}. 164 | } 165 | \item{\code{maximum}}{ 166 | The Maximum/Supremum/Chebyshev distance.\cr Type: continuous\cr Formula: \eqn{max_i |x_i - y_i|}.\cr Details: See \command{pr_DB$get_entry("maximum")} in \pkg{proxy}. 167 | } 168 | \item{\code{minkowski}}{ 169 | The Minkowski distance/p-norm (with compensation for excluded components). \cr Type: continuous\cr Formula: \eqn{(sum_i (x_i - y_i)^p)^(1/p)}.\cr Parameters: 170 | \itemize{ 171 | \item{ 172 | \describe{ 173 | \item{\code{p} (double, optional)}{The \eqn{p}th root of the sum of the \eqn{p}th powers of the differences of the components.} 174 | } 175 | } 176 | } 177 | Details: See \command{pr_DB$get_entry("minkowski")} in \pkg{proxy}. 178 | } 179 | 180 | \item{\code{podani}}{ 181 | The Podany measure of discordance is defined on ranks with ties. In the formula, for two given objects x and y, n is the number of variables, a is is the number of pairs of variables ordered identically, b the number of pairs reversely ordered, c the number of pairs tied in both x and y (corresponding to either joint presence or absence), and d the number of all pairs of variables tied at least for one of the objects compared such that one, two, or thee scores are zero.\cr Type: continuous\cr Formula: \eqn{1 - 2 * (a - b + c - d) / (n * (n - 1))}.\cr Details: See \command{pr_DB$get_entry("podani")} in \pkg{proxy}. 182 | } 183 | \item{\code{soergel}}{ 184 | The Soergel distance.\cr Type: continuous\cr Formula: \eqn{sum_i |x_i - y_i| / sum_i max{x_i, y_i}}.\cr Details: See \command{pr_DB$get_entry("soergel")} in \pkg{proxy}. 185 | } 186 | \item{\code{wave}}{ 187 | The Wave/Hedges distance.\cr Type: continuous\cr Formula: \eqn{sum_i (1 - min(x_i, y_i) / max(x_i, y_i))}.\cr Details: See \command{pr_DB$get_entry("wave")} in \pkg{proxy}. 188 | } 189 | \item{\code{whittaker}}{ 190 | The Whittaker distance.\cr Type: continuous\cr Formula: \eqn{sum_i |x_i / sum_i x - y_i / sum_i y| / 2}.\cr Details: See \command{pr_DB$get_entry("whittaker")} in \pkg{proxy}. 191 | } 192 | } 193 | 194 | \bold{Distance methods for binary input variables} 195 | 196 | \emph{Notation:} 197 | \itemize{ 198 | \item a: number of (TRUE, TRUE) pairs 199 | \item b: number of (FALSE, TRUE) pairs 200 | \item c: number of (TRUE, FALSE) pairs 201 | \item d: number of (FALSE, FALSE) pairs 202 | } 203 | 204 | \emph{Note:} Similarities are converted to distances. 205 | 206 | \describe{ 207 | \item{\code{binary}}{ 208 | The Jaccard Similarity for binary data. It is the proportion of (TRUE, TRUE) pairs, but not considering (FALSE, FALSE) pairs.\cr Type: binary\cr Formula: \eqn{a / (a + b + c)}.\cr Details: See \command{pr_DB$get_entry("binary")} in \pkg{proxy}. 209 | } 210 | \item{\code{braun-blanquet}}{ 211 | The Braun-Blanquet similarity.\cr Type: binary\cr Formula: \eqn{a / max{(a + b), (a + c)}}.\cr Details: See \command{pr_DB$get_entry("braun-blanquet")} in \pkg{proxy}. 212 | } 213 | \item{\code{cosine}}{ 214 | The cosine similarity.\cr Type: continuous\cr Formula: \eqn{(a * b) / (|a|*|b|)}.\cr Details: See \command{pr_DB$get_entry("cosine")} in \pkg{proxy}. 215 | } 216 | \item{\code{dice}}{ 217 | The Dice similarity.\cr Type: binary\cr Formula: \eqn{2a / (2a + b + c)}.\cr Details: See \command{pr_DB$get_entry("dice")} in \pkg{proxy}. 218 | } 219 | \item{\code{fager}}{ 220 | The Fager / McGowan distance.\cr Type: binary\cr Formula: \eqn{a / sqrt((a + b)(a + c)) - sqrt(a + c) / 2}.\cr Details: See \command{pr_DB$get_entry("fager")} in \pkg{proxy}. 221 | } 222 | \item{\code{faith}}{ 223 | The Faith similarity.\cr Type: binary\cr Formula: \eqn{(a + d/2) / n}.\cr Details: See \command{pr_DB$get_entry("faith")} in \pkg{proxy}. 224 | } 225 | \item{\code{hamman}}{ 226 | The Hamman Matching similarity for binary data. It is the proportion difference of the concordant and discordant pairs.\cr Type: binary\cr Formula: \eqn{([a + d] - [b + c]) / n}.\cr Details: See \command{pr_DB$get_entry("hamman")} in \pkg{proxy}. 227 | } 228 | \item{\code{hamming}}{ 229 | The hamming distance between two vectors A and B is the fraction of positions where there is a mismatch. \cr Formula: \eqn{\textit{\# of }(A != B) / \textit{\# in A (or B)}} 230 | } 231 | \item{\code{kulczynski1}}{ 232 | Kulczynski similarity for binary data. Relates the (TRUE, TRUE) pairs to discordant pairs.\cr Type: binary\cr Formula: \eqn{a / (b + c)}.\cr Details: See \command{pr_DB$get_entry("kulczynski1")} in \pkg{proxy}. 233 | } 234 | \item{\code{kulczynski2}}{ 235 | Kulczynski similarity for binary data. Relates the (TRUE, TRUE) pairs to the discordant pairs.\cr Type: binary\cr Formula: \eqn{[a / (a + b) + a / (a + c)] / 2}.\cr Details: See \command{pr_DB$get_entry("kulczynski2")} in \pkg{proxy}. 236 | } 237 | \item{\code{michael}}{ 238 | The Michael similarity.\cr Type: binary\cr Formula: \eqn{4(ad - bc) / [(a + d)^2 + (b + c)^2]}.\cr Details: See \command{pr_DB$get_entry("michael")} in \pkg{proxy}. 239 | } 240 | \item{\code{mountford}}{ 241 | The Mountford similarity for binary data.\cr Type: binary\cr Formula: \eqn{2a / (ab + ac + 2bc)}.\cr Details: See \command{pr_DB$get_entry("mountford")} in \pkg{proxy}. 242 | } 243 | \item{\code{mozley}}{ 244 | The Mozley/Margalef similarity.\cr Type: binary\cr Formula: \eqn{an / (a + b)(a + c)}.\cr Details: See \command{pr_DB$get_entry("mozley")} in \pkg{proxy}. 245 | } 246 | \item{\code{ochiai}}{ 247 | The Ochiai similarity.\cr Type: binary\cr Formula: \eqn{a / sqrt[(a + b)(a + c)]}.\cr Details: See \command{pr_DB$get_entry("ochiai")} in \pkg{proxy}. 248 | } 249 | \item{\code{phi}}{ 250 | The Phi similarity (= Product-Moment-Correlation for binary variables).\cr Type: binary\cr Formula: \eqn{(ad - bc) / sqrt[(a + b)(c + d)(a + c)(b + d)]}.\cr Details: See \command{pr_DB$get_entry("phi")} in \pkg{proxy}. 251 | } 252 | \item{\code{russel}}{ 253 | The Russel/Raosimilarity for binary data. It is just the proportion of (TRUE, TRUE) pairs.\cr Type: binary\cr Formula: \eqn{a / n}.\cr Details: See \command{pr_DB$get_entry("russel")} in \pkg{proxy}. 254 | } 255 | \item{\code{simple matching}}{ 256 | The Simple Matching similarity for binary data. It is the proportion of concordant pairs.\cr Type: binary\cr Formula: \eqn{(a + d) / n}.\cr Details: See \command{pr_DB$get_entry("simple matching")} in \pkg{proxy}. 257 | } 258 | \item{\code{simpson}}{ 259 | The Simpson similarity.\cr Type: binary\cr Formula: \eqn{a / min{(a + b), (a + c)}}.\cr Details: See \command{pr_DB$get_entry("simpson")} in \pkg{proxy}. 260 | } 261 | \item{\code{stiles}}{ 262 | The Stiles similarity. Identical to the logarithm of Krylov's distance.\cr Type: binary\cr Formula: \eqn{log(n(|ad-bc| - 0.5n)^2 / [(a + b)(c + d)(a + c)(b + d)])}.\cr Details: See \command{pr_DB$get_entry("stiles")} in \pkg{proxy}. 263 | } 264 | \item{\code{tanimoto}}{ 265 | The Rogers/Tanimoto similarity for binary data. Similar to the simple matching coefficient, but putting double weight on the discordant pairs.\cr Type: binary\cr Formula: \eqn{(a + d) / (a + 2b + 2c + d)}.\cr Details: See \command{pr_DB$get_entry("tanimoto")} in \pkg{proxy}. 266 | } 267 | \item{\code{yule}}{ 268 | The Yule similarity.\cr Type: binary\cr Formula: \eqn{(ad - bc) / (ad + bc)}.\cr Details: See \command{pr_DB$get_entry("yule")} in \pkg{proxy}. 269 | } 270 | \item{\code{yule2}}{ 271 | The Yule similarity.\cr Type: binary\cr Formula: \eqn{(sqrt(ad) - sqrt(bc)) / (sqrt(ad) + sqrt(bc))}.\cr Details: See \command{pr_DB$get_entry("yule2")} in \pkg{proxy}. 272 | } 273 | } 274 | } 275 | } 276 | 277 | 278 | \value{ 279 | \code{parDist} returns an object of class \code{"dist"}. 280 | 281 | The lower triangle of the distance matrix stored by columns in a 282 | vector, say \code{do}. If \code{n} is the number of 283 | observations, i.e., \code{n <- attr(do, "Size")}, then 284 | for \eqn{i < j \le n}, the dissimilarity between (row) i and j is 285 | \code{do[n*(i-1) - i*(i-1)/2 + j-i]}. 286 | The length of the vector is \eqn{n*(n-1)/2}, i.e., of order \eqn{n^2}. 287 | 288 | The object has the following attributes (besides \code{"class"} equal 289 | to \code{"dist"}): 290 | \item{Size}{integer, the number of observations in the dataset.} 291 | \item{Labels}{optionally, contains the labels, if any, of the 292 | observations of the dataset.} 293 | \item{Diag, Upper}{logicals corresponding to the arguments \code{diag} 294 | and \code{upper} above, specifying how the object should be printed.} 295 | \item{call}{optionally, the \code{\link{call}} used to create the 296 | object.} 297 | \item{method}{optionally, the distance method used; resulting from 298 | \code{\link{parDist}()}, the (\code{\link{match.arg}()}ed) \code{method} 299 | argument.} 300 | } 301 | 302 | \examples{ 303 | \dontrun{ 304 | ## predefined distance functions 305 | # defining a matrix, where each row corresponds to one series 306 | sample.matrix <- matrix(c(1:100), ncol = 10) 307 | 308 | # euclidean distance 309 | parDist(x = sample.matrix, method = "euclidean") 310 | # minkowski distance with parameter p=2 311 | parDist(x = sample.matrix, method = "minkowski", p=2) 312 | # dynamic time warping distance 313 | parDist(x = sample.matrix, method = "dtw") 314 | # dynamic time warping distance normalized with warping path length 315 | parDist(x = sample.matrix, method = "dtw", norm.method="path.length") 316 | # dynamic time warping with different step pattern 317 | parDist(x = sample.matrix, method = "dtw", step.pattern="symmetric2") 318 | # dynamic time warping with window size constraint 319 | parDist(x = sample.matrix, method = "dtw", step.pattern="symmetric2", window.size=1) 320 | 321 | ## multi-dimensional distance functions using list of matrices 322 | # defining a list of matrices, where each list entry row corresponds to a two dimensional series 323 | tmp.mat <- matrix(c(1:40), ncol = 10) 324 | sample.matrix.list <- list(tmp.mat[1:2,], tmp.mat[3:4,]) 325 | 326 | # multi-dimensional euclidean distance 327 | parDist(x = sample.matrix.list, method = "euclidean") 328 | # multi-dimensional dynamic time warping 329 | parDist(x = sample.matrix.list, method = "dtw") 330 | 331 | ## user-defined distance function 332 | library(RcppArmadillo) 333 | # Use RcppXPtrUtils for simple usage of C++ external pointers 334 | library(RcppXPtrUtils) 335 | 336 | # compile user-defined function and return pointer (RcppArmadillo is used as dependency) 337 | euclideanFuncPtr <- cppXPtr( 338 | "double customDist(const arma::mat &A, const arma::mat &B) { 339 | return sqrt(arma::accu(arma::square(A - B))); 340 | }", depends = c("RcppArmadillo")) 341 | 342 | # distance matrix for user-defined euclidean distance function (note that method is set to "custom") 343 | parDist(matrix(1:16, ncol=2), method="custom", func = euclideanFuncPtr)} 344 | } 345 | -------------------------------------------------------------------------------- /src/BinaryCount.h: -------------------------------------------------------------------------------- 1 | // BinaryCount.h 2 | // 3 | // Copyright (C) 2017, 2021 Alexander Eckert 4 | // 5 | // This file is part of parallelDist. 6 | // 7 | // parallelDist is free software: you can redistribute it and/or modify it 8 | // under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 2 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // parallelDist is distributed in the hope that it will be useful, but 13 | // WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with parallelDist. If not, see . 19 | 20 | #ifndef BINARYCOUNT_H_ 21 | #define BINARYCOUNT_H_ 22 | 23 | #include 24 | 25 | class BinaryCount { 26 | private: 27 | uint64_t a; 28 | uint64_t b; 29 | uint64_t c; 30 | uint64_t d; 31 | 32 | public: 33 | BinaryCount(uint64_t a, uint64_t b, uint64_t c, uint64_t d) : a(a), b(b), c(c), d(d) {} 34 | ~BinaryCount() {} 35 | static BinaryCount getBinaryCount(const arma::mat &A, const arma::mat &B) { 36 | uint64_t a = 0; 37 | uint64_t b = 0; 38 | uint64_t c = 0; 39 | uint64_t d = 0; 40 | 41 | for (arma::uword idx = 0; idx < A.size(); ++idx) { 42 | bool aZero = A.at(idx) == 0.0; 43 | bool bZero = B.at(idx) == 0.0; 44 | 45 | if (!aZero && !bZero) { 46 | ++a; 47 | } else if (!aZero && bZero) { 48 | ++b; 49 | } else if (aZero && !bZero) { 50 | ++c; 51 | } else if (aZero && bZero) { 52 | ++d; 53 | } 54 | } 55 | 56 | return BinaryCount(a, b, c, d); 57 | } 58 | uint64_t getA() { 59 | return a; 60 | } 61 | uint64_t getB() { 62 | return b; 63 | } 64 | uint64_t getC() { 65 | return c; 66 | } 67 | uint64_t getD() { 68 | return d; 69 | } 70 | }; 71 | 72 | #endif // BINARYCOUNT_H_ 73 | -------------------------------------------------------------------------------- /src/CPPLINT.cfg: -------------------------------------------------------------------------------- 1 | set noparent 2 | root=src 3 | filter=-whitespace/indent 4 | filter=-runtime/references 5 | filter=-build/include 6 | linelength=120 7 | exclude_files=(Makevars.*|CPPLINT.cfg|RcppExports.cpp) 8 | -------------------------------------------------------------------------------- /src/DistanceBinary.h: -------------------------------------------------------------------------------- 1 | // DistanceBinary.h 2 | // 3 | // Copyright (C) 2017, 2021 Alexander Eckert 4 | // 5 | // This file is part of parallelDist. 6 | // 7 | // parallelDist is free software: you can redistribute it and/or modify it 8 | // under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 2 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // parallelDist is distributed in the hope that it will be useful, but 13 | // WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with parallelDist. If not, see . 19 | 20 | #ifndef DISTANCEBINARY_H_ 21 | #define DISTANCEBINARY_H_ 22 | 23 | #include "BinaryCount.h" 24 | #include "IDistance.h" 25 | #include "Util.h" 26 | #include 27 | #include 28 | 29 | #undef max 30 | #define minOfPair(x, y) ((x) < (y) ? (x) : (y)) 31 | #define maxOfPair(x, y) ((x) < (y) ? (y) : (x)) 32 | 33 | //======================= 34 | // Binary distance 35 | //======================= 36 | class DistanceBinary : public IDistance { 37 | public: 38 | double calcDistance(const arma::mat &A, const arma::mat &B) { 39 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 40 | uint64_t denominator = bc.getA() + bc.getB() + bc.getC(); 41 | return ((denominator == 0) ? 0 : static_cast(bc.getB() + bc.getC()) / denominator); 42 | } 43 | }; 44 | 45 | //======================= 46 | // Braun-Blanquet 47 | //======================= 48 | class DistanceBraunblanquet : public IDistance { 49 | public: 50 | double calcDistance(const arma::mat &A, const arma::mat &B) { 51 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 52 | uint64_t denominator = maxOfPair((bc.getA() + bc.getB()), (bc.getA() + bc.getC())); 53 | return util::similarityToDistance(static_cast(bc.getA()) / denominator); 54 | } 55 | }; 56 | 57 | //======================= 58 | // Dice distance 59 | //======================= 60 | class DistanceDice : public IDistance { 61 | public: 62 | double calcDistance(const arma::mat &A, const arma::mat &B) { 63 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 64 | uint64_t denominator = 2 * bc.getA() + bc.getB() + bc.getC(); 65 | return util::similarityToDistance(static_cast(2 * bc.getA()) / denominator); 66 | } 67 | }; 68 | 69 | //======================= 70 | // Fager distance (like in proxy) 71 | //======================= 72 | class DistanceFager : public IDistance { 73 | public: 74 | double calcDistance(const arma::mat &A, const arma::mat &B) { 75 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 76 | return util::similarityToDistance( 77 | (static_cast(bc.getA()) / 78 | std::sqrt(static_cast((bc.getA() + bc.getB()) * (bc.getA() + bc.getC())))) - 79 | (std::sqrt(static_cast(bc.getA() + bc.getC())) / 2.0)); 80 | } 81 | }; 82 | 83 | //======================= 84 | // Faith distance 85 | //======================= 86 | class DistanceFaith : public IDistance { 87 | public: 88 | double calcDistance(const arma::mat &A, const arma::mat &B) { 89 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 90 | return util::similarityToDistance((bc.getA() + static_cast(bc.getD()) / 2.0) / A.n_cols); 91 | } 92 | }; 93 | 94 | //======================= 95 | // Hamman distance 96 | //======================= 97 | class DistanceHamman : public IDistance { 98 | public: 99 | double calcDistance(const arma::mat &A, const arma::mat &B) { 100 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 101 | return util::similarityToDistance( 102 | (static_cast(bc.getA()) + bc.getD() - bc.getB() - bc.getC()) / A.n_cols); 103 | } 104 | }; 105 | 106 | //======================= 107 | // Kulczynski1 distance 108 | //======================= 109 | class DistanceKulczynski1 : public IDistance { 110 | public: 111 | double calcDistance(const arma::mat &A, const arma::mat &B) { 112 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 113 | return util::similarityToDistance(static_cast(bc.getA()) / (bc.getB() + bc.getC())); 114 | } 115 | }; 116 | 117 | //======================= 118 | // Kulczynski2 distance 119 | //======================= 120 | class DistanceKulczynski2 : public IDistance { 121 | public: 122 | double calcDistance(const arma::mat &A, const arma::mat &B) { 123 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 124 | double div1 = static_cast(bc.getA()) / (bc.getA() + bc.getB()); 125 | double div2 = static_cast(bc.getA()) / (bc.getA() + bc.getC()); 126 | return util::similarityToDistance((div1 + div2) / 2.0); 127 | } 128 | }; 129 | 130 | //======================= 131 | // Michael distance 132 | //======================= 133 | class DistanceMichael : public IDistance { 134 | public: 135 | double calcDistance(const arma::mat &A, const arma::mat &B) { 136 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 137 | double denominator = std::pow(static_cast(bc.getA() + bc.getD()), 2) + 138 | std::pow(static_cast(bc.getB() + bc.getC()), 2); 139 | return util::similarityToDistance((4.0 * (static_cast(bc.getA() * bc.getD()) - 140 | (bc.getB() * bc.getC()))) / 141 | denominator); 142 | } 143 | }; 144 | 145 | //======================= 146 | // Mountford distance 147 | //======================= 148 | class DistanceMountford : public IDistance { 149 | public: 150 | double calcDistance(const arma::mat &A, const arma::mat &B) { 151 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 152 | uint64_t denominator = bc.getA() * (bc.getB() + bc.getC()) + 2 * bc.getB() * bc.getC(); 153 | return util::similarityToDistance(static_cast(2 * bc.getA()) / denominator); 154 | } 155 | }; 156 | 157 | //======================= 158 | // Mozley distance 159 | //======================= 160 | class DistanceMozley : public IDistance { 161 | public: 162 | double calcDistance(const arma::mat &A, const arma::mat &B) { 163 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 164 | uint64_t denominator = (bc.getA() + bc.getB()) * (bc.getA() + bc.getC()); 165 | return util::similarityToDistance((static_cast(bc.getA() * A.n_cols)) / denominator); 166 | } 167 | }; 168 | 169 | //======================= 170 | // Ochiai distance 171 | //======================= 172 | class DistanceOchiai : public IDistance { 173 | public: 174 | double calcDistance(const arma::mat &A, const arma::mat &B) { 175 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 176 | double denominator = std::sqrt(static_cast((bc.getA() + bc.getB()) * (bc.getA() + bc.getC()))); 177 | return util::similarityToDistance(static_cast(bc.getA()) / denominator); 178 | } 179 | }; 180 | 181 | //======================= 182 | // Phi distance 183 | //======================= 184 | class DistancePhi : public IDistance { 185 | public: 186 | double calcDistance(const arma::mat &A, const arma::mat &B) { 187 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 188 | double denominator = (std::sqrt(static_cast(bc.getA() + bc.getB())) * 189 | std::sqrt(static_cast(bc.getC() + bc.getD())) * 190 | std::sqrt(static_cast(bc.getA() + bc.getC())) * 191 | std::sqrt(static_cast(bc.getB() + bc.getD()))); 192 | return util::similarityToDistance( 193 | (static_cast(bc.getA() * bc.getD()) - (bc.getB() * bc.getC())) / denominator); 194 | } 195 | }; 196 | 197 | //======================= 198 | // Russel distance 199 | //======================= 200 | class DistanceRussel : public IDistance { 201 | public: 202 | double calcDistance(const arma::mat &A, const arma::mat &B) { 203 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 204 | return util::similarityToDistance(static_cast(bc.getA()) / A.n_cols); 205 | } 206 | }; 207 | 208 | //======================= 209 | // SimpleMatching distance 210 | //======================= 211 | class DistanceSimplematching : public IDistance { 212 | public: 213 | double calcDistance(const arma::mat &A, const arma::mat &B) { 214 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 215 | return util::similarityToDistance(static_cast(bc.getA() + bc.getD()) / A.n_cols); 216 | } 217 | }; 218 | 219 | //======================= 220 | // Simpson distance 221 | //======================= 222 | class DistanceSimpson : public IDistance { 223 | public: 224 | double calcDistance(const arma::mat &A, const arma::mat &B) { 225 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 226 | uint64_t denominator = minOfPair((bc.getA() + bc.getB()), (bc.getA() + bc.getC())); 227 | return util::similarityToDistance(static_cast(bc.getA()) / denominator); 228 | } 229 | }; 230 | 231 | //======================= 232 | // Stiles distance 233 | //======================= 234 | class DistanceStiles : public IDistance { 235 | public: 236 | double calcDistance(const arma::mat &A, const arma::mat &B) { 237 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 238 | unsigned int n = A.n_cols; 239 | return util::similarityToDistance( 240 | (std::log(static_cast(n)) + 241 | 2 * std::log(std::abs(static_cast(bc.getA() * bc.getD()) - bc.getB() * bc.getC()) - n / 2.0) - 242 | std::log(static_cast(bc.getA() + bc.getB())) - std::log(static_cast(bc.getC() + bc.getD())) - 243 | std::log(static_cast(bc.getA() + bc.getC())) - std::log(static_cast(bc.getB() + bc.getD())))); 244 | } 245 | }; 246 | 247 | //======================= 248 | // Tanimoto distance 249 | //======================= 250 | class DistanceTanimoto : public IDistance { 251 | public: 252 | double calcDistance(const arma::mat &A, const arma::mat &B) { 253 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 254 | uint64_t denominator = bc.getA() + 2 * bc.getB() + 2 * bc.getC() + bc.getD(); 255 | return util::similarityToDistance(static_cast(bc.getA() + bc.getD()) / denominator); 256 | } 257 | }; 258 | 259 | //======================= 260 | // Yule distance 261 | //======================= 262 | class DistanceYule : public IDistance { 263 | public: 264 | double calcDistance(const arma::mat &A, const arma::mat &B) { 265 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 266 | uint64_t denominator = (bc.getA() * bc.getD()) + (bc.getB() * bc.getC()); 267 | return util::similarityToDistance((static_cast(bc.getA() * bc.getD()) - 268 | (bc.getB() * bc.getC())) / 269 | denominator); 270 | } 271 | }; 272 | 273 | //======================= 274 | // Yule2 distance 275 | //======================= 276 | class DistanceYule2 : public IDistance { 277 | public: 278 | double calcDistance(const arma::mat &A, const arma::mat &B) { 279 | BinaryCount bc = BinaryCount::getBinaryCount(A, B); 280 | double denominator = std::sqrt(static_cast(bc.getA() * bc.getD())) + 281 | std::sqrt(static_cast(bc.getB() * bc.getC())); 282 | return util::similarityToDistance((std::sqrt(static_cast(bc.getA() * bc.getD())) - 283 | std::sqrt(static_cast(bc.getB() * bc.getC()))) / 284 | denominator); 285 | } 286 | }; 287 | 288 | #endif // DISTANCEBINARY_H_ 289 | -------------------------------------------------------------------------------- /src/DistanceDTWFactory.cpp: -------------------------------------------------------------------------------- 1 | // DistanceDTWFactory.cpp 2 | // 3 | // Copyright (C) 2017, 2021 Alexander Eckert 4 | // 5 | // This file is part of parallelDist. 6 | // 7 | // parallelDist is free software: you can redistribute it and/or modify it 8 | // under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 2 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // parallelDist is distributed in the hope that it will be useful, but 13 | // WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with parallelDist. If not, see . 19 | 20 | #include "DistanceDTWFactory.h" 21 | #include "StepPattern.h" 22 | #include "Util.h" 23 | 24 | std::shared_ptr DistanceDTWFactory::createDistanceFunction( 25 | const std::string &distName, const Rcpp::List &arguments) { 26 | using util::isEqualStr; 27 | 28 | std::shared_ptr distanceFunction = NULL; 29 | unsigned int windowSize = 0; 30 | NormMethod normMethod = NormMethod::NoNorm; 31 | bool warpingWindow = false; 32 | std::string stepPatternName = "symmetric1"; 33 | 34 | warpingWindow = arguments.containsElementNamed("window.size"); 35 | if (warpingWindow) { 36 | windowSize = Rcpp::as(arguments["window.size"]); 37 | } 38 | if (arguments.containsElementNamed("norm.method")) { 39 | std::string normMethodStr = Rcpp::as(arguments["norm.method"]); 40 | if (isEqualStr(normMethodStr, "n")) { 41 | normMethod = NormMethod::ALength; 42 | } else if (isEqualStr(normMethodStr, "n+m")) { 43 | normMethod = NormMethod::ABLength; 44 | } else if (isEqualStr(normMethodStr, "path.length")) { 45 | normMethod = NormMethod::PathLength; 46 | } 47 | } 48 | if (arguments.containsElementNamed("step.pattern")) { 49 | stepPatternName = Rcpp::as(arguments["step.pattern"]); 50 | } 51 | 52 | if (isEqualStr(stepPatternName, "asymmetric")) { 53 | distanceFunction = std::make_shared(warpingWindow, windowSize, normMethod); 54 | } else if (isEqualStr(stepPatternName, "asymmetricP0")) { 55 | distanceFunction = std::make_shared(warpingWindow, windowSize, normMethod); 56 | } else if (isEqualStr(stepPatternName, "asymmetricP05")) { 57 | distanceFunction = std::make_shared(warpingWindow, windowSize, normMethod); 58 | } else if (isEqualStr(stepPatternName, "asymmetricP1")) { 59 | distanceFunction = std::make_shared(warpingWindow, windowSize, normMethod); 60 | } else if (isEqualStr(stepPatternName, "asymmetricP2")) { 61 | distanceFunction = std::make_shared(warpingWindow, windowSize, normMethod); 62 | } else if ( 63 | isEqualStr(stepPatternName, "symmetric2") || 64 | isEqualStr(stepPatternName, "symmetricP0")) { 65 | distanceFunction = std::make_shared(warpingWindow, windowSize, normMethod); 66 | } else if (isEqualStr(stepPatternName, "symmetricP05")) { 67 | distanceFunction = std::make_shared(warpingWindow, windowSize, normMethod); 68 | } else if (isEqualStr(stepPatternName, "symmetricP1")) { 69 | distanceFunction = std::make_shared(warpingWindow, windowSize, normMethod); 70 | } else if (isEqualStr(stepPatternName, "symmetricP2")) { 71 | distanceFunction = std::make_shared(warpingWindow, windowSize, normMethod); 72 | } else { 73 | distanceFunction = std::make_shared(warpingWindow, windowSize, normMethod); 74 | } 75 | return distanceFunction; 76 | } 77 | -------------------------------------------------------------------------------- /src/DistanceDTWFactory.h: -------------------------------------------------------------------------------- 1 | // DistanceDTWFactory.h 2 | // 3 | // Copyright (C) 2017, 2021 Alexander Eckert 4 | // 5 | // This file is part of parallelDist. 6 | // 7 | // parallelDist is free software: you can redistribute it and/or modify it 8 | // under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 2 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // parallelDist is distributed in the hope that it will be useful, but 13 | // WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with parallelDist. If not, see . 19 | 20 | #ifndef DISTANCEDTWFACTORY_H_ 21 | #define DISTANCEDTWFACTORY_H_ 22 | 23 | #include "IDistance.h" 24 | #include 25 | #include 26 | 27 | //============================== 28 | // Distance DTW Factory 29 | //============================== 30 | class DistanceDTWFactory { 31 | public: 32 | std::shared_ptr createDistanceFunction(const std::string &distName, const Rcpp::List &arguments); 33 | }; 34 | 35 | #endif // DISTANCEDTWFACTORY_H_ 36 | -------------------------------------------------------------------------------- /src/DistanceDTWGeneric.h: -------------------------------------------------------------------------------- 1 | // DistanceDTWGeneric.h 2 | // 3 | // Copyright (C) 2017, 2021 Alexander Eckert 4 | // 5 | // This file is part of parallelDist. 6 | // 7 | // parallelDist is free software: you can redistribute it and/or modify it 8 | // under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 2 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // parallelDist is distributed in the hope that it will be useful, but 13 | // WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with parallelDist. If not, see . 19 | 20 | #ifndef DISTANCEDTWGENERIC_H_ 21 | #define DISTANCEDTWGENERIC_H_ 22 | 23 | #include "IDistance.h" 24 | #include 25 | #include 26 | 27 | #define min(x, y) ((x) < (y) ? (x) : (y)) 28 | #define max(x, y) ((x) < (y) ? (y) : (x)) 29 | #define min3(x, y, z) (min(x, min(y, z))) 30 | #define unused(x) ((void)x) 31 | 32 | enum class NormMethod { NoNorm, 33 | PathLength, 34 | ALength, 35 | ABLength }; 36 | 37 | //============================== 38 | // Dynamic Time Warping distance 39 | //============================== 40 | // Generic implementation 41 | template 42 | class DistanceDTWGeneric : public IDistance { 43 | private: 44 | unsigned int windowSize; 45 | bool warpingWindow; 46 | NormMethod normalizationMethod; 47 | 48 | const unsigned int getPatternOffset() { 49 | return Implementation::patternOffset; 50 | } 51 | 52 | inline Implementation &impl() { 53 | return *static_cast(this); 54 | } 55 | 56 | /** 57 | Calculate costs for two entries of input matrices A and B 58 | @param pen penality matrix 59 | @param bSizeOffset B.ncol + patternOffset 60 | @param A matrix A 61 | @param B matrix B 62 | @param i index i 63 | @param j index j 64 | @return costs for two entries of input matrices A and B 65 | */ 66 | std::pair getCost(double *pen, unsigned int bSizeOffset, const arma::mat &A, const arma::mat &B, 67 | unsigned int i, unsigned int j) { 68 | return impl().getCost(pen, bSizeOffset, A, B, i, j); 69 | } 70 | 71 | protected: 72 | // calculates minimum and argmin of a double array 73 | std::pair argmin(double arr[], unsigned int len) { 74 | double min = arr[0]; 75 | unsigned int argMin = 0; 76 | 77 | for (unsigned int i = 1; i < len; i++) { 78 | if (arr[i] < min) { 79 | min = arr[i]; 80 | argMin = i; 81 | } 82 | } 83 | return std::make_pair(min, argMin); 84 | } 85 | // returns value of cell of matrix 86 | double getCell(double *matrix, unsigned int bMatrixSizeOffset, unsigned int i, unsigned int j) { 87 | return matrix[i * bMatrixSizeOffset + j]; 88 | } 89 | // calculates euclidean distance between two matrices 90 | double getDistance(const arma::mat &A, const arma::mat &B, unsigned int i, unsigned int j) { 91 | if (i < getPatternOffset() || j < getPatternOffset()) { 92 | return INFINITY; 93 | } else { 94 | return std::sqrt(arma::accu(arma::square(A.col(i - getPatternOffset()) - B.col(j - getPatternOffset())))); 95 | } 96 | } 97 | 98 | public: 99 | DistanceDTWGeneric(bool warpingWindow = false, unsigned int windowSize = 0, 100 | NormMethod normalizationMethod = NormMethod::NoNorm) { 101 | this->warpingWindow = warpingWindow; 102 | this->windowSize = windowSize; 103 | this->normalizationMethod = normalizationMethod; 104 | } 105 | 106 | ~DistanceDTWGeneric() { 107 | } 108 | 109 | double calcDistance(const arma::mat &A, const arma::mat &B) { 110 | const unsigned int patternOffset = getPatternOffset(); 111 | // vector sizes for convenience 112 | const unsigned int Asize = A.n_cols, Bsize = B.n_cols; 113 | const unsigned int aSizeOffset = Asize + patternOffset; 114 | const unsigned int bSizeOffset = Bsize + patternOffset; 115 | 116 | // size penality matrix according to the possible offset of the steppattern 117 | double *pen = new double[aSizeOffset * bSizeOffset]; 118 | 119 | char *pre = 0; 120 | if (normalizationMethod == NormMethod::PathLength) { 121 | pre = new char[aSizeOffset * bSizeOffset]; 122 | } else { 123 | unused(pre); 124 | } 125 | 126 | // initialize fully costalty matrix 127 | for (unsigned int i = 0; i < aSizeOffset; ++i) { 128 | unsigned int currIdx = i * bSizeOffset; 129 | for (unsigned int j = 0; j < bSizeOffset; ++j) { 130 | pen[currIdx + j] = INFINITY; 131 | } 132 | } 133 | 134 | // adjust window if needed 135 | unsigned int effectiveWindowSize; 136 | if (warpingWindow) { 137 | effectiveWindowSize = max(windowSize, Asize > Bsize ? Asize - Bsize : Bsize - Asize); 138 | } else { 139 | effectiveWindowSize = max(Asize, Bsize); 140 | } 141 | 142 | for (unsigned int i = patternOffset; i < aSizeOffset; ++i) { 143 | unsigned int lower = patternOffset, upper = bSizeOffset; 144 | 145 | lower = i > effectiveWindowSize + patternOffset ? i - effectiveWindowSize : patternOffset; 146 | upper = min(bSizeOffset, i + effectiveWindowSize + 1); 147 | 148 | unsigned int currIdx = i * bSizeOffset; 149 | for (unsigned int j = lower; j < upper; ++j) { 150 | if (i == patternOffset && j == patternOffset) { 151 | pen[currIdx + j] = getDistance(A, B, i, j); 152 | } else { 153 | std::pair cost = getCost(pen, bSizeOffset, A, B, i, j); 154 | pen[currIdx + j] = cost.first; 155 | 156 | if (normalizationMethod == NormMethod::PathLength) { 157 | pre[currIdx + j] = cost.second; 158 | } 159 | } 160 | } 161 | } 162 | 163 | // remember the optimal distance measure 164 | double dist = pen[aSizeOffset * bSizeOffset - 1]; 165 | 166 | // free memory 167 | delete[] pen; 168 | 169 | // calc warp path for normalization 170 | if (normalizationMethod == NormMethod::PathLength) { 171 | unsigned int warpPathLength = 0; 172 | // start at the end of the warping path 173 | unsigned int i = aSizeOffset - 1, j = bSizeOffset - 1; 174 | unsigned int patternOffsetPlusOne = patternOffset + 1; 175 | // until starting node reached 176 | while (i != patternOffset && j != patternOffset) { 177 | // add node to warping path 178 | ++warpPathLength; 179 | if (i == patternOffsetPlusOne) { 180 | j -= 1; 181 | } else if (j == patternOffsetPlusOne) { 182 | i -= 1; 183 | } else if (pre[i * bSizeOffset + j] == 0) { 184 | i -= 1; 185 | } else if (pre[i * bSizeOffset + j] == 1) { 186 | i -= 1; 187 | j -= 1; 188 | } else if (pre[i * bSizeOffset + j] == 2) { 189 | j -= 1; 190 | } 191 | } 192 | // free memory 193 | delete[] pre; 194 | dist /= warpPathLength; 195 | } else if (normalizationMethod == NormMethod::ABLength) { 196 | dist /= (Asize + Bsize); 197 | } else if (normalizationMethod == NormMethod::ALength) { 198 | dist /= Asize; 199 | } 200 | 201 | return dist; 202 | } 203 | }; 204 | 205 | #endif // DISTANCEDTWGENERIC_H_ 206 | -------------------------------------------------------------------------------- /src/DistanceDist.h: -------------------------------------------------------------------------------- 1 | // DistanceDist.h 2 | // 3 | // Copyright (C) 2017, 2021 Alexander Eckert 4 | // 5 | // This file is part of parallelDist. 6 | // 7 | // parallelDist is free software: you can redistribute it and/or modify it 8 | // under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 2 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // parallelDist is distributed in the hope that it will be useful, but 13 | // WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with parallelDist. If not, see . 19 | 20 | #ifndef DISTANCEDIST_H_ 21 | #define DISTANCEDIST_H_ 22 | 23 | #include 24 | 25 | #include "IDistance.h" 26 | #include "Util.h" 27 | 28 | //======================= 29 | // Bhjattacharyya 30 | //======================= 31 | class DistanceBhjattacharyya : public IDistance { 32 | public: 33 | double calcDistance(const arma::mat &A, const arma::mat &B) { 34 | // sqrt(sum_i (sqrt(x_i) - sqrt(y_i))^2)) 35 | return std::sqrt(arma::accu(arma::square(arma::sqrt(A) - arma::sqrt(B)))); 36 | } 37 | }; 38 | 39 | //======================= 40 | // Bray 41 | //======================= 42 | class DistanceBray : public IDistance { 43 | public: 44 | double calcDistance(const arma::mat &A, const arma::mat &B) { 45 | // sum_i |x_i - y_i| / sum_i (x_i + y_i) 46 | return arma::accu(arma::abs(A - B)) / arma::accu(A + B); 47 | } 48 | }; 49 | 50 | //======================= 51 | // Canberra distance 52 | //======================= 53 | class DistanceCanberra : public IDistance { 54 | public: 55 | double calcDistance(const arma::mat &A, const arma::mat &B) { 56 | arma::mat denominator = arma::abs(A + B); 57 | arma::mat ratio = arma::abs(A - B) / denominator; 58 | 59 | unsigned int notNanCount = 0; 60 | for (arma::mat::iterator it = ratio.begin(); it != ratio.end(); ++it) { 61 | if (std::isnan(*it)) { 62 | (*it) = 0.0; 63 | } else { 64 | ++notNanCount; 65 | } 66 | } 67 | 68 | if (ratio.size() - notNanCount > 0) { 69 | return ((notNanCount + 1) / static_cast(notNanCount)) * 70 | arma::accu(ratio); 71 | } else { 72 | return arma::accu(ratio); 73 | } 74 | } 75 | }; 76 | 77 | //======================= 78 | // Chord 79 | //======================= 80 | class DistanceChord : public IDistance { 81 | public: 82 | double calcDistance(const arma::mat &A, const arma::mat &B) { 83 | // sqrt(2 * (1 - xy / sqrt(xx * yy))) 84 | return std::sqrt(2 * (1 - arma::dot(A.row(0), B.row(0)) / 85 | std::sqrt(arma::dot(A.row(0), A.row(0)) * 86 | arma::dot(B.row(0), B.row(0))))); 87 | } 88 | }; 89 | 90 | //======================= 91 | // Divergence 92 | //======================= 93 | class DistanceDivergence : public IDistance { 94 | public: 95 | double calcDistance(const arma::mat &A, const arma::mat &B) { 96 | // sum_i (x_i - y_i)^2 / (x_i + y_i)^2 97 | arma::mat tmp = arma::square(A - B) / arma::square(A + B); 98 | if (tmp.has_nan()) { 99 | tmp.transform([](double val) { return (std::isnan(val) ? 0 : val); }); 100 | } 101 | return arma::accu(tmp); 102 | } 103 | }; 104 | 105 | //======================= 106 | // Euclidean distance 107 | //======================= 108 | class DistanceEuclidean : public IDistance { 109 | public: 110 | double calcDistance(const arma::mat &A, const arma::mat &B) { 111 | return std::sqrt(arma::accu(arma::square(A - B))); 112 | } 113 | }; 114 | 115 | //======================= 116 | // FJaccard 117 | //======================= 118 | class DistanceFJaccard : public IDistance { 119 | public: 120 | double calcDistance(const arma::mat &A, const arma::mat &B) { 121 | // sum_i (min{x_i, y_i} / max{x_i, y_i}) 122 | arma::mat tmp = arma::join_cols(A, B); 123 | return util::similarityToDistance(arma::accu(colwise_min_idx(tmp)) / 124 | arma::accu(colwise_max_idx(tmp))); 125 | } 126 | }; 127 | 128 | //======================= 129 | // Geodesic 130 | //======================= 131 | class DistanceGeodesic : public IDistance { 132 | public: 133 | double calcDistance(const arma::mat &A, const arma::mat &B) { 134 | // arccos(xy / sqrt(xx * yy)) 135 | return acos(arma::dot(A.row(0), B.row(0)) / 136 | std::sqrt(arma::dot(A.row(0), A.row(0)) * 137 | arma::dot(B.row(0), B.row(0)))); 138 | } 139 | }; 140 | 141 | //======================= 142 | // Hellinger 143 | //======================= 144 | class DistanceHellinger : public IDistance { 145 | public: 146 | double calcDistance(const arma::mat &A, const arma::mat &B) { 147 | // sqrt(sum_i (sqrt(x_i / sum_i x) - sqrt(y_i / sum_i y)) ^ 2) 148 | return std::sqrt(arma::accu(arma::square(arma::sqrt(A / arma::accu(A)) - 149 | arma::sqrt(B / arma::accu(B))))); 150 | } 151 | }; 152 | 153 | //======================= 154 | // Kullback, Leibler 155 | //======================= 156 | class DistanceKullback : public IDistance { 157 | public: 158 | double calcDistance(const arma::mat &A, const arma::mat &B) { 159 | // sum_i [x_i * log((x_i / sum_j x_j) / (y_i / sum_j y_j)) / sum_j x_j)] 160 | arma::mat p = A / arma::accu(A); 161 | arma::mat q = B / arma::accu(B); 162 | double result = arma::accu(p * arma::log(p / q).t()); 163 | // return same results as dist 164 | return std::isinf(result) ? std::numeric_limits::quiet_NaN() 165 | : result; 166 | } 167 | }; 168 | 169 | //======================= 170 | // Mahalanobis 171 | //======================= 172 | class DistanceMahalanobis : public IDistance { 173 | private: 174 | arma::mat invertedCov; 175 | 176 | public: 177 | explicit DistanceMahalanobis(const arma::mat &invertedCov) { 178 | this->invertedCov = invertedCov; 179 | } 180 | double calcDistance(const arma::mat &A, const arma::mat &B) { 181 | arma::mat C = A - B; 182 | return std::sqrt(arma::accu(C * this->invertedCov % C)); 183 | } 184 | }; 185 | 186 | //======================= 187 | // Manhattan distance 188 | //======================= 189 | class DistanceManhattan : public IDistance { 190 | public: 191 | double calcDistance(const arma::mat &A, const arma::mat &B) { 192 | return arma::accu(arma::abs(A - B)); 193 | } 194 | }; 195 | 196 | //======================= 197 | // Maximum distance 198 | //======================= 199 | class DistanceMaximum : public IDistance { 200 | public: 201 | double calcDistance(const arma::mat &A, const arma::mat &B) { 202 | return arma::abs(A - B).max(); 203 | } 204 | }; 205 | 206 | //======================= 207 | // Minkowski distance 208 | //======================= 209 | class DistanceMinkowski : public IDistance { 210 | private: 211 | double p; 212 | 213 | public: 214 | explicit DistanceMinkowski(double p) { this->p = p; } 215 | ~DistanceMinkowski() {} 216 | double calcDistance(const arma::mat &A, const arma::mat &B) { 217 | return std::pow(arma::accu(arma::pow(arma::abs(A - B), this->p)), 218 | 1.0 / this->p); 219 | } 220 | }; 221 | 222 | //======================= 223 | // Podani 224 | //======================= 225 | class DistancePodani : public IDistance { 226 | public: 227 | double calcDistance(const arma::mat &A, const arma::mat &B) { 228 | uint64_t n = A.n_cols; 229 | uint64_t a, b, c, d; 230 | a = b = c = d = 0; 231 | for (unsigned int i = 0; i < n; i++) { 232 | for (unsigned int j = i + 1; j < n; j++) { 233 | if ((A(0, i) < A(0, j) && B(0, i) < B(0, j)) || 234 | (A(0, i) > A(0, j) && B(0, i) > B(0, j))) { 235 | a++; 236 | } 237 | if ((A(0, i) < A(0, j) && B(0, i) > B(0, j)) || 238 | (A(0, i) > A(0, j) && B(0, i) < B(0, j))) { 239 | b++; 240 | } 241 | if (A(0, i) == A(0, j) && B(0, i) == B(0, j) && 242 | ((A(0, i) == 0 && B(0, i) == 0) || (A(0, i) > 0 && B(0, i) > 0))) { 243 | c++; 244 | } 245 | 246 | unsigned int z = 0; 247 | if (A(0, i) == 0) 248 | ++z; 249 | if (A(0, j) == 0) 250 | ++z; 251 | if (B(0, i) == 0) 252 | ++z; 253 | if (B(0, j) == 0) 254 | ++z; 255 | 256 | if ((A(0, i) == A(0, j) || B(0, i) == B(0, j)) && z > 0 && z < 4) { 257 | d++; 258 | } 259 | } 260 | } 261 | return 1 - 2 * (static_cast(a) - b + c - d) / (n * (n - 1)); 262 | } 263 | }; 264 | 265 | //======================= 266 | // Soergel 267 | //======================= 268 | class DistanceSoergel : public IDistance { 269 | public: 270 | double calcDistance(const arma::mat &A, const arma::mat &B) { 271 | // sum_i |x_i - y_i| / sum_i max{x_i, y_i} 272 | arma::mat tmp = arma::join_cols(A, B); 273 | return arma::accu(arma::abs(A - B)) / arma::accu(colwise_max_idx(tmp)); 274 | } 275 | }; 276 | 277 | //======================= 278 | // Wave 279 | // See Comprehensive Survey on Distance/Similarity Measures 280 | // between Probability Density Functions 281 | // Sung-Hyuk Cha 282 | //======================= 283 | class DistanceWave : public IDistance { 284 | public: 285 | double calcDistance(const arma::mat &A, const arma::mat &B) { 286 | // sum_i (1 - min(x_i, y_i) / max(x_i, y_i)) 287 | arma::mat tmp = arma::join_cols(A, B); 288 | arma::mat substr = arma::abs(A - B); 289 | return arma::accu(substr / repmat(colwise_max_idx(tmp), substr.n_rows, 1)); 290 | } 291 | }; 292 | 293 | //======================= 294 | // Whittaker 295 | //======================= 296 | class DistanceWhittaker : public IDistance { 297 | public: 298 | double calcDistance(const arma::mat &A, const arma::mat &B) { 299 | // sum_i |x_i / sum_i x - y_i / sum_i y| / 2 300 | return arma::accu(arma::abs(A / arma::accu(A) - B / arma::accu(B))) / 2.0; 301 | } 302 | }; 303 | 304 | //======================= 305 | // Cosine 306 | //======================= 307 | class DistanceCosine : public IDistance { 308 | public: 309 | double calcDistance(const arma::mat &A, const arma::mat &B) { 310 | return 1.0 - ( 311 | arma::as_scalar(arma::dot(A, B)) / 312 | (arma::as_scalar(arma::norm(A)) * arma::as_scalar(arma::norm(B)))); 313 | } 314 | }; 315 | 316 | //======================= 317 | // Hamming distance 318 | //======================= 319 | class DistanceHamming : public IDistance { 320 | public: 321 | double calcDistance(const arma::mat &A, const arma::mat &B) { 322 | double nc = A.n_cols; 323 | return arma::accu(A != B) / nc; 324 | } 325 | }; 326 | 327 | //======================= 328 | // Custom distance 329 | //======================= 330 | class DistanceCustom : public IDistance { 331 | private: 332 | funcPtr func; 333 | 334 | public: 335 | explicit DistanceCustom(funcPtr function) : func(function) { 336 | this->func = function; 337 | } 338 | ~DistanceCustom() {} 339 | double calcDistance(const arma::mat &A, const arma::mat &B) { 340 | return func(A, B); 341 | } 342 | }; 343 | 344 | #endif // DISTANCEDIST_H_ 345 | -------------------------------------------------------------------------------- /src/DistanceFactory.cpp: -------------------------------------------------------------------------------- 1 | // DistanceFactory.cpp 2 | // 3 | // Copyright (C) 2017, 2021 Alexander Eckert 4 | // 5 | // This file is part of parallelDist. 6 | // 7 | // parallelDist is free software: you can redistribute it and/or modify it 8 | // under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 2 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // parallelDist is distributed in the hope that it will be useful, but 13 | // WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with parallelDist. If not, see . 19 | 20 | #include "DistanceFactory.h" 21 | #include "DistanceBinary.h" 22 | #include "DistanceDTWFactory.h" 23 | #include "DistanceDist.h" 24 | #include "Util.h" 25 | 26 | std::shared_ptr DistanceFactory::createDistanceFunction(const Rcpp::List &attrs, 27 | const Rcpp::List &arguments) { 28 | using util::isEqualStr; 29 | std::string distName = attrs["method"]; 30 | std::shared_ptr distanceFunction = NULL; 31 | 32 | if (isEqualStr(distName, "bhjattacharyya")) { 33 | distanceFunction = std::make_shared(); 34 | } else if (isEqualStr(distName, "bray")) { 35 | distanceFunction = std::make_shared(); 36 | } else if (isEqualStr(distName, "canberra")) { 37 | distanceFunction = std::make_shared(); 38 | } else if (isEqualStr(distName, "chord")) { 39 | distanceFunction = std::make_shared(); 40 | } else if (isEqualStr(distName, "divergence")) { 41 | distanceFunction = std::make_shared(); 42 | } else if (isEqualStr(distName, "dtw")) { 43 | distanceFunction = DistanceDTWFactory().createDistanceFunction(distName, arguments); 44 | } else if (isEqualStr(distName, "fJaccard")) { 45 | distanceFunction = std::make_shared(); 46 | } else if (isEqualStr(distName, "geodesic")) { 47 | distanceFunction = std::make_shared(); 48 | } else if (isEqualStr(distName, "hellinger")) { 49 | distanceFunction = std::make_shared(); 50 | } else if (isEqualStr(distName, "kullback")) { 51 | distanceFunction = std::make_shared(); 52 | } else if (isEqualStr(distName, "cosine")) { 53 | distanceFunction = std::make_shared(); 54 | } else if (isEqualStr(distName, "mahalanobis")) { 55 | bool isInvertedCov = false; 56 | bool isCov = arguments.containsElementNamed("cov"); 57 | arma::Mat cov; 58 | if (isCov) { 59 | cov = Rcpp::as>(arguments["cov"]); 60 | } else { 61 | // if data was provided as matrix 62 | if (this->isDataMatrix) { 63 | // calc covariance matrix if input data is in matrix format 64 | cov = arma::cov(dataMatrix); 65 | } else { 66 | Rcpp::stop("Calculation of inverted covariance matrix is only supported for input data in matrix format."); 67 | } 68 | } 69 | if (arguments.containsElementNamed("inverted")) { 70 | isInvertedCov = Rcpp::as(arguments["inverted"]); 71 | } 72 | if (!isInvertedCov) { 73 | cov = arma::inv(cov); 74 | } 75 | distanceFunction = std::make_shared(cov); 76 | } else if (isEqualStr(distName, "manhattan")) { 77 | distanceFunction = std::make_shared(); 78 | } else if (isEqualStr(distName, "maximum")) { 79 | distanceFunction = std::make_shared(); 80 | } else if (isEqualStr(distName, "minkowski")) { 81 | double p = 2; 82 | if (arguments.containsElementNamed("p")) { 83 | p = Rcpp::as(arguments["p"]); 84 | } 85 | distanceFunction = std::make_shared(p); 86 | } else if (isEqualStr(distName, "podani")) { 87 | distanceFunction = std::make_shared(); 88 | } else if (isEqualStr(distName, "soergel")) { 89 | distanceFunction = std::make_shared(); 90 | } else if (isEqualStr(distName, "wave")) { 91 | distanceFunction = std::make_shared(); 92 | } else if (isEqualStr(distName, "whittaker")) { 93 | distanceFunction = std::make_shared(); 94 | } else if (isEqualStr(distName, "binary")) { 95 | distanceFunction = std::make_shared(); 96 | } else if (isEqualStr(distName, "braun-blanquet")) { 97 | distanceFunction = std::make_shared(); 98 | } else if (isEqualStr(distName, "dice")) { 99 | distanceFunction = std::make_shared(); 100 | } else if (isEqualStr(distName, "fager")) { 101 | distanceFunction = std::make_shared(); 102 | } else if (isEqualStr(distName, "faith")) { 103 | distanceFunction = std::make_shared(); 104 | } else if (isEqualStr(distName, "hamman")) { 105 | distanceFunction = std::make_shared(); 106 | } else if (isEqualStr(distName, "kulczynski1")) { 107 | distanceFunction = std::make_shared(); 108 | } else if (isEqualStr(distName, "kulczynski2")) { 109 | distanceFunction = std::make_shared(); 110 | } else if (isEqualStr(distName, "michael")) { 111 | distanceFunction = std::make_shared(); 112 | } else if (isEqualStr(distName, "mountford")) { 113 | distanceFunction = std::make_shared(); 114 | } else if (isEqualStr(distName, "mozley")) { 115 | distanceFunction = std::make_shared(); 116 | } else if (isEqualStr(distName, "ochiai")) { 117 | distanceFunction = std::make_shared(); 118 | } else if (isEqualStr(distName, "phi")) { 119 | distanceFunction = std::make_shared(); 120 | } else if (isEqualStr(distName, "russel")) { 121 | distanceFunction = std::make_shared(); 122 | } else if (isEqualStr(distName, "simple matching")) { 123 | distanceFunction = std::make_shared(); 124 | } else if (isEqualStr(distName, "simpson")) { 125 | distanceFunction = std::make_shared(); 126 | } else if (isEqualStr(distName, "stiles")) { 127 | distanceFunction = std::make_shared(); 128 | } else if (isEqualStr(distName, "tanimoto")) { 129 | distanceFunction = std::make_shared(); 130 | } else if (isEqualStr(distName, "yule")) { 131 | distanceFunction = std::make_shared(); 132 | } else if (isEqualStr(distName, "yule2")) { 133 | distanceFunction = std::make_shared(); 134 | } else if (isEqualStr(distName, "hamming")) { 135 | distanceFunction = std::make_shared(); 136 | } else if (isEqualStr(distName, "custom")) { 137 | SEXP func_ = arguments["func"]; 138 | funcPtr func = *Rcpp::XPtr(func_); 139 | distanceFunction = std::make_shared(func); 140 | } else { 141 | distanceFunction = std::make_shared(); 142 | } 143 | return distanceFunction; 144 | } 145 | -------------------------------------------------------------------------------- /src/DistanceFactory.h: -------------------------------------------------------------------------------- 1 | // DistanceFactory.h 2 | // 3 | // Copyright (C) 2017, 2021 Alexander Eckert 4 | // 5 | // This file is part of parallelDist. 6 | // 7 | // parallelDist is free software: you can redistribute it and/or modify it 8 | // under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 2 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // parallelDist is distributed in the hope that it will be useful, but 13 | // WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with parallelDist. If not, see . 19 | 20 | #ifndef DISTANCEFACTORY_H_ 21 | #define DISTANCEFACTORY_H_ 22 | 23 | #include "IDistance.h" 24 | #include 25 | #include 26 | 27 | //============================== 28 | // Distance Factory 29 | //============================== 30 | class DistanceFactory { 31 | private: 32 | // Store reference to data objects to enable distance method parameter precalculations 33 | arma::mat dataMatrix; 34 | std::vector dataMatrixList; 35 | bool isDataMatrix; 36 | 37 | public: 38 | explicit DistanceFactory(arma::mat &dataMatrix) : dataMatrix(dataMatrix), isDataMatrix(true) {} 39 | explicit DistanceFactory(std::vector &dataMatrixList) : dataMatrixList(dataMatrixList), 40 | isDataMatrix(false) {} 41 | std::shared_ptr createDistanceFunction(const Rcpp::List &attrs, const Rcpp::List &arguments); 42 | }; 43 | 44 | #endif // DISTANCEFACTORY_H_ 45 | -------------------------------------------------------------------------------- /src/IDistance.h: -------------------------------------------------------------------------------- 1 | // IDistance.h 2 | // 3 | // Copyright (C) 2017, 2021 Alexander Eckert 4 | // 5 | // This file is part of parallelDist. 6 | // 7 | // parallelDist is free software: you can redistribute it and/or modify it 8 | // under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 2 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // parallelDist is distributed in the hope that it will be useful, but 13 | // WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with parallelDist. If not, see . 19 | 20 | #ifndef IDISTANCE_H_ 21 | #define IDISTANCE_H_ 22 | 23 | #include 24 | 25 | using arma::mat; 26 | using arma::Mat; 27 | using arma::uword; 28 | 29 | typedef double (*funcPtr)(const mat &A, const mat &B); 30 | 31 | template 32 | Mat colwise_max_idx(const Mat &A) { 33 | Mat res = mat(1, A.n_cols); 34 | for (uword i = 0; i != A.n_cols; ++i) { 35 | res.at(0, i) = A.col(i).max(); 36 | } 37 | return res; 38 | } 39 | 40 | template 41 | Mat colwise_min_idx(const Mat &A) { 42 | Mat res = mat(1, A.n_cols); 43 | for (uword i = 0; i != A.n_cols; ++i) { 44 | res.at(0, i) = A.col(i).min(); 45 | } 46 | return res; 47 | } 48 | 49 | class IDistance { 50 | public: 51 | virtual ~IDistance() {} 52 | virtual double calcDistance(const mat &A, const mat &B) = 0; 53 | }; 54 | 55 | #endif // IDISTANCE_H_ 56 | -------------------------------------------------------------------------------- /src/Makevars: -------------------------------------------------------------------------------- 1 | CXX_STD = CXX11 2 | 3 | PKG_LIBS = `${R_HOME}/bin/Rscript -e "RcppParallel::RcppParallelLibs()"` $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) 4 | -------------------------------------------------------------------------------- /src/Makevars.win: -------------------------------------------------------------------------------- 1 | CXX_STD = CXX11 2 | 3 | PKG_CXXFLAGS += -DRCPP_PARALLEL_USE_TBB=1 4 | 5 | PKG_LIBS += $(shell "${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe" \ 6 | -e "RcppParallel::RcppParallelLibs()") $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) 7 | -------------------------------------------------------------------------------- /src/RcppExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #include 5 | #include 6 | 7 | using namespace Rcpp; 8 | 9 | #ifdef RCPP_USE_GLOBAL_ROSTREAM 10 | Rcpp::Rostream& Rcpp::Rcout = Rcpp::Rcpp_cout_get(); 11 | Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get(); 12 | #endif 13 | 14 | // cpp_parallelDistVec 15 | Rcpp::NumericVector cpp_parallelDistVec(Rcpp::List dataList, Rcpp::List attrs, Rcpp::List arguments); 16 | RcppExport SEXP _parallelDist_cpp_parallelDistVec(SEXP dataListSEXP, SEXP attrsSEXP, SEXP argumentsSEXP) { 17 | BEGIN_RCPP 18 | Rcpp::RObject rcpp_result_gen; 19 | Rcpp::RNGScope rcpp_rngScope_gen; 20 | Rcpp::traits::input_parameter< Rcpp::List >::type dataList(dataListSEXP); 21 | Rcpp::traits::input_parameter< Rcpp::List >::type attrs(attrsSEXP); 22 | Rcpp::traits::input_parameter< Rcpp::List >::type arguments(argumentsSEXP); 23 | rcpp_result_gen = Rcpp::wrap(cpp_parallelDistVec(dataList, attrs, arguments)); 24 | return rcpp_result_gen; 25 | END_RCPP 26 | } 27 | // cpp_parallelDistMatrixVec 28 | Rcpp::NumericVector cpp_parallelDistMatrixVec(arma::mat dataMatrix, Rcpp::List attrs, Rcpp::List arguments); 29 | RcppExport SEXP _parallelDist_cpp_parallelDistMatrixVec(SEXP dataMatrixSEXP, SEXP attrsSEXP, SEXP argumentsSEXP) { 30 | BEGIN_RCPP 31 | Rcpp::RObject rcpp_result_gen; 32 | Rcpp::RNGScope rcpp_rngScope_gen; 33 | Rcpp::traits::input_parameter< arma::mat >::type dataMatrix(dataMatrixSEXP); 34 | Rcpp::traits::input_parameter< Rcpp::List >::type attrs(attrsSEXP); 35 | Rcpp::traits::input_parameter< Rcpp::List >::type arguments(argumentsSEXP); 36 | rcpp_result_gen = Rcpp::wrap(cpp_parallelDistMatrixVec(dataMatrix, attrs, arguments)); 37 | return rcpp_result_gen; 38 | END_RCPP 39 | } 40 | 41 | static const R_CallMethodDef CallEntries[] = { 42 | {"_parallelDist_cpp_parallelDistVec", (DL_FUNC) &_parallelDist_cpp_parallelDistVec, 3}, 43 | {"_parallelDist_cpp_parallelDistMatrixVec", (DL_FUNC) &_parallelDist_cpp_parallelDistMatrixVec, 3}, 44 | {NULL, NULL, 0} 45 | }; 46 | 47 | RcppExport void R_init_parallelDist(DllInfo *dll) { 48 | R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); 49 | R_useDynamicSymbols(dll, FALSE); 50 | } 51 | -------------------------------------------------------------------------------- /src/StepPattern.h: -------------------------------------------------------------------------------- 1 | // StepPattern.h 2 | // 3 | // Copyright (C) 2017, 2021 Alexander Eckert 4 | // 5 | // This file is part of parallelDist. 6 | // 7 | // parallelDist is free software: you can redistribute it and/or modify it 8 | // under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 2 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // parallelDist is distributed in the hope that it will be useful, but 13 | // WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with parallelDist. If not, see . 19 | 20 | #ifndef STEPPATTERN_H_ 21 | #define STEPPATTERN_H_ 22 | 23 | #include "DistanceDTWGeneric.h" 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | // StepPatternSymmetric1 30 | // g[i,j] = min( 31 | // g[i-1,j-1] + d[i ,j ] , 32 | // g[i ,j-1] + d[i ,j ] , 33 | // g[i-1,j ] + d[i ,j ] , 34 | // ) 35 | class StepPatternSymmetric1 : public DistanceDTWGeneric { 36 | public: 37 | using DistanceDTWGeneric::DistanceDTWGeneric; 38 | static constexpr unsigned int patternOffset = 1; 39 | std::pair getCost(double *pen, unsigned int bSizeOffset, const arma::mat &A, const arma::mat &B, 40 | unsigned int i, unsigned int j) { 41 | double distance = getDistance(A, B, i, j); 42 | // bound checking for this step pattern 43 | double minArray[3] = { 44 | getCell(pen, bSizeOffset, i - 1, j - 1), 45 | getCell(pen, bSizeOffset, i, j - 1), 46 | getCell(pen, bSizeOffset, i - 1, j)}; 47 | 48 | std::pair result = argmin(minArray, 3); 49 | result.first += distance; 50 | return result; 51 | } 52 | }; 53 | 54 | // StepPatternSymmetric2 55 | // g[i,j] = min( 56 | // g[i-1,j-1] + 2 * d[i ,j ] , 57 | // g[i ,j-1] + d[i ,j ] , 58 | // g[i-1,j ] + d[i ,j ] , 59 | // ) 60 | class StepPatternSymmetric2 : public DistanceDTWGeneric { 61 | public: 62 | using DistanceDTWGeneric::DistanceDTWGeneric; 63 | static constexpr unsigned int patternOffset = 1; 64 | std::pair getCost(double *pen, unsigned int bSizeOffset, const arma::mat &A, const arma::mat &B, 65 | unsigned int i, unsigned int j) { 66 | double distance = getDistance(A, B, i, j); 67 | // bound checking for this step pattern 68 | double minArray[3] = { 69 | 2 * distance + getCell(pen, bSizeOffset, i - 1, j - 1), 70 | distance + getCell(pen, bSizeOffset, i, j - 1), 71 | distance + getCell(pen, bSizeOffset, i - 1, j)}; 72 | return argmin(minArray, 3); 73 | } 74 | }; 75 | 76 | // StepPatternAsymmetric 77 | // g[i,j] = min( 78 | // g[i-1,j ] + d[i ,j ] , 79 | // g[i-1,j-1] + d[i ,j ] , 80 | // g[i-1,j-2] + d[i ,j ] , 81 | // ) 82 | class StepPatternAsymmetric : public DistanceDTWGeneric { 83 | public: 84 | using DistanceDTWGeneric::DistanceDTWGeneric; 85 | static constexpr unsigned int patternOffset = 2; 86 | std::pair getCost(double *pen, unsigned int bSizeOffset, const arma::mat &A, const arma::mat &B, 87 | unsigned int i, unsigned int j) { 88 | double distance = getDistance(A, B, i, j); 89 | // bound checking for this step pattern 90 | double minArray[3] = { 91 | distance + getCell(pen, bSizeOffset, i - 1, j), 92 | distance + getCell(pen, bSizeOffset, i - 1, j - 1), 93 | distance + getCell(pen, bSizeOffset, i - 1, j - 2)}; 94 | 95 | return argmin(minArray, 3); 96 | } 97 | }; 98 | 99 | // StepPatternAsymmetricP0 100 | // g[i,j] = min( 101 | // g[i ,j-1] + 0 * d[i ,j ] , 102 | // g[i-1,j-1] + d[i ,j ] , 103 | // g[i-1,j ] + d[i ,j ] , 104 | // ) 105 | class StepPatternAsymmetricP0 : public DistanceDTWGeneric { 106 | public: 107 | using DistanceDTWGeneric::DistanceDTWGeneric; 108 | static constexpr unsigned int patternOffset = 1; 109 | std::pair getCost(double *pen, unsigned int bSizeOffset, const arma::mat &A, const arma::mat &B, 110 | unsigned int i, unsigned int j) { 111 | double distance = getDistance(A, B, i, j); 112 | // bound checking for this step pattern 113 | double minArray[3] = { 114 | getCell(pen, bSizeOffset, i, j - 1), 115 | distance + getCell(pen, bSizeOffset, i - 1, j - 1), 116 | distance + getCell(pen, bSizeOffset, i - 1, j)}; 117 | 118 | return argmin(minArray, 3); 119 | } 120 | }; 121 | 122 | // StepPatternAsymmetricP05 123 | // g[i,j] = min( 124 | // g[i-1,j-3] +0.33 * d[i ,j-2] +0.33 * d[i ,j-1] +0.33 * d[i ,j ] , 125 | // g[i-1,j-2] +0.5 * d[i ,j-1] +0.5 * d[i ,j ] , 126 | // g[i-1,j-1] + d[i ,j ] , 127 | // g[i-2,j-1] + d[i-1,j ] + d[i ,j ] , 128 | // g[i-3,j-1] + d[i-2,j ] + d[i-1,j ] + d[i ,j ] , 129 | // ) 130 | class StepPatternAsymmetricP05 : public DistanceDTWGeneric { 131 | public: 132 | using DistanceDTWGeneric::DistanceDTWGeneric; 133 | static constexpr unsigned int patternOffset = 3; 134 | std::pair getCost(double *pen, unsigned int bSizeOffset, const arma::mat &A, const arma::mat &B, 135 | unsigned int i, unsigned int j) { 136 | double multiplier = 1.0 / 3; 137 | double minArray[5] = { 138 | getCell(pen, bSizeOffset, i - 1, j - 3) + multiplier * getDistance(A, B, i, j - 2) + 139 | multiplier * getDistance(A, B, i, j - 1) + multiplier * getDistance(A, B, i, j), 140 | getCell(pen, bSizeOffset, i - 1, j - 2) + 0.5 * getDistance(A, B, i, j - 1) + 0.5 * getDistance(A, B, i, j), 141 | getCell(pen, bSizeOffset, i - 1, j - 1) + getDistance(A, B, i, j), 142 | getCell(pen, bSizeOffset, i - 2, j - 1) + getDistance(A, B, i - 1, j) + getDistance(A, B, i, j), 143 | getCell(pen, bSizeOffset, i - 3, j - 1) + getDistance(A, B, i - 2, j) + getDistance(A, B, i - 1, j) + 144 | getDistance(A, B, i, j)}; 145 | return argmin(minArray, 5); 146 | } 147 | }; 148 | 149 | // 150 | // g[i,j] = min( 151 | // g[i-1,j-3] + 2 * d[i ,j-2] + d[i ,j-1] + d[i ,j ] , 152 | // g[i-1,j-2] + 2 * d[i ,j-1] + d[i ,j ] , 153 | // g[i-1,j-1] + 2 * d[i ,j ] , 154 | // g[i-2,j-1] + 2 * d[i-1,j ] + d[i ,j ] , 155 | // g[i-3,j-1] + 2 * d[i-2,j ] + d[i-1,j ] + d[i ,j ] , 156 | // ) 157 | class StepPatternSymmetricP05 : public DistanceDTWGeneric { 158 | public: 159 | using DistanceDTWGeneric::DistanceDTWGeneric; 160 | static constexpr unsigned int patternOffset = 3; 161 | std::pair getCost(double *pen, unsigned int bSizeOffset, const arma::mat &A, const arma::mat &B, 162 | unsigned int i, unsigned int j) { 163 | double minArray[5] = { 164 | getCell(pen, bSizeOffset, i - 1, j - 3) + 2 * getDistance(A, B, i, j - 2) + getDistance(A, B, i, j - 1) + 165 | getDistance(A, B, i, j), 166 | getCell(pen, bSizeOffset, i - 1, j - 2) + 2 * getDistance(A, B, i, j - 1) + getDistance(A, B, i, j), 167 | getCell(pen, bSizeOffset, i - 1, j - 1) + 2 * getDistance(A, B, i, j), 168 | getCell(pen, bSizeOffset, i - 2, j - 1) + 2 * getDistance(A, B, i - 1, j) + getDistance(A, B, i, j), 169 | getCell(pen, bSizeOffset, i - 3, j - 1) + 2 * getDistance(A, B, i - 2, j) + getDistance(A, B, i - 1, j) + 170 | getDistance(A, B, i, j)}; 171 | return argmin(minArray, 5); 172 | } 173 | }; 174 | 175 | class StepPatternSymmetricP1 : public DistanceDTWGeneric { 176 | public: 177 | using DistanceDTWGeneric::DistanceDTWGeneric; 178 | static constexpr unsigned int patternOffset = 2; 179 | std::pair getCost(double *pen, unsigned int bSizeOffset, const arma::mat &A, const arma::mat &B, 180 | unsigned int i, unsigned int j) { 181 | double minArray[3] = { 182 | getCell(pen, bSizeOffset, i - 1, j - 2) + 2 * getDistance(A, B, i, j - 1) + getDistance(A, B, i, j), 183 | getCell(pen, bSizeOffset, i - 1, j - 1) + 2 * getDistance(A, B, i, j), 184 | getCell(pen, bSizeOffset, i - 2, j - 1) + 2 * getDistance(A, B, i - 1, j) + getDistance(A, B, i, j)}; 185 | return argmin(minArray, 3); 186 | } 187 | }; 188 | 189 | class StepPatternAsymmetricP1 : public DistanceDTWGeneric { 190 | public: 191 | using DistanceDTWGeneric::DistanceDTWGeneric; 192 | static constexpr unsigned int patternOffset = 2; 193 | std::pair getCost(double *pen, unsigned int bSizeOffset, const arma::mat &A, const arma::mat &B, 194 | unsigned int i, unsigned int j) { 195 | double minArray[3] = { 196 | getCell(pen, bSizeOffset, i - 1, j - 2) + 0.5 * getDistance(A, B, i, j - 1) + 0.5 * getDistance(A, B, i, j), 197 | getCell(pen, bSizeOffset, i - 1, j - 1) + getDistance(A, B, i, j), 198 | getCell(pen, bSizeOffset, i - 2, j - 1) + getDistance(A, B, i - 1, j) + getDistance(A, B, i, j)}; 199 | return argmin(minArray, 3); 200 | } 201 | }; 202 | 203 | // StepPatternAsymmetricP2 204 | // g[i,j] = min( 205 | // g[i-2,j-3] +0.67 * d[i-1,j-2] +0.67 * d[i ,j-1] +0.67 * d[i ,j ] , 206 | // g[i-1,j-1] + d[i ,j ] , 207 | // g[i-3,j-2] + d[i-2,j-1] + d[i-1,j ] + d[i ,j ] , 208 | // ) 209 | class StepPatternAsymmetricP2 : public DistanceDTWGeneric { 210 | public: 211 | using DistanceDTWGeneric::DistanceDTWGeneric; 212 | static constexpr unsigned int patternOffset = 3; 213 | std::pair getCost(double *pen, unsigned int bSizeOffset, const arma::mat &A, const arma::mat &B, 214 | unsigned int i, unsigned int j) { 215 | double multiplier = 2.0 / 3; 216 | double minArray[3] = { 217 | getCell(pen, bSizeOffset, i - 2, j - 3) + multiplier * getDistance(A, B, i - 1, j - 2) + 218 | multiplier * getDistance(A, B, i, j - 1) + multiplier * getDistance(A, B, i, j), 219 | getCell(pen, bSizeOffset, i - 1, j - 1) + getDistance(A, B, i, j), 220 | getCell(pen, bSizeOffset, i - 3, j - 2) + getDistance(A, B, i - 2, j - 1) + getDistance(A, B, i - 1, j) + 221 | getDistance(A, B, i, j)}; 222 | return argmin(minArray, 3); 223 | } 224 | }; 225 | 226 | // StepPatternSymmetricP2 227 | // g[i,j] = min( 228 | // g[i-2,j-3] + 2 * d[i-1,j-2] + 2 * d[i ,j-1] + d[i ,j ] , 229 | // g[i-1,j-1] + 2 * d[i ,j ] , 230 | // g[i-3,j-2] + 2 * d[i-2,j-1] + 2 * d[i-1,j ] + d[i ,j ] , 231 | // ) 232 | class StepPatternSymmetricP2 : public DistanceDTWGeneric { 233 | public: 234 | using DistanceDTWGeneric::DistanceDTWGeneric; 235 | static constexpr unsigned int patternOffset = 3; 236 | std::pair getCost(double *pen, unsigned int bSizeOffset, const arma::mat &A, const arma::mat &B, 237 | unsigned int i, unsigned int j) { 238 | double minArray[3] = { 239 | getCell(pen, bSizeOffset, i - 2, j - 3) + 2 * getDistance(A, B, i - 1, j - 2) + 2 * getDistance(A, B, i, j - 1) + 240 | getDistance(A, B, i, j), 241 | getCell(pen, bSizeOffset, i - 1, j - 1) + 2 * getDistance(A, B, i, j), 242 | getCell(pen, bSizeOffset, i - 3, j - 2) + 2 * getDistance(A, B, i - 2, j - 1) + 2 * getDistance(A, B, i - 1, j) + 243 | getDistance(A, B, i, j)}; 244 | return argmin(minArray, 3); 245 | } 246 | }; 247 | 248 | #endif // STEPPATTERN_H_ 249 | -------------------------------------------------------------------------------- /src/Util.cpp: -------------------------------------------------------------------------------- 1 | // Util.cpp 2 | // 3 | // Copyright (C) 2017, 2021 Alexander Eckert 4 | // 5 | // This file is part of parallelDist. 6 | // 7 | // parallelDist is free software: you can redistribute it and/or modify it 8 | // under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 2 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // parallelDist is distributed in the hope that it will be useful, but 13 | // WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with parallelDist. If not, see . 19 | 20 | #include "Util.h" 21 | 22 | namespace util { 23 | 24 | bool isEqualStr(const std::string &str1, std::string str2) { 25 | return str1.compare(str2) == 0; 26 | } 27 | 28 | double similarityToDistance(const double distance) { 29 | return 1.0 - std::abs(distance); 30 | } 31 | 32 | } // namespace util 33 | -------------------------------------------------------------------------------- /src/Util.h: -------------------------------------------------------------------------------- 1 | // Util.h 2 | // 3 | // Copyright (C) 2017, 2021 Alexander Eckert 4 | // 5 | // This file is part of parallelDist. 6 | // 7 | // parallelDist is free software: you can redistribute it and/or modify it 8 | // under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 2 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // parallelDist is distributed in the hope that it will be useful, but 13 | // WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with parallelDist. If not, see . 19 | 20 | #ifndef UTIL_H_ 21 | #define UTIL_H_ 22 | 23 | #include 24 | #include 25 | #include 26 | 27 | namespace util { 28 | 29 | bool isEqualStr(const std::string &str1, std::string str2); 30 | 31 | double similarityToDistance(const double distance); 32 | 33 | } // namespace util 34 | 35 | #endif // UTIL_H_ 36 | -------------------------------------------------------------------------------- /src/parallelDist.cpp: -------------------------------------------------------------------------------- 1 | // parallelDist.cpp 2 | // 3 | // Copyright (C) 2017, 2021 Alexander Eckert 4 | // 5 | // This file is part of parallelDist. 6 | // 7 | // parallelDist is free software: you can redistribute it and/or modify it 8 | // under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 2 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // parallelDist is distributed in the hope that it will be useful, but 13 | // WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with parallelDist. If not, see . 19 | 20 | #include 21 | #include 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | #include "DistanceFactory.h" 30 | #include "IDistance.h" 31 | 32 | uint64_t sumForm(const uint64_t n) { 33 | return ((n * n) + n) / 2; 34 | } 35 | 36 | uint64_t matToVecIdx(const uint64_t i, const uint64_t j, const uint64_t N) { 37 | return i * N - i - sumForm(i) - 1 + j; 38 | } 39 | 40 | inline bool isInteger(const std::string &s) { 41 | if (s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) 42 | return false; 43 | char *p; 44 | strtol(s.c_str(), &p, 10); 45 | return (*p == 0); 46 | } 47 | 48 | struct DistanceVec : public RcppParallel::Worker { 49 | // input vector of matrices 50 | const std::vector &seriesVec; 51 | 52 | int vecSize = 0; 53 | 54 | // output vector by reference 55 | Rcpp::NumericVector &rvec; 56 | 57 | // distance function 58 | std::shared_ptr distance; 59 | 60 | // initialize from Rcpp input and output matrixes (the RMatrix class 61 | // can be automatically converted to from the Rcpp matrix type) 62 | DistanceVec(const std::vector &seriesVec, Rcpp::NumericVector &rvec, 63 | const std::shared_ptr &distance) 64 | : seriesVec(seriesVec), rvec(rvec), distance(distance) { 65 | vecSize = seriesVec.size(); 66 | } 67 | 68 | void operator()(std::size_t begin, std::size_t end) { 69 | for (std::size_t i = begin; i < end; i++) { 70 | for (std::size_t j = 0; j < i; j++) { 71 | rvec[matToVecIdx(j, i, vecSize)] = distance->calcDistance(seriesVec.at(i), seriesVec.at(j)); 72 | } 73 | } 74 | } 75 | }; 76 | 77 | // uses not a list but the matrix 78 | struct DistanceMatrixVec : public RcppParallel::Worker { 79 | // input vector of matrices 80 | const arma::mat &seriesVec; 81 | 82 | int vecSize = 0; 83 | 84 | // output vector by reference 85 | Rcpp::NumericVector &rvec; 86 | 87 | // distance function 88 | std::shared_ptr distance; 89 | 90 | // initialize from Rcpp input and output matrixes (the RMatrix class 91 | // can be automatically converted to from the Rcpp matrix type) 92 | DistanceMatrixVec(const arma::mat &seriesVec, Rcpp::NumericVector &rvec, const std::shared_ptr &distance) 93 | : seriesVec(seriesVec), rvec(rvec), distance(distance) { 94 | vecSize = seriesVec.n_rows; 95 | } 96 | 97 | void operator()(std::size_t begin, std::size_t end) { 98 | for (std::size_t i = begin; i < end; i++) { 99 | for (std::size_t j = 0; j < i; j++) { 100 | rvec[matToVecIdx(j, i, vecSize)] = distance->calcDistance(seriesVec.row(i), seriesVec.row(j)); 101 | } 102 | } 103 | } 104 | }; 105 | 106 | void setVectorAttributes(Rcpp::NumericVector &rvec, const Rcpp::List &attrs) { 107 | rvec.attr("Size") = attrs["Size"]; 108 | rvec.attr("Labels") = attrs["Labels"]; 109 | rvec.attr("Diag") = Rcpp::as(attrs["Diag"]); 110 | rvec.attr("Upper") = Rcpp::as(attrs["Upper"]); 111 | rvec.attr("method") = attrs["method"]; 112 | rvec.attr("call") = attrs["call"]; 113 | rvec.attr("class") = "dist"; 114 | } 115 | 116 | // [[Rcpp::export]] 117 | Rcpp::NumericVector cpp_parallelDistVec(Rcpp::List dataList, Rcpp::List attrs, Rcpp::List arguments) { 118 | uint64_t n = dataList.size(); 119 | // result matrix 120 | Rcpp::NumericVector rvec(sumForm(n) - n); 121 | 122 | setVectorAttributes(rvec, attrs); 123 | 124 | // Convert list to vector of double matrices 125 | std::vector listVec; 126 | for (Rcpp::List::iterator it = dataList.begin(); it != dataList.end(); ++it) { 127 | listVec.push_back(Rcpp::as(*it)); 128 | } 129 | std::shared_ptr distanceFunction = DistanceFactory(listVec).createDistanceFunction(attrs, arguments); 130 | 131 | DistanceVec *distanceWorker = new DistanceVec(listVec, rvec, distanceFunction); 132 | // call it with parallelFor 133 | RcppParallel::parallelFor(0, n, (*distanceWorker)); 134 | delete distanceWorker; 135 | distanceWorker = NULL; 136 | 137 | return rvec; 138 | } 139 | 140 | // [[Rcpp::export]] 141 | Rcpp::NumericVector cpp_parallelDistMatrixVec(arma::mat dataMatrix, Rcpp::List attrs, Rcpp::List arguments) { 142 | uint64_t n = dataMatrix.n_rows; 143 | 144 | // result matrix 145 | Rcpp::NumericVector rvec(sumForm(n) - n); 146 | 147 | setVectorAttributes(rvec, attrs); 148 | 149 | std::shared_ptr distanceFunction = DistanceFactory(dataMatrix).createDistanceFunction(attrs, arguments); 150 | DistanceMatrixVec *distanceWorker = new DistanceMatrixVec(dataMatrix, rvec, distanceFunction); 151 | // call it with parallelFor 152 | RcppParallel::parallelFor(0, n, (*distanceWorker)); 153 | delete distanceWorker; 154 | distanceWorker = NULL; 155 | 156 | return rvec; 157 | } 158 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | ## testthat.R 2 | ## 3 | ## Copyright (C) 2017 Alexander Eckert 4 | ## 5 | ## This file is part of parallelDist. 6 | ## 7 | ## parallelDist is free software: you can redistribute it and/or modify it 8 | ## under the terms of the GNU General Public License as published by 9 | ## the Free Software Foundation, either version 2 of the License, or 10 | ## (at your option) any later version. 11 | ## 12 | ## parallelDist is distributed in the hope that it will be useful, but 13 | ## WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ## GNU General Public License for more details. 16 | ## 17 | ## You should have received a copy of the GNU General Public License 18 | ## along with parallelDist. If not, see . 19 | 20 | library(testthat) 21 | library(parallelDist) 22 | 23 | # workaround for error "cannot open file 'startup.Rs': No such file or directory" 24 | Sys.setenv("R_TESTS" = "") 25 | test_check("parallelDist") 26 | -------------------------------------------------------------------------------- /tests/testthat/helper.R: -------------------------------------------------------------------------------- 1 | ## helper.R 2 | ## 3 | ## Copyright (C) 2021 Alexander Eckert 4 | ## 5 | ## This file is part of parallelDist. 6 | ## 7 | ## parallelDist is free software: you can redistribute it and/or modify it 8 | ## under the terms of the GNU General Public License as published by 9 | ## the Free Software Foundation, either version 2 of the License, or 10 | ## (at your option) any later version. 11 | ## 12 | ## parallelDist is distributed in the hope that it will be useful, but 13 | ## WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ## GNU General Public License for more details. 16 | ## 17 | ## You should have received a copy of the GNU General Public License 18 | ## along with parallelDist. If not, see . 19 | 20 | isCran <- function() { 21 | !identical(Sys.getenv("NOT_CRAN"), "true") 22 | } 23 | 24 | suppressNaNWarnings <- function(expr) { 25 | tryCatch( 26 | expr = expr, 27 | # suppress NA errors 28 | warning = function(w){ 29 | if (w$message != "NaNs produced") { 30 | warning(w) 31 | } 32 | }) 33 | } 34 | -------------------------------------------------------------------------------- /tests/testthat/testMatrixCustomDistances.R: -------------------------------------------------------------------------------- 1 | ## testMatrixCustomDistances.R 2 | ## 3 | ## Copyright (C) 2017, 2021 Alexander Eckert 4 | ## 5 | ## This file is part of parallelDist. 6 | ## 7 | ## parallelDist is free software: you can redistribute it and/or modify it 8 | ## under the terms of the GNU General Public License as published by 9 | ## the Free Software Foundation, either version 2 of the License, or 10 | ## (at your option) any later version. 11 | ## 12 | ## parallelDist is distributed in the hope that it will be useful, but 13 | ## WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ## GNU General Public License for more details. 16 | ## 17 | ## You should have received a copy of the GNU General Public License 18 | ## along with parallelDist. If not, see . 19 | 20 | context("Custom distance methods using matrix as input") 21 | 22 | mat.sample1 <- matrix(c(0,1,0,1,0,0,1,0), nrow = 2) 23 | mat.sample2 <- matrix(c(0,1,0,1,0,0,1,0,1,1), nrow = 2) 24 | mat.sample3 <- matrix(c(1:500), ncol = 5) 25 | mat.sample4 <- matrix(rep(0,100), ncol = 5) 26 | mat.sample5 <- matrix(c(-500:499), ncol = 5) 27 | mat.sample6 <- matrix(c(1:2), ncol = 1) 28 | mat.sample7 <- matrix(c(0.5,1,0,1,0,0,1,0.3,1,1), nrow = 2) 29 | 30 | mat.list <- list(mat.sample1, mat.sample2, mat.sample3, mat.sample4, mat.sample5, mat.sample6, mat.sample7) 31 | 32 | if (isCran()) { 33 | mat.list <- mat.list[1:4] 34 | } 35 | 36 | testMatrixEquality <- function(matrix, comparisonMethod, func, ...) { 37 | expect_equal(as.matrix(parDist(matrix, method = "custom", func=func, ...)), as.matrix(parDist(matrix, method = comparisonMethod, ...))) 38 | } 39 | 40 | testMatrixListEquality <- function(matlist, comparisonMethod, func, ...) { 41 | invisible(sapply(matlist, function(x) { testMatrixEquality(x, comparisonMethod, func, ...) })) 42 | } 43 | 44 | library(RcppXPtrUtils) 45 | test_that("error for missing func parameter shows up", { 46 | expect_error(parDist(mat.sample1, method = "custom"), "Parameter 'func' is missing.") 47 | }) 48 | 49 | test_that("custom euclidean distance method produces same outputs as native method", { 50 | skip_on_os("solaris") 51 | ptr <- cppXPtr("double customDist(const arma::mat &A, const arma::mat &B) { return sqrt(arma::accu(arma::square(A - B))); }", depends = c("RcppArmadillo")) 52 | testMatrixListEquality(mat.list, "euclidean", func=ptr) 53 | }) 54 | 55 | test_that("error for wrong return value of func pointer shows up", { 56 | skip_on_os("solaris") 57 | ptr <- cppXPtr("int customDist(const arma::mat &A, const arma::mat &B) { return 0; }", depends = c("RcppArmadillo")) 58 | expect_error(parDist(mat.sample1, method = "custom", func=ptr), "Wrong return type 'int', should be 'double'.") 59 | }) 60 | 61 | test_that("error for wrong argument type of func pointer shows up", { 62 | skip_on_os("solaris") 63 | ptr <- cppXPtr("double customDist(int a, const arma::mat &B) { return 0; }", depends = c("RcppArmadillo")) 64 | expect_error(parDist(mat.sample1, method = "custom", func=ptr), "Wrong argument type 'int', should be 'const arma::mat&'.") 65 | }) 66 | 67 | test_that("error for wrong number of arguments of func pointer shows up", { 68 | skip_on_os("solaris") 69 | ptr <- cppXPtr("double customDist(const arma::mat &A) { return 0; }", depends = c("RcppArmadillo")) 70 | expect_error(parDist(mat.sample1, method = "custom", func=ptr), "Wrong number of arguments \\('1'\\), should be 2.") 71 | }) 72 | -------------------------------------------------------------------------------- /tests/testthat/testMatrixDTWDistances.R: -------------------------------------------------------------------------------- 1 | ## testMatrixDTWDistances.R 2 | ## 3 | ## Copyright (C) 2017, 2021 Alexander Eckert 4 | ## 5 | ## This file is part of parallelDist. 6 | ## 7 | ## parallelDist is free software: you can redistribute it and/or modify it 8 | ## under the terms of the GNU General Public License as published by 9 | ## the Free Software Foundation, either version 2 of the License, or 10 | ## (at your option) any later version. 11 | ## 12 | ## parallelDist is distributed in the hope that it will be useful, but 13 | ## WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ## GNU General Public License for more details. 16 | ## 17 | ## You should have received a copy of the GNU General Public License 18 | ## along with parallelDist. If not, see . 19 | 20 | context("DTW distance methods using matrix as input") 21 | 22 | mat.sample1 <- matrix(c(0,1,0,1,0,0,1,0), nrow = 2) 23 | mat.sample2 <- matrix(c(0,1,0,1,0,0,1,0,1,1), nrow = 2) 24 | mat.sample3 <- matrix(c(0,1,0,1,0,0,1,0,1,1,0,1), nrow = 3) 25 | mat.sample4 <- matrix(c(1:100), ncol = 5) 26 | mat.sample5 <- matrix(rep(0,100), ncol = 5) 27 | mat.sample6 <- matrix(c(-50:49), ncol = 5) 28 | mat.sample7 <- matrix(c(1:8), ncol = 2) 29 | mat.sample8 <- matrix(c(1:15), ncol = 5) 30 | mat.sample9 <- matrix(c(1,88,55,72,3,33,44,11,3,42, 52,29,3,45,34,21,34,59,35,84), nrow = 2, byrow = TRUE) 31 | tolerance <- 1e-8 32 | 33 | mat.list <- list(mat.sample1, mat.sample2, mat.sample3, mat.sample4, mat.sample5, mat.sample6, mat.sample7, mat.sample8, mat.sample9) 34 | 35 | if (isCran()) { 36 | mat.list <- mat.list[1:5] 37 | } 38 | 39 | library(dtw) 40 | testMatrixEquality <- function(matrix, method, ...) { 41 | expect_equal(as.matrix(parDist(matrix, method = method, ...)), as.matrix(dist(matrix, method = method, ...))) 42 | } 43 | 44 | testMatrixEqualityForMatList <- function(matlist, method, ...) { 45 | invisible(sapply(matlist, function(x) { testMatrixEquality(x, method, ...) })) 46 | } 47 | 48 | # Tests 49 | test_that("error for unsupported step pattern shows up", { 50 | expect_error(parDist(mat.sample1, method = "dtw", step.pattern="unknown"), "Step pattern is not supported.") 51 | }) 52 | 53 | test_that("parDist and dtw produces same results for different step patterns", { 54 | # symmetric1 / symmetric 55 | testMatrixEqualityForMatList(mat.list, method="dtw", window.type="none", step.pattern=symmetric1) 56 | invisible(sapply(mat.list, function(x) { 57 | expect_equal(as.matrix(parDist(x, method = "dtw", window.type="none", step.pattern="symmetric1")), 58 | as.matrix(dist(x, method = "dtw", step.pattern=symmetric1))) 59 | })) # step.pattern as string 60 | testMatrixEqualityForMatList(mat.list, method="dtw", window.size = 5, window.type=sakoeChibaWindow, step.pattern=symmetric1) 61 | 62 | # symmetric2 / symmetricP0 63 | testMatrixEqualityForMatList(mat.list, method="dtw", window.type="none", step.pattern=symmetric2) 64 | testMatrixEqualityForMatList(mat.list, method="dtw", window.size = 5, window.type=sakoeChibaWindow, step.pattern=symmetric2) 65 | 66 | # symmetricP05 67 | testMatrixEqualityForMatList(mat.list, method="dtw", window.type="none", step.pattern=symmetricP05) 68 | testMatrixEqualityForMatList(mat.list, method="dtw", window.size = 5, window.type=sakoeChibaWindow, step.pattern=symmetricP05) 69 | 70 | # symmetricP1 71 | testMatrixEqualityForMatList(mat.list, method="dtw", window.type="none", step.pattern=symmetricP1) 72 | testMatrixEqualityForMatList(mat.list, method="dtw", window.size = 5, window.type=sakoeChibaWindow, step.pattern=symmetricP1) 73 | 74 | # symmetricP2 75 | testMatrixEqualityForMatList(mat.list, method="dtw", window.type="none", step.pattern=symmetricP2) 76 | testMatrixEqualityForMatList(mat.list, method="dtw", window.size = 5, window.type=sakoeChibaWindow, step.pattern=symmetricP2) 77 | 78 | # asymmetric 79 | testMatrixEqualityForMatList(mat.list, method="dtw", window.type="none", step.pattern=asymmetric) 80 | testMatrixEqualityForMatList(mat.list, method="dtw", window.size = 5, window.type=sakoeChibaWindow, step.pattern=asymmetric) 81 | 82 | # asymmetricP0 83 | testMatrixEqualityForMatList(mat.list, method="dtw", window.type="none", step.pattern=asymmetricP0) 84 | testMatrixEqualityForMatList(mat.list, method="dtw", window.size = 5, window.type=sakoeChibaWindow, step.pattern=asymmetricP0) 85 | 86 | # asymmetricP05 87 | testMatrixEqualityForMatList(mat.list, method="dtw", window.type="none", step.pattern=asymmetricP05) 88 | testMatrixEqualityForMatList(mat.list, method="dtw", window.size = 5, window.type=sakoeChibaWindow, step.pattern=asymmetricP05) 89 | 90 | # asymmetricP1 91 | testMatrixEqualityForMatList(mat.list, method="dtw", window.type="none", step.pattern=asymmetricP1) 92 | testMatrixEqualityForMatList(mat.list, method="dtw", window.size = 5, window.type=sakoeChibaWindow, step.pattern=asymmetricP1) 93 | 94 | # asymmetricP2 95 | testMatrixEqualityForMatList(mat.list, method="dtw", window.type="none", step.pattern=asymmetricP2) 96 | testMatrixEqualityForMatList(mat.list, method="dtw", window.size = 5, window.type=sakoeChibaWindow, step.pattern=asymmetricP2) 97 | }) 98 | 99 | # warping path normalization 100 | test_that("Warping path normalization produces expected outputs", { 101 | expect_equal(as.matrix(parDist(mat.sample9[1:2, 1:3], method = "dtw", norm.method="path.length", threads=1)), 102 | as.matrix(dist(mat.sample9[1:2, 1:3], method = "dtw", step.pattern=symmetric1)) / 3, 103 | tolerance=tolerance) 104 | expect_equal(as.matrix(parDist(mat.sample3, method = "dtw", norm.method="path.length", threads=1)), 105 | as.matrix(dist(mat.sample3, method = "dtw", step.pattern=symmetric1)) / 5, 106 | tolerance=tolerance) 107 | expect_equal(as.matrix(parDist(mat.sample4[c(3, 20),], method = "dtw", norm.method="path.length", threads=1)), 108 | as.matrix(dist(mat.sample4[c(3, 20),], method = "dtw", step.pattern=symmetric1)) / 7, tolerance=tolerance) 109 | expect_equal(as.matrix(parDist(mat.sample9, method = "dtw", norm.method="n")), 110 | as.matrix(dist(mat.sample9, method = "dtw", step.pattern=symmetric1)) / dim(mat.sample9)[2], 111 | tolerance=tolerance) 112 | expect_equal(as.matrix(parDist(mat.sample9, method = "dtw", norm.method="n+m")), 113 | as.matrix(dist(mat.sample9, method = "dtw", step.pattern=symmetric1)) / (dim(mat.sample9)[2] * 2), 114 | tolerance=tolerance) 115 | }) 116 | -------------------------------------------------------------------------------- /tests/testthat/testMatrixDistances.R: -------------------------------------------------------------------------------- 1 | ## testMatrixDistances.R 2 | ## 3 | ## Copyright (C) 2017, 2021 Alexander Eckert 4 | ## 5 | ## This file is part of parallelDist. 6 | ## 7 | ## parallelDist is free software: you can redistribute it and/or modify it 8 | ## under the terms of the GNU General Public License as published by 9 | ## the Free Software Foundation, either version 2 of the License, or 10 | ## (at your option) any later version. 11 | ## 12 | ## parallelDist is distributed in the hope that it will be useful, but 13 | ## WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ## GNU General Public License for more details. 16 | ## 17 | ## You should have received a copy of the GNU General Public License 18 | ## along with parallelDist. If not, see . 19 | 20 | context("Distance methods using matrix as input") 21 | 22 | mat.sample1 <- matrix(c(0, 1, 0, 1, 0, 0, 1, 0), nrow = 2) 23 | mat.sample2 <- matrix(c(0, 1, 0, 1, 0, 0, 1, 0, 1, 1), nrow = 2) 24 | mat.sample3 <- matrix(c(1:500), ncol = 5) 25 | mat.sample4 <- matrix(rep(0, 100), ncol = 5) 26 | mat.sample5 <- matrix(c(-500:499), ncol = 5) 27 | mat.sample6 <- matrix(c(1:2), ncol = 1) 28 | mat.sample7 <- matrix(c(0.5, 1, 0, 1, 0, 0, 1, 0.3, 1, 1), nrow = 2) 29 | 30 | mat.list <- list(mat.sample1, mat.sample2, mat.sample3, mat.sample4, mat.sample5, mat.sample6, mat.sample7) 31 | 32 | if (isCran()) { 33 | mat.list <- mat.list[1:4] 34 | } 35 | 36 | testMatrixEquality <- function(matrix, method, ...) { 37 | suppressNaNWarnings(expect_equal(as.matrix(parDist(matrix, method = method, ...)), as.matrix(dist(matrix, method = method, ...)))) 38 | } 39 | 40 | library(proxy) 41 | testMatrixListEquality <- function(matlist, method, ...) { 42 | invisible(sapply(matlist, function(x) { 43 | testMatrixEquality(x, method, ...) 44 | })) 45 | } 46 | 47 | test_that("error for invalid distance method shows up", { 48 | expect_error(parDist(mat.sample1, method = "unknown"), "Invalid distance method") 49 | }) 50 | 51 | test_that("error for invalid input type", { 52 | expect_error(parDist(data.frame(c(1:2))), "x must be a matrix or a list of matrices.") 53 | }) 54 | 55 | test_that("dist class label attribute keeps preserved", { 56 | namedMatrix <- matrix(1:12, 4) 57 | colnames(namedMatrix) <- c("A", "B", "C") 58 | rownames(namedMatrix) <- c("a", "b", "c", "d") 59 | 60 | attributes1 <- attributes(parDist(namedMatrix)) 61 | attributes2 <- attributes(dist(namedMatrix)) 62 | 63 | expect_equal(attributes1$Labels, attributes2$Labels) 64 | }) 65 | 66 | test_that("bhjattacharyya method produces same outputs as dist", { 67 | testMatrixListEquality(mat.list, "bhjattacharyya") 68 | }) 69 | 70 | test_that("bray method produces same outputs as dist", { 71 | testMatrixListEquality(mat.list, "bray") 72 | }) 73 | 74 | test_that("canberra method produces same outputs as dist", { 75 | testMatrixListEquality(mat.list, "canberra") 76 | }) 77 | 78 | test_that("chord method produces same outputs as dist", { 79 | testMatrixListEquality(mat.list, "chord") 80 | }) 81 | 82 | test_that("divergence method produces same outputs as dist", { 83 | testMatrixListEquality(mat.list, "divergence") 84 | }) 85 | 86 | test_that("euclidean method produces same outputs as dist", { 87 | testMatrixListEquality(mat.list, "euclidean") 88 | }) 89 | # (only vals [0,1]) 90 | test_that("fJaccard method produces same outputs as dist", { 91 | testMatrixListEquality(list(mat.sample1, mat.sample2, mat.sample7), "fJaccard") 92 | }) 93 | 94 | test_that("geodesic method produces same outputs as dist", { 95 | testMatrixListEquality(mat.list, "geodesic") 96 | }) 97 | 98 | test_that("hellinger method produces same outputs as dist", { 99 | testMatrixListEquality(mat.list, "hellinger") 100 | }) 101 | 102 | test_that("kullback method produces same outputs as dist", { 103 | testMatrixListEquality(mat.list, "kullback") 104 | }) 105 | 106 | test_that("mahalanobis method produces same outputs as dist", { 107 | mat.mahalanobis <- cbind(1:6, 1:3) 108 | testMatrixEquality(mat.mahalanobis, "mahalanobis") 109 | testMatrixEquality(mat.mahalanobis, "mahalanobis", cov = cov(mat.mahalanobis)) 110 | expect_equal( 111 | as.matrix(parDist(mat.mahalanobis, "mahalanobis", cov = solve(cov(mat.mahalanobis)), inverted = TRUE)), 112 | as.matrix(dist(mat.mahalanobis, method = "mahalanobis", cov = cov(mat.mahalanobis))) 113 | ) 114 | }) 115 | test_that("mahalanobis method throws error for list of matrices input", { 116 | mat.mahalanobis <- cbind(1:6, 1:3) 117 | mat.list <- list(mat.mahalanobis, mat.mahalanobis) 118 | expect_error(parDist(mat.list, "mahalanobis"), "Calculation of inverted covariance matrix is only supported for input data in matrix format.") 119 | }) 120 | 121 | test_that("manhattan method produces same outputs as dist", { 122 | testMatrixListEquality(mat.list, "manhattan") 123 | }) 124 | 125 | test_that("maximum method produces same outputs as dist", { 126 | testMatrixListEquality(mat.list, "maximum") 127 | }) 128 | 129 | test_that("minkowski method produces same outputs as dist", { 130 | for (p_param in c(1:10)) { 131 | testMatrixListEquality(mat.list, "minkowski", p = as.numeric(p_param)) 132 | } 133 | }) 134 | 135 | test_that("podani method produces same outputs as dist", { 136 | testMatrixListEquality(mat.list, "podani") 137 | }) 138 | # possible wrong implementation in proxy? 139 | test_that("soergel method produces expected output", { 140 | expect_equal(as.matrix(parDist(mat.sample1, method = "soergel"))[1, 2], 1) 141 | expect_equal(as.matrix(parDist(mat.sample2, method = "soergel"))[1, 2], 0.75) 142 | expect_equal(as.matrix(parDist(mat.sample3, method = "soergel"))[1, 2], 0.0049504950495049506) 143 | expect_equal(as.matrix(parDist(mat.sample4, method = "soergel"))[1, 2], NaN) 144 | expect_equal(as.matrix(parDist(mat.sample5, method = "soergel"))[1, 2], -0.010101010101010102) 145 | expect_equal(as.matrix(parDist(mat.sample6, method = "soergel"))[1, 2], 0.5) 146 | expect_equal(as.matrix(parDist(mat.sample7, method = "soergel"))[1, 2], 0.55) 147 | }) 148 | # wrong implementation in proxy? 149 | test_that("wave method produces same outputs as dist", { 150 | expect_equal(as.matrix(parDist(mat.sample1, method = "wave"))[1, 2], NaN) 151 | expect_equal(as.matrix(parDist(mat.sample2, method = "wave"))[1, 2], NaN) 152 | expect_equal(as.matrix(parDist(mat.sample3, method = "wave"))[1, 2], 0.5205532370853329) 153 | expect_equal(as.matrix(parDist(mat.sample4, method = "wave"))[1, 2], NaN) 154 | expect_equal(as.matrix(parDist(mat.sample5, method = "wave"))[1, 2], -0.0022262504871707334) 155 | expect_equal(as.matrix(parDist(mat.sample6, method = "wave"))[1, 2], 0.5) 156 | expect_equal(as.matrix(parDist(mat.sample7, method = "wave"))[1, 2], NaN) 157 | }) 158 | 159 | test_that("whittaker method produces same outputs as dist", { 160 | testMatrixListEquality(mat.list, "whittaker") 161 | }) 162 | # binary distances 163 | 164 | test_that("binary method produces same outputs as dist", { 165 | testMatrixListEquality(mat.list, "binary") 166 | }) 167 | 168 | test_that("braunblanquet method produces same outputs as dist", { 169 | testMatrixListEquality(mat.list, "braun-blanquet") 170 | }) 171 | 172 | test_that("dice method produces same outputs as dist", { 173 | testMatrixListEquality(mat.list, "dice") 174 | }) 175 | 176 | test_that("fager method produces same outputs as dist", { 177 | testMatrixListEquality(mat.list, "fager") 178 | }) 179 | 180 | test_that("faith method produces same outputs as dist", { 181 | testMatrixListEquality(mat.list, "faith") 182 | }) 183 | 184 | test_that("hamman method produces same outputs as dist", { 185 | testMatrixListEquality(mat.list, "hamman") 186 | }) 187 | 188 | test_that("kulczynski1 method produces same outputs as dist", { 189 | testMatrixListEquality(mat.list, "kulczynski1") 190 | }) 191 | 192 | test_that("kulczynski2 method produces same outputs as dist", { 193 | testMatrixListEquality(mat.list, "kulczynski2") 194 | }) 195 | 196 | test_that("michael method produces same outputs as dist", { 197 | testMatrixListEquality(mat.list, "michael") 198 | }) 199 | 200 | test_that("mountford method produces same outputs as dist", { 201 | testMatrixListEquality(mat.list, "mountford") 202 | }) 203 | 204 | test_that("mozley method produces same outputs as dist", { 205 | testMatrixListEquality(mat.list, "mozley") 206 | }) 207 | 208 | test_that("ochiai method produces same outputs as dist", { 209 | testMatrixListEquality(mat.list, "ochiai") 210 | }) 211 | 212 | test_that("phi method produces same outputs as dist", { 213 | testMatrixListEquality(mat.list, "phi") 214 | }) 215 | 216 | test_that("russel method produces same outputs as dist", { 217 | testMatrixListEquality(mat.list, "russel") 218 | }) 219 | 220 | test_that("simplematching method produces same outputs as dist", { 221 | testMatrixListEquality(mat.list, "simple matching") 222 | }) 223 | 224 | test_that("simpson method produces same outputs as dist", { 225 | testMatrixListEquality(mat.list, "simpson") 226 | }) 227 | 228 | test_that("stiles method produces same outputs as dist", { 229 | testMatrixListEquality(mat.list, "stiles") 230 | }) 231 | 232 | test_that("tanimoto method produces same outputs as dist", { 233 | testMatrixListEquality(mat.list, "tanimoto") 234 | }) 235 | 236 | test_that("yule method produces same outputs as dist", { 237 | testMatrixListEquality(mat.list, "yule") 238 | }) 239 | 240 | test_that("yule2 method produces same outputs as dist", { 241 | testMatrixListEquality(mat.list, "yule2") 242 | }) 243 | 244 | test_that("cosine method produces same outputs as dist", { 245 | testMatrixListEquality(mat.list[-4], "cosine") # dividing by zero 246 | }) 247 | 248 | # test for hamming distance method 249 | hammingR <- function(x, y) { 250 | sum(x != y) / length(x) 251 | } 252 | 253 | testMatrixEqualityHamming <- function(matrix, ...) { 254 | testthat::expect_equal( 255 | as.matrix(parDist(matrix, method = "hamming", ...)), 256 | as.matrix(proxy::dist(matrix, method = hammingR, ...)) 257 | ) 258 | } 259 | 260 | testMatrixListEqualityHamming <- function(matlist, ...) { 261 | invisible(sapply(matlist, function(x) { 262 | testMatrixEqualityHamming(x, ...) 263 | })) 264 | } 265 | 266 | testthat::test_that("hamming method produces same outputs as dist", { 267 | testMatrixListEqualityHamming(mat.list) 268 | }) -------------------------------------------------------------------------------- /tests/testthat/testMatrixListDTWDistances.R: -------------------------------------------------------------------------------- 1 | ## testMatrixListDTWDistances.R 2 | ## 3 | ## Copyright (C) 2018, 2021 Alexander Eckert 4 | ## 5 | ## This file is part of parallelDist. 6 | ## 7 | ## parallelDist is free software: you can redistribute it and/or modify it 8 | ## under the terms of the GNU General Public License as published by 9 | ## the Free Software Foundation, either version 2 of the License, or 10 | ## (at your option) any later version. 11 | ## 12 | ## parallelDist is distributed in the hope that it will be useful, but 13 | ## WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ## GNU General Public License for more details. 16 | ## 17 | ## You should have received a copy of the GNU General Public License 18 | ## along with parallelDist. If not, see . 19 | 20 | context("DTW distance methods using matrix as input") 21 | 22 | # Sample data 23 | 24 | matList.sample1 <- list(structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 25 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 26 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), .Dim = c(1L, 40L)), 27 | structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 28 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), .Dim = c(1L, 26L)), 29 | structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 30 | 1, 1, 1), .Dim = c(1L, 18L)), structure(1, .Dim = c(1L, 1L))) 31 | 32 | matList.sample2 <- list(structure(c(0, 0.666221290024121, 0.992138579223845, 0.837675741488087, 33 | 0.298093968979853, -0.36598027656586, -0.861963396802543, -0.992827766724864, 34 | -0.725930890382089, -0.185671194528465, 0.413176851770962, 0.855075968430664, 35 | 0.999129796868121, 0.816424749017454, 0.384112677013609, -0.153156594492941, 36 | -0.635636580058955, -0.935956802538981, -0.988865502668731, -0.798723238550414, 37 | -0.427611028978791, 0.0285324490339255, 0.467078394773374, 0.801915060528429, 38 | 0.978294933963238, 0.978050536506311, 0.816424749017454, 0.533244498772231, 39 | 0.18159436371588, -0.183237680976828, -0.512615351168829, -0.770254350539228, 40 | -0.934664583522371, -0.998831629222526, -0.967951368250845, -0.856101340405466, 41 | -0.682627878063188, -0.46882893202083, -0.235286772144856, -7.34763812293426e-16 42 | ), .Dim = c(1L, 40L)), structure(c(0, 0.637294298455617, 0.98319606956513, 43 | 0.868860740689089, 0.339292108143587, -0.35771316353353, -0.883391258820254, 44 | -0.972575815035646, -0.571496467513928, 0.124331294650235, 0.759722381112957, 45 | 0.999367384948098, 0.707879926506996, 0.032504191469351, -0.664423623249325, 46 | -0.99683424992037, -0.771156544793101, -0.105476926857648, 0.624552817559215, 47 | 0.993872910172706, 0.777587097879622, 0.0946947548310227, -0.649096030626008, 48 | -0.998323195253652, -0.729083830715588, -7.34763812293426e-16 49 | ), .Dim = c(1L, 26L)), structure(c(0, 0.246969768376824, 0.508644727112303, 50 | 0.752713514852865, 0.933926624849675, 0.999757468870668, 0.902994631700102, 51 | 0.621064698874997, 0.178051104865969, -0.339697691026722, -0.787475688668867, 52 | -0.99758720536247, -0.847446820461593, -0.340578183393838, 0.343461298353224, 53 | 0.883479231147892, 0.961169928913234, 0.470238319859503, -0.339697691026722, 54 | -0.938153498032876, -0.851671382567693, -0.0794079161883605, 55 | 0.780014632342609, 0.945203224149745, 0.193789516277419, -0.772441004193791, 56 | -0.911415695442887, -7.34763812293426e-16), .Dim = c(1L, 28L)), 57 | structure(c(0, 0.498706765350665, 0.875807932165434, 0.997939444221616, 58 | 0.793049199327792, 0.297537649041793, -0.328267139499277, 59 | -0.838183694383601, -0.994438048115168, -0.688929896390012, 60 | -0.0318455120202145, 0.658786647043114, 0.99698746548441, 61 | 0.752329817086689, 0.0318455120202155, -0.72482797811622, 62 | -0.994438048115168, -0.545388021934346, 0.328267139499275, 63 | 0.954710085524754, 0.793049199327793, -0.0641628059443414, 64 | -0.875807932165433, -0.866770766808318, -7.34763812293426e-16 65 | ), .Dim = c(1L, 25L))) 66 | 67 | 68 | matListList <- list(matList.sample1, matList.sample2) 69 | 70 | # Test methods 71 | 72 | # Method for calculating a dtw distance matrix with vectors of different length 73 | calcDTWDistMatForMatList <- function(matrixList, step.pattern) { 74 | matrixListLength <- length(matrixList) 75 | mat <- matrix(NA, nrow=matrixListLength, ncol=matrixListLength) 76 | for (i in c(1:(matrixListLength -1))) { 77 | for (j in (i+1):matrixListLength) { 78 | mat[j,i] <- tryCatch({ 79 | dtw(as.vector(matrixList[[j]]), as.vector(matrixList[[i]]), step.pattern = step.pattern, distance.only = TRUE)$distance 80 | }, error=function(e){ 81 | Inf 82 | }) 83 | } 84 | } 85 | as.dist(mat) 86 | } 87 | 88 | library(dtw) 89 | testDtwMatrixListEquality <- function(matList, threads = 2, ...) { 90 | expect_equal(as.matrix(calcDTWDistMatForMatList(matList, ...)), 91 | as.matrix(parDist(matList, method = "dtw", threads = threads, window.type="none", ...))) 92 | } 93 | 94 | # Tests 95 | 96 | test_that("parDist produces same distance for list of matrices with different length for different step patterns", { 97 | threadsForTest = 2 98 | for (matList in matListList) { 99 | testDtwMatrixListEquality(matList, threads = threadsForTest, step.pattern = symmetric1) 100 | testDtwMatrixListEquality(matList, threads = threadsForTest, step.pattern = symmetric2) 101 | testDtwMatrixListEquality(matList, threads = threadsForTest, step.pattern = symmetricP05) 102 | testDtwMatrixListEquality(matList, threads = threadsForTest, step.pattern = symmetricP1) 103 | testDtwMatrixListEquality(matList, threads = threadsForTest, step.pattern = symmetricP2) 104 | testDtwMatrixListEquality(matList, threads = threadsForTest, step.pattern = asymmetric) 105 | testDtwMatrixListEquality(matList, threads = threadsForTest, step.pattern = asymmetricP0) 106 | testDtwMatrixListEquality(matList, threads = threadsForTest, step.pattern = asymmetricP05) 107 | testDtwMatrixListEquality(matList, threads = threadsForTest, step.pattern = asymmetricP1) 108 | testDtwMatrixListEquality(matList, threads = threadsForTest, step.pattern = asymmetricP2) 109 | } 110 | }) 111 | -------------------------------------------------------------------------------- /tests/testthat/testMatrixListDistances.R: -------------------------------------------------------------------------------- 1 | ## testMatrixListDistances.R 2 | ## 3 | ## Copyright (C) 2017, 2021 Alexander Eckert 4 | ## 5 | ## This file is part of parallelDist. 6 | ## 7 | ## parallelDist is free software: you can redistribute it and/or modify it 8 | ## under the terms of the GNU General Public License as published by 9 | ## the Free Software Foundation, either version 2 of the License, or 10 | ## (at your option) any later version. 11 | ## 12 | ## parallelDist is distributed in the hope that it will be useful, but 13 | ## WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ## GNU General Public License for more details. 16 | ## 17 | ## You should have received a copy of the GNU General Public License 18 | ## along with parallelDist. If not, see . 19 | 20 | context("Distance methods using matrix list as input") 21 | 22 | matToList <- function(matrix, vert=TRUE) { 23 | mat <- if (vert == TRUE) { 24 | lapply(as.list(data.frame(t(matrix))), function(x) { matrix(x)}) 25 | } else { 26 | lapply(as.list(data.frame(t(matrix))), function(x) {matrix(x, nrow=1)}) 27 | } 28 | names(mat) <- NULL 29 | mat 30 | } 31 | 32 | mat.sample1 <- matrix(c(0,1,0,1,0,0,1,0), nrow = 2) 33 | mat.sample2 <- matrix(c(0,1,0,1,0,0,1,0,1,1), nrow = 2) 34 | mat.sample3 <- matrix(c(1:500), ncol = 5) 35 | mat.sample4 <- matrix(rep(0,100), ncol = 5) 36 | mat.sample5 <- matrix(c(-500:499), ncol = 5) 37 | mat.sample6 <- matrix(c(1:2), ncol = 1) 38 | mat.sample7 <- matrix(c(0.5,1,0,1,0,0,1,0.3,1,1), nrow = 2) 39 | 40 | mat.list <- list(mat.sample1, mat.sample2, mat.sample3, mat.sample4, mat.sample5, mat.sample6, mat.sample7) 41 | matlist.list.h <- lapply(mat.list, function(x) matToList(x, vert=FALSE)) 42 | 43 | if (isCran()) { 44 | mat.list <- mat.list[1:4] 45 | matlist.list.h <- lapply(mat.list, function(x) matToList(x, vert=FALSE)) 46 | } 47 | 48 | testMatrixListMatrixEquality <- function(matList, matrix, method, ...) { 49 | suppressNaNWarnings(expect_equal(as.matrix(parDist(matList, method = method, ...)), as.matrix(dist(matrix, method = method, ...)))) 50 | } 51 | 52 | testMatrixListEquality <- function(matListList, matList, method, ...) { 53 | mapply(function(X,Y) { 54 | testMatrixListMatrixEquality(X, Y, method, ...) 55 | }, X=matListList, Y=matList) 56 | } 57 | 58 | library(proxy) 59 | 60 | test_that("bhjattacharyya method produces same outputs as dist", { 61 | testMatrixListEquality(matlist.list.h, mat.list, "bhjattacharyya") 62 | }) 63 | 64 | test_that("bray method produces same outputs as dist", { 65 | testMatrixListEquality(matlist.list.h, mat.list, "bray") 66 | }) 67 | 68 | test_that("canberra method produces same outputs as dist", { 69 | testMatrixListEquality(matlist.list.h, mat.list, "canberra") 70 | }) 71 | # first row only 72 | test_that("chord method produces same outputs as dist", { 73 | expect_warning(testMatrixListEquality(matlist.list.h, mat.list, "chord")) 74 | }) 75 | 76 | test_that("divergence method produces same outputs as dist", { 77 | testMatrixListEquality(matlist.list.h, mat.list, "divergence") 78 | }) 79 | 80 | test_that("euclidean method produces same outputs as dist", { 81 | testMatrixListEquality(matlist.list.h, mat.list, "euclidean") 82 | }) 83 | 84 | test_that("fJaccard method produces same outputs as dist", { 85 | testMatrixListEquality(list(matToList(mat.sample1, vert=FALSE), matToList(mat.sample2, vert=FALSE), matToList(mat.sample7, vert=FALSE)), 86 | list(mat.sample1, mat.sample2, mat.sample7), 87 | "fJaccard") 88 | }) 89 | # first row only 90 | test_that("geodesic method produces same outputs as dist", { 91 | expect_warning(testMatrixListEquality(matlist.list.h, mat.list, "geodesic")) 92 | }) 93 | 94 | test_that("hellinger method produces same outputs as dist", { 95 | testMatrixListEquality(matlist.list.h, mat.list, "hellinger") 96 | }) 97 | 98 | test_that("kullback method produces same outputs as dist", { 99 | testMatrixListEquality(matlist.list.h, mat.list, "kullback") 100 | }) 101 | 102 | test_that("manhattan method produces same outputs as dist", { 103 | testMatrixListEquality(matlist.list.h, mat.list, "manhattan") 104 | }) 105 | 106 | test_that("maximum method produces same outputs as dist", { 107 | testMatrixListEquality(matlist.list.h, mat.list, "maximum") 108 | }) 109 | 110 | test_that("minkowski method produces same outputs as dist", { 111 | for (p_param in c(1:10)) { 112 | testMatrixListEquality(matlist.list.h, mat.list, "minkowski", p=as.numeric(p_param)) 113 | } 114 | }) 115 | # first row only 116 | test_that("podani method produces same outputs as dist", { 117 | expect_warning(testMatrixListEquality(matlist.list.h, mat.list, "podani")) 118 | }) 119 | # wrong implementation in proxy? 120 | #test_that("soergel method produces same outputs as dist", { 121 | # testMatrixListEquality(matlist.list.h, mat.list, "soergel") 122 | #}) 123 | # wrong implementation in proxy? 124 | #test_that("wave method produces same outputs as dist", { 125 | # testMatrixListEquality(matlist.list.h, mat.list, "wave") 126 | #}) 127 | 128 | test_that("whittaker method produces same outputs as dist", { 129 | testMatrixListEquality(matlist.list.h, mat.list, "whittaker") 130 | }) 131 | 132 | # binary distances 133 | test_that("binary method produces same outputs as dist", { 134 | testMatrixListEquality(matlist.list.h, mat.list, "binary") 135 | }) 136 | 137 | test_that("braunblanquet method produces same outputs as dist", { 138 | testMatrixListEquality(matlist.list.h, mat.list, "braun-blanquet") 139 | }) 140 | 141 | test_that("dice method produces same outputs as dist", { 142 | testMatrixListEquality(matlist.list.h, mat.list, "dice") 143 | }) 144 | 145 | test_that("fager method produces same outputs as dist", { 146 | testMatrixListEquality(matlist.list.h, mat.list, "fager") 147 | }) 148 | 149 | test_that("faith method produces same outputs as dist", { 150 | testMatrixListEquality(matlist.list.h, mat.list, "faith") 151 | }) 152 | 153 | test_that("hamman method produces same outputs as dist", { 154 | testMatrixListEquality(matlist.list.h, mat.list, "hamman") 155 | }) 156 | 157 | test_that("kulczynski1 method produces same outputs as dist", { 158 | testMatrixListEquality(matlist.list.h, mat.list, "kulczynski1") 159 | }) 160 | 161 | test_that("kulczynski2 method produces same outputs as dist", { 162 | testMatrixListEquality(matlist.list.h, mat.list, "kulczynski2") 163 | }) 164 | 165 | test_that("michael method produces same outputs as dist", { 166 | testMatrixListEquality(matlist.list.h, mat.list, "michael") 167 | }) 168 | 169 | test_that("mountford method produces same outputs as dist", { 170 | testMatrixListEquality(matlist.list.h, mat.list, "mountford") 171 | }) 172 | 173 | test_that("mozley method produces same outputs as dist", { 174 | testMatrixListEquality(matlist.list.h, mat.list, "mozley") 175 | }) 176 | 177 | test_that("ochiai method produces same outputs as dist", { 178 | testMatrixListEquality(matlist.list.h, mat.list, "ochiai") 179 | }) 180 | 181 | test_that("phi method produces same outputs as dist", { 182 | testMatrixListEquality(matlist.list.h, mat.list, "phi") 183 | }) 184 | 185 | test_that("russel method produces same outputs as dist", { 186 | testMatrixListEquality(matlist.list.h, mat.list, "russel") 187 | }) 188 | 189 | test_that("simplematching method produces same outputs as dist", { 190 | testMatrixListEquality(matlist.list.h, mat.list, "simple matching") 191 | }) 192 | 193 | test_that("simpson method produces same outputs as dist", { 194 | testMatrixListEquality(matlist.list.h, mat.list, "simpson") 195 | }) 196 | 197 | test_that("stiles method produces same outputs as dist", { 198 | testMatrixListEquality(matlist.list.h, mat.list, "stiles") 199 | }) 200 | 201 | test_that("tanimoto method produces same outputs as dist", { 202 | testMatrixListEquality(matlist.list.h, mat.list, "tanimoto") 203 | }) 204 | 205 | test_that("yule method produces same outputs as dist", { 206 | testMatrixListEquality(matlist.list.h, mat.list, "yule") 207 | }) 208 | 209 | test_that("yule2 method produces same outputs as dist", { 210 | testMatrixListEquality(matlist.list.h, mat.list, "yule2") 211 | }) 212 | -------------------------------------------------------------------------------- /vignettes/.gitignore: -------------------------------------------------------------------------------- 1 | Rplots.pdf 2 | vignette-benchmarkOverall.pdf 3 | vignette-performanceDtw.pdf 4 | vignette-performance_dtw.pdf 5 | vignette.bbl 6 | vignette.blg 7 | vignette.log 8 | vignette.pdf 9 | vignette.synctex.gz(busy) 10 | vignette.tex 11 | vignette.toc 12 | parallelDist.log 13 | parallelDist.pdf 14 | parallelDist.synctex.gz 15 | parallelDist.tex 16 | parallelDist.toc 17 | parallelDist-benchmarkOverall.pdf 18 | parallelDist-performanceDtw.pdf 19 | parallelDist.synctex.gz(busy) 20 | parallelDist-concordance.tex 21 | -------------------------------------------------------------------------------- /vignettes/parallelDist.Rnw: -------------------------------------------------------------------------------- 1 | \documentclass[10pt]{article} 2 | %\VignetteIndexEntry{parallelDist vignette} 3 | %\VignetteKeywords{parallelDist, Performance} 4 | %\VignetteDepends{parallelDist, stats, ggplot2} 5 | 6 | \usepackage{geometry} 7 | \geometry{letterpaper} 8 | 9 | \usepackage{color,alltt} 10 | \usepackage[colorlinks]{hyperref} 11 | \definecolor{link}{rgb}{0,0,0.3} %% next few lines courtesy of RJournal.sty 12 | \hypersetup{ 13 | colorlinks,% 14 | citecolor=link,% 15 | filecolor=link,% 16 | linkcolor=link,% 17 | urlcolor=link 18 | } 19 | 20 | \usepackage{microtype} %% cf http://www.khirevich.com/latex/microtype/ 21 | \usepackage[T1]{fontenc} %% cf http://www.khirevich.com/latex/font/ 22 | \usepackage{lmodern} %% cf http://www.khirevich.com/latex/font/ 23 | 24 | \newcommand{\proglang}[1]{\textsf{#1}} 25 | \newcommand{\pkg}[1]{{\fontseries{b}\selectfont #1}} 26 | \newcommand{\code}[1]{\texttt{#1}} 27 | \newcommand{\R}[0]{\proglang{R}} 28 | 29 | \newcommand{\rdoc}[2]{\href{http://www.rdocumentation.org/packages/#1/functions/#2}{\code{#2}}} 30 | 31 | <>= 32 | prettyVersion <- packageDescription("parallelDist")$Version 33 | require(ggplot2) 34 | @ 35 | 36 | \author{Alexander Eckert} 37 | \title{\pkg{parallelDist}} 38 | \date{\pkg{parallelDist} version \Sexpr{prettyVersion} as of \today} 39 | 40 | \begin{document} 41 | \SweaveOpts{concordance=TRUE} 42 | \maketitle 43 | 44 | \abstract{ 45 | \noindent This document highlights the performance gains for calculating distance matrices with the \pkg{parallelDist} package and provides basic usage examples.} 46 | 47 | \tableofcontents 48 | 49 | \section{Introduction} 50 | 51 | The \pkg{parallelDist} package provides a fast parallelized alternative to \proglang{R}'s native \rdoc{stats}{dist} function to calculate distance matrices for continuous, binary, and multi-dimensional input matrices and offers a broad variety of predefined distance functions from the \pkg{stats}, \pkg{proxy} and \pkg{dtw} \proglang{R} packages, as well as support for user-defined distance functions written in C++. For ease of use, the \rdoc{parallelDist}{parDist} function extends the signature of the \rdoc{stats}{dist} function and uses the same parameter naming conventions as distance methods of existing \proglang{R} packages. 52 | 53 | The package is mainly implemented in \proglang{C++} and leverages the \pkg{Rcpp} \cite{Rcpp} and \pkg{RcppParallel} \cite{RcppParallel} package to parallelize the distance computations with the help of the TinyThread library. Furthermore, the Armadillo linear algebra library \cite{Sanderson:2010:Armadillo} is used via \pkg{RcppArmadillo} \cite{RcppArmadillo} for optimized matrix operations for distance calculations. The curiously recurring template pattern (CRTP) technique is applied to avoid virtual functions, which improves the Dynamic Time Warping calculations while keeping the implementation flexible enough to support different step patterns and normalization methods. 54 | 55 | \section{Performance} 56 | 57 | The inital motivation for building this package was the need for a fast Dynamic Time Warping implementation which uses multiple cores and supports multi-dimensional (time) series. DTW is an expensive distance measure, where the computation of the DTW distance between two series of length $N$ has a complexity of $\mathcal{O}(N^2)$. This motivates an efficient and parallelized implementation in \proglang{C++}. 58 | 59 | Figure \ref{fig:performanceDtw} shows a performance comparison between the \rdoc{parallelDist}{parDist} function of \pkg{parallelDist} and the \rdoc{stats}{dist} function in conjunction with the \pkg{dtw} package. 60 | 61 | The benchmark has been performed on a system with the following specifications: 62 | \begin{itemize} 63 | \item Intel(R) Xeon(R) E3-1230 v3 @ 3.30 GHz, 4 cores with hyper-threading 64 | \item 32 Gb RAM 65 | \end{itemize} 66 | 67 | As depicted in figure \ref{fig:performanceDtw}, \rdoc{parallelDist}{parDist} makes the calculation of large distance matrices with DTW up to 3 orders of magnitudes faster. 68 | 69 | \begin{figure} 70 | \begin{center} 71 | %height=4, width=8 72 | <>= 73 | comparison <- structure(list(expr = c(10, 100, 1000, 10000, 10, 100, 1000, 74 | 10000, 10, 100, 1000, 10000), min = c(0.02173888, 2.508674745, 75 | 247.536645172, 24893.826760134, 0.001671714, 0.003850385, 0.36582544, 76 | 37.370421954, 0.000135292, 0.001352922, 0.123839325, 11.108382113 77 | ), lq = c(0.02173888, 2.508674745, 247.536645172, 24893.826760134, 78 | 0.001671714, 0.003850385, 0.36582544, 37.370421954, 0.000135292, 79 | 0.001352922, 0.123839325, 11.108382113), mean = c(0.02173888, 80 | 2.508674745, 247.536645172, 24893.826760134, 0.001671714, 0.003850385, 81 | 0.36582544, 37.370421954, 0.000135292, 0.001352922, 0.123839325, 82 | 11.108382113), median = c(0.02173888, 2.508674745, 247.536645172, 83 | 24893.826760134, 0.001671714, 0.003850385, 0.36582544, 37.370421954, 84 | 0.000135292, 0.001352922, 0.123839325, 11.108382113), uq = c(0.02173888, 85 | 2.508674745, 247.536645172, 24893.826760134, 0.001671714, 0.003850385, 86 | 0.36582544, 37.370421954, 0.000135292, 0.001352922, 0.123839325, 87 | 11.108382113), max = c(0.02173888, 2.508674745, 247.536645172, 88 | 24893.826760134, 0.001671714, 0.003850385, 0.36582544, 37.370421954, 89 | 0.000135292, 0.001352922, 0.123839325, 11.108382113), neval = c(1, 90 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), method = c("dtw", "dtw", "dtw", 91 | "dtw", "parDist threads=1", "parDist threads=1", "parDist threads=1", 92 | "parDist threads=1", "parDist threads=8", "parDist threads=8", 93 | "parDist threads=8", "parDist threads=8")), unit = "seconds", row.names = c(2L, 94 | 3L, 4L, 5L, 9L, 10L, 11L, 12L, 16L, 17L, 18L, 19L), class = "data.frame") 95 | fig2 <- ggplot(data=comparison, aes(x=expr, y=min, group = method, colour = method)) + 96 | geom_line() + 97 | geom_point() + 98 | scale_y_log10(breaks=c(0.0001,.001,.01,.1,1,10,100,1000,10000), labels=c(0.0001,.001,.01,.1,1,10,100,1000,10000)) + 99 | scale_x_log10(breaks=c(0,10,100,1000,10000),labels=c(0,10,100,1000,10000)) + 100 | guides(fill=guide_legend(title="Method")) + 101 | xlab("Number of series (length 10)") + 102 | ylab("Computation time in s") + 103 | theme_light() + 104 | theme(legend.position="bottom") + 105 | ggtitle("Distance matrix computation time (dtw, parDist)") 106 | print(fig2) 107 | @ 108 | \end{center} 109 | \caption{Distance matrix computation time for Dynamic Time Warping} 110 | \label{fig:performanceDtw} 111 | \end{figure} 112 | 113 | The \rdoc{parallelDist}{parDist} function can be used as a replacement for the \rdoc{stats}{dist} function of the \pkg{stats} package, since it supports all other distance methods of the \pkg{stats} package and most of the distances of the \pkg{proxy} package. Figure \ref{fig:benchmarkOverall} shows the performance comparison of the \rdoc{parallelDist}{parDist} function with the distance methods of \pkg{stats} and the \pkg{proxy} package when calculating distance matrices with 5000 series of length 10. 114 | 115 | \begin{figure} 116 | \begin{center} 117 | %height=4, width=8 118 | <>= 119 | comparison.overall <- structure(list(expr = c("dist", "parDist", "dist", "parDist", 120 | "dist", "parDist", "dist", "parDist", "dist", "parDist", "dist", 121 | "parDist", "dist", "parDist", "dist", "parDist", "dist", "parDist", 122 | "dist", "parDist", "dist", "parDist", "dist", "parDist", "dist", 123 | "parDist", "dist", "parDist", "dist", "parDist", "dist", "parDist", 124 | "dist", "parDist", "dist", "parDist", "dist", "parDist", "dist", 125 | "parDist", "dist", "parDist", "dist", "parDist", "dist", "parDist", 126 | "dist", "parDist", "dist", "parDist", "dist", "parDist", "dist", 127 | "parDist", "dist", "parDist", "dist", "parDist", "dist", "parDist", 128 | "dist", "parDist", "dist", "parDist", "dist", "parDist", "dist", 129 | "parDist", "dist", "parDist", "dist", "parDist"), min = c(27.023019786, 130 | 0.42355673, 23.337486167, 0.162221163, 1.132874622, 0.258428158, 131 | 57.787881691, 0.192326593, 38.823629012, 0.218193139, 0.943546255, 132 | 0.125315296, 1.19984082, 0.560230453, 49.638932656, 0.287721827, 133 | 38.601467265, 0.575263573, 40.453796831, 1.274451564, 0.933230054, 134 | 0.122381139, 0.933518058, 0.124280224, 894.344310554, 1.209659702, 135 | 24.010877591, 0.504667156, 22.613629988, 0.625519014, 28.623759888, 136 | 0.311995644, 0.748200286, 0.150044756, 25.131624635, 0.151615403, 137 | 21.827435577, 0.151512145, 32.544226019, 0.166376382, 17.890447476, 138 | 0.156928859, 20.680027643, 0.142911527, 16.802475029, 0.152215982, 139 | 27.751515131, 0.140722573, 45.313170363, 0.163320617, 27.947986367, 140 | 0.146164789, 26.016592883, 0.164806356, 24.045695896, 0.159119679, 141 | 46.747133491, 0.150115357, 12.639720779, 0.134051207, 16.417508337, 142 | 0.152236198, 23.787851211, 0.137237601, 664.737856716, 0.422527878, 143 | 26.300990224, 0.149172968, 28.118753098, 0.150392786, 35.712203217, 144 | 0.164383059), lq = c(27.023019786, 0.42355673, 23.337486167, 145 | 0.162221163, 1.132874622, 0.258428158, 57.787881691, 0.192326593, 146 | 38.823629012, 0.218193139, 0.943546255, 0.125315296, 1.19984082, 147 | 0.560230453, 49.638932656, 0.287721827, 38.601467265, 0.575263573, 148 | 40.453796831, 1.274451564, 0.933230054, 0.122381139, 0.933518058, 149 | 0.124280224, 894.344310554, 1.209659702, 24.010877591, 0.504667156, 150 | 22.613629988, 0.625519014, 28.623759888, 0.311995644, 0.748200286, 151 | 0.150044756, 25.131624635, 0.151615403, 21.827435577, 0.151512145, 152 | 32.544226019, 0.166376382, 17.890447476, 0.156928859, 20.680027643, 153 | 0.142911527, 16.802475029, 0.152215982, 27.751515131, 0.140722573, 154 | 45.313170363, 0.163320617, 27.947986367, 0.146164789, 26.016592883, 155 | 0.164806356, 24.045695896, 0.159119679, 46.747133491, 0.150115357, 156 | 12.639720779, 0.134051207, 16.417508337, 0.152236198, 23.787851211, 157 | 0.137237601, 664.737856716, 0.422527878, 26.300990224, 0.149172968, 158 | 28.118753098, 0.150392786, 35.712203217, 0.164383059), mean = c(27.023019786, 159 | 0.42355673, 23.337486167, 0.162221163, 1.132874622, 0.258428158, 160 | 57.787881691, 0.192326593, 38.823629012, 0.218193139, 0.943546255, 161 | 0.125315296, 1.19984082, 0.560230453, 49.638932656, 0.287721827, 162 | 38.601467265, 0.575263573, 40.453796831, 1.274451564, 0.933230054, 163 | 0.122381139, 0.933518058, 0.124280224, 894.344310554, 1.209659702, 164 | 24.010877591, 0.504667156, 22.613629988, 0.625519014, 28.623759888, 165 | 0.311995644, 0.748200286, 0.150044756, 25.131624635, 0.151615403, 166 | 21.827435577, 0.151512145, 32.544226019, 0.166376382, 17.890447476, 167 | 0.156928859, 20.680027643, 0.142911527, 16.802475029, 0.152215982, 168 | 27.751515131, 0.140722573, 45.313170363, 0.163320617, 27.947986367, 169 | 0.146164789, 26.016592883, 0.164806356, 24.045695896, 0.159119679, 170 | 46.747133491, 0.150115357, 12.639720779, 0.134051207, 16.417508337, 171 | 0.152236198, 23.787851211, 0.137237601, 664.737856716, 0.422527878, 172 | 26.300990224, 0.149172968, 28.118753098, 0.150392786, 35.712203217, 173 | 0.164383059), median = c(27.023019786, 0.42355673, 23.337486167, 174 | 0.162221163, 1.132874622, 0.258428158, 57.787881691, 0.192326593, 175 | 38.823629012, 0.218193139, 0.943546255, 0.125315296, 1.19984082, 176 | 0.560230453, 49.638932656, 0.287721827, 38.601467265, 0.575263573, 177 | 40.453796831, 1.274451564, 0.933230054, 0.122381139, 0.933518058, 178 | 0.124280224, 894.344310554, 1.209659702, 24.010877591, 0.504667156, 179 | 22.613629988, 0.625519014, 28.623759888, 0.311995644, 0.748200286, 180 | 0.150044756, 25.131624635, 0.151615403, 21.827435577, 0.151512145, 181 | 32.544226019, 0.166376382, 17.890447476, 0.156928859, 20.680027643, 182 | 0.142911527, 16.802475029, 0.152215982, 27.751515131, 0.140722573, 183 | 45.313170363, 0.163320617, 27.947986367, 0.146164789, 26.016592883, 184 | 0.164806356, 24.045695896, 0.159119679, 46.747133491, 0.150115357, 185 | 12.639720779, 0.134051207, 16.417508337, 0.152236198, 23.787851211, 186 | 0.137237601, 664.737856716, 0.422527878, 26.300990224, 0.149172968, 187 | 28.118753098, 0.150392786, 35.712203217, 0.164383059), uq = c(27.023019786, 188 | 0.42355673, 23.337486167, 0.162221163, 1.132874622, 0.258428158, 189 | 57.787881691, 0.192326593, 38.823629012, 0.218193139, 0.943546255, 190 | 0.125315296, 1.19984082, 0.560230453, 49.638932656, 0.287721827, 191 | 38.601467265, 0.575263573, 40.453796831, 1.274451564, 0.933230054, 192 | 0.122381139, 0.933518058, 0.124280224, 894.344310554, 1.209659702, 193 | 24.010877591, 0.504667156, 22.613629988, 0.625519014, 28.623759888, 194 | 0.311995644, 0.748200286, 0.150044756, 25.131624635, 0.151615403, 195 | 21.827435577, 0.151512145, 32.544226019, 0.166376382, 17.890447476, 196 | 0.156928859, 20.680027643, 0.142911527, 16.802475029, 0.152215982, 197 | 27.751515131, 0.140722573, 45.313170363, 0.163320617, 27.947986367, 198 | 0.146164789, 26.016592883, 0.164806356, 24.045695896, 0.159119679, 199 | 46.747133491, 0.150115357, 12.639720779, 0.134051207, 16.417508337, 200 | 0.152236198, 23.787851211, 0.137237601, 664.737856716, 0.422527878, 201 | 26.300990224, 0.149172968, 28.118753098, 0.150392786, 35.712203217, 202 | 0.164383059), max = c(27.023019786, 0.42355673, 23.337486167, 203 | 0.162221163, 1.132874622, 0.258428158, 57.787881691, 0.192326593, 204 | 38.823629012, 0.218193139, 0.943546255, 0.125315296, 1.19984082, 205 | 0.560230453, 49.638932656, 0.287721827, 38.601467265, 0.575263573, 206 | 40.453796831, 1.274451564, 0.933230054, 0.122381139, 0.933518058, 207 | 0.124280224, 894.344310554, 1.209659702, 24.010877591, 0.504667156, 208 | 22.613629988, 0.625519014, 28.623759888, 0.311995644, 0.748200286, 209 | 0.150044756, 25.131624635, 0.151615403, 21.827435577, 0.151512145, 210 | 32.544226019, 0.166376382, 17.890447476, 0.156928859, 20.680027643, 211 | 0.142911527, 16.802475029, 0.152215982, 27.751515131, 0.140722573, 212 | 45.313170363, 0.163320617, 27.947986367, 0.146164789, 26.016592883, 213 | 0.164806356, 24.045695896, 0.159119679, 46.747133491, 0.150115357, 214 | 12.639720779, 0.134051207, 16.417508337, 0.152236198, 23.787851211, 215 | 0.137237601, 664.737856716, 0.422527878, 26.300990224, 0.149172968, 216 | 28.118753098, 0.150392786, 35.712203217, 0.164383059), neval = c(1, 217 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 218 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 219 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 220 | 1, 1, 1, 1, 1, 1, 1, 1), method = structure(c(36L, 36L, 33L, 221 | 33L, 32L, 32L, 31L, 31L, 29L, 29L, 28L, 28L, 25L, 25L, 24L, 24L, 222 | 22L, 22L, 19L, 19L, 18L, 18L, 17L, 17L, 11L, 11L, 7L, 7L, 4L, 223 | 4L, 3L, 3L, 35L, 35L, 34L, 34L, 30L, 30L, 27L, 27L, 26L, 26L, 224 | 23L, 23L, 21L, 21L, 20L, 20L, 16L, 16L, 15L, 15L, 14L, 14L, 13L, 225 | 13L, 12L, 12L, 10L, 10L, 9L, 9L, 8L, 8L, 6L, 6L, 5L, 5L, 2L, 226 | 2L, 1L, 1L), .Label = c("yule2", "yule", "whittaker", "wave", 227 | "tanimoto", "stiles", "soergel", "simpson", "simple matching", 228 | "russel", "podani", "phi", "ochiai", "mozley", "mountford", "michael", 229 | "maximum", "manhattan", "kullback", "kulczynski2", "kulczynski1", 230 | "hellinger", "hamman", "geodesic", "fJaccard", "faith", "fager", 231 | "euclidean", "divergence", "dice", "chord", "canberra", "bray", 232 | "braun-blanquet", "binary", "bhjattacharyya"), class = c("ordered", 233 | "factor"))), .Names = c("expr", "min", "lq", "mean", "median", 234 | "uq", "max", "neval", "method"), row.names = c(NA, -72L), unit = "seconds", class = "data.frame") 235 | plot.distances <- ggplot(data=comparison.overall, aes(x=method, y=min, fill=expr)) + 236 | geom_bar(stat="identity", position=position_dodge()) + 237 | xlab("Distance method") + 238 | ylab("Computation time in s") + 239 | theme_light() + 240 | #scale_x_discrete(name="", limits = rev(levels(comparison.overall$method))) + 241 | coord_flip() + 242 | guides(fill=guide_legend(title="Method")) + 243 | labs(title = "Distance matrix computation time (5000 series of length 10)", 244 | caption = "Excluded distances for better comparison: dtw, mahalanobis, minkowski") 245 | print(plot.distances) 246 | @ 247 | \end{center} 248 | \caption{Distance matrix computation times} 249 | \label{fig:benchmarkOverall} 250 | \end{figure} 251 | 252 | \section{Quick start} 253 | 254 | \subsection{Using matrices as input parameter} 255 | 256 | The function signature of \rdoc{parallelDist}{parDist} is based on dist. To calculate a distance matrix for 10 series of length 10, a matrix is passed to the \rdoc{parallelDist}{parDist} function where each row corresponds to one series. 257 | 258 | <>= 259 | # matrix where each row corresponds to one series 260 | sample.matrix <- matrix(c(1:100), ncol = 10) 261 | @ 262 | 263 | Here the \rdoc{parallelDist}{parDist} function calculates the distance matrix using the euclidean distance and returns a dist object, like the dist function. 264 | 265 | <>= 266 | # euclidean distance 267 | dist.euclidean <- parDist(sample.matrix, method = "euclidean") 268 | @ 269 | 270 | The dist object can easily converted into a matrix, or can be used as an input for R's clustering algorithms. 271 | 272 | <>= 273 | # convert to matrix 274 | as.matrix(dist.euclidean) 275 | 276 | # create hierarchical agglomerative clustering model 277 | hclust.model <- hclust(dist.euclidean, method="ward") 278 | @ 279 | 280 | Some distance methods require additional arguments (see \code{?parDist}). These additional arguments can be passed directly to the \rdoc{parallelDist}{parDist} function. 281 | 282 | <>= 283 | # minkowski distance with parameter p=2 284 | parDist(x = sample.matrix, method = "minkowski", p=2) 285 | 286 | # dynamic time warping distance normalized with warping path length 287 | parDist(x = sample.matrix, method = "dtw", norm.method="path.length") 288 | @ 289 | 290 | A list of all available distance methods can be found in the \rdoc{parallelDist}{parDist} documentation. 291 | 292 | <>= 293 | ?parDist 294 | @ 295 | 296 | The number of threads to use can be set via the threads parameter. 297 | 298 | <>= 299 | # use 2 threads 300 | dist.euclidean <- parDist(sample.matrix, method = "euclidean", threads = 2) 301 | @ 302 | 303 | \subsection{Using a list of matrices as input parameter} 304 | 305 | \rdoc{parallelDist}{parDist} also supports the calculation of distances between multi-dimensional series. Instead of one single matrix a list of matrices is used as input parameter. One matrix with M rows and N columns corresponds to a series with M dimensions and length N. 306 | 307 | In the example below, a list with 2 matrices is defined where each matrix corresponds to a series with 2 dimensions of length 10. 308 | 309 | <>= 310 | # defining a list of matrices, where each 311 | # list entry row corresponds to a two dimensional series 312 | tmp.mat <- matrix(c(1:40), ncol = 10) 313 | sample.matrix.list <- list(tmp.mat[1:2,], tmp.mat[3:4,]) 314 | @ 315 | 316 | The sample matrix now can be used to calculate a distance matrix for the multi-dimensional DTW distance. 317 | 318 | <>= 319 | # multi-dimensional dynamic time warping 320 | parDist(x = sample.matrix.list, method = "dtw") 321 | @ 322 | 323 | \subsection{Using user-defined distance functions} 324 | 325 | Since version 0.2.0 of \pkg{parallelDist} custom user-defined distance measures can be defined to calculate distances matrices in parallel. To ensure a performant execution, the user-defined function needs to be defined and compiled in C++ and an external pointer to the compiled C++ function needs to be passed to \rdoc{parallelDist}{parDist} with the \code{func} argument. 326 | \newline\newline 327 | The user-defined function needs to have the following signature: 328 | 329 | \begin{verbatim} 330 | double customDist(const arma::mat &A, const arma::mat &B) 331 | \end{verbatim} 332 | 333 | Note that the return value must be a \texttt{double} and the two parameters must be of type \texttt{const arma::mat \¶m}. More information about the Armadillo library can be found at \cite{ArmadilloDoc} or as part of the documentation of the \pkg{RcppArmadillo} \cite{RcppArmadillo} package. 334 | \newline\newline 335 | Defining and compiling the function, as well as creating an external pointer to the user-defined function can easily be achieved with the \rdoc{RcppXPtrUtils}{cppXPtr} function of the \pkg{RcppXPtrUtils} package. The following code shows a full example of defining and using a user-defined euclidean distance function: 336 | 337 | <>= 338 | # RcppArmadillo is used as dependency 339 | library(RcppArmadillo) 340 | # Use RcppXPtrUtils for simple usage of C++ external pointers 341 | library(RcppXPtrUtils) 342 | 343 | # compile user-defined function and return pointer (RcppArmadillo is used as dependency) 344 | euclideanFuncPtr <- cppXPtr("double customDist(const arma::mat &A, const arma::mat &B) { 345 | return sqrt(arma::accu(arma::square(A - B))); }", 346 | depends = c("RcppArmadillo")) 347 | 348 | # distance matrix for user-defined euclidean distance function 349 | # (note that method is set to "custom") 350 | parDist(matrix(1:16, ncol=2), method="custom", func = euclideanFuncPtr) 351 | @ 352 | 353 | As displayed in table \ref{table:performanceCustomDist}, the performance between a user-defined and a predefined distance function is close to equal for large matrices. 354 | 355 | % latex table generated in R 3.4.0 by xtable 1.8-2 package 356 | % Sat Sep 23 16:06:28 2017 357 | \begin{table}[ht] 358 | \centering 359 | \begin{tabular}{rrrrrrrrrr} 360 | \hline 361 | & matrix & method & min & lq & mean & median & uq & max & neval \\ 362 | \hline 363 | 1 & 10x10 & euclidean & 0.04 & 0.05 & 0.08 & 0.06 & 0.13 & 0.17 & 100.00 \\ 364 | 2 & 10x10 & custom & 0.16 & 0.18 & 0.24 & 0.22 & 0.30 & 0.40 & 100.00 \\ 365 | 3 & 100x10 & euclidean & 0.09 & 0.11 & 0.14 & 0.13 & 0.18 & 0.24 & 100.00 \\ 366 | 4 & 100x10 & custom & 0.22 & 0.24 & 0.31 & 0.29 & 0.37 & 0.51 & 100.00 \\ 367 | 5 & 1000x10 & euclidean & 4.19 & 4.29 & 4.44 & 4.35 & 4.50 & 5.54 & 100.00 \\ 368 | 6 & 1000x10 & custom & 4.34 & 4.48 & 4.66 & 4.60 & 4.80 & 5.14 & 100.00 \\ 369 | 7 & 10000x10 & euclidean & 448.87 & 451.33 & 490.99 & 453.26 & 465.36 & 644.65 & 100.00 \\ 370 | 8 & 10000x10 & custom & 452.83 & 454.99 & 492.68 & 456.36 & 464.66 & 678.49 & 100.00 \\ 371 | \hline 372 | \end{tabular} 373 | \caption{Performance comparison between user-defined and predefined euclidean distance function (in ms)} 374 | \label{table:performanceCustomDist} 375 | \end{table} 376 | 377 | \subsection{Using objects of other R packages} 378 | 379 | The \rdoc{parallelDist}{parDist} supports different kinds of step patterns for calculating DTW distance matrices (see \code{?parDist}). For ease of use, it is also possible to use the StepPattern objects of the \pkg{dtw} package as input parameters for \rdoc{parallelDist}{parDist}. 380 | 381 | <>= 382 | # load dtw package 383 | library(dtw) 384 | # print the step pattern 385 | print(symmetric2) 386 | # use the symmetric2 object as input parameter for the parDist function 387 | parDist(x = sample.matrix, method = "dtw", step.pattern = symmetric2) 388 | @ 389 | 390 | \bibliographystyle{alpha} 391 | \bibliography{parallelDist} 392 | \end{document} 393 | -------------------------------------------------------------------------------- /vignettes/parallelDist.bib: -------------------------------------------------------------------------------- 1 | @String{CRAN = "http://CRAN.R-Project.org/" } 2 | @String{manuals = CRAN # "doc/manuals/" } 3 | @String{RCoreTeam = "{R Development Core Team}" } 4 | @String{RFoundation = "R Foundation for Statistical Computing" } 5 | @String{R-Forge = "http://R-Forge.R-Project.org/" } 6 | @String{Armadillo = "http://arma.sourceforge.net/docs.html"} 7 | 8 | @misc{ArmadilloDoc, 9 | title = {Armadillo: C++ linear algebra library documentation}, 10 | url = {http://arma.sourceforge.net/docs.html}, 11 | howpublished = {http://arma.sourceforge.net/docs.html} 12 | } 13 | 14 | @Article{Rcpp, 15 | title = {{Rcpp}: Seamless {R} and {C++} Integration}, 16 | author = {Dirk Eddelbuettel and Romain Fran\c{c}ois}, 17 | journal = {Journal of Statistical Software}, 18 | year = {2011}, 19 | volume = {40}, 20 | number = {8}, 21 | pages = {1--18}, 22 | url = {http://www.jstatsoft.org/v40/i08/}, 23 | } 24 | 25 | @Manual{RcppParallel, 26 | title = {RcppParallel: Parallel Programming Tools for 'Rcpp'}, 27 | author = {JJ Allaire and Romain Francois and Kevin Ushey and Gregory Vandenbrouck and Marcus Geelnard and {Intel}}, 28 | year = {2016}, 29 | note = {R package version 4.3.20}, 30 | url = {https://CRAN.R-project.org/package=RcppParallel}, 31 | } 32 | 33 | @Article{RcppArmadillo, 34 | title = {RcppArmadillo: Accelerating R with high-performance C++ linear algebra}, 35 | author = {Dirk Eddelbuettel and Conrad Sanderson}, 36 | journal = {Computational Statistics and Data Analysis}, 37 | year = {2014}, 38 | volume = {71}, 39 | month = {March}, 40 | pages = {1054--1063}, 41 | url = {http://dx.doi.org/10.1016/j.csda.2013.02.005}, 42 | } 43 | 44 | @TechReport{Sanderson:2010:Armadillo, 45 | author = {Conrad Sanderson}, 46 | title = {{Armadillo}: {An} open source {C++} Algebra Library 47 | for Fast Prototyping and Computationally Intensive 48 | Experiments }, 49 | institution = {{NICTA}}, 50 | year = 2010, 51 | url = "http://arma.sourceforge.net" 52 | } 53 | --------------------------------------------------------------------------------