csa-0.1.0/0000755000514000051400000000000011735363223011623 5ustar mdjmdj00000000000000csa-0.1.0/README0000644000514000051400000001324011735362304012502 0ustar mdjmdj00000000000000This is a demonstration implementation in Python of the Connection-Set Algebra (Djurfeldt, Mikael (2012), Neuroinformatics) * Purpose The CSA library provides elementary connection-sets and operators for combining them. It also provides an iteration interface to such connection-sets enabling efficient iteration over existing connections with a small memory footprint also for very large networks. The CSA can be used as a component of neuronal network simulators or other tools. * License CSA is released under the GNU General Public License * Requirements CSA is dependent on Numpy and Matplotlib * Introduction A connection set is a set of existing connections between a set of source nodes and a set of target nodes. Typically, source and target nodes are neurons in a neuronal network, but targets could also be particular structures of a neuron, such synaptic sites. Sources and targets are enumerated by integers and a connection is represented by a pair of integers, one denoting the source node and one the target node. Source and target can be (and is often) the same set. CSA connection sets are usually infinite. This is a simplification compared to the common situation of finite source and target sets in that the sizes of these sets do not need to be considered. Connection sets can have arbitrary values associated with connections. Pure connection sets without any values associated are called masks. * Getting started ** Basics To get access to the CSA in Python, type: from csa import * The mask representing all possible connections between an infinite source and target set is: full To display a finite portion of the corresponding connectivity matrix, type: show (full) One-to-one connectivity (where source node 0 is connected to target node 0, source 1 to target 1 etc) is represented by the mask oneToOne: show (oneToOne) The default portion displayed by "show" is (0, 29) x (0, 29). (0, 99) x (0, 99) can be displayed using: show (oneToOne, 100, 100) If source and target set is the same, oneToOne describes self-connections. We can use CSA to compute the set of connections consisting of all possible connections except for self-connections using the set difference operator "-": show (full - oneToOne) Finite connection sets can be represented using either lists of connections, with connections represented as tuples: show ([(22, 7), (8, 23)]) or using the Cartesian product of intervals: show (cross (xrange (10), xrange (20))) We can form a finite version of the infinite oneToOne by taking the intersection "*" with a finite connection set: c = cross (xrange (10), xrange (10)) * oneToOne show (c) Finite connection sets can be tabulated: tabulate (c) In Python, finite connection sets provide an iterator interface: for x in cross (xrange (10), xrange (10)) * oneToOne: print x ** Random connectivity and the block operator Connectivity where the existence of each possible connection is determined by a Bernoulli trial with probability p is expressed with the random mask random (p), e.g.: show (random (0.5)) The block operator expands each connection in the operand into a rectangular block in the resulting connection matrix, e.g.: show (block (5,3) * random (0.5)) Note that "*" here means operator application. There is also a quadratic version of the operator: show (block (10) * random (0.7)) Using intersection and set difference, we can now formulate a more complex mask: show (block (10) * random (0.7) * random (0.5) - oneToOne) ** Geometry In CSA, the basic tool to handle distance dependent connectivity is metrics. Metrics are value sets d (i, j). Metrics can be defined through geometry functions. A geometry function maps an index to a position. We can, for example, assign a random position in the unit square to each index: g = random2d (900) The positions of the grid described by g have indices from 0 to 899 and can be displayed like this: gplot2d (g, 900) Alternatively, we can arrange indices in a 30 x 30 grid within the unit square: g = grid2d (30) We can now define the euclidean metric on this grid: d = euclidMetric2d (g) An example of a distance dependent connection set is the disc mask Disc (r) * d which connects each index i to all indices j within a distance d (i, j) < r: c = disc (r) * d To examine the result we can employ the function gplotsel2d (g, c, i) which displays the targets g (j) of i in the connection set c: gplotsel2d (g, c, 434) In the case where the connection set represents a projection between two different coordinate systems, we define one geometry function for each. In the following example g1 is direction in visual space in arc minutes while g2 is position in the cortical representation of the Macaque fovea in mm: g1 = grid2d (30) g2 = grid2d (30, x0 = -7.0, xScale = 8.0, yScale = 8.0) We now define a projection operator which takes visual coordinates into cortical (Dow et al. 1985): import cmath @ProjectionOperator def GvspaceToCx (p): w = 7.7 * cmath.log (complex (p[0] + 0.33, p[1])) return (w.real, w.imag) To see how the grid g1 is transformed into cortical space, we type: gplot2d (GvspaceToCx * g1, 900) The inverse projection is defined: @ProjectionOperator def GcxToVspace (p): c = cmath.exp (complex (p[0], p[1]) / 7.7) - 0.33 return (c.real, c.imag) Real receptive field sizes vary with eccentricity. Assume, for now, that we want to connect each target index to sources within a disc of constant radius. We then need to project back into visual space and use the disc operator: c = disc (0.1) * euclidMetric2d (g1, GcxToVspace * g2) Again, we use gplotsel2d to check the result: gplotsel2d (g2, c, 282) csa-0.1.0/COPYING0000644000514000051400000010451311735362304012661 0ustar mdjmdj00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . csa-0.1.0/MANIFEST.in0000644000514000051400000000005511735362304013360 0ustar mdjmdj00000000000000include setup.py MANIFEST.in include COPYING csa-0.1.0/PKG-INFO0000644000514000051400000000215011735363223012716 0ustar mdjmdj00000000000000Metadata-Version: 1.1 Name: csa Version: 0.1.0 Summary: The Connection-Set Algebra implemented in Python Home-page: http://software.incf.org/software/csa/ Author: Mikael Djurfeldt Author-email: mikael@djurfeldt.com License: GPLv3 Description: The CSA library provides elementary connection-sets and operators for combining them. It also provides an iteration interface to such connection-sets enabling efficient iteration over existing connections with a small memory footprint also for very large networks. The CSA can be used as a component of neuronal network simulators or other tools. Keywords: computational neuroscience modeling connectivity Platform: UNKNOWN Classifier: Development Status :: 2 - Pre-Alpha Classifier: Environment :: Console Classifier: Intended Audience :: Science/Research Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2 Classifier: Topic :: Scientific/Engineering Requires: numpy Requires: matplotlib csa-0.1.0/setup.py0000644000514000051400000000262711735362304013343 0ustar mdjmdj00000000000000#!/usr/bin/env python from distutils.core import setup from csa.version import __version__ long_description = """The CSA library provides elementary connection-sets and operators for combining them. It also provides an iteration interface to such connection-sets enabling efficient iteration over existing connections with a small memory footprint also for very large networks. The CSA can be used as a component of neuronal network simulators or other tools.""" setup ( name = "csa", version = __version__, packages = ['csa',], author = "Mikael Djurfeldt", # add your name here if you contribute to the code author_email = "mikael@djurfeldt.com", description = "The Connection-Set Algebra implemented in Python", long_description = long_description, license = "GPLv3", keywords = "computational neuroscience modeling connectivity", url = "http://software.incf.org/software/csa/", classifiers = ['Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Topic :: Scientific/Engineering'], requires = ['numpy', 'matplotlib'], ) csa-0.1.0/csa/0000755000514000051400000000000011735363223012371 5ustar mdjmdj00000000000000csa-0.1.0/csa/misc.py0000644000514000051400000000230711735362304013677 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import _misc def disc (r): return _misc.Disc (r) def rectangle (width, height): return _misc.Rectangle (width, height) def gaussian (sigma, cutoff): return _misc.Gaussian (sigma, cutoff) def block (M, N = None): return _misc.Block (M, M if N == None else N) transpose = _misc.Transpose () def shift (M, N): return _misc.Shift (M, N) fix = _misc.Fix () def block1 (N): return _misc.Block (N) #del _misc # not for export csa-0.1.0/csa/_misc.py0000644000514000051400000001775411735362304014052 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import math import random import copy import connset as cs import valueset as vs import _elementary from csaobject import * class Random (cs.Operator): def __mul__ (self, valueSet): return ValueSetRandomMask (valueSet) def __call__ (self, p = None, N = None, fanIn = None, fanOut = None): if p != None: assert N == None and fanIn == None and fanOut == None, \ 'inconsistent parameters' return _elementary.ConstantRandomMask (p) elif N != None: assert fanIn == None and fanOut == None, \ 'inconsistent parameters' return _elementary.SampleNRandomOperator (N) elif fanIn != None: assert fanOut == None, \ 'inconsistent parameters' return _elementary.FanInRandomOperator (fanIn) elif fanOut != None: return _elementary.FanOutRandomOperator (fanOut) assert False, 'inconsistent parameters' class ValueSetRandomMask (cs.Mask): def __init__ (self, valueSet): cs.Mask.__init__ (self) self.valueSet = valueSet self.state = random.getstate () def startIteration (self, state): random.setstate (self.state) return self def iterator (self, low0, high0, low1, high1, state): for j in xrange (low1, high1): for i in xrange (low0, high0): if random.random () < self.valueSet (i, j): yield (i, j) def _to_xml (self): return CSAObject.apply ('times', 'random', self.valueSet._to_xml ()) class Disc (cs.Operator): def __init__ (self, r): self.r = r def __mul__ (self, metric): return DiscMask (self.r, metric) class DiscMask (cs.Mask): def __init__ (self, r, metric): cs.Mask.__init__ (self) self.r = r self.metric = metric def iterator (self, low0, high0, low1, high1, state): for j in xrange (low1, high1): for i in xrange (low0, high0): if self.metric (i, j) < self.r: yield (i, j) class Rectangle (cs.Operator): def __init__ (self, width, height): self.width = width self.height = height def __mul__ (self, gFunction): if isinstance (gFunction, tuple): return RectangleMask (self.width, self.height, gFunction[0], gFunction[1]) else: return RectangleMask (self.width, self.height, gFunction, gFunction) class RectangleMask (cs.Mask): def __init__ (self, width, height, g0, g1): cs.Mask.__init__ (self) self.hwidth = width / 2.0 self.hheight = height / 2.0 self.g0 = g0 self.g1 = g1 def iterator (self, low0, high0, low1, high1, state): for j in xrange (low1, high1): for i in xrange (low0, high0): p0 = self.g0 (i) p1 = self.g1 (j) dx = p0[0] - p1[0] dy = p0[1] - p1[1] if abs (dx) < self.hwidth and abs (dy) < self.hheight: yield (i, j) class Gaussian (cs.Operator): def __init__ (self, sigma, cutoff): self.sigma = sigma self.cutoff = cutoff def __mul__ (self, metric): return GaussianValueSet (self, metric) class GaussianValueSet (OpExprValue, vs.ValueSet): def __init__ (self, operator, metric): OpExprValue.__init__ (self, operator, metric) self.sigma22 = 2 * operator.sigma * operator.sigma self.cutoff = operator.cutoff self.metric = metric def __call__ (self, i, j): d = self.metric (i, j) return math.exp (- d * d / self.sigma22) if d < self.cutoff else 0.0 class Block (cs.Operator): def __init__ (self, M, N): self.M = M self.N = N def __mul__ (self, other): c = cs.coerceCSet (other) if isinstance (c, cs.Mask): return BlockMask (self.M, self.N, c) else: return cs.ConnectionSet (BlockCSet (self.M, self.N, c)) class BlockMask (cs.Mask): def __init__ (self, M, N, mask): cs.Mask.__init__ (self) self.M = M self.N = N self.m = mask def iterator (self, low0, high0, low1, high1, state): maskIter = self.m.iterator (low0 / self.M, (high0 + self.M - 1) / self.M, low1 / self.N, (high1 + self.N - 1) / self.N, state) try: pre = [] (i, j) = maskIter.next () while True: # collect connections in one connection matrix column post = j while j == post: pre.append (i) (i, j) = maskIter.next () # generate blocks for the column for jj in xrange (max (self.N * post, low1), min (self.N * (post + 1), high1)): for k in pre: for ii in xrange (max (self.M * k, low0), min (self.M * (k + 1), high0)): yield (ii, jj) pre = [] except StopIteration: if pre: # generate blocks for the last column for jj in xrange (max (self.N * post, low1), min (self.N * (post + 1), high1)): for k in pre: for ii in xrange (max (self.M * k, low0), min (self.M * (k + 1), high0)): yield (ii, jj) class Transpose (cs.Operator): def __mul__ (self, other): c = cs.coerceCSet (other) if isinstance (c, cs.Mask): return other.transpose () else: return cs.ConnectionSet (other.transpose ()) class Shift (cs.Operator): def __init__ (self, M, N): self.M = M self.N = N def __mul__ (self, other): c = cs.coerceCSet (other) if isinstance (c, cs.Mask): return other.shift (self.M, self.N) else: return cs.ConnectionSet (other.shift (self.M, self.N)) class Fix (cs.Operator): def __mul__ (self, other): c = cs.coerceCSet (other) if isinstance (c, cs.Mask): return FixedMask (other) else: return cs.ConnectionSet (FixedCSet (other)) class FixedMask (cs.FiniteMask): def __init__ (self, mask): cs.FiniteMask.__init__ (self) ls = [] for c in mask: ls.append (c) self.connections = ls targets = map (cs.target, ls) self.low0 = min (ls)[0] self.high0 = max (ls)[0] + 1 self.low1 = min (targets) self.high1 = max (targets) + 1 def iterator (self, low0, high0, low1, high1, state): if not self.isBoundedBy (low0, high0, low1, high1): return iter (self.connections) else: return self.boundedIterator (low0, high0, low1, high1) def boundedIterator (self, low0, high0, low1, high1): for c in self.connections: if low0 <= c[0] and c[0] < high0 \ and low1 <= c[1] and c[1] < high1: yield c csa-0.1.0/csa/valueset.py0000644000514000051400000001500111735362304014567 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # from csaobject import * class ValueSet (CSAObject): def __init__ (self): CSAObject.__init__ (self, "valueset") def __neg__ (self): return GenericValueSet (lambda i, j: - self (i, j)) def __add__ (self, other): if not callable (other): return maybeAffine (other, 1.0, self) elif isinstance (other, (QuotedValueSet, AffineValueSet)): return other.__add__ (self) elif isinstance (other, GenericValueSet): return GenericValueSet (lambda i, j: self (i, j) + other.function (i, j)) else: return GenericValueSet (lambda i, j: self (i, j) + other (i, j)) def __radd__ (self, other): return self.__add__ (other) def __sub__ (self, other): return self.__add__ (- other) def __rsub__ (self, other): return self.__neg__ ().__add__ (other) def __mul__ (self, other): if not callable (other): return maybeAffine (0.0, other, self) elif isinstance (other, (QuotedValueSet, AffineValueSet)): return other.__mul__ (self) elif isinstance (other, GenericValueSet): return GenericValueSet (lambda i, j: self (i, j) * other.function (i, j)) else: return GenericValueSet (lambda i, j: self (i, j) * other (i, j)) def __rmul__ (self, other): return self.__mul__ (other) class QuotedValueSet (ValueSet): def __init__ (self, expression): ValueSet.__init__ (self) self.expression = expression def __call__ (self, i, j): return self.expression def __neg__ (self): return QuotedValueSet (- self.expression) def __add__ (self, other): if not callable (other): return QuotedValueSet (self.expression + other) elif isinstance (other, QuotedValueSet): return QuotedValueSet (self.expression + other.expression) elif isinstance (other, AffineValueSet): return other.__add__ (self) else: return maybeAffine (self.expression, 1.0, other) def __mul__ (self, other): if not callable (other): return QuotedValueSet (self.expression * other) elif isinstance (other, QuotedValueSet): return QuotedValueSet (self.expression * other.expression) elif isinstance (other, AffineValueSet): return other.__mul__ (self) else: return maybeAffine (0.0, self.expression, other) class GenericValueSet (ValueSet): def __init__ (self, function): ValueSet.__init__ (self) self.function = function def __call__ (self, i, j): return self.function (i, j) def __neg__ (self): return GenericValueSet (lambda i, j: - self.function (i, j)) def __add__ (self, other): if not callable (other): return maybeAffine (other, 1.0, self.function) elif isinstance (other, (QuotedValueSet, AffineValueSet)): return other.__add__ (self) elif isinstance (other, GenericValueSet): return GenericValueSet (lambda i, j: self.function (i, j) + other.function (i, j)) else: return GenericValueSet (lambda i, j: self.function (i, j) + other (i, j)) def __mul__ (self, other): if not callable (other): return maybeAffine (0.0, other, self.function) elif isinstance (other, (QuotedValueSet, AffineValueSet)): return other.__mul__ (self) elif isinstance (other, GenericValueSet): return GenericValueSet (lambda i, j: self.function (i, j) * other.function (i, j)) else: return GenericValueSet (lambda i, j: self.function (i, j) * other (i, j)) class AffineValueSet (ValueSet): def __init__ (self, constant, coefficient, function): ValueSet.__init__ (self) self.const = constant self.coeff = coefficient self.func = function def __call__ (self, i, j): return self.const + self.coeff * self.func (i, j) def __neg__ (self): return maybeAffine (- self.const, - self.coeff, self.func) def __add__ (self, other): if not callable (other): return maybeAffine (self.const + other, self.coeff, self.func) elif isinstance (other, QuotedValueSet): return maybeAffine (self.const + other.expression, self.coeff, self.func) elif isinstance (other, AffineValueSet): f = lambda i, j: \ self.const * self.func (i, j) \ + other.const * other.func (i, j) return maybeAffine (self.const + other.const, 1.0, f) def __mul__ (self, other): if not callable (other): return maybeAffine (self.const * other, self.coeff * other, self.func) elif isinstance (other, QuotedValueSet): return maybeAffine (self.const * other.expression, self.coeff * other.expression, self.func) elif isinstance (other, AffineValueSet): f = lambda i, j: \ other.const * self.coeff * self.func (i, j) \ + self.const * other.coeff * other.func (i, j) \ + self.coeff * other.coeff \ * self.func (i, j) * other.func (i, j) return maybeAffine (self.const * other.const, 1.0, f) def maybeAffine (const, coeff, func): if coeff == 0.0: return QuotedValueSet (const) elif const == 0.0 and coeff == 1.0: return GenericValueSet (func) else: return AffineValueSet (const, coeff, func) csa-0.1.0/csa/intervalset.py0000644000514000051400000003137511735362304015313 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import sys from csaobject import * infinity = sys.maxint - 1 # Interval sets are represented as ordered lists of closed intervals # class IntervalSet (CSAObject): tag = 'intervalset' @staticmethod # return true if tuple i represents a well-formed interval def goodInterval (i): return len (i) == 2 \ and isinstance (i[0], int) \ and isinstance (i[1], int) \ and i[0] <= i[1] @staticmethod def xrangeToIntervals (x): if not x: return [] elif len (x) == 1: return [(x[0], x[0])] elif x[1] - x[0] == 1: return [(x[0], x[-1])] else: return ((e, e) for e in x) @staticmethod def coerce (s): if not isinstance (s, list): s = [ s ] res = [] for x in s: if isinstance (x, tuple): assert IntervalSet.goodInterval (x), 'malformed interval' res.append (x) elif isinstance (x, int): res.append ((x, x)) elif isinstance (x, xrange): res += IntervalSet.xrangeToIntervals (x) else: raise TypeError, "can't interpret element as interval" s = res s.sort () # merge intervals # by construction we know that i[0] <= i[1] for i in s res = [] N = 0 if s: lastLower = s[0][0] lastUpper = s[0][1] assert lastLower >= 0, 'only positive values allowed' for i in s[1:]: assert lastLower < i[0] and lastUpper < i[0], 'intervals overlap' if i[0] - lastUpper == 1: lastUpper = i[1] else: res.append ((lastLower, lastUpper)) N += 1 + lastUpper - lastLower lastLower = i[0] lastUpper = i[1] res.append ((lastLower, lastUpper)) N += 1 + lastUpper - lastLower return (res, N) def __init__ (self, s = [], intervals = None, nIntegers = None): if intervals: self.intervals = intervals self.nIntegers = nIntegers else: (self.intervals, self.nIntegers) = self.coerce (s) def repr (self): return 'IntervalSet(%r)' % self.intervals def __len__ (self): return self.nIntegers def __contains__ (self, n): for i in self.intervals: if n > i[1]: continue elif n >= i[0]: return True else: return False return False def __iter__ (self): for i in self.intervals: for e in xrange (i[0], i[1] + 1): yield e def __invert__ (self): return ComplementaryIntervalSet (intervals = self.intervals, \ nIntegers = self.nIntegers) def __add__ (self, other): if not isinstance (other, IntervalSet): other = IntervalSet (other) return self.union (other) def __radd__ (self, other): return IntervalSet (other).union (self) def __sub__ (self, other): if not isinstance (other, IntervalSet): other = IntervalSet (other) return self.intersection (~other) def __rsub__ (self, other): return IntervalSet (other).intersection (~self) def __mul__ (self, other): if not isinstance (other, IntervalSet): other = IntervalSet (other) return self.intersection (other) def __rmul__ (self, other): return IntervalSet (other).intersection (self) def finite (self): return True def shift (self, N): if not self or N == 0: return self intervals = [] nIntegers = self.nIntegers for (i, j) in self.intervals: i += N j += N if i >= 0: intervals.append ((i, j)) elif j >= 0: intervals.append ((0, j)) nIntegers += i return IntervalSet (intervals = intervals, nIntegers = nIntegers) def intervalIterator (self): return iter (self.intervals) def boundedIterator (self, low, high): iterator = iter (self.intervals) i = iterator.next () while i[1] < low: i = iterator.next () while i[0] < high: for e in xrange (max (low, i[0]), min (i[1] + 1, high)): yield e i = iterator.next () def count (self, low, high): iterator = iter (self.intervals) c = 0 try: i = iterator.next () while i[1] < low: i = iterator.next () while i[0] < high: c += min (i[1] + 1, high) - max (low, i[0]) i = iterator.next () except StopIteration: pass return c def min (self): return self.intervals[0][0] def max (self): return self.intervals[-1][1] def intersection (self, other): res = [] N = 0 iter0 = self.intervalIterator () iter1 = other.intervalIterator () try: i0 = iter0.next () i1 = iter1.next () while True: if i0[1] <= i1[1]: if i0[1] >= i1[0]: lower = max (i0[0], i1[0]) res.append ((lower, i0[1])) N += 1 + i0[1] - lower i0 = iter0.next () else: if i1[1] >= i0[0]: lower = max (i0[0], i1[0]) res.append ((lower, i1[1])) N += 1 + i1[1] - lower i1 = iter1.next () except StopIteration: pass iset = IntervalSet () iset.intervals = res iset.nIntegers = N return iset def union (self, other): if isinstance (other, ComplementaryIntervalSet): return ~(~self).intersection (~other) iset = IntervalSet () if not other.nIntegers: iset.intervals = list (self.intervals) iset.nIntegers = self.nIntegers return iset if not self.nIntegers: iset.intervals = list (other.intervals) iset.nIntegers = other.nIntegers return iset res = [] N = 0 iter0 = self.intervalIterator () iter1 = other.intervalIterator () i0 = iter0.next () i1 = iter1.next () if i0[0] <= i1[0]: (lower, upper) = i0 else: (lower, upper) = i1 try: while True: if i0[0] <= i1[0]: if i0[0] <= upper + 1: if i0[1] > upper: upper = i0[1] else: res.append ((lower, upper)) N += 1 + upper - lower (lower, upper) = i0 try: i0 = iter0.next () except StopIteration: if i1[0] <= upper + 1: if i1[1] > upper: upper = i1[1] i1 = (lower, upper) else: res.append ((lower, upper)) N += 1 + upper - lower while True: res.append (i1) N += 1 + i1[1] - i1[0] i1 = iter1.next () else: if i1[0] <= upper + 1: if i1[1] > upper: upper = i1[1] else: res.append ((lower, upper)) N += 1 + upper - lower (lower, upper) = i1 try: i1 = iter1.next () except StopIteration: if i0[0] <= upper + 1: if i0[1] > upper: upper = i0[1] i0 = (lower, upper) else: res.append ((lower, upper)) N += 1 + upper - lower while True: res.append (i0) N += 1 + i0[1] - i0[0] i0 = iter0.next () except StopIteration: pass iset.intervals = res iset.nIntegers = N return iset def _to_xml (self): intervals = [ E ('interval', E ('cn', str (i)), E ('cn', str (j))) for (i, j) in self.intervals ] return E (IntervalSet.tag, *intervals) @classmethod def from_xml (cls, element, env = {}): intervals = [] for ivalElement in element.getchildren (): ival = ivalElement.getchildren () intervals.append ((int (ival[0].text), int (ival[1].text))) return IntervalSet (intervals) CSAObject.tag_map[CSA + IntervalSet.tag] = (IntervalSet, CUSTOM) class ComplementaryIntervalSet (IntervalSet): def __init__ (self, s = [], intervals = None, nIntegers = None): IntervalSet.__init__ (self, s, intervals, nIntegers) def repr (self): if not self.intervals: return 'N' else: return '~IntervalSet(%r)' % self.intervals def __nonzero__ (self): return True def __len__ (self): raise RuntimeError, 'ComplementaryIntervalSet has infinite length' def __contains__ (self, n): for i in self.intervals: if n < i[0]: continue elif n <= i[1]: return False else: return True return True def __iter__ (self): raise RuntimeError, "can't interate over ComplementaryIntervalSet" def __invert__ (self): return IntervalSet (intervals = self.intervals, \ nIntegers = self.nIntegers) def finite (self): return False def shift (self, N): iset = IntervalSet (intervals = self.intervals, \ nIntegers = self.nIntegers).shift (N) return ComplementaryIntervalSet (intervals = iset.intervals, \ nIntegers = iset.nIntegers) def intervalIterator (self): start = 0 for i in self.intervals: if i[0] > 0: yield (start, i[0] - 1) start = i[1] + 1 yield (start, infinity) def boundedIterator (self, low, high): raise RuntimeError, "can't interate over ComplementaryIntervalSet" def count (self, low, high): iterator = iter (self.intervals) c = 0 prev = low try: i = iterator.next () while i[1] < low: i = iterator.next () while i[0] < high: c += i[0] - prev prev = i[1] + 1 i = iterator.next () except StopIteration: pass if prev < high: c += high - prev return c def min (self): if not self.intervals or self.intervals[0][0] > 0: return 0 else: return self.intervals[0][1] + 1 def max (self): raise RuntimeError, 'the maximum of a ComplementaryIntervalSet is infinity' def intersection (self, other): if isinstance (other, ComplementaryIntervalSet): return ~(~self).union (~other) else: return IntervalSet.intersection (self, other) def union (self, other): return ~(~self).intersection (~other) def _to_xml (self): if not self.intervals: return E ('N') else: return E ('apply', E ('complement'), IntervalSet._to_xml (self)) N = ComplementaryIntervalSet ([]) CSAObject.tag_map[CSA + 'N'] = (N, SINGLETON) csa-0.1.0/csa/closure.py0000644000514000051400000000316011735362304014416 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # from csaobject import * import inspect try: from lxml import etree from lxml.builder import E except ImportError: pass class Closure (CSAObject): tag = 'closure' name = tag def __init__ (self, formals, e): self.formals = formals self.etree = e @staticmethod def formalToXML (formal): return E ('bvar', E ('ci', formal)) def _to_xml (self): formals = map (Closure.formalToXML, self.formals) return E ('bind', E ('closure'), *formals + [ self.etree ]) def __call__ (self, *args): assert len (args) == len (self.formals), "arguments %s don't match formals %s" % (args, self.formals) bindings = {} for (formal, arg) in map (None, self.formals, args): bindings[formal] = arg return CSAObject.from_xml (self.etree, bindings) registerTag (Closure.tag, Closure, BINDOPERATOR) csa-0.1.0/csa/plot.py0000644000514000051400000000607611735362304013731 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import numpy as _numpy import matplotlib import matplotlib.pyplot as _plt import elementary # This function was autogenerated by boilerplate.py. Do not edit as # changes will be lost def inverseGray(): ''' set the default colormap to gray and apply to current image if any. See help(colormaps) for more information ''' _plt.rc('image', cmap='gray_r') im = _plt.gci() if im is not None: im.set_cmap(_plt.cm.gray_r) _plt.draw_if_interactive() def show (cset, N0 = 30, N1 = None): N1 = N0 if N1 == None else N1 _plt.clf () _plt.axis ('equal') a = _numpy.zeros ((N0, N1)) for (i, j) in elementary.cross (xrange (N0), xrange (N1)) * cset: a[i,j] += 1.0 _plt.imshow (a, interpolation='nearest') _plt.show () def gplotsel2d (g, cset, source = elementary.N, target = elementary.N, N0 = 900, N1 = None, value = None, range=[], lines = True): N1 = N0 if N1 == None else N1 _plt.clf () _plt.axis ('equal') gplot2d (g, N1, color = 'grey', show = False) cset = elementary.cross (source, target) * cset N = len (cset) if lines: marker = 'ro-' else: marker = 'ro' if elementary.arity (cset): if value != None: if range: normalize = matplotlib.colors.Normalize (*range) else: normalize = matplotlib.colors.Normalize () normalize.autoscale ([v[value] for (i, j, v) in cset.c]) cmap = matplotlib.cm.get_cmap () for (i, j, v) in cset.c: color = cmap (normalize (v[value])) _plt.plot ([g (i)[0], g (j)[0]], [g (i)[1], g (j)[1]], \ marker, color = color, mfc = color) else: for (i, j, v) in cset.c: _plt.plot ([g (i)[0], g (j)[0]], [g (i)[1], g (j)[1]], marker) else: for (i, j) in cset: _plt.plot ([g (i)[0], g (j)[0]], [g (i)[1], g (j)[1]], marker) _plt.show () def gplot2d (g, N, color = None, show = True): if show: _plt.clf () _plt.axis ('equal') x = [] y = [] for i in xrange (0, N): pos = g (i) x.append (pos[0]) y.append (pos[1]) if color != None: _plt.plot (x, y, 'o', color = color) else: _plt.plot (x, y, 'bo') if show: _plt.show () #del numpy, plt csa-0.1.0/csa/_elementary.py0000644000514000051400000002604211735362304015252 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import random import numpy import copy import connset as cs import intervalset as iset from csaobject import * class FullMask (cs.IntervalSetMask): tag = 'full' def __init__ (self): cs.IntervalSetMask.__init__ (self, iset.N, iset.N) self.name = FullMask.tag CSAObject.tag_map[CSA + FullMask.tag] = (self, SINGLETON) def __call__ (self, N0, N1 = None): if N1 == None: N1 = N0 return cs.FiniteISetMask (iset.IntervalSet ((0, N0 - 1)), \ iset.IntervalSet ((0, N1 - 1))) class OneToOne (cs.Mask): tag = 'oneToOne' def __init__ (self): cs.Mask.__init__ (self) self.name = OneToOne.tag CSAObject.tag_map[CSA + OneToOne.tag] = (self, SINGLETON) def iterator (self, low0, high0, low1, high1, state): for i in xrange (max (low0, low1), min (high0, high1)): yield (i, i) class ConstantRandomMask (cs.Mask): tag = 'randomMask' def __init__ (self, p): cs.Mask.__init__ (self) self.p = p self.state = random.getstate () self.name = ConstantRandomMask.tag def startIteration (self, state): random.setstate (self.state) return self def iterator (self, low0, high0, low1, high1, state): for j in xrange (low1, high1): for i in xrange (low0, high0): if random.random () < self.p: yield (i, j) def repr (self): return 'random(%s)' % self.p def _to_xml (self): return CSAObject.apply (ConstantRandomMask.tag, self.p) registerTag (ConstantRandomMask.tag, ConstantRandomMask, 1) class SampleNRandomOperator (cs.Operator): tag = 'random_N' def __init__ (self, N): self.N = N def __mul__ (self, other): assert isinstance (other, cs.Finite) \ and isinstance (other, cs.Mask), \ 'expected finite mask' return SampleNRandomMask (self.N, other) def repr (self): return 'random(N = %s)' % self.N def _to_xml (self): return CSAObject.apply (SampleNRandomOperator.tag, self.N) registerTag (SampleNRandomOperator.tag, SampleNRandomOperator, 1) class SampleNRandomMask (cs.Finite,cs.Mask): # The algorithm based on first sampling the number of connections # per partition has been arrived at through discussions with Hans # Ekkehard Plesser. # def __init__ (self, N, mask): cs.Mask.__init__ (self) self.N = N assert isinstance (mask, cs.FiniteISetMask), \ 'SampleNRandomMask currently only operates on FiniteISetMask:s' self.mask = mask self.randomState = random.getstate () self.npRandomState = numpy.random.get_state () def bounds (self): return self.mask.bounds () def startIteration (self, state): obj = copy.copy (self) # local state: N, N0, perTarget, sources random.setstate (self.randomState) obj.isPartitioned = False if 'partitions' in state: obj.isPartitioned = True partitions = map (self.mask.intersection, state['partitions']) sizes = map (len, partitions) total = sum (sizes) # The following yields the same result on all processes. # We should add a seed function to the CSA. if 'seed' in state: seed = state['seed'] else: seed = 'SampleNRandomMask' numpy.random.seed (hash (seed)) N = numpy.random.multinomial (self.N, numpy.array (sizes) \ / float (total)) obj.N = N[state['selected']] obj.mask = partitions[state['selected']] assert isinstance (obj.mask, cs.FiniteISetMask), \ 'SampleNRandomMask iterator only handles finite IntervalSetMask partitions' obj.mask = obj.mask.startIteration (state) obj.N0 = len (obj.mask.set0) obj.lastBound0 = False N1 = len (obj.mask.set1) numpy.random.set_state (self.npRandomState) obj.perTarget = numpy.random.multinomial (obj.N, [1.0 / N1] * N1) return obj def iterator (self, low0, high0, low1, high1, state): m = self.mask.set1.count (0, low1) if self.isPartitioned and m > 0: # "replacement" for a proper random.jumpahead (n) # This is required so that different partitions of this # mask aren't produced using the same stream of random # numbers. random.seed (random.getrandbits (32) + m) if self.lastBound0 != (low0, high0): self.lastBound0 = (low0, high0) self.sources = [] for i in self.mask.set0.boundedIterator (low0, high0): self.sources.append (i) nSources = len (self.sources) for j in self.mask.set1.boundedIterator (low1, high1): s = [] for k in xrange (0, self.perTarget[m]): i = random.randint (0, self.N0 - 1) if i < nSources: s.append (self.sources[i]) s.sort () for i in s: yield (i, j) m += 1 def repr (self): return self._repr_applyop ('random(N=%s)' % self.N, self.mask) def _to_xml (self): return E ('apply', E ('times'), CSAObject.apply (SampleNRandomOperator.tag, self.N), self.mask._to_xml ()) class FanInRandomOperator (cs.Operator): tag = 'random_fanIn' def __init__ (self, fanIn): self.fanIn = fanIn def __mul__ (self, other): assert isinstance (other, cs.Finite) \ and isinstance (other, cs.Mask), \ 'expected finite mask' return FanInRandomMask (self.fanIn, other) def repr (self): return 'random(fanIn=%s)' % self.fanIn def _to_xml (self): return CSAObject.apply (FanInRandomOperator.tag, self.fanIn) registerTag (FanInRandomOperator.tag, FanInRandomOperator, 1) # This code is copied and modified from SampleNRandomMask # *fixme* refactor code and eliminate code duplication class FanInRandomMask (cs.Finite, cs.Mask): # The algorithm based on first sampling the number of connections # per partition has been arrived at through discussions with Hans # Ekkehard Plesser. # def __init__ (self, fanIn, mask): cs.Mask.__init__ (self) self.fanIn = fanIn assert isinstance (mask, cs.FiniteISetMask), \ 'FanInRandomMask currently only operates on FiniteISetMask:s' self.mask = mask self.randomState = random.getstate () def bounds (self): return self.mask.bounds () def startIteration (self, state): obj = copy.copy (self) # local state: N, N0, perTarget, sources random.setstate (self.randomState) obj.isPartitioned = False if 'partitions' in state: obj.isPartitioned = True partitions = map (self.mask.intersection, state['partitions']) # The following yields the same result on all processes. # We should add a seed function to the CSA. if 'seed' in state: seed = state['seed'] else: seed = 'FanInRandomMask' # Numpy.random.seed requires unsigned integer numpy.random.seed (abs (hash (seed))) selected = state['selected'] obj.mask = partitions[selected] assert isinstance (obj.mask, cs.FiniteISetMask), \ 'FanInRandomMask iterator only handles finite IntervalSetMask partitions' obj.mask = obj.mask.startIteration (state) obj.N0 = len (obj.mask.set0) obj.lastBound0 = False if obj.isPartitioned: obj.perTarget = [] for j in obj.mask.set1: size = 0 sourceDist = numpy.zeros (len (partitions)) for k in xrange (len (partitions)): if j in partitions[k].set1: sourceDist[k] = len (partitions[k].set0) sourceDist /= sum (sourceDist) dist = numpy.random.multinomial (self.fanIn, sourceDist) obj.perTarget.append (dist[selected]) else: obj.perTarget = [self.fanIn] * len (obj.mask.set1) return obj def iterator (self, low0, high0, low1, high1, state): m = self.mask.set1.count (0, low1) if self.isPartitioned and m > 0: # "replacement" for a proper random.jumpahead (n) # This is required so that different partitions of this # mask aren't produced using the same stream of random # numbers. random.seed (random.getrandbits (32) + m) if self.lastBound0 != (low0, high0): self.lastBound0 = (low0, high0) self.sources = [] for i in self.mask.set0.boundedIterator (low0, high0): self.sources.append (i) nSources = len (self.sources) for j in self.mask.set1.boundedIterator (low1, high1): s = [] for k in xrange (0, self.perTarget[m]): i = random.randint (0, self.N0 - 1) if i < nSources: s.append (self.sources[i]) s.sort () for i in s: yield (i, j) m += 1 def repr (self): return self._repr_applyop ('random(fanIn=%s)' % self.fanIn, self.mask) def _to_xml (self): return E ('apply', E ('times'), CSAObject.apply (FanInRandomOperator.tag, self.fanIn), self.mask._to_xml ()) class FanOutRandomOperator (cs.Operator): tag = 'random_fanOut' def __init__ (self, fanOut): self.fanOut = fanOut def __mul__ (self, other): assert isinstance (other, cs.Finite) \ and isinstance (other, cs.Mask), \ 'expected finite mask' return FanInRandomMask (self.fanOut, other.transpose ()).transpose () def repr (self): return 'random(fanOut=%s)' % self.fanOut def _to_xml (self): return CSAObject.apply (FanOutRandomOperator.tag, self.fanOut) registerTag (FanOutRandomOperator.tag, FanOutRandomOperator, 1) csa-0.1.0/csa/__init__.py0000644000514000051400000000203211735362304014476 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # from version import __version__ from connset import Mask from connset import ConnectionSet from elementary import * #from operators import * #from arithmetic import * from misc import * from geometry import * from csaobject import parse, from_xml from plot import * from closure import * from conngen import * csa-0.1.0/csa/elementary.py0000644000514000051400000000460011735362304015107 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import sys as _sys import intervalset as _iset import connset as _cs import valueset as _vs import _elementary import _misc from csaobject import registerTag # Connection-Set constructor # def cset (mask, *valueSets): if valueSets: c = _cs.ExplicitCSet (mask, *valueSets) return _cs.ConnectionSet (c) else: return mask registerTag (_cs.CSet.tag, cset, 1) # Selectors # def mask (obj): cset = _cs.coerceCSet (obj) return cset.mask () def value (obj, k): assert isinstance (obj, _cs.ConnectionSet), 'expected connection-set' return obj.c.value (k) def arity (obj): if isinstance (obj, _cs.ConnectionSet): return obj.c.arity else: return 0 # Value-set constructor # def vset (obj): if not callable (obj): return _vs.QuotedValueSet (obj) else: return _vs.GenericValueSet (obj) # Intervals # def ival (beg, end): return _iset.IntervalSet ((beg, end)) N = _iset.N # Cartesian product # def cross (set0, set1): return _cs.intervalSetMask (set0, set1) # Elementary masks # empty = cross ([], []) full = _elementary.FullMask () oneToOne = _elementary.OneToOne () random = _misc.Random () # Support for parallel simulator # def partition (c, masks, selected, seed = None): if isinstance (c, _cs.Mask): return _cs.MaskPartition (c, masks, selected, seed) elif isinstance (c, _cs.ConnectionSet): return _cs.ConnectionSet (_cs.CSetPartition (c, masks, selected, seed)) # Utilities # def tabulate (c): for x in c: print x[0], for e in x[1:]: print '\t', e, print #del _elementary, cs, sys # not for export csa-0.1.0/csa/connset.py0000644000514000051400000010257011735362304014420 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import copy import intervalset import valueset from csaobject import * # This is the fundamental connection-set class # which is also the base class for masks # class CSet (CSAObject): tag = 'cset' def __init__ (self, mask, *valueSets): CSAObject.__init__ (self, "icset"); self._mask = mask self.valueSets = list (valueSets) self.arity = len (self.valueSets) def repr (self, name = None): if self.arity: if not name: name = self.name vreprs = [] for k in xrange (self.arity): v = self.value (k) if isinstance (v, CSAObject): vreprs += ", %s" % v.repr () else: vreprs += ", %s" % v return "%s (%s%s)" % (self.name, self.mask (), "".join (vreprs)) else: if self.mask () == self: return self.name else: return "%s (%s)" % (self.name, self.mask ()) def mask (self): #*fixme* remove this condition? if self._mask == None: self._mask = self.makeMask () return self._mask def value (self, k): if self.valueSets[k] == None: self.valueSets[k] = self.makeValueSet (k) return self.valueSets[k] def makeValueSet (self, k): if isFinite (self.mask ()): return self.makeFiniteValueSet (k, self.mask ().bounds ()) raise RuntimeError, "don't know how to return value set for this connection-set" def makeFiniteValueSet (self, k, bounds): raise RuntimeError, "don't know how to return value set for this connection-set" def __len__ (self): return len (self.mask ()) def __iter__ (self): # this code is used for full connection sets if isFinite (self.mask ()): state = State () obj = self.startIteration (state) (low0, high0, low1, high1) = self.bounds () return obj.iterator (low0, high0, low1, high1, state) else: raise RuntimeError, 'attempt to retrieve iterator over infinite connection-set' def bounds (self): return self.mask ().bounds () def startIteration (self, state): obj = copy.copy (self) obj._mask = self.mask ().startIteration (state) return obj def iterator (self, low0, high0, low1, high1, state): for (i, j) in self._mask.iterator (low0, high0, low1, high1, state): yield (i, j, [ v (i, j) for v in self.valueSets ]) def multisetSum (self, other): return CSetMultisetSum (self, other) def intersection (self, other): assert isinstance (other, Mask), 'expected Mask operand' return SubCSet (self, self.mask ().intersection (other), *self.valueSets) def difference (self, other): assert isinstance (other, Mask), 'expected Mask operand' return SubCSet (self, self.mask ().difference (other), *self.valueSets) # This is the connection-set wrapper class which has as its only purpose # to wrap non mask connection-sets so that the same code can implement # connection-sets of different arity. Some type dispatch is also done here. # class ConnectionSet (CSAObject): def __init__ (self, c): CSAObject.__init__ (self, "cset") self.c = c def repr (self): return self.c.repr () def __len__ (self): return len (self.c) def __iter__ (self): return ConnectionSet.iterators[self.c.arity] (self) def iter0 (self): assert False, 'Should not have executed ConnectionSet.iter0' def iter1 (self): for (i, j, vs) in iter (self.c): (v0,) = vs yield (i, j, v0) def iter2 (self): for (i, j, vs) in iter (self.c): (v0, v1) = vs yield (i, j, v0, v1) def iter3 (self): for (i, j, vs) in iter (self.c): (v0, v1, v2) = vs yield (i, j, v0, v1, v2) def __add__ (self, other): if isNumber (other): return ConnectionSet (self.c.addScalar (other)) else: return ConnectionSet (self.c.multisetSum (coerceCSet (other))) def __radd__ (self, other): return self.__add__ (other) def __sub__ (self, other): if isNumber (other): return ConnectionSet (self.c.addScalar (- other)) else: return ConnectionSet (self.c.difference (coerceCSet (other))) def __rsub__ (self, other): return ConnectionSet (self.c.__neg__ ().addScalar (other)) def __mul__ (self, other): if isNumber (other): return ConnectionSet (self.c.mulScalar (other)) else: return ConnectionSet (self.c.intersection (coerceCSet (other))) def __rmul__ (self, other): return self.__mul__ (other) ConnectionSet.iterators = [ ConnectionSet.iter0, \ ConnectionSet.iter1, \ ConnectionSet.iter2, \ ConnectionSet.iter3 ] # Some helper functions def source (x): return x[0] def target (x): return x[1] def isNumber (x): return isinstance (x, (int, long, float, complex)) def coerceCSet (obj): if isinstance (obj, list): return ExplicitMask (obj) elif isinstance (obj, ConnectionSet): return obj.c assert isinstance (obj, Mask), 'expected connection-set' return obj def valueSet (obj): return valueset.QuotedValueSet (obj) def coerceValueSet (obj): if callable (obj): return obj else: return valueSet (obj) def isFinite (x): return isinstance (x, Finite) def isEmpty (x): iterator = iter (x.mask ()) try: iterator.next () return False except StopIteration: return True def transpose (obj): return obj.transpose () # This is the fundamental mask class # class Mask (CSet): def __init__ (self): CSet.__init__ (self, self) def __len__ (self): N = 0 for c in self: N += 1 return N def __iter__ (self): raise RuntimeError, 'attempt to retrieve iterator over infinite mask' def __add__ (self, other): return self.multisetSum (other) def __sub__ (self, other): return self.difference (other) def __mul__ (self, other): if isinstance (other, Mask): return self.intersection (other) elif isinstance (other, list): return self.intersection (ExplicitMask (other)) elif isinstance (other, ConnectionSet): return other.__mul__ (self) else: return NotImplemented def __rmul__ (self, other): if isinstance (other, list): return self.intersection (ExplicitMask (other)) else: return NotImplemented def __invert__ (self): return self.complement () def transpose (self): assert isFinite (self), \ 'transpose currently only supports finite masks' return TransposedMask (self) def shift (self, M, N): return shiftedMask (self, M, N) def startIteration (self, state): # default action: return self def iterator (self, low0, high0, low1, high1, state): return NotImplemented def multisetSum (self, other): if isFinite (self) and isFinite (other): return FiniteMaskMultisetSum (self, other) else: return MaskMultisetSum (self, other) def intersection (self, other): # IntervalSetMask implements a specialized version of intersection if isinstance (other, IntervalSetMask): return other.intersection (self) # Generate Finite instances if either operand is finite elif isFinite (self): return FiniteMaskIntersection (self, other) elif isFinite (other): return FiniteMaskIntersection (other, self) else: return MaskIntersection (self, other) def complement (self): return MaskComplement (self) def difference (self, other): return MaskDifference (self, other) class Finite (object): def bounds (self): return NotImplemented def maxBounds (self, b1, b2): return (min (b1[0], b2[0]), max (b1[1], b2[1]), min (b1[2], b2[2]), max (b1[3], b2[3])) def __iter__ (self): state = State () obj = self.startIteration (state) (low0, high0, low1, high1) = self.bounds () return obj.iterator (low0, high0, low1, high1, state) class FiniteMask (Finite, Mask): def __init__ (self): Mask.__init__ (self) self.low0 = 0 self.high0 = 0 self.low1 = 0 self.high1 = 0 def bounds (self): return (self.low0, self.high0, self.low1, self.high1) def isBoundedBy (self, low0, high0, low1, high1): return low0 > self.low0 or high0 < self.high0 \ or low1 > self.low1 or high1 < self.high1 # not used class NoParIterator (): def __init__ (self): self.subIterator = False def iterator (self, low0, high0, low1, high1, state): print low0, high0, low1, high1 if not self.subIterator: self.subIterator = self.noParIterator (state) self.lastC = self.subIterator.next () c = self.lastC while c[1] < low1: c = self.subIterator.next () while c[1] < high1: j = c[1] while c[1] == j and c[0] < low0: c = self.subIterator.next () while c[1] == j and c[0] < high0: yield c c = self.subIterator.next () while c[1] == j: c = self.subIterator.next () self.lastC = c class BinaryMask (BinaryCSAObject, Mask): def __init__ (self, operator, op1, op2, precedence): Mask.__init__ (self) BinaryCSAObject.__init__ (self, operator, op1, op2, precedence) def startIteration (self, state): obj = copy.copy (self) obj.op1 = self.op1.startIteration (state) obj.op2 = self.op2.startIteration (state) return obj class MaskIntersection (BinaryMask): def __init__ (self, op1, op2): BinaryMask.__init__ (self, '*', op1, op2, 1) def iterator (self, low0, high0, low1, high1, state): iter1 = self.op1.iterator (low0, high0, low1, high1, state) iter2 = self.op2.iterator (low0, high0, low1, high1, state) (i1, j1) = iter1.next () (i2, j2) = iter2.next () while True: if (j1, i1) < (j2, i2): (i1, j1) = iter1.next () elif (j2, i2) < (j1, i1): (i2, j2) = iter2.next () else: yield (i1, j1) (i1, j1) = iter1.next () (i2, j2) = iter2.next () class FiniteMaskIntersection (Finite, MaskIntersection): def __init__ (self, op1, op2): assert isFinite (op1) MaskIntersection.__init__ (self, op1, op2) def bounds (self): return self.op1.bounds () class MaskMultisetSum (BinaryMask): def __init__ (self, op1, op2): BinaryMask.__init__ (self, "+", op1, op2, 0) def iterator (self, low0, high0, low1, high1, state): iter1 = self.op1.iterator (low0, high0, low1, high1, state) iter2 = self.op2.iterator (low0, high0, low1, high1, state) try: (i1, j1) = iter1.next () except StopIteration: (i2, j2) = iter2.next () while True: yield (i2, j2) (i2, j2) = iter2.next () try: (i2, j2) = iter2.next () except StopIteration: while True: yield (i1, j1) (i1, j1) = iter1.next () while True: i1s = i1 j1s = j1 while (j1, i1) <= (j2, i2): yield (i1, j1) try: (i1, j1) = iter1.next () except StopIteration: while True: yield (i2, j2) (i2, j2) = iter2.next () while (j2, i2) <= (j1s, i1s): yield (i2, j2) try: (i2, j2) = iter2.next () except StopIteration: while True: yield (i1, j1) (i1, j1) = iter1.next () class FiniteMaskMultisetSum (Finite, MaskMultisetSum): def __init__ (self, op1, op2): assert isFinite (op1) and isFinite (op2) MaskMultisetSum.__init__ (self, op1, op2) def bounds (self): return self.maxBounds (self.op1.bounds (), self.op2.bounds ()) class MaskDifference (BinaryMask): def __init__ (self, op1, op2): BinaryMask.__init__ (self, "-", op1, op2, 0) def iterator (self, low0, high0, low1, high1, state): iter1 = self.op1.iterator (low0, high0, low1, high1, state) iter2 = self.op2.iterator (low0, high0, low1, high1, state) (i1, j1) = iter1.next () (i2, j2) = iter2.next () while True: if (j1, i1) < (j2, i2): yield (i1, j1) (i1, j1) = iter1.next () continue elif (i1, j1) == (i2, j2): (i1, j1) = iter1.next () try: (i2, j2) = iter2.next () except StopIteration: while True: yield (i1, j1) (i1, j1) = iter1.next () def cmpPostOrder (c0, op1): return cmp ((c0[1], c0[0]), (op1[1], op1[0])) class ExplicitMask (FiniteMask): def __init__ (self, connections): FiniteMask.__init__ (self) self.connections = list (connections) self.connections.sort (cmpPostOrder) if connections: self.low0 = min ((i for (i, j) in self.connections)) self.high0 = max ((i for (i, j) in self.connections)) + 1 self.low1 = self.connections[0][1] self.high1 = self.connections[-1][1] + 1 def __len__ (self): return len (self.connections) def iterator (self, low0, high0, low1, high1, state): if not self.isBoundedBy (low0, high0, low1, high1): return iter (self.connections) else: return self.boundedIterator (low0, high0, low1, high1, state) def boundedIterator (self, low0, high0, low1, high1, state): iterator = iter (self.connections) (i, j) = iterator.next () while j < low1: (i, j) = iterator.next () while j < high1: if low0 <= i and i < high0: yield (i, j) (i, j) = iterator.next () class IntervalSetMask (Mask): tag = 'cross' def __init__ (self, set0, set1): Mask.__init__ (self) self.set0 = set0 self.set1 = set1 @staticmethod def _sets_to_repr (set0, set1): return 'cross(%s, %s)' % (set0.repr (), set1.repr ()) def repr (self): return self._sets_to_repr (self.set0, self.set1) def __contains__ (self, c): return c[0] in self.set0 and c[1] in self.set1 def transpose (self): return IntervalSetMask (self.set1, self.set0) def shift (self, M, N): return IntervalSetMask (self.set0.shift (M), self.set1.shift (N)) def iterator (self, low0, high0, low1, high1, state): iterator1 = self.set1.intervalIterator () i1 = iterator1.next () while i1[1] < low1: i1 = iterator1.next () while i1[0] < high1: for j in xrange (max (i1[0], low1), min (i1[1] + 1, high1)): iterator0 = self.set0.intervalIterator () try: i0 = iterator0.next () while i0[1] < low0: i0 = iterator0.next () if i0[1] < high0: for i in xrange (max (i0[0], low0), i0[1] + 1): yield (i, j) i0 = iterator0.next () while i0[1] < high0: for i in xrange (i0[0], i0[1] + 1): yield (i, j) i0 = iterator0.next () for i in xrange (i0[0], min (i0[1] + 1, high0)): yield (i, j) else: for i in xrange (max (i0[0], low0), min (i0[1] + 1, high0)): yield (i, j) except StopIteration: pass i1 = iterator1.next () def intersection (self, other): if isinstance (other, IntervalSetMask): set0 = self.set0.intersection (other.set0) set1 = self.set1.intersection (other.set1) return intervalSetMask (set0, set1) else: return ISetBoundedMask (self.set0, self.set1, other) def multisetSum (self, other): if isinstance (other, IntervalSetMask): if not self.set0.intersection (other.set0) \ or not self.set1.intersection (other.set1): set0 = self.set0.union (other.set0) set1 = self.set1.union (other.set1) return intervalSetMask (set0, set1) else: raise RuntimeError, \ 'sums of overlapping IntervalSetMask:s not yet supported' else: return FiniteMask.multisetSum (self, other) @staticmethod def _sets_to_xml (set0, set1): return CSAObject.apply (IntervalSetMask.tag, set0, set1) def _to_xml (self): return self._sets_to_xml (self.set0, self.set1) class FiniteISetMask (FiniteMask, IntervalSetMask): def __init__ (self, set0, set1): FiniteMask.__init__ (self) IntervalSetMask.__init__ (self, set0, set1) if self.set0 and self.set1: self.low0 = self.set0.min () self.high0 = self.set0.max () + 1 self.low1 = self.set1.min () self.high1 = self.set1.max () + 1 def __len__ (self): return len (self.set0) * len (self.set1) def transpose (self): return FiniteISetMask (self.set1, self.set0) def shift (self, M, N): return FiniteISetMask (self.set0.shift (M), self.set1.shift (N)) def iterator (self, low0, high0, low1, high1, state): if not self.isBoundedBy (low0, high0, low1, high1): return self.simpleIterator () else: return IntervalSetMask.iterator (self, low0, high0, low1, high1, state) def simpleIterator (self): for j in self.set1: for i in self.set0: yield (i, j) class FiniteSourcesISetMask (IntervalSetMask): def __init__ (self, set0, set1): IntervalSetMask.__init__ (self, set0, set1) def transpose (self): return FiniteTargetsISetMask (self.set1, self.set0) def shift (self, M, N): return FiniteSourcesISetMask (self.set0.shift (M), \ self.set1.shift (N)) class FiniteTargetsISetMask (IntervalSetMask): def __init__ (self, set0, set1): IntervalSetMask.__init__ (self, set0, set1) def transpose (self): return FiniteSourcesISetMask (self.set1, self.set0) def shift (self, M, N): return FiniteTargetsISetMask (self.set0.shift (M), \ self.set1.shift (N)) def intervalSetMask (set0, set1): set0 = set0 if isinstance (set0, intervalset.IntervalSet) \ else intervalset.IntervalSet (set0) set1 = set1 if isinstance (set1, intervalset.IntervalSet) \ else intervalset.IntervalSet (set1) if set0.finite (): if set1.finite (): return FiniteISetMask (set0, set1) else: return FiniteSourcesISetMask (set0, set1) else: if set1.finite (): return FiniteTargetsISetMask (set0, set1) else: return IntervalSetMask (set0, set1) CSAObject.tag_map[CSA + IntervalSetMask.tag] = (intervalSetMask, 2) class ISetBoundedMask (FiniteMask): def __init__ (self, set0, set1, mask): FiniteMask.__init__ (self) self.precedence = 1 self.set0 = set0 self.set1 = set1 self.subMask = mask inf = intervalset.infinity if isFinite (mask): (low0, high0, low1, high1) = mask.bounds () else: (low0, high0, low1, high1) = (0, inf, 0, inf) if self.set0 and self.set1: self.low0 = max (self.set0.min (), low0) if self.set0.finite (): self.high0 = min (self.set0.max () + 1, high0) else: self.high0 = high0 self.low1 = max (self.set1.min (), low1) if self.set1.finite (): self.high1 = min (self.set1.max () + 1, high1) else: self.high1 = high1 assert self.high0 != inf and self.high1 != inf, 'infinite ISetBoundedMask:s currently not supported' def startIteration (self, state): obj = copy.copy (self) obj.subMask = self.subMask.startIteration (state) return obj def iterator (self, low0, high0, low1, high1, state): if not self.isBoundedBy (low0, high0, low1, high1): return self.simpleIterator (state) else: return self.boundedIterator (low0, high0, low1, high1, state) def simpleIterator (self, state): for i1 in self.set1.intervalIterator (): for i0 in self.set0.intervalIterator (): for e in self.subMask.iterator (i0[0], i0[1] + 1, i1[0], i1[1] + 1, state): yield e def boundedIterator (self, low0, high0, low1, high1, state): iterator1 = self.set1.intervalIterator () i1 = iterator1.next () while i1[1] < low1: i1 = iterator1.next () while i1[0] < high1: i1 = (max (i1[0], low1), min (i1[1], high1 - 1)) iterator0 = self.set0.intervalIterator () try: i0 = iterator0.next () while i0[1] < low0: i0 = iterator0.next () if i0[1] < high0: for e in self.subMask.iterator (max (i0[0], low0), i0[1] + 1, i1[0], i1[1] + 1, state): yield e i0 = iterator0.next () while i0[1] < high0: for e in self.subMask.iterator (i0[0], i0[1] + 1, i1[0], i1[1] + 1, state): yield e i0 = iterator0.next () for e in self.subMask.iterator (i0[0], min (i0[1] + 1, high0), i1[0], i1[1] + 1, state): yield e else: for e in self.subMask.iterator (max (i0[0], low0), min (i0[1] + 1, high0), i1[0], i1[1] + 1, state): yield e except StopIteration: pass i1 = iterator1.next () def repr (self): return '%s*%s' % (IntervalSetMask._sets_to_repr (self.set0, self.set1), self.subMask._repr_as_op2 (self.precedence)) def _to_xml (self): return E ('apply', E ('times'), IntervalSetMask._sets_to_xml (self.set0, self.set1), self.subMask._to_xml ()) # The ExplicitCSet captures the original value sets before coercion. # It is used in the implementation of the "cset" constructor. # class ExplicitCSet (CSet): def __init__ (self, mask, *valueSets): if isinstance (mask, list): mask = ExplicitMask (mask) self.originalValueSets = valueSets CSet.__init__ (self, mask, *map (coerceValueSet, valueSets)) def value (self, k): return self.originalValueSets[k] # SubCSet is used in the cases where a new CSet can be created by # an operation on the mask. # class SubCSet (CSet): def __init__ (self, cset, mask, *valueSets): CSet.__init__ (self, mask, *valueSets) self.subCSet = cset def value (self, k): if self.valueSets[k] == None: self.valueSets[k] = self.makeValueSet (k) # defer to subCSet in case it is an ExplicitCSet return self.subCSet.value (k) def makeValueSet (self, k): if isFinite (self.mask ()): bounds = self.mask ().bounds () return self.subCSet.makeFiniteValueSet (k, bounds) else: return self.subCSet.makeValueSet (k) class BinaryCSet (BinaryCSAObject, CSet): def __init__ (self, operator, op1, op2): CSet.__init__ (self, None, *[ None for v in op1.valueSets ]) self.name = operator self.op1 = op1 self.op2 = op2 self.valueSetMap = None def makeFiniteValueSet (self, k, bounds): if self.valueSetMap == None: self.valueSetMap = self.makeValueSetMap (bounds) return lambda i, j: self.valueSetMap[(i, j)][k] def makeValueSetMap (self, bounds): m = {} state = State () obj = self.startIteration (state) (low0, high0, low1, high1) = bounds for (i, j, v) in obj.iterator (low0, high0, low1, high1, state): m[(i, j)] = v return m class BinaryCSets (BinaryCSet): def __init__ (self, operator, op1, op2): assert op1.arity == op2.arity, 'binary operation on connection-sets with different arity' BinaryCSet.__init__ (self, operator, op1, op2) class CSetIntersection (BinaryCSet): def __init__ (self, op1, op2): assert isinstance (op2, Mask), 'expected Mask operand' BinaryCSet.__init__ (self, "*", op1, op2) self._mask = op1.mask ().intersection (op2) def iterator (self, low0, high0, low1, high1, state): iter1 = self.op1.iterator (low0, high0, low1, high1, state) iter2 = self.op2.iterator (low0, high0, low1, high1, state) (i1, j1, v1) = iter1.next () (i2, j2) = iter2.next () while True: if (j1, i1) < (j2, i2): (i1, j1, v1) = iter1.next () elif (j2, i2) < (j1, i1): (i2, j2) = iter2.next () else: yield (i1, j1, v1) (i1, j1, v1) = iter1.next () (i2, j2) = iter2.next () class CSetMultisetSum (BinaryCSets): def __init__ (self, op1, op2): BinaryCSet.__init__ (self, "+", op1, op2) self._mask = op1.mask ().multisetSum (op2.mask ()) def iterator (self, low0, high0, low1, high1, state): iter1 = self.op1.iterator (low0, high0, low1, high1, state) iter2 = self.op2.iterator (low0, high0, low1, high1, state) try: (i1, j1, v1) = iter1.next () except StopIteration: (i2, j2, v2) = iter2.next () while True: yield (i2, j2, v2) (i2, j2, v2) = iter2.next () try: (i2, j2, v2) = iter2.next () except StopIteration: while True: yield (i1, j1, v1) (i1, j1, v1) = iter1.next () while True: i1s = i1 j1s = j1 while (j1, i1) <= (j2, i2): yield (i1, j1, v1) try: (i1, j1, v1) = iter1.next () except StopIteration: while True: yield (i2, j2, v2) (i2, j2, v2) = iter2.next () while (j2, i2) <= (j1s, i1s): yield (i2, j2, v2) try: (i2, j2, v2) = iter2.next () except StopIteration: while True: yield (i1, j1, v1) (i1, j1, v1) = iter1.next () def intersection (self, other): assert isinstance (other, Mask), 'expected Mask operand' if isFinite (self) or isFinite (other): # since operands are finite we are allowed to use isEmpty if isEmpty (self.op2.mask ().intersection (other)): return self.op1.intersection (other) if isEmpty (self.op1.mask ().intersection (other)): return self.op2.intersection (other) return CSetIntersection (self, other) class TransposedMask (Finite, Mask): def __init__ (self, mask): self.subMask = mask def transpose (self): return self.subMask def bounds (self): (low0, high0, low1, high1) = self.subMask.bounds () return (low1, high1, low0, high0) def startIteration (self, state): obj = copy.copy (self) obj.transposedState = state.transpose () obj.subMask = self.subMask.startIteration (obj.transposedState) return obj def iterator (self, low0, high0, low1, high1, state): ls = [] for c in self.subMask.iterator (low1, high1, low0, high0, \ self.transposedState): ls.append ((c[1], c[0])) ls.sort (cmpPostOrder) return iter (ls) class ShiftedMask (Mask): def __init__ (self, mask, M, N): self.subMask = mask self.M = M self.N = N def startIteration (self, state): obj = copy.copy (self) obj.subMask = self.subMask.startIteration (state) return obj def iterator (self, low0, high0, low1, high1, state): low0 -= self.M high0 -= self.M low1 -= self.N high1 -= self.N for (i, j) in self.subMask.iterator (max (low0, 0), high0, \ max (low1, 0), high1, \ state): (i1, j1) = (i + self.M, j + self.N) if i1 >= 0 and j1 >= 0: yield (i1, j1) class FiniteShiftedMask (Finite, ShiftedMask): def bounds (self): (low0, high0, low1, high1) = self.subMask.bounds () low0 += self.M high0 += self.M low1 += self.N high1 += self.N return (max (low0, 0), high0, max (low1, 0), high1) def shiftedMask (mask, M, N): if isFinite (mask): return FiniteShiftedMask (mask, M, N) else: return ShiftedMask (mask, M, N) class State (dict): def transpose (self): if 'partitions' in self: s = State (self) s['partitions'] = map (transpose, s['partitions']) return s else: return self class MaskPartition (Finite, Mask): def __init__ (self, mask, partitions, selected, seed): Mask.__init__ (self) #*fixme* How can we know when this is not necessary? self.subMask = partitions[selected] * mask #domain = IntervalSetMask ([], []) #for m in partitions: # assert isFinite (m), 'partitions must be finite' # domain = domain.multisetSum (m) self.state = { #'domain' : domain, 'partitions' : partitions, 'selected' : selected } if seed != None: self.state['seed'] = seed def bounds (self): return self.subMask.bounds () def startIteration (self, state): for key in self.state: state[key] = self.state[key] return self.subMask.startIteration (state) def iterator (self, low0, high0, low1, high1, state): raise RuntimeError, 'iterator called on wrong object' class CSetPartition (CSet): def __init__ (self, c, partitions, selected, seed): #*fixme* How can we know when this is not necessary? self.subCSet = (partitions[selected] * c).c CSet.__init__ (self, self.subCSet.mask (), *self.subCSet.valueSets) self.state = { #'domain' : domain, 'partitions' : partitions, 'selected' : selected } if seed != None: self.state['seed'] = seed def makeFiniteValueSet (self, k, bounds): return self.subCSet.makeFiniteValueSet (k, bounds); def bounds (self): return self.subCSet.bounds () def startIteration (self, state): for key in self.state: state[key] = self.state[key] return self.subCSet.startIteration (state) def iterator (self, low0, high0, low1, high1, state): raise RuntimeError, 'iterator called on wrong object' csa-0.1.0/csa/csaobject.py0000644000514000051400000001452011735362304014701 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # try: from lxml import etree from lxml.builder import E except ImportError: pass csa_tag = 'CSA' csa_namespace = 'http://software.incf.org/software/csa/1.0' CSA = '{%s}' % csa_namespace CUSTOM = -4 OPERATOR = -3 BINDOPERATOR = -2 SINGLETON = -1 def to_xml (obj): if isinstance (obj, str): return E (obj) elif isinstance (obj, (int, float)): return E ('cn', str (obj)) elif isinstance (obj, CSAObject): return obj._to_xml () else: raise RuntimeError, "don't know how to turn %s into xml" % obj # precedence levels: # # 0 + - # 1 * # 2 ~ class CSAObject (object): tag_map = {} def __init__ (self, name, precedence = 3): self.name = name self.precedence = precedence def __repr__ (self): return 'CSA(%s)' % self.repr () def repr (self): if hasattr (self, 'name'): return self.name else: return self.__class__.__name__ def _repr_as_op2 (self, parentPrecedence): if self.precedence <= parentPrecedence: return '(%s)' % self.repr () else: return self.repr () def _repr_applyop (self, op_repr, obj): return '%s*%s' % (op_repr, obj._repr_as_op2 (1)) def to_xml (self): return E (csa_tag, self._to_xml (), xmlns=csa_namespace) def _to_xml (self): return E (self.name) @classmethod def apply (cls, operator, *operands): return E ('apply', to_xml (operator), *map (to_xml, operands)) @classmethod def formalFromXML (cls, element): assert element.tag == CSA + 'bvar' nodes = element.getchildren () assert nodes[0].tag == CSA + 'ci' return nodes[0].text @classmethod def from_xml (cls, element, env = {}): if element.tag == CSA + 'cn': return eval (element.text) elif element.tag == CSA + 'ci': #*fixme* Implement env as lists of dictionaries return env[element.text] elif element.tag == CSA + 'apply': nodes = element.getchildren () operator = nodes[0].tag operands = [ cls.from_xml (e, env) for e in nodes[1:] ] if operator == CSA + 'plus': return operands[0].__add__ (operands[1]) elif operator == CSA + 'minus': return operands[0].__sub__ (operands[1]) elif operator == CSA + 'times': return operands[0].__mul__ (operands[1]) elif operator == CSA + 'complement': return operands[0].__invert__ () else: # Function or operator application entry = CSAObject.tag_map[operator] obj = entry[0] if entry[1] == OPERATOR: return obj * operands[1] else: return obj (*operands) elif element.tag == CSA + 'bind': nodes = element.getchildren () tag = nodes[0].tag entry = CSAObject.tag_map[tag] if entry[1] != BINDOPERATOR: raise RuntimeError, "unknown binding operator tag %s" % tag bindingOperator = entry[0] bvars = [ CSAObject.formalFromXML (e) for e in nodes[1:-1] ] return bindingOperator (bvars, nodes[-1]) elif element.tag in CSAObject.tag_map: entry = CSAObject.tag_map[element.tag] obj = entry[0] if entry[1] == SINGLETON: return obj elif entry[1] == CUSTOM: return obj.from_xml (element, env) else: return obj () else: raise RuntimeError, "don't know how parse tag %s" % element.tag def xml (e): print etree.tostring (e) def write(self, file): doc = self.to_xml () etree.ElementTree(doc).write (file, encoding="UTF-8", pretty_print=True, xml_declaration=True) class BinaryCSAObject (CSAObject): operator_table = {'+': 'plus', '-': 'minus', '*': 'times'} def __init__ (self, name, op1, op2, precedence = 0): CSAObject.__init__ (self, name, precedence) self.op1 = op1 self.op2 = op2 def repr (self): if isinstance (self.op1, CSAObject): op1 = self.op1.repr () if self.op1.precedence < self.precedence: op1 = "(%s)" % op1 else: op1 = self.op1 if isinstance (self.op2, CSAObject): op2 = self.op2._repr_as_op2 (self.precedence) else: op2 = self.op2 return "%s%s%s" % (op1, self.name, op2) def _to_xml (self): if isinstance (self.op1, CSAObject): op1 = self.op1._to_xml () else: op1 = self.op1 if isinstance (self.op2, CSAObject): op2 = self.op2._to_xml () else: op2 = self.op2 if self.name in BinaryCSAObject.operator_table: op = BinaryCSAObject.operator_table[self.name] else: op = self.name return E ('apply', E (op), op1, op2) class OpExprValue (BinaryCSAObject): def __init__ (self, operator, operand): BinaryCSAObject.__init__ (self, '*', operator, operand, 1) class Operator (CSAObject): def __init__ (self, name='ioperator'): CSAObject.__init__ (self, name) def from_xml (root): assert root.nsmap[None] == csa_namespace return CSAObject.from_xml (root.getchildren ()[0]) def parse (filename): doc = etree.parse (filename) return from_xml (doc.getroot()) def registerTag (tag, obj, mode): CSAObject.tag_map[CSA + tag] = (obj, mode) csa-0.1.0/csa/version.py0000644000514000051400000000137211735362304014432 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # __version__ = "0.1.0" csa-0.1.0/csa/geometry.py0000644000514000051400000000445011735362304014600 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import math as _math import random as _random import numpy as _numpy import intervalset as _iset def grid2d (width, xScale = 1.0, yScale = 1.0, x0 = 0.0, y0 = 0.0): xScale /= width yScale /= width g = lambda i: \ (x0 + xScale * (i % width), y0 + yScale * (i / width)) g.type = 'grid' g.width = width g.xScale = xScale g.yScale = yScale g.x0 = x0 g.y0 = y0 g.inverse = lambda x, y: \ int (round (x / xScale - x0)) \ + width * int (round (y / yScale - y0)) return g def random2d (N, xScale = 1.0, yScale = 1.0): coords = [(xScale * _random.random (), yScale * _random.random ()) for i in xrange (0, N)] g = lambda i: coords[i] g.type = 'ramdom' g.N = N g.xScale = xScale g.yScale = yScale # We should use a KD-tree here g.inverse = lambda x, y, domain=_iset.IntervalSet ((0, N - 1)): \ _numpy.array ([euclidDistance2d ((x, y), g(i)) \ for i in domain]).argmin () \ + domain.min () return g def euclidDistance2d (p1, p2): dx = p1[0] - p2[0] dy = p1[1] - p2[1] return _math.sqrt (dx * dx + dy * dy) class ProjectionOperator (object): def __init__ (self, projection): self.projection = projection def __mul__ (self, g): projection = self.projection return lambda i: projection (g (i)) def euclidMetric2d (g1, g2 = None): g2 = g1 if g2 == None else g2 return lambda i, j: euclidDistance2d (g1 (i), g2 (j)) #del random csa-0.1.0/csa/conngen.py0000644000514000051400000000460011735362304014371 0ustar mdjmdj00000000000000# # This file is part of the Connection-Set Algebra (CSA). # Copyright (C) 2010,2011,2012 Mikael Djurfeldt # # CSA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # try: from nineml.connection_generator import ConnectionGenerator HAVE_CG=True except ImportError: HAVE_CG=False if HAVE_CG: from csaobject import from_xml from elementary import arity, cross, partition from closure import Closure class CSAConnectionGenerator (ConnectionGenerator): def __init__ (self, cset): self.cset = cset self.generator = False @property def arity (self): return arity (self.cset) def setMask (self, mask): self.setMasks ([mask], 0) def setMasks (self, masks, local): csaMasks = map (CSAConnectionGenerator.makeMask, masks) self.generator = partition (self.cset, csaMasks, local) @staticmethod def makeMask (mask): return cross (CSAConnectionGenerator.makeIList (mask.sources), CSAConnectionGenerator.makeIList (mask.targets)) @staticmethod def makeIList (iset): if iset.skip == 1: return iset.intervals else: ls = [] for ivl in iset.intervals: for i in xrange (ivl[0], ivl[1] + 1, iset.skip): ls.append ((i, i)) return ls def __len__ (self): return self.generator.__len__ () def __iter__ (self): return self.generator.__iter__ () def connectionGeneratorClosureFromXML (element): cset = from_xml (element) if isinstance (cset, Closure): return lambda *args: CSAConnectionGenerator (cset (*args)) else: return lambda: CSAConnectionGenerator (cset)