├── LICENSE ├── README.md ├── environment.yml ├── models ├── LundNet3 │ ├── TopTagging │ │ ├── Top_QCD_500GeV_LundNet3_INFO.txt │ │ ├── Top_QCD_500GeV_LundNet3_ROC_data.pickle │ │ └── Top_QCD_500GeV_LundNet3_state.pt │ └── WTagging │ │ ├── W_QCD_500GeV_LundNet3_INFO.txt │ │ ├── W_QCD_500GeV_LundNet3_ROC_data.pickle │ │ └── W_QCD_500GeV_LundNet3_state.pt └── LundNet5 │ ├── TopTagging │ ├── Top_QCD_500GeV_LundNet5_INFO.txt │ ├── Top_QCD_500GeV_LundNet5_ROC_data.pickle │ └── Top_QCD_500GeV_LundNet5_state.pt │ └── WTagging │ ├── W_QCD_500GeV_LundNet5_INFO.txt │ ├── W_QCD_500GeV_LundNet5_ROC_data.pickle │ └── W_QCD_500GeV_LundNet5_state.pt ├── requirements.txt ├── sample_QCD_500GeV.json.gz ├── sample_WW_500GeV.json.gz ├── setup.py └── src └── lundnet ├── EdgeConv.py ├── JetTree.py ├── LundNet.py ├── ParticleNet.py ├── dgl_dataset.py ├── dgl_utils.py ├── read_data.py └── scripts └── lundnet.py /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.4443146.svg)](https://doi.org/10.5281/zenodo.4443146) 2 | 3 | LundNet 4 | ======= 5 | 6 | This repository contains the code and results presented in 7 | [arXiv:2012.08526](https://arxiv.org/abs/2012.08526 "LundNet paper"). 8 | 9 | ## About 10 | 11 | LundNet is a jet tagging framework to train graph-based jet tagging strategies. 12 | 13 | ## Install LundNet 14 | 15 | LundNet is tested and supported on 64-bit systems running Linux. 16 | 17 | Install LundNet with Python's pip package manager: 18 | ``` 19 | git clone https://github.com/fdreyer/lundnet.git 20 | cd lundnet 21 | pip install -e . 22 | ``` 23 | To install the package in a specific location, use 24 | the "--target=PREFIX_PATH" flag. 25 | 26 | This process will copy the `lundnet` program to your environment python path. 27 | 28 | We recommend the installation of the LundNet package using a `miniconda3` 29 | environment with the 30 | [configuration specified here](https://github.com/fdreyer/LundNet/blob/master/environment.yml). 31 | 32 | LundNet requires the following python 3 packages: 33 | - torch 34 | - dgl 35 | - numpy 36 | - [fastjet](http://fastjet.fr/) (compiled with --enable-pyext) 37 | - pandas 38 | - json 39 | - gzip 40 | - argparse 41 | - tqdm 42 | - networkx 43 | - uproot_methods 44 | - scipy 45 | - sklearn 46 | 47 | ## Pre-trained models 48 | 49 | The final models presented in 50 | [arXiv:2012.08526](https://arxiv.org/abs/2012.08526 "LundNet paper") 51 | are stored in: 52 | - models/LundNet3: contains the LundNet-3 models for each benchmark. 53 | - models/LundNet5: contains the LundNet-5 models for each benchmark. 54 | 55 | ## Input data 56 | 57 | All data used for the final models can be downloaded from the git-lfs repository 58 | at https://github.com/JetsGame/data. 59 | 60 | ## Running the code 61 | 62 | To launch a test of the code, use 63 | ``` 64 | lundnet --demo --save test --device cpu --num-epochs 1 65 | ``` 66 | 67 | This will run the LundNet code on a sample of 5000 signal and background events and train a model on the CPU for one epoch, saving the results in a new test/ directory. 68 | 69 | To train a full model, you can type: 70 | ``` 71 | lundnet --model lundnet5 --train-sig TRAIN_SIG --train-bkg TRAIN_BKG 72 | --val-sig VAL_SIG --val-bkg VAL_BKG --test-sig TEST_SIG --test-bkg TEST_BKG 73 | --save OUTPUT 74 | ``` 75 | where the first six filenames are the locations of the signal and background training, validation and testing samples, and the model is saved to an OUTPUT folder. 76 | 77 | To apply an existing LundNet model to a new data set, you can use 78 | ``` 79 | lundnet --model lundnet5 --load PATH/TO/model_state.pt --test-sig TEST_SIG --test-bkg TEST_BKG --test-output OUTPUT 80 | ``` 81 | which loads the model given as input, before applying it to the TEST_SIG and TEST_BKG samples, with the results then saved to OUTPUT.pickle 82 | 83 | To find more options on how to run full models, use 84 | ``` 85 | lundnet --help 86 | ``` 87 | 88 | ## References 89 | 90 | * F. A. Dreyer and H. Qu, "Jet tagging in the Lund plane with graph networks," 91 | [arXiv:2012.08526](https://arxiv.org/abs/2012.08526 "LundNet paper") 92 | -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | name: torch_gpu 2 | channels: 3 | - defaults 4 | dependencies: 5 | - _libgcc_mutex=0.1=main 6 | - _pytorch_select=0.2=gpu_0 7 | - blas=1.0=mkl 8 | - brotlipy=0.7.0=py37h27cfd23_1003 9 | - ca-certificates=2020.12.8=h06a4308_0 10 | - certifi=2020.12.5=py37h06a4308_0 11 | - cffi=1.14.4=py37h261ae71_0 12 | - chardet=4.0.0=py37h06a4308_1003 13 | - cryptography=3.3.1=py37h3c74f83_0 14 | - cudatoolkit=10.1.243=h6bb024c_0 15 | - cudnn=7.6.5=cuda10.1_0 16 | - decorator=4.4.2=py_0 17 | - idna=2.10=py_0 18 | - intel-openmp=2020.2=254 19 | - joblib=1.0.0=pyhd3eb1b0_0 20 | - ld_impl_linux-64=2.33.1=h53a641e_7 21 | - libedit=3.1.20191231=h14c3975_1 22 | - libffi=3.3=he6710b0_2 23 | - libgcc-ng=9.1.0=hdf63c60_0 24 | - libgfortran-ng=7.3.0=hdf63c60_0 25 | - libstdcxx-ng=9.1.0=hdf63c60_0 26 | - mkl=2020.2=256 27 | - mkl-service=2.3.0=py37he8ac12f_0 28 | - mkl_fft=1.2.0=py37h23d657b_0 29 | - mkl_random=1.1.1=py37h0573a6f_0 30 | - ncurses=6.2=he6710b0_1 31 | - networkx=2.5=py_0 32 | - ninja=1.10.2=py37hff7bd54_0 33 | - numpy=1.19.2=py37h54aff64_0 34 | - numpy-base=1.19.2=py37hfa32c7d_0 35 | - openssl=1.1.1i=h27cfd23_0 36 | - pandas=1.1.5=py37ha9443f7_0 37 | - pip=20.3.3=py37h06a4308_0 38 | - pycparser=2.20=py_2 39 | - pyopenssl=20.0.1=pyhd3eb1b0_1 40 | - pysocks=1.7.1=py37_1 41 | - python=3.7.9=h7579374_0 42 | - python-dateutil=2.8.1=py_0 43 | - pytorch=1.4.0=cuda101py37h02f0884_0 44 | - pytz=2020.4=pyhd3eb1b0_0 45 | - readline=8.0=h7b6447c_0 46 | - requests=2.25.1=pyhd3eb1b0_0 47 | - scipy=1.5.2=py37h0b6359f_0 48 | - setuptools=51.0.0=py37h06a4308_2 49 | - six=1.15.0=py37h06a4308_0 50 | - sqlite=3.33.0=h62c20be_0 51 | - tk=8.6.10=hbc83047_0 52 | - tqdm=4.54.1=pyhd3eb1b0_0 53 | - urllib3=1.26.2=pyhd3eb1b0_0 54 | - wheel=0.36.2=pyhd3eb1b0_0 55 | - xz=5.2.5=h7b6447c_0 56 | - zlib=1.2.11=h7b6447c_3 57 | - pip: 58 | - awkward==0.14.0 59 | - dgl-cu101==0.5.3 60 | - scikit-learn==0.24.0 61 | - uproot==4.0.0 62 | - uproot-methods==0.9.2 63 | prefix: /users/dreyer/local/miniconda3/envs/torch_gpu_recent 64 | -------------------------------------------------------------------------------- /models/LundNet3/TopTagging/Top_QCD_500GeV_LundNet3_INFO.txt: -------------------------------------------------------------------------------- 1 | model_name: tree-lund-net 2 | model_params: {'conv_params': [[32, 32], [32, 32], [64, 64], [64, 64], [128, 128], [128, 128]], 'fc_params': [(256, 0.1)]} 3 | data_format: lund3 4 | lund_dimension: 3 5 | lund_ln_kt_min: None 6 | lund_ln_delta_min: None 7 | rsd-groom: None 8 | remove-secondary: False 9 | date: 2020-05-26 10 | model_path: saved_models/TreeLundNet/TopTagging/Lund_dim3_z-delta-kt/Top_QCD_500GeV_Lund_dim3_z-delta-kt_TreeLundNet 11 | test_sig: data/test/test_Top_500GeV.json.gz 12 | test_bkg: data/test/test_QCD_500GeV.json.gz 13 | train_sig: data/train/Top_500GeV.json.gz 14 | train_bkg: data/train/QCD_500GeV.json.gz 15 | accuracy: 0.9444 16 | auc: 0.982137023 17 | inv_bkg_at_sig_50: 1785.7142857142699 18 | inv_bkg_at_sig_30: 16666.666666680838 19 | -------------------------------------------------------------------------------- /models/LundNet3/TopTagging/Top_QCD_500GeV_LundNet3_ROC_data.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdreyer/LundNet/f705e597006e83e07c4608116d0ca1806fbed0c8/models/LundNet3/TopTagging/Top_QCD_500GeV_LundNet3_ROC_data.pickle -------------------------------------------------------------------------------- /models/LundNet3/TopTagging/Top_QCD_500GeV_LundNet3_state.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdreyer/LundNet/f705e597006e83e07c4608116d0ca1806fbed0c8/models/LundNet3/TopTagging/Top_QCD_500GeV_LundNet3_state.pt -------------------------------------------------------------------------------- /models/LundNet3/WTagging/W_QCD_500GeV_LundNet3_INFO.txt: -------------------------------------------------------------------------------- 1 | model_name: tree-lund-net 2 | model_params: {'conv_params': [[32, 32], [32, 32], [64, 64], [64, 64], [128, 128], [128, 128]], 'fc_params': [(256, 0.1)]} 3 | data_format: lund3 4 | lund_dimension: 3 5 | lund_ln_kt_min: None 6 | lund_ln_delta_min: None 7 | rsd-groom: None 8 | remove-secondary: False 9 | date: 2020-05-26 10 | model_path: saved_models/TreeLundNet/WTagging/Lund_dim3_z-delta-kt/W_QCD_500GeV_Lund_dim3_z-delta-kt_TreeLundNet 11 | test_sig: data/test/test_WW_500GeV.json.gz 12 | test_bkg: data/test/test_QCD_500GeV.json.gz 13 | train_sig: data/train/WW_500GeV.json.gz 14 | train_bkg: data/train/QCD_500GeV.json.gz 15 | accuracy: 0.87001 16 | auc: 0.9347001016 17 | inv_bkg_at_sig_50: 499.99999999999955 18 | inv_bkg_at_sig_30: 2941.176470588175 19 | -------------------------------------------------------------------------------- /models/LundNet3/WTagging/W_QCD_500GeV_LundNet3_ROC_data.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdreyer/LundNet/f705e597006e83e07c4608116d0ca1806fbed0c8/models/LundNet3/WTagging/W_QCD_500GeV_LundNet3_ROC_data.pickle -------------------------------------------------------------------------------- /models/LundNet3/WTagging/W_QCD_500GeV_LundNet3_state.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdreyer/LundNet/f705e597006e83e07c4608116d0ca1806fbed0c8/models/LundNet3/WTagging/W_QCD_500GeV_LundNet3_state.pt -------------------------------------------------------------------------------- /models/LundNet5/TopTagging/Top_QCD_500GeV_LundNet5_INFO.txt: -------------------------------------------------------------------------------- 1 | model_name: tree-lund-net 2 | model_params: {'conv_params': [[32, 32], [32, 32], [64, 64], [64, 64], [128, 128], [128, 128]], 'fc_params': [(256, 0.1)]} 3 | data_format: lund 4 | lund_dimension: 5 5 | lund_ln_kt_min: None 6 | lund_ln_delta_min: None 7 | rsd-groom: None 8 | remove-secondary: False 9 | date: 2020-12-08 10 | model_path: saved_models/TreeLundNet/TopTagging/Lund_dim5/Top_QCD_500GeV_Lund_dim5_TreeLundNet 11 | test_sig: data/test/test_Top_500GeV.json.gz 12 | test_bkg: data/test/test_QCD_500GeV.json.gz 13 | train_sig: data/train/Top_500GeV.json.gz 14 | train_bkg: data/train/QCD_500GeV.json.gz 15 | accuracy: 0.95994 16 | auc: 0.9867899704 17 | inv_bkg_at_sig_50: 5000.00000000055 18 | inv_bkg_at_sig_30: 49999.99999994999 19 | -------------------------------------------------------------------------------- /models/LundNet5/TopTagging/Top_QCD_500GeV_LundNet5_ROC_data.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdreyer/LundNet/f705e597006e83e07c4608116d0ca1806fbed0c8/models/LundNet5/TopTagging/Top_QCD_500GeV_LundNet5_ROC_data.pickle -------------------------------------------------------------------------------- /models/LundNet5/TopTagging/Top_QCD_500GeV_LundNet5_state.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdreyer/LundNet/f705e597006e83e07c4608116d0ca1806fbed0c8/models/LundNet5/TopTagging/Top_QCD_500GeV_LundNet5_state.pt -------------------------------------------------------------------------------- /models/LundNet5/WTagging/W_QCD_500GeV_LundNet5_INFO.txt: -------------------------------------------------------------------------------- 1 | model_name: tree-lund-net 2 | model_params: {'conv_params': [[32, 32], [32, 32], [64, 64], [64, 64], [128, 128], [128, 128]], 'fc_params': [(256, 0.1)]} 3 | data_format: lund 4 | lund_dimension: 5 5 | lund_ln_kt_min: None 6 | lund_ln_delta_min: None 7 | rsd-groom: None 8 | remove-secondary: False 9 | date: 2020-12-09 10 | model_path: saved_models/TreeLundNet/WTagging/Lund_dim5/W_QCD_500GeV_Lund_dim5_TreeLundNet 11 | test_sig: data/test/test_WW_500GeV.json.gz 12 | test_bkg: data/test/test_QCD_500GeV.json.gz 13 | train_sig: data/train/WW_500GeV.json.gz 14 | train_bkg: data/train/QCD_500GeV.json.gz 15 | accuracy: 0.87232 16 | auc: 0.9384987083999999 17 | inv_bkg_at_sig_50: 609.7560975609849 18 | inv_bkg_at_sig_30: 5000.00000000055 19 | -------------------------------------------------------------------------------- /models/LundNet5/WTagging/W_QCD_500GeV_LundNet5_ROC_data.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdreyer/LundNet/f705e597006e83e07c4608116d0ca1806fbed0c8/models/LundNet5/WTagging/W_QCD_500GeV_LundNet5_ROC_data.pickle -------------------------------------------------------------------------------- /models/LundNet5/WTagging/W_QCD_500GeV_LundNet5_state.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdreyer/LundNet/f705e597006e83e07c4608116d0ca1806fbed0c8/models/LundNet5/WTagging/W_QCD_500GeV_LundNet5_state.pt -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | hyperopt==0.1.1 2 | setuptools==40.6.2 3 | gym==0.10.9 4 | matplotlib==3.0.1 5 | Keras==2.2.4 6 | numpy==1.15.4 7 | rl==2.4 8 | fastjet==0.0.3 9 | hfile==1.0.8 10 | -------------------------------------------------------------------------------- /sample_QCD_500GeV.json.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdreyer/LundNet/f705e597006e83e07c4608116d0ca1806fbed0c8/sample_QCD_500GeV.json.gz -------------------------------------------------------------------------------- /sample_WW_500GeV.json.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdreyer/LundNet/f705e597006e83e07c4608116d0ca1806fbed0c8/sample_WW_500GeV.json.gz -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # This file is part of LundNet by F. Dreyer and H. Qu 2 | 3 | from __future__ import print_function 4 | import sys 5 | from setuptools import setup, find_packages 6 | 7 | if sys.version_info < (3,6): 8 | print("LundNet requires Python 3.6 or later", file=sys.stderr) 9 | sys.exit(1) 10 | 11 | with open('README.md') as f: 12 | long_desc = f.read() 13 | 14 | setup(name= "lundnet", 15 | version = '1.0.0', 16 | description = "A jet tagging algorithm based on graph networks", 17 | author = "F. Dreyer, H. Qu", 18 | author_email = "frederic.dreyer@cern.ch, huilin.qu@cern.ch", 19 | url="https://github.com/fdreyer/lundnet", 20 | long_description = long_desc, 21 | entry_points = {'console_scripts': 22 | ['lundnet = lundnet.scripts.lundnet:main']}, 23 | package_dir = {'': 'src'}, 24 | packages = find_packages('src'), 25 | zip_safe = False, 26 | classifiers=[ 27 | 'Operating System :: Unix', 28 | 'Programming Language :: Python', 29 | 'Programming Language :: Python :: 3', 30 | 'Programming Language :: Python :: 3.5', 31 | 'Topic :: Scientific/Engineering', 32 | 'Topic :: Scientific/Engineering :: Physics', 33 | ], 34 | ) 35 | 36 | -------------------------------------------------------------------------------- /src/lundnet/EdgeConv.py: -------------------------------------------------------------------------------- 1 | # This file is part of LundNet by F. Dreyer and H. Qu 2 | 3 | from __future__ import print_function 4 | 5 | import dgl.function as fn 6 | import torch.nn as nn 7 | 8 | 9 | class EdgeConvBlock(nn.Module): 10 | r"""EdgeConv layer. 11 | Introduced in "Dynamic Graph CNN for Learning on Point Clouds" (https://arxiv.org/pdf/1801.07829). 12 | Code adapted from https://github.com/dmlc/dgl/blob/master/python/dgl/nn/pytorch/conv/edgeconv.py. 13 | """ 14 | 15 | def __init__(self, in_feat, out_feats, batch_norm=True, activation=True): 16 | super(EdgeConvBlock, self).__init__() 17 | self.batch_norm = batch_norm 18 | self.activation = activation 19 | self.num_layers = len(out_feats) 20 | 21 | out_feat = out_feats[0] 22 | self.theta = nn.Linear(in_feat, out_feat, bias=False if self.batch_norm else True) 23 | self.phi = nn.Linear(in_feat, out_feat, bias=False if self.batch_norm else True) 24 | self.fcs = nn.ModuleList() 25 | for i in range(1, self.num_layers): 26 | self.fcs.append(nn.Linear(out_feats[i - 1], out_feats[i], bias=False if self.batch_norm else True)) 27 | 28 | if batch_norm: 29 | self.bns = nn.ModuleList() 30 | for i in range(self.num_layers): 31 | self.bns.append(nn.BatchNorm1d(out_feats[i])) 32 | 33 | if activation: 34 | self.acts = nn.ModuleList() 35 | for i in range(self.num_layers): 36 | self.acts.append(nn.ReLU()) 37 | 38 | if in_feat == out_feats[-1]: 39 | self.sc = None 40 | else: 41 | self.sc = nn.Linear(in_feat, out_feats[-1], bias=False if self.batch_norm else True) 42 | self.sc_bn = nn.BatchNorm1d(out_feats[-1]) 43 | 44 | if activation: 45 | self.sc_act = nn.ReLU() 46 | 47 | def message(self, edges): 48 | theta_x = self.theta(edges.dst['x'] - edges.src['x']) 49 | phi_x = self.phi(edges.src['x']) 50 | return {'e': theta_x + phi_x} 51 | 52 | def forward(self, g, h): 53 | with g.local_scope(): 54 | g.ndata['x'] = h 55 | # generate the message and store it on the edges 56 | g.apply_edges(self.message) 57 | # process the message 58 | e = g.edata['e'] 59 | for i in range(self.num_layers): 60 | if i > 0: 61 | e = self.fcs[i - 1](e) 62 | if self.batch_norm: 63 | e = self.bns[i](e) 64 | if self.activation: 65 | e = self.acts[i](e) 66 | g.edata['e'] = e 67 | # pass the message and update the nodes 68 | g.update_all(fn.copy_e('e', 'e'), fn.mean('e', 'x')) 69 | # shortcut connection 70 | x = g.ndata.pop('x') 71 | g.edata.pop('e') 72 | if self.sc is None: 73 | sc = h 74 | else: 75 | sc = self.sc(h) 76 | if self.batch_norm: 77 | sc = self.sc_bn(sc) 78 | if self.activation: 79 | return self.sc_act(x + sc) 80 | else: 81 | return x + sc 82 | -------------------------------------------------------------------------------- /src/lundnet/JetTree.py: -------------------------------------------------------------------------------- 1 | # This file is part of LundNet by F. Dreyer and H. Qu 2 | 3 | import fastjet as fj 4 | import numpy as np 5 | import math 6 | 7 | # ====================================================================== 8 | 9 | 10 | class LundCoordinates: 11 | """ 12 | LundCoordinates takes two subjets associated with a declustering, 13 | and store the corresponding Lund coordinates. 14 | """ 15 | 16 | # components of the LundCoordinates 17 | components = ['lnz', 'lnDelta', 'psi', 'lnm', 'lnKt'] 18 | 19 | # number of dimensions for the state() method 20 | dimension = 5 21 | 22 | # ---------------------------------------------------------------------- 23 | def __init__(self, j1, j2): 24 | """Define a number of variables associated with the declustering.""" 25 | delta = np.float32(max(1e-6, j1.delta_R(j2))) 26 | z = np.float32(j2.pt() / (j1.pt() + j2.pt())) 27 | self.lnm = np.float32(0.5 * math.log(abs((j1 + j2).m2()))) 28 | self.lnKt = np.float32(math.log(j2.pt() * delta)) 29 | self.lnz = np.float32(math.log(z)) 30 | self.lnDelta = np.float32(math.log(delta)) 31 | self.lnKappa = np.float32(math.log(z * delta)) 32 | try: 33 | self.psi = np.float32(math.atan((j1.rap() - j2.rap()) / (j1.phi() - j2.phi()))) 34 | except ZeroDivisionError: 35 | self.psi = 0 36 | 37 | # ---------------------------------------------------------------------- 38 | @staticmethod 39 | def change_dimension(n, order=['lnz', 'lnDelta', 'psi', 'lnm', 'lnKt']): 40 | LundCoordinates.components = order[:n] 41 | print(LundCoordinates.components) 42 | LundCoordinates.dimension = len(LundCoordinates.components) 43 | 44 | # ---------------------------------------------------------------------- 45 | def state(self): 46 | # WARNING: For consistency with other parts of the code, 47 | # lnz and lnDelta need to be the first two components 48 | return np.array([getattr(self, v) for v in LundCoordinates.components], dtype='float32') 49 | 50 | 51 | # ====================================================================== 52 | class JetTree: 53 | """JetTree keeps track of the tree structure of a jet declustering.""" 54 | 55 | ktmin = 0.0 56 | deltamin = 0.0 57 | 58 | # ---------------------------------------------------------------------- 59 | def __init__(self, pseudojet, child=None): 60 | """Initialize a new node, and create its two parents if they exist.""" 61 | self.harder = None 62 | self.softer = None 63 | self.delta2 = 0.0 64 | self.lundCoord = None 65 | # if it has a direct child (i.e. one level further up in the 66 | # tree), give a link to the corresponding tree object here 67 | self.child = child 68 | 69 | while True: 70 | j1 = fj.PseudoJet() 71 | j2 = fj.PseudoJet() 72 | if pseudojet and pseudojet.has_parents(j1, j2): 73 | # order the parents in pt 74 | if (j2.pt() > j1.pt()): 75 | j1, j2 = j2, j1 76 | # check if we satisfy cuts 77 | delta = j1.delta_R(j2) 78 | kt = j2.pt() * delta 79 | if (delta < JetTree.deltamin): 80 | break 81 | # then create two new tree nodes with j1 and j2 82 | if kt >= JetTree.ktmin: 83 | self.harder = JetTree(j1, child=self) 84 | self.softer = JetTree(j2, child=self) 85 | self.delta2 = np.float32(delta * delta) 86 | self.lundCoord = LundCoordinates(j1, j2) 87 | break 88 | else: 89 | pseudojet = j1 90 | else: 91 | break 92 | 93 | # finally define the current node 94 | self.node = np.array([pseudojet.px(), pseudojet.py(), pseudojet.pz(), pseudojet.E()], dtype='float32') 95 | 96 | # ---------------------------------------------------------------------- 97 | @staticmethod 98 | def change_cuts(ktmin=0.0, deltamin=0.0): 99 | JetTree.ktmin = ktmin 100 | JetTree.deltamin = deltamin 101 | 102 | # ------------------------------------------------------------------------------- 103 | def remove_soft(self): 104 | """Remove the softer branch of the JetTree node.""" 105 | # start by removing softer parent momentum from the rest of the tree 106 | child = self.child 107 | while(child): 108 | child.node -= self.softer.node 109 | child = child.child 110 | del self.softer 111 | # then move the harder branch to the current node, 112 | # effectively deleting the soft branch 113 | newTree = self.harder 114 | self.node = newTree.node 115 | self.softer = newTree.softer 116 | self.harder = newTree.harder 117 | self.delta2 = newTree.delta2 118 | self.lundCoord = newTree.lundCoord 119 | # finally set the child pointer in the two parents to 120 | # the current node 121 | if self.harder: 122 | self.harder.child = self 123 | if self.softer: 124 | self.softer.child = self 125 | # NB: self.child doesn't change, we are just moving up the part 126 | # of the tree below it 127 | 128 | # ---------------------------------------------------------------------- 129 | def state(self): 130 | """Return state of lund coordinates.""" 131 | if not self.lundCoord: 132 | return np.zeros(LundCoordinates.dimension) 133 | return self.lundCoord.state() 134 | 135 | # ---------------------------------------------------------------------- 136 | def jet(self, pseudojet=False): 137 | """Return the kinematics of the JetTree.""" 138 | # TODO: implement pseudojet option which returns a pseudojet 139 | # with the reclustered constituents (after grooming) 140 | if not pseudojet: 141 | return self.node 142 | else: 143 | raise ValueError("JetTree: jet() with pseudojet return value not implemented.") 144 | 145 | # ---------------------------------------------------------------------- 146 | def __lt__(self, other_tree): 147 | """Comparison operator needed for priority queue.""" 148 | return self.delta2 > other_tree.delta2 149 | 150 | # ---------------------------------------------------------------------- 151 | def __del__(self): 152 | """Delete the node.""" 153 | if self.softer: 154 | del self.softer 155 | if self.harder: 156 | del self.harder 157 | del self.node 158 | del self 159 | 160 | # ====================================================================== 161 | 162 | 163 | class LundImage: 164 | """Class to create Lund images from a jet tree.""" 165 | 166 | # ---------------------------------------------------------------------- 167 | def __init__(self, xval=[0.0, 7.0], yval=[-3.0, 7.0], 168 | npxlx=50, npxly=None): 169 | """Set up the LundImage instance.""" 170 | # set up the pixel numbers 171 | self.npxlx = npxlx 172 | if not npxly: 173 | self.npxly = npxlx 174 | else: 175 | self.npxly = npxly 176 | # set up the bin edge and width 177 | self.xmin = xval[0] 178 | self.ymin = yval[0] 179 | self.x_pxl_wdth = (xval[1] - xval[0]) / self.npxlx 180 | self.y_pxl_wdth = (yval[1] - yval[0]) / self.npxly 181 | 182 | # ---------------------------------------------------------------------- 183 | def __call__(self, tree): 184 | """Process a jet tree and return an image of the primary Lund plane.""" 185 | res = np.zeros((self.npxlx, self.npxly)) 186 | 187 | self.fill(tree, res) 188 | return res 189 | 190 | # ---------------------------------------------------------------------- 191 | def fill(self, tree, res): 192 | """Fill the res array recursively with the tree declusterings of the hard branch.""" 193 | if(tree and tree.lundCoord): 194 | x = -tree.lundCoord.lnDelta 195 | y = tree.lundCoord.lnKt 196 | xind = math.ceil((x - self.xmin) / self.x_pxl_wdth - 1.0) 197 | yind = math.ceil((y - self.ymin) / self.y_pxl_wdth - 1.0) 198 | if (xind < self.npxlx and yind < self.npxly and min(xind, yind) >= 0): 199 | res[xind, yind] += 1 200 | self.fill(tree.harder, res) 201 | #self.fill(tree.softer, res) 202 | 203 | 204 | # ====================================================================== 205 | class RSD: 206 | """RSD applies Recursive Soft Drop grooming to a JetTree.""" 207 | 208 | # ---------------------------------------------------------------------- 209 | def __init__(self, zcut=0.05, beta=1.0, R0=1.0): 210 | """Initialize RSD with its parameters.""" 211 | self.lnzcut = math.log(zcut) 212 | self.beta = beta 213 | self.lnR0 = math.log(R0) 214 | 215 | # ---------------------------------------------------------------------- 216 | def __call__(self, jet, returnTree=False): 217 | """Apply the groomer after casting the jet to a JetTree, and return groomed momenta.""" 218 | # TODO: replace result by reclustered jet of all remaining constituents. 219 | if type(jet) == JetTree: 220 | tree = jet 221 | else: 222 | tree = JetTree(jet) 223 | self._groom(tree) 224 | return tree 225 | 226 | # ---------------------------------------------------------------------- 227 | def _groom(self, tree): 228 | """Apply RSD grooming to a jet.""" 229 | if not tree.lundCoord: 230 | # current node has no subjets => no grooming 231 | return 232 | state = tree.state() 233 | if not state.size > 0: 234 | # current node has no subjets => no grooming 235 | return 236 | # check the SD condition 237 | lnz, lndelta = state[:1] 238 | remove_soft = (lnz < self.lnzcut + self.beta * (lndelta - self.lnR0)) 239 | if remove_soft: 240 | # call internal method to remove soft branch and replace 241 | # current tree node with harder branch 242 | tree.remove_soft() 243 | # now we groom the new tree, since both nodes have been changed 244 | self._groom(tree) 245 | else: 246 | # if we don't groom the current soft branch, then continue 247 | # iterating on both subjets 248 | if tree.harder: 249 | self._groom(tree.harder) 250 | if tree.softer: 251 | self._groom(tree.softer) 252 | -------------------------------------------------------------------------------- /src/lundnet/LundNet.py: -------------------------------------------------------------------------------- 1 | # This file is part of LundNet by F. Dreyer and H. Qu 2 | 3 | from __future__ import print_function 4 | 5 | import dgl 6 | import torch 7 | import torch.nn as nn 8 | import numpy as np 9 | 10 | from lundnet.EdgeConv import EdgeConvBlock 11 | 12 | 13 | class LundNet(nn.Module): 14 | 15 | def __init__(self, 16 | input_dims, 17 | num_classes, 18 | conv_params=[[32, 32], [32, 32], [64, 64], [64, 64], [128, 128], [128, 128]], 19 | fc_params=[(128, 0.1)], 20 | use_fusion=True, 21 | **kwargs): 22 | super(LundNet, self).__init__(**kwargs) 23 | 24 | self.bn_fts = nn.BatchNorm1d(input_dims) 25 | 26 | self.edge_convs = nn.ModuleList() 27 | for idx, channels in enumerate(conv_params): 28 | in_feat = input_dims if idx == 0 else conv_params[idx - 1][-1] 29 | self.edge_convs.append(EdgeConvBlock(in_feat=in_feat, out_feats=channels)) 30 | 31 | self.use_fusion = use_fusion 32 | if self.use_fusion: 33 | in_chn = sum(x[-1] for x in conv_params) 34 | out_chn = np.clip((in_chn // 128) * 128, 128, 1024) 35 | self.fusion_block = nn.Sequential(nn.Linear(in_chn, out_chn), nn.ReLU(), nn.BatchNorm1d(out_chn)) 36 | 37 | fcs = [] 38 | for idx, layer_param in enumerate(fc_params): 39 | channels, drop_rate = layer_param 40 | if idx == 0: 41 | in_chn = out_chn if self.use_fusion else conv_params[-1][-1] 42 | else: 43 | in_chn = fc_params[idx - 1][0] 44 | fcs.append(nn.Sequential(nn.Linear(in_chn, channels), nn.ReLU(), nn.Dropout(drop_rate))) 45 | fcs.append(nn.Linear(fc_params[-1][0], num_classes)) 46 | self.fc = nn.Sequential(*fcs) 47 | 48 | def forward(self, batch_graph, features): 49 | fts = self.bn_fts(features) 50 | outputs = [] 51 | for idx, conv in enumerate(self.edge_convs): 52 | fts = conv(batch_graph, fts) 53 | if self.use_fusion: 54 | outputs.append(fts) 55 | if self.use_fusion: 56 | fts = self.fusion_block(torch.cat(outputs, dim=1)) 57 | 58 | batch_graph.ndata['fts'] = fts 59 | x = dgl.mean_nodes(batch_graph, 'fts') 60 | return self.fc(x) 61 | -------------------------------------------------------------------------------- /src/lundnet/ParticleNet.py: -------------------------------------------------------------------------------- 1 | # This file is part of LundNet by F. Dreyer and H. Qu 2 | 3 | from __future__ import print_function 4 | 5 | import dgl 6 | from dgl.transform import remove_self_loop 7 | from .dgl_utils import segmented_knn_graph 8 | import torch 9 | import torch.nn as nn 10 | import numpy as np 11 | 12 | from lundnet.EdgeConv import EdgeConvBlock 13 | 14 | 15 | class ParticleNet(nn.Module): 16 | r""" 17 | DGL implementation of "ParticleNet: Jet Tagging via Particle Clouds" (https://arxiv.org/abs/1902.08570). 18 | """ 19 | 20 | def __init__(self, 21 | input_dims, 22 | num_classes, 23 | conv_params=[(7, (32, 32, 32)), (7, (64, 64, 64))], 24 | fc_params=[(128, 0.1)], 25 | use_fusion=False, 26 | **kwargs): 27 | super(ParticleNet, self).__init__(**kwargs) 28 | 29 | self.bn_fts = nn.BatchNorm1d(input_dims) 30 | 31 | self.k_neighbors = [] 32 | self.edge_convs = nn.ModuleList() 33 | for idx, layer_param in enumerate(conv_params): 34 | k, channels = layer_param 35 | in_feat = input_dims if idx == 0 else conv_params[idx - 1][1][-1] 36 | self.edge_convs.append(EdgeConvBlock(in_feat=in_feat, out_feats=channels)) 37 | self.k_neighbors.append(k) 38 | 39 | self.use_fusion = use_fusion 40 | if self.use_fusion: 41 | in_chn = sum(x[-1] for _, x in conv_params) 42 | out_chn = np.clip((in_chn // 128) * 128, 128, 1024) 43 | self.fusion_block = nn.Sequential(nn.Linear(in_chn, out_chn), nn.ReLU(), nn.BatchNorm1d(out_chn)) 44 | 45 | fcs = [] 46 | for idx, layer_param in enumerate(fc_params): 47 | channels, drop_rate = layer_param 48 | if idx == 0: 49 | in_chn = out_chn if self.use_fusion else conv_params[-1][1][-1] 50 | else: 51 | in_chn = fc_params[idx - 1][0] 52 | fcs.append(nn.Sequential(nn.Linear(in_chn, channels), nn.ReLU(), nn.Dropout(drop_rate))) 53 | fcs.append(nn.Linear(fc_params[-1][0], num_classes)) 54 | self.fc = nn.Sequential(*fcs) 55 | 56 | def forward(self, batch_graph, features): 57 | g = batch_graph 58 | segs = batch_graph.batch_num_nodes().cpu().numpy().tolist() 59 | fts = self.bn_fts(features) 60 | outputs = [] 61 | for idx, (k, conv) in enumerate(zip(self.k_neighbors, self.edge_convs)): 62 | if idx > 0: 63 | g = remove_self_loop(segmented_knn_graph(fts, k + 1, segs)).to(features.device) 64 | fts = conv(g, fts) 65 | if self.use_fusion: 66 | outputs.append(fts) 67 | if self.use_fusion: 68 | fts = self.fusion_block(torch.cat(outputs, dim=1)) 69 | 70 | batch_graph.ndata['fts'] = fts 71 | x = dgl.mean_nodes(batch_graph, 'fts') 72 | return self.fc(x) 73 | -------------------------------------------------------------------------------- /src/lundnet/dgl_dataset.py: -------------------------------------------------------------------------------- 1 | # This file is part of LundNet by F. Dreyer and H. Qu 2 | 3 | from __future__ import print_function 4 | 5 | import dgl 6 | import networkx as nx 7 | import numpy as np 8 | from dgl.transform import remove_self_loop 9 | from .dgl_utils import knn_graph 10 | from torch.utils.data import Dataset 11 | from .JetTree import JetTree, LundCoordinates 12 | from .read_data import Jets 13 | import torch 14 | import torch.nn.functional as F 15 | try: 16 | from uproot_methods import TLorentzVectorArray, TLorentzVector 17 | except ImportError: 18 | from uproot3_methods import TLorentzVectorArray, TLorentzVector 19 | import time 20 | import pandas as pd 21 | 22 | groomer = None 23 | dump_number_of_nodes = False 24 | 25 | 26 | class DGLGraphDatasetLund(Dataset): 27 | 28 | fill_secondary = True 29 | node_coordinates = 'eta-phi' # 'lund' 30 | 31 | def __init__(self, filepath_bkg, filepath_sig, nev=-1): 32 | super(DGLGraphDatasetLund, self).__init__() 33 | print('Start loading dataset %s (bkg) and %s (sig)' % (filepath_bkg, filepath_sig)) 34 | tic = time.process_time() 35 | reader_bkg = Jets(filepath_bkg, nev, groomer=groomer) 36 | reader_sig = Jets(filepath_sig, nev, groomer=groomer) 37 | # attempt at using less memory 38 | self.data = [] 39 | self.label = [] 40 | for jet in reader_bkg: 41 | self.data += [self._build_tree(JetTree(jet))] 42 | self.label += [0] 43 | for jet in reader_sig: 44 | self.data += [self._build_tree(JetTree(jet))] 45 | self.label += [1] 46 | print(' ... Total time to read input files + construct the graphs for {num} jets: {ts} seconds'.format( 47 | num=len(self.label), ts=time.process_time() - tic)) 48 | if dump_number_of_nodes: 49 | df = pd.DataFrame({'num_nodes': np.array( 50 | [g.number_of_nodes() for g in self.data]), 'label': np.array(self.label)}) 51 | df.to_csv('num_nodes_lund_net_ktmin_%s_deltamin_%s.csv' % (JetTree.ktmin, JetTree.deltamin)) 52 | self.label = torch.tensor(self.label, dtype=torch.float32) 53 | 54 | def _build_tree(self, root): 55 | g = nx.Graph() 56 | jet_p4 = TLorentzVector(*root.node) 57 | 58 | def _rec_build(nid, node): 59 | branches = [node.harder, node.softer] if DGLGraphDatasetLund.fill_secondary else [node.harder] 60 | for branch in branches: 61 | if branch is None or branch.lundCoord is None: 62 | # stop when reaching the leaf nodes 63 | # we do not add the leaf nodes to the graph/tree as they do not have Lund coordinates 64 | continue 65 | cid = g.number_of_nodes() 66 | if DGLGraphDatasetLund.node_coordinates == 'lund': 67 | spatialCoord = branch.lundCoord.state()[:2] 68 | else: 69 | node_p4 = TLorentzVector(*branch.node) 70 | spatialCoord = np.array( 71 | [delta_eta_reflect(node_p4, jet_p4), 72 | node_p4.delta_phi(jet_p4)], 73 | dtype='float32') 74 | g.add_node(cid, coordinates=spatialCoord, features=branch.lundCoord.state()) 75 | g.add_edge(cid, nid) 76 | _rec_build(cid, branch) 77 | # add root 78 | if root.lundCoord is not None: 79 | if DGLGraphDatasetLund.node_coordinates == 'lund': 80 | spatialCoord = root.lundCoord.state()[:2] 81 | else: 82 | spatialCoord = np.zeros(2, dtype='float32') 83 | g.add_node(0, coordinates=spatialCoord, features=root.lundCoord.state()) 84 | _rec_build(0, root) 85 | else: 86 | # when a jet has only one particle (?) 87 | g.add_node(0, coordinates=np.zeros(2, dtype='float32'), 88 | features=np.zeros(LundCoordinates.dimension, dtype='float32')) 89 | ret = dgl.from_networkx(g, node_attrs=['coordinates', 'features']) 90 | # print(ret.number_of_nodes()) 91 | return ret 92 | 93 | @property 94 | def num_features(self): 95 | return self.data[0].ndata['features'].shape[1] 96 | 97 | def __len__(self): 98 | return len(self.data) 99 | 100 | def __getitem__(self, i): 101 | x = self.data[i] 102 | y = self.label[i] 103 | return x, y 104 | 105 | 106 | class DGLGraphDatasetParticle(Dataset): 107 | 108 | def __init__(self, filepath_bkg, filepath_sig, nev=-1): 109 | super(DGLGraphDatasetParticle, self).__init__() 110 | print('Start loading dataset %s (bkg) and %s (sig)' % (filepath_bkg, filepath_sig)) 111 | tic = time.process_time() 112 | reader_bkg = Jets(filepath_bkg, nev, pseudojets=False, groomer=groomer) 113 | reader_sig = Jets(filepath_sig, nev, pseudojets=False, groomer=groomer) 114 | # Format of jets_bkg/jets_sig: 115 | # [# jet 116 | # [ # particle 117 | # [px, py, pz, E], 118 | # # particle 2 119 | # [px, py, pze, E] 120 | # ], 121 | # # jet 2 122 | # #..... 123 | # ] 124 | # attempt at saving memory use: 125 | self.data = [] 126 | self.label = [] 127 | for constits in reader_bkg: 128 | self.data += [self._build_graph(constits)] 129 | self.label += [0] 130 | for constits in reader_sig: 131 | self.data += [self._build_graph(constits)] 132 | self.label += [1] 133 | print(' ... Total time to read input files + construct the graphs for {num} jets: {ts} seconds'.format( 134 | num=len(self.label), ts=time.process_time() - tic)) 135 | if dump_number_of_nodes: 136 | df = pd.DataFrame({'num_nodes': np.array( 137 | [g.number_of_nodes() for g in self.data]), 'label': np.array(self.label)}) 138 | df.to_csv('num_nodes_particle_net.csv') 139 | self.label = torch.tensor(self.label, dtype=torch.float32) 140 | 141 | def _build_graph(self, constits): 142 | constits_p4 = TLorentzVectorArray.from_cartesian(*list(zip(*constits))) 143 | jet_p4 = constits_p4.sum() 144 | spatialCoord = np.stack([delta_eta_reflect(constits_p4, jet_p4), constits_p4.delta_phi(jet_p4)], axis=1) 145 | energyFeatures = np.log(np.stack([constits_p4.pt, constits_p4.energy], axis=1)) 146 | features = np.concatenate([spatialCoord, energyFeatures], axis=1) 147 | ret = dgl.DGLGraph() 148 | ret.add_nodes( 149 | len(constits), 150 | {'coordinates': torch.tensor(spatialCoord, dtype=torch.float32), 151 | 'features': torch.tensor(features, dtype=torch.float32)}) 152 | # print(ret.number_of_nodes()) 153 | return ret 154 | 155 | @property 156 | def num_features(self): 157 | return self.data[0].ndata['features'].shape[1] 158 | 159 | def __len__(self): 160 | return len(self.data) 161 | 162 | def __getitem__(self, i): 163 | x = self.data[i] 164 | y = self.label[i] 165 | return x, y 166 | 167 | 168 | def delta_eta_reflect(constits_p4, jet_p4): 169 | deta = constits_p4.eta - jet_p4.eta 170 | return deta if jet_p4.eta > 0 else -deta 171 | 172 | 173 | def pad_array(a, min_len=20, pad_value=0): 174 | if a.shape[0] < min_len: 175 | return F.pad(a, (0, 0, 0, min_len - a.shape[0]), mode='constant', value=pad_value) 176 | else: 177 | return a 178 | 179 | 180 | class _SimpleCustomBatch: 181 | 182 | def __init__(self, data, k, min_nodes=20): 183 | transposed_data = list(zip(*data)) 184 | graphs = [] 185 | features = [] 186 | for g in transposed_data[0]: 187 | nng = remove_self_loop(knn_graph(g.ndata['coordinates'], min(g.number_of_nodes(), k + 1))) 188 | if nng.number_of_nodes() < min_nodes: 189 | nng.add_nodes(min_nodes - nng.number_of_nodes()) 190 | graphs.append(nng) 191 | fts = pad_array(g.ndata['features'], min_nodes, 0) 192 | features.append(fts) 193 | assert(nng.number_of_nodes() == fts.shape[0]) 194 | self.batch_graph = dgl.batch(graphs) 195 | self.features = torch.cat(features, 0) 196 | self.label = torch.tensor(transposed_data[1]) 197 | 198 | def pin_memory(self): 199 | self.features = self.features.pin_memory() 200 | self.label = self.label.pin_memory() 201 | return self 202 | 203 | 204 | def collate_wrapper(batch, k): 205 | return _SimpleCustomBatch(batch, k) 206 | 207 | 208 | class _LundTreeBatch: 209 | 210 | def __init__(self, data): 211 | transposed_data = list(zip(*data)) 212 | self.batch_graph = dgl.batch(transposed_data[0]) 213 | self.batch_graph.ndata.pop('coordinates') # drop (eta, phi) coordinates 214 | self.features = self.batch_graph.ndata.pop('features') 215 | self.label = torch.tensor(transposed_data[1]) 216 | 217 | def pin_memory(self): 218 | self.features = self.features.pin_memory() 219 | self.label = self.label.pin_memory() 220 | return self 221 | 222 | 223 | def collate_wrapper_tree(batch): 224 | return _LundTreeBatch(batch) 225 | -------------------------------------------------------------------------------- /src/lundnet/dgl_utils.py: -------------------------------------------------------------------------------- 1 | # This file is part of LundNet by F. Dreyer and H. Qu 2 | 3 | import numpy as np 4 | from scipy import sparse 5 | from dgl import DGLGraph 6 | from dgl import backend as F 7 | from dgl.transform import pairwise_squared_distance 8 | 9 | '''copied from dgl.transform and fixed a bug''' 10 | 11 | 12 | def knn_graph(x, k): 13 | """Transforms the given point set to a directed graph, whose coordinates 14 | are given as a matrix. The predecessors of each point are its k-nearest 15 | neighbors. 16 | 17 | If a 3D tensor is given instead, then each row would be transformed into 18 | a separate graph. The graphs will be unioned. 19 | 20 | Parameters 21 | ---------- 22 | x : Tensor 23 | The input tensor. 24 | 25 | If 2D, each row of ``x`` corresponds to a node. 26 | 27 | If 3D, a k-NN graph would be constructed for each row. Then 28 | the graphs are unioned. 29 | k : int 30 | The number of neighbors 31 | 32 | Returns 33 | ------- 34 | DGLGraph 35 | The graph. The node IDs are in the same order as ``x``. 36 | """ 37 | if F.ndim(x) == 2: 38 | x = F.unsqueeze(x, 0) 39 | n_samples, n_points, _ = F.shape(x) 40 | n_total_points = n_samples * n_points 41 | 42 | dist = pairwise_squared_distance(x) 43 | k_indices = F.argtopk(dist, k, 2, descending=False) 44 | dst = F.copy_to(k_indices, F.cpu()) 45 | 46 | src = F.zeros_like(dst) + F.reshape(F.arange(0, n_points), (1, -1, 1)) 47 | 48 | per_sample_offset = F.reshape(F.arange(0, n_samples) * n_points, (-1, 1, 1)) 49 | dst += per_sample_offset 50 | src += per_sample_offset 51 | dst = F.reshape(dst, (-1,)) 52 | src = F.reshape(src, (-1,)) 53 | adj = sparse.csr_matrix((F.asnumpy(F.zeros_like(dst) + 1), (F.asnumpy(dst), F.asnumpy(src))), 54 | shape=(n_total_points, n_total_points)) 55 | 56 | g = DGLGraph(adj, readonly=True) 57 | return g 58 | 59 | 60 | def segmented_knn_graph(x, k, segs): 61 | """Transforms the given point set to a directed graph, whose coordinates 62 | are given as a matrix. The predecessors of each point are its k-nearest 63 | neighbors. 64 | 65 | The matrices are concatenated along the first axis, and are segmented by 66 | ``segs``. Each block would be transformed into a separate graph. The 67 | graphs will be unioned. 68 | 69 | Parameters 70 | ---------- 71 | x : Tensor 72 | The input tensor. 73 | k : int 74 | The number of neighbors 75 | segs : iterable of int 76 | Number of points of each point set. 77 | Must sum up to the number of rows in ``x``. 78 | 79 | Returns 80 | ------- 81 | DGLGraph 82 | The graph. The node IDs are in the same order as ``x``. 83 | """ 84 | n_total_points, _ = F.shape(x) 85 | offset = np.insert(np.cumsum(segs), 0, 0) 86 | 87 | h_list = F.split(x, segs, 0) 88 | dst = [ 89 | F.argtopk(pairwise_squared_distance(h_g), k, 1, descending=False) + 90 | offset[i] 91 | for i, h_g in enumerate(h_list)] 92 | dst = F.cat(dst, 0) 93 | src = F.arange(0, n_total_points).unsqueeze(1).expand(n_total_points, k) 94 | 95 | dst = F.reshape(dst, (-1,)) 96 | src = F.reshape(src, (-1,)) 97 | # !!! fix shape 98 | adj = sparse.csr_matrix((F.asnumpy(F.zeros_like(dst) + 1), (F.asnumpy(dst), F.asnumpy(src))), 99 | shape=(n_total_points, n_total_points)) 100 | 101 | g = DGLGraph(adj, readonly=True) 102 | return g 103 | 104 | 105 | def reversed_graph(g): 106 | ret = DGLGraph() 107 | ret.add_nodes(g.number_of_nodes()) 108 | u, v = g.all_edges() 109 | ret.add_edges(v, u) 110 | return ret 111 | -------------------------------------------------------------------------------- /src/lundnet/read_data.py: -------------------------------------------------------------------------------- 1 | # This file is part of LundNet by F. Dreyer and H. Qu 2 | # adapted from code written by G. Salam 3 | 4 | import json, gzip, sys 5 | from abc import ABC, abstractmethod 6 | from math import pow 7 | import fastjet as fj 8 | 9 | 10 | # ====================================================================== 11 | class Reader(object): 12 | """ 13 | Reader for files consisting of a sequence of json objects. 14 | Any pure string object is considered to be part of a header (even if it appears at the end!) 15 | """ 16 | 17 | # ---------------------------------------------------------------------- 18 | def __init__(self, infile, nmax=-1): 19 | """Initialize the reader.""" 20 | self.infile = infile 21 | self.nmax = nmax 22 | self.reset() 23 | 24 | # ---------------------------------------------------------------------- 25 | def reset(self): 26 | """ 27 | Reset the reader to the start of the file, clear the header and event count. 28 | """ 29 | self.stream = gzip.open(self.infile, 'r') 30 | self.n = 0 31 | self.header = [] 32 | 33 | # ---------------------------------------------------------------------- 34 | 35 | def __iter__(self): 36 | # needed for iteration to work 37 | return self 38 | 39 | # ---------------------------------------------------------------------- 40 | def __next__(self): 41 | ev = self.next_event() 42 | if (ev is None): 43 | raise StopIteration 44 | else: 45 | return ev 46 | 47 | # ---------------------------------------------------------------------- 48 | def next(self): 49 | return self.__next__() 50 | 51 | # ---------------------------------------------------------------------- 52 | def next_event(self): 53 | # we have hit the maximum number of events 54 | if (self.n == self.nmax): 55 | print("# Exiting after having read nmax jet declusterings") 56 | return None 57 | 58 | try: 59 | line = self.stream.readline() 60 | j = json.loads(line.decode('utf-8')) 61 | except IOError: 62 | print("# got to end with IOError (maybe gzip structure broken?) around event", self.n, file=sys.stderr) 63 | return None 64 | except EOFError: 65 | print("# got to end with EOFError (maybe gzip structure broken?) around event", self.n, file=sys.stderr) 66 | return None 67 | except ValueError: 68 | print("# got to end with ValueError (empty json entry) around event", self.n, file=sys.stderr) 69 | return None 70 | 71 | # skip this 72 | if (type(j) is str): 73 | self.header.append(j) 74 | return self.next_event() 75 | self.n += 1 76 | return j 77 | 78 | 79 | # ====================================================================== 80 | class Image(ABC): 81 | """Image which transforms point-like information into pixelated 2D 82 | images which can be processed by convolutional neural networks.""" 83 | 84 | def __init__(self, infile, nmax): 85 | self.reader = Reader(infile, nmax) 86 | 87 | # ---------------------------------------------------------------------- 88 | @abstractmethod 89 | def process(self, event): 90 | pass 91 | 92 | # ---------------------------------------------------------------------- 93 | def __iter__(self): 94 | # needed for iteration to work 95 | return self 96 | 97 | # ---------------------------------------------------------------------- 98 | def __next__(self): 99 | ev = self.reader.next_event() 100 | if (ev is None): 101 | raise StopIteration 102 | else: 103 | return self.process(ev) 104 | 105 | # ---------------------------------------------------------------------- 106 | def next(self): return self.__next__() 107 | 108 | # ---------------------------------------------------------------------- 109 | def values(self): 110 | res = [] 111 | while True: 112 | event = self.reader.next_event() 113 | if event != None: 114 | res.append(self.process(event)) 115 | else: 116 | break 117 | self.reader.reset() 118 | return res 119 | 120 | 121 | # ====================================================================== 122 | class Jets(Image): 123 | """Read input file with jet constituents and transform into python jets.""" 124 | 125 | # ---------------------------------------------------------------------- 126 | def __init__(self, infile, nmax, pseudojets=True, groomer=None): 127 | Image.__init__(self, infile, nmax) 128 | self.jet_def = fj.JetDefinition(fj.cambridge_algorithm, 1000.0) 129 | self.pseudojets = pseudojets 130 | self.groomer = groomer 131 | 132 | # ---------------------------------------------------------------------- 133 | def process(self, event): 134 | constits = [] 135 | if self.pseudojets or self.groomer: 136 | for p in event[1:]: 137 | constits.append(fj.PseudoJet(p['px'], p['py'], p['pz'], p['E'])) 138 | jets = self.jet_def(constits) 139 | if (len(jets) > 0): 140 | if self.groomer: 141 | constits = self.groomer(jets[0], self.pseudojets) 142 | return self.jet_def(constits)[0] if self.pseudojets else constits 143 | return jets[0] 144 | return fj.PseudoJet() 145 | else: 146 | for p in event[1:]: 147 | constits.append([p['px'], p['py'], p['pz'], p['E']]) 148 | return constits 149 | 150 | 151 | # ====================================================================== 152 | class GroomJetRSD: 153 | """Recursive Soft Drop groomer applicable on fastjet PseudoJets""" 154 | 155 | # ---------------------------------------------------------------------- 156 | def __init__(self, zcut=0.05, beta=1.0, R0=1.0): 157 | """Initialize RSD with its parameters.""" 158 | self.zcut = zcut 159 | self.beta = beta 160 | self.R0 = R0 161 | 162 | def __call__(self, jet, pseudojets=True): 163 | constits = [] 164 | self._groom(jet, constits, pseudojets) 165 | return constits 166 | 167 | def _groom(self, j, constits, pseudojets): 168 | j1 = fj.PseudoJet() 169 | j2 = fj.PseudoJet() 170 | if j.has_parents(j1, j2): 171 | # order the parents in pt 172 | if (j2.pt() > j1.pt()): 173 | j1, j2 = j2, j1 174 | delta = j1.delta_R(j2) 175 | z = j2.pt() / (j1.pt() + j2.pt()) 176 | remove_soft = (z < self.zcut * pow(delta / self.R0, self.beta)) 177 | if remove_soft: 178 | self._groom(j1, constits, pseudojets) 179 | else: 180 | self._groom(j1, constits, pseudojets) 181 | self._groom(j2, constits, pseudojets) 182 | else: 183 | if pseudojets: 184 | constits.append(fj.PseudoJet(j.px(), j.py(), j.pz(), j.E())) 185 | else: 186 | constits.append([j.px(), j.py(), j.pz(), j.E()]) 187 | -------------------------------------------------------------------------------- /src/lundnet/scripts/lundnet.py: -------------------------------------------------------------------------------- 1 | # This file is part of LundNet by F. Dreyer and H. Qu 2 | 3 | """ 4 | lundnet.py: the entry point for LundNet. 5 | """ 6 | 7 | from __future__ import print_function 8 | 9 | import numpy as np 10 | import torch 11 | from torch.utils.data import DataLoader 12 | 13 | import tqdm 14 | from functools import partial 15 | import os, time, datetime, argparse, pickle 16 | 17 | from lundnet.dgl_dataset import DGLGraphDatasetParticle, DGLGraphDatasetLund, collate_wrapper, collate_wrapper_tree 18 | from sklearn.metrics import roc_curve 19 | 20 | 21 | def bkg_rejection_at_threshold(signal_eff, background_eff, sig_eff=0.5): 22 | """Background rejection at a given signal efficiency.""" 23 | return 1 / (1 - background_eff[np.argmin(np.abs(signal_eff - sig_eff)) + 1]) 24 | 25 | 26 | def ROC_area(signal_eff, background_eff): 27 | """Area under the ROC curve.""" 28 | normal_order = signal_eff.argsort() 29 | return np.trapz(background_eff[normal_order], signal_eff[normal_order]) 30 | 31 | 32 | def accuracy(preds, labels): 33 | """Return the accuracy.""" 34 | if labels.ndim == 2: 35 | labels = labels[:, 1] 36 | return (preds.argmax(1) == labels).sum().item() / len(labels) 37 | 38 | 39 | def main(): 40 | parser = argparse.ArgumentParser() 41 | parser.add_argument('--demo', action='store_true', default=False) 42 | parser.add_argument('--train-sig', type=str, default='') 43 | parser.add_argument('--train-bkg', type=str, default='') 44 | parser.add_argument('--val-sig', type=str, default='') 45 | parser.add_argument('--val-bkg', type=str, default='') 46 | parser.add_argument('--test-sig', type=str, default='') 47 | parser.add_argument('--test-bkg', type=str, default='') 48 | parser.add_argument('--model', type=str, default='lundnet5', choices=['lundnet5', 'lundnet2', 49 | 'lundnet3', 'lundnet4', 50 | 'particlenet', 'particlenet-lite']) 51 | parser.add_argument('--ln-kt-min', type=float, default=None) 52 | parser.add_argument('--ln-delta-min', type=float, default=None) 53 | parser.add_argument('--load', type=str, default='') 54 | parser.add_argument('--save', type=str, default='') 55 | parser.add_argument('--name', type=str, default='model') 56 | parser.add_argument('--test-output', type=str, default='') 57 | parser.add_argument('--num-epochs', type=int, default=30) 58 | parser.add_argument('--nev', type=int, default=-1) 59 | parser.add_argument('--nev-val', type=int, default=-1) 60 | parser.add_argument('--nev-test', type=int, default=-1) 61 | parser.add_argument('--start-lr', type=float, default=0.001) 62 | parser.add_argument('--lr-steps', type=str, default='10,20') 63 | parser.add_argument('--num-workers', type=int, default=0) 64 | parser.add_argument('--batch-size', type=int, default=-1) 65 | parser.add_argument('--device', type=str, default='cuda:0') 66 | args = parser.parse_args() 67 | 68 | if 'lund' in args.model: 69 | from lundnet.JetTree import JetTree, LundCoordinates 70 | if args.model == 'lundnet4': 71 | LundCoordinates.change_dimension(4, ['lnz', 'lnDelta', 'lnKt', 'psi']) 72 | elif args.model == 'lundnet3': 73 | LundCoordinates.change_dimension(3, ['lnz', 'lnDelta', 'lnKt']) 74 | elif args.model == 'lundnet2': 75 | LundCoordinates.change_dimension(2, ['lnDelta', 'lnKt']) 76 | kt_min = np.exp(args.ln_kt_min) if (args.ln_kt_min is not None and args.ln_kt_min > -99) else 0 77 | delta_min = np.exp(args.ln_delta_min) if args.ln_delta_min is not None else 0 78 | JetTree.change_cuts(kt_min, delta_min) 79 | print('Using %s, kt_min=%f and delta_min=%f' % (args.model, JetTree.ktmin, JetTree.deltamin)) 80 | 81 | if args.demo: 82 | args.train_sig = 'sample_WW_500GeV.json.gz' 83 | args.train_bkg = 'sample_QCD_500GeV.json.gz' 84 | args.val_sig = 'sample_WW_500GeV.json.gz' 85 | args.val_bkg = 'sample_QCD_500GeV.json.gz' 86 | args.test_sig = 'sample_WW_500GeV.json.gz' 87 | args.test_bkg = 'sample_QCD_500GeV.json.gz' 88 | 89 | # training/testing mode 90 | if args.train_bkg and args.train_sig: 91 | training_mode = True 92 | else: 93 | assert(args.load) 94 | training_mode = False 95 | 96 | # data format 97 | DGLGraphDataset = DGLGraphDatasetLund if 'lund' in args.model else DGLGraphDatasetParticle 98 | 99 | # model parameter 100 | if args.model == 'particlenet': 101 | from lundnet.ParticleNet import ParticleNet 102 | Net = ParticleNet 103 | conv_params = [ 104 | (16, (64, 64, 64)), 105 | (16, (128, 128, 128)), 106 | (16, (256, 256, 256)), 107 | ] 108 | fc_params = [(256, 0.1)] 109 | use_fusion = False 110 | if args.batch_size <= 0: 111 | args.batch_size = 256 112 | collate_fn = partial(collate_wrapper, k=conv_params[0][0]) 113 | elif args.model == 'particlenet-lite': 114 | from lundnet.ParticleNet import ParticleNet 115 | Net = ParticleNet 116 | conv_params = [ 117 | (7, (32, 32, 32)), 118 | (7, (64, 64, 64)) 119 | ] 120 | fc_params = [(128, 0.1)] 121 | use_fusion = False 122 | if args.batch_size <= 0: 123 | args.batch_size = 1024 124 | collate_fn = partial(collate_wrapper, k=conv_params[0][0]) 125 | else: 126 | from lundnet.LundNet import LundNet 127 | Net = LundNet 128 | conv_params = [[32, 32], [32, 32], [64, 64], [64, 64], [128, 128], [128, 128]] 129 | fc_params = [(256, 0.1)] 130 | use_fusion = True 131 | if args.batch_size <= 0: 132 | args.batch_size = 256 133 | collate_fn = collate_wrapper_tree 134 | 135 | # device 136 | dev = torch.device(args.device) 137 | 138 | # load data 139 | if training_mode: 140 | train_data = DGLGraphDataset(args.train_bkg, args.train_sig, nev=args.nev) 141 | val_data = DGLGraphDataset(args.val_bkg, args.val_sig, nev=args.nev_val) 142 | train_loader = DataLoader(train_data, num_workers=args.num_workers, batch_size=args.batch_size, 143 | collate_fn=collate_fn, shuffle=True, drop_last=True, pin_memory=True) 144 | val_loader = DataLoader(val_data, num_workers=args.num_workers, batch_size=args.batch_size, 145 | collate_fn=collate_fn, shuffle=False, drop_last=True, pin_memory=True) 146 | input_dims = train_data.num_features 147 | else: 148 | test_data = DGLGraphDataset(args.test_bkg, args.test_sig, nev=args.nev_test) 149 | test_loader = DataLoader(test_data, num_workers=args.num_workers, batch_size=args.batch_size, 150 | collate_fn=collate_fn, shuffle=False, drop_last=False, pin_memory=True) 151 | input_dims = test_data.num_features 152 | 153 | # model 154 | model = Net(input_dims=input_dims, num_classes=2, 155 | conv_params=conv_params, 156 | fc_params=fc_params, 157 | use_fusion=use_fusion) 158 | model = model.to(dev) 159 | 160 | def train(model, opt, scheduler, train_loader, dev): 161 | model.train() 162 | 163 | total_loss = 0 164 | num_batches = 0 165 | total_correct = 0 166 | count = 0 167 | tic = time.time() 168 | with tqdm.tqdm(train_loader, ascii=True) as tq: 169 | for batch in tq: 170 | label = batch.label 171 | num_examples = label.shape[0] 172 | label = label.to(dev).squeeze().long() 173 | opt.zero_grad() 174 | logits = model(batch.batch_graph.to(dev), batch.features.to(dev)) 175 | loss = loss_func(logits, label) 176 | loss.backward() 177 | opt.step() 178 | 179 | _, preds = logits.max(1) 180 | 181 | num_batches += 1 182 | count += num_examples 183 | loss = loss.item() 184 | correct = (preds == label).sum().item() 185 | total_loss += loss 186 | total_correct += correct 187 | 188 | tq.set_postfix({ 189 | 'Loss': '%.5f' % loss, 190 | 'AvgLoss': '%.5f' % (total_loss / num_batches), 191 | 'Acc': '%.5f' % (correct / num_examples), 192 | 'AvgAcc': '%.5f' % (total_correct / count)}) 193 | scheduler.step() 194 | 195 | ts = time.time() - tic 196 | print('Trained over {count} samples in {ts} secs (avg. speed {speed} samples/s.)'.format( 197 | count=count, ts=ts, speed=count / ts 198 | )) 199 | 200 | def evaluate(model, test_loader, dev, return_scores=False, return_time=False): 201 | model.eval() 202 | 203 | total_correct = 0 204 | count = 0 205 | scores = [] 206 | tic = time.time() 207 | 208 | with torch.no_grad(): 209 | with tqdm.tqdm(test_loader, ascii=True) as tq: 210 | for batch in tq: 211 | label = batch.label 212 | num_examples = label.shape[0] 213 | label = label.to(dev).squeeze().long() 214 | logits = model(batch.batch_graph.to(dev), batch.features.to(dev)) 215 | _, preds = logits.max(1) 216 | 217 | if return_scores: 218 | scores.append(torch.softmax(logits, dim=1).cpu().detach().numpy()) 219 | 220 | correct = (preds == label).sum().item() 221 | total_correct += correct 222 | count += num_examples 223 | 224 | tq.set_postfix({ 225 | 'Acc': '%.5f' % (correct / num_examples), 226 | 'AvgAcc': '%.5f' % (total_correct / count)}) 227 | 228 | ts = time.time() - tic 229 | print('Tested over {count} samples in {ts} secs (avg. speed {speed} samples/s.)'.format( 230 | count=count, ts=ts, speed=count / ts 231 | )) 232 | if return_time: 233 | return ts 234 | 235 | if return_scores: 236 | return np.concatenate(scores) 237 | else: 238 | return total_correct / count 239 | 240 | if training_mode: 241 | # loss function 242 | loss_func = torch.nn.CrossEntropyLoss() 243 | 244 | # optimizer 245 | opt = torch.optim.Adam(model.parameters(), lr=args.start_lr) 246 | 247 | # learning rate 248 | lr_steps = [int(x) for x in args.lr_steps.split(',')] 249 | scheduler = torch.optim.lr_scheduler.MultiStepLR(opt, milestones=lr_steps, gamma=0.1) 250 | 251 | # training loop 252 | best_valid_acc = 0 253 | for epoch in range(args.num_epochs): 254 | train(model, opt, scheduler, train_loader, dev) 255 | 256 | print('Epoch #%d Validating' % epoch) 257 | valid_acc = evaluate(model, val_loader, dev) 258 | if valid_acc > best_valid_acc: 259 | best_valid_acc = valid_acc 260 | if args.save: 261 | if args.save and not os.path.exists(args.save): 262 | os.makedirs(args.save) 263 | torch.save(model.state_dict(), os.path.join(args.save, '%s_state.pt' % args.name)) 264 | print('Current validation acc: %.5f (best: %.5f)' % (valid_acc, best_valid_acc)) 265 | 266 | # evaluate model on test dataset 267 | path = args.save if training_mode else os.path.dirname(args.load) 268 | name = args.test_output if args.test_output else 'test' 269 | if path and not os.path.exists(path): 270 | os.makedirs(path) 271 | 272 | if training_mode: 273 | del train_data, train_loader, val_data, val_loader 274 | test_data = DGLGraphDataset(args.test_bkg, args.test_sig, args.nev_test) 275 | test_loader = DataLoader(test_data, num_workers=args.num_workers, batch_size=args.batch_size, 276 | collate_fn=collate_fn, shuffle=False, drop_last=False, pin_memory=True) 277 | 278 | test_labels = test_data.label.cpu().detach().numpy() 279 | test_preds = np.zeros((len(test_labels), 2), dtype='float32') 280 | 281 | # load saved model 282 | model_path = args.save if training_mode else args.load 283 | if not model_path.endswith('.pt'): 284 | model_path = os.path.join(model_path, '%s_state.pt' % args.name) 285 | print('Loading model %s for eval' % model_path) 286 | 287 | model.load_state_dict(torch.load(model_path, map_location=torch.device(args.device))) 288 | 289 | test_preds += evaluate(model, test_loader, dev, return_scores=True) 290 | 291 | info_dict = {'model_name': args.model, 292 | 'model_params': {'conv_params': conv_params, 'fc_params': fc_params}, 293 | 'lund_ln_kt_min': args.ln_kt_min, 294 | 'lund_ln_delta_min': args.ln_delta_min, 295 | 'date': str(datetime.date.today()), 296 | 'model_path': args.save if training_mode else args.load, 297 | 'model_name': args.name, 298 | 'test_sig': args.test_sig, 299 | 'test_bkg': args.test_bkg} 300 | if training_mode: 301 | info_dict.update({'train_sig': args.train_sig, 302 | 'train_bkg': args.train_bkg}) 303 | 304 | fpr, tpr, threshs = roc_curve(test_labels, test_preds[:, 1], pos_label=1) 305 | # convert into signal and background efficiency 306 | eff_s = tpr 307 | eff_b = 1 - fpr 308 | auc = ROC_area(eff_s, eff_b) 309 | 310 | info_dict['accuracy'] = accuracy(test_preds, test_labels) 311 | info_dict['auc'] = auc 312 | info_dict['inv_bkg_at_sig_50'] = bkg_rejection_at_threshold(eff_s, eff_b, 0.5) 313 | info_dict['inv_bkg_at_sig_30'] = bkg_rejection_at_threshold(eff_s, eff_b, 0.3) 314 | 315 | print(' === Summary ===') 316 | for k in info_dict: 317 | print('%s: %s' % (k, info_dict[k])) 318 | 319 | info_file = os.path.join(path, args.name if training_mode else name) + '_INFO.txt' 320 | with open(info_file, 'w') as f: 321 | for k in info_dict: 322 | f.write('%s: %s\n' % (k, info_dict[k])) 323 | 324 | base_name = name.split('.')[0] 325 | filename = os.path.join(path, base_name) 326 | with open(filename + '_ROC_data.pickle', 'wb') as f: 327 | pickle.dump({'signal_eff': eff_s, 328 | 'background_eff': eff_b, 329 | 'thresholds': threshs, 330 | 'description': str(args)}, f) 331 | 332 | print('Saving ROC data for %s' % base_name) 333 | --------------------------------------------------------------------------------