├── .github └── workflows │ └── wheels.yml ├── COPYING ├── MANIFEST.in ├── PKG-INFO ├── README.rst ├── build-boost-python.sh ├── build-deps.sh ├── example.py ├── setup.cfg ├── setup.py ├── src ├── docstrings.h.in ├── timblapi.cc └── timblapi.h ├── timbl.py └── utils.py /.github/workflows/wheels.yml: -------------------------------------------------------------------------------- 1 | name: Build Wheels 2 | 3 | on: [workflow_dispatch] 4 | 5 | jobs: 6 | build_wheels: 7 | name: Build wheels on for ${{matrix.python.cp}}-${{ matrix.buildplat.sys }} 8 | runs-on: ${{ matrix.buildplat.runs_on }} 9 | strategy: 10 | matrix: 11 | buildplat: 12 | - { runs_on: ubuntu-22.04, sys: manylinux, arch: x86_64, benv: "" } 13 | - { runs_on: macos-14, sys: macosx, arch: arm64, benv: "14.0" } 14 | python: 15 | - { cp: "cp310", rel: "3.10" } 16 | - { cp: "cp311", rel: "3.11" } 17 | - { cp: "cp312", rel: "3.12" } 18 | - { cp: "cp313", rel: "3.13" } 19 | 20 | steps: 21 | - uses: actions/checkout@v4.1.1 22 | 23 | # Used to host cibuildwheel 24 | - uses: actions/setup-python@v5 25 | with: 26 | python-version: 3.12 27 | 28 | - name: Install cibuildwheel 29 | run: python -m pip install cibuildwheel 30 | 31 | - name: Build wheels (Linux glibc) 32 | if: ${{ matrix.buildplat.sys == 'manylinux' }} 33 | run: python -m cibuildwheel --output-dir wheelhouse 34 | env: 35 | CIBW_BUILD: ${{ matrix.python.cp }}-${{ matrix.buildplat.sys }}* 36 | CIBW_ARCHS_LINUX: "x86_64" 37 | CIBW_BEFORE_ALL_LINUX: > 38 | if command -v apt-get; then 39 | apt-get -y git libicu-dev libxml2-dev libxslt1-dev libbz2-dev zlib1g-dev autoconf automake autoconf-archive libtool autotools-dev gcc g++ make libboost-dev 40 | elif command -v yum; then 41 | yum install -y git libicu-devel libxml2-devel libxslt-devel zlib-devel bzip2-devel libtool autoconf-archive autoconf automake m4 wget cmake 42 | fi && 43 | ./build-deps.sh 44 | CIBW_BEFORE_BUILD: ./build-boost-python.sh 45 | CIBW_MANYLINUX_X86_64_IMAGE: quay.io/pypa/manylinux_2_28_x86_64 46 | CIBW_SKIP: "*-win* *-manylinux_i686 pp*" 47 | 48 | - name: Build wheels (Linux musl) 49 | if: ${{ matrix.buildplat.sys == 'musllinux' }} 50 | run: python -m cibuildwheel --output-dir wheelhouse 51 | env: 52 | CIBW_BUILD: ${{ matrix.python.cp }}-${{ matrix.buildplat.sys }}* 53 | CIBW_ARCHS_LINUX: "x86_64" 54 | CIBW_BEFORE_ALL_LINUX: > 55 | apk add build-base git autoconf-archive autoconf automake libtool bzip2-dev icu-dev libxml2-dev boost-dev boost-python3 libtool rsync && 56 | mkdir -p /usr/local/share/aclocal/ && rsync -av --ignore-existing /usr/share/aclocal/*.m4 /usr/local/share/aclocal/ && 57 | ./build-deps.sh 58 | CIBW_MUSLLINUX_X86_64_IMAGE: quay.io/pypa/musllinux_1_1_x86_64 59 | CIBW_MUSLLINUX_AARCH64_IMAGE: quay.io/pypa/musllinux_1_1_aarch64 60 | CIBW_SKIP: "*-win* *-manylinux_i686 pp*" 61 | 62 | - name: Build wheels (macOS) 63 | if: ${{ runner.os == 'macOS' && matrix.python.cp == 'cp313' }} 64 | run: python -m cibuildwheel --output-dir wheelhouse 65 | env: 66 | CIBW_BUILD: ${{ matrix.python.cp }}-${{ matrix.buildplat.sys }}* 67 | CIBW_ARCHS: ${{ matrix.buildplat.arch }} 68 | CIBW_ENVIRONMENT: "MACOSX_DEPLOYMENT_TARGET=${{ matrix.buildplat.benv }}" 69 | CIBW_BEFORE_ALL_MACOS: > 70 | brew install boost boost-python3 && 71 | brew tap fbkarsdorp/homebrew-lamachine && 72 | brew install timbl && 73 | du -ah /opt/homebrew | grep boost_python 74 | 75 | - uses: actions/upload-artifact@v4 76 | if: ${{ ! (runner.os == 'macOS' && matrix.python.cp != 'cp313') }} 77 | with: 78 | name: ${{matrix.python.cp}}-${{matrix.buildplat.sys}}-${{matrix.buildplat.arch}} 79 | path: ./wheelhouse/*.whl 80 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 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 | 635 | Copyright (C) 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 | Copyright (C) 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 | . 675 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst COPYING example.py timbl.py setup.py 2 | recursive-include src *.cc *.h.in timblapi.h 3 | -------------------------------------------------------------------------------- /PKG-INFO: -------------------------------------------------------------------------------- 1 | Metadata-Version: 1.1 2 | Name: python-timbl 3 | Version: 2013.02.11 4 | Summary: Python language binding for the Tilburg Memory-Based Learner 5 | Home-page: http://github.com/proycon/python-timbl 6 | Author: Sander Canisius, Maarten van Gompel 7 | Author-email: proycon@anaproy.nl 8 | License: GPL 9 | Description: UNKNOWN 10 | Platform: UNKNOWN 11 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. image:: https://www.repostatus.org/badges/latest/active.svg 2 | :alt: Project Status: Active – The project has reached a stable, usable state and is being actively developed. 3 | :target: https://www.repostatus.org/#active 4 | 5 | .. image:: https://zenodo.org/badge/8136669.svg 6 | :target: https://zenodo.org/badge/latestdoi/8136669 7 | 8 | ====================== 9 | README: python-timbl 10 | ====================== 11 | 12 | :Authors: Sander Canisius, Maarten van Gompel 13 | :Contact: proycon@anaproy.nl 14 | :Web site: https://github.com/proycon/python-timbl/ 15 | 16 | python-timbl is a Python extension module wrapping the full TiMBL C++ 17 | programming interface. With this module, all functionality exposed 18 | through the C++ interface is also available to Python scripts. Being 19 | able to access the API from Python greatly facilitates prototyping 20 | TiMBL-based applications. 21 | 22 | This is the 2013 release by Maarten van Gompel, building on the 2006 release by Sander Canisius. For those used to the old library, there is one backwards-incompatible change, adapt your scripts to use ``import timblapi`` instead of ``import timbl``, as the latter is now a higher-level interface. 23 | 24 | Since 2020, this only supports Python 3, Python 2 support has been deprecated. 25 | 26 | License 27 | ======= 28 | 29 | python-timbl is free software, distributed under the terms of the GNU `General 30 | Public License`_. Please cite TiMBL in publication of research that uses 31 | TiMBL. 32 | 33 | .. _General Public License: http://www.gnu.org/licenses/gpl.html 34 | 35 | Installation 36 | ============ 37 | 38 | In a Python virtual environment, run: 39 | 40 | ``` 41 | pip install python3-timbl 42 | ``` 43 | 44 | Note that on macOS, wheel packages are currently only available for Python 45 | 3.13, as this the the Python version Homebrew uses in linking libboost-python. 46 | 47 | If no wheels (binary packages) are available for your system, then this will 48 | attempt to compile from source. If that is the case, a number of dependencies 49 | are required: 50 | 51 | python-timbl depends on two external packages, which must have been built 52 | and/or installed on your system in order to successfully build python-timbl. 53 | The first is TiMBL itself; download its tarball from TiMBL's homepage and 54 | follow the installation instructions. The second prerequisite is Boost.Python, a library that facilitates writing 55 | Python extension modules in C++. Many Linux distributions come with prebuilt 56 | packages of Boost.Python. If so, install this package; on Ubuntu/Debian this 57 | can be done as follows. 58 | 59 | $ sudo apt-get install libboost-python libboost-python-dev 60 | 61 | 62 | Usage 63 | ======= 64 | 65 | python-timbl offers two interface to the timbl API. A low-level interface contained in the module ``timblapi``, which is very much like the C++ library, and a high-level object oriented interface in the ``timbl`` module, which offers a ``TimblClassifier`` class. 66 | 67 | timbl.TimblClassifier: High-level interface 68 | ---------------------------------------------- 69 | 70 | The high-level interface features as ``TimblClassifier`` class which can be used for training and testing classifiers. An example is provided in ``example.py``, parts of it will be discussed here. 71 | 72 | After importing the necessary module, the classifier is instantiated by passing it an identifier which will be used as prefix used for all filenames written, and a string containing options just as you would pass them to Timbl:: 73 | 74 | import timbl 75 | classifier = timbl.TimblClassifier("wsd-bank", "-a 0 -k 1" ) 76 | 77 | Normalization of theclass distribution is enabled by default (regardless of the ``-G`` option to Timbl), pass ``normalize=False`` to disable it. 78 | 79 | Training instances can be added using the ``append(featurevector, classlabel)`` method:: 80 | 81 | classifier.append( (1,0,0), 'financial') 82 | classifier.append( (0,1,0), 'furniture') 83 | classifier.append( (0,0,1), 'geographic') 84 | 85 | Subsequently, you invoke the actual training, note that at each step Timbl may output considerable details about what it is doing to standard error output:: 86 | 87 | classifier.train() 88 | 89 | The results of this training is an instance base file, which you can save to file so you can load it again later:: 90 | 91 | classifier.save() 92 | 93 | classifier = timbl.TimblClassifier("wsd-bank", "-a 0 -k 1" ) 94 | classifier.load() 95 | 96 | 97 | 98 | The main advantage of the Python library is the fact that you can classify instances on the fly as follows, just pass a feature vector and optionally also a class label to ``classify(featurevector, classlabel)``:: 99 | 100 | classlabel, distribution, distance = classifier.classify( (1,0,0) ) 101 | 102 | You can also create a test file and test it all at once:: 103 | 104 | classifier = timbl.TimblClassifier("wsd-bank", "-a 0 -k 1" ) 105 | classifier.load() 106 | classifier.addinstance("testfile", (1,0,0),'financial' ) #addinstance can be used to add instances to external files (use append() for training) 107 | classifier.addinstance("testfile", (0,1,0),'furniture' ) 108 | classifier.addinstance("testfile", (0,0,1),'geograpic' ) 109 | classifier.addinstance("testfile", (1,1,0),'geograpic' ) #this one will be wrongly classified as financial & furniture 110 | classifier.test("testfile") 111 | 112 | print "Accuracy: ", classifier.getAccuracy() 113 | 114 | 115 | Real multithreading support 116 | ----------------------------- 117 | 118 | If you are writing a multithreaded Python application (i.e. using the 119 | ``threading`` module) and want to benefit from actual concurrency, 120 | side-stepping Python's Global Interpreter Lock, add the parameter 121 | ``threading=True`` when invoking the ``TimblClassifier`` constructor. Take 122 | care to instantiate ``TimblClassifier`` *before* threading. You can then call 123 | ``TimblClassifier.classify()`` from within your threads. Concurrency only 124 | exists for this ``classify`` method. 125 | 126 | If you do not set this option, everything will still work fine, but you won't benefit 127 | from actual concurrency due to Python's the Global Interpret Lock. 128 | 129 | 130 | timblapi: Low-level interface 131 | ------------------------------- 132 | 133 | For documentation on the low level ``timblapi`` interface you can consult the TiMBL API guide. Although this document actually describes the C++ interface to TiMBL, the latter is similar enough to its Python binding for this document to be a useful reference for python-timbl as well. For most part, the Python TiMBL interface follows the C++ version closely. The differences are listed below. 134 | 135 | **Naming style** 136 | 137 | In the C++ interface, method names are in *UpperCamelCase*; for example, ``Classify``, ``SetOptions``, etc. In contrast, the Python interface uses *lowerCamelCase*: ``classify``, ``setOptions``, etc. 138 | Method overloading TiMBL's ``Classify`` methods use the C++ method overloading feature to provide three different kinds of outputs. Method overloading is non-existant in Python though; therefore, python-timbl has three differently named methods to mirror the functionality of the overloaded Classify method. The mapping is as follows:: 139 | 140 | # bool TimblAPI::Classify(const std::string& Line, 141 | # std::string& result); 142 | # 143 | def TimblAPI.classify(line) -> bool, result 144 | 145 | # 146 | # bool TimblAPI::Classify(const std::string& Line, 147 | # std::string& result, 148 | # double& distance); 149 | # 150 | def TimblAPI.classify2(line) -> bool, string, distance 151 | 152 | # 153 | # bool TimblAPI::Classify(const std::string& Line, 154 | # std::string& result, 155 | # std::string& Distrib, 156 | # double& distance); 157 | # 158 | def TimblAPI.classify3(line, bool normalize=true,int requireddepth=0) -> bool, string, dictionary, distance 159 | 160 | #Thread-safe version of the above, releases and reacquires Python's Global Interprer Lock 161 | def TimblAPI.classify3safe(line, normalize, requireddepth=0) -> bool, string, dictionary, distance 162 | 163 | 164 | Note that the ``classify3`` function returned a string representation of the 165 | distribution in versions of python-timbl prior to 2015.08.12, now it returns an 166 | actual dictionary. When using ``classify3safe`` (the thread-safe version) , 167 | ensure you first call initthreads after instantiating ``timblapi``, and 168 | manually call the ``initthreading()`` method. 169 | 170 | 171 | **Python-only methods** 172 | 173 | Three TiMBL API methods print information to a standard C++ output stream object (ShowBestNeighbors, ShowOptions, ShowSettings, ShowSettings). In the Python interface, these methods will only work with Python (stream) objects that have a fileno method returning a valid file descriptor. Alternatively, three new methods are provided (bestNeighbo(u)rs, options, settings); these methods return the same information as a Python string object. 174 | 175 | 176 | **scikit-learn wrapper** 177 | 178 | A wrapper for use in scikit-learn has been added. It was designed for use in scikit-learn Pipeline objects. The wrapper is not finished and has to date only been tested on sparse data. Note that TiMBL does not work well with large amounts of features. It is suggested to reduce the amount of features to a number below 100 to keep system performance reasonable. Use on servers with large amounts of memory and processing cores advised. 179 | -------------------------------------------------------------------------------- /build-boost-python.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | 4 | # build boost-python from source on AlmaLinux 8 in manylinux_2_28 container (do not use in other contexts) 5 | 6 | set -e 7 | 8 | #var gets set bu cibuildwheel, assign to PYTHON_HOME for boost 9 | export PYTHON_HOME=$Python_ROOT_DIR 10 | 11 | cd /tmp/ 12 | wget -q https://github.com/boostorg/boost/releases/download/boost-1.87.0/boost-1.87.0-cmake.tar.gz 13 | tar -xzf boost-1.87.0-cmake.tar.gz 14 | cd boost-1.87.0 15 | ./bootstrap.sh 16 | ./b2 --clean 17 | ./b2 install --with-python --prefix=/usr 18 | cd $PREVPWD 19 | -------------------------------------------------------------------------------- /build-deps.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # Builds dependencies (latest stable releases) from source 4 | # Used for building wheels. Invoke via 'make wheels' rather 5 | # than directly! 6 | 7 | set -e 8 | 9 | . /etc/os-release 10 | echo "OS: $ID">&2 11 | echo "VERSION: $VERSION_ID">&2 12 | 13 | get_latest_version() { 14 | #Finds the latest git tag or falls back to returning the git default branch (usually master or main) 15 | #Assumes some kind of semantic versioning (possibly with a v prefix) 16 | TAG=$(git tag -l | grep -E "^v?[0-9]+(\.[0-9])*" | sort -t. -k 1.2,1n -k 2,2n -k 3,3n -k 4,4n | tail -n 1) 17 | if [ -z "$TAG" ]; then 18 | echo "No releases found, falling back to default git branch!">&2 19 | #output the git default branch for the repository in the current working dir (usually master or main) 20 | git symbolic-ref refs/remotes/origin/HEAD | sed 's@^refs/remotes/origin/@@' 21 | else 22 | echo "$TAG" 23 | fi 24 | } 25 | 26 | [ -z "$PREFIX" ] && PREFIX="/usr/local/" 27 | if [ "$ID" = "almalinux" ] || [ "$ID" = "centos" ] || [ "$ID" = "rhel" ]; then 28 | if [ -d /usr/local/share/aclocal ]; then 29 | #needed for manylinux_2_28 container which ships custom autoconf, possibly others too? 30 | export ACLOCAL_PATH=/usr/share/aclocal 31 | fi 32 | case $VERSION_ID in 33 | 7*) 34 | if [ -d /opt/rh/devtoolset-10/root/usr/lib ]; then 35 | #we are running in the manylinux2014 image 36 | export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib:/opt/rh/devtoolset-10/root/usr/lib 37 | #libxml2 is out of date, compile and install a new one 38 | yum install -y xz 39 | wget https://download.gnome.org/sources/libxml2/2.9/libxml2-2.9.14.tar.xz 40 | unxz libxml2-2.9.14.tar.xz 41 | tar -xf libxml2-2.9.14.tar 42 | cd libxml2-2.9.14 && ./configure --prefix=$PREFIX --without-python && make && make install 43 | cd .. 44 | fi 45 | ;; 46 | esac 47 | fi 48 | 49 | PWD="$(pwd)" 50 | BUILDDIR="$(mktemp -dt "build-deps.XXXXXX")" 51 | cd "$BUILDDIR" 52 | for PACKAGE in LanguageMachines/ticcutils LanguageMachines/timbl; do 53 | echo "Git cloning $PACKAGE ">&2 54 | git clone https://github.com/$PACKAGE 55 | PACKAGE="$(basename $PACKAGE)" 56 | cd "$PACKAGE" 57 | if [ "$1" != "--devel" ]; then 58 | VERSION="$(get_latest_version)" 59 | if [ "$VERSION" != "master" ] && [ "$VERSION" != "main" ] && [ "$VERSION" != "devel" ]; then 60 | echo "Checking out latest stable version: $VERSION">&2 61 | git -c advice.detachedHead=false checkout "$VERSION" 62 | fi 63 | fi 64 | echo "Bootstrapping $PACKAGE ">&2 65 | if [ ! -f configure ] && [ -f configure.ac ]; then 66 | #shellcheck disable=SC2086 67 | autoreconf --install --verbose 68 | fi 69 | echo "Configuring $PACKAGE" >&2 70 | ./configure --prefix="$PREFIX" >&2 71 | echo "Make $PACKAGE" >&2 72 | make 73 | echo "Make install $PACKAGE" >&2 74 | make install 75 | cd .. 76 | done 77 | cd $PWD 78 | [ -n "$BUILDDIR" ] && rm -Rf "$BUILDDIR" 79 | 80 | echo "Dependencies installed" >&2 81 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf8 -*- 3 | 4 | import timbl 5 | import os 6 | 7 | #We are building a very simple context-aware translator Word Sense Disambiguator for the word "bank", based on the occurrence of some keywords in the same sentence: 8 | 9 | # The features are binary and represent presence or absence of certain keywords. We choose: 10 | # - money 11 | # - sit 12 | # - river 13 | #They have a value of 0 or 1 (but note that Timbl support string features just as well!) 14 | 15 | #The classes we predict are: 16 | # - financial 17 | # - furniture 18 | # - geographic 19 | 20 | #Build the classifier training 21 | classifier = timbl.TimblClassifier("wsd-bank", "-a 0 -k 1" ) #wsd-bank will be the prefix of any files written for timbl 22 | classifier.append( (1,0,0), 'financial') #append is used to add training instances 23 | classifier.append( (0,1,0), 'furniture') 24 | classifier.append( (0,0,1), 'geographic') 25 | 26 | #Train the classifier 27 | classifier.train() 28 | 29 | 30 | #Save 31 | classifier.save() 32 | 33 | #We start anew and load the classifier again (of course we could have just skipped this and the save step and continued immediately) 34 | classifier = timbl.TimblClassifier("wsd-bank", "-a 0 -k 1" ) #wsd-bank will be the prefix of any files written for timbl 35 | classifier.load() #even if this is omitted it will still work, the first classify() call will invoke load() 36 | 37 | #Let's classify an instance: 38 | classlabel, distribution, distance = classifier.classify( (1,0,0) ) 39 | if classlabel == "financial": 40 | print("Classified correctly! Our accuracy is " + str(classifier.getAccuracy())) 41 | 42 | 43 | #Let's classify an ambiguous one: 44 | winningclasslabel, distribution, distance = classifier.classify( (1,1,1) ) 45 | for classlabel, score in distribution.items(): 46 | print(classlabel + ": " + str(score)) 47 | 48 | print("Distance: ", distance) 49 | 50 | 51 | #We again start anew and build a test file 52 | if os.path.exists("testfile"): #delete if it already exists 53 | os.unlink("testfile") 54 | 55 | 56 | 57 | classifier = timbl.TimblClassifier("wsd-bank", "-a 0 -k 1 +v n+di+k" ) #add some extra verbosity flags 58 | classifier.load() 59 | classifier.addinstance("testfile", (1,0,0),'financial' ) #addinstance can be used to add instances to external files (use append() for training) 60 | classifier.addinstance("testfile", (0,1,0),'furniture' ) 61 | classifier.addinstance("testfile", (0,0,1),'geograpic' ) 62 | classifier.addinstance("testfile", (1,1,0),'geograpic' ) #this one will be wrongly classified as financial & furniture 63 | 64 | classifier.test("testfile") 65 | 66 | print("Accuracy: ", classifier.getAccuracy()) 67 | print("Best neighbours: ", classifier.bestNeighbours()) #this only works with the extra verbosity flags and only if python-timbl is compiled with gcc 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [build_ext] 2 | force=1 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python3 2 | 3 | import sys 4 | import os 5 | import shutil 6 | import platform 7 | import glob 8 | 9 | from distutils.core import setup, Extension 10 | from distutils.command.build_ext import build_ext 11 | from distutils.dep_util import newer 12 | from distutils.unixccompiler import UnixCCompiler 13 | 14 | 15 | def updateDocHeader(input, output): 16 | docstrings = {} 17 | exec(compile(open(input, "rb").read(), input, 'exec'), docstrings) 18 | 19 | stream = open(output, "w") 20 | print("#ifndef TIMBL_DOC_H",file=stream) 21 | print("#define TIMBL_DOC_H\n",file=stream) 22 | print("#include \n",file=stream) 23 | 24 | for var in filter(lambda v: v.endswith("_DOC"), docstrings): 25 | print("PyDoc_STRVAR(%s, \"%s\");\n" % (var, str(docstrings[var].strip().encode("unicode_escape"), 'ascii') ), file=stream) 26 | 27 | print("#endif", file=stream) 28 | 29 | stream.close() 30 | 31 | includedirs = [] 32 | libdirs = [] 33 | print(f"system={platform.system()} machine={platform.machine()}", file=sys.stderr) 34 | if platform.system() == "Darwin": 35 | #we are running on Mac OS X (with homebrew hopefully), stuff is in specific locations: 36 | if platform.machine().lower() == "arm64": 37 | print("(macos arm64 detected)", file=sys.stderr) 38 | libdirs.append("/opt/homebrew/lib") 39 | includedirs.append("/opt/homebrew/include") 40 | libdirs.append("/opt/homebrew/icu4c/lib") 41 | includedirs.append("/opt/homebrew/icu4c/include") 42 | libdirs.append("/opt/homebrew/libxml2/lib") 43 | includedirs.append("/opt/homebrew/libxml2/include") 44 | includedirs.append("/opt/homebrew/libxml2/include/libxml2") 45 | libdirs.append("/opt/homebrew/opt/icu4c/lib") 46 | includedirs.append("/opt/homebrew/opt/icu4c/include") 47 | libdirs.append("/opt/homebrew/opt/libxml2/lib") 48 | includedirs.append("/opt/homebrew/opt/libxml2/include") 49 | libdirs.append("/opt/homebrew/opt/boost-python3/lib") 50 | libdirs.append("/opt/homebrew/opt/boost/lib") 51 | includedirs.append("/opt/homebrew/opt/boost/include") 52 | else: 53 | #we are running on Mac OS X with homebrew, stuff is in specific locations: 54 | libdirs.append("/usr/local/opt/icu4c/lib") 55 | includedirs.append("/usr/local/opt/icu4c/include") 56 | libdirs.append("/usr/local/opt/libxml2/lib") 57 | includedirs.append("/usr/local/opt/libxml2/include") 58 | includedirs.append("/usr/local/opt/libxml2/include/libxml2") 59 | libdirs.append("/usr/local/opt/boost-python3/lib") 60 | includedirs.append("/usr/local/opt/boost-python3/lib") 61 | libdirs.append("/usr/local/opt/boost/lib") 62 | includedirs.append("/usr/local/opt/boost/include") 63 | 64 | #add some common default paths 65 | includedirs += ['/usr/include/', '/usr/include/libxml2','/usr/local/include/' ] 66 | libdirs += ['/usr/lib','/usr/local/lib'] 67 | if 'VIRTUAL_ENV' in os.environ: 68 | includedirs.insert(0,os.environ['VIRTUAL_ENV'] + '/include') 69 | libdirs.insert(0,os.environ['VIRTUAL_ENV'] + '/lib') 70 | if 'INCLUDE_DIRS' in os.environ: 71 | includedirs = list(os.environ['INCLUDE_DIRS'].split(':')) + includedirs 72 | if 'LIBRARY_DIRS' in os.environ: 73 | libdirs = list(os.environ['LIBRARY_DIRS'].split(':')) + libdirs 74 | 75 | if platform.system() == "Darwin": 76 | extra_options = ["--stdlib=libc++",'-D U_USING_ICU_NAMESPACE=1'] 77 | else: 78 | extra_options = ['-D U_USING_ICU_NAMESPACE=1'] 79 | 80 | print(f"include_dirs={' '.join(includedirs)} library_dirs={' '.join(libdirs)} extra_options={' '.join(extra_options)}", file=sys.stderr) 81 | 82 | class BuildExt(build_ext): 83 | def initialize_options(self): 84 | build_ext.initialize_options(self) 85 | pyversion = sys.version.split(" ")[0] 86 | pyversion = pyversion.split(".")[0] + pyversion.split(".")[1] #returns something like 312 for 3.12 87 | #Find boost 88 | self.findboost(libdirs, includedirs, pyversion) 89 | 90 | def findboost(self, libsearch, includesearch, pyversion): 91 | self.boost_library_dir = None 92 | self.boost_include_dir = None 93 | self.boostlib = "boost_python" 94 | if os.path.exists('/usr/local/opt/boost-python3'): 95 | #Mac OS X with homebrew 96 | self.boostlib = "boost_python3" 97 | libsearch.insert(0,'/usr/local/opt/boost-python3/lib') 98 | libsearch.insert(0,'/usr/local/opt/boost/lib') 99 | includesearch.insert(0,'/usr/local/opt/boost/include') 100 | if os.path.exists('/opt/homebrew/opt/boost-python3'): 101 | self.boostlib = "boost_python3" 102 | libsearch.insert(0,'/opt/homebrew/opt/boost-python3/lib') 103 | libsearch.insert(0,'/opt/homebrew/opt/boost/lib') 104 | includesearch.insert(0,'/opt/homebrew/opt/boost/include') 105 | if os.path.exists('/opt/homebrew/opt/boost-python' + pyversion): 106 | self.boostlib = "boost_python" + pyversion 107 | libsearch.insert(0,f"/opt/homebrew/opt/boost-python{pyversion}/lib") 108 | libsearch.insert(0,'/opt/homebrew/opt/boost/lib') 109 | includesearch.insert(0,'/opt/homebrew/opt/boost/include') 110 | 111 | for d in libsearch: 112 | if os.path.exists(d + "/libboost_python-py"+pyversion+".so"): 113 | self.boost_library_dir = d 114 | self.boostlib = "boost_python-py" + pyversion 115 | break 116 | elif os.path.exists(d + "/libboost_python"+pyversion+".so"): 117 | self.boost_library_dir = d 118 | self.boostlib = "boost_python" + pyversion 119 | break 120 | elif os.path.exists(d + "/libboost_python3.so"): 121 | self.boost_library_dir = d 122 | self.boostlib = "boost_python3" 123 | break 124 | elif os.path.exists(d + "/libboost_python.so"): 125 | #probably goes wrong if this is for python 2! 126 | self.boost_library_dir = d 127 | self.boostlib = "boost_python" 128 | break 129 | elif os.path.exists(d + "/libboost_python-py" + pyversion + ".dylib"): #Mac OS X 130 | self.boost_library_dir = d 131 | self.boostlib = "boost_python-py" + pyversion 132 | break 133 | elif os.path.exists(d + "/libboost_python" + pyversion + ".dylib"): #Mac OS X 134 | self.boost_library_dir = d 135 | self.boostlib = "boost_python" + pyversion 136 | break 137 | elif os.path.exists(d + "/libboost_python3.dylib"): #Mac OS X 138 | self.boost_library_dir = d 139 | self.boostlib = "boost_python3" 140 | break 141 | elif os.path.exists(d + "/libboost_python.dylib"): #Mac OS X 142 | self.boost_library_dir = d 143 | #probably goes wrong if this is for python 2! 144 | self.boostlib = "boost_python" 145 | break 146 | for d in includesearch: 147 | if os.path.exists(d + "/boost"): 148 | self.boost_include_dir = d 149 | break 150 | 151 | if self.boost_library_dir is not None: 152 | print("Detected boost library in " + self.boost_library_dir + " (" + self.boostlib +")",file=sys.stderr) 153 | else: 154 | print("Unable to find boost library directory automatically. Is libboost-python3 installed?",file=sys.stderr) 155 | self.boost_library_dir = libsearch[0] 156 | if self.boost_include_dir is not None: 157 | print("Detected boost headers in " + self.boost_include_dir ,file=sys.stderr) 158 | else: 159 | print("Unable to find boost headers automatically. Is libboost-python-dev installed?",file=sys.stderr) 160 | self.boost_include_dir = includesearch[0] 161 | 162 | def build_extensions(self): 163 | if newer("src/docstrings.h.in", "src/docstrings.h"): 164 | updateDocHeader("src/docstrings.h.in", "src/docstrings.h") 165 | 166 | for ext in self.extensions: 167 | ext.include_dirs += includedirs 168 | ext.library_dirs += libdirs 169 | 170 | compile_args = ["-std=c++17"] 171 | if platform.system() == "Darwin": 172 | compile_args.append("-stdlib=libc++") 173 | ext.extra_compile_args.extend(compile_args) 174 | ext.libraries.append(self.boostlib) 175 | 176 | build_ext.build_extensions(self) 177 | 178 | 179 | timblModule = Extension("timblapi", ["src/timblapi.cc"], 180 | libraries=["timbl"], 181 | depends=["src/timblapi.h", "src/docstrings.h"]) 182 | 183 | setup( 184 | name="python3-timbl", 185 | version="2025.05.02", 186 | description="Python 3 language binding for the Tilburg Memory-Based Learner", 187 | author="Sander Canisius, Maarten van Gompel", 188 | author_email="S.V.M.Canisius@uvt.nl, proycon@anaproy.nl", 189 | url="http://github.com/proycon/python-timbl", 190 | classifiers=["Development Status :: 4 - Beta","Topic :: Text Processing :: Linguistic","Topic :: Scientific/Engineering","Programming Language :: Python :: 3","Operating System :: POSIX","Intended Audience :: Developers","Intended Audience :: Science/Research","License :: OSI Approved :: GNU General Public License v3 (GPLv3)"], 191 | license="GPL", 192 | py_modules=['timbl'], 193 | ext_modules=[timblModule], 194 | cmdclass={"build_ext": BuildExt}) 195 | -------------------------------------------------------------------------------- /src/docstrings.h.in: -------------------------------------------------------------------------------- 1 | MODULE_DOC = """ 2 | The Tilburg Memory-Based Learner (TiMBL) is an efficient 3 | implementation of several memory-based learning algorithms. In 4 | addition to the TiMBL command-line application, TiMBL's functionality 5 | is also available for programmatic access via a C++ programming 6 | interface, referred to as the TimblAPI. This module implements a 7 | Python language binding to this interface. 8 | 9 | The main entry point for this module is the TimblAPI class. It 10 | provides methods for all standard tasks that can be performed with 11 | TiMBL. The following brief example shows how a TiMBL classifier is 12 | trained, and subsequently applied to an unseen test instance. 13 | 14 | >>> import timbl 15 | >>> mbl = timbl.TimblAPI('-a IB1', '') 16 | >>> mbl.learn('dimin.data') 17 | >>> mbl.classOf('- - - = t j e ?') 18 | (True, 'T') 19 | """ 20 | 21 | 22 | TIMBLAPI_DOC = """ 23 | The TiMBL Application Programming Interface. All functionality exposed 24 | through the TiMBL C++ API can be accessed using methods of this class. 25 | """ 26 | 27 | 28 | INIT_DOC = """ 29 | TimblAPI(options, name) 30 | 31 | Create a TiMBL experiment. The options argument is used to pass 32 | various options to TiMBL in exactly the same way as they would be 33 | written on the command-line. Some (but not all) option settings can 34 | later on be changed using the setOptions method. 35 | 36 | :Parameters: 37 | `options` : str 38 | an option string used to initialise various TiMBL settings 39 | 40 | `name` : str 41 | a descriptive name given to the experiment. This name is printed 42 | with any warning or error messages produced by TiMBL. 43 | """ 44 | 45 | 46 | LEARN_DOC = """ 47 | self.learn(file) 48 | 49 | Train TiMBL on the specified input file. 50 | 51 | :Parameters: 52 | `file` : str 53 | the input file containing the training instances. 54 | 55 | :return: boolean signalling success or failure 56 | :rtype: bool 57 | """ 58 | 59 | 60 | TEST_DOC = """ 61 | self.test(in, out, perc) 62 | 63 | Test the TiMBL model using the given test file. 64 | 65 | :Parameters: 66 | `in` : str 67 | the input file containing the test instances 68 | 69 | `out` : str 70 | the output file to write the output predictions to 71 | 72 | `perc` : str 73 | if not empty (''), the file to write the classification accuracy to 74 | 75 | :return: boolean signalling success or failure 76 | :rtype: bool 77 | """ 78 | 79 | 80 | SETOPTIONS_DOC = """ 81 | self.setOptions(opts) 82 | 83 | Change the value of one or more options. 84 | 85 | Some options can only be set when initialising a TimblAPI 86 | instance. Trying to change the value of those options with this method 87 | will not succeed. 88 | 89 | :Parameters: 90 | `opts` : str 91 | an option string; this string follows the same format as is used 92 | to pass option values to the TiMBL command-line application 93 | 94 | :return: boolean signalling success or failure 95 | :rtype: bool 96 | """ 97 | 98 | 99 | SHOWOPTIONS_DOC = """ 100 | self.showOptions(stream) 101 | 102 | Print all options with their possible and current values to an output 103 | stream. 104 | 105 | :Parameters: 106 | `stream` 107 | a stream object, i.e. any object that has a `fileno` method 108 | whose return value is a valid file descriptor 109 | 110 | :return: boolean signalling success or failure 111 | :rtype: bool 112 | """ 113 | 114 | 115 | SHOWSETTINGS_DOC = """ 116 | self.showSettings(stream) 117 | 118 | Print all options and their current values to an output stream. 119 | 120 | :Parameters: 121 | `stream` 122 | a stream object, i.e. any object that has a `fileno` method 123 | whose return value is a valid file descriptor 124 | 125 | :return: boolean signalling success or failure 126 | :rtype: bool 127 | """ 128 | 129 | SHOWSTATISTICS_DOC = """ 130 | self.showStatistics(stream) 131 | 132 | Print statistics to an output stream 133 | 134 | :return: boolean signalling success or failure 135 | :rtype: bool 136 | """ 137 | 138 | 139 | 140 | WRITEINSTANCEBASE_DOC = """ 141 | self.writeInstanceBase(file) 142 | 143 | Store the current instance base to a file. 144 | 145 | :Parameters: 146 | `file` : str 147 | the output file to write the instance base to 148 | 149 | :return: boolean signalling success or failure 150 | :rtype: bool 151 | """ 152 | 153 | 154 | SAVEWEIGHTS_DOC = """ 155 | self.saveWeights(file) 156 | 157 | Store the current feature weight tables to a file. 158 | 159 | :Parameters: 160 | `file` : str 161 | the output file to write the tables to 162 | 163 | :return: boolean signalling success or failure 164 | :rtype: bool 165 | """ 166 | 167 | 168 | WRITEARRAYS_DOC = """ 169 | self.writeArrays(file) 170 | 171 | Store the current probability arrays to a file. 172 | 173 | :Parameters: 174 | `file` : str 175 | the output file to write the arrays to 176 | 177 | :return: boolean signalling success or failure 178 | :rtype: bool 179 | """ 180 | 181 | 182 | GETINSTANCEBASE_DOC = """ 183 | self.getInstanceBase(file) 184 | 185 | Load an instance base from a file. 186 | 187 | :Parameters: 188 | `file` : str 189 | the input file to load the instance base from 190 | 191 | :return: boolean signalling success or failure 192 | :rtype: bool 193 | """ 194 | 195 | 196 | GETWEIGHTS_DOC = """ 197 | self.getWeights(file, weighting) 198 | 199 | Load the feature weight table for the given weighting scheme from a file. 200 | 201 | :Parameters: 202 | `file` : str 203 | the input file to load the table from 204 | 205 | `weighting` : Weighting 206 | the feature weighting scheme for which to load the table 207 | 208 | :return: boolean signalling success or failure 209 | :rtype: bool 210 | """ 211 | 212 | 213 | GETACCURACY_DOC = """ 214 | self.getAccuracy() 215 | 216 | Return the accuracy after classification 217 | 218 | :return: accuracy value 219 | :rtype: double 220 | """ 221 | 222 | 223 | GETARRAYS_DOC = """ 224 | self.getArrays(file) 225 | 226 | Load probability arrays from a file. 227 | 228 | :Parameters: 229 | `file` : str 230 | the input file to load the arrays from 231 | 232 | :return: boolean signalling success or failure 233 | :rtype: bool 234 | """ 235 | 236 | 237 | CLASSIFY_DOC = """ 238 | self.classify(instance) 239 | 240 | Return the predicted class for a given test instance. 241 | 242 | :Parameters: 243 | `instance` : str 244 | a string representation of the test instance. The format of this 245 | string is the same as used by the TiMBL command-line 246 | application. 247 | 248 | :return: (boolean signalling success or failure, the predicted class) 249 | :rtype: (bool, str) 250 | """ 251 | 252 | 253 | CLASSIFY2_DOC = """ 254 | self.classify2(instance) 255 | 256 | Return the predicted class and the distance of the nearest neighbour 257 | for a given test instance. 258 | 259 | :Parameters: 260 | `instance` : str 261 | a string representation of the test instance. The format of this 262 | string is the same as used by the TiMBL command-line 263 | application. 264 | 265 | :return: (boolean signalling success or failure, the predicted class, 266 | distance of the nearest neighbour) 267 | :rtype: (bool, str, float) 268 | """ 269 | 270 | 271 | CLASSIFY3_DOC = """ 272 | self.classify3(instance,normalize=true,requireddepth=0) 273 | 274 | Return the predicted class, the class distribution, and the distance 275 | of the nearest neighbour for a given test instance. 276 | 277 | :Parameters: 278 | `instance` : str 279 | a string representation of the test instance. The format of this 280 | string is the same as used by the TiMBL command-line 281 | application. 282 | `normalize`: bool 283 | normalize the resulting distribution? (note that the Timbl -G option is ineffective) 284 | `requireddepth`: int 285 | integer indicating the required depth necessary for a distribution to be 286 | returned. Only works with IGTree, it enforces the number of features that 287 | must match, zero (the default) corresponds to a top level distribution, 288 | higher values will result in no distribution being returned if the 289 | required depth is not reached, this improves performance. 290 | 291 | 292 | 293 | :return: (boolean signalling success or failure, the predicted class, 294 | class distribution, distance of the nearest neighbour) 295 | :rtype: (bool, str, dict, float) 296 | """ 297 | 298 | CLASSIFY3SAFE_DOC = """ 299 | self.classify3safe(instance, normalize=true, requireddepth=0) 300 | 301 | Return the predicted class, the class distribution, and the distance 302 | of the nearest neighbour for a given test instance. 303 | 304 | :Parameters: 305 | `instance` : str 306 | a string representation of the test instance. The format of this 307 | string is the same as used by the TiMBL command-line 308 | application. 309 | `normalize`: bool 310 | normalize the resulting distribution?(note that the Timbl -G option is ineffective) 311 | `requireddepth`: int 312 | integer indicating the required depth necessary for a distribution to be 313 | returned. Only works with IGTree, it enforces the number of features that 314 | must match, zero (the default) corresponds to a top level distribution, 315 | higher values will result in no distribution being returned if the 316 | required depth is not reached, this improves performance. 317 | 318 | :return: (boolean signalling success or failure, the predicted class, 319 | class distribution, distance of the nearest neighbour) 320 | :rtype: (bool, str, dict, float) 321 | """ 322 | 323 | SHOWBESTNEIGHBOURS_DOC = """ 324 | self.showBestNeighbours(stream, distr) 325 | 326 | Print the nearest neighbour set for the most-recent classification to 327 | an output stream. 328 | 329 | For this method to work successfully, either the +vn or the +vk 330 | options must have been enabled. The output printed to the output 331 | stream is the same as produced by the TiMBL command-line application 332 | using the same options. 333 | 334 | :Parameters: 335 | `stream` 336 | a stream object, i.e. any object that has a `fileno` method whose 337 | return value is a valid file descriptor 338 | 339 | `distr` : bool 340 | if True, also print distributions 341 | 342 | :return: boolean signalling success or failure 343 | :rtype: bool 344 | """ 345 | 346 | 347 | SHOWBESTNEIGHBORS_DOC = """ 348 | self.showBestNeighbors(stream, distr) 349 | 350 | This is an alias for ``showBestNeighbours``. 351 | """ 352 | 353 | 354 | INCREMENT_DOC = """ 355 | self.increment(instance) 356 | 357 | Add an instance to the instance base. 358 | 359 | :Parameters: 360 | `instance` : str 361 | a string representation of the instance to be added. The format 362 | of this string is the same as used by the TiMBL command-line 363 | application. 364 | 365 | :return: boolean signalling success or failure 366 | :rtype: bool 367 | """ 368 | 369 | 370 | DECREMENT_DOC = """ 371 | self.decrement(instance) 372 | 373 | Remove an instance from the instance base. 374 | 375 | :Parameters: 376 | `instance` : str 377 | a string representation of the instance to be removed. The 378 | format of this string is the same as used by the TiMBL 379 | command-line application. 380 | 381 | :return: boolean signalling success or failure 382 | :rtype: bool 383 | """ 384 | 385 | 386 | EXPAND_DOC = """ 387 | self.expand(file) 388 | 389 | Add all instances in a file to the instance base. 390 | 391 | :Parameters: 392 | `file` : str 393 | the input file to read the instances from 394 | 395 | :return: boolean signalling success or failure 396 | :rtype: bool 397 | """ 398 | 399 | 400 | REMOVE_DOC = """ 401 | self.remove(file) 402 | 403 | Remove all instances in a file from the instance base. 404 | 405 | :Parameters: 406 | `file` : str 407 | the input file to read the instances from 408 | 409 | :return: boolean signalling success or failure 410 | :rtype: bool 411 | """ 412 | 413 | 414 | WRITENAMESFILE_DOC = """ 415 | self.writeNamesFile(file) 416 | 417 | Write a C4.5-style names file. 418 | 419 | :Parameters: 420 | `file` : str 421 | the output file to write 422 | 423 | :return: boolean signalling success or failure 424 | :rtype: bool 425 | """ 426 | 427 | 428 | ALGO_DOC = """ 429 | self.algo() 430 | 431 | Return the current algorithm. 432 | 433 | :return: the current algorithm 434 | :rtype: Algorithm 435 | """ 436 | 437 | 438 | EXPNAME_DOC = """ 439 | self.expName() 440 | 441 | Return the experiment name passed to the constructor of this TimblAPI 442 | instance. 443 | 444 | :return: the name of the current experiment 445 | :rtype: str 446 | """ 447 | 448 | 449 | VERSIONINFO_DOC = """ 450 | self.versionInfo(full) 451 | 452 | Return a string containing the version number, revision, revision 453 | string, and optionally date and time of compilation of this TimblAPI 454 | implementation 455 | 456 | :Parameters: 457 | `full` : bool 458 | if True, include the date and time of compilation in the 459 | returned string 460 | 461 | :return: version info string 462 | :rtype: str 463 | """ 464 | 465 | 466 | 467 | 468 | CURRENTWEIGHTING_DOC = """ 469 | self.currentWeighting() 470 | 471 | Return the current weighting scheme. 472 | 473 | :return: the current weighting scheme 474 | :rtype: Weighting 475 | """ 476 | 477 | 478 | BESTNEIGHBOURS_DOC = """ 479 | self.bestNeighbours(distr) 480 | 481 | Return the output of the showBestNeighbours method as a string. 482 | 483 | :return: the output of the showBestNeighbours method 484 | :rtype: str 485 | """ 486 | 487 | 488 | BESTNEIGHBORS_DOC = """ 489 | self.bestNeighbors(distr) 490 | 491 | This is an alias for ``bestNeighbours``. 492 | """ 493 | 494 | 495 | OPTIONS_DOC = """ 496 | self.options() 497 | 498 | Return the output of the showOptions method as a string. 499 | 500 | :return: the output of the showOptions method 501 | :rtype: str 502 | """ 503 | 504 | ENABLEDEBUG_DOC = """ 505 | self.enableDebug() 506 | 507 | Enable debug 508 | """ 509 | 510 | SETTINGS_DOC = """ 511 | self.settings() 512 | 513 | Return the output of the showSettings method as a string. 514 | 515 | :return: the output of the showSettings method 516 | :rtype: str 517 | """ 518 | 519 | INITTHREADING_DOC = """ 520 | self.initthreading() 521 | 522 | Initialised multi-threading, to be issues *before* doing the threading. Then allows for usage of classify3safe() from with the actual threads. Using the non-thread-safe methods after initthreading will cause segfaults! 523 | """ 524 | 525 | -------------------------------------------------------------------------------- /src/timblapi.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2006-2015 Sander Canisius, Maarten van Gompel 3 | * 4 | * This file is part of python-timbl. 5 | * 6 | * python-timbl is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU General Public License as 8 | * published by the Free Software Foundation; either version 2 of the 9 | * License, or (at your option) any later version. 10 | * 11 | * python-timbl is distributed in the hope that it will be useful, but 12 | * WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | * General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with python-timbl; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 19 | * 02110-1301 USA 20 | * 21 | * Linking python-timbl statically or dynamically with other modules 22 | * is making a combined work based on python-timbl. Thus, the terms 23 | * and conditions of the GNU General Public License cover the whole 24 | * combination. 25 | * 26 | * In addition, as a special exception, the copyright holder of 27 | * python-timbl gives you permission to combine python-timbl with free 28 | * software programs or libraries that are released under the GNU LGPL 29 | * and with code included in the standard release of TiMBL under the 30 | * TiMBL license (or modified versions of such code, with unchanged 31 | * license). You may copy and distribute such a system following the 32 | * terms of the GNU GPL for python-timbl and the licenses of the other 33 | * code concerned, provided that you include the source code of that 34 | * other code when and as the GNU GPL requires distribution of source 35 | * code. 36 | * 37 | * Note that people who make modified versions of python-timbl are not 38 | * obligated to grant this special exception for their modified 39 | * versions; it is their choice whether to do so. The GNU General 40 | * Public License gives permission to release a modified version 41 | * without this exception; this exception also makes it possible to 42 | * release a modified version which carries forward this exception. 43 | * 44 | #*/ 45 | 46 | 47 | #include "timblapi.h" 48 | #include "timbl/GetOptClass.h" 49 | #include "timbl/Instance.h" 50 | #include "docstrings.h" 51 | 52 | #include 53 | #include 54 | 55 | #include 56 | #include 57 | #include 58 | #include 59 | 60 | #ifndef __clang__ 61 | #include 62 | #endif 63 | 64 | #include 65 | #include 66 | 67 | using namespace boost::python; 68 | 69 | 70 | tuple TimblApiWrapper::classify(const std::string& line) 71 | { 72 | std::string cls; 73 | bool result = Classify(line, cls); 74 | return boost::python::make_tuple(result, cls); 75 | } 76 | 77 | 78 | tuple TimblApiWrapper::classify2(const std::string& line) 79 | { 80 | std::string cls; 81 | double distance; 82 | bool result = Classify(line, cls, distance); 83 | return boost::python::make_tuple(result, cls, distance); 84 | } 85 | 86 | 87 | tuple TimblApiWrapper::classify3(const std::string& line, bool normalize, const unsigned char requireddepth) 88 | { 89 | std::string cls; 90 | double distance; 91 | const Timbl::ClassDistribution * distrib; 92 | const Timbl::TargetValue * result = Classify(line, distrib , distance); 93 | if (result != NULL) { 94 | if ((requireddepth > 0) && (matchDepth() < requireddepth)) { 95 | return boost::python::make_tuple(true, "", python::dict(), 999999); 96 | } else { 97 | const std::string cls = result->Name(); 98 | return boost::python::make_tuple(true, cls, dist2dict(distrib, normalize), distance); 99 | } 100 | } else { 101 | return boost::python::make_tuple(false,"",python::dict(),999999); 102 | } 103 | } 104 | 105 | 106 | Timbl::TimblExperiment * TimblApiWrapper::getexperimentforthread() { 107 | pthread_t thisthread = pthread_self(); 108 | Timbl::TimblExperiment * clonedexp = NULL; 109 | pthread_mutex_lock(&lock); 110 | for (std::vector >::const_iterator iter = experimentpool.begin(); iter != experimentpool.end(); iter++) { 111 | if (iter->first == thisthread) { 112 | if (debug) std::cerr << "(Experiment in pool for thread " << (size_t) thisthread << ", runningthreads=" << runningthreads << ")" << std::endl; 113 | clonedexp = iter->second; 114 | break; 115 | } 116 | } 117 | pthread_mutex_unlock(&lock); 118 | 119 | if (clonedexp == NULL) { 120 | clonedexp = detachedexp->clone(); 121 | if (debug) std::cerr << "(Creating new experiment in pool for thread " << (size_t) thisthread << ", clonedexp=" << (size_t) clonedexp << ", experimentpool=" << (size_t) &experimentpool << ", runningthreads=" << runningthreads << ")" << std::endl; 122 | *clonedexp = *detachedexp; //ugly but needed 123 | if ( detachedexp->getOptParams() ){ 124 | clonedexp->setOptParams( detachedexp->getOptParams()->Clone(0) ); 125 | } 126 | if (clonedexp == NULL) { 127 | std::cerr << "(FATAL ERROR clonedexp=NULL)" << std::endl; 128 | } else { 129 | pthread_mutex_lock(&lock); 130 | experimentpool.push_back(std::pair(thisthread,clonedexp)); 131 | pthread_mutex_unlock(&lock); 132 | } 133 | if (debug) std::cerr << "(Experimentpool size = " << experimentpool.size() << ")" << std::endl; 134 | } 135 | return clonedexp; 136 | } 137 | 138 | tuple TimblApiWrapper::classify3safe(const std::string& line, bool normalize,const unsigned char requireddepth) 139 | { 140 | runningthreads++; 141 | PyThreadState * m_thread_state = PyEval_SaveThread(); //release GIL 142 | 143 | Timbl::TimblExperiment * clonedexp = getexperimentforthread(); 144 | 145 | const Timbl::ClassDistribution * distrib; 146 | double distance; 147 | const auto line_unicode = TiCC::toUnicodeString(line); 148 | const Timbl::TargetValue * result = clonedexp->Classify(line_unicode, distrib,distance); 149 | if (result != NULL) { 150 | if ((requireddepth > 0) && (clonedexp->matchDepth() < requireddepth)) { 151 | PyEval_RestoreThread(m_thread_state); 152 | m_thread_state = NULL; 153 | runningthreads--; 154 | return boost::python::make_tuple(true, "", python::dict(), 999999); 155 | } else { 156 | const std::string cls = result->Name(); 157 | //const std::string diststring = distrib->DistToString(); 158 | PyEval_RestoreThread(m_thread_state); 159 | m_thread_state = NULL; 160 | runningthreads--; 161 | return boost::python::make_tuple(true, cls, dist2dict(distrib, normalize), distance); 162 | } 163 | } else { 164 | PyEval_RestoreThread(m_thread_state); 165 | m_thread_state = NULL; 166 | runningthreads--; 167 | return boost::python::make_tuple(false,"",python::dict(),999999); 168 | } 169 | } 170 | 171 | std::string TimblApiWrapper::bestNeighbours() 172 | { 173 | std::ostringstream buf; 174 | ShowBestNeighbors(buf); 175 | return buf.str(); 176 | } 177 | 178 | 179 | bool TimblApiWrapper::showBestNeighbours(object& stream) 180 | { 181 | #ifdef __clang__ 182 | std::cerr << "showBestNeighbours is not implemented for clang" << std::endl; 183 | return false; 184 | #else 185 | int fd = extract(stream.attr("fileno")()); 186 | __gnu_cxx::stdio_filebuf fdbuf(dup(fd), std::ios::out); 187 | std::ostream out(&fdbuf); 188 | return ShowBestNeighbors(out); 189 | #endif 190 | } 191 | 192 | 193 | std::string TimblApiWrapper::options() 194 | { 195 | std::ostringstream buf; 196 | ShowOptions(buf); 197 | return buf.str(); 198 | } 199 | 200 | 201 | bool TimblApiWrapper::showOptions(object& stream) 202 | { 203 | #ifdef __clang__ 204 | std::cerr << "showOptions is not implemented for clang" << std::endl; 205 | return false; 206 | #else 207 | int fd = extract(stream.attr("fileno")()); 208 | __gnu_cxx::stdio_filebuf fdbuf(dup(fd), std::ios::out); 209 | std::ostream out(&fdbuf); 210 | return ShowOptions(out); 211 | #endif 212 | } 213 | 214 | 215 | std::string TimblApiWrapper::settings() 216 | { 217 | std::ostringstream buf; 218 | ShowSettings(buf); 219 | return buf.str(); 220 | } 221 | 222 | 223 | void TimblApiWrapper::initthreading() { 224 | initExperiment(); 225 | detachedexp = grabAndDisconnectExp(); 226 | } 227 | 228 | 229 | bool TimblApiWrapper::showSettings(object& stream) 230 | { 231 | #ifdef __clang__ 232 | std::cerr << "showSettings is not implemented for clang" << std::endl; 233 | return false; 234 | #else 235 | int fd = extract(stream.attr("fileno")()); 236 | __gnu_cxx::stdio_filebuf fdbuf(dup(fd), std::ios::out); 237 | std::ostream out(&fdbuf); 238 | return ShowSettings(out); 239 | #endif 240 | } 241 | 242 | 243 | python::dict TimblApiWrapper::dist2dict(const Timbl::ClassDistribution * distribution, bool normalize, double minf) const { 244 | python::dict result; 245 | 246 | double freq; 247 | double sum = 0.0; 248 | if (normalize) { 249 | for (Timbl::ClassDistribution::VDlist::const_iterator it = distribution->begin(); it != distribution->end(); it++) { 250 | sum += it->second->Weight(); 251 | } 252 | } 253 | for (Timbl::ClassDistribution::VDlist::const_iterator it = distribution->begin(); it != distribution->end(); it++) { 254 | if (normalize) { 255 | it->second->SetWeight(it->second->Weight() / sum); 256 | } 257 | freq = it->second->Weight(); 258 | if ( freq >= minf ){ 259 | result[it->second->Value()->Name()] = freq; 260 | } 261 | } 262 | 263 | return result; 264 | } 265 | 266 | /*std::string TimblApiWrapper::weights() 267 | { 268 | std::ostringstream buf; 269 | ShowWeights(buf); 270 | return buf.str(); 271 | } 272 | 273 | 274 | bool TimblApiWrapper::showWeights(object& stream) 275 | { 276 | int fd = extract(stream.attr("fileno")()); 277 | #if __GLIBCXX__ < 20040419 278 | __gnu_cxx::stdio_filebuf fdbuf(fd, std::ios::out, false, 279 | static_cast< size_t >(BUFSIZ)); 280 | #else 281 | __gnu_cxx::stdio_filebuf fdbuf(dup(fd), std::ios::out); 282 | #endif 283 | std::ostream out(&fdbuf); 284 | return ShowWeights(out); 285 | }*/ 286 | 287 | 288 | BOOST_PYTHON_MODULE(timblapi) 289 | { 290 | scope().attr("__doc__") = MODULE_DOC; 291 | 292 | class_("TimblAPI", 293 | TIMBLAPI_DOC, 294 | init(INIT_DOC)) 296 | .def("learn", &TimblApiWrapper::Learn, LEARN_DOC) 297 | .def("test", &TimblApiWrapper::Test, TEST_DOC) 298 | 299 | .def("setOptions", &TimblApiWrapper::SetOptions, SETOPTIONS_DOC) 300 | .def("showOptions", &TimblApiWrapper::showOptions, SHOWOPTIONS_DOC) 301 | .def("showSettings", &TimblApiWrapper::showSettings, SHOWSETTINGS_DOC) 302 | .def("showStatistics", &TimblApiWrapper::ShowStatistics, SHOWSTATISTICS_DOC) 303 | 304 | .def("writeInstanceBase", &TimblApiWrapper::WriteInstanceBase, 305 | WRITEINSTANCEBASE_DOC) 306 | .def("getInstanceBase", &TimblApiWrapper::GetInstanceBase, 307 | GETINSTANCEBASE_DOC) 308 | 309 | .def("saveWeights", &TimblApiWrapper::SaveWeights, SAVEWEIGHTS_DOC) 310 | .def("getWeights", &TimblApiWrapper::GetWeights, GETWEIGHTS_DOC) 311 | 312 | .def("getAccuracy", &TimblApiWrapper::GetAccuracy, GETACCURACY_DOC) 313 | 314 | .def("writeArrays", &TimblApiWrapper::WriteArrays, WRITEARRAYS_DOC) 315 | .def("getArrays", &TimblApiWrapper::GetArrays, GETARRAYS_DOC) 316 | 317 | .def("classify", &TimblApiWrapper::classify, CLASSIFY_DOC) 318 | .def("classify2", &TimblApiWrapper::classify2, CLASSIFY2_DOC) 319 | .def("classify3", &TimblApiWrapper::classify3, CLASSIFY3_DOC) 320 | .def("classify3safe", &TimblApiWrapper::classify3safe, CLASSIFY3SAFE_DOC) 321 | 322 | .def("initthreading", &TimblApiWrapper::initthreading, INITTHREADING_DOC) 323 | .def("enableDebug", &TimblApiWrapper::enableDebug, ENABLEDEBUG_DOC) 324 | 325 | .def("showBestNeighbours", &TimblApiWrapper::showBestNeighbours, 326 | SHOWBESTNEIGHBOURS_DOC) 327 | .def("showBestNeighbors", &TimblApiWrapper::showBestNeighbours, 328 | SHOWBESTNEIGHBORS_DOC) 329 | 330 | 331 | .def("increment", &TimblApiWrapper::Increment, INCREMENT_DOC) 332 | .def("decrement", &TimblApiWrapper::Decrement, DECREMENT_DOC) 333 | .def("expand", &TimblApiWrapper::Expand, EXPAND_DOC) 334 | .def("remove", &TimblApiWrapper::Remove, REMOVE_DOC) 335 | 336 | .def("writeNamesFile", &TimblApiWrapper::WriteNamesFile, 337 | WRITENAMESFILE_DOC) 338 | .def("algo", &TimblApiWrapper::Algo, ALGO_DOC) 339 | .def("expName", &TimblApiWrapper::ExpName, EXPNAME_DOC) 340 | .def("versionInfo", &TimblApiWrapper::VersionInfo, VERSIONINFO_DOC) 341 | .staticmethod("versionInfo") 342 | .def("currentWeighting", &TimblApiWrapper::CurrentWeighting, 343 | CURRENTWEIGHTING_DOC) 344 | .def("valid", &TimblApiWrapper::Valid) 345 | //.def("showWeights", &TimblApiWrapper::showWeights) 346 | 347 | // EXTRA METHODS 348 | .def("bestNeighbours", &TimblApiWrapper::bestNeighbours, 349 | BESTNEIGHBOURS_DOC) 350 | .def("bestNeighbors", &TimblApiWrapper::bestNeighbours, 351 | BESTNEIGHBORS_DOC) 352 | .def("options", &TimblApiWrapper::options, OPTIONS_DOC) 353 | .def("settings", &TimblApiWrapper::settings, SETTINGS_DOC) 354 | //.def("weights", &TimblApiWrapper::weights) 355 | ; 356 | 357 | enum_("Algorithm") 358 | .value("UNKNOWN_ALG", Timbl::UNKNOWN_ALG) 359 | .value("IB1", Timbl::IB1) 360 | .value("IB2", Timbl::IB2) 361 | .value("IGTREE", Timbl::IGTREE) 362 | .value("TRIBL", Timbl::TRIBL) 363 | .value("TRIBL2", Timbl::TRIBL2) 364 | .value("LOO", Timbl::LOO) 365 | .value("CV", Timbl::CV) 366 | ; 367 | 368 | enum_("Weighting") 369 | .value("UNKNOWN_W", Timbl::UNKNOWN_W) 370 | .value("UD", Timbl::UD) 371 | .value("NW", Timbl::NW) 372 | .value("GR", Timbl::GR) 373 | .value("IG", Timbl::IG) 374 | .value("X2", Timbl::X2) 375 | .value("SV", Timbl::SV) 376 | ; 377 | 378 | //def("to_string", to_string); 379 | } 380 | 381 | 382 | 383 | -------------------------------------------------------------------------------- /src/timblapi.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2006 Sander Canisius 3 | * 4 | * This file is part of python-timbl. 5 | * 6 | * python-timbl is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU General Public License as 8 | * published by the Free Software Foundation; either version 2 of the 9 | * License, or (at your option) any later version. 10 | * 11 | * python-timbl is distributed in the hope that it will be useful, but 12 | * WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | * General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with python-timbl; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 19 | * 02110-1301 USA 20 | * 21 | * Linking python-timbl statically or dynamically with other modules 22 | * is making a combined work based on python-timbl. Thus, the terms 23 | * and conditions of the GNU General Public License cover the whole 24 | * combination. 25 | * 26 | * In addition, as a special exception, the copyright holder of 27 | * python-timbl gives you permission to combine python-timbl with free 28 | * software programs or libraries that are released under the GNU LGPL 29 | * and with code included in the standard release of TiMBL under the 30 | * TiMBL license (or modified versions of such code, with unchanged 31 | * license). You may copy and distribute such a system following the 32 | * terms of the GNU GPL for python-timbl and the licenses of the other 33 | * code concerned, provided that you include the source code of that 34 | * other code when and as the GNU GPL requires distribution of source 35 | * code. 36 | * 37 | * Note that people who make modified versions of python-timbl are not 38 | * obligated to grant this special exception for their modified 39 | * versions; it is their choice whether to do so. The GNU General 40 | * Public License gives permission to release a modified version 41 | * without this exception; this exception also makes it possible to 42 | * release a modified version which carries forward this exception. 43 | * 44 | */ 45 | 46 | #ifndef TIMBL_H 47 | #define TIMBL_H 48 | 49 | #include "Python.h" 50 | 51 | #include 52 | 53 | #include 54 | #include 55 | #include 56 | #include 57 | #include 58 | #include 59 | 60 | namespace python = boost::python; 61 | 62 | 63 | class TimblApiWrapper : public Timbl::TimblAPI { 64 | private: 65 | std::vector > experimentpool; 66 | Timbl::TimblExperiment * detachedexp; 67 | python::dict dist2dict(const Timbl::ClassDistribution * dist, bool=true,double=0) const; 68 | pthread_mutex_t lock; //global lock 69 | bool debug; 70 | int runningthreads; 71 | public: 72 | TimblApiWrapper(const std::string& args, const std::string& name="") : Timbl::TimblAPI(args, name) { 73 | detachedexp = NULL; 74 | debug = false; 75 | runningthreads = 0; 76 | pthread_mutex_init(&lock, NULL); 77 | } 78 | ~TimblApiWrapper() { 79 | if (debug) std::cerr << "TimblApiWrapper Destructor" << std::endl; 80 | if (runningthreads == 0) { 81 | if (detachedexp != NULL) delete detachedexp; 82 | for (std::vector >::iterator iter = experimentpool.begin(); iter != experimentpool.end(); iter++) { 83 | delete iter->second; 84 | } 85 | } 86 | } 87 | 88 | 89 | 90 | void initthreading(); 91 | void enableDebug() { debug = true; }; 92 | Timbl::TimblExperiment * getexperimentforthread(); 93 | 94 | python::tuple classify(const std::string& line); 95 | python::tuple classify2(const std::string& line); 96 | python::tuple classify3(const std::string& line, bool normalize=true,const unsigned char requireddepth=0); 97 | python::tuple classify3safe(const std::string& line, bool normalize=true,const unsigned char requireddepth=0); 98 | 99 | std::string bestNeighbours(); 100 | bool showBestNeighbours(python::object& stream); 101 | 102 | std::string options(); 103 | bool showOptions(python::object& stream); 104 | 105 | std::string settings(); 106 | bool showSettings(python::object& stream); 107 | 108 | std::string weights(); 109 | bool showWeights(python::object& stream); 110 | 111 | }; 112 | 113 | #endif 114 | -------------------------------------------------------------------------------- /timbl.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf8 -*- 3 | 4 | # Object oriented Python interface wrapping the Timbl API 5 | # by Maarten van Gompel 6 | # Radboud University Nijmegen 7 | 8 | # Licensed under GPL 9 | 10 | from __future__ import print_function 11 | from __future__ import unicode_literals 12 | from __future__ import division 13 | from __future__ import absolute_import 14 | 15 | import sys 16 | from tempfile import mktemp 17 | import timblapi 18 | import io 19 | import os 20 | 21 | stderr = sys.stderr 22 | stdout = sys.stdout 23 | 24 | 25 | class LoadException(Exception): 26 | pass 27 | 28 | class ClassifyException(Exception): 29 | pass 30 | 31 | 32 | def u(s, encoding = 'utf-8', errors='strict'): 33 | #will work on byte arrays 34 | if isinstance(s, str): 35 | return s 36 | else: 37 | return str(s,encoding,errors=errors) 38 | 39 | 40 | class TimblClassifier(object): 41 | def __init__(self, fileprefix, timbloptions, format = "Tabbed", dist=True, encoding = 'utf-8', overwrite = True, flushthreshold=10000, threading=False, normalize=True, debug=False, sklearn=False, flushdir=None): 42 | if format.lower() == "tabbed": 43 | self.format = "Tabbed" 44 | self.delimiter = "\t" 45 | elif format.lower() == "columns": 46 | self.format = "Columns" 47 | self.delimiter = " " 48 | elif format.lower() == 'sparse': # for sparse arrays, e.g. scipy.sparse.csr 49 | self.format = "Sparse" 50 | self.delimiter = "" 51 | else: 52 | raise ValueError("Only Tabbed, Columns, and Sparse are supported input format for the python wrapper, not " + format) 53 | 54 | self.timbloptions = timbloptions 55 | self.fileprefix = fileprefix 56 | 57 | self.encoding = encoding 58 | self.dist = dist 59 | 60 | self.normalize= normalize 61 | 62 | self.flushthreshold = flushthreshold 63 | self.instances = [] 64 | self.api = None 65 | self.debug = debug 66 | self.sklearn = sklearn 67 | 68 | if sklearn: 69 | import scipy as sp 70 | self.flushfile = mktemp(prefix=self.fileprefix, dir=flushdir) 71 | self.flushed = 0 72 | else: 73 | if os.path.exists(self.fileprefix + ".train") and overwrite: 74 | self.flushed = 0 75 | else: 76 | self.flushed = 1 77 | 78 | self.threading = threading 79 | 80 | def validatefeatures(self,features): 81 | """Returns features in validated form, or raises an Exception. Mostly for internal use""" 82 | validatedfeatures = [] 83 | for feature in features: 84 | if isinstance(feature, int) or isinstance(feature, float): 85 | validatedfeatures.append( str(feature) ) 86 | elif self.delimiter in feature and not self.sklearn: 87 | raise ValueError("Feature contains delimiter: " + feature) 88 | elif self.sklearn and isinstance(feature, str): #then is sparse added together 89 | validatedfeatures.append(feature) 90 | else: 91 | validatedfeatures.append(feature) 92 | return validatedfeatures 93 | 94 | def append(self, features, classlabel): 95 | if not isinstance(features, list) and not isinstance(features, tuple): 96 | raise ValueError("Expected list or tuple of features") 97 | 98 | features = self.validatefeatures(features) 99 | 100 | if self.delimiter in classlabel and self.delimiter != '': 101 | raise ValueError("Class label contains delimiter: " + self.delimiter) 102 | 103 | self.instances.append(self.delimiter.join(features) + (self.delimiter if not self.delimiter == '' else ' ') + classlabel) 104 | if len(self.instances) >= self.flushthreshold: 105 | self.flush() 106 | 107 | def flush(self): 108 | if self.debug: print("Flushing...",file=sys.stderr) 109 | if len(self.instances) == 0: return False 110 | 111 | if hasattr(self, 'flushfile'): 112 | f = io.open(self.flushfile,'w', encoding=self.encoding) 113 | else: 114 | if self.flushed: 115 | f = io.open(self.fileprefix + ".train",'a', encoding=self.encoding) 116 | else: 117 | f = io.open(self.fileprefix + ".train",'w', encoding=self.encoding) 118 | 119 | for instance in self.instances: 120 | f.write(instance + "\n") 121 | 122 | self.flushed += len(self.instances) 123 | f.close() 124 | self.instances = [] 125 | return True 126 | 127 | def __delete__(self): 128 | self.flush() 129 | 130 | def train(self, save=False): 131 | self.flush() 132 | 133 | if hasattr(self, 'flushfile'): 134 | if not os.path.exists(self.flushfile): 135 | raise LoadException("Training file '"+self.flushfile+"' not found. Did you forget to add instances with append()?") 136 | else: 137 | filepath = self.flushfile 138 | else: 139 | if not os.path.exists(self.fileprefix + ".train"): 140 | raise LoadException("Training file '"+self.fileprefix+".train' not found. Did you forget to add instances with append()?") 141 | else: 142 | filepath = self.fileprefix + '.train' 143 | 144 | options = "-F " + self.format + " " + self.timbloptions 145 | if self.dist: 146 | options += " +v+db +v+di" 147 | print("Calling Timbl API for training: " + options, file=stderr) 148 | self.api = timblapi.TimblAPI(options,"") 149 | if self.debug: 150 | print("Enabling debug for timblapi",file=stderr) 151 | self.api.enableDebug() 152 | 153 | trainfile = filepath 154 | self.api.learn(trainfile) 155 | if save: 156 | self.save() 157 | if self.threading: 158 | self.api.initthreading() 159 | 160 | def save(self): 161 | if not self.api: 162 | raise Exception("No API instantiated, did you train the classifier first?") 163 | self.api.writeInstanceBase(self.fileprefix + ".ibase") 164 | self.api.saveWeights(self.fileprefix + ".wgt") 165 | 166 | def classify(self, features, allowtopdistribution=True): 167 | 168 | features = self.validatefeatures(features) 169 | 170 | if not self.api: 171 | self.load() 172 | 173 | testinstance = self.delimiter.join(features) + (self.delimiter if not self.delimiter == '' else ' ') + "?" 174 | if self.dist: 175 | if self.threading: 176 | result, cls, distribution, distance = self.api.classify3safe(testinstance, self.normalize, int(not allowtopdistribution)) 177 | else: 178 | result, cls, distribution, distance = self.api.classify3(testinstance, self.normalize, int(not allowtopdistribution)) 179 | if result: 180 | cls = u(cls) 181 | return (cls, distribution, distance) 182 | #distribution = u(distribution) 183 | #if cls: 184 | # return (cls, self._parsedistribution(distribution.split(' ')), distance) 185 | #else: 186 | # return (cls, {}, distance) 187 | else: 188 | raise ClassifyException("Failed to classify: " + u(testinstance)) 189 | else: 190 | result, cls = self.api.classify(testinstance) 191 | if result: 192 | cls = u(cls) 193 | return cls 194 | else: 195 | raise ClassifyException("Failed to classify: " + u(testinstance)) 196 | 197 | def getAccuracy(self): 198 | if not self.api: 199 | raise Exception("No API instantiated, did you train and test the classifier first?") 200 | return self.api.getAccuracy() 201 | 202 | def load(self): 203 | if not os.path.exists(self.fileprefix + ".ibase"): 204 | raise LoadException("Instance base '"+self.fileprefix+".ibase' not found, did you train and save the classifier first?") 205 | 206 | options = "-F " + self.format + " " + self.timbloptions 207 | self.api = timblapi.TimblAPI(options, "") 208 | if self.debug: 209 | print("Enabling debug for timblapi",file=stderr) 210 | self.api.enableDebug() 211 | print("Calling Timbl API : " + options,file=stderr) 212 | self.api.getInstanceBase(self.fileprefix + '.ibase') 213 | #if os.path.exists(self.fileprefix + ".wgt"): 214 | # self.api.getWeights(self.fileprefix + '.wgt') 215 | if self.threading: 216 | if self.debug: print("Invoking initthreading()",file=sys.stderr) 217 | self.api.initthreading() 218 | 219 | def addinstance(self, testfile, features, classlabel="?"): 220 | """Adds an instance to a specific file. Especially suitable for generating test files""" 221 | 222 | features = self.validatefeatures(features) 223 | 224 | if self.delimiter in classlabel: 225 | raise ValueError("Class label contains delimiter: " + self.delimiter) 226 | 227 | 228 | f = io.open(testfile,'a', encoding=self.encoding) 229 | f.write(self.delimiter.join(features) + self.delimiter + classlabel + "\n") 230 | f.close() 231 | 232 | def test(self, testfile): 233 | """Test on an existing testfile and return the accuracy""" 234 | if not self.api: 235 | self.load() 236 | self.api.test(u(testfile), u(self.fileprefix + '.out'),'') 237 | return self.api.getAccuracy() 238 | 239 | 240 | def crossvalidate(self, foldsfile): 241 | """Train & Test using cross validation, testfile is a file that contains the filenames of all the folds!""" 242 | options = "-F " + self.format + " " + self.timbloptions + " -t cross_validate" 243 | print("Instantiating Timbl API : " + options,file=stderr) 244 | self.api = timblapi.TimblAPI(options, "") 245 | if self.debug: 246 | print("Enabling debug for timblapi",file=stderr) 247 | self.api.enableDebug() 248 | print("Calling Timbl Test : " + options,file=stderr) 249 | self.api.test(u(foldsfile),'','') 250 | a = self.api.getAccuracy() 251 | del self.api 252 | return a 253 | 254 | 255 | 256 | def leaveoneout(self): 257 | """Train & Test using leave one out""" 258 | traintestfile = self.fileprefix + '.train' 259 | options = "-F " + self.format + " " + self.timbloptions + " -t leave_one_out" 260 | self.api = timblapi.TimblAPI(options, "") 261 | if self.debug: 262 | print("Enabling debug for timblapi",file=stderr) 263 | self.api.enableDebug() 264 | print("Calling Timbl API : " + options,file=stderr) 265 | self.api.learn(u(traintestfile)) 266 | self.api.test(u(traintestfile), u(self.fileprefix + '.out'),'') 267 | return self.api.getAccuracy() 268 | 269 | def readtestoutput(self): 270 | if not os.path.exists(self.fileprefix + ".out"): 271 | raise LoadException("No test output available, expected '" + self.fileprefix + ".out' . Run test() first") 272 | f = io.open(self.fileprefix + '.out', 'r', encoding=self.encoding) 273 | for line in f: 274 | endfvec = None 275 | line = line.strip() 276 | if line and line[0] != '#': #ignore empty lines and comments 277 | segments = [ x for i, x in enumerate(line.split(' ')) ] 278 | #segments = [ x for x in line.split() if x != "^" and not (len(x) == 3 and x[0:2] == "n=") ] #obtain segments, and filter null fields and "n=?" feature (in fixed-feature configuration) 279 | if not endfvec: 280 | try: 281 | # Modified by Ruben. There are some cases where one of the features is a {, and then 282 | # the module is not able to obtain the distribution of scores and senses 283 | # We have to look for the last { in the vector, and due to there is no rindex method 284 | # we obtain the reverse and then apply index. 285 | aux=list(reversed(segments)).index("{") 286 | endfvec=len(segments)-aux-1 287 | #endfvec = segments.index("{") 288 | except ValueError: 289 | endfvec = None 290 | 291 | if endfvec > 2: #only for +v+db 292 | try: 293 | enddistr = segments.index('}',endfvec) 294 | except ValueError: 295 | raise 296 | distribution = self._parsedistribution(segments, endfvec, enddistr) 297 | if len(segments) > enddistr + 1: 298 | distance = float(segments[-1]) 299 | else: 300 | distance = None 301 | else: 302 | endfvec = len(segments) 303 | distribution = None 304 | distance = None 305 | 306 | #features, referenceclass, predictedclass, distribution, distance 307 | yield " ".join(segments[:endfvec - 2]).split(self.delimiter), segments[endfvec - 2], segments[endfvec - 1], distribution, distance 308 | f.close() 309 | 310 | def bestNeighbours(self): 311 | return self.api.bestNeighbours() 312 | 313 | def bestNeighbors(self): 314 | return self.api.bestNeighbours() 315 | 316 | def settings(self): 317 | return self.api.settings() 318 | 319 | def options(self): 320 | return self.api.options() 321 | 322 | def _parsedistribution(self, instance, start=0, end =None): 323 | dist = {} 324 | i = start + 1 325 | 326 | if not end: 327 | end = len(instance) - 1 328 | 329 | while i < end: #instance[i] != "}": 330 | label = instance[i] 331 | if self.format == "Tabbed": label = label.replace('\\_',' ') 332 | try: 333 | score = float(instance[i+1].rstrip(",")) 334 | dist[label] = score 335 | except: 336 | print("ERROR: timbl._parsedistribution -- Could not fetch score for class '" + label + "', expected float, but found '"+instance[i+1].rstrip(",")+"'. Instance= " + " ".join(instance)+ ".. Attempting to compensate...",file=stderr) 337 | i = i - 1 338 | i += 2 339 | 340 | if not dist: 341 | print("ERROR: timbl._parsedistribution -- Did not find class distribution for ", instance, file=stderr) 342 | 343 | return dist 344 | 345 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | from sklearn.base import BaseEstimator, ClassifierMixin 2 | from sklearn.utils import check_X_y, check_array 3 | from timbl import TimblClassifier 4 | import scipy as sp 5 | import numpy as np 6 | 7 | class skTiMBL(BaseEstimator, ClassifierMixin): 8 | def __init__(self, prefix='timbl', algorithm=4, dist_metric=None, 9 | k=1, normalize=False, debug=0, flushdir=None): 10 | self.prefix = prefix 11 | self.algorithm = algorithm 12 | self.dist_metric = dist_metric 13 | self.k = k 14 | self.normalize = normalize 15 | self.debug = debug 16 | self.flushdir = flushdir 17 | 18 | 19 | def _make_timbl_options(self, *options): 20 | """ 21 | -a algorithm 22 | -m metric 23 | -w weighting 24 | -k amount of neighbours 25 | -d class voting weights 26 | -L frequency threshold 27 | -T which feature index is label 28 | -N max number of features 29 | -H turn hashing on/off 30 | 31 | This function still has to be made, for now the appropriate arguments 32 | can be passed in fit() 33 | """ 34 | pass 35 | 36 | 37 | def fit(self, X, y): 38 | X, y = check_X_y(X, y, dtype=np.int64, accept_sparse='csr') 39 | 40 | n_rows = X.shape[0] 41 | self.classes_ = np.unique(y) 42 | 43 | if sp.sparse.issparse(X): 44 | if self.debug: print('Features are sparse, choosing faster learning') 45 | 46 | self.classifier = TimblClassifier(self.prefix, "-a{} -k{} -N{} -vf".format(self.algorithm,self.k, X.shape[1]), 47 | format='Sparse', debug=True, sklearn=True, flushdir=self.flushdir, 48 | flushthreshold=20000, normalize=self.normalize) 49 | 50 | for i in range(n_rows): 51 | sparse = ['({},{})'.format(i+1, c) for i,c in zip(X[i].indices, X[i].data)] 52 | self.classifier.append(sparse,str(y[i])) 53 | 54 | else: 55 | 56 | self.classifier = TimblClassifier(self.prefix, "-a{} -k{} -N{} -vf".format(self.algorithm, self.k, X.shape[1]), 57 | debug=True, sklearn=True, flushdir=self.flushdir, flushthreshold=20000, 58 | normalize=self.normalize) 59 | 60 | if y.dtype != 'O': 61 | y = y.astype(str) 62 | 63 | for i in range(n_rows): 64 | self.classifier.append(list(X[i].toarray()[0]), y[i]) 65 | 66 | self.classifier.train() 67 | return self 68 | 69 | 70 | def _timbl_predictions(self, X, part_index, y=None): 71 | choices = {0 : lambda x : x.append(np.int64(label)), 72 | 1 : lambda x : x.append([np.float(distance)]), 73 | } 74 | X = check_array(X, dtype=np.float64, accept_sparse='csr') 75 | 76 | n_samples = X.shape[0] 77 | 78 | pred = [] 79 | func = choices[part_index] 80 | if sp.sparse.issparse(X): 81 | if self.debug: print('Features are sparse, choosing faster predictions') 82 | 83 | for i in range(n_samples): 84 | sparse = ['({},{})'.format(i+1, c) for i,c in zip(X[i].indices, X[i].data)] 85 | label,proba, distance = self.classifier.classify(sparse) 86 | func(pred) 87 | 88 | else: 89 | for i in range(n_samples): 90 | label,proba, distance = self.classifier.classify(list(X[i].toarray()[0])) 91 | func(pred) 92 | 93 | return np.array(pred) 94 | 95 | 96 | 97 | def predict(self, X, y=None): 98 | return self._timbl_predictions(X, part_index=0) 99 | 100 | 101 | def predict_proba(self, X, y=None): 102 | """ 103 | TIMBL is a discrete classifier. It cannot give probability estimations. 104 | To ensure that scikit-learn functions with TIMBL (and especially metrics 105 | such as ROC_AUC), this method is implemented. 106 | 107 | For ROC_AUC, the classifier corresponds to a single point in ROC space, 108 | instead of a probabilistic continuum such as classifiers that can give 109 | a probability estimation (e.g. Linear classifiers). For an explanation, 110 | see Fawcett (2005). 111 | """ 112 | return predict(X) 113 | 114 | 115 | def decision_function(self, X, y=None): 116 | """ 117 | The decision function is interpreted here as being the distance between 118 | the instance that is being classified and the nearest point in k space. 119 | """ 120 | return self._timbl_predictions(X, part_index=1) 121 | 122 | 123 | --------------------------------------------------------------------------------