import 0.2.1

This commit is contained in:
Jan Petykiewicz 2019-05-15 21:06:29 -07:00
commit 5a4c7db6b4
35 changed files with 3888 additions and 0 deletions

674
GPL-3 Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

165
LGPL-3 Normal file
View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

29
Makefile Normal file
View File

@ -0,0 +1,29 @@
PYCHECKER_MOULES = gdsii gdsii.library gdsii.structure gdsii.elements gdsii.types gdsii.tags \
gdsii._records gdsii.exceptions gdsii.record
PYTHON ?= python
help:
@echo Commands: doc clean check pychecker
doc:
$(MAKE) -C doc html
clean: clean-pyc
rm -rf build dist
rm -f MANIFEST
$(MAKE) -C doc clean
clean-pyc:
find . -name '*.py[co]' -print0 | xargs -r0 rm --
check:
$(PYTHON) -m gdsii.record
$(PYTHON) -m gdsii.tags
$(PYTHON) -m test.test_record
$(PYTHON) -m test.test_lib
pychecker:
pychecker -J 20 $(PYCHECKER_MOULES)
.PHONY: clean clean-pyc doc check pychecker

25
PKG-INFO Normal file
View File

@ -0,0 +1,25 @@
Metadata-Version: 1.1
Name: python-gdsii
Version: 0.2.1
Summary: GDSII manipulation libaray
Home-page: http://www.gitorious.org/python-gdsii
Author: Eugeniy Meshcheryakov
Author-email: eugen@debian.org
License: LGPL-3+
Description:
python-gdsii is a library that can be used to read, create, modify and save
GDSII files. It supports both low-level record I/O and high level interface to
GDSII libraries (databases), structures, and elements.
This package also includes scripts that can be used to convert binary GDS file
to a simple text format (gds2txt), YAML (gds2yaml), and from text fromat back
to GDSII (txt2gds).
Platform: any
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)
Classifier: Programming Language :: Python
Classifier: Topic :: Scientific/Engineering :: Electronic Design Automation (EDA)
Classifier: Topic :: Software Development :: Libraries :: Python Modules

40
README Normal file
View File

@ -0,0 +1,40 @@
python-gdsii --- a GDSII manipulation libaray
=============================================
python-gdsii is a library that can be used to read, create, modify and save
GDSII files. It supports both low-level record I/O and high level interface to
GDSII libraries (databases), structures, and elements.
This package also includes scripts that can be used to convert binary GDS file
to a simple text format (gds2txt), YAML (gds2yaml), and from text fromat
back to GDSII (txt2gds).
Usage
-----
For most cases interface provided by Library class from gdsii.library should be
enough. Here is a small example::
from gdsii.library import Library
from gdsii.elements import *
# read a library from a file
with open('file.gds', 'rb') as stream:
lib = Library.load(stream)
# let's move the first structure to a new library
new_lib = Library(5, b'NEWLIB.DB', 1e-9, 0.001)
struc = lib.pop(0) # libraries and structures are derived from list class
new_lib.append(struc)
# let's also add some elements...
# Note: first and last points in the boundary should be the same
# this is required by GDSII spec.
struc.append(Boundary(45, 0, [(-100000, -100000), (-100000, 0), (0,0), (0, -100000), (-100000, -100000)]))
# Save both files with different names...
with open('newfile1.gds', 'wb') as stream:
lib.save(stream)
with open('newfile2.gds', 'wb') as stream:
new_lib.save(stream)

89
doc/Makefile Normal file
View File

@ -0,0 +1,89 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pygdsii.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pygdsii.qhc"
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
"run these through (pdf)latex."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

194
doc/conf.py Normal file
View File

@ -0,0 +1,194 @@
# -*- coding: utf-8 -*-
#
# pygdsii documentation build configuration file, created by
# sphinx-quickstart on Sun Aug 15 02:07:50 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.append(os.path.abspath('..'))
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'python-gdsii'
copyright = u'20102011, Eugeniy Meshcheryakov'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.2'
# The full version, including alpha/beta/rc tags.
release = '0.2'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'default'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'sphinxdoc'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
#htmlhelp_basename = 'pygdsiidoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'pygdsii.tex', u'python-gdsii Documentation',
u'Eugeniy Meshcheryakov', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True

111
doc/gdsii/elements.rst Normal file
View File

@ -0,0 +1,111 @@
.. automodule:: gdsii.elements
:synopsis: module containing classes for GDSII elements.
Possible instance attributes:
:attr:`elflags`
Element flags (:class:`int`, optional).
Bit 15 specifies template data.
Bit 14 specifies external data.
:attr:`plex`
Plex number (:class:`int`, optional).
:attr:`layer`
Element layer (:class:`int`)
:attr:`data_type`
Element data type (:class:`int`)
:attr:`path_type`
Type of path endpoints (:class:`int`, optional).
The values have the following meaning:
* 0 -- square ends, flush with endpoints
* 1 -- round ends, centered on endpoints
* 2 -- square ends, centered on endpoints
* 4 -- custom square ends
:attr:`width`
Width of the path (:class:`int`, optional). If the value is negative,
then the width is absolute and not affected by magnification factor.
:attr:`bgn_extn`, :attr:`end_extn`
Start end end extensions for :attr:`path_type` 4 (:class:`int`, optional).
:attr:`xy`
List of points (:class:`list` of tuples ``(x, y)``).
:attr:`struct_name`
Name of the referenced structure (:class:`bytes`).
:attr:`strans`
Transformation flags (:class:`int`, optional). Bits have the following meaning:
* 0 -- reclection about X axis
* 13 -- absolute magnification
* 14 -- absolute angle
:attr:`mag`
Magnification factor (:class:`float`, optional).
:attr:`angle`
Rotation factor in degrees (:class:`float`, optional). Rotation is counterclockwise.
:attr:`cols`
Number of columns (:class:`int`).
:attr:`rows`
Number of rows (:class:`int`).
:attr:`text_type`
Text type (:class:`int`).
:attr:`presentation`
Bit array that specifies how the text is presented (:class:`int`, optional).
Meaning of bits:
* Bits 10 and 11 specify font number (0-3).
* Bits 12 and 13 specify vertical justification (0 -- top, 1 -- middle, 2 -- bottom).
* Bits 14 and 15 specify horizontal justification (0 -- left, 1 -- center, 2 -- rigth).
:attr:`string`
String for :const:`TEXT` element (:class:`bytes`).
:attr:`node_type`
Node type (:class:`int`).
:attr:`box_type`
Box type (:class:`int`).
:attr:`properties`
Element properties, represented as a list of tupes (`propattr`, `propvalue`).
`propattr` is an :class:`int`, `propvalue` is :class:`bytes`.
This attribute is optional.
.. autoclass:: ARef
Required attributes: :attr:`struct_name`, :attr:`cols`, :attr:`rows`, :attr:`xy`.
Optional attributes: :attr:`elflags`, :attr:`plex`, :attr:`strans`, :attr:`mag`,
:attr:`angle`, :attr:`properties`.
.. autoclass:: Boundary
Required attributes: :attr:`layer`, :attr:`data_type`, :attr:`xy`.
Optional attributes: :attr:`elflags`, :attr:`plex`, :attr:`properties`.
.. autoclass:: Box
Required attributes: :attr:`layer`, :attr:`box_type`, :attr:`xy`.
Optional attributes: :attr:`elflags`, :attr:`plex`, :attr:`properties`.
.. autoclass:: Node
Required attributes: :attr:`layer`, :attr:`node_type`, :attr:`xy`
Optional attributes: :attr:`elflags`, :attr:`plex`, :attr:`properties`
.. autoclass:: Path
Required attributes: :attr:`layer`, :attr:`data_type`, :attr:`xy`
Optional attributes: :attr:`elflags`, :attr:`plex`, :attr:`path_type`,
:attr:`width`, :attr:`bgn_extn`, :attr:`end_extn`, :attr:`properties`
.. autoclass:: SRef
Required attributes: :attr:`struct_name`, :attr:`xy`
Optional attributes: :attr:`elflags`, :attr:`strans`, :attr:`mag`,
:attr:`angle`, :attr:`properties`
.. autoclass:: Text
Required attributes: :attr:`layer`, :attr:`text_type`, :attr:`xy`, :attr:`string`
Optional attributes: :attr:`elflags`, :attr:`plex`, :attr:`presentation`,
:attr:`path_type`, :attr:`width`, :attr:`strans`, :attr:`mag`, :attr:`angle`, :attr:`properties`

3
doc/gdsii/exceptions.rst Normal file
View File

@ -0,0 +1,3 @@
.. automodule:: gdsii.exceptions
:members:
:show-inheritance:

13
doc/gdsii/index.rst Normal file
View File

@ -0,0 +1,13 @@
:mod:`gdsii` --- GDSII manipulation library
===========================================
.. toctree::
:maxdepth: 2
library
structure
elements
tags
types
record
exceptions

81
doc/gdsii/library.rst Normal file
View File

@ -0,0 +1,81 @@
.. automodule:: gdsii.library
:synopsis: module containing GDSII library class.
.. autoclass:: Library
:show-inheritance:
.. automethod:: __init__
Instance attributes:
.. attribute:: version
GDSII file verion (:class:`int`).
Number as found in a GDSII file.
For example value is 5 for GDSII v5 and 0x600 for GDSII v6.
.. attribute:: name
Library name (:class:`bytes`).
.. attribute:: physical_unit
Size of database unit in meters (:class:`float`).
.. attribute:: logical_unit
Size of user unit in database units (:class:`float`).
.. attribute:: mod_time
Last modification time (:class:`datetime`).
.. attribute:: acc_time
Last access time (:class:`datetime`).
.. attribute:: libdirsize
Number of pages in the library directory (:class:`int`, optional).
.. attribute:: srfname
Name of spacing rules file (:class:`bytes`, optional).
.. attribute:: acls
ACL data (:class:`list` of tuples ``(GID, UID, ACCESS)``, optional).
.. attribute:: reflibs
Names of reference libraries (:class:`bytes`, optional).
See GDSII stream format documentation for format.
.. attribute:: fonts
Names of font definition files (:class:`bytes`, optional).
The content is not parsed, see GDSII stream format documentation
for format.
.. attribute:: attrtable
Name of attribute definition file (:class:`bytes`, optional).
.. attribute:: generations
Number of copies for deleted structures (:class:`int`, optional)
.. attribute:: format
Library format (:class:`int`, optional). Possible values:
* 0 -- GDSII archive format
* 1 -- GDSII filtered format
* 2 -- EDSIII archive format
* 3 -- EDSIII filtered format
.. attribute:: masks
Masks for filtered format (:class:`list` of :class:`bytes`, optional).
.. automethod:: load
.. automethod:: save

