Showing preview only (1,817K chars total). Download the full file or copy to clipboard to get everything.
Repository: malcolmw/pykonal
Branch: master
Commit: d91d914d5066
Files: 47
Total size: 38.1 MB
Directory structure:
gitextract_79682ixy/
├── .gitignore
├── LICENSE
├── MANIFEST.in
├── README.md
├── jupyter/
│ ├── Locator2.ipynb
│ ├── figure_3.ipynb
│ ├── figure_4.ipynb
│ ├── figure_5.ipynb
│ ├── figure_6.ipynb
│ ├── figure_7.ipynb
│ └── figure_8.ipynb
├── pykonal/
│ ├── __init__.py
│ ├── __version__.py
│ ├── constants.pxd
│ ├── constants.pyx
│ ├── data/
│ │ ├── ak135.npz
│ │ ├── marmousi2/
│ │ │ ├── LICENSE
│ │ │ ├── README
│ │ │ └── marmousi2.npz
│ │ └── mitp2008.npz
│ ├── fields.pxd
│ ├── fields.pyx
│ ├── heapq.pxd
│ ├── heapq.pyx
│ ├── inventory.py
│ ├── locate.pxd
│ ├── locate.pyx
│ ├── solver.pxd
│ ├── solver.pyx
│ ├── stats.pxd
│ ├── stats.pyx
│ ├── tests/
│ │ ├── data/
│ │ │ └── test_EikonalSolver_uniform_velocity_cartesian.npz
│ │ ├── test_EikonalSolver.py
│ │ ├── test_GridND.py
│ │ └── test_LinearInterpolator3D.py
│ └── transformations.py
├── pyproject.toml
├── scripts/
│ ├── eq_loc/
│ │ ├── eq_loc.cfg
│ │ └── eq_loc.py
│ └── mcmc/
│ ├── 315_loc.cfg
│ └── 315_locate_serial_mcmc.py
├── setup.py
└── tutorials/
├── tomography/
│ ├── cartesian_tomography_2D.ipynb
│ └── vmodel.txt
└── tracing_PKiKP/
├── .ipynb_checkpoints/
│ └── tracing_PKiKP_rays-checkpoint.ipynb
├── IASP91.csv
└── tracing_PKiKP_rays.ipynb
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
*.DS_Store
jupyter/.ipynb_checkpoints
scripts/eq_loc/test_data
*.log
*.cpp
*.c
build
dist
pykonal.egg-info
pykonal/__pycache__
================================================
FILE: LICENSE
================================================
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:
{project} Copyright (C) {year} {fullname}
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>.
================================================
FILE: MANIFEST.in
================================================
include pykonal/*.pyx
include pykonal/*.pxd
include pykonal/*.cpp
include pykonal/data
include README.md
================================================
FILE: README.md
================================================




# Welcome to the *pykonal* repository!
This code implements the Fast Marching Method (FMM; Sethian *et al.*, 1996) for solving the eikonal equation in Cartesian or spherical coordinates in 2 or 3 dimensions. The method implements mixed first- and second-order finite differences.

PyKonal offers two features that are absent from the comparable [scikit-fmm](https://pythonhosted.org/scikit-fmm/ "sckit-fmm documentation") package: (a) an implementation in spherical coordinates, and (b) functionality to compute shortest-traveltime paths.
## Documentation
Documentation is available [here](https://malcolmw.github.io/pykonal-docs/ "PyKonal documentation").
## Citation
If you make use of this code in published work, please cite White *et al.* (2020).
## Installation
### PIP—recommended
```bash
sh$> pip install pykonal
```
### From source code
Download and unzip the [latest release](https://github.com/malcolmw/pykonal/releases "Releases").
```bash
sh$> cd path/to/pykonal
sh$> pip install .
```
## Bugs
Please report bugs, feature requests, and questions through the [Issues](https://github.com/malcolmw/pykonal/issues "PyKonal Issues tracker") tracker.
## References
1. Sethian, J. A. (1996). A fast marching level set method for monotonically advancing fronts. *Proceedings of the National Academy of Sciences, 93*(4), 1591–1595. https://doi.org/10.1073/pnas.93.4.1591
2. White, M. C. A., Fang, H., Nakata, N., & Ben-Zion, Y. (2020). PyKonal: A Python Package for Solving the Eikonal Equation in Spherical and Cartesian Coordinates Using the Fast Marching Method. *Seismological Research Letters, 91*(4), 2378-2389. https://doi.org/10.1785/0220190318
================================================
FILE: jupyter/Locator2.ipynb
================================================
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%load_ext Cython\n",
"import matplotlib.pyplot as plt\n",
"import multiprocessing as mp\n",
"import numpy as np\n",
"import pandas as pd\n",
"import pykonal\n",
"import seispy\n",
"\n",
"DTYPE_REAL = np.float64\n",
"EARTH_RADIUS = 6371.\n",
"\n",
"def geo2sph(arr) -> np.ndarray:\n",
" \"\"\"\n",
" Map Geographical coordinates to spherical coordinates.\n",
" \"\"\"\n",
" geo = np.array(arr, dtype=DTYPE_REAL)\n",
" sph = np.empty_like(geo)\n",
" sph[..., 0] = EARTH_RADIUS - geo[..., 2]\n",
" sph[..., 1] = np.pi / 2 - np.radians(geo[..., 0])\n",
" sph[..., 2] = np.radians(geo[..., 1])\n",
" return (sph)\n",
"\n",
"\n",
"def sph2geo(arr) -> np.ndarray:\n",
" \"\"\"\n",
" Map spherical coordinates to geographic coordinates.\n",
" \"\"\"\n",
" sph = np.array(arr, dtype=DTYPE_REAL)\n",
" geo = np.empty_like(sph)\n",
" geo[..., 0] = np.degrees(np.pi / 2 - sph[..., 1])\n",
" geo[..., 1] = np.degrees(sph[..., 2])\n",
" geo[..., 2] = EARTH_RADIUS - sph[..., 0]\n",
" return (geo)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"outputs": [],
"source": [
"# Load velocity model\n",
"grid = pykonal.fields.ScalarField3D(coord_sys=\"spherical\")\n",
"with np.load(\"/home/malcolmw/google_drive/malcolm.white@usc.edu/data/velocity/White_et_al_2019a/White_et_al_2019a.regular.npz\") as npz:\n",
" grid.min_coords = npz[\"grid_parameters\"][:3]\n",
" grid.node_intervals = npz[\"grid_parameters\"][3:6]\n",
" grid.npts = npz[\"grid_parameters\"][6:] + [1, 0, 0]\n",
" pwave_velocity = np.append(npz[\"vp\"], npz[\"vp\"][[-1]], axis=0)\n",
" swave_velocity = np.append(npz[\"vs\"], npz[\"vs\"][[-1]], axis=0)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"outputs": [],
"source": [
"db = seispy.pandas.catalog.Catalog(\n",
" \"/home/malcolmw/google_drive/malcolm.white@usc.edu/data/events/malcolmw/SJFZ_catalog_2008-2016.h5\",\n",
" fmt=\"hdf5\"\n",
")\n",
"\n",
"stations_dataframe = db[\"site\"][\n",
" [\"sta\", \"lat\", \"lon\", \"elev\"]\n",
"].drop_duplicates(\n",
" \"sta\"\n",
").merge(\n",
" db[\"snetsta\"][\n",
" [\"snet\", \"sta\"]\n",
" ].drop_duplicates(\n",
" \"sta\"\n",
" ),\n",
" on=\"sta\"\n",
")\n",
"stations_dataframe[\"station_id\"] = stations_dataframe[\"snet\"] + \".\" + stations_dataframe[\"sta\"]\n",
"\n",
"arrivals_dataframe = db[\"arrival\"][\n",
" [\"sta\", \"time\", \"arid\"]\n",
"].merge(\n",
" db[\"assoc\"][\n",
" [\"arid\", \"orid\", \"phase\"]\n",
" ],\n",
" on=\"arid\"\n",
").merge(\n",
" stations_dataframe[[\"sta\", \"station_id\"]],\n",
" on=\"sta\"\n",
").merge(\n",
" db[\"origin\"][[\"orid\", \"evid\"]],\n",
" on=\"orid\"\n",
").sort_values(\n",
" \"evid\"\n",
").set_index(\n",
" \"evid\"\n",
")[\n",
" [\"station_id\", \"phase\", \"time\", \"arid\"]\n",
"]\n",
"\n",
"stations_dataframe[\"depth\"] = -stations_dataframe[\"elev\"]\n",
"stations_dataframe = stations_dataframe[\n",
" [\"station_id\", \"lat\", \"lon\", \"depth\"]\n",
"].set_index(\n",
" \"station_id\"\n",
")\n",
"stations_dataframe = stations_dataframe[\n",
" stations_dataframe.index.isin(arrivals_dataframe[\"station_id\"].unique())\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"outputs": [],
"source": [
"stations_dict = dict(zip(stations_dataframe.index.values, geo2sph(stations_dataframe)))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"outputs": [],
"source": [
"# Only events inside the focus region of White et al. 2019 with 128 or more arrivals\n",
"df = arrivals_dataframe.reset_index().groupby(\"evid\").count()\n",
"arrivals_dataframe = arrivals_dataframe[\n",
" (arrivals_dataframe.index.isin(df[df[\"station_id\"] >= 128].index))\n",
" &(arrivals_dataframe.index.isin(\n",
" db[\"origin\"][seispy.coords.as_geographic(db[\"origin\"][[\"lat\", \"lon\", \"depth\"]]).in_rectangle()][\"evid\"]\n",
" )\n",
" )\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"outputs": [],
"source": [
"def generate_arrivals(arrivals_dataframe):\n",
" for event_id in arrivals_dataframe.index.unique()[:]:\n",
" yield (event_id, arrivals_dataframe.loc[event_id].set_index([\"station_id\", \"phase\"]).to_dict()[\"time\"])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"locator = pykonal.locate.EQLocator(stations_dict, tt_dir=\"/home/malcolmw/scratch/traveltimes\")\n",
"locator.grid.min_coords = grid.min_coords\n",
"locator.grid.node_intervals = grid.node_intervals\n",
"locator.grid.npts = grid.npts\n",
"locator.pwave_velocity = pwave_velocity\n",
"locator.swave_velocity = swave_velocity\n",
"# locator.compute_all_traveltime_lookup_tables(\"P\")\n",
"# locator.compute_all_traveltime_lookup_tables(\"S\")\n",
"for event_id, arrivals in generate_arrivals(arrivals_dataframe):\n",
" locator.clear_arrivals()\n",
" locator.add_arrivals(arrivals)\n",
" locator.load_traveltimes()\n",
" %time loc0 = locator.grid_search()\n",
" %time loc1 = locator.locate()\n",
" break"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"locator.counter"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# [locator.arrivals[key] for key in sorted(locator.arrivals)], \n",
"[locator.traveltimes[key] for key in sorted(locator.arrivals)]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"locator.grid.max_coords, locator.grid.min_coords + locator.grid.node_intervals * (locator.grid.npts - 1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sph2geo(loc0[:3]), sph2geo(loc1[:3])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"locator.cost(loc0), locator.cost(loc1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%cython\n",
"\n",
"import numpy as np\n",
"import scipy.optimize\n",
"cimport numpy as np\n",
"\n",
"\n",
"ctypedef np.float64_t _REAL_t\n",
"\n",
"EARTH_RADIUS = 6371.\n",
"DTYPE_REAL = np.float64\n",
"\n",
"def geo2sph(arr):\n",
" \"\"\"\n",
" Map Geographical coordinates to spherical coordinates.\n",
" \"\"\"\n",
" geo = np.array(arr, dtype=DTYPE_REAL)\n",
" sph = np.empty_like(geo)\n",
" sph[..., 0] = EARTH_RADIUS - geo[..., 2]\n",
" sph[..., 1] = np.pi / 2 - np.radians(geo[..., 0])\n",
" sph[..., 2] = np.radians(geo[..., 1])\n",
" return (sph)\n",
"\n",
"\n",
"def sph2geo(arr):\n",
" \"\"\"\n",
" Map spherical coordinates to geographic coordinates.\n",
" \"\"\"\n",
" sph = np.array(arr, dtype=DTYPE_REAL)\n",
" geo = np.empty_like(sph)\n",
" geo[..., 0] = np.degrees(np.pi / 2 - sph[..., 1])\n",
" geo[..., 1] = np.degrees(sph[..., 2])\n",
" geo[..., 2] = EARTH_RADIUS - sph[..., 0]\n",
" return (geo)\n",
"\n",
"\n",
"cdef class EQLocator(object):\n",
" cdef dict _arrivals\n",
" cdef dict _tt_calculators\n",
" cdef _REAL_t[:,:,:,:] _grid\n",
" cdef tuple _bounds\n",
" cdef dict _priors\n",
" \n",
" def __init__(self, arrivals, tt_calculators, grid):\n",
" self.arrivals = {key: arrivals[key] for key in tt_calculators}\n",
" self.tt_calculators = tt_calculators\n",
" self.grid = grid\n",
" \n",
" @property\n",
" def arrivals(self):\n",
" return (self._arrivals)\n",
" \n",
" @arrivals.setter\n",
" def arrivals(self, value):\n",
" self._arrivals = value\n",
" \n",
" @property\n",
" def grid(self):\n",
" return (np.asarray(self._grid))\n",
" \n",
" @grid.setter\n",
" def grid(self, value):\n",
" self._grid = value\n",
" \n",
" @property\n",
" def tt_calculators(self):\n",
" return (self._tt_calculators)\n",
" \n",
" @tt_calculators.setter\n",
" def tt_calculators(self, value):\n",
" self._tt_calculators = value\n",
" \n",
" cpdef initial_guess(self):\n",
" values = [self.arrivals[key]-self.tt_calculators[key].values for key in self.tt_calculators]\n",
" values = np.ma.masked_invalid(np.stack(values))\n",
" std = values.std(axis=0)\n",
" arg_min = np.argmin(std)\n",
" idx_min = np.unravel_index(arg_min, std.shape)\n",
" geo = sph2geo(self.grid[idx_min])\n",
" time = values.mean(axis=0)[idx_min]\n",
" return (np.array([*geo, time]))\n",
"\n",
" cpdef cost(self, _REAL_t[:] hypocenter):\n",
" cdef tuple key\n",
" cdef _REAL_t csum = 0\n",
" cdef _REAL_t lat, lon, depth, time\n",
" lat = hypocenter[0]\n",
" lon = hypocenter[1]\n",
" depth = hypocenter[2]\n",
" time = hypocenter[3]\n",
" sph_coords = geo2sph((lat, lon, depth))\n",
" if not np.all(sph_coords > np.asarray(self.grid).min(axis=(0,1,2))) or not np.all(sph_coords < np.asarray(self.grid).max(axis=(0,1,2))):\n",
" return (np.inf)\n",
" for key in self.arrivals:\n",
" tt_calculator = self.tt_calculators[key].value\n",
" csum += np.square(self.arrivals[key]-(time+tt_calculator(sph_coords)))\n",
" return (np.sqrt(csum/len(self.arrivals)))\n",
" \n",
" cpdef locate(self):\n",
" cdef _REAL_t[4] h0\n",
" h0 = self.initial_guess()\n",
" soln = scipy.optimize.differential_evolution(\n",
" self.cost,\n",
" ((h0[0]-0.1, h0[0]+0.1), (h0[1]-0.1, h0[1]+0.1), (0, 30), (h0[3]-5, h0[3]+5))\n",
" )\n",
" return (soln.x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Load a test data set"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"db = seispy.pandas.catalog.Catalog(\n",
" \"/home/malcolmw/google_drive/malcolm.white@usc.edu/data/events/malcolmw/SJFZ_catalog_2008-2016.h5\",\n",
" fmt=\"hdf5\"\n",
")\n",
"\n",
"gc_events_dataframe = pd.read_csv(\n",
" \"/home/malcolmw/scratch/events.grow\", \n",
" delim_whitespace=True, \n",
" header=None,\n",
" names=[\"year\", \"month\", \"day\", \"hour\", \"minute\", \"second\", \"lat\", \"lon\", \"depth\", \"null_0\", \"null_1\", \"null_2\", \"null_3\", \"event_id\"]\n",
")\n",
"gc_events_dataframe[\"time\"] = seispy.pandas.time.to_epoch(seispy.pandas.time.ymd_to_dt(gc_events_dataframe))*1e-9\n",
"gc_events_dataframe[\"event_id\"] -= int(2e9)\n",
"db[\"origin\"] = db[\"origin\"][[\"orid\", \"evid\"]].merge(\n",
" gc_events_dataframe[[\"lat\", \"lon\", \"depth\", \"time\", \"event_id\"]],\n",
" left_on=\"evid\",\n",
" right_on=\"event_id\"\n",
").drop(columns=[\"evid\"])\n",
"\n",
"stations_dataframe = db[\"site\"][\n",
" [\"sta\", \"lat\", \"lon\", \"elev\"]\n",
"].drop_duplicates(\n",
" \"sta\"\n",
").merge(\n",
" db[\"snetsta\"][\n",
" [\"snet\", \"sta\"]\n",
" ].drop_duplicates(\n",
" \"sta\"\n",
" ),\n",
" on=\"sta\"\n",
")\n",
"stations_dataframe[\"station_id\"] = stations_dataframe[\"snet\"] + \".\" + stations_dataframe[\"sta\"]\n",
"\n",
"arrivals_dataframe = db[\"arrival\"][\n",
" [\"sta\", \"time\", \"arid\"]\n",
"].merge(\n",
" db[\"assoc\"][\n",
" [\"arid\", \"orid\", \"phase\"]\n",
" ],\n",
" on=\"arid\"\n",
").merge(\n",
" stations_dataframe[[\"sta\", \"station_id\"]],\n",
" on=\"sta\"\n",
").merge(\n",
" db[\"origin\"][[\"orid\", \"event_id\"]],\n",
" on=\"orid\"\n",
").sort_values(\n",
" \"event_id\"\n",
").set_index(\n",
" \"event_id\"\n",
")[\n",
" [\"station_id\", \"phase\", \"time\", \"arid\"]\n",
"]\n",
"\n",
"stations_dataframe[\"depth\"] = -stations_dataframe[\"elev\"]\n",
"stations_dataframe = stations_dataframe[\n",
" [\"station_id\", \"lat\", \"lon\", \"depth\"]\n",
"].set_index(\n",
" \"station_id\"\n",
")\n",
"stations_dataframe = stations_dataframe[\n",
" stations_dataframe.index.isin(arrivals_dataframe[\"station_id\"].unique())\n",
"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Read and resample the velocity model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with np.load(\"/home/malcolmw/google_drive/malcolm.white@usc.edu/data/velocity/White_et_al_2019a/White_et_al_2019a.regular.npz\") as npz:\n",
" vp = pykonal.field.ScalarField3D(coord_sys=\"spherical\")\n",
" vs = pykonal.field.ScalarField3D(coord_sys=\"spherical\")\n",
" vp.min_coords = vs.min_coords = npz[\"grid_parameters\"][:3]\n",
" vp.node_intervals = vs.node_intervals = npz[\"grid_parameters\"][3:6]\n",
" vp.npts = vs.npts = npz[\"grid_parameters\"][6:] + [1, 0, 0]\n",
" vp.values = np.append(npz[\"vp\"], npz[\"vp\"][[-1]], axis=0)\n",
" vs.values = np.append(npz[\"vs\"], npz[\"vs\"][[-1]], axis=0)\n",
" \n",
"# Resample the velocity model (18, 32, 32) --> (64, 128, 128)\n",
"rho_min, theta_min, phi_min = vp.min_coords\n",
"rho_max, theta_max, phi_max = vp.max_coords\n",
"nrho, ntheta, nphi = 64, 128, 128\n",
"\n",
"drho = (rho_max - rho_min) / (nrho - 1)\n",
"rho = np.linspace(rho_min, rho_max, nrho)\n",
"\n",
"dtheta = (theta_max - theta_min) / (ntheta - 1)\n",
"theta = np.linspace(theta_min, theta_max, ntheta)\n",
"\n",
"dphi = (phi_max - phi_min) / (nphi - 1)\n",
"phi = np.linspace(phi_min, phi_max, nphi)\n",
"\n",
"rtp = np.moveaxis(\n",
" np.stack(np.meshgrid(rho, theta, phi, indexing=\"ij\")),\n",
" 0, \n",
" -1\n",
")\n",
"vp_new = vp.resample(rtp.reshape(-1, 3)).reshape(rtp.shape[:-1])\n",
"vs_new = vs.resample(rtp.reshape(-1, 3)).reshape(rtp.shape[:-1])\n",
"\n",
"vp = pykonal.field.ScalarField3D(coord_sys=\"spherical\")\n",
"vs = pykonal.field.ScalarField3D(coord_sys=\"spherical\")\n",
"vp.min_coords = vs.min_coords = rho_min, theta_min, phi_min\n",
"vp.node_intervals = vs.node_intervals = drho, dtheta, dphi\n",
"vp.npts = vs.npts = nrho, ntheta, nphi\n",
"vp.values = vp_new\n",
"vs.values = vs_new"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Compute traveltime-lookup tables"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def target(args, vp=vp, vs=vs):\n",
" station_id, coords = args[0], geo2sph(args[1].values)\n",
" print(station_id)\n",
" solver = compute_traveltime_lookup_table(coords, vp)\n",
" solver.tt.savez(f\"/home/malcolmw/scratch/traveltimes/{station_id}.P.npz\")\n",
" solver = compute_traveltime_lookup_table(coords, vs)\n",
" solver.tt.savez(f\"/home/malcolmw/scratch/traveltimes/{station_id}.S.npz\")\n",
" \n",
"with mp.Pool() as pool:\n",
" pool.map(target, stations_dataframe.iterrows())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Locate events"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def generate_arrivals(arrivals_dataframe):\n",
" for event_id in arrivals_dataframe.index.unique()[:]:\n",
" yield (event_id, arrivals_dataframe.loc[event_id].set_index([\"station_id\", \"phase\"]).to_dict()[\"time\"])\n",
" \n",
"def target(args, nodes=vp.nodes):\n",
" event_id, arrivals = args\n",
" print(f\"Locating event #{event_id}\")\n",
" tt_calculators = {\n",
" key: pykonal.field.load(f\"/home/malcolmw/scratch/traveltimes/{key[0]}.{key[1]}.npz\") for key in arrivals\n",
" }\n",
" locator = EQLocator(\n",
" arrivals=arrivals,\n",
" tt_calculators=tt_calculators,\n",
" grid=nodes\n",
" )\n",
" return (event_id, locator.locate())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with mp.Pool(4) as pool:\n",
" locations = pool.map(target, generate_arrivals(arrivals_dataframe))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"relocated_events_dataframe = pd.DataFrame([[loc[0], *loc[1]] for loc in locations], columns=[\"event_id\", \"lat\", \"lon\", \"depth\", \"time\"]).set_index(\"event_id\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"original_events_dataframe = db[\"origin\"][db[\"origin\"][\"event_id\"].isin(arrivals_dataframe.index.unique())].set_index(\"event_id\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.close(\"all\")\n",
"fig = plt.figure()\n",
"ax00 = fig.add_subplot(2, 2, 1)\n",
"ax01 = fig.add_subplot(2, 2, 2)\n",
"ax10 = fig.add_subplot(2, 2, 3)\n",
"ax11 = fig.add_subplot(2, 2, 4)\n",
"for ax, key in ((ax00, \"lat\"), (ax01, \"lon\"), (ax10, \"depth\"), (ax11, \"time\")):\n",
" ax.hist(original_events_dataframe[key] - relocated_events_dataframe[key], bins=32)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig = plt.figure(figsize=(12, 12))\n",
"ax1 = fig.add_subplot(1, 3, 1, aspect=1)\n",
"ax2 = fig.add_subplot(1, 3, 2, aspect=1)\n",
"ax3 = fig.add_subplot(1, 3, 3, aspect=1)\n",
"ax1.scatter(\n",
" original_events_dataframe[\"lon\"], \n",
" original_events_dataframe[\"lat\"],\n",
" c=original_events_dataframe[\"depth\"],\n",
" vmin=0,\n",
" vmax=25\n",
")\n",
"ax2.scatter(\n",
" relocated_events_dataframe[\"lon\"],\n",
" relocated_events_dataframe[\"lat\"],\n",
" c=original_events_dataframe[\"depth\"],\n",
" vmin=0,\n",
" vmax=25\n",
")\n",
"ax3.quiver(\n",
" original_events_dataframe[\"lon\"], \n",
" original_events_dataframe[\"lat\"],\n",
" relocated_events_dataframe[\"lon\"] - original_events_dataframe[\"lon\"],\n",
" relocated_events_dataframe[\"lat\"] - original_events_dataframe[\"lat\"],\n",
")\n",
"for ax in (ax1, ax2, ax3):\n",
" ax.set_xlim(-117, -116)\n",
" ax.set_ylim(33, 34)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig = plt.figure(figsize=(12, 12))\n",
"ax = fig.add_subplot(1, 1, 1, aspect=1)\n",
"ax.quiver(\n",
" original_events_dataframe[\"lon\"], \n",
" original_events_dataframe[\"lat\"],\n",
" relocated_events_dataframe[\"lon\"] - original_events_dataframe[\"lon\"],\n",
" relocated_events_dataframe[\"lat\"] - original_events_dataframe[\"lat\"],\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for event_id, origin in relocated_events_dataframe.iterrows():\n",
" arrivals = arrivals_dataframe.loc[event_id].set_index([\"station_id\", \"phase\"]).to_dict()[\"time\"]\n",
" tt_calculators = {\n",
" key: pykonal.field.load(f\"/home/malcolmw/scratch/traveltimes/{key[0]}.{key[1]}.npz\") for key in arrivals\n",
" }\n",
" locator = EQLocator(\n",
" arrivals=arrivals,\n",
" tt_calculators=tt_calculators,\n",
" grid=vp.nodes\n",
" )\n",
" print(\n",
" event_id, \n",
" locator.cost(origin[[\"lat\", \"lon\", \"depth\", \"time\"]].values), \n",
" locator.cost(original_events_dataframe.loc[event_id, [\"lat\", \"lon\", \"depth\", \"time\"]].values)\n",
" )"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:py37]",
"language": "python",
"name": "conda-env-py37-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
================================================
FILE: jupyter/figure_3.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Figure 3\n",
"Compatible with PyKonal Version 0.2.0"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib ipympl\n",
"\n",
"import matplotlib.gridspec as gs\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import pykonal"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initialize a solver in Cartesian coordinates"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"solver_c = pykonal.EikonalSolver(coord_sys='cartesian')\n",
"solver_c.velocity.min_coords = -25, -25, 0\n",
"solver_c.velocity.node_intervals = 1, 1, 1\n",
"solver_c.velocity.npts = 51, 51, 1\n",
"solver_c.velocity.values = np.ones(solver_c.velocity.npts) # Uniform velocity model\n",
"\n",
"# Add a point source at the origin of the grid.\n",
"src_idx = (25, 25, 0)\n",
"solver_c.traveltime.values[src_idx] = 0\n",
"solver_c.unknown[src_idx] = False\n",
"solver_c.trial.push(*src_idx)\n",
"\n",
"# Solve the system.\n",
"%time solver_c.solve()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initialize a solver in Spherical coordinates"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"solver_s = pykonal.EikonalSolver(coord_sys='spherical')\n",
"solver_s.velocity.min_coords = 0.01, np.pi/2, 0\n",
"solver_s.velocity.node_intervals = 1, 1, np.pi/10\n",
"solver_s.velocity.npts = 25, 1, 21\n",
"solver_s.velocity.values = np.ones(solver_s.velocity.npts) # Uniform velocity model\n",
"\n",
"# Add a point source at the origin of the grid.\n",
"for it in range(solver_s.velocity.npts[1]):\n",
" for ip in range(solver_s.velocity.npts[2]):\n",
" src_idx = (0, it, ip)\n",
" vv = solver_s.velocity.values[src_idx]\n",
" solver_s.traveltime.values[src_idx] = solver_s.velocity.nodes[src_idx + (0,)] / vv\n",
" solver_s.unknown[src_idx] = False\n",
" solver_s.trial.push(*src_idx)\n",
" \n",
"# Solve the system\n",
"%time solver_s.solve()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Plot the results"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"iz, it = 0, 0\n",
"plot_kwargs = dict(\n",
" shading='gouraud'\n",
")\n",
"plt.close('all')\n",
"\n",
"nodes = solver_s.traveltime.nodes\n",
"xx = nodes[...,0] * np.sin(nodes[...,1]) * np.cos(nodes[...,2])\n",
"yy = nodes[...,0] * np.sin(nodes[...,1]) * np.sin(nodes[...,2])\n",
"\n",
"fig = plt.figure(figsize=(4.5, 4))\n",
"\n",
"gridspec = gs.GridSpec(nrows=2, ncols=4, width_ratios=[0.08, 1, 1, 0.08])\n",
"ax1 = fig.add_subplot(gridspec[0, 1], aspect=1)\n",
"ax2 = fig.add_subplot(gridspec[0, 2], aspect=1)\n",
"ax3 = fig.add_subplot(gridspec[1, 1], aspect=1)\n",
"ax4 = fig.add_subplot(gridspec[1, 2], aspect=1)\n",
"cax1 = fig.add_subplot(gridspec[0, 3])\n",
"cax2 = fig.add_subplot(gridspec[1, 3])\n",
"ax1.set_title('Cartesian')\n",
"ax2.set_title('Spherical')\n",
"qmesh = ax1.pcolormesh(\n",
" solver_c.traveltime.nodes[:,:,iz,0],\n",
" solver_c.traveltime.nodes[:,:,iz,1],\n",
" solver_c.traveltime.values[:,:,iz],\n",
" cmap=plt.get_cmap('jet_r'),\n",
" **plot_kwargs\n",
")\n",
"qmesh = ax2.pcolormesh(\n",
" xx[:,it,:],\n",
" yy[:,it,:],\n",
" solver_s.traveltime.values[:,it,:],\n",
" vmin=qmesh.get_array().min(),\n",
" vmax=qmesh.get_array().max(),\n",
" cmap=plt.get_cmap('jet_r'),\n",
" **plot_kwargs\n",
")\n",
"cbar1 = fig.colorbar(qmesh, cax=cax1)\n",
"cbar1.set_label('Travel time [s]')\n",
"qmesh = ax3.pcolormesh(\n",
" solver_c.traveltime.nodes[:,:,iz,0],\n",
" solver_c.traveltime.nodes[:,:,iz,1],\n",
" solver_c.traveltime.values[:,:,iz]-np.sqrt(np.sum(np.square(solver_c.traveltime.nodes[:,:,iz]), axis=-1)),\n",
" vmin=0.0,\n",
" vmax=0.35,\n",
" cmap=plt.get_cmap('bone_r'),\n",
" **plot_kwargs\n",
")\n",
"qmesh = ax4.pcolormesh(\n",
" xx[:,it,:],\n",
" yy[:,it,:],\n",
" solver_s.traveltime.values[:,it,:]-np.sqrt(xx[:,it,:]**2 + yy[:,it,:]**2),\n",
" vmin=0.0,\n",
" vmax=0.35,\n",
" cmap=plt.get_cmap('bone_r'),\n",
" **plot_kwargs\n",
")\n",
"cbar2 = fig.colorbar(qmesh, cax=cax2)\n",
"cbar2.set_label('Absolute error [s]')\n",
"\n",
"for ax in (ax1, ax2):\n",
" ax.set_xticklabels([])\n",
" \n",
"for ax in (ax2, ax4):\n",
" ax.set_yticklabels([])\n",
" \n",
"panel = ord(\"a\")\n",
"for ax in (ax1, ax2, ax3, ax4):\n",
" ax.text(\n",
" 0, 1.025, f\"({chr(panel)})\",\n",
" ha=\"right\",\n",
" va=\"bottom\",\n",
" transform=ax.transAxes\n",
" )\n",
" panel += 1\n",
"\n",
"fig.text(0.5, 0, \"x [km]\", ha=\"center\", va=\"bottom\")\n",
"fig.text(0.05, 0.5, \"y [km]\", ha=\"left\", va=\"center\", rotation=90)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:py37]",
"language": "python",
"name": "conda-env-py37-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
================================================
FILE: jupyter/figure_4.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Figure 4\n",
"Compatible with PyKonal Version 0.2.0"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib ipympl\n",
"\n",
"import matplotlib.gridspec as gs\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import pykonal"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initialize a solver in Cartesian coordinates"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"solver_c = pykonal.EikonalSolver(coord_sys='cartesian')\n",
"solver_c.velocity.min_coords = -25, -25, 0\n",
"solver_c.velocity.node_intervals = 1, 1, 1\n",
"solver_c.velocity.npts = 51, 51, 1\n",
"solver_c.velocity.values = np.ones(solver_c.velocity.npts) # Uniform velocity model\n",
"\n",
"# Add a line source at y = 0.\n",
"for ix in range(solver_c.velocity.npts[0]):\n",
" src_idx = (ix, 25, 0)\n",
" solver_c.traveltime.values[src_idx] = 0\n",
" solver_c.unknown[src_idx] = False\n",
" solver_c.trial.push(*src_idx)\n",
"\n",
"# Solve the system\n",
"%time solver_c.solve()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initialize a solver in spherical coordinates"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"solver_s = pykonal.EikonalSolver(coord_sys='spherical')\n",
"solver_s.velocity.min_coords = 0.01, np.pi/2, 0\n",
"solver_s.velocity.node_intervals = 1, 1, np.pi/10\n",
"solver_s.velocity.npts = 26, 1, 21\n",
"solver_s.velocity.values = np.ones(solver_s.velocity.npts) # Uniform velocity model\n",
"\n",
"# Add a line source at y = 0.\n",
"for ir in range(solver_s.velocity.npts[0]):\n",
" for it in range(solver_s.velocity.npts[1]):\n",
" for ip in np.argwhere(solver_s.traveltime.nodes[0,0,:,2] % np.pi == 0).flatten():\n",
" src_idx = (ir, it, ip)\n",
" solver_s.traveltime.values[src_idx] = 0\n",
" solver_s.unknown[src_idx] = False\n",
" solver_s.trial.push(*src_idx)\n",
"\n",
"# Solve the system\n",
"%time solver_s.solve()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Plot the results"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"iz, it = 0, 0\n",
"plot_kwargs = dict(\n",
" shading='gouraud'\n",
")\n",
"plt.close('all')\n",
"\n",
"nodes = solver_s.traveltime.nodes\n",
"xx = nodes[...,0] * np.sin(nodes[...,1]) * np.cos(nodes[...,2])\n",
"yy = nodes[...,0] * np.sin(nodes[...,1]) * np.sin(nodes[...,2])\n",
"\n",
"fig = plt.figure(figsize=(4.5, 4))\n",
"\n",
"gridspec = gs.GridSpec(nrows=2, ncols=4, width_ratios=[0.08, 1, 1, 0.08])\n",
"ax1 = fig.add_subplot(gridspec[0, 1], aspect=1)\n",
"ax2 = fig.add_subplot(gridspec[0, 2], aspect=1)\n",
"ax3 = fig.add_subplot(gridspec[1, 1], aspect=1)\n",
"ax4 = fig.add_subplot(gridspec[1, 2], aspect=1)\n",
"cax1 = fig.add_subplot(gridspec[0, 3])\n",
"cax2 = fig.add_subplot(gridspec[1, 3])\n",
"ax1.set_title('Cartesian')\n",
"ax2.set_title('Spherical')\n",
"qmesh = ax1.pcolormesh(\n",
" solver_c.traveltime.nodes[:,:,iz,0],\n",
" solver_c.traveltime.nodes[:,:,iz,1],\n",
" solver_c.traveltime.values[:,:,iz],\n",
" cmap=plt.get_cmap('jet_r'),\n",
" **plot_kwargs\n",
")\n",
"qmesh = ax2.pcolormesh(\n",
" xx[:,it,:],\n",
" yy[:,it,:],\n",
" solver_s.traveltime.values[:,it,:],\n",
" vmin=qmesh.get_array().min(),\n",
" vmax=qmesh.get_array().max(),\n",
" cmap=plt.get_cmap('jet_r'),\n",
" **plot_kwargs\n",
")\n",
"cbar1 = fig.colorbar(qmesh, cax=cax1)\n",
"cbar1.set_label('Travel time [s]')\n",
"qmesh = ax3.pcolormesh(\n",
" solver_c.traveltime.nodes[:,:,iz,0],\n",
" solver_c.traveltime.nodes[:,:,iz,1],\n",
" solver_c.traveltime.values[:,:,iz]-np.abs(solver_c.traveltime.nodes[:,:,iz,1]),\n",
" vmin=0.0,\n",
" vmax=0.35,\n",
" cmap=plt.get_cmap('bone_r'),\n",
" **plot_kwargs\n",
")\n",
"qmesh = ax4.pcolormesh(\n",
" xx[:,it,:],\n",
" yy[:,it,:],\n",
" np.abs(solver_s.traveltime.values[:,it,:]-np.abs(yy[:,it,:])),\n",
" vmin=0.0,\n",
" vmax=0.35,\n",
" cmap=plt.get_cmap('bone_r'),\n",
" **plot_kwargs\n",
")\n",
"cbar2 = fig.colorbar(qmesh, cax=cax2)\n",
"cbar2.set_label('Absolute error [s]')\n",
"\n",
"for ax in (ax1, ax2):\n",
" ax.set_xticklabels([])\n",
" \n",
"for ax in (ax2, ax4):\n",
" ax.set_yticklabels([])\n",
" \n",
"panel = ord(\"a\")\n",
"for ax in (ax1, ax2, ax3, ax4):\n",
" ax.text(\n",
" 0, 1.025, f\"({chr(panel)})\",\n",
" ha=\"right\",\n",
" va=\"bottom\",\n",
" transform=ax.transAxes\n",
" )\n",
" panel += 1\n",
"\n",
"fig.text(0.5, 0, \"x [km]\", ha=\"center\", va=\"bottom\")\n",
"fig.text(0.05, 0.5, \"y [km]\", ha=\"left\", va=\"center\", rotation=90)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:py37]",
"language": "python",
"name": "conda-env-py37-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
================================================
FILE: jupyter/figure_5.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Figure 5\n",
"Compatible with PyKonal Version 0.2.0"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib ipympl\n",
"import matplotlib\n",
"import matplotlib.gridspec as gs\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import os\n",
"import pkg_resources\n",
"import pykonal"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Load Marmousi 2D velocity model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fname = pkg_resources.resource_filename(\n",
" 'pykonal',\n",
" os.path.join('data', \"marmousi2\", 'marmousi2.npz')\n",
")\n",
"with np.load(fname) as infile:\n",
" vv = infile['vv']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Initialize the EikonalSolver"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"velocity = pykonal.fields.ScalarField3D(coord_sys=\"cartesian\")\n",
"velocity.min_coords = 0, 0, 0\n",
"velocity.node_intervals = 0.004, 0.004, 1\n",
"velocity.npts = vv.shape\n",
"velocity.values = vv"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"traveltime_fields = dict()\n",
"for decimation_factor in range(7, -1, -1):\n",
" decimation_factor = 2**decimation_factor\n",
" \n",
" vv = velocity.values[::decimation_factor, ::decimation_factor]\n",
"\n",
" solver = pykonal.EikonalSolver(coord_sys=\"cartesian\")\n",
"\n",
" solver.velocity.min_coords = 0, 0, 0\n",
" solver.velocity.node_intervals = velocity.node_intervals * decimation_factor\n",
" solver.velocity.npts = vv.shape\n",
" solver.velocity.values = vv\n",
"\n",
" src_idx = 0, 0, 0\n",
" solver.traveltime.values[src_idx] = 0\n",
" solver.unknown[src_idx] = False\n",
" solver.trial.push(*src_idx)\n",
"\n",
" %time solver.solve()\n",
" traveltime_fields[decimation_factor] = solver.traveltime"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Plot the results"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.close('all')\n",
"fig = plt.figure(figsize=(5, 4.25))\n",
"ax = fig.add_subplot(1, 1, 1, frameon=False)\n",
"plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)\n",
"ax.set_xlabel(\"Horizontal offset [km]\")\n",
"ax.set_ylabel(\"Depth [km]\")\n",
"\n",
"gridspec = gs.GridSpec(nrows=8, ncols=2, height_ratios=[0.08, 1, 1, 1, 1, 0.2, 0.08, 0.72], width_ratios=[1, 1])\n",
"cax00 = fig.add_subplot(gridspec[0, 0])\n",
"cax01 = fig.add_subplot(gridspec[0, 1])\n",
"cax51 = fig.add_subplot(gridspec[6, 1])\n",
"ax10 = fig.add_subplot(gridspec[1, 0])\n",
"ax11 = fig.add_subplot(gridspec[1, 1])\n",
"ax20 = fig.add_subplot(gridspec[2, 0])\n",
"ax21 = fig.add_subplot(gridspec[2, 1])\n",
"ax30 = fig.add_subplot(gridspec[3, 0])\n",
"ax31 = fig.add_subplot(gridspec[3, 1])\n",
"ax40 = fig.add_subplot(gridspec[4, 0])\n",
"ax41 = fig.add_subplot(gridspec[4, 1])\n",
"ax50 = fig.add_subplot(gridspec[5:, 0])\n",
"\n",
"panel = ord(\"a\")\n",
"for ax in (ax10, ax11, ax20, ax21, ax30, ax31, ax40, ax41, ax50):\n",
" ax.text(-0.05, 0.8, f\"({chr(panel)})\", ha=\"right\", va=\"top\", transform=ax.transAxes)\n",
" panel += 1\n",
"\n",
"qmesh = ax10.pcolormesh(\n",
" velocity.nodes[:,:,0,0],\n",
" velocity.nodes[:,:,0,1],\n",
" velocity.values[:,:,0],\n",
" cmap=plt.get_cmap(\"hot\")\n",
")\n",
"cbar = fig.colorbar(qmesh, cax=cax00, orientation=\"horizontal\")\n",
"cbar.set_label(\"Velocity [km/s]\")\n",
"cbar.ax.xaxis.tick_top()\n",
"cbar.ax.xaxis.set_label_position(\"top\")\n",
"\n",
"tt0 = traveltime_fields[1]\n",
"qmesh = ax11.pcolormesh(\n",
" tt0.nodes[:,:,0,0],\n",
" tt0.nodes[:,:,0,1],\n",
" tt0.values[:,:,0],\n",
" cmap=plt.get_cmap(\"jet\"),\n",
")\n",
"ax11.contour(\n",
" tt0.nodes[:,:,0,0],\n",
" tt0.nodes[:,:,0,1],\n",
" tt0.values[:,:,0],\n",
" colors=\"k\",\n",
" levels=np.arange(0, tt0.values.max(), 0.25),\n",
" linewidths=0.5,\n",
" linestyles=\"--\"\n",
")\n",
"cbar = fig.colorbar(qmesh, cax=cax01, orientation=\"horizontal\")\n",
"cbar.set_label(\"Traveltime [s]\")\n",
"cbar.ax.xaxis.tick_top()\n",
"cbar.ax.xaxis.set_label_position(\"top\")\n",
"\n",
"for ax, decimation_factor in ((ax20, 128), (ax21, 64), (ax30, 32), (ax31, 16), (ax40, 8), (ax41, 4), (ax50, 2)):\n",
" tt = traveltime_fields[decimation_factor]\n",
" qmesh = ax.pcolormesh(\n",
" tt.nodes[:,:,0,0],\n",
" tt.nodes[:,:,0,1],\n",
" np.abs(tt.values[:,:,0] - tt0.values[::decimation_factor, ::decimation_factor, 0]),\n",
" cmap=plt.get_cmap(\"bone_r\"),\n",
" vmin=0,\n",
" vmax=0.62\n",
" )\n",
" ax.text(\n",
" 0.05, 0.95,\n",
" f\"$d={decimation_factor}$\",\n",
" ha=\"left\",\n",
" va=\"top\",\n",
" transform=ax.transAxes\n",
" )\n",
"cbar = fig.colorbar(qmesh, cax=cax51, orientation=\"horizontal\")\n",
"cbar.set_label(\"$\\Delta t$ [s]\")\n",
"\n",
"for ax in (ax10, ax11, ax20, ax21, ax30, ax31, ax40):\n",
" ax.set_xticklabels([])\n",
"for ax in (ax11, ax21, ax31, ax41):\n",
" ax.yaxis.tick_right()\n",
"for ax in (ax10, ax11, ax20, ax21, ax30, ax31, ax40, ax41, ax50):\n",
" ax.set_yticks([0, 4])\n",
" ax.set_xticks([0, 8, 16, 24])\n",
" ax.set_xlim(0, 27.136)\n",
" ax.set_ylim(0, 5.12)\n",
" ax.invert_yaxis()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:py37]",
"language": "python",
"name": "conda-env-py37-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
================================================
FILE: jupyter/figure_6.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Figure 6\n",
"Compatible with PyKonal Version 0.2.0"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib ipympl\n",
"\n",
"import matplotlib.gridspec as gs\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import pykonal\n",
"\n",
"from matplotlib import markers\n",
"from matplotlib.path import Path\n",
"from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def align_marker(marker, halign='center', valign='middle',):\n",
" \"\"\"\n",
" create markers with specified alignment.\n",
"\n",
" Parameters\n",
" ----------\n",
"\n",
" marker : a valid marker specification.\n",
" See mpl.markers\n",
"\n",
" halign : string, float {'left', 'center', 'right'}\n",
" Specifies the horizontal alignment of the marker. *float* values\n",
" specify the alignment in units of the markersize/2 (0 is 'center',\n",
" -1 is 'right', 1 is 'left').\n",
"\n",
" valign : string, float {'top', 'middle', 'bottom'}\n",
" Specifies the vertical alignment of the marker. *float* values\n",
" specify the alignment in units of the markersize/2 (0 is 'middle',\n",
" -1 is 'top', 1 is 'bottom').\n",
"\n",
" Returns\n",
" -------\n",
"\n",
" marker_array : numpy.ndarray\n",
" A Nx2 array that specifies the marker path relative to the\n",
" plot target point at (0, 0).\n",
"\n",
" Notes\n",
" -----\n",
" The mark_array can be passed directly to ax.plot and ax.scatter, e.g.::\n",
"\n",
" ax.plot(1, 1, marker=align_marker('>', 'left'))\n",
"\n",
" \"\"\"\n",
"\n",
" halign = {'right': -1.,\n",
" 'middle': 0.,\n",
" 'center': 0.,\n",
" 'left': 1.,\n",
" }[halign]\n",
"\n",
" valign = {'top': -1.,\n",
" 'middle': 0.,\n",
" 'center': 0.,\n",
" 'bottom': 1.,\n",
" }[valign]\n",
"\n",
" # Define the base marker\n",
" bm = markers.MarkerStyle(marker)\n",
"\n",
" # Get the marker path and apply the marker transform to get the\n",
" # actual marker vertices (they should all be in a unit-square\n",
" # centered at (0, 0))\n",
" m_arr = bm.get_path().transformed(bm.get_transform()).vertices\n",
"\n",
" # Shift the marker vertices for the specified alignment.\n",
" m_arr[:, 0] += halign / 2\n",
" m_arr[:, 1] += valign / 2\n",
"\n",
" return Path(m_arr, bm.get_path().codes)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Define the velocity model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Set the velocity gradient in 1/s\n",
"velocity_gradient = 0.25\n",
"\n",
"velocity = pykonal.fields.ScalarField3D(coord_sys=\"cartesian\")\n",
"velocity.min_coords = 0, 0, 0\n",
"velocity.npts = 4096, 1024, 1\n",
"velocity.node_intervals = [40, 10, 1] / velocity.npts\n",
"velocity.values = np.full(velocity.npts, fill_value=4.5)\n",
"\n",
"for iy in range(velocity.npts[1]):\n",
" velocity.values[:,iy] += velocity_gradient * velocity.nodes[0,iy,0,1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Determine the analytical solution"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Set the take-off angle in radians.\n",
"takeoff_angle = np.radians(50)\n",
"\n",
"# Set the index of the node corresponding to the source location.\n",
"src_idx = np.array([128, 128, 0])\n",
"\n",
"# Get the source coordinates.\n",
"src_coords = velocity.nodes[tuple(src_idx)]\n",
"\n",
"# Compute the radius of the circle defining the raypath.\n",
"radius = velocity.value(src_coords) / (velocity_gradient * np.sin(takeoff_angle))\n",
"\n",
"# Compute the coordinates of the center of the circle.\n",
"center_coords = src_coords + radius*np.array([np.cos(takeoff_angle), np.sin(takeoff_angle), 0])\n",
"\n",
"# Define function mapping horizontal coordinate to vertical\n",
"def vertical_coords(horizontal_coord, src_coords=src_coords, radius=radius, takeoff_angle=takeoff_angle):\n",
" sqrt = np.sqrt(radius**2 - (horizontal_coord - src_coords[0] - radius*np.cos(takeoff_angle))**2)\n",
" first_two_terms = src_coords[1] - radius * np.sin(takeoff_angle)\n",
" return (first_two_terms + sqrt, first_two_terms - sqrt)\n",
"\n",
"# Define function mapping vertical coordinate to horizontal\n",
"def horizontal_coords(vertical_coord, src_coords=src_coords, radius=radius, takeoff_angle=takeoff_angle):\n",
" sqrt = np.sqrt(radius**2 - (src_coords[1] - vertical_coord - radius*np.sin(takeoff_angle))**2)\n",
" first_two_terms = src_coords[0] + radius * np.cos(takeoff_angle)\n",
" return (first_two_terms + sqrt, first_two_terms - sqrt)\n",
"\n",
"rec_coords = [horizontal_coords(0)[0], 0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Compute numerical solutions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"rays = dict()\n",
"\n",
"for decimation_factor in range(6, 1, -1):\n",
" decimation_factor = 2**decimation_factor\n",
" \n",
" vv = velocity.values[::decimation_factor, ::decimation_factor]\n",
"\n",
" solver = pykonal.EikonalSolver(coord_sys=\"cartesian\")\n",
"\n",
" solver.velocity.min_coords = 0, 0, 0\n",
" solver.velocity.node_intervals = velocity.node_intervals * decimation_factor\n",
" solver.velocity.npts = vv.shape\n",
" solver.velocity.values = vv\n",
"\n",
" idx = tuple((src_idx / decimation_factor).astype(np.int) - [1, 1, 0])\n",
" solver.traveltime.values[idx] = 0\n",
" solver.unknown[idx] = False\n",
" solver.trial.push(*idx)\n",
"\n",
" %time solver.solve()\n",
" rays[decimation_factor] = solver.trace_ray(np.array([rec_coords[0], 0, 0]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Plot the results"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"zoom = 22\n",
"dx = 0.5\n",
"dy = 0.5\n",
"anchor_y = 1.1\n",
"\n",
"\n",
"plt.close(\"all\")\n",
"fig = plt.figure(figsize=(6, 3))\n",
"\n",
"# Set up the main Axes.\n",
"ax0 = fig.add_subplot(2, 1, 2, aspect=1)\n",
"ax0.set_xlabel(\"Horizontal offset [km]\")\n",
"ax0.set_ylabel(\"Depth [km]\")\n",
"ax0.set_xlim(0, rec_coords[0]+src_coords[0])\n",
"ax0.set_ylim(-2, 10)\n",
"ax0.invert_yaxis()\n",
"\n",
"# Set up the first inset Axes.\n",
"axins1 = zoomed_inset_axes(\n",
" ax0,\n",
" zoom=zoom,\n",
" loc=\"lower left\",\n",
" bbox_to_anchor=(0, anchor_y),\n",
" bbox_transform=ax0.transAxes\n",
")\n",
"axins1.set_xlim(src_coords[0]-dx/2, src_coords[0]+dx/2)\n",
"axins1.set_ylim(src_coords[1]+dy/2, src_coords[1]-dy/2)\n",
"\n",
"# Set up the second inset Axes.\n",
"axins2 = zoomed_inset_axes(\n",
" ax0,\n",
" zoom=zoom,\n",
" loc=\"lower center\",\n",
" bbox_to_anchor=(0.5, anchor_y),\n",
" bbox_transform=ax0.transAxes\n",
")\n",
"turning_point = (src_coords[0] + rec_coords[0]) / 2\n",
"axins2.set_xlim(turning_point-dx/2, turning_point+dx/2)\n",
"axins2.set_ylim(vertical_coords(turning_point)[0]+dy/2, vertical_coords(turning_point)[0]-dy/2)\n",
"\n",
"# Set up the third inset Axes.\n",
"axins3 = zoomed_inset_axes(\n",
" ax0,\n",
" zoom=zoom,\n",
" loc=\"lower right\",\n",
" bbox_to_anchor=(1, anchor_y),\n",
" bbox_transform=ax0.transAxes\n",
")\n",
"axins3.set_xlim(horizontal_coords(0)[0]-3*dx/4, horizontal_coords(0)[0]+dx/4)\n",
"axins3.set_ylim(3*dy/4, -dy/4)\n",
"\n",
"for ax in (ax0, axins1):\n",
" # Plot the source location.\n",
" ax.scatter(\n",
" src_coords[0], src_coords[1], \n",
" marker=\"*\",\n",
" s=250,\n",
" facecolor=\"w\",\n",
" edgecolor=\"k\"\n",
" )\n",
"\n",
"for ax in (ax0, axins3):\n",
" # Plot the receiver location.\n",
" ax.scatter(\n",
" rec_coords[0], rec_coords[1], \n",
" marker=align_marker(\"v\", valign=\"bottom\"),\n",
" s=250,\n",
" facecolor=\"w\",\n",
" edgecolor=\"k\"\n",
" )\n",
" \n",
"xx = np.linspace(src_coords[0], rec_coords[0])\n",
"yy = vertical_coords(xx)[0]\n",
"label = True\n",
"for ax in (ax0, axins1, axins2, axins3):\n",
" # Plot the synthetic raypaths.\n",
" for decimation_factor in rays:\n",
" ax.plot(\n",
" rays[decimation_factor][:,0], \n",
" rays[decimation_factor][:,1],\n",
" linewidth=1,\n",
" label=f\"d={decimation_factor}\" if label is True else None\n",
" )\n",
" # Plot the analytic raypath.\n",
" ax.plot(xx, yy, \"k--\", label=\"Analytical\" if label is True else None)\n",
" label = False\n",
" \n",
"for ax in (axins1, axins2, axins3):\n",
" mark_inset(ax0, ax, loc1=3, loc2=4, fc=\"none\", ec=\"0.5\", linestyle=\"-.\")\n",
" ax.text(0.5, 0.95, f\"{zoom}x\", ha=\"center\", va=\"top\", transform=ax.transAxes)\n",
" ax.set_xticks(np.arange(*ax.get_xlim(), 0.2))\n",
" ax.set_yticks(np.arange(*ax.get_ylim(), -0.2))\n",
" ax.set_xticklabels([])\n",
" ax.set_yticklabels([])\n",
" ax.tick_params(direction=\"in\")\n",
"\n",
"label = ord(\"a\")\n",
"for ax in (axins1, axins2, axins3, ax0):\n",
" ax.text(\n",
" 0, 1.05, f\"{chr(label)})\",\n",
" ha=\"center\",\n",
" va=\"bottom\",\n",
" transform=ax.transAxes\n",
" )\n",
" label += 1\n",
"fig.legend(loc=\"center right\")\n",
"fig.tight_layout()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:py37]",
"language": "python",
"name": "conda-env-py37-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
================================================
FILE: jupyter/figure_7.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Figure 7\n",
"Compatible with PyKonal Version 0.2.0"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib ipympl\n",
"\n",
"import matplotlib.gridspec as gs\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import os\n",
"import pkg_resources\n",
"import pykonal"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fname = pkg_resources.resource_filename(\n",
" \"pykonal\",\n",
" os.path.join(\"data\", \"mitp2008.npz\")\n",
")\n",
"\n",
"with np.load(fname) as npz:\n",
" vv = pykonal.fields.ScalarField3D(coord_sys='spherical')\n",
" dv = pykonal.fields.ScalarField3D(coord_sys='spherical')\n",
" vv.min_coords = dv.min_coords = npz['min_coords_2d'] + [0, 0, np.pi/4]\n",
" vv.node_intervals = dv.node_intervals = npz['node_intervals_2d']\n",
" vv.npts = dv.npts = npz['npts_2d'][0], npz['npts_2d'][1], npz['npts_2d'][2]//4\n",
" vv.values = npz['vv_2d'][:,:,128:256]\n",
" dv.values = npz[\"dv_2d\"][:,:,128:256]\n",
"\n",
"# Resample the velocity model (64, 1, 128) --> (1024, 1, 2048)\n",
"rho_min, theta_min, phi_min = vv.min_coords\n",
"rho_max, theta_max, phi_max = vv.max_coords\n",
"nrho, ntheta, nphi = 1024, 1, 2048\n",
"\n",
"drho = (rho_max - rho_min) / (nrho - 1)\n",
"rho = np.linspace(rho_min, rho_max, nrho)\n",
"\n",
"# dtheta = (theta_max - theta_min) / (ntheta - 1)\n",
"dtheta = 1\n",
"theta = np.linspace(theta_min, theta_max, ntheta)\n",
"\n",
"dphi = (phi_max - phi_min) / (nphi - 1)\n",
"phi = np.linspace(phi_min, phi_max, nphi)\n",
"\n",
"rtp = np.moveaxis(\n",
" np.stack(np.meshgrid(rho, theta, phi, indexing=\"ij\")),\n",
" 0, \n",
" -1\n",
")\n",
"vv_new = vv.resample(rtp.reshape(-1, 3)).reshape(rtp.shape[:-1])\n",
"dv_new = dv.resample(rtp.reshape(-1, 3)).reshape(rtp.shape[:-1])\n",
"\n",
"vv = pykonal.fields.ScalarField3D(coord_sys=\"spherical\")\n",
"dv = pykonal.fields.ScalarField3D(coord_sys=\"spherical\")\n",
"vv.min_coords = dv.min_coords = rho_min, theta_min, phi_min\n",
"vv.node_intervals = dv.node_intervals = drho, dtheta, dphi\n",
"vv.npts = dv.npts = nrho, ntheta, nphi\n",
"vv.values = vv_new\n",
"dv.values = dv_new\n",
"\n",
"velocity = vv"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"SRC_IDX = np.array([512, 0, 1024])\n",
"\n",
"traveltime_fields = dict()\n",
"for decimation_factor in range(7, -1, -1):\n",
" decimation_factor = 2**decimation_factor\n",
" \n",
" vv = velocity.values[::decimation_factor, :, ::decimation_factor]\n",
"\n",
" solver = pykonal.EikonalSolver(coord_sys=\"spherical\")\n",
"\n",
" solver.vv.min_coords = velocity.min_coords\n",
" solver.vv.node_intervals = velocity.node_intervals * decimation_factor\n",
" solver.vv.npts = vv.shape\n",
" solver.vv.values = vv\n",
"\n",
" src_idx = tuple(SRC_IDX // decimation_factor - [1, 0, 1])\n",
" print(src_idx)\n",
" solver.traveltime.values[src_idx] = 0\n",
" solver.unknown[src_idx] = False\n",
" solver.trial.push(*src_idx)\n",
"\n",
" %time solver.solve()\n",
" traveltime_fields[decimation_factor] = solver.traveltime"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.close('all')\n",
"fig = plt.figure(figsize=(4.5, 6.5))\n",
"\n",
"fig.text(0, 0.5, \"$y$ [km]\", ha=\"left\", va=\"center\", rotation=90)\n",
"fig.text(0.5, 0.05, \"$x$ [km]\", ha=\"center\", va=\"bottom\")\n",
"\n",
"gridspec = gs.GridSpec(nrows=6, ncols=2, height_ratios=[0.08, 1, 1, 1, 1, 1], width_ratios=[1, 1])\n",
"cax00 = fig.add_subplot(gridspec[0, 0])\n",
"cax01 = fig.add_subplot(gridspec[0, 1])\n",
"ax10 = fig.add_subplot(gridspec[1, 0], aspect=1)\n",
"ax11 = fig.add_subplot(gridspec[1, 1], aspect=1)\n",
"ax20 = fig.add_subplot(gridspec[2, 0], aspect=1)\n",
"ax21 = fig.add_subplot(gridspec[2, 1], aspect=1)\n",
"ax30 = fig.add_subplot(gridspec[3, 0], aspect=1)\n",
"ax31 = fig.add_subplot(gridspec[3, 1], aspect=1)\n",
"ax40 = fig.add_subplot(gridspec[4, 0], aspect=1)\n",
"ax41 = fig.add_subplot(gridspec[4, 1], aspect=1)\n",
"ax50 = fig.add_subplot(gridspec[5, 0], aspect=1)\n",
"\n",
"gridspec = gs.GridSpec(nrows=8, ncols=2, height_ratios=[0.08, 1, 1, 1, 1, 0.2, 0.08, 0.72], width_ratios=[1, 1])\n",
"cax51 = fig.add_subplot(gridspec[6, 1])\n",
"\n",
"panel = ord(\"a\")\n",
"for ax in (ax10, ax11, ax20, ax21, ax30, ax31, ax40, ax41, ax50):\n",
" ax.text(-0.05, 1.1, f\"({chr(panel)})\", ha=\"right\", va=\"top\", transform=ax.transAxes)\n",
" panel += 1\n",
"\n",
"nodes = dv.nodes\n",
"xx = nodes[...,0] * np.sin(nodes[...,1]) * np.cos(nodes[...,2])\n",
"yy = nodes[...,0] * np.sin(nodes[...,1]) * np.sin(nodes[...,2])\n",
"qmesh = ax10.pcolormesh(\n",
" xx[:,0],\n",
" yy[:,0],\n",
" dv.values[:,0],\n",
" cmap=plt.get_cmap(\"seismic_r\"),\n",
" vmin=-1.25,\n",
" vmax=1.25,\n",
" shading=\"gouraud\"\n",
")\n",
"cbar = fig.colorbar(qmesh, cax=cax00, orientation=\"horizontal\")\n",
"cbar.set_label(\"$dV_P/V_P$ [\\%]\")\n",
"cbar.ax.xaxis.tick_top()\n",
"cbar.ax.xaxis.set_label_position(\"top\")\n",
"\n",
"tt0 = traveltime_fields[1]\n",
"nodes = tt0.nodes\n",
"xx = nodes[...,0] * np.sin(nodes[...,1]) * np.cos(nodes[...,2])\n",
"yy = nodes[...,0] * np.sin(nodes[...,1]) * np.sin(nodes[...,2])\n",
"qmesh = ax11.pcolormesh(\n",
" xx[:,0],\n",
" yy[:,0],\n",
" tt0.values[:,0],\n",
" cmap=plt.get_cmap(\"jet\"),\n",
" shading=\"gouraud\"\n",
")\n",
"ax11.contour(\n",
" xx[:,0],\n",
" yy[:,0],\n",
" tt0.values[:,0],\n",
" colors=\"k\",\n",
" levels=np.arange(0, tt0.values.max(), 20),\n",
" linewidths=0.5,\n",
" linestyles=\"--\"\n",
")\n",
"ax11.scatter(\n",
" xx[511, 0, 1023], yy[511, 0, 1023],\n",
" marker=\"*\",\n",
" s=250,\n",
" facecolor=\"w\",\n",
" edgecolor=\"k\"\n",
")\n",
"cbar = fig.colorbar(qmesh, cax=cax01, orientation=\"horizontal\")\n",
"cbar.set_label(\"Traveltime [s]\")\n",
"cbar.ax.xaxis.tick_top()\n",
"cbar.ax.xaxis.set_label_position(\"top\")\n",
"\n",
"for ax, decimation_factor in ((ax20, 128), (ax21, 64), (ax30, 32), (ax31, 16), (ax40, 8), (ax41, 4), (ax50, 2)):\n",
" tt = traveltime_fields[decimation_factor]\n",
" nodes = tt.nodes\n",
" xx = nodes[...,0] * np.sin(nodes[...,1]) * np.cos(nodes[...,2])\n",
" yy = nodes[...,0] * np.sin(nodes[...,1]) * np.sin(nodes[...,2])\n",
" qmesh = ax.pcolormesh(\n",
" xx[:,0],\n",
" yy[:,0],\n",
" np.abs(tt.values[:,0] - tt0.values[::decimation_factor, 0, ::decimation_factor]),\n",
" cmap=plt.get_cmap(\"bone_r\"),\n",
" vmax=50,\n",
" shading=\"gouraud\"\n",
" )\n",
" ax.text(\n",
" 0.05, 0.95,\n",
" f\"$d={decimation_factor}$\",\n",
" ha=\"left\",\n",
" va=\"top\",\n",
" transform=ax.transAxes\n",
" )\n",
"cbar = fig.colorbar(qmesh, cax=cax51, orientation=\"horizontal\")\n",
"cbar.set_label(\"$\\Delta t$ [s]\")\n",
"for ax in (ax10, ax11, ax20, ax21, ax30, ax31, ax40):\n",
" ax.set_xticklabels([])\n",
"for ax in (ax11, ax21, ax31, ax41):\n",
" ax.yaxis.tick_right()\n",
"for ax in (ax10, ax11, ax20, ax21, ax30, ax31, ax40, ax41, ax50):\n",
" ax.set_yticks([3500, 5500])\n",
" ax.set_xlim(-4500, 4500)\n",
" ax.set_ylim(2500, 6500)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:py37]",
"language": "python",
"name": "conda-env-py37-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
================================================
FILE: jupyter/figure_8.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Figure 8\n",
"Compatible with PyKonal Version 0.2.0"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib ipympl\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import os\n",
"import pkg_resources\n",
"import pykonal\n",
"import scipy.ndimage"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"velocity = pykonal.fields.ScalarField3D(coord_sys=\"cartesian\")\n",
"velocity.min_coords = 0, 0, 0\n",
"velocity.node_intervals = 0.1, 0.1, 0.1\n",
"velocity.npts = 512, 128, 1\n",
"velocity.values = scipy.ndimage.gaussian_filter(20. * np.random.randn(*velocity.npts) + 6., 10)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"solver_dg = pykonal.EikonalSolver(coord_sys=\"cartesian\")\n",
"solver_dg.vv.min_coords = velocity.min_coords\n",
"solver_dg.vv.node_intervals = velocity.node_intervals\n",
"solver_dg.vv.npts = velocity.npts\n",
"solver_dg.vv.values = velocity.values\n",
"\n",
"src_idx = (127, 32, 0)\n",
"solver_dg.tt.values[src_idx] = 0\n",
"solver_dg.unknown[src_idx] = False\n",
"solver_dg.trial.push(*src_idx)\n",
"solver_dg.solve()\n",
"\n",
"\n",
"solver_ug = pykonal.EikonalSolver(coord_sys=\"cartesian\")\n",
"solver_ug.vv.min_coords = solver_dg.vv.min_coords\n",
"solver_ug.vv.node_intervals = solver_dg.vv.node_intervals\n",
"solver_ug.vv.npts = solver_dg.vv.npts\n",
"solver_ug.vv.values = solver_dg.vv.values\n",
"\n",
"for ix in range(solver_ug.tt.npts[0]):\n",
" idx = (ix, solver_ug.tt.npts[1]-1, 0)\n",
" solver_ug.tt.values[idx] = solver_dg.tt.values[idx]\n",
" solver_ug.unknown[idx] = False\n",
" solver_ug.trial.push(*idx)\n",
"solver_ug.solve()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.close(\"all\")\n",
"fig = plt.figure(figsize=(6, 2.5))\n",
"\n",
"ax1 = fig.add_subplot(2, 1, 1)\n",
"ax2 = fig.add_subplot(2, 1, 2)\n",
"\n",
"ax = fig.add_subplot(1, 1, 1, frameon=False)\n",
"plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)\n",
"ax.set_ylabel(\"Depth [km]\")\n",
"ax2.set_xlabel(\"Horizontal offset [km]\")\n",
"ax1.set_xticklabels([])\n",
"\n",
"for solver, ax, panel in (\n",
" (solver_dg, ax1, f\"(a)\"), \n",
" (solver_ug, ax2, f\"(b)\")\n",
"):\n",
" ax.text(-0.025, 1.05, panel, va=\"bottom\", ha=\"right\", transform=ax.transAxes)\n",
" qmesh = ax.pcolormesh(\n",
" solver.vv.nodes[:,:,0,0], \n",
" solver.vv.nodes[:,:,0,1], \n",
" solver.vv.values[:,:,0],\n",
" cmap=plt.get_cmap(\"hot\")\n",
" )\n",
" ax.contour(\n",
" solver.tt.nodes[:,:,0,0], \n",
" solver.tt.nodes[:,:,0,1], \n",
" solver.tt.values[:,:,0],\n",
" colors=\"k\",\n",
" linestyles=\"--\",\n",
" linewidths=1,\n",
" levels=np.arange(0, solver.tt.values.max(), 0.25)\n",
" )\n",
" ax.scatter(\n",
" solver.vv.nodes[src_idx + (0,)],\n",
" solver.vv.nodes[src_idx + (1,)],\n",
" marker=\"*\",\n",
" facecolor=\"w\",\n",
" edgecolor=\"k\",\n",
" s=256\n",
" )\n",
" ax.invert_yaxis()\n",
"cbar = fig.colorbar(qmesh, ax=(ax1, ax2))\n",
"cbar.set_label(\"Velocity [km/s]\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:py37]",
"language": "python",
"name": "conda-env-py37-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
================================================
FILE: pykonal/__init__.py
================================================
from .__version__ import (
__major_version__,
__minor_version__,
__patch__,
__release__,
__version_tuple__,
__version__
)
from .solver import EikonalSolver
from . import constants
from . import fields
from . import heapq
from . import inventory
from . import locate
from . import solver
from . import stats
================================================
FILE: pykonal/__version__.py
================================================
__major_version__ = 0
__minor_version__ = 4
__patch__ = 1
__release__ = ''
__version_tuple__ = (
__major_version__,
__minor_version__,
__patch__
)
__version_number__ = '.'.join([str(v) for v in __version_tuple__])
__version__ = f'{__version_number__}{__release__}'
================================================
FILE: pykonal/constants.pxd
================================================
cimport numpy as np
ctypedef np.float64_t REAL_t
ctypedef np.uint16_t UINT_t
ctypedef np.npy_bool BOOL_t
================================================
FILE: pykonal/constants.pyx
================================================
"""
Package-level constants.
"""
import numpy as np
DTYPE_REAL = np.float64
DTYPE_UINT = np.uint32
DTYPE_INT = np.int32
DTYPE_BOOL = np.bool_
EARTH_RADIUS = 6371.
================================================
FILE: pykonal/data/marmousi2/LICENSE
================================================
Attribution 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution 4.0 International Public License ("Public License"). To the
extent this Public License may be interpreted as a contract, You are
granted the Licensed Rights in consideration of Your acceptance of
these terms and conditions, and the Licensor grants You such rights in
consideration of benefits the Licensor receives from making the
Licensed Material available under these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
d. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
g. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
i. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
j. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
k. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
================================================
FILE: pykonal/data/marmousi2/README
================================================
AGL Elastic Marmousi
# Statement
The AGL Elastic Marmousi model was created at the University of Houston,
and was released by its authors Gary S. Martin, Robert Wiley and Kurt J.
Marfurt with the permission of the program director of the Allied
Geophysical Labs consortium in 2019.
# Description
The AGL elastic Marmousi model, also commonly referred to as the Marmousi2
model, is an elastic extension of the original Marmousi model created by
Gary S. Martin, Robert Wiley and Kurt J. Marfurt (2004, 2006). The model
has a lateral extension of 17 km and a depth of 3.5 km and includes a
total of 199 layers geological layers, as well as an extended water layer
of 450 m depth to simulate a deep water setting. The layers were derived
from the same horizon picks that were used for the original Marmousi model
and were supplied by Aline Bourgeois from the Institut Francais du Petrole
(IFP). The simulated data were computed on a supercomputer system at the
University of Houston (UH), supported by Sun Microsystems. The data set
includes subsurface models for density, P-wave and S-wave velocity, as well
as a series of processed data sets (NMO stacks, pre- and poststack time and
depth migrated sections).
# Copyright notice
Copyright 2004 Allied Geophysical Laboratory, University of Houston, TX, USA
# License
This model is licensed under the Creative Commons Attribution 4.0
International License. To view a copy of the license, visit
https://creativecommons.org/licenses/by/4.0 or send a letter to
Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
The license permits any user to freely copy and redistribute the material
in any medium or format. Users are free to remix, transform, and build
upon the material for any purpose, including commercially. Refer to
LICENSE.txt for all terms and conditions, as well as the disclaimer of
warranties.
Please DO NOT separate the model and data from this license and ALWAYS
include the above statement and link with the data.
# Acknowledgments
This model was created by Gary S. Martin (ION), Robert Wiley (University
of Houston) and Kurt J. Marfurt (University of Oklahoma), with support
from Aline Bourgeois (formerly IFP), Fred Hilterman (formerly University
of Houston), Don Larson and Shawn Larson (Lawrence Livermore National
Laboratory, formerly Los Alamos National Laboratory).
Funding for this work was in part provided by the United States Department
of Energy's Next Generation Modeling and Imaging project.
This model was added to the SEG Open Data collection with help from Joseph
Dellinger (BP), Robert Stewart (University of Houston) and Karl Schleicher
(University of Texas at Austin).
# References
Martin, G. S., 2004, The Marmousi2 model, elastic synthetic data, and an
analysis of imaging and AVO in a structurally complex environment:
Master’s thesis. University of Houston. Retrieved from
www.agl.uh.edu/pdf/theses/martin.pdf
Martin, G. S., Marfurt, K. J., and Larsen, S., 2005, Marmousi‐2: An
updated model for the investigation of AVO in structurally complex areas:
SEG Technical Program Expanded Abstracts 2002, 1979–1982.
doi:10.1190/1.1817083
Martin, G. S., Wiley, R., and Marfurt, K. J., 2006, Marmousi2: An elastic
upgrade for Marmousi: The Leading Edge, 25, 156–166.
doi:10.1190/1.2172306
================================================
FILE: pykonal/data/marmousi2/marmousi2.npz
================================================
[File too large to display: 36.3 MB]
================================================
FILE: pykonal/fields.pxd
================================================
cimport numpy as np
from . cimport constants
cdef class Field3D(object):
cdef str cy_coord_sys
cdef str cy_field_type
cdef constants.BOOL_t[3] cy_iax_isnull
cdef constants.BOOL_t[3] cy_iax_isperiodic
cdef constants.REAL_t[3] cy_max_coords
cdef constants.REAL_t[3] cy_min_coords
cdef constants.REAL_t[:,:,:,:] cy_norm
cdef constants.UINT_t[3] cy_npts
cdef constants.REAL_t[3] cy_node_intervals
cdef constants.BOOL_t _update_max_coords(Field3D self)
cdef constants.BOOL_t _update_iax_isnull(Field3D self)
cdef constants.BOOL_t _update_iax_isperiodic(Field3D self)
cpdef constants.BOOL_t to_hdf(
Field3D self,
str path,
str key=*,
constants.BOOL_t overwrite=*
)
cdef class ScalarField3D(Field3D):
cdef constants.REAL_t[:,:,:] cy_values
cpdef np.ndarray[constants.REAL_t, ndim=1] resample(
ScalarField3D self,
constants.REAL_t[:,:] points,
constants.REAL_t null=*
)
cpdef np.ndarray[constants.REAL_t, ndim=2] trace_ray(
ScalarField3D self,
constants.REAL_t[:] end
)
cpdef constants.REAL_t value(
ScalarField3D self,
constants.REAL_t[:] point,
constants.REAL_t null=*
)
cpdef VectorField3D _gradient_of_cartesian(ScalarField3D self)
cpdef VectorField3D _gradient_of_spherical(ScalarField3D self)
cdef class VectorField3D(Field3D):
cdef constants.REAL_t[:,:,:,:] cy_values
cpdef np.ndarray[constants.REAL_t, ndim=1] value(
VectorField3D self,
constants.REAL_t[:] point
)
cpdef Field3D load(str path)
================================================
FILE: pykonal/fields.pyx
================================================
# distutils: language=c++
"""
This module provides three classes (:class:`Field3D <pykonal.fields.Field3D>`,
:class:`ScalarField3D <pykonal.fields.ScalarField3D>`, and
:class:`VectorField3D <pykonal.fields.VectorField3D>`).
:class:`Field3D <pykonal.fields.Field3D>` is a base class intended to
be used only as an abstraction. :class:`ScalarField3D <pykonal.fields.ScalarField3D>`
and :class:`VectorField3D <pykonal.fields.VectorField3D>` both inherit
from :class:`Field3D <pykonal.fields.Field3D>` and add important
functionality that make the classes useful. They are primarily intended
for storing and interpolating data, and, in the case of scalar fields,
computing the gradient.
This module also provides an I/O function
(:func:`read_hdf <pykonal.fields.read_hdf>`) to read data that was saved using
the :func:`to_hdf <pykonal.fields.Field3D.to_hdf>` method of the above
classes.
.. autofunction:: pykonal.fields.load(path)
.. autofunction:: pykonal.fields.read_hdf(path)
"""
import warnings
# Third-party imports
import h5py
import numpy as np
# Local imports
from . import constants
from . import transformations
# Cython built-in imports.
from libc.math cimport sqrt, sin
from libcpp.vector cimport vector as cpp_vector
# Third-party Cython imports
cimport numpy as np
# Local Cython imports
from . cimport constants
cdef class Field3D(object):
"""
Base class for representing generic 3D fields.
"""
def __init__(self, coord_sys="cartesian"):
self.cy_coord_sys = coord_sys
@property
def coord_sys(self):
"""
[*Read only*, :class:`str`] Coordinate system of grid on which
field data is represented {"Cartesian", "spherical"}.
"""
return (self.cy_coord_sys)
@property
def field_type(self):
return (self.cy_field_type)
@property
def iax_isnull(self):
"""
[*Read only*, :class:`numpy.ndarray`\ (shape=(3,), dtype=numpy.bool)]
Array of booleans indicating whether each axis is null. The
axis with only one layer of nodes in 2D problems will be null.
"""
arr = np.array(
[self.cy_iax_isnull[iax] for iax in range(3)],
dtype=constants.DTYPE_BOOL
)
return (arr)
@property
def iax_isperiodic(self):
"""
[*Read only*, :class:`numpy.ndarray`\ (shape=(3,), dtype=numpy.bool)]
Array of booleans indicating whether each axis is periodic. In
practice, only the azimuthal (:math:`\phi`) axis in spherical
coordinates will ever be periodic.
"""
arr = np.array(
[self.cy_iax_isperiodic[iax] for iax in range(3)],
dtype=constants.DTYPE_BOOL
)
return (arr)
@property
def min_coords(self):
"""
[*Read/Write*, :class:`numpy.ndarray`\ (shape=(3,), dtype=numpy.float)]
Array specifying the lower bound of each axis. This attribute
must be initialized by the user.
:math:`\phi` coordinate must be in [-:math:`\pi`, :math:`\pi`) or
[0, 2:math:`\pi`] for spherical coordinates.
"""
return (np.asarray(self.cy_min_coords))
@min_coords.setter
def min_coords(self, value):
if self.coord_sys == "spherical" and value[0] == 0:
raise (ValueError("ρ must be > 0 for spherical coordinates."))
if self.coord_sys == "spherical" and value[2] < -np.pi:
raise (ValueError("φ must be in [-π,π) or [0,2π) for spherical coordinates."))
self.cy_min_coords = np.asarray(value, dtype=constants.DTYPE_REAL)
self._update_max_coords()
self._update_iax_isperiodic()
@property
def max_coords(self):
"""
[*Read only*, :class:`numpy.ndarray`\ (shape=(3,), dtype=numpy.float)]
Array specifying the upper bound of each axis.
"""
return (np.asarray(self.cy_max_coords))
@property
def node_intervals(self):
"""
[*Read/Write*, :class:`numpy.ndarray`\ (shape=(3,), dtype=numpy.float)]
Array of node intervals along each axis. This attribute must be
initialized by the user.
"""
return (np.asarray(self.cy_node_intervals))
@node_intervals.setter
def node_intervals(self, value):
value = np.asarray(value, dtype=constants.DTYPE_REAL)
if np.any(value <= 0):
raise (ValueError("All node intervals must be > 0"))
self.cy_node_intervals = value
self._update_max_coords()
self._update_iax_isperiodic()
@property
def nodes(self):
"""
[*Read only*, :class:`numpy.ndarray`\ (shape=(N0,N1,N2,3), dtype=numpy.float)]
Array specifying the grid-node coordinates.
"""
nodes = [
np.linspace(
self.min_coords[idx],
self.max_coords[idx],
self.npts[idx],
dtype=constants.DTYPE_REAL
)
for idx in range(3)
]
nodes = np.meshgrid(*nodes, indexing="ij")
nodes = np.stack(nodes)
nodes = np.moveaxis(nodes, 0, -1)
return (nodes)
@property
def norm(self):
"""
[*Read-only*, numpy.ndarray(shape=(N0,N1,N2,3), dtype=numpy.float)] 4D array of scaling
factors for gradient operator.
"""
try:
return (np.asarray(self.cy_norm))
except AttributeError:
norm = np.tile(
self.node_intervals,
np.append(self.npts, 1)
)
if self.coord_sys == "spherical":
norm[..., 1] *= self.nodes[..., 0]
norm[..., 2] *= self.nodes[..., 0]
norm[..., 2] *= np.sin(self.nodes[..., 1])
self.cy_norm = norm
return (np.asarray(self.cy_norm))
@property
def npts(self):
"""
[*Read/Write*, :class:`numpy.ndarray`\ (shape=(3,), dtype=numpy.int)]
Array specifying the number of nodes along each axis. This
attribute must be initialized by the user.
"""
return (np.asarray(self.cy_npts))
@npts.setter
def npts(self, value):
self.cy_npts = np.asarray(value, dtype=constants.DTYPE_UINT)
self._update_max_coords()
self._update_iax_isnull()
self._update_iax_isperiodic()
@property
def step_size(self):
"""
[*Read only*, :class:`float`] Step size used for ray tracing.
"""
norm = self.norm[..., ~self.iax_isnull]
return (norm[~np.isclose(norm, 0)].min() / 4)
cdef constants.BOOL_t _update_iax_isperiodic(Field3D self):
if self.cy_coord_sys == "spherical":
self.cy_iax_isperiodic[2] = np.isclose(
self.cy_max_coords[2]+self.cy_node_intervals[2]-self.cy_min_coords[2],
2 * np.pi
)
return (True)
cdef constants.BOOL_t _update_iax_isnull(Field3D self):
cdef Py_ssize_t iax
for iax in range(3):
self.cy_iax_isnull[iax] = True if self.cy_npts[iax] == 1 else False
return (True)
cdef constants.BOOL_t _update_max_coords(Field3D self):
cdef Py_ssize_t iax
cdef constants.REAL_t dx
for iax in range(3):
dx = self.cy_node_intervals[iax] * <constants.REAL_t>(self.cy_npts[iax] - 1)
self.cy_max_coords[iax] = self.cy_min_coords[iax] + dx
if self.cy_coord_sys == "spherical":
if self.cy_min_coords[2] >= 0 and self.cy_max_coords[2] > 2*np.pi:
raise(ValueError("Phi coordinates must be in [-π, π) or [0, 2π)."))
elif self.cy_min_coords[2] < 0 and self.cy_max_coords[2] > np.pi:
raise(ValueError("Phi coordinates must be in [-π, π) or [0, 2π)."))
return (True)
def savez(self, path):
"""
savez(self, path)
Save the field to disk using numpy.savez.
:param path: Path to output file.
:type path: str
:return: Returns True upon successful execution.
:rtype: bool
"""
warning_message = "The savez() method is deprecated and will be removed"\
" from future versions of PyKonal. Use pykonal.fields.Field3D.to_hdf()"\
" instead."
warnings.warn(warning_message, DeprecationWarning)
np.savez_compressed(
path,
min_coords=self.min_coords,
node_intervals=self.node_intervals,
npts=self.npts,
values=self.values,
coord_sys=[self.coord_sys]
)
return (True)
cpdef constants.BOOL_t to_hdf(Field3D self, str path, str key=None, constants.BOOL_t overwrite=False):
with h5py.File(path, mode="a") as f5:
if key is not None:
if key in f5 and overwrite is True:
del (f5[key])
group = f5.create_group(key)
else:
group = f5["/"]
group.attrs["coord_sys"] = self.coord_sys
group.attrs["field_type"] = self.field_type
for attr in ("min_coords", "node_intervals", "npts", "values"):
if attr in group and overwrite is True:
del (group[attr])
group.create_dataset(attr, data=getattr(self, attr))
return (True)
def transform_coordinates(self, coord_sys, origin, force_phi_positive=False):
"""
transform_coordinates(self, coord_sys, origin)
Transform node coordinates to a new frame of reference.
:param coord_sys: Coordinate system to transform to
("*spherical*", or "*Cartesian*")
:type coord_sys: str
:param origin: Coordinates of the origin of the new frame with
respect to the old frame of reference.
:type origin: tuple(float, float, float)
:param force_phi_positive: Force :math:`\phi` to be in [0, 2:math:`pi`)
for output spherical coordinates.
:type force_phi_positive: bool
:return: Node coordinates in new frame of reference.
:rtype: numpy.ndarray(shape=(N0,N1,N2,3), dtype=numpy.float)
"""
if self.coord_sys == "spherical" and coord_sys.lower() == "spherical":
return (
transformations.sph2sph(
self.nodes,
origin,
force_phi_positive=force_phi_positive
)
)
elif self.coord_sys == "cartesian" and coord_sys.lower() == "spherical":
return (transformations.xyz2sph(self.nodes, origin))
elif self.coord_sys == "spherical" and coord_sys.lower() == "cartesian":
return (transformations.sph2xyz(self.nodes, origin))
elif self.coord_sys == "cartesian" and coord_sys.lower() == "cartesian":
return (transformations.xyz2xyz(self.nodes, origin))
else:
raise (NotImplementedError())
cdef class ScalarField3D(Field3D):
"""
Class for representing 3D scalar fields.
"""
def __init__(self, coord_sys="cartesian"):
super(ScalarField3D, self).__init__(coord_sys=coord_sys)
self.cy_field_type = "scalar"
@property
def gradient(self):
"""
[*Read only*, numpy.ndarray(shape=(N0,N1,N2,3), dtype=numpy.float)]
Gradient of the field.
"""
if self.coord_sys == "cartesian":
return (self._gradient_of_cartesian())
elif self.coord_sys == "spherical":
return (self._gradient_of_spherical())
@property
def values(self):
"""
[*Read/Write*, numpy.ndarray(shape=(N0,N1,N2), dtype=numpy.float)]
Value of the field at each grid node.
"""
try:
return (np.asarray(self.cy_values))
except AttributeError:
self.cy_values = np.full(self.npts, fill_value=np.nan)
return (np.asarray(self.cy_values))
@values.setter
def values(self, value):
values = np.asarray(value, dtype=constants.DTYPE_REAL)
if not np.all(values.shape == self.npts):
raise (ValueError("Shape of values does not match npts attribute."))
self.cy_values = values
cpdef np.ndarray[constants.REAL_t, ndim=1] resample(ScalarField3D self, constants.REAL_t[:,:] points, constants.REAL_t null=np.nan):
"""
resample(self, points, null=numpy.nan)
Resample the field at an arbitrary set of points using
trilinear interpolation.
:param points: Points at which to resample the field.
:type points: numpy.ndarray(shape=(N,3), dtype=numpy.float)
:param null: Default (null) value to return for points lying
outside the interpolation domain.
:type null: float
:return: Resampled field values.
:rtype: numpy.ndarray(shape=(N,), dtype=numpy.float)
"""
cdef Py_ssize_t idx
cdef np.ndarray[constants.REAL_t, ndim=1] resampled # Using a MemoryViewBuffer might make this faster.
resampled = np.empty(points.shape[0], dtype=constants.DTYPE_REAL)
for idx in range(points.shape[0]):
resampled[idx] = self.value(points[idx], null=null)
return (resampled)
cpdef np.ndarray[constants.REAL_t, ndim=2] trace_ray(
ScalarField3D self,
constants.REAL_t[:] end
):
"""
trace_ray(self, end)
Trace the ray ending at *end* (given in the
same coordinate system as self.coord_sys.)
This method traces the ray that ends at *end* in reverse
direction by taking small steps along the path of steepest
descent. The resulting ray is reversed before being returned,
so it is in the normal forward-time orientation.
:param end: Coordinates of the ray's end point.
:type end: numpy.ndarray(shape=(3,), dtype=numpy.float)
:return: The ray path ending at *end*.
:rtype: numpy.ndarray(shape=(N,3), dtype=numpy.float)
"""
cdef cpp_vector[constants.REAL_t] ray
cdef constants.REAL_t norm, step_size, value, value_1back
cdef constants.REAL_t[3] gg
cdef constants.REAL_t[:] point
cdef Py_ssize_t idx
cdef str coord_sys
cdef np.ndarray[constants.REAL_t, ndim=1] ray_np
cdef VectorField3D grad
coord_sys = self.coord_sys
step_size = self.step_size
grad = self.gradient
for idx in range(3):
ray.push_back(end[idx])
value = np.infty
while True:
point = <constants.REAL_t[:3]>&ray[ray.size()-3]
try:
value_1back = value
value = self.value(point)
if value >= value_1back or np.isnan(value):
ray.resize(ray.size()-3) # drop bad pt
break
except ValueError:
return (None)
gg = grad.value(point)
norm = sqrt(gg[0]**2 + gg[1]**2 + gg[2]**2)
if np.isnan(norm):
raise (ValueError("Encountered NaN gradient."))
for idx in range(3):
gg[idx] /= norm
if coord_sys == "spherical":
gg[1] /= point[0]
gg[2] /= point[0] * sin(point[1])
for idx in range(3):
ray.push_back(point[idx] - step_size * gg[idx])
ray_np = np.empty(ray.size(), dtype=constants.DTYPE_REAL)
for idx in range(ray_np.size):
ray_np[idx] = ray[idx]
return (np.flipud(ray_np.reshape(-1,3)))
cpdef constants.REAL_t value(
ScalarField3D self,
constants.REAL_t[:] point,
constants.REAL_t null=np.nan
):
"""
value(self, point, null=numpy.nan)
Interpolate the field at *point* using trilinear interpolation.
:param point: Coordinates of the point at which to interpolate
the field.
:type point: numpy.ndarray(shape=(3,), dtype=numpy.float)
:param null: Default (null) value to return if point lies
outside the interpolation domain.
:type null: float
:return: Value of the field at *point*.
:rtype: float
"""
cdef constants.REAL_t[3] delta, idx
cdef constants.REAL_t f000, f100, f110, f101, f111, f010, f011, f001
cdef constants.REAL_t f00, f10, f01, f11
cdef constants.REAL_t f0, f1
cdef constants.REAL_t f
cdef Py_ssize_t[3][2] ii
cdef Py_ssize_t i1, i2, i3, iax, di1, di2, di3
for iax in range(3):
if (
(
point[iax] < self.cy_min_coords[iax]
or point[iax] > self.cy_max_coords[iax]
)
and not self.cy_iax_isperiodic[iax]
and not self.cy_iax_isnull[iax]
):
return (null)
idx[iax] = (point[iax] - self.cy_min_coords[iax]) / self.cy_node_intervals[iax]
if self.cy_iax_isnull[iax]:
ii[iax][0] = 0
ii[iax][1] = 0
else:
ii[iax][0] = <Py_ssize_t>idx[iax]
ii[iax][1] = <Py_ssize_t>(ii[iax][0]+1) % self.npts[iax]
delta[iax] = idx[iax] % 1
f000 = self.cy_values[ii[0][0], ii[1][0], ii[2][0]]
f100 = self.cy_values[ii[0][1], ii[1][0], ii[2][0]]
f110 = self.cy_values[ii[0][1], ii[1][1], ii[2][0]]
f101 = self.cy_values[ii[0][1], ii[1][0], ii[2][1]]
f111 = self.cy_values[ii[0][1], ii[1][1], ii[2][1]]
f010 = self.cy_values[ii[0][0], ii[1][1], ii[2][0]]
f011 = self.cy_values[ii[0][0], ii[1][1], ii[2][1]]
f001 = self.cy_values[ii[0][0], ii[1][0], ii[2][1]]
f00 = f000 + (f100 - f000) * delta[0]
f10 = f010 + (f110 - f010) * delta[0]
f01 = f001 + (f101 - f001) * delta[0]
f11 = f011 + (f111 - f011) * delta[0]
f0 = f00 + (f10 - f00) * delta[1]
f1 = f01 + (f11 - f01) * delta[1]
f = f0 + (f1 - f0) * delta[2]
return (f)
cpdef VectorField3D _gradient_of_cartesian(ScalarField3D self):
"""
The gradient of a field represented on a Cartesian grid.
"""
gg = np.gradient(
self.values,
*[
self.node_intervals[iax]
for iax in range(3) if not self.iax_isnull[iax]
],
axis=[
iax
for iax in range(3)
if not self.iax_isnull[iax]
]
)
gg = np.moveaxis(np.stack(gg), 0, -1)
for iax in range(3):
if self.iax_isnull[iax]:
gg = np.insert(gg, iax, np.zeros(self.npts), axis=-1)
grad = VectorField3D(coord_sys=self.coord_sys)
grad.min_coords = self.min_coords
grad.node_intervals = self.node_intervals
grad.npts = self.npts
grad.values = gg
return (grad)
cpdef VectorField3D _gradient_of_spherical(ScalarField3D self):
"""
The gradient of a field represented on a spherical grid.
"""
grid = self.nodes
d0, d1, d2 = self.node_intervals
n0, n1, n2 = self.npts
if not self.iax_isnull[0]:
# Second-order forward difference evaluated along the lower edge
g0_lower = (
(
self.values[2]
- 4*self.values[1]
+ 3*self.values[0]
) / (2*d0)
).reshape(1, n1, n2)
# Second order central difference evaluated in the interior
g0_interior = (self.values[2:] - self.values[:-2]) / (2*d0)
# Second order backward difference evaluated along the upper edge
g0_upper = (
(
self.values[-3]
- 4*self.values[-2]
+ 3*self.values[-1]
) / (2*d0)
).reshape(1, n1, n2)
g0 = np.concatenate([g0_lower, g0_interior, g0_upper], axis=0)
else:
g0 = np.zeros((n0, n1, n2))
if not self.iax_isnull[1]:
# Second-order forward difference evaluated along the lower edge
g1_lower = (
(
self.values[:,2]
- 4*self.values[:,1]
+ 3*self.values[:,0]
) / (2*grid[:,0,:,0]*d1)
).reshape(n0, 1, n2)
# Second order central difference evaluated in the interior
g1_interior = (
self.values[:,2:]
- self.values[:,:-2]
) / (2*grid[:,1:-1,:,0]*d1)
# Second order backward difference evaluated along the upper edge
g1_upper = (
(
self.values[:,-3]
- 4*self.values[:,-2]
+ 3*self.values[:,-1]
) / (2*grid[:,-1,:,0]*d1)
).reshape(n0, 1, n2)
g1 = np.concatenate([g1_lower, g1_interior, g1_upper], axis=1)
else:
g1 = np.zeros((n0, n1, n2))
if not self.iax_isnull[2]:
# Second-order forward difference evaluated along the lower edge
g2_lower = (
(
self.values[:,:,2]
- 4*self.values[:,:,1]
+ 3*self.values[:,:,0]
) / (2*grid[:,:,0,0]*np.sin(grid[:,:,0,1])*d2)
).reshape(n0, n1, 1)
# Second order central difference evaluated in the interior
g2_interior = (
self.values[:,:,2:]
- self.values[:,:,:-2]
) / (2*grid[:,:,1:-1,0]*np.sin(grid[:,:,1:-1,1])*d2)
# Second order backward difference evaluated along the upper edge
g2_upper = (
(
self.values[:,:,-3]
- 4*self.values[:,:,-2]
+ 3*self.values[:,:,-1]
) / (2*grid[:,:,-1,0]*np.sin(grid[:,:,-1,1])*d2)
).reshape(n0, n1, 1)
g2 = np.concatenate([g2_lower, g2_interior, g2_upper], axis=2)
else:
g2 = np.zeros((n0, n1, n2))
gg = np.moveaxis(np.stack([g0, g1, g2]), 0, -1)
grad = VectorField3D(coord_sys=self.coord_sys)
grad.min_coords = self.min_coords
grad.node_intervals = self.node_intervals
grad.npts = self.npts
grad.values = gg
return (grad)
cdef class VectorField3D(Field3D):
"""
Class for representing 3D vector fields.
"""
def __init__(self, coord_sys="cartesian"):
super(VectorField3D, self).__init__(coord_sys=coord_sys)
self.cy_field_type = "vector"
@property
def values(self):
"""
[*Read/Write*, numpy.ndarray(shape=(N0,N1,N2,3), dtype=numpy.float)]
Value of the field at each grid node.
"""
try:
return (np.asarray(self.cy_values))
except AttributeError:
self.cy_values = np.full(self.npts, fill_value=np.nan)
return (np.asarray(self.cy_values))
@values.setter
def values(self, value):
values = np.asarray(value)
if not np.all(values.shape[:3] == self.npts):
raise (ValueError("Shape of values does not match npts attribute."))
self.cy_values = np.asarray(value)
cpdef np.ndarray[constants.REAL_t, ndim=1] value(VectorField3D self, constants.REAL_t[:] point):
"""
value(self, point)
Interpolate the field at *point* using trilinear interpolation.
:param point: Coordinates of the point at which to interpolate
the field.
:type point: numpy.ndarray(shape=(3,), dtype=numpy.float)
:return: Value of the field at *point*.
:rtype: numpy.ndarray(shape=(3,), dtype=numpy.float)
"""
cdef constants.REAL_t[3] ff
cdef constants.REAL_t[3] delta, idx
cdef constants.REAL_t f000, f100, f110, f101, f111, f010, f011, f001
cdef constants.REAL_t f00, f10, f01, f11
cdef constants.REAL_t f0, f1
cdef constants.REAL_t f
cdef Py_ssize_t[3][2] ii
cdef Py_ssize_t i1, i2, i3, iax, di1, di2, di3
for iax in range(3):
#if (
# (
# point[iax] < self.min_coords[iax]
# or point[iax] > self.max_coords[iax]
# )
# and not self.is_periodic[iax]
# and not self._iax_isnull[iax]
#):
# raise(
# OutOfBoundsError(
# f"Point outside of interpolation domain requested: ({point[0]}, {point[1]}, {point[2]})"
# )
# )
idx[iax] = (point[iax] - self.min_coords[iax]) / self.node_intervals[iax]
if self.iax_isnull[iax]:
ii[iax][0] = 0
ii[iax][1] = 0
else:
ii[iax][0] = <Py_ssize_t>idx[iax]
ii[iax][1] = <Py_ssize_t>(ii[iax][0]+1) % self.npts[iax]
delta[iax] = idx[iax] % 1
for iax in range(3):
f000 = self.cy_values[ii[0][0], ii[1][0], ii[2][0], iax]
f100 = self.cy_values[ii[0][1], ii[1][0], ii[2][0], iax]
f110 = self.cy_values[ii[0][1], ii[1][1], ii[2][0], iax]
f101 = self.cy_values[ii[0][1], ii[1][0], ii[2][1], iax]
f111 = self.cy_values[ii[0][1], ii[1][1], ii[2][1], iax]
f010 = self.cy_values[ii[0][0], ii[1][1], ii[2][0], iax]
f011 = self.cy_values[ii[0][0], ii[1][1], ii[2][1], iax]
f001 = self.cy_values[ii[0][0], ii[1][0], ii[2][1], iax]
f00 = f000 + (f100 - f000) * delta[0]
f10 = f010 + (f110 - f010) * delta[0]
f01 = f001 + (f101 - f001) * delta[0]
f11 = f011 + (f111 - f011) * delta[0]
f0 = f00 + (f10 - f00) * delta[1]
f1 = f01 + (f11 - f01) * delta[1]
f = f0 + (f1 - f0) * delta[2]
ff[iax] = f
return (np.asarray(ff))
cpdef Field3D load(str path):
"""
.. deprecated:: 0.3.2
Use :func:`read_hdf` instead.
Load field data from disk.
:param path: Path to input file.
:type path: str
:return: A Field3D-derivative class initialized with data in *path*.
:rtype: ScalarField3D or VectorField3D
"""
warning_message = "The load() function is deprecated and will be removed"\
" from future versions of PyKonal. Use pykonal.fields.read_hdf()"\
" instead."
warnings.warn(warning_message, DeprecationWarning)
with np.load(path) as npz:
coord_sys = str(npz["coord_sys"][0])
if len(npz["values"].shape) == 4:
field = VectorField3D(coord_sys=coord_sys)
else:
field = ScalarField3D(coord_sys=coord_sys)
field.min_coords = npz["min_coords"]
field.node_intervals = npz["node_intervals"]
field.npts = npz["npts"]
field.values = npz["values"]
return (field)
def read_hdf(path, min_coords=None, max_coords=None):
"""
Load field data from HDF5 file on disk.
:param path: Path to input file.
:type path: str
:param min_coords: Minimum bounding coordinates to read. This is for
reading a limited portion of the file and should
be given in the same coordinates as self.coord_sys.
:type min_coords: numpy.ndarray(shape=(3,), dtype=numpy.float), optional
:param max_coords: Maximum bounding coordinates to read. This is for
reading a limited portion of the file and should
be given in the same coordinates as self.coord_sys.
:type max_coords: numpy.ndarray(shape=(3,), dtype=numpy.float), optional
:return: A Field3D-derivative class initialized with data in *path*.
:rtype: ScalarField3D or VectorField3D
"""
with h5py.File(path, mode="r") as f5:
_coord_sys = f5.attrs["coord_sys"]
_field_type = f5.attrs["field_type"]
_min_coords = f5["min_coords"][:]
_node_intervals = f5["node_intervals"][:]
_npts = f5["npts"][:]
if min_coords is not None:
min_coords = np.array(min_coords)
if max_coords is not None:
max_coords = np.array(max_coords)
if min_coords is not None and max_coords is not None:
if np.any(min_coords >= max_coords):
raise(ValueError("All values of min_coords must satisfy min_coords < max_coords."))
if min_coords is not None:
idx_start = (min_coords - _min_coords) / _node_intervals
idx_start = np.floor(idx_start)
idx_start = idx_start.astype(np.int32)
idx_start = np.clip(idx_start, 0, _npts - 1)
else:
idx_start = np.array([0, 0, 0])
if max_coords is not None:
idx_end = (max_coords - _min_coords) / _node_intervals
idx_end = np.ceil(idx_end) + 1
idx_end = idx_end.astype(np.int32)
idx_end = np.clip(idx_end, idx_start + 1, _npts)
else:
idx_end = _npts
if _field_type == "scalar":
field = ScalarField3D(coord_sys=_coord_sys)
elif _field_type == "vector":
field = VectorField3D(coord_sys=_coord_sys)
else:
raise (ValueError(f"Unrecognized field type: {_field_type}"))
field.min_coords = _min_coords + idx_start * _node_intervals
field.node_intervals = _node_intervals
field.npts = idx_end - idx_start
idxs = tuple(slice(idx_start[idx], idx_end[idx]) for idx in range(3))
field.values = f5["values"][idxs]
return (field)
================================================
FILE: pykonal/heapq.pxd
================================================
# distutils: language=c++
from libcpp.vector cimport vector as cpp_vector
from . cimport constants
cdef struct Index3D:
Py_ssize_t i1, i2, i3
cdef class Heap(object):
cdef cpp_vector[Index3D] cy_keys
cdef constants.REAL_t[:,:,:] cy_values
cdef Py_ssize_t[:,:,:] cy_heap_index
cpdef (Py_ssize_t, Py_ssize_t, Py_ssize_t) pop(Heap self)
cpdef constants.BOOL_t push(Heap self, Py_ssize_t i1, Py_ssize_t i2, Py_ssize_t i3)
cpdef constants.BOOL_t sift_down(Heap self, Py_ssize_t j_start, Py_ssize_t j)
cpdef constants.BOOL_t sift_up(Heap self, Py_ssize_t j_start)
================================================
FILE: pykonal/heapq.pyx
================================================
"""
A module providing heap-sort functionality.
This module provides a single class (:class:`pykonal.heapq.Heap`) which
implements a binary min-heap structure whose elements are indices
(each having three components) sorted by an auxiliary value. Indices can
be pushed onto and popped from the Heap and the auxiliary sort values
can be updated on the fly, although care must be taken to resort the
Heap so as to maintain the heap invariant when updating the underlying
sort values.
"""
# Imports.
import numpy as np
from . import constants
# C Imports.
cimport numpy as np
from . cimport constants
cdef struct Index3D:
Py_ssize_t i1, i2, i3
cdef class Heap(object):
"""
Binary Min-Heap structure for storing indices sorted by auxiliary
values.
"""
def __init__(self, values):
self.cy_values = values
self.cy_heap_index = np.full(values.shape, fill_value=-1)
@property
def heap_index(self):
"""
[*Read only*, numpy.ndarray(shape=(N0,N1,N2), dtype=numpy.int)]
Array of indices indicating the heap position of each node.
Index -1 indicates that a node is not on the heap.
"""
return (np.asarray(self.cy_heap_index, dtype=constants.DTYPE_INT))
@property
def keys(self):
"""
[*Read only*, list] Sorted list of node
indices currently on the heap.
"""
cdef Index3D idx
output = []
for i in range(self.cy_keys.size()):
idx = self.cy_keys[i]
output.append((idx.i1, idx.i2, idx.i3))
return (output)
@property
def size(self):
"""
[*Read only*, int] Number of node indices on the heap.
"""
return (self.cy_keys.size())
@property
def values(self):
"""
[*Read/Write*, numpy.ndarray(shape=(N0,N1,N2), dtype=numpy.float)]
Auxiliary values to sort by.
"""
return (np.asarray(self.cy_values))
@values.setter
def values(self, values):
self.cy_values = values
cpdef (Py_ssize_t, Py_ssize_t, Py_ssize_t) pop(Heap self):
"""
pop(self)
Pop the index of the item with the smallest sort value from the
heap, maintaining the heap invariant.
:return: Index of node on the heap with smallest sort value.
:rtype: tuple(int, int, int)
"""
cdef Index3D last, idx_return
last = self.cy_keys.back()
self.cy_keys.pop_back()
self.cy_heap_index[last.i1, last.i2, last.i3] = -1
if self.cy_keys.size() > 0:
idx_return = self.cy_keys[0]
self.cy_heap_index[idx_return.i1, idx_return.i2, idx_return.i3] = -1
self.cy_keys[0] = last
self.cy_heap_index[last.i1, last.i2, last.i3] = 0
self.sift_up(0)
return ((idx_return.i1, idx_return.i2, idx_return.i3))
return ((last.i1, last.i2, last.i3))
cpdef constants.BOOL_t push(Heap self, Py_ssize_t i1, Py_ssize_t i2, Py_ssize_t i3):
"""
push(self, i1, i2, i3)
Push index onto the heap, maintaining the heap invariant.
:param i1: First component of index.
:type i1: int
:param i2: Second component of index.
:type i2: int
:param i3: Third component of index.
:type i3: int
:return: True upon successful completion.
:rtype: bool
.. todo:: Check that index is in range.
"""
cdef Index3D idx
idx.i1, idx.i2, idx.i3 = i1, i2, i3
self.cy_keys.push_back(idx)
self.cy_heap_index[idx.i1, idx.i2, idx.i3] = self.cy_keys.size()-1
self.sift_down(0, self.cy_keys.size()-1)
return (True)
cpdef constants.BOOL_t sift_down(Heap self, Py_ssize_t j_start, Py_ssize_t j):
"""
sift_down(self, j_start, j)
Sift the heap element at *j* down the heap (towards the root),
without going past *j_start*, until finding a place that it
fits.
:param j_start: Heap index creating a barrier beyond which heap
element *j* cannot be sifted.
:type j_start: int
:param j: Heap index of element to sift towards root.
:type j: int
:return: Returns True upon successful execution.
:rtype: bool
"""
cdef Py_ssize_t j_parent
cdef Index3D idx_new, idx_parent
idx_new = self.cy_keys[j]
# Follow the path to the root, moving parents down until finding a place
# new item fits.
while j > j_start:
j_parent = (j - 1) >> 1
idx_parent = self.cy_keys[j_parent]
if self.cy_values[idx_new.i1, idx_new.i2, idx_new.i3] < self.cy_values[idx_parent.i1, idx_parent.i2, idx_parent.i3]:
self.cy_keys[j] = idx_parent
self.cy_heap_index[idx_parent.i1, idx_parent.i2, idx_parent.i3] = j
j = j_parent
continue
break
self.cy_keys[j] = idx_new
self.cy_heap_index[idx_new.i1, idx_new.i2, idx_new.i3] = j
return (True)
cpdef constants.BOOL_t sift_up(Heap self, Py_ssize_t j_start):
"""
sift_up(self, j_start)
Sift the heap element at *j_start* up the heap (away from the
root), until finding a place that it fits.
:param j_start: Heap index of element to sift away from root.
:type j_start: int
:return: Returns True upon successful execution.
:rtype: bool
"""
cdef Py_ssize_t j, j_child, j_end, j_right
cdef Index3D idx_child, idx_right, idx_new
j_end = self.cy_keys.size()
j = j_start
idx_new = self.cy_keys[j_start]
# Bubble up the smaller child until hitting a leaf.
j_child = 2 * j_start + 1 # leftmost child position
while j_child < j_end:
# Set childpos to index of smaller child.
j_right = j_child + 1
idx_child, idx_right = self.cy_keys[j_child], self.cy_keys[j_right]
if j_right < j_end and not self.cy_values[idx_child.i1, idx_child.i2, idx_child.i3] < self.cy_values[idx_right.i1, idx_right.i2, idx_right.i3]:
j_child = j_right
# Move the smaller child up.
self.cy_keys[j] = self.cy_keys[j_child]
self.cy_heap_index[self.cy_keys[j_child].i1, self.cy_keys[j_child].i2, self.cy_keys[j_child].i3] = j
j = j_child
j_child = 2 * j + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
self.cy_keys[j] = idx_new
self.cy_heap_index[idx_new.i1, idx_new.i2, idx_new.i3] = j
self.sift_down(j_start, j)
return (True)
================================================
FILE: pykonal/inventory.py
================================================
import h5py
import numpy as np
import os
from . import fields
class TraveltimeInventory(object):
def __init__(self, path, mode="r"):
self._mode = mode
self._path = path
self._f5 = h5py.File(path, mode=mode)
def __del__(self):
self.f5.close()
def __enter__(self):
return (self)
def __exit__(self, exc_type, exc_value, exc_traceback):
self.__del__()
@property
def f5(self):
return (self._f5)
@property
def mode(self):
return (self._mode)
@mode.setter
def mode(self, value):
self._mode = value
self.f5.close()
self._f5 = h5py.File(self.path, mode=value)
@property
def path(self):
return (self._path)
def add(self, field, key):
group = self.f5.create_group(key)
group.attrs["coord_sys"] = field.coord_sys
group.attrs["field_type"] = field.field_type
for attr in ("min_coords", "node_intervals", "npts", "values"):
group.create_dataset(attr, data=getattr(field, attr))
return (True)
def merge(self, paths):
for path in paths:
_, filename = os.path.split(path)
filename, file_ext = os.path.splitext(filename)
network, station, phase = filename.split(".")
field = fields.read_hdf(path)
self.add(field, "/".join([network, station, phase]))
return (True)
def read(self, key, min_coords=None, max_coords=None):
group = self.f5[key]
_coord_sys = group.attrs["coord_sys"]
_field_type = group.attrs["field_type"]
_min_coords = group["min_coords"][:]
_node_intervals = group["node_intervals"][:]
_npts = group["npts"][:]
if min_coords is not None:
min_coords = np.array(min_coords)
if max_coords is not None:
max_coords = np.array(max_coords)
if min_coords is not None and max_coords is not None:
if np.any(min_coords >= max_coords):
raise(ValueError("All values of min_coords must satisfy min_coords < max_coords."))
if min_coords is not None:
idx_start = (min_coords - _min_coords) / _node_intervals
idx_start = np.floor(idx_start)
idx_start = idx_start.astype(np.int32)
idx_start = np.clip(idx_start, 0, _npts - 1)
else:
idx_start = np.array([0, 0, 0])
if max_coords is not None:
idx_end = (max_coords - _min_coords) / _node_intervals
idx_end = np.ceil(idx_end) + 1
idx_end = idx_end.astype(np.int32)
idx_end = np.clip(idx_end, idx_start + 1, _npts)
else:
idx_end = _npts
if _field_type == "scalar":
field = fields.ScalarField3D(coord_sys=_coord_sys)
elif _field_type == "vector":
field = fields.VectorField3D(coord_sys=_coord_sys)
else:
raise (ValueError(f"Unrecognized field type: {_field_type}"))
field.min_coords = _min_coords + idx_start * _node_intervals
field.node_intervals = _node_intervals
field.npts = idx_end - idx_start
idxs = tuple(slice(idx_start[idx], idx_end[idx]) for idx in range(3))
field.values = group["values"][idxs]
return (field)
================================================
FILE: pykonal/locate.pxd
================================================
cimport numpy as np
from . cimport constants
from . cimport fields
cdef class EQLocator(object):
cdef str cy_coord_sys
cdef dict cy_stations
cdef object cy_traveltime_inventory
cdef fields.ScalarField3D cy_grid
cdef fields.ScalarField3D cy_pwave_velocity
cdef fields.ScalarField3D cy_swave_velocity
cdef dict cy_arrivals
cdef dict cy_traveltimes
cdef dict cy_residual_rvs
cpdef constants.BOOL_t add_arrivals(EQLocator self, dict arrivals)
cpdef constants.BOOL_t add_residual_rvs(EQLocator self, dict residua_rvs)
cpdef constants.BOOL_t clear_arrivals(EQLocator self)
cpdef constants.BOOL_t clear_residual_rvs(EQLocator self)
cpdef constants.BOOL_t read_traveltimes(
EQLocator self,
constants.REAL_t[:] min_coords=*,
constants.REAL_t[:] max_coords=*
)
cpdef constants.REAL_t log_likelihood(
EQLocator self,
constants.REAL_t[:] model
)
#cpdef np.ndarray[constants.REAL_t, ndim=1] grid_search(EQLocator self)
cpdef constants.REAL_t rms(EQLocator self, constants.REAL_t[:] hypocenter)
cpdef np.ndarray[constants.REAL_t, ndim=1] locate(
EQLocator self,
np.ndarray[constants.REAL_t, ndim=1] initial,
np.ndarray[constants.REAL_t, ndim=1] delta
)
================================================
FILE: pykonal/locate.pyx
================================================
# Cython compiler directives.
# distutils: language=c++
# cython: profile=True
import numpy as np
import os
import pykonal
import scipy.optimize
import tempfile
from . import constants as _constants
from . import inventory as _inventory
from . import solver as _solver
from . import transformations as _transformations
cimport numpy as np
from libc.math cimport sqrt
from . cimport fields
from . cimport constants
inf = np.inf
cdef class EQLocator(object):
"""
EQLocator(stations, tt_inv, coord_sys='spherical')
A class to locate earthquakes.
"""
def __init__(
self,
traveltime_inventory: str,
coord_sys: str="spherical"
):
self.cy_arrivals = {}
self.cy_traveltimes = {}
self.cy_coord_sys = coord_sys
inventory = _inventory.TraveltimeInventory(
traveltime_inventory,
mode="r"
)
self.cy_traveltime_inventory = inventory
def __del__(self):
self.traveltime_inventory.f5.close()
def __enter__(self):
return (self)
def __exit__(self, exc_type, exc_value, exc_traceback):
self.__del__()
cpdef constants.BOOL_t add_arrivals(EQLocator self, dict arrivals):
self.cy_arrivals = {**self.cy_arrivals, **arrivals}
return (True)
cpdef constants.BOOL_t add_residual_rvs(EQLocator self, dict residual_rvs):
self.cy_residual_rvs = {**self.cy_residual_rvs, **residual_rvs}
return (True)
cpdef constants.BOOL_t clear_arrivals(EQLocator self):
self.cy_arrivals = {}
return (True)
cpdef constants.BOOL_t clear_residual_rvs(EQLocator self):
self.cy_residual_rvs = {}
return (True)
@property
def arrivals(self) -> dict:
return (self.cy_arrivals)
@arrivals.setter
def arrivals(self, value: dict):
self.cy_arrivals = value
@property
def coord_sys(self) -> str:
return (self.cy_coord_sys)
@property
def grid(self) -> object:
if self.cy_grid is None:
self.cy_grid = fields.ScalarField3D(coord_sys=self.cy_coord_sys)
return (self.cy_grid)
@property
def traveltime_inventory(self) -> object:
return (self.cy_traveltime_inventory)
@property
def pwave_velocity(self) -> object:
if self.cy_pwave_velocity is None:
self.cy_pwave_velocity = fields.ScalarField3D(
coord_sys=self.cy_coord_sys
)
self.cy_pwave_velocity.min_coords = self.cy_grid.min_coords
self.cy_pwave_velocity.node_intervals = self.cy_grid.node_intervals
self.cy_pwave_velocity.npts = self.cy_grid.npts
return (self.cy_pwave_velocity)
@pwave_velocity.setter
def pwave_velocity(self, value: np.ndarray):
if self.cy_pwave_velocity is None:
self.pwave_velocity
self.cy_pwave_velocity.values = value
@property
def vp(self) -> object:
return (self.pwave_velocity)
@vp.setter
def vp(self, value: np.ndarray):
self.pwave_velocity = value
@property
def residual_rvs(self) -> dict:
return (self.cy_residual_rvs)
@residual_rvs.setter
def residual_rvs(self, value: dict):
self.cy_residual_rvs = value
@property
def swave_velocity(self) -> object:
if self.cy_swave_velocity is None:
self.cy_swave_velocity = fields.ScalarField3D(
coord_sys=self.cy_coord_sys
)
self.cy_swave_velocity.min_coords = self.cy_grid.min_coords
self.cy_swave_velocity.node_intervals = self.cy_grid.node_intervals
self.cy_swave_velocity.npts = self.cy_grid.npts
return (self.cy_swave_velocity)
@swave_velocity.setter
def swave_velocity(self, value: np.ndarray):
if self.cy_swave_velocity is None:
self.swave_velocity
self.cy_swave_velocity.values = value
@property
def traveltimes(self) -> dict:
return (self.cy_traveltimes)
@traveltimes.setter
def traveltimes(self, value: dict):
self.cy_traveltimes = value
@property
def vs(self) -> object:
return (self.swave_velocity)
@vs.setter
def vs(self, value: np.ndarray):
self.swave_velocity = value
cpdef constants.BOOL_t read_traveltimes(
EQLocator self,
constants.REAL_t[:] min_coords=None,
constants.REAL_t[:] max_coords=None
):
inventory = self.cy_traveltime_inventory
self.cy_traveltimes = {
index: inventory.read(
"/".join(index),
min_coords=min_coords,
max_coords=max_coords
) for index in self.cy_arrivals
}
return True
#cpdef np.ndarray[constants.REAL_t, ndim=1] grid_search(EQLocator self):
# values = [self.cy_arrivals[key]-np.ma.masked_invalid(self.cy_traveltimes[key].values) for key in self.cy_traveltimes]
# values = np.stack(values)
# std = values.std(axis=0)
# arg_min = np.argmin(std)
# idx_min = np.unravel_index(arg_min, std.shape)
# coords = self.cy_grid.nodes[idx_min]
# time = values.mean(axis=0)[idx_min]
# return (np.array([*coords, time], dtype=_constants.DTYPE_REAL))
#
cpdef constants.REAL_t rms(EQLocator self, constants.REAL_t[:] hypocenter):
cdef tuple key
cdef dict arrivals
cdef dict traveltimes
cdef constants.REAL_t csum = 0
cdef constants.REAL_t num
cdef constants.REAL_t t0
arrivals = self.cy_arrivals
traveltimes = self.cy_traveltimes
t0 = hypocenter[3]
for key in arrivals:
num = arrivals[key] - t0
num -= traveltimes[key].value(hypocenter[:3], null=np.inf)
csum += num * num
return (sqrt(csum/len(arrivals)))
cpdef np.ndarray[constants.REAL_t, ndim=1] locate(
EQLocator self,
np.ndarray[constants.REAL_t, ndim=1] initial,
np.ndarray[constants.REAL_t, ndim=1] delta
):
"""
Locate event using a grid search and Differential Evolution
Optimization to minimize the residual RMS.
"""
min_coords = initial - delta
max_coords = initial + delta
bounds = np.stack([min_coords, max_coords]).T
self.read_traveltimes(
min_coords=min_coords[:3],
max_coords=max_coords[:3]
)
soln = scipy.optimize.differential_evolution(self.rms, bounds)
return (soln.x)
cpdef constants.REAL_t log_likelihood(
EQLocator self,
constants.REAL_t[:] model
):
cdef constants.REAL_t t_pred, residual
cdef constants.REAL_t log_likelihood = 0.0
cdef tuple key
cdef EQLocator[:] junk
for key in self.cy_arrivals:
t_pred = model[3] + self.cy_traveltimes[key].value(model[:3])
residual = self.cy_arrivals[key] - t_pred
log_likelihood = log_likelihood + self.cy_residual_rvs[key].logpdf(residual)
return (log_likelihood)
================================================
FILE: pykonal/solver.pxd
================================================
cimport numpy as np
from libcpp cimport bool as bool_t
from . cimport constants
from . cimport fields
from . cimport heapq
cdef class EikonalSolver(object):
cdef str cy_coord_sys
cdef fields.ScalarField3D cy_velocity
cdef fields.ScalarField3D cy_traveltime
cdef heapq.Heap cy_trial
cdef constants.BOOL_t[:,:,:] cy_known
cdef constants.BOOL_t[:,:,:] cy_unknown
cdef constants.REAL_t[:,:,:,:] cy_norm
cdef constants.UINT_t[3] cy_is_periodic
cpdef constants.BOOL_t solve(EikonalSolver self)
cpdef np.ndarray[constants.REAL_t, ndim=2] trace_ray(
EikonalSolver self,
constants.REAL_t[:] end
)
================================================
FILE: pykonal/solver.pyx
================================================
# Cython compiler directives.
# distutils: language=c++
"""
The core module of PyKonal for solving the Eikonal equation.
This module provides the core class (:class:`pykonal.solver.EikonalSolver`),
which gets imported into the root-level namespace and can thus be
instantiated as below:
.. code-block:: python
import pykonal
solver = pykonal.EikonalSolver(coord_sys="cartesian")
An additional convenience class (:class:`pykonal.solver.PointSourceSolver`)
is made available in this module.
"""
import warnings
# Python thrid-party imports.
import numpy as np
# Local imports.
from . import constants
# Cython built-in imports.
cimport cython
from libc.math cimport sqrt, sin
from libcpp.vector cimport vector as cpp_vector
from libc.stdlib cimport malloc, free
# Cython third-party imports.
cimport numpy as np
# Cython local imports.
from . cimport constants
from . cimport fields
from . cimport heapq
cdef class EikonalSolver(object):
"""
The core class of PyKonal for solving the Eikonal equation.
.. code-block:: python
import numpy as np
import pykonal
# Instantiate EikonalSolver object.
solver = pykonal.solver.EikonalSolver(coord_sys="cartesian")
# Initialize EikonalSolver object's velocity attribute.
solver.velocity.min_coords = 0, 0, 0
solver.velocity.node_intervals = 1, 1, 1
solver.velocity.npts = 16, 16, 16
solver.velocity.values = np.ones(solver.velocity.npts)
# Initialize the traveltime field with a source at node with
# index (0, 0, 0).
src_idx = (0, 0, 0)
# Remove source node from *Unknown*
solver.unknown[src_idx] = False
# Add source node to *Trial*.
solver.trial.push(*src_idx)
# Solve the system.
solver.solve()
# Extract the traveltime values.
tt = solver.traveltime.values
"""
def __init__(self, coord_sys="cartesian"):
self.cy_coord_sys = coord_sys
self.cy_velocity = fields.ScalarField3D(coord_sys=self.coord_sys)
@property
def trial(self):
"""
[*Read/Write*, :class:`pykonal.heapq.Heap`] Heap of node
indices in *Trial*.
"""
if self.cy_trial is None:
self.cy_trial = heapq.Heap(self.traveltime.values)
return (self.cy_trial)
@property
def coord_sys(self):
"""
[*Read only*, str] Coordinate system of solver
{"Cartesian", "spherical"}.
"""
return (self.cy_coord_sys)
@property
def known(self):
"""
[*Read/Write*, numpy.ndarray(shape=(N0,N1,N2), dtype=numpy.bool)] 3D array of booleans
indicating whether nodes are in *Known*.
"""
try:
return (np.asarray(self.cy_known))
except AttributeError:
self.cy_known = np.zeros(self.tt.npts, dtype=constants.DTYPE_BOOL)
return (np.asarray(self.cy_known))
@property
def unknown(self):
"""
[*Read/Write*, numpy.ndarray(shape=(N0,N1,N2), dtype=numpy.bool)] 3D array of booleans
indicating whether nodes are in *Unknown*.
"""
try:
return (np.asarray(self.cy_unknown))
except AttributeError:
self.cy_unknown = np.ones(self.tt.npts, dtype=constants.DTYPE_BOOL)
return (np.asarray(self.cy_unknown))
@property
def norm(self):
"""
.. deprecated:: 0.3.2
Use self.velocity.norm or self.traveltime.velocity instead.
[*Read-only*, numpy.ndarray(shape=(N0,N1,N2,3), dtype=numpy.float)] 4D array of scaling
factors for gradient operator.
"""
warning_message = "This attribute is deprecated and will go away in a "\
"future version of PyKonal. Use pykonal.solver.EikonalSolver"\
".traveltime.norm instead."
warnings.warn(warning_message, DeprecationWarning)
try:
return (np.asarray(self.cy_norm))
except AttributeError:
norm = np.tile(
self.traveltime.node_intervals,
np.append(self.traveltime.npts, 1)
)
if self.coord_sys == 'spherical':
norm[..., 1] *= self.traveltime.nodes[..., 0]
norm[..., 2] *= self.traveltime.nodes[..., 0]
norm[..., 2] *= np.sin(self.traveltime.nodes[..., 1])
self.cy_norm = norm
return (np.asarray(self.cy_norm))
@property
def step_size(self):
"""
.. deprecated:: 0.3.2
Use self.velocity.step_size of self.traveltime.step_size instead.
[*Read only*, float] Step size used for ray tracing.
"""
warning_message = "This attribute is deprecated and will go away in a "\
"future version of PyKonal. Use pykonal.solver.EikonalSolver"\
".traveltime.step_size instead."
warnings.warn(warning_message, DeprecationWarning)
return (self.norm[~np.isclose(self.norm, 0)].min() / 4)
@property
def traveltime(self):
"""
[*Read/Write*, :class:`pykonal.fields.ScalarField3D`] 3D array
of traveltime values.
"""
if self.cy_traveltime is None:
self.cy_traveltime = fields.ScalarField3D(coord_sys=self.coord_sys)
self.cy_traveltime.min_coords = self.velocity.min_coords
self.cy_traveltime.node_intervals = self.velocity.node_intervals
self.cy_traveltime.npts = self.velocity.npts
self.cy_traveltime.values = np.full_like(self.velocity.values, fill_value=np.inf)
return (self.cy_traveltime)
@property
def tt(self):
"""
[*Read/Write*, :class:`pykonal.fields.ScalarField3D`] Alias for
self.traveltime.
"""
return (self.traveltime)
@property
def velocity(self):
"""
[*Read/Write*, :class:`pykonal.fields.ScalarField3D`] 3D array
of velocity values.
"""
return (self.cy_velocity)
@property
def vv(self):
"""
[*Read/Write*, :class:`pykonal.fields.ScalarField3D`] Alias for
self.velocity.
"""
return (self.velocity)
@cython.initializedcheck(False)
cpdef constants.BOOL_t solve(EikonalSolver self):
"""
solve(self)
Solve the Eikonal equation using the FMM.
:return: Returns True upon successful execution.
:rtype: bool
"""
cdef Py_ssize_t i, iax, idrxn, iheap
cdef Py_ssize_t[6][3] nbrs
cdef Py_ssize_t[3] nbr, switch, max_idx, active_idx
cdef Py_ssize_t[2] drxns = [-1, 1]
cdef Py_ssize_t[:,:,:] heap_index
cdef (Py_ssize_t, Py_ssize_t, Py_ssize_t) idx
cdef int count_a = 0
cdef int count_b = 0
cdef int inbr
cdef int[2] order
cdef constants.REAL_t a, b, c, bfd, ffd, new
cdef constants.REAL_t[2] fdu
cdef constants.REAL_t[3] aa, bb, cc
cdef constants.REAL_t[:,:,:] tt, vv
cdef constants.REAL_t[:,:,:,:] norm
cdef constants.BOOL_t[3] iax_isperiodic,
cdef constants.BOOL_t[:,:,:] known, unknown
cdef heapq.Heap trial
for iax in range(3):
max_idx[iax] = <Py_ssize_t> self.cy_traveltime.cy_npts[iax]
iax_isperiodic[iax] = <constants.BOOL_t> self.cy_traveltime.cy_iax_isperiodic[iax]
tt = self.traveltime.values
vv = self.velocity.values
norm = self.velocity.norm
known = self.known
unknown = self.unknown
trial = self.trial
heap_index = trial.cy_heap_index
while trial.cy_keys.size() > 0:
# Let Active be the point in Trial with the smallest
# traveltime value.
idx = trial.pop()
active_idx = [idx[0], idx[1], idx[2]]
known[active_idx[0], active_idx[1], active_idx[2]] = True
# Determine the indices of neighbouring nodes.
inbr = 0
for iax in range(3):
switch = [0, 0, 0]
for idrxn in range(2):
switch[iax] = drxns[idrxn]
for jax in range(3):
if iax_isperiodic[jax]:
nbrs[inbr][jax] = (
active_idx[jax]
+ switch[jax]
+ max_idx[jax]
)\
% max_idx[jax]
else:
nbrs[inbr][jax] = active_idx[jax] + switch[jax]
inbr += 1
# Recompute the traveltime values at all Trial neighbours
# of Active by solving the piecewise quadratic equation.
for i in range(6):
nbr = nbrs[i]
if not stencil(nbr[0], nbr[1], nbr[2], max_idx[0], max_idx[1], max_idx[2]) or known[nbr[0], nbr[1], nbr[2]]:
continue
if vv[nbr[0], nbr[1], nbr[2]] > 0:
for iax in range(3):
switch = [0, 0, 0]
idrxn = 0
if norm[nbr[0], nbr[1], nbr[2], iax] == 0:
aa[iax], bb[iax], cc[iax] = 0, 0, 0
continue
for idrxn in range(2):
switch[iax] = drxns[idrxn]
nbr1_i1 = (nbr[0]+switch[0]+max_idx[0]) % max_idx[0]\
if iax_isperiodic[0] else nbr[0]+switch[0]
nbr1_i2 = (nbr[1]+switch[1]+max_idx[1]) % max_idx[1]\
if iax_isperiodic[1] else nbr[1]+switch[1]
nbr1_i3 = (nbr[2]+switch[2]+max_idx[2]) % max_idx[2]\
if iax_isperiodic[2] else nbr[2]+switch[2]
nbr2_i1 = (nbr[0]+2*switch[0]+max_idx[0]) % max_idx[0]\
if iax_isperiodic[0] else nbr[0]+2*switch[0]
nbr2_i2 = (nbr[1]+2*switch[1]+max_idx[1]) % max_idx[1]\
if iax_isperiodic[1] else nbr[1]+2*switch[1]
nbr2_i3 = (nbr[2]+2*switch[2]+max_idx[2]) % max_idx[2]\
if iax_isperiodic[2] else nbr[2]+2*switch[2]
if (
(
drxns[idrxn] == -1
and (nbr[iax] > 1 or iax_isperiodic[iax])
)
or
(
drxns[idrxn] == 1
and (nbr[iax] < max_idx[iax] - 2 or iax_isperiodic[iax])
)
)\
and known[nbr2_i1, nbr2_i2, nbr2_i3]\
and known[nbr1_i1, nbr1_i2, nbr1_i3]\
and tt[nbr2_i1, nbr2_i2, nbr2_i3] \
<= tt[nbr1_i1, nbr1_i2, nbr1_i3]\
:
order[idrxn] = 2
fdu[idrxn] = drxns[idrxn] * (
- 3 * tt[nbr[0], nbr[1], nbr[2]]
+ 4 * tt[nbr1_i1, nbr1_i2, nbr1_i3]
- tt[nbr2_i1, nbr2_i2, nbr2_i3]
) / (2 * norm[nbr[0], nbr[1], nbr[2], iax])
elif (
(
drxns[idrxn] == -1
and (nbr[iax] > 0 or iax_isperiodic[iax])
)
or (
drxns[idrxn] == 1
and (nbr[iax] < max_idx[iax] - 1 or iax_isperiodic[iax])
)
)\
and known[nbr1_i1, nbr1_i2, nbr1_i3]\
:
order[idrxn] = 1
fdu[idrxn] = drxns[idrxn] * (
tt[nbr1_i1, nbr1_i2, nbr1_i3]
- tt[nbr[0], nbr[1], nbr[2]]
) / norm[nbr[0], nbr[1], nbr[2], iax]
else:
order[idrxn], fdu[idrxn] = 0, 0
if fdu[0] > -fdu[1]:
# Do the update using the backward operator
idrxn, switch[iax] = 0, -1
else:
# Do the update using the forward operator
idrxn, switch[iax] = 1, 1
nbr1_i1 = (nbr[0]+switch[0]+max_idx[0]) % max_idx[0]\
if iax_isperiodic[0] else nbr[0]+switch[0]
nbr1_i2 = (nbr[1]+switch[1]+max_idx[1]) % max_idx[1]\
if iax_isperiodic[1] else nbr[1]+switch[1]
nbr1_i3 = (nbr[2]+switch[2]+max_idx[2]) % max_idx[2]\
if iax_isperiodic[2] else nbr[2]+switch[2]
nbr2_i1 = (nbr[0]+2*switch[0]+max_idx[0]) % max_idx[0]\
if iax_isperiodic[0] else nbr[0]+2*switch[0]
nbr2_i2 = (nbr[1]+2*switch[1]+max_idx[1]) % max_idx[1]\
if iax_isperiodic[1] else nbr[1]+2*switch[1]
nbr2_i3 = (nbr[2]+2*switch[2]+max_idx[2]) % max_idx[2]\
if iax_isperiodic[2] else nbr[2]+2*switch[2]
if order[idrxn] == 2:
aa[iax] = 9 / (4*norm[nbr[0], nbr[1], nbr[2], iax] ** 2)
bb[iax] = (
6 * tt[nbr2_i1, nbr2_i2, nbr2_i3]
- 24 * tt[nbr1_i1, nbr1_i2, nbr1_i3]
) / (4 * norm[nbr[0], nbr[1], nbr[2], iax]**2)
cc[iax] = (
tt[nbr2_i1, nbr2_i2, nbr2_i3]**2
- 8 * tt[nbr2_i1, nbr2_i2, nbr2_i3]
* tt[nbr1_i1, nbr1_i2, nbr1_i3]
+ 16 * tt[nbr1_i1, nbr1_i2, nbr1_i3]**2
) / (4 * norm[nbr[0], nbr[1], nbr[2], iax]**2)
elif order[idrxn] == 1:
aa[iax] = 1 / norm[nbr[0], nbr[1], nbr[2], iax]**2
bb[iax] = -2 * tt[nbr1_i1, nbr1_i2, nbr1_i3]\
/ norm[nbr[0], nbr[1], nbr[2], iax] ** 2
cc[iax] = tt[nbr1_i1, nbr1_i2, nbr1_i3]**2\
/ norm[nbr[0], nbr[1], nbr[2], iax]**2
elif order[idrxn] == 0:
aa[iax], bb[iax], cc[iax] = 0, 0, 0
a = aa[0] + aa[1] + aa[2]
if a == 0:
count_a += 1
continue
b = bb[0] + bb[1] + bb[2]
c = cc[0] + cc[1] + cc[2] - 1/vv[nbr[0], nbr[1], nbr[2]]**2
if b**2 < 4*a*c:
# This is a hack to solve the quadratic equation
# when the discrimnant is negative. This hack
# simply sets the discriminant to zero.
new = -b / (2*a)
count_b += 1
else:
new = (-b + sqrt(b**2 - 4*a*c)) / (2*a)
if new < tt[nbr[0], nbr[1], nbr[2]]:
tt[nbr[0], nbr[1], nbr[2]] = new
# Tag as Trial all neighbours of Active that are not
# Alive. If the neighbour is in Far, remove it from
# that list and add it to Trial.
if unknown[nbr[0], nbr[1], nbr[2]]:
trial.push(nbr[0], nbr[1], nbr[2])
unknown[nbr[0], nbr[1], nbr[2]] = False
else:
trial.sift_down(0, heap_index[nbr[0], nbr[1], nbr[2]])
return (True)
cpdef np.ndarray[constants.REAL_t, ndim=2] trace_ray(
EikonalSolver self,
constants.REAL_t[:] end
):
"""
trace_ray(self, end)
An alias to self.traveltime.trace_ray().
"""
return (self.traveltime.trace_ray(end))
class PointSourceSolver(EikonalSolver):
"""
A convenience class to improve precision
gitextract_79682ixy/
├── .gitignore
├── LICENSE
├── MANIFEST.in
├── README.md
├── jupyter/
│ ├── Locator2.ipynb
│ ├── figure_3.ipynb
│ ├── figure_4.ipynb
│ ├── figure_5.ipynb
│ ├── figure_6.ipynb
│ ├── figure_7.ipynb
│ └── figure_8.ipynb
├── pykonal/
│ ├── __init__.py
│ ├── __version__.py
│ ├── constants.pxd
│ ├── constants.pyx
│ ├── data/
│ │ ├── ak135.npz
│ │ ├── marmousi2/
│ │ │ ├── LICENSE
│ │ │ ├── README
│ │ │ └── marmousi2.npz
│ │ └── mitp2008.npz
│ ├── fields.pxd
│ ├── fields.pyx
│ ├── heapq.pxd
│ ├── heapq.pyx
│ ├── inventory.py
│ ├── locate.pxd
│ ├── locate.pyx
│ ├── solver.pxd
│ ├── solver.pyx
│ ├── stats.pxd
│ ├── stats.pyx
│ ├── tests/
│ │ ├── data/
│ │ │ └── test_EikonalSolver_uniform_velocity_cartesian.npz
│ │ ├── test_EikonalSolver.py
│ │ ├── test_GridND.py
│ │ └── test_LinearInterpolator3D.py
│ └── transformations.py
├── pyproject.toml
├── scripts/
│ ├── eq_loc/
│ │ ├── eq_loc.cfg
│ │ └── eq_loc.py
│ └── mcmc/
│ ├── 315_loc.cfg
│ └── 315_locate_serial_mcmc.py
├── setup.py
└── tutorials/
├── tomography/
│ ├── cartesian_tomography_2D.ipynb
│ └── vmodel.txt
└── tracing_PKiKP/
├── .ipynb_checkpoints/
│ └── tracing_PKiKP_rays-checkpoint.ipynb
├── IASP91.csv
└── tracing_PKiKP_rays.ipynb
SYMBOL INDEX (76 symbols across 7 files)
FILE: pykonal/inventory.py
class TraveltimeInventory (line 8) | class TraveltimeInventory(object):
method __init__ (line 10) | def __init__(self, path, mode="r"):
method __del__ (line 15) | def __del__(self):
method __enter__ (line 18) | def __enter__(self):
method __exit__ (line 21) | def __exit__(self, exc_type, exc_value, exc_traceback):
method f5 (line 25) | def f5(self):
method mode (line 29) | def mode(self):
method mode (line 33) | def mode(self, value):
method path (line 39) | def path(self):
method add (line 43) | def add(self, field, key):
method merge (line 55) | def merge(self, paths):
method read (line 68) | def read(self, key, min_coords=None, max_coords=None):
FILE: pykonal/tests/test_EikonalSolver.py
class EikonalSolverTestCase (line 10) | class EikonalSolverTestCase(unittest.TestCase):
method setUp (line 11) | def setUp(self):
method tearDown (line 15) | def tearDown(self):
method test_uniform_velocity_cartesian (line 19) | def test_uniform_velocity_cartesian(self):
FILE: pykonal/tests/test_GridND.py
function random_grid (line 7) | def random_grid():
class GridNDTestCase (line 17) | class GridNDTestCase(unittest.TestCase):
method setUp (line 20) | def setUp(self):
method tearDown (line 27) | def tearDown(self):
method test_iax_null (line 31) | def test_iax_null(self):
method test_mesh (line 37) | def test_mesh(self):
method test_min_coords (line 51) | def test_min_coords(self):
method test_max_coords (line 57) | def test_max_coords(self):
method test_node_intervals (line 66) | def test_node_intervals(self):
method test_npts (line 71) | def test_npts(self):
FILE: pykonal/tests/test_LinearInterpolator3D.py
function random_grid (line 7) | def random_grid():
class LinearInterpolator3DTestCase (line 23) | class LinearInterpolator3DTestCase(unittest.TestCase):
method setUp (line 26) | def setUp(self):
method tearDown (line 30) | def tearDown(self):
method test_interpolate_2D (line 34) | def test_interpolate_2D(self):
method test_interpolate (line 44) | def test_interpolate(self):
method test_interpolate_OutOfBoundsError (line 59) | def test_interpolate_OutOfBoundsError(self):
method test_interpolate_error_float (line 74) | def test_interpolate_error_float(self):
method test_interpolate_edge_case_lower (line 94) | def test_interpolate_edge_case_lower(self):
method test_interpolate_edge_case_upper (line 103) | def test_interpolate_edge_case_upper(self):
method test_periodic (line 111) | def test_periodic(self):
FILE: pykonal/transformations.py
function geo2sph (line 17) | def geo2sph(nodes):
function sph2sph (line 29) | def sph2sph(nodes, origin=(0,0,0), force_phi_positive=False):
function xyz2sph (line 65) | def xyz2sph(nodes, origin=(0,0,0), force_phi_positive=False):
function sph2geo (line 90) | def sph2geo(nodes):
function sph2xyz (line 102) | def sph2xyz(nodes, origin=(0,0,0)):
function xyz2xyz (line 130) | def xyz2xyz(nodes, origin=(0,0,0)):
function rotation_matrix (line 146) | def rotation_matrix(alpha, beta, gamma):
FILE: scripts/eq_loc/eq_loc.py
function parse_args (line 36) | def parse_args():
function parse_cfg (line 81) | def parse_cfg(configuration_file):
function main (line 136) | def main(argc, cfg):
function configure_logging (line 163) | def configure_logging(verbose, logfile):
function log_errors (line 200) | def log_errors(func):
function signal_handler (line 218) | def signal_handler(sig, frame):
function event_location_loop (line 227) | def event_location_loop(argc, cfg):
function id_distribution_loop (line 297) | def id_distribution_loop(argc, cfg):
function load_arrivals (line 318) | def load_arrivals(input_file):
function load_stations (line 335) | def load_stations(input_file):
function arrival_dict (line 362) | def arrival_dict(dataframe, event_id):
function station_dict (line 385) | def station_dict(dataframe):
function write_events (line 413) | def write_events(dataframe, output_file):
FILE: scripts/mcmc/315_locate_serial_mcmc.py
function parse_args (line 64) | def parse_args():
function parse_cfg (line 145) | def parse_cfg(configuration_file):
function main (line 197) | def main(argc, cfg):
class VoigtProfile (line 228) | class VoigtProfile(object):
method __init__ (line 229) | def __init__(self, mu=0, sigma=1, gamma=1):
method logpdf (line 234) | def logpdf(self, x):
function configure_logging (line 238) | def configure_logging(verbose, logfile):
function log_errors (line 274) | def log_errors(func):
function log_probability (line 291) | def log_probability(args):
function locate_events (line 306) | def locate_events(catalog, stations, pick_errors, argc, cfg):
function load_catalog (line 415) | def load_catalog(input_file, starttime=None, endtime=None):
function _load_catalog_hdf5 (line 447) | def _load_catalog_hdf5(input_file):
function load_pick_errors (line 458) | def load_pick_errors(input_file):
function load_stations (line 469) | def load_stations(input_file):
function _load_stations_hdf5 (line 491) | def _load_stations_hdf5(input_file):
function _load_stations_txt (line 504) | def _load_stations_txt(input_file):
function arrival_dict (line 514) | def arrival_dict(dataframe, event_id):
function station_dict (line 537) | def station_dict(dataframe):
function write_events (line 565) | def write_events(dataframe, output_file):
Condensed preview — 47 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,833K chars).
[
{
"path": ".gitignore",
"chars": 127,
"preview": "*.DS_Store\njupyter/.ipynb_checkpoints\nscripts/eq_loc/test_data\n*.log\n*.cpp\n*.c\nbuild\ndist\npykonal.egg-info\npykonal/__pyc"
},
{
"path": "LICENSE",
"chars": 35141,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "MANIFEST.in",
"chars": 105,
"preview": "include pykonal/*.pyx\ninclude pykonal/*.pxd\ninclude pykonal/*.cpp\ninclude pykonal/data\ninclude README.md\n"
},
{
"path": "README.md",
"chars": 1943,
"preview": "\n\n![]"
},
{
"path": "jupyter/Locator2.ipynb",
"chars": 22356,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": "
},
{
"path": "jupyter/figure_3.ipynb",
"chars": 6085,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Figure 3\\n\",\n \"Compatible with"
},
{
"path": "jupyter/figure_4.ipynb",
"chars": 6088,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Figure 4\\n\",\n \"Compatible with"
},
{
"path": "jupyter/figure_5.ipynb",
"chars": 6858,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Figure 5\\n\",\n \"Compatible with"
},
{
"path": "jupyter/figure_6.ipynb",
"chars": 11410,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Figure 6\\n\",\n \"Compatible with"
},
{
"path": "jupyter/figure_7.ipynb",
"chars": 8833,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Figure 7\\n\",\n \"Compatible with"
},
{
"path": "jupyter/figure_8.ipynb",
"chars": 4390,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Figure 8\\n\",\n \"Compatible with"
},
{
"path": "pykonal/__init__.py",
"chars": 333,
"preview": "from .__version__ import (\n __major_version__,\n __minor_version__,\n __patch__,\n __release__,\n __version_t"
},
{
"path": "pykonal/__version__.py",
"chars": 295,
"preview": "__major_version__ = 0\n__minor_version__ = 4\n__patch__ = 1\n__release__ = ''\n__version_tuple__ = (\n _"
},
{
"path": "pykonal/constants.pxd",
"chars": 111,
"preview": "cimport numpy as np\n\nctypedef np.float64_t REAL_t\nctypedef np.uint16_t UINT_t\nctypedef np.npy_bool BOOL_t\n"
},
{
"path": "pykonal/constants.pyx",
"chars": 166,
"preview": "\"\"\"\nPackage-level constants.\n\"\"\"\nimport numpy as np\n\nDTYPE_REAL = np.float64\nDTYPE_UINT = np.uint32\nDTYPE_INT = np.int3"
},
{
"path": "pykonal/data/marmousi2/LICENSE",
"chars": 19046,
"preview": "Attribution 4.0 International\r\n\r\n=======================================================================\r\n\r\nCreative Com"
},
{
"path": "pykonal/data/marmousi2/README",
"chars": 3396,
"preview": "AGL Elastic Marmousi\r\n\r\n\r\n# Statement\r\n\r\nThe AGL Elastic Marmousi model was created at the University of Houston,\r\nand w"
},
{
"path": "pykonal/fields.pxd",
"chars": 1703,
"preview": "cimport numpy as np\n\nfrom . cimport constants\n\n\ncdef class Field3D(object):\n cdef str cy_coord_"
},
{
"path": "pykonal/fields.pyx",
"chars": 30683,
"preview": "# distutils: language=c++\n\"\"\"\nThis module provides three classes (:class:`Field3D <pykonal.fields.Field3D>`,\n:class:`Sca"
},
{
"path": "pykonal/heapq.pxd",
"chars": 604,
"preview": "# distutils: language=c++\n\nfrom libcpp.vector cimport vector as cpp_vector\nfrom . cimport constants\n\ncdef struct Index3D"
},
{
"path": "pykonal/heapq.pyx",
"chars": 6830,
"preview": "\"\"\"\nA module providing heap-sort functionality.\n\nThis module provides a single class (:class:`pykonal.heapq.Heap`) which"
},
{
"path": "pykonal/inventory.py",
"chars": 3356,
"preview": "import h5py\nimport numpy as np\nimport os\n\nfrom . import fields\n\n\nclass TraveltimeInventory(object):\n\n def __init__(se"
},
{
"path": "pykonal/locate.pxd",
"chars": 1413,
"preview": "cimport numpy as np\n\nfrom . cimport constants\nfrom . cimport fields\n\n\ncdef class EQLocator(object):\n cdef str "
},
{
"path": "pykonal/locate.pyx",
"chars": 7310,
"preview": "# Cython compiler directives.\n# distutils: language=c++\n# cython: profile=True\n\n\nimport numpy as np\nimport os\nimport pyk"
},
{
"path": "pykonal/solver.pxd",
"chars": 717,
"preview": "cimport numpy as np\n\nfrom libcpp cimport bool as bool_t\n\nfrom . cimport constants\nfrom . cimport fields\nfrom . cimport h"
},
{
"path": "pykonal/solver.pyx",
"chars": 26709,
"preview": "# Cython compiler directives.\n# distutils: language=c++\n\n\"\"\"\nThe core module of PyKonal for solving the Eikonal equation"
},
{
"path": "pykonal/stats.pxd",
"chars": 217,
"preview": "from . cimport constants\n\n\ncdef class NormalDistribution(object):\n cdef constants.REAL_t cy_mu\n cdef constants.REA"
},
{
"path": "pykonal/stats.pyx",
"chars": 608,
"preview": "cimport numpy as np\n\nfrom . cimport constants\n\nfrom libc.math cimport log, pi, sqrt\n\ncdef class NormalDistribution(objec"
},
{
"path": "pykonal/tests/test_EikonalSolver.py",
"chars": 1252,
"preview": "import nose\nimport numpy as np\nimport os\nimport pkg_resources\nimport pykonal\nimport unittest\n\n\n\nclass EikonalSolverTestC"
},
{
"path": "pykonal/tests/test_GridND.py",
"chars": 2167,
"preview": "import nose\nimport numpy as np\nimport pykonal\nimport unittest\n\n\ndef random_grid():\n grid = pykonal.Gr"
},
{
"path": "pykonal/tests/test_LinearInterpolator3D.py",
"chars": 4093,
"preview": "import nose\nimport numpy as np\nimport pykonal\nimport unittest\n\n\ndef random_grid():\n grid = pykonal.Gr"
},
{
"path": "pykonal/transformations.py",
"chars": 6536,
"preview": "\"\"\"\nA module to facilitate coordinate-system transformations.\n\n.. autofunction:: geo2sph(nodes)\n.. autofunction:: sph2sp"
},
{
"path": "pyproject.toml",
"chars": 895,
"preview": "[build-system]\nrequires = ['setuptools==68.2.2', 'wheel', 'Cython>=0.29.14', 'numpy']\nbuild-backend = 'setuptools.build_"
},
{
"path": "scripts/eq_loc/eq_loc.cfg",
"chars": 414,
"preview": "[DEFAULT]\ntraveltime_directory = /home/malcolmw/src/pykonal/scripts/eq_loc/test_data/traveltimes\noverwrite_traveltimes "
},
{
"path": "scripts/eq_loc/eq_loc.py",
"chars": 12032,
"preview": "\"\"\"\nAn MPI script to locate earthquakes.\n\n.. author: Malcolm C. A. White\n\"\"\"\n\nimport argparse\nimport configparser\nimport"
},
{
"path": "scripts/mcmc/315_loc.cfg",
"chars": 204,
"preview": "[DEFAULT]\nmu_P = 0.031\nsigma_P = 0.195\nmu_S = 0.079\nsigma_S = 0.291\nconfidence"
},
{
"path": "scripts/mcmc/315_locate_serial_mcmc.py",
"chars": 15690,
"preview": "\"\"\"\nAn MPI script to locate earthquakes.\n\n.. author: Malcolm C. A. White\n\"\"\"\n\nimport argparse\nimport configparser\nimport"
},
{
"path": "setup.py",
"chars": 2798,
"preview": "\"\"\"\nsetup.py adapted from https://github.com/kennethreitz/setup.py\n\"\"\"\nimport io\nimport numpy as np\nimport os\n#from dist"
},
{
"path": "tutorials/tomography/cartesian_tomography_2D.ipynb",
"chars": 1526811,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": 1,\n \"id\": \"11651601-56f2-4015-9984-3a64deb1d0b3\",\n \""
},
{
"path": "tutorials/tomography/vmodel.txt",
"chars": 4151,
"preview": "depth,vs\n0,1334.69487742103\n2,1334.69487742103\n4,1334.69487742103\n6,1334.69487742103\n8,1334.69487742103\n10,1334.69487742"
},
{
"path": "tutorials/tracing_PKiKP/.ipynb_checkpoints/tracing_PKiKP_rays-checkpoint.ipynb",
"chars": 10578,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Teleseismic ray tracing: PKiKP\\n\""
},
{
"path": "tutorials/tracing_PKiKP/IASP91.csv",
"chars": 4421,
"preview": "0.00,6371.00,5.8000,3.3600\n1.00,6370.00,5.8000,3.3600\n2.00,6369.00,5.8000,3.3600\n3.00,6368.00,5.8000,3.3600\n4.00,6367.00"
},
{
"path": "tutorials/tracing_PKiKP/tracing_PKiKP_rays.ipynb",
"chars": 10578,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Teleseismic ray tracing: PKiKP\\n\""
}
]
// ... and 4 more files (download for full content)
About this extraction
This page contains the full source code of the malcolmw/pykonal GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 47 files (38.1 MB), approximately 1.1M tokens, and a symbol index with 76 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.