├── .gitignore ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── cdindex ├── __init__.py ├── cdindex.py ├── pycdindex.c └── time_utilities.py ├── docs ├── Makefile ├── cdindex.cdindex.rst ├── cdindex.rst ├── cdindex.time_utilities.rst ├── conf.py ├── index.rst └── modules.rst ├── setup.py ├── src ├── cdindex.c ├── cdindex.h ├── graph.c ├── main.c └── utility.c └── tests.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | # os x 104 | .DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | graft src 2 | global-exclude .DS_Store -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CC=gcc 2 | CFLAGS= 3 | LDFLAGS= 4 | SOURCES=src/main.c src/cdindex.c src/graph.c src/utility.c 5 | OBJECTS=$(SOURCES:.c=.o) 6 | EXECUTABLE=bin/cdindex 7 | 8 | all: $(SOURCES) $(EXECUTABLE) 9 | 10 | $(EXECUTABLE): $(OBJECTS) 11 | $(CC) $(LDFLAGS) $(OBJECTS) -o $@ 12 | 13 | c.o: 14 | $(CC) $(CFLAGS) $< -o $@ 15 | 16 | clean: 17 | rm src/*o 18 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | cdindex 2 | ======= 3 | 4 | .. image:: https://readthedocs.org/projects/cdindex/badge/?version=latest 5 | :target: https://readthedocs.org/projects/cdindex/?badge=latest 6 | :alt: Documentation Status 7 | 8 | cdindex is a Python package, written in C, for computing the CD index and other dynamic 9 | measures on evolving directed graphs. 10 | 11 | - **Website:** http://www.cdindex.info 12 | - **Source:** https://github.com/russellfunk/cdindex 13 | - **Bug reports:** 14 | 15 | Install 16 | ------- 17 | 18 | Install the latest version of cdindex:: 19 | 20 | $ pip install cdindex 21 | 22 | Simple example 23 | -------------- 24 | 25 | Create a graph with some dummy data and compute the CD index:: 26 | 27 | >>> import cdindex 28 | >>> import datetime 29 | >>> from dateutil.relativedelta import relativedelta 30 | 31 | >>> def get_t_delta(vertex, years): 32 | vertex_datetime = cdindex.datetime_from_timestamp(graph.timestamp(vertex)) 33 | future_datetime = vertex_datetime + relativedelta(years=years) 34 | difference = future_datetime - vertex_datetime 35 | return int(difference.total_seconds()) 36 | 37 | >>> # dummy vertices for python module tests 38 | >>> pyvertices= [{"name": "0Z", "time": datetime.datetime(1992, 1, 1)}, 39 | {"name": "1Z", "time": datetime.datetime(1992, 1, 1)}, 40 | {"name": "2Z", "time": datetime.datetime(1993, 1, 1)}, 41 | {"name": "3Z", "time": datetime.datetime(1993, 1, 1)}, 42 | {"name": "4Z", "time": datetime.datetime(1995, 1, 1)}, 43 | {"name": "5Z", "time": datetime.datetime(1997, 1, 1)}, 44 | {"name": "6Z", "time": datetime.datetime(1998, 1, 1)}, 45 | {"name": "7Z", "time": datetime.datetime(1999, 1, 1)}, 46 | {"name": "8Z", "time": datetime.datetime(1999, 1, 1)}, 47 | {"name": "9Z", "time": datetime.datetime(1998, 1, 1)}, 48 | {"name": "10Z", "time": datetime.datetime(1997, 1, 1)}] 49 | 50 | >>> # dummy edges for python module tests 51 | >>> pyedges = [{"source": "4Z", "target": "2Z"}, 52 | {"source": "4Z", "target": "0Z"}, 53 | {"source": "4Z", "target": "1Z"}, 54 | {"source": "4Z", "target": "3Z"}, 55 | {"source": "5Z", "target": "2Z"}, 56 | {"source": "6Z", "target": "2Z"}, 57 | {"source": "6Z", "target": "4Z"}, 58 | {"source": "7Z", "target": "4Z"}, 59 | {"source": "8Z", "target": "4Z"}, 60 | {"source": "9Z", "target": "4Z"}, 61 | {"source": "9Z", "target": "1Z"}, 62 | {"source": "9Z", "target": "3Z"}, 63 | {"source": "10Z", "target": "4Z"}] 64 | 65 | 66 | >>> # create graph 67 | >>> graph = cdindex.Graph() 68 | 69 | >>> # add vertices 70 | >>> for vertex in pyvertices: 71 | graph.add_vertex(vertex["name"], cdindex.timestamp_from_datetime(vertex["time"])) 72 | 73 | >>> # add edges 74 | >>> for edge in pyedges: 75 | graph.add_edge(edge["source"], edge["target"]) 76 | 77 | >>> graph.cdindex("4Z", get_t_delta("4Z", years=5)) 78 | 79 | >>> graph.mcdindex("4Z", get_t_delta("4Z", years=5)) 80 | 81 | Bugs 82 | ---- 83 | 84 | Please report any bugs to . 85 | 86 | License 87 | ------- 88 | 89 | Released under the GNU General Public License (GPL) (see `LICENSE`):: 90 | 91 | Copyright (C) 2024 Russell J. Funk 92 | 93 | Other implementations 94 | --------------------- 95 | 96 | Below is a list of other (known) implementations of the cdindex. Please contact us if you know of others. 97 | 98 | * novelpy (https://novelpy.readthedocs.io/en/latest/index.html) 99 | * fast-cdindex (https://github.com/dspinellis/fast-cdindex) 100 | -------------------------------------------------------------------------------- /cdindex/__init__.py: -------------------------------------------------------------------------------- 1 | try: 2 | from cdindex.cdindex import * 3 | except ImportError: 4 | from cdindex import * 5 | 6 | try: 7 | from cdindex.time_utilities import * 8 | except ImportError: 9 | from time_utilities import * -------------------------------------------------------------------------------- /cdindex/cdindex.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | """cdindex.py: This script is an interface for the c extension _cdindex.""" 5 | 6 | __author__ = "Russell J. Funk" 7 | __copyright__ = "Copyright (C) 2019" 8 | 9 | # built in modules 10 | import math 11 | import random 12 | import itertools 13 | import os 14 | 15 | try: 16 | from builtins import int 17 | except ImportError: 18 | from __builtin__ import int 19 | 20 | # custom modules 21 | if "READTHEDOCS" not in os.environ: 22 | try: 23 | import cdindex._cdindex as _cdindex 24 | except ImportError: 25 | import _cdindex 26 | 27 | try: 28 | import cdindex.time_utilities 29 | except ImportError: 30 | import time_utilities 31 | 32 | class Graph: 33 | """Create a graph. 34 | 35 | This class defines a graph data structure on which to compute the cdindex and other 36 | functions that are made available through the module. 37 | """ 38 | 39 | def __init__(self, vertices=[], edges=[]): 40 | """Initialize a new graph. 41 | 42 | Create a new graph for analysis. Vertices and edges can be added either when the graph 43 | is initialized, or later. 44 | 45 | Example 46 | ------- 47 | vs = [{"name": "0Z", "time": datetime.datetime(1992, 1, 1)}, 48 | {"name": "1Z", "time": datetime.datetime(1992, 1, 1)}, 49 | {"name": "2Z", "time": datetime.datetime(1993, 1, 1)}, 50 | {"name": "3Z", "time": datetime.datetime(1993, 1, 1)}, 51 | {"name": "4Z", "time": datetime.datetime(1995, 1, 1)}, 52 | {"name": "5Z", "time": datetime.datetime(1997, 1, 1)}, 53 | {"name": "6Z", "time": datetime.datetime(1998, 1, 1)}, 54 | {"name": "7Z", "time": datetime.datetime(1999, 1, 1)}, 55 | {"name": "8Z", "time": datetime.datetime(1999, 1, 1)}, 56 | {"name": "9Z", "time": datetime.datetime(1998, 1, 1)}, 57 | {"name": "10Z", "time": datetime.datetime(1997, 1, 1)}] 58 | 59 | es = [{"source": "4Z", "target": "2Z"}, 60 | {"source": "4Z", "target": "0Z"}, 61 | {"source": "4Z", "target": "1Z"}, 62 | {"source": "4Z", "target": "3Z"}, 63 | {"source": "5Z", "target": "2Z"}, 64 | {"source": "6Z", "target": "2Z"}, 65 | {"source": "6Z", "target": "4Z"}, 66 | {"source": "7Z", "target": "4Z"}, 67 | {"source": "8Z", "target": "4Z"}, 68 | {"source": "9Z", "target": "4Z"}, 69 | {"source": "9Z", "target": "1Z"}, 70 | {"source": "9Z", "target": "3Z"}, 71 | {"source": "10Z", "target": "4Z"}] 72 | 73 | graph = cdindex.Graph(vertices=vs, edges=es) 74 | 75 | 76 | Parameters 77 | ---------- 78 | vertices : 79 | List of vertices with names and timestamps, e.g., 80 | [{"name": "0Z", "time": datetime.datetime(1992, 1, 1)}]. 81 | edges : 82 | List of edges with sources and targets, e.g., [{"source": "4Z", "target": "2Z"}]. 83 | """ 84 | 85 | self._graph = _cdindex.Graph() 86 | self._vertex_name_crosswalk = {} 87 | self._vertex_id_crosswalk = {} 88 | 89 | # add vertices 90 | for vertex in vertices: 91 | self.add_vertex(vertex["name"], vertex["time"]) 92 | 93 | # add edges 94 | for edge in edges: 95 | self.add_edge(edge["source"], edge["target"]) 96 | 97 | def add_vertex(self, name, t): 98 | """Add a new vertex to the graph. 99 | 100 | This function adds a new vertex to the graph, given a name and timestamp. 101 | 102 | Parameters 103 | ---------- 104 | name : 105 | The vertex name. 106 | t : int 107 | The vertex timestamp. 108 | """ 109 | vertex_id = self.vcount() 110 | if name in self._vertex_name_crosswalk: 111 | raise ValueError("Vertex already added to graph") 112 | else: 113 | self._vertex_name_crosswalk[name] = vertex_id 114 | self._vertex_id_crosswalk[vertex_id] = name 115 | if isinstance(t, (int)) is False: 116 | raise ValueError("Time (t) of vertex must be an integer or long") 117 | 118 | # add the vertex 119 | _cdindex.add_vertex(self._graph, vertex_id, t) 120 | 121 | def add_edge(self, source_name, target_name): 122 | """Add a new edge to the graph. 123 | 124 | This function adds a new edge to the graph, given a source name and target 125 | name. 126 | 127 | Parameters 128 | ---------- 129 | source_name : 130 | The source vertex name. 131 | target_name : 132 | The target vertex timestamp. 133 | """ 134 | if (source_name not in self._vertex_name_crosswalk 135 | or target_name not in self._vertex_name_crosswalk): 136 | raise ValueError("One or more vertices are not in the graph") 137 | elif (target_name in self.out_edges(source_name)): 138 | raise ValueError("The edge being added is already in the graph") 139 | else: 140 | _cdindex.add_edge(self._graph, 141 | self._vertex_name_crosswalk[source_name], 142 | self._vertex_name_crosswalk[target_name]) 143 | 144 | def vcount(self): 145 | """Return the number of vertices in the graph. 146 | 147 | This function returns the number of vertices in the graph. Note that time is 148 | not taken into account. The total count of vertices are returned regardless 149 | of when they appear in the graph. 150 | 151 | Returns 152 | ------- 153 | int 154 | The number of vertices. 155 | """ 156 | return _cdindex.get_vcount(self._graph) 157 | 158 | def _c_vertices(self): 159 | """Return the ids of the vertices in the graph from the C extension. 160 | 161 | This function returns a list of vertices in the graph. Rather than returning 162 | names, the id numbers from the C extension are returned. This function is 163 | not useful other than for internal purpuses. Note that time is not taken 164 | into account. Vertices are returned regardless of when they appear in the 165 | graph. 166 | 167 | Returns 168 | ------- 169 | list 170 | The vertices. 171 | """ 172 | return _cdindex.get_vertices(self._graph) 173 | 174 | def vertices(self): 175 | """Return the vertices in the graph. 176 | 177 | This function returns a list of vertices in the graph. Note that time is not 178 | taken into account. Vertices are returned regardless of when they appear in 179 | the graph. 180 | 181 | Returns 182 | ------- 183 | list 184 | The vertices. 185 | """ 186 | return self._vertex_name_crosswalk.keys() 187 | 188 | def ecount(self): 189 | """Return the number of edges in the graph. 190 | 191 | This function returns the number of edges in the graph. Note that time is 192 | not taken into account. The total count of edges are returned regardless of 193 | when they appear in the graph. 194 | 195 | Returns 196 | ------- 197 | int 198 | The number of edges. 199 | """ 200 | return _cdindex.get_ecount(self._graph) 201 | 202 | def in_degree(self, name): 203 | """Return the in degree of the focal vertex. 204 | 205 | Given a vertex, this function returns its in degree centrality, i.e., the 206 | number of other vertices in the graph that cite the focal vertex. Note that 207 | time is not taken into account. The function counts edges regardless of when 208 | they appear in the graph. 209 | 210 | Parameters 211 | ---------- 212 | name : 213 | The vertex name. 214 | 215 | Returns 216 | ------- 217 | int 218 | The in degree centrality. 219 | """ 220 | return _cdindex.get_vertex_in_degree(self._graph, 221 | self._vertex_name_crosswalk[name]) 222 | 223 | def in_edges(self, name): 224 | """Return the in edges of the focal vertex. 225 | 226 | Given a vertex, this function returns its in edges, i.e., the other 227 | vertices in the graph cited by the focal vertex. Note that time is not taken 228 | into account. The function returns edges regardless of when they appear in 229 | the graph. 230 | 231 | Parameters 232 | ---------- 233 | name : 234 | The vertex name. 235 | 236 | Returns 237 | ------- 238 | list 239 | The in edges. 240 | """ 241 | in_edges_ids = _cdindex.get_vertex_in_edges(self._graph, 242 | self._vertex_name_crosswalk[name]) 243 | return [self._vertex_id_crosswalk[vertex_id] for vertex_id in in_edges_ids] 244 | 245 | def out_degree(self, name): 246 | """Return the out degree of the focal vertex. 247 | 248 | Given a vertex, this function returns its out degree centrality, i.e., the 249 | number of other vertices in the graph cited by the focal vertex. Note that 250 | time is not taken into account. The function counts edges regardless of when 251 | they appear in the graph. 252 | 253 | Parameters 254 | ---------- 255 | name : 256 | The vertex name. 257 | 258 | Returns 259 | ------- 260 | int 261 | The out degree centrality. 262 | """ 263 | return _cdindex.get_vertex_out_degree(self._graph, 264 | self._vertex_name_crosswalk[name]) 265 | 266 | def out_edges(self, name): 267 | """Return the out edges of the focal vertex. 268 | 269 | Given a vertex, this function returns its out edges, i.e., the other 270 | vertices in the graph cited by the focal vertex. Note that time is not taken 271 | into account. The function returns edges regardless of when they appear in 272 | the graph. 273 | 274 | Parameters 275 | ---------- 276 | name : 277 | The vertex name. 278 | 279 | Returns 280 | ------- 281 | list 282 | The out edges. 283 | """ 284 | out_edges_ids = _cdindex.get_vertex_out_edges(self._graph, 285 | self._vertex_name_crosswalk[name]) 286 | return [self._vertex_id_crosswalk[vertex_id] for vertex_id in out_edges_ids] 287 | 288 | def timestamp(self, name): 289 | """Return the timestamp of the focal vertex. 290 | 291 | Given a vertex, this function returns its timestamp. 292 | 293 | Parameters 294 | ---------- 295 | name : 296 | The vertex name. 297 | 298 | Returns 299 | ------- 300 | int 301 | The timestamp. 302 | """ 303 | return _cdindex.get_vertex_timestamp(self._graph, 304 | self._vertex_name_crosswalk[name]) 305 | 306 | def cdindex(self, name, t_delta): 307 | """Compute the CD index. 308 | 309 | This function computes the CD index for a specified vertex at a given 310 | t_delta, where t_delta is an integer that gives the positive distance in 311 | time from the timestamp of the focal node when the index should be 312 | calculated. 313 | 314 | Parameters 315 | ---------- 316 | t_delta : int 317 | A time delta. 318 | 319 | Returns 320 | ------- 321 | double 322 | The CD index. 323 | """ 324 | if isinstance(t_delta, (int)) is False: 325 | raise ValueError("Time delta (t_delta) must be an integer or long") 326 | result = _cdindex.cdindex(self._graph, 327 | self._vertex_name_crosswalk[name], 328 | t_delta) 329 | if math.isnan(result): 330 | return None 331 | else: 332 | return result 333 | 334 | def mcdindex(self, name, t_delta): 335 | """Compute the mCD index. 336 | 337 | This function computes the mCD index for a specified vertex at a given 338 | t_delta, where t_delta is an integer that gives the positive distance in 339 | time from the timestamp of the focal node when the index should be 340 | calculated. 341 | 342 | Parameters 343 | ---------- 344 | t_delta : int 345 | A time delta. 346 | 347 | Returns 348 | ------- 349 | double 350 | The mCD index. 351 | """ 352 | if isinstance(t_delta, (int)) is False: 353 | raise ValueError("Time delta (t_delta) must be an integer or long") 354 | 355 | result = _cdindex.mcdindex(self._graph, 356 | self._vertex_name_crosswalk[name], 357 | t_delta) 358 | if math.isnan(result): 359 | return None 360 | else: 361 | return result 362 | 363 | def iindex(self, name, t_delta): 364 | """Compute the I index. 365 | 366 | This function computes the I index for a specified vertex at a given 367 | t_delta, where t_delta is an integer that gives the positive distance in 368 | time from the timestamp of the focal node when the index should be 369 | calculated. The I index is the in degree of the focal node at time t. 370 | 371 | Parameters 372 | ---------- 373 | t_delta : int 374 | A time delta. 375 | 376 | Returns 377 | ------- 378 | double 379 | The I index. 380 | """ 381 | if isinstance(t_delta, (int)) is False: 382 | raise ValueError("Time delta (t_delta) must be an integer or long") 383 | return _cdindex.iindex(self._graph, 384 | self._vertex_name_crosswalk[name], 385 | t_delta) 386 | 387 | def _is_graph_sane(self): 388 | """Test graph sanity. 389 | 390 | Run tests to verify the internal graph storage structure. Not really a 391 | useful function other than for checking possible issues with the module. 392 | 393 | Returns 394 | ------- 395 | bool 396 | True if successful, False otherwise. 397 | """ 398 | return _cdindex._is_graph_sane(self._graph) 399 | 400 | class RandomGraph(Graph): 401 | """Create a random graph. 402 | 403 | This class generates a random graph that can be used for testing the cdindex and other 404 | functions that are made available through the module. 405 | """ 406 | 407 | def __init__(self, generations=[], edge_fraction=[]): 408 | """Initialize a new random graph. 409 | 410 | Create a new random graph for analysis. 411 | 412 | Example 413 | ------- 414 | graph = cdindex.RandomGraph(generations=(2,3,4,5,6,7,7,9), edge_fraction=1) 415 | 416 | Parameters 417 | ---------- 418 | generations : 419 | List of discrete "generations", i.e., timestamps for each vertex. 420 | edge_fraction : 421 | The fraction of edges that should be present in the graph. 422 | """ 423 | 424 | # build vertex list 425 | vertices = [] 426 | for generation_id, generation_size in enumerate(generations): 427 | new_vertices = range(generation_size) 428 | vertices.extend([{"name": "v" + str(nv) + "g" + str(generation_id), 429 | "time": generation_id} for nv in new_vertices]) 430 | 431 | # build edge list 432 | edges = [] 433 | for possible_edges in itertools.product(vertices, vertices): 434 | if possible_edges[0]["time"] > possible_edges[1]["time"]: 435 | edges.append({"source": possible_edges[0]["name"], 436 | "target": possible_edges[1]["name"]}) 437 | 438 | # pull fraction of edges to keep 439 | random.shuffle(edges) 440 | edges = edges[0:int(math.ceil(edge_fraction * len(edges)))] 441 | 442 | # initialize graph 443 | Graph.__init__(self, vertices, edges) 444 | 445 | def main(): 446 | 447 | return None 448 | 449 | if __name__ == '__main__': 450 | main() 451 | -------------------------------------------------------------------------------- /cdindex/pycdindex.c: -------------------------------------------------------------------------------- 1 | /* 2 | cdindex library. 3 | Copyright (C) 2017 Russell J. Funk 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include "cdindex.h" 21 | 22 | #if PY_MAJOR_VERSION >= 3 23 | #define PY3K 24 | #endif 25 | 26 | /* Destructor function for Graph */ 27 | static void del_Graph(PyObject *obj) { 28 | free_graph(PyCapsule_GetPointer(obj,"Graph")); 29 | free(PyCapsule_GetPointer(obj,"Graph")); 30 | } 31 | 32 | /* Graph utility functions */ 33 | static Graph *PyGraph_AsGraph(PyObject *obj) { 34 | return (Graph *) PyCapsule_GetPointer(obj, "Graph"); 35 | } 36 | static PyObject *PyGraph_FromGraph(Graph *g, int must_free) { 37 | return PyCapsule_New(g, "Graph", must_free ? del_Graph : NULL); 38 | } 39 | 40 | /******************************************************************************* 41 | * Create a new Graph object * 42 | ******************************************************************************/ 43 | static PyObject *py_Graph(PyObject *self, PyObject *args) { 44 | Graph *g; 45 | 46 | // create a graph 47 | g = (Graph *) malloc(sizeof(Graph)); 48 | g->vcount = 0; 49 | g->ecount = 0; 50 | 51 | return PyGraph_FromGraph(g, 1); 52 | } 53 | 54 | /******************************************************************************* 55 | * Check graph sanity * 56 | ******************************************************************************/ 57 | static PyObject *py_is_graph_sane(PyObject *self, PyObject *args) { 58 | Graph *g; 59 | PyObject *py_g; 60 | 61 | if (!PyArg_ParseTuple(args,"O",&py_g)) 62 | return NULL; 63 | if (!(g = PyGraph_AsGraph(py_g))) 64 | return NULL; 65 | 66 | return Py_BuildValue("O", is_graph_sane(g) ? Py_True : Py_False); 67 | } 68 | 69 | /******************************************************************************* 70 | * Add a vertex to the graph * 71 | ******************************************************************************/ 72 | static PyObject *py_add_vertex(PyObject *self, PyObject *args) { 73 | long long int ID; 74 | long long int TIMESTAMP; 75 | Graph *g; 76 | PyObject *py_g; 77 | 78 | if (!PyArg_ParseTuple(args,"OLL",&py_g, &ID, &TIMESTAMP)) 79 | return NULL; 80 | if (!(g = PyGraph_AsGraph(py_g))) 81 | return NULL; 82 | 83 | add_vertex(g, ID, TIMESTAMP); 84 | 85 | return Py_BuildValue(""); 86 | } 87 | 88 | /******************************************************************************* 89 | * Add an edge to the graph * 90 | ******************************************************************************/ 91 | static PyObject *py_add_edge(PyObject *self, PyObject *args) { 92 | long long int SOURCE_ID, TARGET_ID; 93 | Graph *g; 94 | PyObject *py_g; 95 | 96 | if (!PyArg_ParseTuple(args,"OLL",&py_g, &SOURCE_ID, &TARGET_ID)) 97 | return NULL; 98 | if (!(g = PyGraph_AsGraph(py_g))) 99 | return NULL; 100 | 101 | add_edge(g, SOURCE_ID, TARGET_ID); 102 | 103 | return Py_BuildValue(""); 104 | } 105 | 106 | /******************************************************************************* 107 | * Get a count of vertices in the graph * 108 | ******************************************************************************/ 109 | static PyObject *py_get_vcount(PyObject *self, PyObject *args) { 110 | 111 | Graph *g; 112 | PyObject *py_g; 113 | 114 | if (!PyArg_ParseTuple(args,"O",&py_g)) 115 | return NULL; 116 | if (!(g = PyGraph_AsGraph(py_g))) 117 | return NULL; 118 | 119 | return Py_BuildValue("L", g->vcount); 120 | } 121 | 122 | /******************************************************************************* 123 | * Get list of vertices in the graph * 124 | ******************************************************************************/ 125 | static PyObject *py_get_vertices(PyObject *self, PyObject *args) { 126 | 127 | Graph *g; 128 | PyObject *py_g, *id, *result; 129 | 130 | if (!PyArg_ParseTuple(args,"O",&py_g)) 131 | return NULL; 132 | if (!(g = PyGraph_AsGraph(py_g))) 133 | return NULL; 134 | 135 | PyObject *vs_list = PyList_New(g->vcount); 136 | 137 | for (long long int i = 0; i < g->vcount; i++) { 138 | id = Py_BuildValue("L", g->vs[i].id); 139 | PyList_SetItem(vs_list, i, id); 140 | } 141 | 142 | result = Py_BuildValue("O", vs_list); 143 | 144 | // clean up 145 | Py_DECREF(vs_list); 146 | 147 | return result; 148 | } 149 | 150 | /******************************************************************************* 151 | * Get a count of edges in the graph * 152 | ******************************************************************************/ 153 | static PyObject *py_get_ecount(PyObject *self, PyObject *args) { 154 | 155 | Graph *g; 156 | PyObject *py_g; 157 | 158 | if (!PyArg_ParseTuple(args,"O",&py_g)) 159 | return NULL; 160 | if (!(g = PyGraph_AsGraph(py_g))) 161 | return NULL; 162 | 163 | return Py_BuildValue("L", g->ecount); 164 | } 165 | 166 | /******************************************************************************* 167 | * Get a vertex timestamp * 168 | ******************************************************************************/ 169 | static PyObject *py_get_vertex_timestamp(PyObject *self, PyObject *args) { 170 | long long int ID; 171 | 172 | Graph *g; 173 | PyObject *py_g; 174 | 175 | if (!PyArg_ParseTuple(args,"OL",&py_g, &ID)) 176 | return NULL; 177 | if (!(g = PyGraph_AsGraph(py_g))) 178 | return NULL; 179 | 180 | return Py_BuildValue("L", g->vs[ID].timestamp); 181 | } 182 | 183 | /******************************************************************************* 184 | * Get a vertex in degree * 185 | ******************************************************************************/ 186 | static PyObject *py_get_vertex_in_degree(PyObject *self, PyObject *args) { 187 | long long int ID; 188 | 189 | Graph *g; 190 | PyObject *py_g; 191 | 192 | if (!PyArg_ParseTuple(args,"OL",&py_g, &ID)) 193 | return NULL; 194 | if (!(g = PyGraph_AsGraph(py_g))) 195 | return NULL; 196 | 197 | return Py_BuildValue("L", g->vs[ID].in_degree); 198 | } 199 | 200 | /******************************************************************************* 201 | * Get the in edges of a vertex * 202 | ******************************************************************************/ 203 | static PyObject *py_get_vertex_in_edges(PyObject *self, PyObject *args) { 204 | 205 | long long int ID; 206 | Graph *g; 207 | PyObject *py_g, *source_id, *result; 208 | 209 | if (!PyArg_ParseTuple(args,"OL",&py_g, &ID)) 210 | return NULL; 211 | if (!(g = PyGraph_AsGraph(py_g))) 212 | return NULL; 213 | 214 | PyObject *vs_list = PyList_New(g->vs[ID].in_degree); 215 | 216 | for (long long int i = 0; i < g->vs[ID].in_degree; i++) { 217 | source_id = Py_BuildValue("L", g->vs[ID].in_edges[i]); 218 | PyList_SetItem(vs_list, i, source_id); 219 | } 220 | 221 | result = Py_BuildValue("O", vs_list); 222 | 223 | // clean up 224 | Py_DECREF(vs_list); 225 | 226 | return result; 227 | } 228 | 229 | /******************************************************************************* 230 | * Get a vertex out degree * 231 | ******************************************************************************/ 232 | static PyObject *py_get_vertex_out_degree(PyObject *self, PyObject *args) { 233 | long long int ID; 234 | 235 | Graph *g; 236 | PyObject *py_g; 237 | 238 | if (!PyArg_ParseTuple(args,"OL",&py_g, &ID)) 239 | return NULL; 240 | if (!(g = PyGraph_AsGraph(py_g))) 241 | return NULL; 242 | 243 | return Py_BuildValue("L", g->vs[ID].out_degree); 244 | } 245 | 246 | /******************************************************************************* 247 | * Get the out edges of a vertex * 248 | ******************************************************************************/ 249 | static PyObject *py_get_vertex_out_edges(PyObject *self, PyObject *args) { 250 | 251 | long long int ID; 252 | Graph *g; 253 | PyObject *py_g, *target_id, *result; 254 | 255 | if (!PyArg_ParseTuple(args,"OL",&py_g, &ID)) 256 | return NULL; 257 | if (!(g = PyGraph_AsGraph(py_g))) 258 | return NULL; 259 | 260 | PyObject *vs_list = PyList_New(g->vs[ID].out_degree); 261 | 262 | for (long long int i = 0; i < g->vs[ID].out_degree; i++) { 263 | target_id = Py_BuildValue("L", g->vs[ID].out_edges[i]); 264 | PyList_SetItem(vs_list, i, target_id); 265 | } 266 | 267 | result = Py_BuildValue("O", vs_list); 268 | 269 | // clean up 270 | Py_DECREF(vs_list); 271 | 272 | return result; 273 | } 274 | 275 | /******************************************************************************* 276 | * Compute the CD index * 277 | ******************************************************************************/ 278 | static PyObject *py_cdindex(PyObject *self, PyObject *args) { 279 | long long int ID; 280 | long long int TIMESTAMP; 281 | 282 | double result; 283 | Graph *g; 284 | PyObject *py_g; 285 | 286 | if (!PyArg_ParseTuple(args,"OLL",&py_g, &ID, &TIMESTAMP)) 287 | return NULL; 288 | if (!(g = PyGraph_AsGraph(py_g))) 289 | return NULL; 290 | 291 | result = cdindex(g, ID, TIMESTAMP); 292 | 293 | return Py_BuildValue("d", result); 294 | } 295 | 296 | /******************************************************************************* 297 | * Compute the mCD index * 298 | ******************************************************************************/ 299 | static PyObject *py_mcdindex(PyObject *self, PyObject *args) { 300 | long long int ID; 301 | long long int TIMESTAMP; 302 | double result; 303 | Graph *g; 304 | PyObject *py_g; 305 | 306 | if (!PyArg_ParseTuple(args,"OLL",&py_g, &ID, &TIMESTAMP)) 307 | return NULL; 308 | if (!(g = PyGraph_AsGraph(py_g))) 309 | return NULL; 310 | 311 | result = mcdindex(g, ID, TIMESTAMP); 312 | 313 | return Py_BuildValue("d", result); 314 | } 315 | 316 | /******************************************************************************* 317 | * Compute the I index * 318 | ******************************************************************************/ 319 | static PyObject *py_iindex(PyObject *self, PyObject *args) { 320 | long long int ID; 321 | long long int TIMESTAMP; 322 | double result; 323 | Graph *g; 324 | PyObject *py_g; 325 | 326 | if (!PyArg_ParseTuple(args,"OLL",&py_g, &ID, &TIMESTAMP)) 327 | return NULL; 328 | if (!(g = PyGraph_AsGraph(py_g))) 329 | return NULL; 330 | 331 | result = iindex(g, ID, TIMESTAMP); 332 | 333 | return Py_BuildValue("d", result); 334 | } 335 | 336 | 337 | /******************************************************************************* 338 | * Module method table * 339 | ******************************************************************************/ 340 | static PyMethodDef CDIndexMethods[] = { 341 | {"Graph", py_Graph, METH_VARARGS, "Make a graph"}, 342 | {"_is_graph_sane", py_is_graph_sane, METH_VARARGS, "Test graph sanity"}, 343 | {"add_vertex", py_add_vertex, METH_VARARGS, "Add a vertex to a graph"}, 344 | {"add_edge", py_add_edge, METH_VARARGS, "Add an edge to a graph"}, 345 | {"get_vertices", py_get_vertices, METH_VARARGS, "Get a list of vertices in the graph"}, 346 | {"get_vcount", py_get_vcount, METH_VARARGS, "Get the number of vertices in the graph"}, 347 | {"get_ecount", py_get_ecount, METH_VARARGS, "Get the number of edges in the graph"}, 348 | {"get_vertex_timestamp", py_get_vertex_timestamp, METH_VARARGS, "Get the timestamp of a vertex"}, 349 | {"get_vertex_in_degree", py_get_vertex_in_degree, METH_VARARGS, "Get the in degree of a vertex"}, 350 | {"get_vertex_in_edges", py_get_vertex_in_edges, METH_VARARGS, "Get the in edges of a vertex"}, 351 | {"get_vertex_out_degree", py_get_vertex_out_degree, METH_VARARGS, "Get the out degree of a vertex"}, 352 | {"get_vertex_out_edges", py_get_vertex_out_edges, METH_VARARGS, "Get the out edges of a vertex"}, 353 | {"cdindex", py_cdindex, METH_VARARGS, "Compute the CD index"}, 354 | {"mcdindex", py_mcdindex, METH_VARARGS, "Compute the mCD index"}, 355 | {"iindex", py_iindex, METH_VARARGS, "Compute the I index"}, 356 | { NULL, NULL, 0, NULL} 357 | }; 358 | 359 | /******************************************************************************* 360 | * Module initialization function * 361 | ******************************************************************************/ 362 | 363 | 364 | #ifdef PY3K 365 | static struct PyModuleDef _cdindex = 366 | { 367 | PyModuleDef_HEAD_INIT, 368 | "_cdindex", 369 | "", 370 | -1, 371 | CDIndexMethods 372 | }; 373 | 374 | PyMODINIT_FUNC PyInit__cdindex(void) 375 | { 376 | return PyModule_Create(&_cdindex); 377 | } 378 | #else 379 | PyMODINIT_FUNC 380 | init_cdindex(void) { 381 | (void) Py_InitModule("_cdindex", CDIndexMethods); 382 | } 383 | #endif -------------------------------------------------------------------------------- /cdindex/time_utilities.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | """time_utilities.py: Utility functions for converting time formats.""" 5 | 6 | __author__ = "Russell J. Funk" 7 | __copyright__ = "Copyright (C) 2017" 8 | 9 | # built in modules 10 | import datetime 11 | import calendar 12 | 13 | def timestamp_from_datetime(dt): 14 | """Convert a datetime to a Unix timestamp. 15 | 16 | Given a datetime, this function returns a Unix timestamp. Input is assumed to 17 | be Greenwich Mean Time (GMT) and local time zone information is ignored. The 18 | function is useful for converting dates to integers, which are required as 19 | input to some other functions in the module. 20 | 21 | Parameters 22 | ---------- 23 | dt : datetime 24 | A datetime. 25 | 26 | Returns 27 | ------- 28 | int 29 | A Unix timestamp. 30 | """ 31 | return calendar.timegm(dt.utctimetuple()) 32 | 33 | def datetime_from_timestamp(ts): 34 | """Convert a Unix timestamp to a datetime. 35 | 36 | Given a Unix timestamp, this function returns a datetime. Input is assumed to 37 | be Greenwich Mean Time (GMT) and local time zone information is ignored. The 38 | function is useful for converting integers, which are required by some 39 | functions in the module, to more human readable dates. 40 | 41 | Parameters 42 | ---------- 43 | ts : int 44 | A Unix timestamp. 45 | 46 | Returns 47 | ------- 48 | datetime 49 | A datetime. 50 | """ 51 | return datetime.datetime.utcfromtimestamp(ts) 52 | 53 | def main(): 54 | 55 | return None 56 | 57 | if __name__ == "__main__": 58 | main() -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help 23 | help: 24 | @echo "Please use \`make ' where is one of" 25 | @echo " html to make standalone HTML files" 26 | @echo " dirhtml to make HTML files named index.html in directories" 27 | @echo " singlehtml to make a single large HTML file" 28 | @echo " pickle to make pickle files" 29 | @echo " json to make JSON files" 30 | @echo " htmlhelp to make HTML files and a HTML help project" 31 | @echo " qthelp to make HTML files and a qthelp project" 32 | @echo " applehelp to make an Apple Help Book" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | @echo " coverage to run coverage check of the documentation (if enabled)" 49 | 50 | .PHONY: clean 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | .PHONY: html 55 | html: 56 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 57 | @echo 58 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 59 | 60 | .PHONY: dirhtml 61 | dirhtml: 62 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 63 | @echo 64 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 65 | 66 | .PHONY: singlehtml 67 | singlehtml: 68 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 69 | @echo 70 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 71 | 72 | .PHONY: pickle 73 | pickle: 74 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 75 | @echo 76 | @echo "Build finished; now you can process the pickle files." 77 | 78 | .PHONY: json 79 | json: 80 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 81 | @echo 82 | @echo "Build finished; now you can process the JSON files." 83 | 84 | .PHONY: htmlhelp 85 | htmlhelp: 86 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 87 | @echo 88 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 89 | ".hhp project file in $(BUILDDIR)/htmlhelp." 90 | 91 | .PHONY: qthelp 92 | qthelp: 93 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 94 | @echo 95 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 96 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 97 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/cdindex.qhcp" 98 | @echo "To view the help file:" 99 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/cdindex.qhc" 100 | 101 | .PHONY: applehelp 102 | applehelp: 103 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 104 | @echo 105 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 106 | @echo "N.B. You won't be able to view it unless you put it in" \ 107 | "~/Library/Documentation/Help or install it in your application" \ 108 | "bundle." 109 | 110 | .PHONY: devhelp 111 | devhelp: 112 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 113 | @echo 114 | @echo "Build finished." 115 | @echo "To view the help file:" 116 | @echo "# mkdir -p $$HOME/.local/share/devhelp/cdindex" 117 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/cdindex" 118 | @echo "# devhelp" 119 | 120 | .PHONY: epub 121 | epub: 122 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 123 | @echo 124 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 125 | 126 | .PHONY: latex 127 | latex: 128 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 129 | @echo 130 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 131 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 132 | "(use \`make latexpdf' here to do that automatically)." 133 | 134 | .PHONY: latexpdf 135 | latexpdf: 136 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 137 | @echo "Running LaTeX files through pdflatex..." 138 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 139 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 140 | 141 | .PHONY: latexpdfja 142 | latexpdfja: 143 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 144 | @echo "Running LaTeX files through platex and dvipdfmx..." 145 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 146 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 147 | 148 | .PHONY: text 149 | text: 150 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 151 | @echo 152 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 153 | 154 | .PHONY: man 155 | man: 156 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 157 | @echo 158 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 159 | 160 | .PHONY: texinfo 161 | texinfo: 162 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 163 | @echo 164 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 165 | @echo "Run \`make' in that directory to run these through makeinfo" \ 166 | "(use \`make info' here to do that automatically)." 167 | 168 | .PHONY: info 169 | info: 170 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 171 | @echo "Running Texinfo files through makeinfo..." 172 | make -C $(BUILDDIR)/texinfo info 173 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 174 | 175 | .PHONY: gettext 176 | gettext: 177 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 178 | @echo 179 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 180 | 181 | .PHONY: changes 182 | changes: 183 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 184 | @echo 185 | @echo "The overview file is in $(BUILDDIR)/changes." 186 | 187 | .PHONY: linkcheck 188 | linkcheck: 189 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 190 | @echo 191 | @echo "Link check complete; look for any errors in the above output " \ 192 | "or in $(BUILDDIR)/linkcheck/output.txt." 193 | 194 | .PHONY: doctest 195 | doctest: 196 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 197 | @echo "Testing of doctests in the sources finished, look at the " \ 198 | "results in $(BUILDDIR)/doctest/output.txt." 199 | 200 | .PHONY: coverage 201 | coverage: 202 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 203 | @echo "Testing of coverage in the sources finished, look at the " \ 204 | "results in $(BUILDDIR)/coverage/python.txt." 205 | 206 | .PHONY: xml 207 | xml: 208 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 209 | @echo 210 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 211 | 212 | .PHONY: pseudoxml 213 | pseudoxml: 214 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 215 | @echo 216 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 217 | -------------------------------------------------------------------------------- /docs/cdindex.cdindex.rst: -------------------------------------------------------------------------------- 1 | cdindex.cdindex module 2 | ====================== 3 | 4 | .. automodule:: cdindex.cdindex 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/cdindex.rst: -------------------------------------------------------------------------------- 1 | cdindex package 2 | =============== 3 | 4 | Submodules 5 | ---------- 6 | 7 | .. toctree:: 8 | 9 | cdindex.cdindex 10 | cdindex.time_utilities 11 | 12 | Module contents 13 | --------------- 14 | 15 | .. automodule:: cdindex 16 | :members: 17 | :undoc-members: 18 | :show-inheritance: 19 | -------------------------------------------------------------------------------- /docs/cdindex.time_utilities.rst: -------------------------------------------------------------------------------- 1 | cdindex.time_utilities module 2 | ============================= 3 | 4 | .. automodule:: cdindex.time_utilities 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # cdindex documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Jul 11 13:27:32 2017. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | 18 | import sys 19 | from mock import Mock as MagicMock 20 | class Mock(MagicMock): 21 | @classmethod 22 | def __getattr__(cls, name): 23 | return MagicMock() 24 | MOCK_MODULES = ['_cdindex'] 25 | sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) 26 | 27 | 28 | # If extensions (or modules to document with autodoc) are in another directory, 29 | # add these directories to sys.path here. If the directory is relative to the 30 | # documentation root, use os.path.abspath to make it absolute, like shown here. 31 | #sys.path.insert(0, os.path.abspath('.')) 32 | sys.path.insert(0, os.path.abspath("../")) 33 | 34 | # -- General configuration ------------------------------------------------ 35 | 36 | # If your documentation needs a minimal Sphinx version, state it here. 37 | #needs_sphinx = '1.0' 38 | 39 | # Add any Sphinx extension module names here, as strings. They can be 40 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 41 | # ones. 42 | extensions = [ 43 | 'sphinx.ext.autodoc', 44 | 'sphinx.ext.coverage', 45 | 'sphinx.ext.viewcode', 46 | 'sphinx.ext.napoleon' 47 | ] 48 | 49 | # Add any paths that contain templates here, relative to this directory. 50 | templates_path = ['_templates'] 51 | 52 | # The suffix(es) of source filenames. 53 | # You can specify multiple suffix as a list of string: 54 | # source_suffix = ['.rst', '.md'] 55 | source_suffix = '.rst' 56 | 57 | # The encoding of source files. 58 | #source_encoding = 'utf-8-sig' 59 | 60 | # The master toctree document. 61 | master_doc = 'index' 62 | 63 | # General information about the project. 64 | project = u'cdindex' 65 | copyright = u'2024, Russell J. Funk' 66 | author = u'Russell J. Funk' 67 | 68 | # The version info for the project you're documenting, acts as replacement for 69 | # |version| and |release|, also used in various other places throughout the 70 | # built documents. 71 | # 72 | # The short X.Y version. 73 | version = u'1.0' 74 | # The full version, including alpha/beta/rc tags. 75 | release = u'1.0.20' 76 | 77 | # The language for content autogenerated by Sphinx. Refer to documentation 78 | # for a list of supported languages. 79 | # 80 | # This is also used if you do content translation via gettext catalogs. 81 | # Usually you set "language" from the command line for these cases. 82 | language = None 83 | 84 | # There are two options for replacing |today|: either, you set today to some 85 | # non-false value, then it is used: 86 | #today = '' 87 | # Else, today_fmt is used as the format for a strftime call. 88 | #today_fmt = '%B %d, %Y' 89 | 90 | # List of patterns, relative to source directory, that match files and 91 | # directories to ignore when looking for source files. 92 | exclude_patterns = ['_build'] 93 | 94 | # The reST default role (used for this markup: `text`) to use for all 95 | # documents. 96 | #default_role = None 97 | 98 | # If true, '()' will be appended to :func: etc. cross-reference text. 99 | #add_function_parentheses = True 100 | 101 | # If true, the current module name will be prepended to all description 102 | # unit titles (such as .. function::). 103 | #add_module_names = True 104 | 105 | # If true, sectionauthor and moduleauthor directives will be shown in the 106 | # output. They are ignored by default. 107 | #show_authors = False 108 | 109 | # The name of the Pygments (syntax highlighting) style to use. 110 | pygments_style = 'sphinx' 111 | 112 | # A list of ignored prefixes for module index sorting. 113 | #modindex_common_prefix = [] 114 | 115 | # If true, keep warnings as "system message" paragraphs in the built documents. 116 | #keep_warnings = False 117 | 118 | # If true, `todo` and `todoList` produce output, else they produce nothing. 119 | todo_include_todos = False 120 | 121 | 122 | # -- Options for HTML output ---------------------------------------------- 123 | 124 | # The theme to use for HTML and HTML Help pages. See the documentation for 125 | # a list of builtin themes. 126 | #html_theme = 'alabaster' 127 | html_theme = "sphinx_rtd_theme" 128 | 129 | # Theme options are theme-specific and customize the look and feel of a theme 130 | # further. For a list of options available for each theme, see the 131 | # documentation. 132 | #html_theme_options = {} 133 | 134 | # Add any paths that contain custom themes here, relative to this directory. 135 | #html_theme_path = [] 136 | 137 | # The name for this set of Sphinx documents. If None, it defaults to 138 | # " v documentation". 139 | #html_title = None 140 | 141 | # A shorter title for the navigation bar. Default is the same as html_title. 142 | #html_short_title = None 143 | 144 | # The name of an image file (relative to this directory) to place at the top 145 | # of the sidebar. 146 | #html_logo = None 147 | 148 | # The name of an image file (within the static path) to use as favicon of the 149 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 150 | # pixels large. 151 | #html_favicon = None 152 | 153 | # Add any paths that contain custom static files (such as style sheets) here, 154 | # relative to this directory. They are copied after the builtin static files, 155 | # so a file named "default.css" will overwrite the builtin "default.css". 156 | html_static_path = ['_static'] 157 | 158 | # Add any extra paths that contain custom files (such as robots.txt or 159 | # .htaccess) here, relative to this directory. These files are copied 160 | # directly to the root of the documentation. 161 | #html_extra_path = [] 162 | 163 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 164 | # using the given strftime format. 165 | #html_last_updated_fmt = '%b %d, %Y' 166 | 167 | # If true, SmartyPants will be used to convert quotes and dashes to 168 | # typographically correct entities. 169 | #html_use_smartypants = True 170 | 171 | # Custom sidebar templates, maps document names to template names. 172 | #html_sidebars = {} 173 | 174 | # Additional templates that should be rendered to pages, maps page names to 175 | # template names. 176 | #html_additional_pages = {} 177 | 178 | # If false, no module index is generated. 179 | #html_domain_indices = True 180 | 181 | # If false, no index is generated. 182 | #html_use_index = True 183 | 184 | # If true, the index is split into individual pages for each letter. 185 | #html_split_index = False 186 | 187 | # If true, links to the reST sources are added to the pages. 188 | #html_show_sourcelink = True 189 | 190 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 191 | #html_show_sphinx = True 192 | 193 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 194 | #html_show_copyright = True 195 | 196 | # If true, an OpenSearch description file will be output, and all pages will 197 | # contain a tag referring to it. The value of this option must be the 198 | # base URL from which the finished HTML is served. 199 | #html_use_opensearch = '' 200 | 201 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 202 | #html_file_suffix = None 203 | 204 | # Language to be used for generating the HTML full-text search index. 205 | # Sphinx supports the following languages: 206 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 207 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' 208 | #html_search_language = 'en' 209 | 210 | # A dictionary with options for the search language support, empty by default. 211 | # Now only 'ja' uses this config value 212 | #html_search_options = {'type': 'default'} 213 | 214 | # The name of a javascript file (relative to the configuration directory) that 215 | # implements a search results scorer. If empty, the default will be used. 216 | #html_search_scorer = 'scorer.js' 217 | 218 | # Output file base name for HTML help builder. 219 | htmlhelp_basename = 'cdindexdoc' 220 | 221 | # -- Options for LaTeX output --------------------------------------------- 222 | 223 | latex_elements = { 224 | # The paper size ('letterpaper' or 'a4paper'). 225 | #'papersize': 'letterpaper', 226 | 227 | # The font size ('10pt', '11pt' or '12pt'). 228 | #'pointsize': '10pt', 229 | 230 | # Additional stuff for the LaTeX preamble. 231 | #'preamble': '', 232 | 233 | # Latex figure (float) alignment 234 | #'figure_align': 'htbp', 235 | } 236 | 237 | # Grouping the document tree into LaTeX files. List of tuples 238 | # (source start file, target name, title, 239 | # author, documentclass [howto, manual, or own class]). 240 | latex_documents = [ 241 | (master_doc, 'cdindex.tex', u'cdindex Documentation', 242 | u'Russell J. Funk', 'manual'), 243 | ] 244 | 245 | # The name of an image file (relative to this directory) to place at the top of 246 | # the title page. 247 | #latex_logo = None 248 | 249 | # For "manual" documents, if this is true, then toplevel headings are parts, 250 | # not chapters. 251 | #latex_use_parts = False 252 | 253 | # If true, show page references after internal links. 254 | #latex_show_pagerefs = False 255 | 256 | # If true, show URL addresses after external links. 257 | #latex_show_urls = False 258 | 259 | # Documents to append as an appendix to all manuals. 260 | #latex_appendices = [] 261 | 262 | # If false, no module index is generated. 263 | #latex_domain_indices = True 264 | 265 | 266 | # -- Options for manual page output --------------------------------------- 267 | 268 | # One entry per manual page. List of tuples 269 | # (source start file, name, description, authors, manual section). 270 | man_pages = [ 271 | (master_doc, 'cdindex', u'cdindex Documentation', 272 | [author], 1) 273 | ] 274 | 275 | # If true, show URL addresses after external links. 276 | #man_show_urls = False 277 | 278 | 279 | # -- Options for Texinfo output ------------------------------------------- 280 | 281 | # Grouping the document tree into Texinfo files. List of tuples 282 | # (source start file, target name, title, author, 283 | # dir menu entry, description, category) 284 | texinfo_documents = [ 285 | (master_doc, 'cdindex', u'cdindex Documentation', 286 | author, 'cdindex', 'One line description of project.', 287 | 'Miscellaneous'), 288 | ] 289 | 290 | # Documents to append as an appendix to all manuals. 291 | #texinfo_appendices = [] 292 | 293 | # If false, no module index is generated. 294 | #texinfo_domain_indices = True 295 | 296 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 297 | #texinfo_show_urls = 'footnote' 298 | 299 | # If true, do not generate a @detailmenu in the "Top" node's menu. 300 | #texinfo_no_detailmenu = False 301 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. cdindex documentation master file, created by 2 | sphinx-quickstart on Tue Jul 11 15:29:31 2017. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to cdindex's documentation! 7 | =================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | 15 | 16 | Indices and tables 17 | ================== 18 | 19 | * :ref:`genindex` 20 | * :ref:`modindex` 21 | * :ref:`search` 22 | 23 | -------------------------------------------------------------------------------- /docs/modules.rst: -------------------------------------------------------------------------------- 1 | cdindex 2 | ======= 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | cdindex 8 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | """setup.py: This script installs the cdindex python module.""" 5 | 6 | __author__ = "Russell J. Funk" 7 | __copyright__ = "Copyright (C) 2024" 8 | 9 | # built in modules 10 | from setuptools import setup, Extension, find_packages 11 | 12 | setup(name="cdindex", 13 | version="1.0.20", 14 | description="Package for computing the cdindex.", 15 | author="Russell J. Funk", 16 | author_email="russellfunk@gmail.com", 17 | url="http://www.cdindex.info", 18 | license="GNU General Public License (GPL)", 19 | install_requires=['future'], 20 | ext_modules=[ 21 | Extension("cdindex._cdindex", 22 | ["src/cdindex.c", 23 | "src/graph.c", 24 | "src/utility.c", 25 | "cdindex/pycdindex.c"], 26 | include_dirs = ["src"], 27 | ) 28 | ], 29 | packages=find_packages() 30 | ) 31 | 32 | # python setup.py build_ext --inplace 33 | # python setup.py sdist -------------------------------------------------------------------------------- /src/cdindex.c: -------------------------------------------------------------------------------- 1 | /* 2 | cdindex library. 3 | Copyright (C) 2017 Russell J. Funk 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include "cdindex.h" 22 | 23 | /** 24 | * \function cdindex 25 | * \brief Computes the CD Index. 26 | * 27 | * \param graph The input graph. 28 | * \param id The focal vertex id. 29 | * \param time_delta Time beyond stamp of focal vertex to consider in measure. 30 | * 31 | * \return The value of the CD index. 32 | */ 33 | double cdindex(Graph *graph, long long int id, long long int time_delta){ 34 | 35 | /* Build a list of "it" vertices that are "in_edges" of the focal vertex's 36 | "out_edges" as of timestamp t. Vertices in the list are unique. */ 37 | 38 | long long int it_count = 0; 39 | long long int *it = malloc(sizeof(long long int)); 40 | 41 | /* check for malloc problems */ 42 | if (it==NULL) { 43 | raise_error(0); 44 | } 45 | 46 | /* define i for multiple loops */ 47 | long long int i; 48 | 49 | /* add unique "in_edges" of focal vertex "out_edges" */ 50 | for (i = 0; i < graph->vs[id].out_degree; i++) { 51 | long long int out_edge_i = graph->vs[id].out_edges[i]; 52 | for (long long int j = 0; j < graph->vs[out_edge_i].in_degree; j++) { 53 | long long int out_edge_i_in_edge_j = graph->vs[out_edge_i].in_edges[j]; 54 | if (graph->vs[out_edge_i_in_edge_j].timestamp > graph->vs[id].timestamp && 55 | graph->vs[out_edge_i_in_edge_j].timestamp <= (graph->vs[id].timestamp + time_delta) && 56 | !in_int_array(it, it_count, out_edge_i_in_edge_j)) { 57 | add_to_int_array(&it, it_count, out_edge_i_in_edge_j, true); 58 | it_count++; 59 | } 60 | } 61 | } 62 | 63 | /* add unique "in_edges" of focal vertex */ 64 | for (i = 0; i < graph->vs[id].in_degree; i++) { 65 | long long int in_edge_i = graph->vs[id].in_edges[i]; 66 | if (graph->vs[in_edge_i].timestamp > graph->vs[id].timestamp && 67 | graph->vs[in_edge_i].timestamp <= (graph->vs[id].timestamp + time_delta) && 68 | !in_int_array(it, it_count, in_edge_i)) { 69 | add_to_int_array(&it, it_count, in_edge_i, true); 70 | it_count++; 71 | } 72 | } 73 | 74 | /* compute the cd index */ 75 | double sum_i = 0.0; 76 | for (i = 0; i < it_count; i++) { 77 | long long int f_it = in_int_array(graph->vs[it[i]].out_edges, graph->vs[it[i]].out_degree, id); 78 | long long int b_it = 0; 79 | for (long long int j = 0; j < graph->vs[it[i]].out_degree; j++) { 80 | if (in_int_array(graph->vs[id].out_edges, graph->vs[id].out_degree, graph->vs[it[i]].out_edges[j])) { 81 | b_it = 1; 82 | } 83 | } 84 | sum_i += -2.0*f_it*b_it + f_it; 85 | } 86 | 87 | free(it); 88 | return sum_i/it_count; 89 | } 90 | 91 | /** 92 | * \function iindex 93 | * \brief Computes the I Index (i.e., the in degree of the focal vertex at time t). 94 | * 95 | * \param graph The input graph. 96 | * \param id The focal vertex id. 97 | * \param time_delta Time beyond stamp of focal vertex to consider in computing the measure. 98 | * 99 | * \return The value of the I index. 100 | */ 101 | long long int iindex(Graph *graph, long long int id, long long int time_delta){ 102 | 103 | /* count mt vertices that are "in_edges" of the focal vertex as of timestamp t. */ 104 | long long int mt_count = 0; 105 | for (long long int i = 0; i < graph->vs[id].in_degree; i++) { 106 | long long int in_edge_i = graph->vs[id].in_edges[i]; 107 | if (graph->vs[in_edge_i].timestamp <= (graph->vs[id].timestamp + time_delta)) { 108 | mt_count++; 109 | } 110 | } 111 | 112 | return mt_count; 113 | } 114 | 115 | /** 116 | * \function mcdindex 117 | * \brief Computes the mCD Index. 118 | * 119 | * \param graph The input graph. 120 | * \param id The focal vertex id. 121 | * \param time_delta Time beyond stamp of focal vertex to consider in computing the measure. 122 | * 123 | * \return The value of the mCD index. 124 | */ 125 | double mcdindex(Graph *graph, long long int id, long long int time_delta){ 126 | 127 | double cdindex_value = cdindex(graph, id, time_delta); 128 | long long int iindex_value = iindex(graph, id, time_delta); 129 | 130 | return cdindex_value * iindex_value; 131 | 132 | } 133 | -------------------------------------------------------------------------------- /src/cdindex.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef struct Vertex { 4 | long long int id; 5 | long long int timestamp; 6 | long long int *in_edges; 7 | long long int *out_edges; 8 | long long int in_degree; 9 | long long int out_degree; 10 | } Vertex; 11 | 12 | typedef struct Edge { 13 | long long int source_id; 14 | long long int target_id; 15 | } Edge; 16 | 17 | typedef struct Graph { 18 | long long int vcount; 19 | Vertex *vs; 20 | long long int ecount; 21 | } Graph; 22 | 23 | #define CREATE_GRAPH(G) Graph G = {.vcount = 0, .ecount = 0} 24 | 25 | /* function prototypes for utility.c */ 26 | void raise_error(int code); 27 | bool in_int_array(long long int *array, long long int sizeof_array, long long int value); 28 | void add_to_int_array(long long int **array, long long int sizeof_array, long long int value, bool add_memory); 29 | 30 | /* function prototypes for graph.c */ 31 | bool is_graph_sane(Graph *graph); 32 | void add_vertex(Graph *graph, long long int id, long long int timestamp); 33 | void add_edge(Graph *graph, long long int source_id, long long int target_id); 34 | void free_graph(Graph *graph); 35 | 36 | /* function prototypes for cdindex.c */ 37 | double cdindex(Graph *graph, long long int id, long long int time_delta); 38 | double mcdindex(Graph *graph, long long int id, long long int time_delta); 39 | long long int iindex(Graph *graph, long long int id, long long int time_delta); 40 | -------------------------------------------------------------------------------- /src/graph.c: -------------------------------------------------------------------------------- 1 | /* 2 | cdindex library. 3 | Copyright (C) 2017 Russell J. Funk 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | #include "cdindex.h" 23 | 24 | /** 25 | * \function is_graph_sane 26 | * \brief Run a few basic (not comprehensive) checks on graph data structure. 27 | * 28 | * \param graph The input graph. 29 | * 30 | * \return Whether the graph is sane. 31 | */ 32 | bool is_graph_sane(Graph *graph) { 33 | bool sane = true; 34 | 35 | /* vcount should not be negative */ 36 | if (graph->vcount < 0) { 37 | sane = false; 38 | } 39 | else { 40 | /* vertex ids should be sequential */ 41 | if (graph->vcount > 1) { 42 | for (long long int i = 1; i < graph->vcount; i++) { 43 | if (graph->vs[i-1].id + 1 != graph->vs[i].id) { 44 | sane = false; 45 | } 46 | } 47 | } 48 | /* the last vertex id should correspond to the number of vertices - 1 */ 49 | if (graph->vs[graph->vcount - 1].id != graph->vcount - 1) { 50 | sane = false; 51 | } 52 | } 53 | return sane; 54 | } 55 | 56 | /** 57 | * \function add_vertex 58 | * \brief Add a vertex to a graph (note the graph must have memory allocated). 59 | * 60 | * \param graph The input graph. 61 | * \param id The new vertex id. 62 | * \param timestamp The new vertex timestamp. 63 | */ 64 | void add_vertex(Graph *graph, long long int id, long long int timestamp) { 65 | 66 | /* allocate memory for a vertex */ 67 | Vertex *tmp; 68 | if (graph->vcount == 0) { 69 | tmp = malloc(sizeof(Vertex)); 70 | } 71 | else { 72 | tmp = realloc(graph->vs, (graph->vcount + 1) * sizeof(Vertex)); 73 | } 74 | if (tmp==NULL) { 75 | raise_error(0); 76 | } 77 | else { 78 | graph->vs = tmp; 79 | } 80 | 81 | /* the new vertex id should come at the end of the list */ 82 | if (id != graph->vcount) { 83 | raise_error(1); 84 | } 85 | graph->vs[graph->vcount].id = graph->vcount; 86 | graph->vs[graph->vcount].timestamp = timestamp; 87 | graph->vs[graph->vcount].in_degree = 0; 88 | graph->vs[graph->vcount].out_degree = 0; 89 | graph->vcount++; 90 | } 91 | 92 | /** 93 | * \function add_edge 94 | * \brief Add a edge to a graph (note the graph must have memory allocated). 95 | * 96 | * \param graph The input graph. 97 | * \param source_id The source vertex id. 98 | * \param target_id The target vertex id. 99 | */ 100 | void add_edge(Graph *graph, long long int source_id, long long int target_id) { 101 | 102 | /* confirm vertices are in graph */ 103 | if (source_id >= graph->vcount || target_id >= graph->vcount) { 104 | raise_error(2); 105 | } 106 | 107 | /* confirm vertices are in graph */ 108 | /* 109 | long long int vs_ids[graph->vcount]; 110 | for (long long int i = 0; i < graph->vcount; i++) { 111 | vs_ids[i] = graph->vs[i].id; 112 | } 113 | if (!in_int_array(vs_ids, graph->vcount, source_id) || !in_int_array(vs_ids, graph->vcount, target_id)) { 114 | raise_error(2); 115 | } 116 | */ 117 | 118 | /* confirm edge is not already in graph */ 119 | else if (in_int_array(graph->vs[source_id].out_edges, graph->vs[source_id].out_degree, target_id)) { 120 | raise_error(3); 121 | } 122 | else { 123 | 124 | /* memory reallocation flags */ 125 | bool reallocate_out_edges = true; 126 | bool reallocate_in_edges = true; 127 | 128 | /* allocate memory for source_id out_edge record if needed */ 129 | if (graph->vs[source_id].out_degree == 0) { 130 | graph->vs[source_id].out_edges = malloc(sizeof(long long int)); 131 | reallocate_out_edges = false; 132 | } 133 | 134 | /* allocate memory for target_id in_edge record if needed */ 135 | if (graph->vs[target_id].in_degree == 0) { 136 | graph->vs[target_id].in_edges = malloc(sizeof(long long int)); 137 | reallocate_in_edges = false; 138 | } 139 | 140 | /* check for problems */ 141 | if (graph->vs[target_id].in_edges==NULL || graph->vs[source_id].out_edges==NULL) { 142 | raise_error(0); 143 | } 144 | 145 | /* append the new source_id and target_id */ 146 | add_to_int_array(&graph->vs[source_id].out_edges, graph->vs[source_id].out_degree, target_id, reallocate_out_edges); 147 | add_to_int_array(&graph->vs[target_id].in_edges, graph->vs[target_id].in_degree, source_id, reallocate_in_edges); 148 | 149 | /* increment degree counts */ 150 | graph->vs[source_id].out_degree++; 151 | graph->vs[target_id].in_degree++; 152 | 153 | /* increment graph ecount */ 154 | graph->ecount++; 155 | 156 | } 157 | } 158 | 159 | /** 160 | * \function free_graph 161 | * \brief Free memory taken by a graph. 162 | * 163 | * \param graph The input graph. 164 | */ 165 | void free_graph(Graph *graph) { 166 | for (long long int i = 0; i < graph->vcount; i++) { 167 | if (graph->vs[i].in_degree > 0) free(graph->vs[i].in_edges); 168 | if (graph->vs[i].out_degree > 0) free(graph->vs[i].out_edges); 169 | } 170 | free(graph->vs); 171 | } 172 | -------------------------------------------------------------------------------- /src/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | cdindex library. 3 | Copyright (C) 2017 Russell J. Funk 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | #include "cdindex.h" 23 | 24 | int main() { 25 | 26 | /* initialize graph components */ 27 | int VERTICES = 11; 28 | int EDGES = 13; 29 | 30 | /* dummy data */ 31 | long long int raw_vertices_time[] = {694245600, 32 | 694245600, 33 | 725868000, 34 | 725868000, 35 | 788940000, 36 | 852098400, 37 | 883634400, 38 | 915170400, 39 | 915170400, 40 | 883634400, 41 | 852098400}; 42 | long long int raw_edges[13][2] = {{4,2}, 43 | {4,0}, 44 | {4,1}, 45 | {4,3}, 46 | {5,2}, 47 | {6,2}, 48 | {6,4}, 49 | {7,4}, 50 | {8,4}, 51 | {9,4}, 52 | {9,1}, 53 | {9,3}, 54 | {10,4}}; 55 | 56 | /* create an empty graph */ 57 | CREATE_GRAPH(g); 58 | 59 | /* add vertices to the graph */ 60 | for (int i = 0; i < VERTICES; i++) { 61 | add_vertex(&g, i, raw_vertices_time[i]); 62 | } 63 | 64 | /* add edges to the graph */ 65 | for (int p = 0; p < EDGES; p++) { 66 | add_edge(&g, raw_edges[p][0], raw_edges[p][1]); 67 | } 68 | 69 | /* test and report sanity */ 70 | printf("Testing graph sanity: %s\n", is_graph_sane(&g) ? "PASS" : "FAIL"); 71 | 72 | /* compute cdindex measure */ 73 | printf("CD index: %f\n", cdindex(&g, 4, 157852800)); 74 | 75 | /* compute mcdindex measure */ 76 | printf("mCD index: %f\n", mcdindex(&g, 4, 157852800)); 77 | 78 | /* free memory use by the graph */ 79 | free_graph(&g); 80 | 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /src/utility.c: -------------------------------------------------------------------------------- 1 | /* 2 | cdindex library. 3 | Copyright (C) 2017 Russell J. Funk 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | /** 24 | * \function raise_error 25 | * \brief Raise an error. 26 | * 27 | * \param code The error code. 28 | */ 29 | void raise_error(int code) { 30 | const char *error[4]; 31 | error[0] = "Problem (re)allocating memory"; 32 | error[1] = "Vertex ids must be added sequentially from 0"; 33 | error[2] = "One or more vertices are not in the graph"; 34 | error[3] = "The edge being added is already in the graph"; 35 | 36 | fprintf(stderr, "%s\n", error[code]); 37 | exit(EXIT_FAILURE); 38 | } 39 | 40 | /** 41 | * \function in_int_array 42 | * \brief See if an integer is in an integer array. 43 | * 44 | * \param array The input array. 45 | * \param sizeof_array The size of the input array. 46 | * \param value The value to look for in the input array. 47 | * 48 | * \return Whether value is in the array. 49 | */ 50 | bool in_int_array(long long int *array, long long int sizeof_array, long long int value) { 51 | bool in_array = false; 52 | for (long long int i = 0; i < sizeof_array; i++) { 53 | if (array[i] == value) { 54 | in_array = true; 55 | } 56 | } 57 | return in_array; 58 | } 59 | 60 | /** 61 | * \function add_to_int_array 62 | * \brief Add an integer to an integer array. 63 | * 64 | * \param array The input array. 65 | * \param sizeof_array The size of the input array. 66 | * \param value The value to add to the array. 67 | * \param add_memory Whether to add memory to the array. 68 | */ 69 | void add_to_int_array(long long int **array, long long int sizeof_array, long long int value, bool add_memory) { 70 | long long int *tmp; 71 | if (add_memory) { 72 | tmp = realloc(*array, (sizeof_array + 1) * sizeof(long long int)); 73 | if (tmp==NULL) { 74 | raise_error(0); 75 | } 76 | else { 77 | *array = tmp; 78 | } 79 | } 80 | (*array)[sizeof_array] = value; 81 | } 82 | -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | """tests.py: This script runs simple tests on the cdindex module.""" 5 | 6 | __author__ = "Russell J. Funk" 7 | __copyright__ = "Copyright (C) 2024" 8 | 9 | # built in modules 10 | import datetime 11 | 12 | # custom modules 13 | import cdindex.cdindex 14 | import cdindex._cdindex as _cdindex 15 | 16 | # dummy vertices for c module tests 17 | ctimes = (694224000, 18 | 694224000, 19 | 725846400, 20 | 725846400, 21 | 788918400, 22 | 852098400, 23 | 883612800, 24 | 915148800, 25 | 915148800, 26 | 883612800, 27 | 852076800) 28 | 29 | # dummy edges for c module tests 30 | cedges = ((4,2), 31 | (4,0), 32 | (4,1), 33 | (4,3), 34 | (5,2), 35 | (6,2), 36 | (6,4), 37 | (7,4), 38 | (8,4), 39 | (9,4), 40 | (9,1), 41 | (9,3), 42 | (10,4)) 43 | 44 | # dummy vertices for python module tests 45 | pyvertices= [{"name": "0Z", "time": datetime.datetime(1992, 1, 1)}, 46 | {"name": "1Z", "time": datetime.datetime(1992, 1, 1)}, 47 | {"name": "2Z", "time": datetime.datetime(1993, 1, 1)}, 48 | {"name": "3Z", "time": datetime.datetime(1993, 1, 1)}, 49 | {"name": "4Z", "time": datetime.datetime(1995, 1, 1)}, 50 | {"name": "5Z", "time": datetime.datetime(1997, 1, 1)}, 51 | {"name": "6Z", "time": datetime.datetime(1998, 1, 1)}, 52 | {"name": "7Z", "time": datetime.datetime(1999, 1, 1)}, 53 | {"name": "8Z", "time": datetime.datetime(1999, 1, 1)}, 54 | {"name": "9Z", "time": datetime.datetime(1998, 1, 1)}, 55 | {"name": "10Z", "time": datetime.datetime(1997, 1, 1)}] 56 | 57 | # dummy edges for python module tests 58 | pyedges = [{"source": "4Z", "target": "2Z"}, 59 | {"source": "4Z", "target": "0Z"}, 60 | {"source": "4Z", "target": "1Z"}, 61 | {"source": "4Z", "target": "3Z"}, 62 | {"source": "5Z", "target": "2Z"}, 63 | {"source": "6Z", "target": "2Z"}, 64 | {"source": "6Z", "target": "4Z"}, 65 | {"source": "7Z", "target": "4Z"}, 66 | {"source": "8Z", "target": "4Z"}, 67 | {"source": "9Z", "target": "4Z"}, 68 | {"source": "9Z", "target": "1Z"}, 69 | {"source": "9Z", "target": "3Z"}, 70 | {"source": "10Z", "target": "4Z"}] 71 | 72 | # test time 73 | TEST_TIME = 157852800 74 | TEST_TIME_PY = datetime.timedelta(days=1827) 75 | 76 | # tests for the c extension 77 | def c_tests(): 78 | """Run tests for c extension.""" 79 | 80 | # create graph 81 | graph = _cdindex.Graph() 82 | 83 | # add vertices 84 | for id, time in enumerate(ctimes): 85 | _cdindex.add_vertex(graph, id, time) 86 | 87 | # add edges 88 | for source, target in cedges: 89 | _cdindex.add_edge(graph, source, target) 90 | 91 | # examine the graph 92 | print("Vertices in graph: %s" % (_cdindex.get_vcount(graph))) 93 | print("Edges in graph: %s" % (_cdindex.get_ecount(graph))) 94 | print("Graph sanity: %s" % (_cdindex._is_graph_sane(graph))) 95 | 96 | # examine properties of a vertices 97 | for vertex in _cdindex.get_vertices(graph): 98 | print("%s: %-5s | %s: %-15s %s: %-10s %s: %-10s %s at %s: %-20s %s at %s: %-20s %s: %-20s %s: %-20s" 99 | % ("vertex", vertex, 100 | "timestamp", _cdindex.get_vertex_timestamp(graph, vertex), 101 | "in degree", _cdindex.get_vertex_in_degree(graph, vertex), 102 | "out degree", _cdindex.get_vertex_out_degree(graph, vertex), 103 | "cd index", TEST_TIME, _cdindex.cdindex(graph, vertex, TEST_TIME), 104 | "mcd index", TEST_TIME, _cdindex.mcdindex(graph, vertex, TEST_TIME), 105 | "in edges", _cdindex.get_vertex_in_edges(graph, vertex), 106 | "out edges", _cdindex.get_vertex_out_edges(graph, vertex))) 107 | 108 | # tests for the python module 109 | def py_tests(): 110 | """Run tests for python module.""" 111 | 112 | # create graph 113 | graph = cdindex.Graph() 114 | 115 | # add vertices 116 | for vertex in pyvertices: 117 | graph.add_vertex(vertex["name"], cdindex.timestamp_from_datetime(vertex["time"])) 118 | 119 | # add edges 120 | for edge in pyedges: 121 | graph.add_edge(edge["source"], edge["target"]) 122 | 123 | # examine the graph 124 | print("Vertices in graph: %s" % (graph.vcount())) 125 | print("Edges in graph: %s" % (graph.ecount())) 126 | print("Graph sanity: %s" % (graph._is_graph_sane())) 127 | 128 | # examine properties of a vertices 129 | for vertex in graph.vertices(): 130 | print("%s: %-5s | %s: %-15s %s: %-10s %s: %-10s %s at %s: %-20s %s at %s: %-20s %s: %-35s %s: %-35s" 131 | % ("vertex", vertex, 132 | "timestamp", graph.timestamp(vertex), 133 | "in degree", graph.in_degree(vertex), 134 | "out degree", graph.out_degree(vertex), 135 | "cd index", TEST_TIME_PY, graph.cdindex(vertex, int(TEST_TIME_PY.total_seconds())), 136 | "mcd index", TEST_TIME_PY, graph.mcdindex(vertex, int(TEST_TIME_PY.total_seconds())), 137 | "in edges", graph.in_edges(vertex), 138 | "out edges", graph.out_edges(vertex))) 139 | 140 | def main(): 141 | 142 | # run c tests 143 | c_tests() 144 | 145 | # run python tests 146 | py_tests() 147 | 148 | # generate random graph 149 | g = cdindex.RandomGraph(generations=(2,3,4,5,6,7,7,9), edge_fraction=1) 150 | 151 | # print some information 152 | print(g.ecount()) 153 | print(g.vcount()) 154 | 155 | if __name__ == "__main__": 156 | main() 157 | --------------------------------------------------------------------------------