19
doc/gdsii/record.rst Normal file
View File

@ -0,0 +1,19 @@
.. automodule:: gdsii.record
.. autoclass:: Record
:members:
.. attribute:: data
Element data.
.. attribute:: tag
Element tag (:class:`int`).
.. autoclass:: Reader
:members:
.. attribute:: current
Last record read from stream.

24
doc/gdsii/structure.rst Normal file
View File

@ -0,0 +1,24 @@
.. automodule:: gdsii.structure
:synopsis: module containing GDSII structure class.
.. autoclass:: Structure
:show-inheritance:
.. automethod:: __init__
Instance attributes:
.. attribute:: name
Structure name (:class:`bytes`).
.. attribute:: mod_time
Last modification time (:class:`datetime`).
.. attribute:: acc_time
Last access time (:class:`datetime`).
.. attribute:: strclass
Structure class (:class:`int`, optional).

83
doc/gdsii/tags.rst Normal file
View File

@ -0,0 +1,83 @@
.. automodule:: gdsii.tags
The following vaues are defined::
HEADER = 0x0002
BGNLIB = 0x0102
LIBNAME = 0x0206
UNITS = 0x0305
ENDLIB = 0x0400
BGNSTR = 0x0502
STRNAME = 0x0606
ENDSTR = 0x0700
BOUNDARY = 0x0800
PATH = 0x0900
SREF = 0x0A00
AREF = 0x0B00
TEXT = 0x0C00
LAYER = 0x0D02
DATATYPE = 0x0E02
WIDTH = 0x0F03
XY = 0x1003
ENDEL = 0x1100
SNAME = 0x1206
COLROW = 0x1302
TEXTNODE = 0x1400
NODE = 0x1500
TEXTTYPE = 0x1602
PRESENTATION = 0x1701
STRING = 0x1906
STRANS = 0x1A01
MAG = 0x1B05
ANGLE = 0x1C05
REFLIBS = 0x1F06
FONTS = 0x2006
PATHTYPE = 0x2102
GENERATIONS = 0x2202
ATTRTABLE = 0x2306
STYPTABLE = 0x2406
STRTYPE = 0x2502
ELFLAGS = 0x2601
ELKEY = 0x2703
NODETYPE = 0x2A02
PROPATTR = 0x2B02
PROPVALUE = 0x2C06
BOX = 0x2D00
BOXTYPE = 0x2E02
PLEX = 0x2F03
BGNEXTN = 0x3003
ENDEXTN = 0x3103
TAPENUM = 0x3202
TAPECODE = 0x3302
STRCLASS = 0x3401
FORMAT = 0x3602
MASK = 0x3706
ENDMASKS = 0x3800
LIBDIRSIZE = 0x3902
SRFNAME = 0x3A06
LIBSECUR = 0x3B02
Types used only with Custom Plus (not handled by pygdsii)::
BORDER = 0x3C00
SOFTFENCE = 0x3D00
HARDFENCE = 0x3E00
SOFTWIRE = 0x3F00
HARDWIRE = 0x4000
PATHPORT = 0x4100
NODEPORT = 0x4200
USERCONSTRAINT = 0x4300
SPACERERROR = 0x4400
CONTACT = 0x4500
Additionaly this module contains the following members:
.. autofunction:: type_of_tag
.. data:: DICT
A dictionary that maps tag names to tag IDs.
.. data:: REV_DICT
A dictionary that maps tag IDs to tag names.

23
doc/gdsii/types.rst Normal file
View File

@ -0,0 +1,23 @@
.. automodule:: gdsii.types
Defined members::
NODATA = 0
BITARRAY = 1
INT2 = 2
INT4 = 3
REAL4 = 4
REAL8 = 5
ASCII = 6
Type :const:`REAL4` is not used in GDSII and not handled by `python-gdsii`.
Additionaly this module contains the following members:
.. data:: DICT
A dictionary that maps type names to type IDs.
.. data:: REV_DICT
A dictionary that maps type IDs to type names.

60
doc/index.rst Normal file
View File

@ -0,0 +1,60 @@
Welcome to python-gdsii's documentation!
========================================
`python-gdsii` is a library that can be used to read, create, modify and save
GDSII files. It supports both low-level record I/O and high level interface to
GDSII libraries (databases), structures, and elements.
This package also includes scripts that can be used to convert binary GDS file
to a simple text format (`gds2txt`), YAML (`gds2yaml`), and from text format
back to GDSII (`txt2gds`).
Contents:
.. toctree::
:maxdepth: 2
gdsii/index
Download
--------
`python-gdsii` can be downloaded from its Python Package Index `page <http://pypi.python.org/pypi/python-gdsii/>`_.
The source code repository is available on `gitorious.org <http://gitorious.org/python-gdsii>`_.
Usage
-----
For most cases interface provided by Library class from gdsii.library should be
enough. Here is a small example::
from gdsii.library import Library
from gdsii.elements import *
# read a library from a file
with open('file.gds', 'rb') as stream:
lib = Library.load(stream)
# let's move the first structure to a new library
new_lib = Library(5, b'NEWLIB.DB', 1e-9, 0.001)
struc = lib.pop(0) # libraries and structures are derived from list class
new_lib.append(struc)
# let's also add some elements...
# Note: first and last points in the boundary should be the same
# this is required by GDSII spec.
struc.append(Boundary(45, 0, [(-100000, -100000), (-100000, 0), (0,0), (0, -100000), (-100000, -100000)]))
# Save both files with different names...
with open('newfile1.gds', 'wb') as stream:
lib.save(stream)
with open('newfile2.gds', 'wb') as stream:
new_lib.save(stream)
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

113
doc/make.bat Normal file
View File

@ -0,0 +1,113 @@
@ECHO OFF
REM Command file for Sphinx documentation
set SPHINXBUILD=sphinx-build
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\pygdsii.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\pygdsii.ghc
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end

0
gdsii/__init__.py Normal file
View File

230
gdsii/_records.py Normal file
View File

