├── License.md
├── README.md
├── dirspec.py
├── infospec.py
├── interpspec.py
├── plotspec.py
├── private
├── EMEP.py
├── IMLM.py
├── check_data.py
├── diwasp_csd.py
├── elev.py
├── hsig.py
├── pres.py
├── smoothspec.py
├── spectobasis.py
├── velx.py
├── vely.py
└── wavenumber.py
└── writespec.py
/License.md:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # pyDiwasp
2 | conversion of diwasp package (DIWASP: DIrectional WAve SPectrum analysis Version 1.4) for python
3 | converted from https://github.com/metocean/diwasp
4 |
5 | I would LOVE help making this into better package of the original diwasp tool. Please check issues for needed functionality adds.
6 |
7 | ## Toolbox contents:
8 | ### Main functions:
9 | - dirspec.m Main function for directional wave analysis
10 | - readspec.m Reads in DIWASP format spectrum files
11 | - writespec.m Writes DIWASP format spectrum files
12 | - plotspec.m Plots DIWASP spectrums
13 | - testspec.m Testing function for the estimation methods
14 | - makespec.m Makes a fake spectrum and generates fake data for testing dirspec.m
15 | - infospec.m Returns information about a directional spectrum
16 | - data_structures.m is a help file describing the new Version 1.1 data structures
17 |
18 | ## Private functions (some can be used as stand alone functions):
19 | ### The transfer functions
20 | - /private/elev.m
21 | - /private/pres.m
22 | - /private/velx.m
23 | - /private/vely.m
24 | - /private/velz.m
25 | - /private/slpx.m
26 | - /private/slpy.m
27 | - /private/vels.m
28 | - /private/accs.m
29 |
30 | ### The estimation functions
31 | - /private/DFTM.m
32 | - /private/EMLM.m
33 | - /private/IMLM.m
34 | - /private/EMEP.m
35 | - /private/BDM.m
36 |
37 | ### Miscellaneous functions
38 | - /private/smoothspec.m
39 | - /private/wavenumber.m
40 | - /private/makerandomsea.m
41 | - /private/makewavedata.m
42 | - /private/Hsig.m
43 | - /private/gsamp.m
44 | - /private/check_data.m
45 |
46 |
47 | carying original license agreement and copyright
48 |
49 | ## License agreement
50 | DIWASP, is free software; you can redistribute it and/or modify it under the terms of the
51 | GNU General Public License as published by the Free Software Foundation.
52 | However, the DIWASP license includes the following addendum concerning its usage:
53 | This software and any derivatives of it shall only be used for educational purposes or
54 | scientific research without the intention of any financial gain.
55 | Use of this software or derivatives for any purpose that results in financial gain
56 | for a person or organization without written consent from the author is a breach of the license agreement.
57 | This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
58 | without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
59 | In addition the author is not liable in any way for consequences arising from the application of
60 | software output for any design or decision-making process.
61 | The GNU General Public License forms the main part of the license agreement included in the package.
62 |
63 | Copyright (C) 2002 David Johnson Coastal Oceanography Group, CWR, UWA, Perth
64 |
65 |
--------------------------------------------------------------------------------
/dirspec.py:
--------------------------------------------------------------------------------
1 | import warnings
2 | import numpy as np
3 | import matplotlib.pyplot as plt
4 | from scipy.signal import detrend
5 | from interpspec import interpspec
6 | from infospec import infospec
7 | from writespec import writespec
8 | from plotspec import plotspec
9 | from private.velx import velx
10 | from private.vely import vely
11 | from private.pres import pres
12 | from private.elev import elev
13 | from private.wavenumber import wavenumber
14 | from private.IMLM import IMLM
15 | from private.EMEP import EMEP
16 | from private.smoothspec import smoothspec
17 | from private.diwasp_csd import diwasp_csd
18 | from private.check_data import check_data
19 |
20 | def dirspec(ID, SM, EP, Options_=None):
21 | """
22 | DIWASP V1.4 function
23 | dirspec: main spectral estimation routine
24 |
25 | [SMout,EPout]=dirspec(ID,SM,EP,{options})
26 |
27 | Outputs:
28 | SMout A spectral matrix structure containing the results
29 | Epout The estimation parameters structure with the values actually used for the computation including any default settings.
30 |
31 | Inputs:
32 | ID An instrument data structure containing the measured data
33 | SM A spectral matrix structure; data in field SM.S is ignored.
34 | EP The estimation parameters structure. For default values enter EP as []
35 | [options] options entered as cell array with parameter/value pairs: e.g.{'MESSAGE',1,'PLOTTYPE',2};
36 | Available options with default values:
37 | 'MESSAGE',1, Level of screen display: 0,1,2 (increasing output)
38 | 'PLOTTYPE',1, Plot type: 0 none, 1 3d surface, 2 polar type plot, 3 3d surface(compass angles), 4 polar plot(compass angles)
39 | 'FILEOUT','' Filename for output file: empty string means no file output
40 |
41 | Input structures ID and SM are required. Either [EP] or [options] can be included but must be in order if both are included.
42 | "help data_structures" for information on the DIWASP data structures
43 |
44 | All of the implemented calculation algorithms are as described by:
45 | Hashimoto,N. 1997 "Analysis of the directional wave spectrum from field data"
46 | In: Advances in Coastal Engineering Vol.3. Ed:Liu,P.L-F. Pub:World Scientific,Singapore
47 |
48 |
49 | Original copyright (C) 2002 Coastal Oceanography Group, CWR, UWA, Perth
50 |
51 | Translated by Chuan Li and Spicer Bak,
52 | Field Research Facility, US Army Corps of Engineers
53 | """
54 |
55 | Options = {'MESSAGE':1, 'PLOTTYPE':1, 'FILEOUT':''}
56 |
57 | if Options_ is not None:
58 | nopts = len(Options_)
59 | else:
60 | nopts = 0
61 |
62 | ID = check_data(ID, 1)
63 | if len(ID) == 0:
64 | return [], []
65 | SM = check_data(SM, 2)
66 | if len(SM) == 0:
67 | return [], []
68 | EP = check_data(EP, 3)
69 | if len(EP) == 0:
70 | return [], []
71 |
72 | if nopts != 0:
73 | if nopts % 2 != 0:
74 | warnings.warn('Options must be in Name/Value pairs - setting to '
75 | 'defaults')
76 | else:
77 | for i in range(int(nopts / 2)):
78 | arg = Options_[2 * i + 1]
79 | field = Options_[2 * i]
80 | Options[field] = arg
81 |
82 | ptype = Options['PLOTTYPE']
83 | displ = Options['MESSAGE']
84 |
85 |
86 | print('\ncalculating.....\n\ncross power spectra')
87 |
88 | data = detrend(ID['data'], axis=0)
89 | ndat, szd = np.shape(ID['data'])
90 |
91 | #get resolution of FFT - if not specified, calculate a sensible value
92 | if 'nfft' not in EP:
93 | nfft = int(2 ** (8 + np.round(np.log2(ID['fs']))))
94 | EP['nfft'] = nfft
95 | else:
96 | nfft = int(EP['nfft'])
97 | if nfft > ndat:
98 | raise Exception('Data length of {} too small'.format(ndat))
99 |
100 | #calculate the cross-power spectra
101 | xps = np.empty((szd, szd, int(nfft / 2)), 'complex128')
102 | for m in range(szd):
103 | for n in range(szd):
104 | xpstmp, Ftmp = diwasp_csd(data[:, m], data[:, n],
105 | nfft, ID['fs'], flag=2)
106 | xps[m, n, :] = xpstmp[1:int(nfft / 2) + 1]
107 | F = Ftmp[1:int(nfft / 2) + 1]
108 | nf = int(nfft / 2)
109 | print('wavenumbers')
110 | wns = wavenumber(2 * np.pi * F, ID['depth'] * np.ones(np.shape(F)))
111 | pidirs = np.linspace(-np.pi, np.pi - 2 * np.pi / EP['dres'],
112 | num=EP['dres'])
113 |
114 | #calculate transfer parameters
115 | print('transfer parameters\n')
116 | trm = np.empty((szd, nf, len(pidirs)))
117 | kx = np.empty((szd, szd, nf, len(pidirs)))
118 | for m in range(szd):
119 | trm[m, :, :] = eval(ID['datatypes'][m])(2 * np.pi * F, pidirs, wns,
120 | ID['layout'][2, m], ID['depth'])
121 | for n in range(szd):
122 | kx[m, n, :, :] = wns[:, np.newaxis] * ((ID['layout'][0, n] -
123 | ID['layout'][0, m]) * np.cos(pidirs) + (ID['layout'][1, n] -
124 | ID['layout'][1, m]) * np.sin(pidirs))
125 |
126 | Ss = np.empty((szd, nf), dtype='complex128')
127 | for m in range(szd):
128 | tfn = trm[m, :, :]
129 | Sxps = xps[m, m, :]
130 | Ss[m, :] = Sxps / (np.max(tfn, axis=1) * np.conj(np.max(tfn, axis=1)))
131 |
132 | ffs = np.logical_and(F >= np.min(SM['freqs']), F <= np.max(SM['freqs']))
133 | SM1 = dict()
134 | SM1['freqs'] = F[ffs]
135 | SM1['funit'] = 'Hz'
136 | SM1['dirs'] = pidirs
137 | SM1['dunit'] = 'rad'
138 |
139 | # call appropriate estimation function
140 | print('directional spectra using {} method'.format(EP['method']))
141 | SM1['S'] = eval(EP['method'])(xps[:, :, ffs], trm[:, ffs, :],
142 | kx[:, :, ffs, :], Ss[:, ffs], pidirs, EP['iter'], displ)
143 | SM1['S'][np.logical_or(np.isnan(SM1['S']), SM1['S'] < 0)] = 0
144 |
145 | #Interpolate onto user specified matrix
146 | print('\ninterpolating onto specified matrix...\n')
147 | SMout = interpspec(SM1, SM, method='linear')
148 |
149 | #smooth spectrum
150 | if EP['smooth'].upper() == 'ON':
151 | print('\nsmoothing spectrum...\n')
152 | SMout = smoothspec(SMout, [[1, 0.5, 0.25], [1, 0.5, 0.25]])
153 |
154 | infospec(SMout)
155 |
156 | #write out spectrum matrix in DIWASP format
157 | filename = Options['FILEOUT']
158 | if len(filename) > 0:
159 | print('writing out spectrum matrix to file')
160 | writespec(SMout,filename)
161 |
162 | #plot spectrum
163 | if ptype > 0:
164 | print('finished...plotting spectrum')
165 | plotspec(SMout, ptype)
166 | T = 'Directional spectrum estimate using {} method'.format(EP['method'])
167 | plt.title(T)
168 | plt.show()
169 |
170 | return SMout, EP
171 |
--------------------------------------------------------------------------------
/infospec.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from private.hsig import hsig
3 |
4 | def infospec(SM):
5 | """
6 | DIWASP V1.4 function
7 | infospec: calculates and displays information about a directional spectrum
8 |
9 | [Hsig,Tp,DTp,Dp]=infospec(SM)
10 |
11 | Outputs:
12 | Hsig Signficant wave height
13 | Tp Peak period
14 | DTp Direction of spectral peak
15 | Dp Dominant direction
16 |
17 | Inputs:
18 | SM A spectral matrix structure containing the file data
19 |
20 | Hsig is the significant wave height. Tp is the peak frequency, the highest point in the one dimensional spectrum.
21 | DTp is the main direction of the peak period (i.e the highest point in the two-dimensional directional spectrum).
22 | Dp is the dominant direction defined as the direction with the highest energy integrated over all frequencies.
23 |
24 | "help data_structures" for information on the DIWASP data structures
25 |
26 | Copyright (C) 2002 Coastal Oceanography Group, CWR, UWA, Perth
27 | """
28 |
29 | H = hsig(SM)
30 |
31 | S = np.sum(np.real(SM['S']), 1)
32 |
33 | I = np.argmax(S)
34 | Tp = 1 / (SM['freqs'][I])
35 | I = np.argmax(np.real(SM['S'][I, :]))
36 | DTp = SM['dirs'][I]
37 | I = np.argmax(np.real(np.sum(SM['S'], 0)))
38 | Dp = SM['dirs'][I]
39 |
40 | print('Infospec::')
41 | print('Significant wave height: {}'.format(H))
42 | print('Peak period: {}'.format(Tp))
43 | print('Direction of peak period: {} axis angle / {} '
44 | 'compass bearing'.format(DTp, compangle(DTp, SM['xaxisdir'])))
45 | print('Dominant direction: {} axis angle / {} '
46 | 'compass bearing'.format(Dp, compangle(Dp, SM['xaxisdir'])))
47 |
48 | return H, Tp, DTp, Dp
49 |
50 | def compangle(dirs, xaxisdir):
51 | return (180 + xaxisdir * np.ones(np.shape(dirs)) - dirs) % 360
52 |
--------------------------------------------------------------------------------
/interpspec.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from warnings import warn
3 | from scipy.interpolate import griddata
4 | from private.hsig import hsig
5 | from private.spectobasis import spectobasis
6 |
7 | def interpspec(SMin, SMout, method='linear'):
8 | """
9 | DIWASP V1.4 function
10 | interpspec: interpolates between spectral matrix bases
11 |
12 | SMout=interpspec(SMin,SMout)
13 |
14 | Outputs:
15 | SMout Output spectral matrix structure with interpolated power density
16 |
17 | Inputs:
18 | SMin A spectral matrix structure containing the original spectra
19 | SMout A spectral matrix defining the new spectral matrix
20 |
21 | SMout only needs to have the frequency and directional axes defined -
22 | spectral density ignored
23 |
24 | "help data_structures" for information on the DIWASP data structures
25 | """
26 | Hs1 = hsig(SMin)
27 |
28 | SMin, facin = spectobasis(SMin)
29 | SMtmp, facout = spectobasis(SMout)
30 |
31 | s1 = SMin['freqs'][:, np.newaxis] * np.sin(SMin['dirs'])
32 | c1 = SMin['freqs'][:, np.newaxis] * np.cos(SMin['dirs'])
33 | s2 = SMtmp['freqs'][:, np.newaxis] * np.sin(SMtmp['dirs'])
34 | c2 = SMtmp['freqs'][:, np.newaxis] * np.cos(SMtmp['dirs'])
35 |
36 | if np.array_equal(s1, s2) and np.array_equal(c1, c2):
37 | warn('No interpolation required, skipping')
38 | Stmp = SMin['S']
39 | else:
40 | Stmp = griddata((s1.flatten(), c1.flatten()), SMin['S'].flatten(),
41 | (s2.flatten(), c2.flatten()), method=method).reshape(s2.shape)
42 |
43 | Stmp[np.isnan(Stmp)] = 0
44 | SMout['S'] = Stmp / facout
45 |
46 | # check Hsig of mapped spectrum and check sufficiently close to original
47 | Hs2 = hsig(SMout)
48 | if (Hs2 - Hs1) / Hs1 > 0.02:
49 | warn('User defined grid may be too coarse; try increasing' +
50 | ' resolution of ''SM[\'freqs\']'' or ''SM[\'dirs\']''')
51 |
52 | return SMout
--------------------------------------------------------------------------------
/plotspec.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 | import numpy as np
3 | from private.spectobasis import spectobasis
4 |
5 | def plotspec(SM, ptype):
6 | """
7 | DIWASP V1.4 function
8 | plotspec: plots the spectral matrix in 3D or polar form
9 |
10 | plotspec(SM,ptype)
11 |
12 | Inputs:
13 | SM A spectral matrix structure
14 | ptype plot type:
15 | 1 3D surface plot
16 | 2 polar type plot
17 | 3 3D surface plot (compass bearing angles direction from)
18 | 4 polar type plot (compass bearing angles direction from)
19 |
20 | The 3D surface plot type is a MATLAB surface plot with SM.freqs on the x axis, SM.dirs on the y axis and the spectral density, SM.S as the z value.
21 | The polar type plot is a MATLAB polar plot with the direction showing values in SM.dirs, the radius showing values in SM.freqs
22 | and contours representing the spectral density, SM.S. An example of the polar type plot is shown on the front cover of the manual.
23 | For plot types 1 and 2, the direction is the direction of propagation relative to the Cartesian axis.
24 | For options 3 and 4 the direction is coming from as a true compass bearing (this has changed from previous versions).
25 | Directions are corrected internally from the SM.xaxisdir and SM.dunit
26 | fields that define the orientation of the axes and directional units in the spectral matrix.
27 |
28 | "help data_structures" for information on the DIWASP data structures
29 |
30 | Copyright (C) 2002 Coastal Oceanography Group, CWR, UWA, Perth
31 | """
32 |
33 | fig = plt.figure(tight_layout=True)
34 |
35 | SM, sfac = spectobasis(SM) #Convert to basis matrix
36 | dirs = SM['dirs']
37 | ffreqs = SM['freqs'] / (2 * np.pi)
38 | S = 2 * np.pi ** 2 * np.real(SM['S'])/ 180
39 |
40 | #Convert directions to nautical
41 | if ptype == 3 or ptype == 4:
42 | if 'xaxisdir' in SM.keys():
43 | xaxisdir = SM['xaxisdir']
44 | else:
45 | xaxisdir = 90
46 | dirs = dirs + np.pi + np.pi * (90 - xaxisdir) / 180
47 |
48 | #Surface plots
49 | if ptype == 1 or ptype == 3:
50 | if ptype == 3:
51 | dirs %= 2 * np.pi
52 | order = np.argsort(dirs)
53 | dirs = (180 * dirs / np.pi)[order]
54 | ddir, df = np.meshgrid(dirs, ffreqs)
55 | S = S[:, order]
56 | ax = fig.add_subplot(111, projection='3d')
57 | ax.set_xlabel('frequency [Hz]')
58 | if ptype == 1:
59 | ax.set_ylabel('direction [degrees]')
60 | ax.set_xlim(0, np.max(ffreqs))
61 | ax.set_ylim(-180, 180)
62 | ax.set_zlim(0, np.max(S))
63 | S[:, dirs > 180] = np.nan
64 | else:
65 | ax.set_ylabel('direction [bearings]')
66 | ax.set_xlim(0, np.max(ffreqs))
67 | ax.set_ylim(0, 360)
68 | ax.set_zlim(0, np.max(S))
69 | ax.plot_surface(df, ddir, np.real(S))
70 | ax.set_zlabel('m^2s / deg')
71 | ax.view_init(30, -135)
72 |
73 | #Polar plots
74 | elif ptype == 2 or ptype == 4:
75 | ddir, df = np.meshgrid(dirs, ffreqs)
76 | ax = fig.add_subplot(111, projection='polar')
77 | ax.set_rlim(0, 0.8 * np.max(ffreqs))
78 | c = ax.contour(ddir, df, np.real(S), 20)
79 | fig.colorbar(c)
80 | if ptype == 2:
81 | ax.set_ylabel('direction [degrees] / frequency [Hz]')
82 | else:
83 | ax.set_ylabel('direction [bearing] / frequency [Hz]')
84 | ax.set_xlabel('m^2 s / deg')
85 |
--------------------------------------------------------------------------------
/private/EMEP.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import warnings
3 |
4 |
5 | def solve_with_nan_handling(C, Z):
6 | """
7 | Solve the least-squares problem C * x = Z with MATLAB-like behavior for NaN values.
8 | If NaNs are present in C or Z, return a vector of zeros with appropriate dimensions.
9 | """
10 | # Check for NaN in C or Z
11 | if np.isnan(C).any() or np.isnan(Z).any():
12 | # MATLAB returns zeros in this scenario
13 | num_cols = C.shape[1] if C.ndim > 1 else 1
14 | return np.zeros((num_cols,))
15 |
16 | # Perform least-squares solving
17 | try:
18 | solution, _, _, _ = np.linalg.lstsq(C, Z, rcond=None)
19 | return solution
20 | except np.linalg.LinAlgError:
21 | return np.zeros((C.shape[1],))
22 |
23 | def EMEP(xps, trm, kx, Ss, pidirs, miter, displ):
24 | szd = xps.shape[0]
25 | freqs = xps.shape[2]
26 | ddirs = trm.shape[2]
27 |
28 | ddir = abs(pidirs[1] - pidirs[0])
29 | pi = np.pi
30 |
31 | if displ < 2:
32 | warnings.simplefilter("ignore")
33 |
34 | Co = np.real(xps)
35 | Quad = -np.imag(xps)
36 |
37 | sigCo = np.zeros_like(Co)
38 | sigQuad = np.zeros_like(Quad)
39 | xpsx = np.zeros_like(Co)
40 | for ff in range(freqs):
41 | xpsx[:,:,ff] = np.outer(np.real(np.diag(xps[:,:,ff])),
42 | np.real(np.diag(xps[:,:,ff]).T))
43 | sigCo[:,:,ff] = np.sqrt(0.5 * (xpsx[:,:,ff] + Co[:,:,ff]**2 - Quad[:,:,ff]**2))
44 | sigQuad[:,:,ff] = np.sqrt(0.5 * (xpsx[:,:,ff] - Co[:,:,ff]**2 + Quad[:,:,ff]**2))
45 |
46 | S = np.zeros((freqs, ddirs))
47 |
48 | phi = np.zeros((szd+2, freqs))
49 | H = np.zeros((ddirs, szd+2, freqs))
50 | for ff in range(freqs):
51 | index = 0
52 |
53 | for m in range(szd):
54 | for n in range(m, szd):
55 | expx = np.exp(-1j * kx[m, n, ff, :ddirs])
56 | Hh = trm[m, ff, :ddirs]
57 | Hhs = np.conj(trm[n, ff, :ddirs])
58 | Htemp = Hh * Hhs * expx
59 |
60 | if Htemp[0] != Htemp[1]:
61 | phi[index,ff] = (np.real(xps[m, n, ff]) / (sigCo[m, n, ff] * Ss[0, ff]))
62 | H[0:ddirs,index,ff] = np.real(Htemp) / sigCo[m, n, ff]
63 | index += 1
64 |
65 | if kx[m, n, 0, 0] + kx[m, n, 0, 1] != 0:
66 | phi[index,ff] = (np.imag(xps[m, n, ff]) / (sigQuad[m, n, ff] * Ss[0, ff]))
67 | H[0:ddirs,index,ff] = np.imag(Htemp) / sigQuad[m, n, ff]
68 | index += 1
69 |
70 | M = index
71 |
72 | cosnt = np.zeros((ddirs, M, M // 2 + 1))
73 | sinnt = np.zeros((ddirs, M, M // 2 + 1))
74 | for eni in range(1, M // 2 + 2):
75 | cosnt[:, :, eni - 1] = np.cos(eni * pidirs)[:, None]
76 | sinnt[:, :, eni - 1] = np.sin(eni * pidirs)[:, None]
77 | cosn = np.cos(np.arange(1, M // 2 + 2)[:, None] * pidirs)
78 | sinn = np.sin(np.arange(1, M // 2 + 2)[:, None] * pidirs)
79 |
80 | for ff in range(freqs):
81 | if displ >= 1:
82 | print(f"Calculating for frequency {ff + 1} of {freqs}")
83 |
84 | Hi = H[0:ddirs,0:M,ff]
85 | Phione = np.outer(np.ones_like(pidirs), phi[:M,ff])
86 |
87 | keepgoing = True
88 | n = 0
89 | AIC = []
90 |
91 | a1held, b1held = [], []
92 | while keepgoing:
93 | n += 1
94 |
95 | if n <= M // 2 + 1:
96 | if displ > 0:
97 | print(f"Model: {n}")
98 |
99 | a1, b1 = np.zeros(n), np.zeros(n)
100 | a2, b2 = np.ones(n) * 100, np.ones(n) * 100
101 | count = 0
102 | rlx = 1.0
103 |
104 | while np.max(np.abs(a2)) > 0.01 or np.max(np.abs(b2)) > 0.01:
105 | count += 1
106 | Fn = (a1 @ cosn[:n, :] + b1 @ sinn[:n, :]).T
107 |
108 | Fnexp = np.exp(Fn)[:, None] * np.ones((1, M))
109 | PhiHF = (Phione - Hi) * Fnexp
110 | Z = np.sum(PhiHF, axis=0) / np.sum(Fnexp, axis=0)
111 |
112 | X = np.zeros((n, M))
113 | Y = np.zeros((n, M))
114 | for eni in range(n):
115 | X[eni,0:M] = Z * ((
116 | np.sum(Fnexp * cosnt[:,:,eni], axis=0) / \
117 | np.sum(Fnexp, axis=0)
118 | ) - (
119 | np.sum(PhiHF * cosnt[:,:,eni], axis=0) / \
120 | np.sum(PhiHF, axis=0)
121 | ))
122 | Y[eni,0:M] = Z * ((
123 | np.sum(Fnexp * sinnt[:,:,eni], axis=0) / \
124 | np.sum(Fnexp, axis=0)
125 | ) - (
126 | np.sum(PhiHF * sinnt[:,:,eni], axis=0) / \
127 | np.sum(PhiHF, axis=0)
128 | ))
129 |
130 | C = np.hstack((X.T, Y.T))
131 |
132 | out = solve_with_nan_handling(C, Z)
133 |
134 | a2old, b2old = a2.copy(), b2.copy()
135 | a2, b2 = out[:n], out[n:2*n]
136 |
137 | if (
138 | np.sum(np.abs(a2) - np.abs(a2old) > 100) > 0
139 | or np.sum(np.abs(b2) - np.abs(b2old) > 100) > 0
140 | or count > miter
141 | ):
142 | if rlx > 0.0625:
143 | rlx *= 0.5
144 | if displ == 2:
145 | print(f"Relaxing computation...factor: {rlx:.4f}")
146 |
147 | count = 0
148 | a1[:n], b1[:n] = 0.0, 0.0
149 | else:
150 | if displ == 2:
151 | print("Computation fully relaxed...bailing out")
152 | keepgoing = False
153 | break
154 | else:
155 | a1 = a1 + rlx*a2
156 | b1 = b1 + rlx*b2
157 |
158 | error = Z - a2 @ X - b2 @ Y
159 | AIC.append(M * (np.log(2 * pi * np.var(error)) + 1) + 4 * n + 2)
160 |
161 | if n > 1 and (AIC[-1] > AIC[-2] or np.isnan(AIC[-1])):
162 | keepgoing = False
163 |
164 | a1held.append(a1[:n])
165 | b1held.append(b1[:n])
166 | best = n
167 |
168 | if not keepgoing:
169 | if n > 1:
170 | max_len = max(len(arr) for arr in a1held)
171 | padded_a1held = [np.pad(
172 | arr, (0, max_len - len(arr))) for arr in a1held]
173 | padded_b1held = [np.pad(
174 | arr, (0, max_len - len(arr))) for arr in b1held]
175 | a1 = np.array(padded_a1held)[n - 2, :n - 1]
176 | b1 = np.array(padded_b1held)[n - 2, :n - 1]
177 | best = n - 1
178 | else:
179 | a1 = np.zeros(1)
180 | b1 = np.zeros(1)
181 |
182 | else:
183 | keepgoing = False
184 |
185 | if displ == 2:
186 | print(f"Best: {best}")
187 |
188 | G = np.exp(a1@cosn[:best, :] + \
189 | b1@sinn[:best, :]).T
190 | SG = G / (np.sum(G) * ddir)
191 | S[ff, 0:ddirs] = Ss[0, ff] * SG.T
192 |
193 | return S
194 |
--------------------------------------------------------------------------------
/private/IMLM.py:
--------------------------------------------------------------------------------
1 | import warnings
2 | import numpy as np
3 | from numpy.linalg import inv
4 |
5 | def IMLM(xps, trm, kx, Ss, pidirs, miter, displ):
6 |
7 | gamma = 0.1
8 | alpha = 0.1
9 |
10 | szd = np.shape(xps)[0]
11 | ffreqs = np.shape(xps)[2]
12 | ddirs = np.shape(trm)[2]
13 |
14 | ddir = 8 * np.arctan(1) / ddirs
15 |
16 | if displ < 2:
17 | warnings.simplefilter('ignore')
18 |
19 | Htemp = np.empty((ddirs, szd, szd), dtype='complex128')
20 | iHtemp = np.empty((ddirs, szd, szd), dtype='complex128')
21 | ixps = np.empty((szd, szd), dtype='complex128')
22 | S = np.empty((ffreqs, ddirs), dtype='complex128')
23 |
24 | for ff in range(ffreqs):
25 | if displ >= 1:
26 | print('calculating for frequency {} of {}'.format(ff + 1, ffreqs))
27 |
28 | for m in range(szd):
29 | for n in range(szd):
30 | H = trm[n, ff, :]
31 | Hs = np.conj(trm[m, ff, :])
32 | expx = np.exp(1j * kx[m, n, ff, :])
33 | iexpx = np.exp(-1j * kx[m, n, ff, :])
34 | Htemp[:, m, n] = H * Hs * expx
35 | iHtemp[:, m, n] = H * Hs * iexpx
36 |
37 | invcps = inv(xps[:, :, ff])
38 | Sftmp = np.zeros(ddirs, dtype='complex128')
39 | for m in range(szd):
40 | for n in range(szd):
41 | xtemp = invcps[m, n] * Htemp[:, m, n]
42 | Sftmp += xtemp
43 | Eo = 1 / Sftmp
44 | kappa = 1 / (ddir * np.sum(Eo))
45 | Eo *= kappa
46 | E = Eo
47 | T = Eo
48 |
49 | for it in range(miter):
50 | for m in range(szd):
51 | for n in range(szd):
52 | expG = iHtemp[:, m, n] * E
53 | ixps[m, n] = np.sum(expG) * ddir
54 | invcps = inv(ixps)
55 | Sftmp = np.zeros(ddirs, dtype='complex128')
56 | for m in range(szd):
57 | for n in range(szd):
58 | xtemp = invcps[m, n] * Htemp[:, m, n]
59 | Sftmp = Sftmp + xtemp
60 | Told = T
61 | T = 1 / Sftmp
62 |
63 | kappa = 1 / (ddir * np.sum(T))
64 | T = T * kappa
65 |
66 | ei = gamma * ((Eo - T) + alpha * (T - Told))
67 | E = E + ei
68 | kappa = 1 / (ddir * np.sum(E))
69 | E = E * kappa
70 |
71 |
72 |
73 | S[ff, :] = Ss[0, ff] * E
74 |
75 |
76 |
77 | warnings.simplefilter('default')
78 |
79 | return S
80 |
--------------------------------------------------------------------------------
/private/check_data.py:
--------------------------------------------------------------------------------
1 | import warnings
2 | import numpy as np
3 |
4 | def check_data(DDS, type_):
5 | """
6 | internal DIWASP1.1 function
7 | checks data structures
8 |
9 | DDS=check_data(DDS,type)
10 | DDS: the data structure
11 | type: 1, Instrument data structure;
12 | 2, Spectral matrix structure;
13 | 3, Estimation parameters structure.
14 |
15 | Updated on 29/04/2013 by r.guedes to fix some errors that were not being
16 | detected (e.g., ID.datatype not being a cell array).
17 | """
18 |
19 | #--------------------------------------------------------------------------
20 | # Defaults
21 | #--------------------------------------------------------------------------
22 | SM = dict()
23 | EP = dict()
24 | SM['xaxisdir'] = 90
25 | EP['dres'] = 180
26 | EP['nfft'] = []
27 | EP['method'] = 'IMLM'
28 | EP['iter'] = 100
29 | error = ''
30 |
31 | #--------------------------------------------------------------------------
32 | # Instrument data structure
33 | #--------------------------------------------------------------------------
34 | if type_ == 1:
35 | if type(DDS) != dict:
36 | print('DIWASP data_check: Instrument data type is not a '
37 | 'dictionary')
38 | nc = 1
39 | if 'layout' in DDS:
40 | nr, nc = np.shape(DDS['layout'])
41 | if nr < 3:
42 | if nr == 2:
43 | np.array(DDS['layout'])[2, :] = 0
44 | else:
45 | error = 'layout'
46 |
47 | if ('datatypes' not in DDS or type(DDS['datatypes']) not in
48 | (list, np.ndarray) or np.squeeze(DDS['datatypes']).ndim != 1
49 | or max(np.shape(DDS['datatypes'])) != nc):
50 | error = 'datatypes'
51 | else:
52 | DDS['datatypes'] = np.reshape(DDS['datatypes'],
53 | np.size(DDS['datatypes']))
54 |
55 | if 'depth' not in DDS or type(DDS['depth']) not in (int, float):
56 | error = 'depth'
57 |
58 | if 'fs' not in DDS or type(DDS['fs']) not in (int, float):
59 | error = 'fs'
60 |
61 | if 'data' in DDS:
62 | if np.ndim(DDS['data']) < 2 or np.shape(DDS['data'])[1] != nc:
63 | error = 'data'
64 | else:
65 | DDS['data'] = np.zeros((1, nc))
66 |
67 | if len(error) != 0:
68 | print('\nInstrument data structure error: field [{}] not specified '
69 | 'correctly'.format(error))
70 | DDS = []
71 | return DDS
72 |
73 | # -------------------------------------------------------------------------
74 | # Special matrix
75 | # -------------------------------------------------------------------------
76 | if type_ == 2:
77 | if type(DDS) != dict:
78 | print('DIWASP data_check: Special matrix data type is not a '
79 | 'structure')
80 |
81 | if 'freqs' in DDS and np.squeeze(DDS['freqs']).ndim == 1:
82 | nf = np.size(DDS['freqs'])
83 | else:
84 | error = 'freqs'
85 |
86 | if 'dirs' in DDS and np.squeeze(DDS['dirs']).ndim == 1:
87 | nd = np.size(DDS['dirs'])
88 | else:
89 | error = 'dirs'
90 |
91 | if 'S' in DDS:
92 | if (np.shape(DDS['S'])[0] != nf or np.ndim(DDS['S']) < 2 or
93 | np.shape(DDS['S'])[1] != nd):
94 | error = 'S'
95 | else:
96 | DDS['S'] = []
97 |
98 | if 'xaxisdir' in DDS:
99 | if type(DDS['xaxisdir']) not in (int, float):
100 | error = 'xaxisdir'
101 | else:
102 | DDS['xaxisdir'] = SM['xaxisdir']
103 |
104 | if 'dunit' not in DDS:
105 | DDS['dunit'] = 'cart'
106 |
107 | if 'funit' not in DDS:
108 | DDS['funit'] = 'hz'
109 |
110 | if len(error) != 0:
111 | print('\nSpectral matrix structure error: field [{}] not '
112 | 'specified correctly'.format(error))
113 | DDS = []
114 | return DDS
115 |
116 | #--------------------------------------------------------------------------
117 | # Estimation parameters
118 | #--------------------------------------------------------------------------
119 | if type_ == 3:
120 | if type(DDS) != dict:
121 | print('DIWASP data_check: Estimation parameter data type is not a '
122 | 'structure')
123 |
124 | if 'dres' in DDS:
125 | if type(DDS['dres']) not in (int, float):
126 | error = 'dres'
127 | elif DDS['dres'] < 10:
128 | DDS['dres'] = 10
129 | warnings.warn('dres is too small and has been set to 10')
130 |
131 | else:
132 | DDS['dres'] = EP['dres']
133 |
134 | if 'nfft' in DDS:
135 | if type(DDS['nfft']) not in (int, float):
136 | error = 'nfft'
137 | elif DDS['nfft'] < 64:
138 | DDS['nfft'] = 64
139 | warnings.warn('nfft is too small and has been set to 64')
140 | else:
141 | DDS['nfft'] = EP['nfft']
142 |
143 | if 'iter' in DDS:
144 | if type(DDS['iter']) not in (int, float):
145 | error = 'iter'
146 | else:
147 | DDS['iter'] = EP['iter']
148 |
149 | if 'smooth' in DDS:
150 | if DDS['smooth'].upper() != 'OFF':
151 | DDS['smooth'] = 'ON'
152 | else:
153 | DDS['smooth'] = 'ON'
154 |
155 | if 'method' in DDS:
156 | if DDS['method'].upper() not in ('DFTM', 'EMLM', 'IMLM', 'EMEP',
157 | 'BDM'):
158 | error = 'method'
159 | else:
160 | DDS['method'] = EP['method']
161 |
162 | if len(error) != 0:
163 | print('\nEstimation parameters structure error: field [{}] not '
164 | 'specified correctly')
165 | DDS = []
166 | return DDS
167 |
168 | if type_ not in (1, 2, 3):
169 | print()
170 | warnings.warn('DIWASP data_check: Data type unknown')
171 | DDS = []
172 |
173 | return DDS
174 |
--------------------------------------------------------------------------------
/private/diwasp_csd.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from scipy.signal import csd
3 |
4 | def diwasp_csd(x, y, nfft, fs, flag=1):
5 | """
6 | Diwasp cross spectral density.
7 | If flag = 1, use scipy's cross spectral density function
8 | If flag = 2, use custom cross spectral density function
9 |
10 | [Pxy, f] = diwasp_csd(x,y,nfft,fs)
11 | """
12 |
13 | if flag == 1:
14 | f, S = csd(y, x, fs=fs, window='hamming', nperseg=nfft,
15 | noverlap=0, nfft=nfft, detrend=False)
16 | elif flag == 2: # match mlab version if Signal Processing Toolbox not available
17 | hann = 0.5 * (1 - np.cos(2 * np.pi * np.arange(1, int(nfft / 2) + 1) /
18 | (nfft + 1)))
19 | win = np.hstack((hann, np.flipud(hann)))
20 | nw = np.size(win)
21 | nseg = int(np.size(x) / nw)
22 | S = np.zeros(nfft, dtype='complex128')
23 | for iseg in range(nseg):
24 | ind = nw * iseg + np.arange(nw)
25 | xw = win * x[ind]
26 | yw = win * y[ind]
27 | Px = np.fft.fft(xw, nfft)
28 | Py = np.fft.fft(yw, nfft)
29 | Pxy = Py * np.conj(Px)
30 | S += Pxy
31 | nfac = fs * nseg * np.linalg.norm(win) ** 2
32 | S = np.hstack((S[0], 2 * S[1:int(nfft / 2)], S[int(nfft / 2)])) / nfac
33 | f = (fs / nfft) * np.arange(int(nfft / 2) + 1).T
34 |
35 | return S, f
36 |
--------------------------------------------------------------------------------
/private/elev.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | def elev(ffreqs, dirs, wns, z, depth):
4 |
5 | trm = np.ones((np.size(ffreqs), np.size(dirs)))
6 |
7 | return trm
--------------------------------------------------------------------------------
/private/hsig.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | def hsig(argin):
4 | """
5 | DIWASP function to calculate significant wave height
6 |
7 | Hs=Hsig(SM)
8 |
9 | Hs is significant wave height of spectral matrix SM
10 |
11 | "help data_structures" for information on the DIWASP data structures
12 |
13 | Copyright (C) 2002 Coastal Oceanography Group, CWR, UWA, Perth
14 | """
15 |
16 | SM = argin
17 | df = SM['freqs'][1] - SM['freqs'][0]
18 | ddir = SM['dirs'][1] - SM['dirs'][0]
19 | S = SM['S']
20 |
21 | Hs = 4 * np.sqrt(np.sum(np.sum(np.real(S))) * df * ddir)
22 |
23 | return Hs
--------------------------------------------------------------------------------
/private/pres.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | def pres(ffreqs, dirs, wns, z, depth):
4 | Kz = np.cosh(z * wns) / np.cosh(depth * wns)
5 | #include a maximum cuttoff for the pressure response function
6 | Kz[Kz < 0.1] = 0.1
7 | trm = Kz[:, np.newaxis] * np.ones(np.shape(dirs))
8 |
9 | return trm
--------------------------------------------------------------------------------
/private/smoothspec.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | def smoothspec(S, kernel):
4 | """
5 | smooths a directional spectrum using the
6 | first dimension is frequency
7 | kernel is 2*3 matrix with smoothing parameters
8 | """
9 |
10 | f1 = kernel[0][2]
11 | f2 = kernel[0][1]
12 | f3 = kernel[0][0]
13 | d1 = kernel[1][2]
14 | d2 = kernel[1][1]
15 | d3 = kernel[1][0]
16 | tot = 2 * f1 + 2 * f2 + f3 + 2 * d1 + 2 * d2 + d3
17 |
18 | nf, nd = np.shape(S['S'])
19 |
20 | Sin = S['S']
21 | Sin[np.isnan(Sin)] = 0
22 |
23 | S['S'][2:nf - 2, 2:nd - 2] = (f1 * Sin[:nf - 4, 2:nd - 2] + f2 *
24 | Sin[1:nf - 3, 2:nd - 2] + f3 * Sin[2:nf - 2, 2:nd - 2] + f2 *
25 | Sin[3:nf - 1, 2:nd - 2] + f1 * Sin[4:nf, 2:nd - 2] + d1 *
26 | Sin[2:nf - 2, :nd - 4] + d2 * Sin[2:nf - 2, 1:nd - 3] + d3 *
27 | Sin[2:nf - 2, 2:nd - 2] + d2 * Sin[2:nf - 2, 3:nd - 1] + d1 *
28 | Sin[2:nf - 2, 4:nd]) / tot
29 |
30 | return S
31 |
--------------------------------------------------------------------------------
/private/spectobasis.py:
--------------------------------------------------------------------------------
1 | import copy
2 | import numpy as np
3 |
4 | def spectobasis(SM):
5 | """Converts any spectral matrix to rad/s and cartesian radians"""
6 |
7 | SM = copy.deepcopy(SM)
8 |
9 | Sfac = 1.0
10 | if 'funit' in SM.keys() and SM['funit'].lower() == 'hz':
11 | SM['freqs'] *= 2 * np.pi
12 | Sfac /= (2 * np.pi)
13 |
14 | r2d = np.pi / 180
15 | if 'dunit' in SM.keys():
16 | if SM['dunit'][:3].lower() == 'car':
17 | SM['dirs'] = SM['dirs'] * r2d
18 | Sfac /= r2d
19 | elif SM['dunit'][:3].lower() == 'nau':
20 | if 'xaxisdir' in SM.keys():
21 | SM['dirs'] += (90 - SM['xaxisdir'])
22 | SM['dirs'] = r2d * (270 - SM['dirs'])
23 | Sfac /= r2d
24 |
25 | if 'S' in SM.keys() and (isinstance(SM['S'], np.ndarray) and \
26 | SM['S'].size > 0):
27 | SM['S'] *= Sfac
28 |
29 | return SM, Sfac
--------------------------------------------------------------------------------
/private/velx.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | def velx(ffreqs, dirs, wns, z, depth):
4 |
5 | Kz = np.cosh(z * wns) / np.sinh(depth * wns)
6 | #include a maximum cuttoff for the velocity response function
7 | Kz[Kz < 0.1] = 0.1
8 | trm = (ffreqs * Kz)[:, np.newaxis] * np.cos(dirs)
9 |
10 | return trm
--------------------------------------------------------------------------------
/private/vely.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | def vely(ffreqs, dirs, wns, z, depth):
4 | Kz = np.cosh(z * wns) / np.sinh(depth * wns)
5 | #include a maximum cuttoff for the velocity response function
6 | Kz[Kz < 0.1] = 0.1
7 | trm = np.transpose((ffreqs * Kz, )) * np.sin(dirs)
8 |
9 | return trm
--------------------------------------------------------------------------------
/private/wavenumber.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | def wavenumber(sigma, h):
4 | """"
5 | k = wavenumber(sigma,h)
6 |
7 | k is the matrix of same size as sigma and h containing the calculated wave numbers
8 |
9 | sigma is the wave frequencies in rad/s
10 | h is the water depth
11 |
12 | sigma and h must be scalars,vectors or matricies of the same dimensions
13 |
14 |
15 | modified from R.Dalrymple's java code
16 | """
17 | g = 9.81
18 |
19 | a0 = (sigma * sigma * h) / g
20 | b1 = 1 / np.tanh(a0 ** 0.75)
21 | a1 = a0 * (b1 ** 0.666)
22 | da1 = 1000
23 |
24 | d1 = np.ones(np.shape(h))
25 | while np.max(d1) == 1:
26 | d1 = np.abs(da1 / a1) > 0.00000001
27 | th = np.tanh(a1)
28 | ch = np.cosh(a1)
29 | f1 = a0 - (a1 * th)
30 | f2 = -a1 * (1 / ch) ** 2 - th
31 | da1 = -f1 / f2
32 | a1 += da1
33 |
34 | k = a1 / h
35 |
36 | return k
--------------------------------------------------------------------------------
/writespec.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | def writespec(SM, filename):
4 | """
5 | DIWASP V1.4 function
6 | writespec: writes spectrum matrix to file using DIWASP format
7 |
8 | writespec(SM,filename)
9 |
10 | Inputs:
11 | SM A spectral matrix structure
12 | filename String containing the filename including file extension if required
13 |
14 | All inputs required
15 |
16 | "help data_structures" for information on the DIWASP data structures
17 |
18 | Copyright (C) 2002 Coastal Oceanography Group, CWR, UWA, Perth
19 | """
20 |
21 | nf = np.max(SM['freqs'].shape)
22 | nd = np.max(SM['dirs'].shape)
23 |
24 | streamout = np.empty((nf + nd + 4 + nf * nd))
25 |
26 | streamout[0] = SM['xaxisdir']
27 | streamout[1] = nf
28 | streamout[2] = nd
29 | streamout[3:nf + 3] = SM['freqs']
30 | streamout[nf + 3:nf + nd + 3] = SM['dirs']
31 | streamout[nf + nd + 3] = 999
32 | streamout[nf + nd + 4:nf + nd + 4 + nf * nd] = np.reshape(np.real(SM['S']),
33 | (nf * nd))
34 |
35 | streamout = streamout.T
36 |
37 | np.savetxt(filename, streamout)
38 |
--------------------------------------------------------------------------------