@ -0,0 +1,230 @@
# -*- coding: utf-8 -*-
#
# Copyright © 2010 Eugeniy Meshcheryakov <eugen@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from . import record, tags
class AbstractRecord(object):
def __init__(self, variable):
self.variable = variable
def read(self, instance, gen):
raise NotImplementedError
def save(self, instance, stream):
raise NotImplementedError
def __repr__(self):
return '<property: %s>'%self.variable
class SecondVar(object):
"""Class that simplifies second property support."""
def __init__(self, variable2):
self.variable2 = variable2
class SimpleRecord(AbstractRecord):
def __init__(self, variable, gds_record):
AbstractRecord.__init__(self, variable)
self.gds_record = gds_record
def read(self, instance, gen):
rec = gen.current
rec.check_tag(self.gds_record)
rec.check_size(1)
setattr(instance, self.variable, rec.data[0])
gen.read_next()
def save(self, instance, stream):
record.Record(self.gds_record, (getattr(instance, self.variable),)).save(stream)
class SimpleOptionalRecord(SimpleRecord):
def optional_read(self, instance, unused_gen, rec):
"""
Called when optional tag is found. `rec` contains that tag.
`gen` is advanced to next record befor calling this function.
"""
rec.check_size(1)
setattr(instance, self.variable, rec.data[0])
def read(self, instance, gen):
rec = gen.current
if rec.tag == self.gds_record:
gen.read_next()
self.optional_read(instance, gen, rec)
def save(self, instance, stream):
data = getattr(instance, self.variable, None)
if data is not None:
record.Record(self.gds_record, (data,)).save(stream)
class OptionalWholeRecord(SimpleOptionalRecord):
"""Class for records that need to store all data (not data[0])."""
def optional_read(self, instance, unused_gen, rec):
setattr(instance, self.variable, rec.data)
def save(self, instance, stream):
data = getattr(instance, self.variable, None)
if data is not None:
record.Record(self.gds_record, data).save(stream)
class PropertiesRecord(AbstractRecord):
def read(self, instance, gen):
rec = gen.current
props = []
while rec.tag == tags.PROPATTR:
rec.check_size(1)
propattr = rec.data[0]
rec = gen.read_next()
rec.check_tag(tags.PROPVALUE)
props.append((propattr, rec.data))
rec = gen.read_next()
setattr(instance, self.variable, props)
def save(self, instance, stream):
props = getattr(instance, self.variable)
if props:
for (propattr, propvalue) in props:
record.Record(tags.PROPATTR, (propattr,)).save(stream)
record.Record(tags.PROPVALUE, propvalue).save(stream)
class XYRecord(SimpleRecord):
def read(self, instance, gen):
rec = gen.current
rec.check_tag(self.gds_record)
setattr(instance, self.variable, rec.points)
gen.read_next()
def save(self, instance, stream):
pts = getattr(instance, self.variable)
record.Record(self.gds_record, points=pts).save(stream)
class StringRecord(SimpleRecord):
def read(self, instance, gen):
rec = gen.current
rec.check_tag(self.gds_record)
setattr(instance, self.variable, rec.data)
gen.read_next()
def save(self, instance, stream):
record.Record(self.gds_record, getattr(instance, self.variable)).save(stream)
class ColRowRecord(AbstractRecord, SecondVar):
def __init__(self, variable1, variable2):
AbstractRecord.__init__(self, variable1)
SecondVar.__init__(self, variable2)
def read(self, instance, gen):
rec = gen.current
rec.check_tag(tags.COLROW)
rec.check_size(2)
cols, rows = rec.data
setattr(instance, self.variable, cols)
setattr(instance, self.variable2, rows)
gen.read_next()
def save(self, instance, stream):
col = getattr(instance, self.variable)
row = getattr(instance, self.variable2)
record.Record(tags.COLROW, (col, row)).save(stream)
class TimestampsRecord(SimpleRecord, SecondVar):
def __init__(self, variable1, variable2, gds_record):
SimpleRecord.__init__(self, variable1, gds_record)
SecondVar.__init__(self, variable2)
def read(self, instance, gen):
rec = gen.current
rec.check_tag(self.gds_record)
mod_time, acc_time = rec.times
setattr(instance, self.variable, mod_time)
setattr(instance, self.variable2, acc_time)
gen.read_next()
def save(self, instance, stream):
mod_time = getattr(instance, self.variable)
acc_time = getattr(instance, self.variable2)
record.Record(self.gds_record, times=(mod_time, acc_time)).save(stream)
class STransRecord(OptionalWholeRecord):
mag = SimpleOptionalRecord('mag', tags.MAG)
angle = SimpleOptionalRecord('angle', tags.ANGLE)
def optional_read(self, instance, gen, rec):
setattr(instance, self.variable, rec.data)
self.mag.read(instance, gen)
self.angle.read(instance, gen)
def save(self, instance, stream):
data = getattr(instance, self.variable, None)
if data is not None:
OptionalWholeRecord.save(self, instance, stream)
self.mag.save(instance, stream)
self.angle.save(instance, stream)
class ACLRecord(SimpleOptionalRecord):
def optional_read(self, instance, unused_gen, rec):
setattr(instance, self.variable, rec.acls)
def save(self, instance, stream):
data = getattr(instance, self.variable, None)
if data:
record.Record(self.gds_record, acls=data).save(stream)
class FormatRecord(SimpleOptionalRecord, SecondVar):
def __init__(self, variable1, variable2, gds_record):
SimpleOptionalRecord.__init__(self, variable1, gds_record)
SecondVar.__init__(self, variable2)
def optional_read(self, instance, gen, rec):
SimpleOptionalRecord.optional_read(self, instance, gen, rec)
cur_rec = gen.curent
if cur_rec.tag == tags.MASK:
masks = []
while cur_rec.tag == tags.MASK:
masks.append(cur_rec.data)
cur_rec = gen.read_next()
cur_rec.check_tag(tags.ENDMASKS)
setattr(instance, self.variable2, masks)
gen.read_next()
def save(self, instance, stream):
fmt = getattr(instance, self.variable, None)
if fmt is not None:
SimpleOptionalRecord.save(self, instance, stream)
masks = getattr(instance, self.variable2, None)
if masks:
for mask in masks:
record.Record(tags.MASK, mask).save(stream)
record.Record(tags.ENDMASKS).save(stream)
class UnitsRecord(SimpleRecord, SecondVar):
def __init__(self, variable1, variable2, gds_record):
SimpleRecord.__init__(self, variable1, gds_record)
SecondVar.__init__(self, variable2)
def read(self, instance, gen):
rec = gen.current
rec.check_tag(self.gds_record)
rec.check_size(2)
unit1, unit2 = rec.data
setattr(instance, self.variable, unit1)
setattr(instance, self.variable2, unit2)
gen.read_next()
def save(self, instance, stream):
unit1 = getattr(instance, self.variable)
unit2 = getattr(instance, self.variable2)
record.Record(self.gds_record, (unit1, unit2)).save(stream)

390
gdsii/elements.py Normal file
View File

@ -0,0 +1,390 @@
# -*- coding: utf-8 -*-
#
# Copyright © 2010 Eugeniy Meshcheryakov <eugen@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`gdsii.elements` -- interface to GDSII elements
====================================================
This module contains definitions for classes representing
various GDSII elements. Mapping between GDSII elements and
classes is given in the following table:
+-------------------+-------------------+
| GDSII Record | Class |
+===================+===================+
| :const:`AREF` | :class:`ARef` |
+-------------------+-------------------+
| :const:`BOUNDARY` | :class:`Boundary` |
+-------------------+-------------------+
| :const:`BOX` | :class:`Box` |
+-------------------+-------------------+
| :const:`NODE` | :class:`Node` |
+-------------------+-------------------+
| :const:`PATH` | :class:`Path` |
+-------------------+-------------------+
| :const:`SREF` | :class:`SRef` |
+-------------------+-------------------+
| :const:`TEXT` | :class:`Text` |
+-------------------+-------------------+
This module implements the following GDS syntax:
.. productionlist::
element: `aref` |
: `boundary` |
: `box` |
: `node` |
: `path` |
: `sref` |
: `text`
Additional definitions:
.. productionlist::
properties: `property`*
property: PROPATTR
: PROPVALUE
strans: STRANS
: [MAG]
: [ANGLE]
.. moduleauthor:: Eugeniy Meshcheryakov <eugen@debian.org>
"""
from __future__ import absolute_import
from . import exceptions, record, tags, _records
__all__ = (
'Boundary',
'Path',
'SRef',
'ARef',
'Text',
'Node',
'Box'
)
_ELFLAGS = _records.OptionalWholeRecord('elflags', tags.ELFLAGS)
_PLEX = _records.SimpleOptionalRecord('plex', tags.PLEX)
_LAYER = _records.SimpleRecord('layer', tags.LAYER)
_DATATYPE = _records.SimpleRecord('data_type', tags.DATATYPE)
_PATHTYPE = _records.SimpleOptionalRecord('path_type', tags.PATHTYPE)
_WIDTH = _records.SimpleOptionalRecord('width', tags.WIDTH)
_BGNEXTN = _records.SimpleOptionalRecord('bgn_extn', tags.BGNEXTN)
_ENDEXTN = _records.SimpleOptionalRecord('end_extn', tags.ENDEXTN)
_XY = _records.XYRecord('xy', tags.XY)
_SNAME = _records.StringRecord('struct_name', tags.SNAME)
_STRANS = _records.STransRecord('strans', tags.STRANS)
_COLROW = _records.ColRowRecord('cols', 'rows')
_TEXTTYPE = _records.SimpleRecord('text_type', tags.TEXTTYPE)
_PRESENTATION = _records.OptionalWholeRecord('presentation', tags.PRESENTATION)
_STRING = _records.StringRecord('string', tags.STRING)
_NODETYPE = _records.SimpleRecord('node_type', tags.NODETYPE)
_BOXTYPE = _records.SimpleRecord('box_type', tags.BOXTYPE)
_PROPERTIES = _records.PropertiesRecord('properties')
class _Base(object):
"""Base class for all GDSII elements."""
# dummy descriptors to silence pyckecker, should be set in derived classes
_gds_tag = None
_gds_objs = None
__slots__ = ()
def __init__(self):
"""Initialize the element."""
self._init_optional()
def _init_optional(self):
"""Initialize optional attributes to None."""
raise NotImplementedError
@classmethod
def _load(cls, gen):
"""
Load an element from file using given generator `gen`.
:param gen: :class:`pygdsii.record.Record` generator
:returns: new element of class defined by `gen`
"""
element_class = cls._tag_to_class_map[gen.current.tag]
if not element_class:
raise exceptions.FormatError('unexpected element tag')
# do not call __init__() during reading from file
# __init__() should require some arguments
new_element = element_class._read_element(gen)
return new_element
@classmethod
def _read_element(cls, gen):
"""Read element using `gen` generator."""
self = cls.__new__(cls)
self._init_optional()
gen.read_next()
for obj in self._gds_objs:
obj.read(self, gen)
gen.current.check_tag(tags.ENDEL)
gen.read_next()
return self
def _save(self, stream):
record.Record(self._gds_tag).save(stream)
for obj in self._gds_objs:
obj.save(self, stream)
record.Record(tags.ENDEL).save(stream)
class Boundary(_Base):
"""
Class for :const:`BOUNDARY` GDSII element.
GDS syntax:
.. productionlist::
boundary: BOUNDARY
: [ELFLAGS]
: [PLEX]
: LAYER
: DATATYPE
: XY
: [`properties`]
: ENDEL
"""
_gds_tag = tags.BOUNDARY
_gds_objs = (_ELFLAGS, _PLEX, _LAYER, _DATATYPE, _XY, _PROPERTIES)
__slots__ = ('layer', 'data_type', 'xy', 'elflags', 'plex', 'properties')
def __init__(self, layer, data_type, xy):
_Base.__init__(self)
self.layer = layer
self.data_type = data_type
self.xy = xy
def _init_optional(self):
self.elflags = None
self.plex = None
self.properties = None
class Path(_Base):
"""
Class for :const:`PATH` GDSII element.
GDS syntax:
.. productionlist::
path: PATH
: [ELFLAGS]
: [PLEX]
: LAYER
: DATATYPE
: [PATHTYPE]
: [WIDTH]
: [BGNEXTN]
: [ENDEXTN]
: XY
: [`properties`]
: ENDEL
"""
_gds_tag = tags.PATH
_gds_objs = (_ELFLAGS, _PLEX, _LAYER, _DATATYPE, _PATHTYPE, _WIDTH,
_BGNEXTN, _ENDEXTN, _XY, _PROPERTIES)
__slots__ = ('layer', 'data_type', 'xy', 'elflags', 'plex', 'path_type',
'width', 'bgn_extn', 'end_extn', 'properties')
def __init__(self, layer, data_type, xy):
_Base.__init__(self)
self.layer = layer
self.data_type = data_type
self.xy = xy
def _init_optional(self):
self.elflags = None
self.plex = None
self.path_type = None
self.width = None
self.bgn_extn = None
self.end_extn = None
self.properties = None
class SRef(_Base):
"""
Class for :const:`SREF` GDSII element.
GDS syntax:
.. productionlist::
sref: SREF
: [ELFLAGS]
: [PLEX]
: SNAME
: [`strans`]
: XY
: [`properties`]
: ENDEL
"""
_gds_tag = tags.SREF
_gds_objs = (_ELFLAGS, _PLEX, _SNAME, _STRANS, _XY, _PROPERTIES)
__slots__ = ('struct_name', 'xy', 'elflags', 'strans', 'mag', 'angle',
'properties')
def __init__(self, struct_name, xy):
_Base.__init__(self)
self.struct_name = struct_name
self.xy = xy
def _init_optional(self):
self.elflags = None
self.strans = None
self.mag = None
self.angle = None
self.properties = None
class ARef(_Base):
"""
Class for :const:`AREF` GDSII element.
GDS syntax:
.. productionlist::
aref: AREF
: [ELFLAGS]
: [PLEX]
: SNAME
: [`strans`]
: COLROW
: XY
: [`properties`]
: ENDEL
"""
_gds_tag = tags.AREF
_gds_objs = (_ELFLAGS, _PLEX, _SNAME, _STRANS, _COLROW, _XY, _PROPERTIES)
__slots__ = ('struct_name', 'cols', 'rows', 'xy', 'elflags', 'plex',
'strans', 'mag', 'angle', 'properties')
def __init__(self, struct_name, cols, rows, xy):
_Base.__init__(self)
self.struct_name = struct_name
self.cols = cols
self.rows = rows
self.xy = xy
def _init_optional(self):
self.elflags = None
self.plex = None
self.strans = None
self.mag = None
self.angle = None
self.properties = None
class Text(_Base):
"""
Class for :const:`TEXT` GDSII element.
GDS syntax:
.. productionlist::
text: TEXT
: [ELFLAGS]
: [PLEX]
: LAYER
: TEXTTYPE
: [PRESENTATION]
: [PATHTYPE]
: [WIDTH]
: [`strans`]
: XY
: STRING
: [`properties`]
: ENDEL
"""
_gds_tag = tags.TEXT
_gds_objs = (_ELFLAGS, _PLEX, _LAYER, _TEXTTYPE, _PRESENTATION, _PATHTYPE,
_WIDTH, _STRANS, _XY, _STRING, _PROPERTIES)
__slots__ = ('layer', 'text_type', 'xy', 'string', 'elflags', 'plex',
'presentation', 'path_type', 'width', 'strans', 'mag', 'angle',
'properties')
def __init__(self, layer, text_type, xy, string):
_Base.__init__(self)
self.layer = layer
self.text_type = text_type
self.xy = xy
self.string = string
def _init_optional(self):
self.elflags = None
self.plex = None
self.presentation = None
self.path_type = None
self.width = None
self.strans = None
self.mag = None
self.angle = None
self.properties = None
class Node(_Base):
"""
Class for :const:`NODE` GDSII element.
GDS syntax:
.. productionlist::
node: NODE
: [ELFLAGS]
: [PLEX]
: LAYER
: NODETYPE
: XY
: [`properties`]
: ENDEL
"""
_gds_tag = tags.NODE
_gds_objs = (_ELFLAGS, _PLEX, _LAYER, _NODETYPE, _XY, _PROPERTIES)
__slots__ = ('layer', 'node_type', 'xy', 'elflags', 'plex', 'properties')
def __init__(self, layer, node_type, xy):
_Base.__init__(self)
self.layer = layer
self.node_type = node_type
self.xy = xy
def _init_optional(self):
self.elflags = None
self.plex = None
self.properties = None
class Box(_Base):
"""
Class for :const:`BOX` GDSII element.
GDS syntax:
.. productionlist::
box: BOX
: [ELFLAGS]
: [PLEX]
: LAYER
: BOXTYPE
: XY
: [`properties`]
: ENDEL
"""
_gds_tag = tags.BOX
_gds_objs = (_ELFLAGS, _PLEX, _LAYER, _BOXTYPE, _XY, _PROPERTIES)
__slots__ = ('layer', 'box_type', 'xy', 'elflags', 'plex', 'properties')
def __init__(self, layer, box_type, xy):
_Base.__init__(self)
self.layer = layer
self.box_type = box_type
self.xy = xy
def _init_optional(self):
self.elflags = None
self.plex = None
self.properties = None
_all_elements = (Boundary, Path, SRef, ARef, Text, Node, Box)
_Base._tag_to_class_map = (lambda: dict(((cls._gds_tag, cls) for cls in _all_elements)))()

42
gdsii/exceptions.py Normal file
View File

@ -0,0 +1,42 @@
# -*- coding: utf-8 -*-
#
# Copyright © 2010 Eugeniy Meshcheryakov <eugen@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`gdsii.exceptions` --- GDSII exceptions
============================================
This module contains exception classes used in `python-gdsii`.
"""
__all__ = ('FormatError', 'EndOfFileError', 'IncorrectDataSize',
'UnsupportedTagType', 'MissingRecord', 'DataSizeError')
class FormatError(Exception):
"""Base class for all GDSII exceptions."""
class EndOfFileError(FormatError):
"""Raised on unexpected end of file."""
class IncorrectDataSize(FormatError):
"""Raised if data size is incorrect."""
class UnsupportedTagType(FormatError):
"""Raised on unsupported tag type."""
class MissingRecord(FormatError):
"""Raised when required record is not found."""
class DataSizeError(FormatError):
"""Raised when data size is incorrect for a given record."""

139
gdsii/library.py Normal file
View File

@ -0,0 +1,139 @@
# -*- coding: utf-8 -*-
#
# Copyright © 2010 Eugeniy Meshcheryakov <eugen@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`gdsii.library` --- interface to a GDSII library
=====================================================
This module contains class that represents a GDSII library.
.. moduleauthor:: Eugeniy Meshcheryakov <eugen@debian.org>
"""
from __future__ import absolute_import
from . import exceptions, record, structure, tags, _records
from datetime import datetime
_HEADER = _records.SimpleRecord('version', tags.HEADER)
_BGNLIB = _records.TimestampsRecord('mod_time', 'acc_time', tags.BGNLIB)
_LIBDIRSIZE = _records.SimpleOptionalRecord('libdirsize', tags.LIBDIRSIZE)
_SRFNAME = _records.OptionalWholeRecord('srfname', tags.SRFNAME)
_LIBSECUR = _records.ACLRecord('acls', tags.LIBSECUR)
_LIBNAME = _records.StringRecord('name', tags.LIBNAME)
_REFLIBS = _records.OptionalWholeRecord('reflibs', tags.REFLIBS)
_FONTS = _records.OptionalWholeRecord('fonts', tags.FONTS)
_ATTRTABLE = _records.OptionalWholeRecord('attrtable', tags.ATTRTABLE)
_GENERATIONS = _records.SimpleOptionalRecord('generations', tags.GENERATIONS)
_FORMAT = _records.FormatRecord('format', 'masks', tags.FORMAT)
_UNITS = _records.UnitsRecord('logical_unit', 'physical_unit', tags.UNITS)
class Library(list):
"""
GDSII library class. This class is derived from :class:`list` and can contain
one one more instances of :class:`gdsii.structure.Structure`.
GDS syntax for the library:
.. productionlist::
library: HEADER
: BGNLIB
: [LIBDIRSIZE]
: [SRFNAME]
: [LIBSECUR]
: LIBNAME
: [REFLIBS]
: [FONTS]
: [ATTRTABLE]
: [GENERATIONS]
: [`format`]
: UNITS
: {`structure`}*
: ENDLIB
format: FORMAT
: [MASK+ ENDMASKS]
"""
_gds_objs = (_HEADER, _BGNLIB, _LIBDIRSIZE, _SRFNAME, _LIBSECUR, _LIBNAME, _REFLIBS,
_FONTS, _ATTRTABLE, _GENERATIONS, _FORMAT, _UNITS)
def __init__(self, version, name, physical_unit, logical_unit, mod_time=None,
acc_time=None):
"""
Initialize the library.
`mod_time` and `acc_time` are set to current UTC time by default.
"""
list.__init__(self)
self.version = version
self.name = name
self.physical_unit = physical_unit
self.logical_unit = logical_unit
self.mod_time = mod_time if mod_time is not None else datetime.utcnow()
self.acc_time = acc_time if acc_time is not None else datetime.utcnow()
self._init_optional()
def _init_optional(self):
"""Initialize optional attributes to None."""
self.libdirsize = None
self.srfname = None
self.acls = None
self.reflibs = None
self.fonts = None
self.attrtable = None
self.generations = None
self.format = None
self.masks = None
@classmethod
def load(cls, stream):
"""
Load a GDS library from a file.
:param stream: a :class:`file` or file-like object opened for reading in binary mode.
:returns: a new library.
"""
self = cls.__new__(cls)
list.__init__(self)
self._init_optional()
gen = record.Reader(stream)
gen.read_next()
for obj in self._gds_objs:
obj.read(self, gen)
# read structures starting with BGNSTR or ENDLIB
rec = gen.current
while True:
if rec.tag == tags.BGNSTR:
self.append(structure.Structure._load(gen))
rec = gen.read_next()
elif rec.tag == tags.ENDLIB:
break
else:
raise exceptions.FormatError('unexpected tag where BGNSTR or ENDLIB are expected: %d', rec.tag)
return self
def save(self, stream):
"""
Save the library into a file.
:param stream: a :class:`file` or file-like object opened for writing in binary mode.
"""
for obj in self._gds_objs:
obj.save(self, stream)
for struc in self:
struc._save(stream)
record.Record(tags.ENDLIB).save(stream)
def __repr__(self):
return '<Library: %s>' % self.name.decode()

578
gdsii/record.py Normal file
View File

@ -0,0 +1,578 @@
# -*- coding: utf-8 -*-
#
# Copyright © 2010 Eugeniy Meshcheryakov <eugen@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`gdsii.record` --- GDSII record I/O
========================================
This module contains classes for low-level GDSII I/O.
.. moduleauthor:: Eugeniy Meshcheryakov <eugen@debian.org>
"""
from __future__ import absolute_import
from . import exceptions, tags, types
from datetime import datetime
import math
import struct
__all__ = [
'Record',
'Reader'
]
_RECORD_HEADER_FMT = struct.Struct('>HH')
def _parse_nodata(data):
"""Parse :const:`NODATA` data type. Does nothing."""
def _parse_bitarray(data):
"""
Parse :const:`BITARRAY` data type.
>>> _parse_bitarray(b'ab') # ok, 2 bytes
24930
>>> _parse_bitarray(b'abcd') # too long
Traceback (most recent call last):
...
IncorrectDataSize: BITARRAY
>>> _parse_bitarray('') # zero bytes
Traceback (most recent call last):
...
IncorrectDataSize: BITARRAY
"""
if len(data) != 2:
raise exceptions.IncorrectDataSize('BITARRAY')
(val,) = struct.unpack('>H', data)
return val
def _parse_int2(data):
"""
Parse INT2 data type.
>>> _parse_int2(b'abcd') # ok, even number of bytes
(24930, 25444)
>>> _parse_int2(b'abcde') # odd number of bytes
Traceback (most recent call last):
...
IncorrectDataSize: INT2
>>> _parse_int2(b'') # zero bytes
Traceback (most recent call last):
...
IncorrectDataSize: INT2
"""
data_len = len(data)
if not data_len or (data_len % 2):
raise exceptions.IncorrectDataSize('INT2')
return struct.unpack('>%dh' % (data_len//2), data)
def _parse_int4(data):
"""
Parse INT4 data type.
>>> _parse_int4(b'abcd')
(1633837924,)
>>> _parse_int4(b'abcdef') # not divisible by 4
Traceback (most recent call last):
...
IncorrectDataSize: INT4
>>> _parse_int4(b'') # zero bytes
Traceback (most recent call last):
...
IncorrectDataSize: INT4
"""
data_len = len(data)
if not data_len or (data_len % 4):
raise exceptions.IncorrectDataSize('INT4')
return struct.unpack('>%dl' % (data_len//4), data)
def _int_to_real(num):
"""
Convert REAL8 from internal integer representation to Python reals.
Zeroes:
>>> print(_int_to_real(0x0))
0.0
>>> print(_int_to_real(0x8000000000000000)) # negative
0.0
>>> print(_int_to_real(0xff00000000000000)) # denormalized
0.0
Others:
>>> print(_int_to_real(0x4110000000000000))
1.0
>>> print(_int_to_real(0xC120000000000000))
-2.0
"""
sgn = -1 if 0x8000000000000000 & num else 1
mant = num & 0x00ffffffffffffff
exp = (num >> 56) & 0x7f
return math.ldexp(sgn * mant, 4 * (exp - 64) - 56)
def _parse_real8(data):
"""
Parse REAL8 data type.
>>> _parse_real8(struct.pack('>3Q', 0x0, 0x4110000000000000, 0xC120000000000000))
(0.0, 1.0, -2.0)
>>> _parse_real8(b'') # zero bytes
Traceback (most recent call last):
...
IncorrectDataSize: REAL8
>>> _parse_real8(b'abcd') # not divisible by 8
Traceback (most recent call last):
...
IncorrectDataSize: REAL8
"""
data_len = len(data)
if not data_len or (data_len % 8):
raise exceptions.IncorrectDataSize('REAL8')
ints = struct.unpack('>%dQ' % (data_len//8), data)
return tuple(_int_to_real(n) for n in ints)
def _parse_ascii(data):
r"""
Parse ASCII data type.
>>> _parse_ascii(b'') # zero bytes
Traceback (most recent call last):
...
IncorrectDataSize: ASCII
>>> _parse_ascii(b'abcde') == b'abcde'
True
>>> _parse_ascii(b'abcde\0') == b'abcde' # strips trailing NUL
True
"""
if not len(data):
raise exceptions.IncorrectDataSize('ASCII')
# XXX cross-version compatibility
if data[-1:] == b'\0':
return data[:-1]
return data
_PARSE_FUNCS = {
types.NODATA: _parse_nodata,
types.BITARRAY: _parse_bitarray,
types.INT2: _parse_int2,
types.INT4: _parse_int4,
types.REAL8: _parse_real8,
types.ASCII: _parse_ascii
}
def _pack_nodata(data):
"""
Pack NODATA tag data. Should always return empty string::
>>> packed = _pack_nodata([])
>>> packed == b''
True
>>> len(packed)
0
"""
return b''
def _pack_bitarray(data):
"""
Pack BITARRAY tag data.
>>> packed = _pack_bitarray(123)
>>> packed == struct.pack('>H', 123)
True
>>> len(packed)
2
"""
return struct.pack('>H', data)
def _pack_int2(data):
"""
Pack INT2 tag data.
>>> _pack_int2([1, 2, -3]) == struct.pack('>3h', 1, 2, -3)
True
>>> packed = _pack_int2((1, 2, 3))
>>> packed == struct.pack('>3h', 1, 2, 3)
True
>>> len(packed)
6
"""
size = len(data)
return struct.pack('>{0}h'.format(size), *data)
def _pack_int4(data):
"""
Pack INT4 tag data.
>>> _pack_int4([1, 2, -3]) == struct.pack('>3l', 1, 2, -3)
True
>>> packed = _pack_int4((1, 2, 3))
>>> packed == struct.pack('>3l', 1, 2, 3)
True
>>> len(packed)
12
"""
size = len(data)
return struct.pack('>{0}l'.format(size), *data)
def _real_to_int(fnum):
"""
Convert REAL8 from Python real to internal integer representation.
>>> '0x%016x' % _real_to_int(0.0)
'0x0000000000000000'
>>> print(_int_to_real(_real_to_int(1.0)))
1.0
>>> print(_int_to_real(_real_to_int(-2.0)))
-2.0
>>> print(_int_to_real(_real_to_int(1e-9)))
1e-09
"""
# first convert number to IEEE double and split it in parts
(ieee,) = struct.unpack('=Q', struct.pack('=d', fnum))
sign = ieee & 0x8000000000000000
ieee_exp = (ieee >> 52) & 0x7ff
ieee_mant = ieee & 0xfffffffffffff
if ieee_exp == 0:
# zero or denormals
# TODO maybe handle denormals
return 0
# substract exponent bias
unb_ieee_exp = ieee_exp - 1023
# add leading one and move to GDSII position
ieee_mant_full = (ieee_mant + 0x10000000000000) << 3
# convert exponent to 16-based, +1 for differences in presentation
# of mantissa (1.xxxx in EEEE and 0.1xxxxx in GDSII
exp16, rest = divmod(unb_ieee_exp + 1, 4)
# compensate exponent converion
if rest:
rest = 4 - rest
exp16 += 1
ieee_mant_comp = ieee_mant_full >> rest
# add GDSII exponent bias
exp16_biased = exp16 + 64
# try to fit everything
if exp16_biased < -14:
return 0 # number is too small. FIXME is it possible?
elif exp16_biased < 0:
ieee_mant_comp = ieee_mant_comp >> (exp16_biased * 4)
exp16_biased = 0
elif exp16_biased > 0x7f:
raise exceptions.FormatError('number is to big for REAL8')
return sign | (exp16_biased << 56) | ieee_mant_comp
def _pack_real8(data):
"""
Pack REAL8 tag data.
>>> packed = _pack_real8([0, 1, -1, 0.5, 1e-9])
>>> len(packed)
40
>>> list(map(str, _parse_real8(packed)))
['0.0', '1.0', '-1.0', '0.5', '1e-09']
"""
size = len(data)
return struct.pack('>{0}Q'.format(size), *[_real_to_int(num) for num in data])
def _pack_ascii(data):
r"""
Pack ASCII tag data.
>>> _pack_ascii(b'abcd') == b'abcd'
True
>>> _pack_ascii(b'abc') == b'abc\0'
True
"""
size = len(data)
if size % 2:
return data + b'\0'
return data
_PACK_FUNCS = {
types.NODATA: _pack_nodata,
types.BITARRAY: _pack_bitarray,
types.INT2: _pack_int2,
types.INT4: _pack_int4,
types.REAL8: _pack_real8,
types.ASCII: _pack_ascii
}
class Record(object):
"""
Class for representing a GDSII record with attached data.
Example::
>>> r = Record(tags.STRNAME, 'my_structure')
>>> '%04x' % r.tag
'0606'
>>> r.tag_name
'STRNAME'
>>> r.tag_type
6
>>> r.tag_type_name
'ASCII'
>>> r.data
'my_structure'
>>> r = Record(0xffff, 'xxx') # Unknown tag type
>>> r.tag_name
'0xffff'
>>> r.tag_type_name
'0xff'
"""
__slots__ = ['tag', 'data']
def __init__(self, tag, data=None, points=None, times=None, acls=None):
"""Initialize with tag and parsed data."""
self.tag = tag
if data is not None:
self.data = data
elif points is not None:
new_data = []
# TODO make it faster
for point in points:
new_data.append(point[0])
new_data.append(point[1])
self.data = new_data
elif times is not None:
mod_time = times[0]
acc_time = times[1]
self.data = (
mod_time.year - 1900,
mod_time.month,
mod_time.day,
mod_time.hour,
mod_time.minute,
mod_time.second,
acc_time.year - 1900,
acc_time.month,
acc_time.day,
acc_time.hour,
acc_time.minute,
acc_time.second
)
elif acls is not None:
new_data = []
for acl in acls:
new_data.extend(acl)
self.data = new_data
else:
self.data = None
def check_tag(self, tag):
"""
Checks if current record has the same tag as the given one.
Raises :exc:`MissingRecord` exception otherwise. For example::
>>> rec = Record(tags.STRNAME, b'struct')
>>> rec.check_tag(tags.STRNAME)
>>> rec.check_tag(tags.DATATYPE)
Traceback (most recent call last):
...
MissingRecord: Wanted: 3586, got: STRNAME
"""
if self.tag != tag:
raise exceptions.MissingRecord('Wanted: %s, got: %s'%(tag, self.tag_name))
def check_size(self, size):
"""
Checks if data size equals to the given size.
Raises :exc:`DataSizeError` otherwise. For example::
>>> rec = Record(tags.DATATYPE, (0,))
>>> rec.check_size(1)
>>> rec.check_size(5)
Traceback (most recent call last):
...
DataSizeError: 3586
"""
if len(self.data) != size:
raise exceptions.DataSizeError(self.tag)
@classmethod
def read(cls, stream):
"""
Read a GDSII record from file.
:param stream: GDS file opened for reading in binary mode
:returns: a new :class:`Record` instance
:raises: :exc:`UnsupportedTagType` if data cannot be parsed
:raises: :exc:`EndOfFileError` if end of file is reached
"""
header = stream.read(4)
if not header or len(header) != 4:
raise exceptions.EndOfFileError
data_size, tag = _RECORD_HEADER_FMT.unpack(header)
if data_size < 4:
raise exceptions.IncorrectDataSize('data size is too small')
if data_size % 2:
raise exceptions.IncorrectDataSize('data size is odd')
data_size -= 4 # substract header size
data = stream.read(data_size)
if len(data) != data_size:
raise exceptions.EndOfFileError
tag_type = tags.type_of_tag(tag)
try:
parse_func = _PARSE_FUNCS[tag_type]
except KeyError:
raise exceptions.UnsupportedTagType(tag_type)
return cls(tag, parse_func(data))
def save(self, stream):
"""
Save record to a GDS file.
:param stream: file opened for writing in binary mode
:raises: :exc:`UnsupportedTagType` if tag type is not supported
:raises: :exc:`FormatError` on incorrect data sizes, etc
:raises: whatever :func:`struct.pack` can raise
"""
tag_type = self.tag_type
try:
pack_func = _PACK_FUNCS[tag_type]
except KeyError:
raise exceptions.UnsupportedTagType(tag_type)
packed_data = pack_func(self.data)
record_size = len(packed_data) + 4
if record_size > 0xFFFF:
raise exceptions.FormatError('data size is too big')
header = _RECORD_HEADER_FMT.pack(record_size, self.tag)
stream.write(header)
stream.write(packed_data)
@property
def tag_name(self):
"""Tag name, if known, otherwise tag ID formatted as hex number."""
if self.tag in tags.REV_DICT:
return tags.REV_DICT[self.tag]
return '0x%04x' % self.tag
@property
def tag_type(self):
"""Tag data type ID."""
return tags.type_of_tag(self.tag)
@property
def tag_type_name(self):
"""Tag data type name, if known, and formatted number otherwise."""
tag_type = tags.type_of_tag(self.tag)
if tag_type in types.REV_DICT:
return types.REV_DICT[tag_type]
return '0x%02x' % tag_type
@property
def points(self):
"""
Convert data to list of points. Useful for :const:`XY` record.
Raises :exc:`DataSizeError` if data size is incorrect.
For example::
>>> r = Record(tags.XY, [0, 1, 2, 3])
>>> r.points
[(0, 1), (2, 3)]
>>> r = Record(tags.XY, []) # not allowed
>>> r.points
Traceback (most recent call last):
...
DataSizeError: 4099
>>> r = Record(tags.XY, [1, 2, 3]) # odd number of coordinates
>>> r.points
Traceback (most recent call last):
...
DataSizeError: 4099
"""
data_size = len(self.data)
if not data_size or (data_size % 2):
raise exceptions.DataSizeError(self.tag)
return [(self.data[i], self.data[i+1]) for i in range(0, data_size, 2)]
@property
def times(self):
"""
Convert data to tuple ``(modification time, access time)``.
Useful for :const:`BGNLIB` and :const:`BGNSTR`.
>>> r = Record(tags.BGNLIB, [100, 1, 1, 1, 2, 3, 110, 8, 14, 21, 10, 35])
>>> print(r.times[0].isoformat())
2000-01-01T01:02:03
>>> print(r.times[1].isoformat())
2010-08-14T21:10:35
>>> r = Record(tags.BGNLIB, [100, 1, 1, 1, 2, 3]) # wrong data length
>>> r.times
Traceback (most recent call last):
...
DataSizeError: 258
"""
if len(self.data) != 12:
raise exceptions.DataSizeError(self.tag)
return (datetime(self.data[0]+1900, *self.data[1:6]),
datetime(self.data[6]+1900, *self.data[7:12]))
@property
def acls(self):
"""
Convert data to list of acls ``(GID, UID, ACCESS)``.
Useful for :const:`LIBSECUR`.
>>> r = Record(tags.LIBSECUR, [1, 2, 3, 4, 5, 6])
>>> r.acls
[(1, 2, 3), (4, 5, 6)]
>>> r = Record(tags.LIBSECUR, [1, 2, 3, 4]) # wrong data size
>>> r.acls
Traceback (most recent call last):
...
DataSizeError: 15106
"""
if len(self.data) % 3:
raise exceptions.DataSizeError(self.tag)
return list(zip(self.data[::3], self.data[1::3], self.data[2::3]))
@classmethod
def iterate(cls, stream):
"""
Generator function for iterating over all records in a GDSII file.
Yields :class:`Record` objects.
:param stream: GDS file opened for reading in binary mode
"""
last = False
while not last:
rec = cls.read(stream)
if rec.tag == tags.ENDLIB:
last = True
yield rec
class Reader(object):
"""Class for buffered reading of Records"""
__slots__ = ('current', 'stream')
def __init__(self, stream):
self.stream = stream
def read_next(self):
"""Read and return next record from stream."""
self.current = Record.read(self.stream)
return self.current
if __name__ == '__main__':
import doctest
doctest.testmod(optionflags=doctest.IGNORE_EXCEPTION_DETAIL)

84
gdsii/structure.py Normal file
View File

@ -0,0 +1,84 @@
# -*- coding: utf-8 -*-
#
# Copyright © 2010 Eugeniy Meshcheryakov <eugen@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`gdsii.structure` --- interface to a GDSII structure
=========================================================
This module contains class that represents a GDSII structure.
.. moduleauthor:: Eugeniy Meshcheryakov <eugen@debian.org>
"""
from __future__ import absolute_import
from . import elements, record, tags, _records
from datetime import datetime
_STRNAME = _records.StringRecord('name', tags.STRNAME)
_BGNSTR = _records.TimestampsRecord('mod_time', 'acc_time', tags.BGNSTR)
_STRCLASS = _records.SimpleOptionalRecord('strclass', tags.STRCLASS)
class Structure(list):
"""
GDSII structure class. This class is derived for :class:`list` and can
contain one or more elements from :mod:`gdsii.elements`.
GDS syntax for the structure:
.. productionlist::
structure: BGNSTR
: STRNAME
: [STRCLASS]
: {`element`}*
: ENDSTR
"""
_gds_objs = (_BGNSTR, _STRNAME, _STRCLASS)
def __init__(self, name, mod_time=None, acc_time=None):
"""
Initialize the structure.
`mod_time` and `acc_time` are set to current UTC time by default.
"""
list.__init__(self)
self.name = name
self.mod_time = mod_time if mod_time is not None else datetime.utcnow()
self.acc_time = acc_time if acc_time is not None else datetime.utcnow()
def _init_optional(self):
"""Initialize optional attributes to None."""
self.strclass = None
@classmethod
def _load(cls, gen):
self = cls.__new__(cls)
list.__init__(self)
self._init_optional()
for obj in self._gds_objs:
obj.read(self, gen)
# read elements till ENDSTR
while gen.current.tag != tags.ENDSTR:
self.append(elements._Base._load(gen))
return self
def _save(self, stream):
for obj in self._gds_objs:
obj.save(self, stream)
for elem in self:
elem._save(stream)
record.Record(tags.ENDSTR).save(stream)
def __repr__(self):
return '<Structure: %s>' % self.name.decode()

128
gdsii/tags.py Normal file
View File

@ -0,0 +1,128 @@
# -*- coding: utf-8 -*-
#
# Copyright © 2010 Eugeniy Meshcheryakov <eugen@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`gdsii.tags` --- definitions of GDSII tags
===============================================
This module containing definitions of GDSII record tags.
.. moduleauthor:: Eugeniy Meshcheryakov <eugen@debian.org>
"""
DICT = {
'HEADER': 0x0002,
'BGNLIB': 0x0102,
'LIBNAME': 0x0206,
'UNITS': 0x0305,
'ENDLIB': 0x0400,
'BGNSTR': 0x0502,
'STRNAME': 0x0606,
'ENDSTR': 0x0700,
'BOUNDARY': 0x0800,
'PATH': 0x0900,
'SREF': 0x0A00,
'AREF': 0x0B00,
'TEXT': 0x0C00,
'LAYER': 0x0D02,
'DATATYPE': 0x0E02,
'WIDTH': 0x0F03,
'XY': 0x1003,
'ENDEL': 0x1100,
'SNAME': 0x1206,
'COLROW': 0x1302,
'TEXTNODE': 0x1400,
'NODE': 0x1500,
'TEXTTYPE': 0x1602,
'PRESENTATION': 0x1701,
# SPACING: 0x18??
'STRING': 0x1906,
'STRANS': 0x1A01,
'MAG': 0x1B05,
'ANGLE': 0x1C05,
# UINTEGER: 0x1D??
# USTRING: 0x1E??
'REFLIBS': 0x1F06,
'FONTS': 0x2006,
'PATHTYPE': 0x2102,
'GENERATIONS': 0x2202,
'ATTRTABLE': 0x2306,
'STYPTABLE': 0x2406,
'STRTYPE': 0x2502,
'ELFLAGS': 0x2601,
'ELKEY': 0x2703,
# LINKTYPE: 0x28??
# LINKKEYS: 0x29??
'NODETYPE': 0x2A02,
'PROPATTR': 0x2B02,
'PROPVALUE': 0x2C06,
'BOX': 0x2D00,
'BOXTYPE': 0x2E02,
'PLEX': 0x2F03,
'BGNEXTN': 0x3003,
'ENDEXTN': 0x3103,
'TAPENUM': 0x3202,
'TAPECODE': 0x3302,
'STRCLASS': 0x3401,
# RESERVED: 0x3503
'FORMAT': 0x3602,
'MASK': 0x3706,
'ENDMASKS': 0x3800,
'LIBDIRSIZE': 0x3902,
'SRFNAME': 0x3A06,
'LIBSECUR': 0x3B02,
# Types used only with Custom Plus
'BORDER': 0x3C00,
'SOFTFENCE': 0x3D00,
'HARDFENCE': 0x3E00,
'SOFTWIRE': 0x3F00,
'HARDWIRE': 0x4000,
'PATHPORT': 0x4100,
'NODEPORT': 0x4200,
'USERCONSTRAINT': 0x4300,
'SPACERERROR': 0x4400,
'CONTACT': 0x4500
}
REV_DICT = {}
for (key, value) in DICT.items():
globals()[key] = value
REV_DICT[value] = key
del key, value
def type_of_tag(tag):
"""
Returns type of a tag.
:param tag: tag ID
:type tag: int
:rtype: int
Examples:
>>> type_of_tag(HEADER)
2
>>> type_of_tag(MASK)
6
"""
return tag & 0xff
if __name__ == '__main__':
import doctest
doctest.testmod()

40
gdsii/types.py Normal file
View File

@ -0,0 +1,40 @@
# -*- coding: utf-8 -*-
#
# Copyright © 2010 Eugeniy Meshcheryakov <eugen@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`gdsii.types` --- definitions of GDSII data types
======================================================
This module contains definitions of GDSII data types.
"""
DICT = {
'NODATA': 0,
'BITARRAY': 1,
'INT2': 2,
'INT4': 3,
'REAL4': 4, # not used
'REAL8': 5,
'ASCII': 6
}
REV_DICT = {}
for (key, value) in DICT.items():
globals()[key] = value
REV_DICT[value] = key
del key, value

36
scripts/gds2txt Executable file
View File

@ -0,0 +1,36 @@
#! /usr/bin/python
# -*- coding: utf-8 -*-
# Copyright © 2010 Eugeniy Meshcheryakov <eugen@debian.org>
# This file is licensed under GNU Lesser General Public License version 3 or later.
"""Demonstration program for basic gdsii reading function."""
from __future__ import print_function
from gdsii import types
from gdsii.record import Record
import sys
def show_data(rec):
"""Shows data in a human-readable format."""
if rec.tag_type == types.ASCII:
return '"%s"' % rec.data.decode() # TODO escape
elif rec.tag_type == types.BITARRAY:
return str(rec.data)
return ', '.join('{0}'.format(i) for i in rec.data)
def main(name):
with open(name, 'rb') as a_file:
for rec in Record.iterate(a_file):
if rec.tag_type == types.NODATA:
print(rec.tag_name)
else:
print('%s: %s' % (rec.tag_name, show_data(rec)))
def usage(prog):
print('Usage: %s <file.gds>' % prog)
if __name__ == '__main__':
if (len(sys.argv) > 1):
main(sys.argv[1])
else:
usage(sys.argv[0])
sys.exit(1)
sys.exit(0)

222
scripts/gds2yaml Executable file
View File

@ -0,0 +1,222 @@
#! /usr/bin/python
# -*- coding: utf-8 -*-
# Copyright © 2010 Eugeniy Meshcheryakov <eugen@debian.org>
# This file is licensed under GNU Lesser General Public License version 3 or later.
from __future__ import print_function
from gdsii.library import Library
from gdsii import elements
import sys
from yaml.dumper import Dumper
from yaml import events
# standard tags
STR = 'tag:yaml.org,2002:str'
TIMESTAMP = 'tag:yaml.org,2002:timestamp'
FLOAT = 'tag:yaml.org,2002:float'
INT = 'tag:yaml.org,2002:int'
SEQ = 'tag:yaml.org,2002:seq'
MAP = 'tag:yaml.org,2002:map'
# non-standard tags
LIBRARY = 'tag:gdsii,2010:library'
STRUCTURE = 'tag:gdsii,2010:structure'
BOUNDARY = 'tag:gdsii,2010:element:boundary'
PATH = 'tag:gdsii,2010:element:path'
SREF = 'tag:gdsii,2010:element:sref'
AREF = 'tag:gdsii,2010:element:aref'
TEXT = 'tag:gdsii,2010:element:text'
NODE = 'tag:gdsii,2010:element:node'
BOX = 'tag:gdsii,2010:element:box'
def emit_string(dumper, prop, tag, value):
dumper.emit(events.ScalarEvent(None, STR, (True, False), prop))
dumper.emit(events.ScalarEvent(None, tag, (True, False), value))
def start_named_seq(dumper, name):
dumper.emit(events.ScalarEvent(None, STR, (True, False), name))
dumper.emit(events.SequenceStartEvent(None, SEQ, True))
def end_named_seq(dumper):
dumper.emit(events.SequenceEndEvent())
def simple_dumper(name, tag):
def dump_fn(dumper, obj):
value = getattr(obj, name)
emit_string(dumper, name, tag, str(value))
return dump_fn
def simple_string_dumper(name):
def dump_fn(dumper, obj):
value = getattr(obj, name)
emit_string(dumper, name, STR, value.decode())
return dump_fn
def timestamp_dumper(name):
def dump_fn(dumper, obj):
value = getattr(obj, name)
emit_string(dumper, name, TIMESTAMP, value.isoformat(' '))
return dump_fn
def optional_dumper(name, tag):
def dump_fn(dumper, obj):
try:
value = getattr(obj, name)
except AttributeError:
value = None
if value is not None:
emit_string(dumper, name, tag, str(value))
return dump_fn
def optional_flags_dumper(name, tag):
def dump_fn(dumper, obj):
try:
value = getattr(obj, name)
except AttributeError:
value = None
if value is not None:
emit_string(dumper, name, tag, '0x%x'%value)
return dump_fn
def xy_dumper(name):
def dump_fn(dumper, obj):
points = getattr(obj, name)
start_named_seq(dumper, name)
for point in points:
dumper.emit(events.SequenceStartEvent(None, SEQ, True, flow_style=True))
dumper.emit(events.ScalarEvent(None, INT, (True, False), str(point[0])))
dumper.emit(events.ScalarEvent(None, INT, (True, False), str(point[1])))
dumper.emit(events.SequenceEndEvent())
end_named_seq(dumper)
return dump_fn
def properties_dumper(name):
def dump_fn(dumper, obj):
properties = getattr(obj, name)
if (properties):
start_named_seq(dumper, name)
for (prop, value) in properties:
dumper.emit(events.MappingStartEvent(None, MAP, True))
dumper.emit(events.ScalarEvent(None, INT, (True, False), str(prop)))
dumper.emit(events.ScalarEvent(None, STR, (True, False), value.decode()))
dumper.emit(events.MappingEndEvent())
end_named_seq(dumper)
return dump_fn
def strans_dumper(name):
my_dumper = optional_flags_dumper('strans', INT)
mag = optional_dumper('mag', FLOAT)
angle = optional_dumper('angle', FLOAT)
def dump_fn(dumper, obj):
try:
value = getattr(obj, name)
except AttributeError:
value = None
if value is not None:
my_dumper(dumper, obj)
mag(dumper, obj)
angle(dumper, obj)
return dump_fn
elflags = optional_flags_dumper('elflags', INT)
plex = optional_dumper('plex', INT)
layer = simple_dumper('layer', INT)
data_type = simple_dumper('data_type', INT)
path_type = optional_dumper('path_type', INT)
width = optional_dumper('width', INT)
bgn_extn = optional_dumper('bgn_extn', INT)
end_extn = optional_dumper('end_extn', INT)
struct_name = simple_string_dumper('struct_name')
strans = strans_dumper('strans')
cols = simple_dumper('cols', INT)
rows = simple_dumper('rows', INT)
text_type = optional_dumper('text_type', INT)
presentation = optional_flags_dumper('presentation', INT)
string = simple_string_dumper('string')
node_type = simple_dumper('node_type', INT)
box_type = simple_dumper('box_type', INT)
xy = xy_dumper('xy')
properties = properties_dumper('properties')
DUMPERS = (
(elements.Boundary, BOUNDARY, (elflags, plex, layer, data_type, xy, properties)),
(elements.Path, PATH, (elflags, plex, layer, data_type, path_type, width, bgn_extn, end_extn, xy, properties)),
(elements.SRef, SREF, (elflags, plex, struct_name, strans, xy, properties)),
(elements.ARef, AREF, (elflags, plex, struct_name, strans, cols, rows, xy, properties)),
(elements.Text, TEXT, (elflags, plex, layer, text_type, presentation, path_type, width, strans, xy, string, properties)),
(elements.Node, NODE, (elflags, plex, layer, node_type, xy)),
(elements.Box, BOX, (elflags, plex, layer, box_type, xy, properties))
)
def dump_element(dumper, elem):
for rec in DUMPERS:
if isinstance(elem, rec[0]):
tag = rec[1]
dumpers = rec[2]
dumper.emit(events.MappingStartEvent(None, tag, False))
for fn in dumpers:
fn(dumper, elem)
dumper.emit(events.MappingEndEvent())
break
else:
raise Exception('Unsupported element: %s' % str(elem))
name = simple_string_dumper('name')
mod_time = timestamp_dumper('mod_time')
acc_time = timestamp_dumper('acc_time')
strclass = optional_dumper('strclass', INT)
def dump_structure(dumper, struc):
dumper.emit(events.MappingStartEvent(None, STRUCTURE, False))
name(dumper, struc)
mod_time(dumper, struc)
acc_time(dumper, struc)
strclass(dumper, struc)
start_named_seq(dumper, 'elements')
for elem in struc:
dump_element(dumper, elem)
end_named_seq(dumper)
dumper.emit(events.MappingEndEvent())
physical_unit = simple_dumper('physical_unit', FLOAT)
logical_unit = simple_dumper('logical_unit', FLOAT)
libdirsize = optional_dumper('libdirsize', INT)
def dump_library(dumper, lib):
dumper.emit(events.StreamStartEvent(encoding='utf-8'))
dumper.emit(events.DocumentStartEvent(explicit=False))
dumper.emit(events.MappingStartEvent(None, LIBRARY, False))
emit_string(dumper, 'version', INT, '0x%x'%lib.version)
name(dumper, lib)
mod_time(dumper, lib)
acc_time(dumper, lib)
libdirsize(dumper, lib)
# TODO
physical_unit(dumper, lib)
logical_unit(dumper, lib)
start_named_seq(dumper, 'structures')
for struc in lib:
dump_structure(dumper, struc)
end_named_seq(dumper)
dumper.emit(events.MappingEndEvent())
dumper.emit(events.DocumentEndEvent(explicit=False))
dumper.emit(events.StreamEndEvent())
def main(name):
with open(name, 'rb') as a_file:
lib = Library.load(stream=a_file)
dumper = Dumper(sys.stdout)
dump_library(dumper, lib)
def usage(prog):
print('Usage: %s <file.gds>' % prog)
if __name__ == '__main__':
if (len(sys.argv) > 1):
main(sys.argv[1])
else:
usage(sys.argv[0])
sys.exit(1)
sys.exit(0)

65
scripts/txt2gds Executable file
View File

@ -0,0 +1,65 @@
#! /usr/bin/python
# -*- coding: utf-8 -*-
# Copyright © 2011 Eugeniy Meshcheryakov <eugen@debian.org>
# This file is licensed under GNU Lesser General Public License version 3 or later.
"""Converter from format produced by gds2txt back to GDSII."""
from __future__ import print_function
from gdsii import tags, types
from gdsii.record import Record
import sys
import getopt
import re
def parse_file(ifile, ofile):
rexp = re.compile(r'^(?P<tag>[^:]+)(:\s*(?P<rest>.*))?$')
lineno = 1
for line in ifile:
stripped = line.strip()
m = rexp.match(stripped)
if not m:
print('Parse error at line {0}'.format(lineno), file=sys.stderr)
sys.exit(1)
tag_name = m.group('tag')
rest = m.group('rest')
tag = tags.DICT[tag_name]
tag_type = tags.type_of_tag(tag)
if tag_type == types.NODATA:
data = None
elif tag_type == types.ASCII:
data = rest[1:-1].encode() # FIXME
elif tag_type == types.BITARRAY:
data = int(rest)
elif tag_type == types.REAL8:
data = [float(s) for s in rest.split(',')]
elif tag_type == types.INT2 or tag_type == types.INT4:
data = [int(s) for s in rest.split(',')]
else:
raise Exception('Unsupported type')
rec = Record(tag, data)
rec.save(ofile)
lineno += 1
def main(argv):
opts, args = getopt.gnu_getopt(argv[1:], 'o:')
if len(opts) != 1 or opts[0][0] != '-o' or len(args) > 1:
usage(argv[0])
sys.exit(2)
with open(opts[0][1], 'wb') as ofile:
if len(args) == 0:
parse_file(sys.stdin, ofile)
else:
with open(args[0], 'r') as ifile:
parse_file(ifile, ofile)
def usage(prog):
print('Usage: %s -o <file.gds> [<input.txt>]' % prog)
if __name__ == '__main__':
if len(sys.argv) > 1:
main(sys.argv)
else:
usage(sys.argv[0])
sys.exit(1)

38
setup.py Normal file
View File

@ -0,0 +1,38 @@
from distutils.core import setup
long_desc = """
python-gdsii is a library that can be used to read, create, modify and save
GDSII files. It supports both low-level record I/O and high level interface to
GDSII libraries (databases), structures, and elements.
This package also includes scripts that can be used to convert binary GDS file
to a simple text format (gds2txt), YAML (gds2yaml), and from text fromat back
to GDSII (txt2gds).
"""
setup(
name = 'python-gdsii',
version = '0.2.1',
description = 'GDSII manipulation libaray',
long_description = long_desc,
author = 'Eugeniy Meshcheryakov',
author_email = 'eugen@debian.org',
url = 'http://www.gitorious.org/python-gdsii',
packages = ['gdsii'],
scripts = [
'scripts/gds2txt',
'scripts/gds2yaml',
'scripts/txt2gds',
],
classifiers = [
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: Electronic Design Automation (EDA)',
'Topic :: Software Development :: Libraries :: Python Modules'
],
license = 'LGPL-3+',
platforms = 'any'
)

0
test/__init__.py Normal file
View File

BIN
test/data/test1.gds Normal file

Binary file not shown.

24
test/data/test1.txt Normal file
View File

@ -0,0 +1,24 @@
HEADER: 5
BGNLIB: 110, 8, 17, 14, 22, 22, 110, 8, 17, 14, 36, 21
LIBNAME: "TEST.DB"
UNITS: 0.001, 1e-09
BGNSTR: 70, 1, 1, 1, 0, 0, 110, 8, 17, 14, 35, 55
STRNAME: "test_struc1"
BOUNDARY
LAYER: 34
DATATYPE: 0
XY: 33100, -198900, 48100, -198900, 48100, -186800, 33100, -186800, 33100, -198900
ENDEL
PATH
LAYER: 44
DATATYPE: 0
PATHTYPE: 0
WIDTH: 15000
XY: -125000, 0, -125000, -52000, -52000, -125000, 13100, -125000
PROPATTR: 1
PROPVALUE: "test property 1"
PROPATTR: 2
PROPVALUE: "test property 2"
ENDEL
ENDSTR
ENDLIB

60
test/test_lib.py Normal file
View File

@ -0,0 +1,60 @@
import unittest
from gdsii import library, elements
import os.path
class TestLibraryLoad(unittest.TestCase):
def setUp(self):
file_name = os.path.join(os.path.dirname(__file__), 'data', 'test1.gds')
with open(file_name, 'rb') as stream:
self.library = library.Library.load(stream)
def test_library(self):
library = self.library
self.assertEqual(library.version, 5)
self.assertEqual(library.name, b'TEST.DB')
self.assertEqual(library.mod_time.isoformat(), '2010-08-17T14:22:22')
self.assertEqual(library.acc_time.isoformat(), '2010-08-17T14:36:21')
self.assertAlmostEqual(library.physical_unit, 1e-9)
self.assertAlmostEqual(library.logical_unit, 0.001)
def test_structure(self):
library = self.library
self.assertEqual(len(library), 1)
struc = library[0]
self.assertEqual(struc.name, b'test_struc1')
self.assertEqual(struc.mod_time.isoformat(), '1970-01-01T01:00:00')
self.assertEqual(struc.acc_time.isoformat(), '2010-08-17T14:35:55')
self.assertEqual(struc.strclass, None)
def test_elements(self):
struc = self.library[0]
self.assertEqual(len(struc), 2)
elem = struc[0]
self.assertTrue(isinstance(elem, elements.Boundary))
self.assertEqual(elem.layer, 34)
self.assertEqual(elem.data_type, 0)
self.assertEqual(elem.xy, [(33100, -198900), (48100, -198900), (48100, -186800),
(33100, -186800), (33100, -198900)])
self.assertEqual(elem.properties, []) # TODO it should not be so
elem = struc[1]
self.assertTrue(isinstance(elem, elements.Path))
self.assertEqual(elem.layer, 44)
self.assertEqual(elem.data_type, 0)
self.assertEqual(elem.path_type, 0)
self.assertEqual(elem.width, 15000)
self.assertEqual(elem.xy, [(-125000, 0), (-125000, -52000), (-52000, -125000), (13100, -125000)])
self.assertEqual(len(elem.properties), 2)
self.assertEqual(elem.properties[0], (1, b'test property 1'))
self.assertEqual(elem.properties[1], (2, b'test property 2'))
test_cases = (TestLibraryLoad,)
def load_tests(loader, tests, pattern):
suite = unittest.TestSuite()
for test_class in test_cases:
tests = loader.loadTestsFromTestCase(test_class)
suite.addTests(tests)
return suite
if __name__ == '__main__':
unittest.main()

66
test/test_record.py Normal file
View File

@ -0,0 +1,66 @@
import unittest
from gdsii.record import _parse_real8, _pack_real8, _int_to_real, _real_to_int
from gdsii import exceptions
import struct
class TestReal8(unittest.TestCase):
data = {
0x4110000000000000: 1.0,
0x4120000000000000: 2.0,
0x4130000000000000: 3.0,
0xC110000000000000: -1.0,
0xC120000000000000: -2.0,
0xC130000000000000: -3.0,
0x4080000000000000: 0.5,
0x4099999999999999: 0.6,
0x40B3333333333333: 0.7,
0x4118000000000000: 1.5,
0x4119999999999999: 1.6,
0x411B333333333333: 1.7,
0x0000000000000000: 0.0,
0x41A0000000000000: 10.0,
0x4264000000000000: 100.0,
0x433E800000000000: 1000.0, # there is error in doc?
0x4427100000000000: 10000.0,
0x45186A0000000000: 100000.0
}
def test_from_int(self):
for int_val, real_val in self.data.items():
self.assertAlmostEqual(_int_to_real(int_val), real_val)
def test_to_int(self):
for int_val, real_val in self.data.items():
self.assertAlmostEqual(real_val, _int_to_real(_real_to_int(real_val)))
def test_parse(self):
packed_data = struct.pack('>{0}Q'.format(len(self.data)), *self.data.keys())
unpacked = _parse_real8(packed_data)
expected_results = list(self.data.values())
self.assertEqual(len(unpacked), len(expected_results))
for i in range(len(unpacked)):
self.assertAlmostEqual(unpacked[i], expected_results[i])
def test_pack(self):
packed_data = _pack_real8(self.data.values())
unpacked = _parse_real8(packed_data)
expected_results = list(self.data.values())
self.assertEqual(len(unpacked), len(expected_results))
for i in range(len(unpacked)):
self.assertAlmostEqual(unpacked[i], expected_results[i])
def test_exceptions(self):
for i in range(8):
self.assertRaises(exceptions.IncorrectDataSize, _parse_real8, b' '*i)
test_cases = (TestReal8,)
def load_tests(loader, tests, pattern):
suite = unittest.TestSuite()
for test_class in test_cases:
tests = loader.loadTestsFromTestCase(test_class)
suite.addTests(tests)
return suite
if __name__ == '__main__':
unittest.main()