diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 25cb635a..d6b8fb7a 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -8,7 +8,6 @@ jobs:
fail-fast: false
env:
SPEC_PATH: ${{ github.workspace }}
- PYTHONPATH: ${{ github.workspace }}/Utilities/pythontools
OMPI_ALLOW_RUN_AS_ROOT: 1
OMPI_ALLOW_RUN_AS_ROOT_CONFIRM: 1
steps:
@@ -22,6 +21,8 @@ jobs:
sudo apt-get update
sudo apt-get install gfortran mpi-default-bin mpi-default-dev libhdf5-103 libhdf5-dev libfftw3-bin libfftw3-dev libopenblas0-openmp libopenblas-dev
pip3 install --user numpy f90nml scikit-build scipy h5py matplotlib
+ cd ${{ github.workspace }}/Utilities/pythontools
+ pip3 install -v .
- name: compile_xspec
run: |
cd ${SPEC_PATH}
@@ -33,14 +34,12 @@ jobs:
- name: run_fast_cartesian
run: |
cd ${SPEC_PATH}/ci/G1V03L2Fi
- echo ${PYTHONPATH}
export OMP_NUM_THREADS=1
mpiexec -n 2 --allow-run-as-root ${SPEC_PATH}/xspec G1V03L2Fi.001.sp
python3 -m py_spec.ci.test compare.h5 G1V03L2Fi.001.sp.h5
- name: run_fast_cylinder
run: |
cd ${SPEC_PATH}/ci/G2V32L1Fi
- echo ${PYTHONPATH}
export OMP_NUM_THREADS=1
mpiexec -n 2 --allow-run-as-root ${SPEC_PATH}/xspec G2V32L1Fi.001.sp
python3 -m py_spec.ci.test compare.h5 G2V32L1Fi.001.sp.h5
diff --git a/.github/workflows/build_cmake.yml b/.github/workflows/build_cmake.yml
index 866a50a9..3ea86651 100644
--- a/.github/workflows/build_cmake.yml
+++ b/.github/workflows/build_cmake.yml
@@ -8,7 +8,6 @@ jobs:
fail-fast: false
env:
SPEC_PATH: ${{ github.workspace }}
- PYTHONPATH: ${{ github.workspace }}/Utilities/pythontools
OMPI_ALLOW_RUN_AS_ROOT: 1
OMPI_ALLOW_RUN_AS_ROOT_CONFIRM: 1
steps:
@@ -20,6 +19,8 @@ jobs:
pip3 install --upgrade pip
pip3 install --user ninja cmake scipy
pip3 install --user numpy f90nml scikit-build scipy h5py matplotlib
+ cd ${{ github.workspace }}/Utilities/pythontools
+ pip3 install -v .
- name: Build & Test
uses: ashutoshvarma/action-cmake-build@master
with:
@@ -39,14 +40,12 @@ jobs:
- name: run_fast_cartesian
run: |
cd ${SPEC_PATH}/ci/G1V03L2Fi
- echo ${PYTHONPATH}
export OMP_NUM_THREADS=1
mpiexec -n 2 --allow-run-as-root $SPEC_PATH/install/bin/xspec G1V03L2Fi.001.sp
python3 -m py_spec.ci.test compare.h5 G1V03L2Fi.001.sp.h5
- name: run_fast_cylinder
run: |
cd ${SPEC_PATH}/ci/G2V32L1Fi
- echo ${PYTHONPATH}
export OMP_NUM_THREADS=1
mpiexec -n 2 --allow-run-as-root $SPEC_PATH/install/bin/xspec G2V32L1Fi.001.sp
python3 -m py_spec.ci.test compare.h5 G2V32L1Fi.001.sp.h5
diff --git a/.github/workflows/py_spec.yml b/.github/workflows/py_spec.yml
index 495d1880..66ce4093 100644
--- a/.github/workflows/py_spec.yml
+++ b/.github/workflows/py_spec.yml
@@ -18,8 +18,8 @@ jobs:
- name: Install dependencies
working-directory: ${{ env.PY_SPEC_DIR }}
run: |
- pip3 install -r requirements.txt
- pip3 install setuptools wheel twine
+ pip install --upgrade pip
+ pip3 install setuptools wheel twine
- name: Build py_spec
working-directory: ${{ env.PY_SPEC_DIR }}
diff --git a/.github/workflows/python_wrapper.yml b/.github/workflows/python_wrapper.yml
index 158451d5..8977807c 100644
--- a/.github/workflows/python_wrapper.yml
+++ b/.github/workflows/python_wrapper.yml
@@ -6,26 +6,25 @@ jobs:
name: python_wrapper build
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v4
# Python3 should be pre-installed on 'ubuntu-latest'
- name: Python version info
run: |
- python3 --version
- pip3 --version
+ python --version
+ pip --version
- name: Install dependencies
run: |
sudo apt-get update
- sudo apt-get install gfortran mpi-default-bin mpi-default-dev libhdf5-103 libhdf5-dev libfftw3-bin libfftw3-dev libopenblas0-openmp libopenblas-dev cmake ninja-build
- pip3 install --user numpy f90nml scikit-build
- pip3 install --user git+https://github.com/zhucaoxiang/f90wrap
+ sudo apt-get install gfortran mpi-default-bin mpi-default-dev libhdf5-dev libfftw3-bin libfftw3-dev libopenblas-dev cmake ninja-build
+ pip install numpy f90nml scikit-build scipy meson meson-python
+ pip install f90wrap
- name: Build python_wrapper
run: |
- python3 setup.py bdist_wheel
- pip3 install --user dist/*.whl
+ pip install .
- name: Test if installation is ok
run: |
- python3 -c "import spec; print('success')"
+ python -c "import spec; print('success')"
diff --git a/.gitignore b/.gitignore
index c0c569eb..564e14d3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -57,3 +57,7 @@ _skbuild/
# Temp fortran files
src/mxspech.f90
src/msphdf5.f90
+
+# Apple Mac related
+.DS_Store
+
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ef806494..98dc87d9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -49,6 +49,17 @@ else ()
endif ()
endif ()
+
+if(CMAKE_Fortran_COMPILER_ID STREQUAL "Intel")
+ set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -DIFORT")
+endif()
+
+if(CMAKE_Fortran_COMPILER_ID STREQUAL "GNU")
+ if(CMAKE_Fortran_COMPILER_VERSION VERSION_GREATER "10.0")
+ set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -fallow-argument-mismatch")
+ endif()
+endif()
+
find_program(AWK awk mawk gawk)
# Find LAPACK
@@ -60,11 +71,11 @@ find_program(AWK awk mawk gawk)
# If Intel MKL is not desired, change BLA_VENDOR variabale during configuration
#set(BLA_VENDOR Intel10_64lp CACHE STRING
# "Define BLAS vendor. Some of the popular options are Intel10_64lp OpenBLAS Apple Generic")
-find_package (BLAS REQUIRED)
-message(STATUS "BLAS vendor is ${BLA_VENDOR}")
-if (NOT ${BLA_VENDOR} MATCHES "^Intel" AND NOT ${BLA_VENDOR} MATCHES "^OpenBLAS")
- find_package (LAPACK REQUIRED)
-endif()
+# find_package (BLAS REQUIRED)
+# message(STATUS "BLAS vendor is ${BLA_VENDOR}")
+# if (NOT ${BLA_VENDOR} MATCHES "^Intel" AND NOT ${BLA_VENDOR} MATCHES "^OpenBLAS")
+find_package (LAPACK REQUIRED)
+#endif()
# Find FFTW3.
# Intel oneAPI has FFT3 available as part of MKL. Just linking against MKL gives FFTW functionality.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000..f288702d
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/Utilities/BoozerXForms/README.md b/Utilities/BoozerXForms/README.md
new file mode 100644
index 00000000..234c0592
--- /dev/null
+++ b/Utilities/BoozerXForms/README.md
@@ -0,0 +1,6 @@
+# BoozerXForms
+Python routines to achieve Boozer coordinates transformation from SPEC output
+Useful e.g to plot modB
+
+For any questions or mistake spotted, contact me at
+salomon.guinchard@epfl.ch
diff --git a/Utilities/BoozerXForms/Tutorial1.txt b/Utilities/BoozerXForms/Tutorial1.txt
new file mode 100644
index 00000000..926325cc
--- /dev/null
+++ b/Utilities/BoozerXForms/Tutorial1.txt
@@ -0,0 +1,33 @@
+This is a basic tutorial on how to use the Booz-xform package (M.Landreman) from SPECout file, using routines init_from_spec.py and run_boz.py
+
+0. Make sure you have the booz-xforms package installed. If not, can be installed with
+ $ pip install booz-xform (or see doc at https://hiddensymmetries.github.io/booz_xform/)
+
+0b. Requires additional packages: py_spec, numpy and h5py
+
+1. Load function to initialise a booz-xforms instance out of a SPEC output (.h5) with
+ > from init_from_spec import init_from_spec
+
+2. Call init_from_spec function with test file QA_002.sp.h5
+ > b = init_from_spec('QA_002.sp.h5')
+
+3. Call internal run method as follows
+ > b.run()
+
+4. The output data sets can be written in .h5 file running all the commands from run_boz.py
+ > f = h5.File('./OutputBOZ/'+ bozout, 'w')
+ > print(f.filename)
+ > grp = f.create_group('Booz_xForms')
+ > ...
+ > ...
+ > outputs.create_dataset('boozer_i_all', data = b.Boozer_I_all)
+ > f.close()
+
+5. Plot the magnetic field intensity in Boozer coordinates
+ > plt.figure
+ > bx.surfplot(b, js=0, fill=False, cmap=plt.cm.jet, ntheta=50, nphi=90, ncontours=25)
+ > plt.savefig('QA002.eps')
+ > plt.show()
+
+6. If major issue can't be solved / code mistake
+ contact: S.Guinchard - salomon.guinchard@epfl.ch
diff --git a/Utilities/BoozerXForms/init_from_spec.py b/Utilities/BoozerXForms/init_from_spec.py
new file mode 100644
index 00000000..3a4ef542
--- /dev/null
+++ b/Utilities/BoozerXForms/init_from_spec.py
@@ -0,0 +1,269 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+Created on Mon May 9 17:51:56 2022
+This file initialises a booz x form instance
+without changing the SPEC output file
+@authors: A.Baillod, S.Guinchard
+"""
+
+import py_spec as sp
+import booz_xform as bx
+import numpy as np
+
+######################################################
+############### EXTRACT ALL SPECOUT DATA #############
+######################################################
+
+
+def init_from_spec( filename ):
+ d = sp.SPECout( filename )
+
+ compute_surfs = np.array([0])
+ verbose = 1
+ asym = False #False if stellarator symmetric
+ nfp = d.input.physics.Nfp
+ mpol = d.input.physics.Mpol+1
+ ntor = d.input.physics.Ntor
+ nvol = d.input.physics.Nvol
+ mpol_nyq = mpol
+ ntor_nyq = ntor
+ mnmax = ntor +1 + (mpol-1) *(2*ntor +1)
+ mnmax_nyq = ntor_nyq+1 + (mpol_nyq-1)*(2*ntor_nyq+1)
+ xm = d.output.im
+ xn = d.output.in_
+ xm_nyq = xm
+ xn_nyq = xn
+ ns_in = int(2*nvol-1)
+ s_in = np.ndarray(ns_in, dtype = np.float64)
+ s_in[0] = d.output.tflux;
+ iota = np.array([d.output.lambdamn[1][0][0]])
+ rmnc = np.array([list(d.output.Rbc[1,:])]).transpose()
+ rmns = np.array([])
+ zmnc = np.array([])
+ zmns = np.array([list(d.output.Zbs[1,:])]).transpose()
+
+ # build lmns
+ lambdamn = d.output.lambdamn[1][:].transpose()
+ xms = d.output.ims
+ xns = d.output.ins
+ mns = d.output.mns
+ lmns = np.zeros([mnmax,ns_in])
+ lmnc = np.array([])
+
+ for ii in range (0,mns):
+ mm = xms[ii]
+ nn = xns[ii]
+
+ if mm==0 and nn==0: #mode (0,0) is zero
+ continue
+ if mm>mpol-1 or mm<0:
+ continue
+ if nn<-ntor*nfp or nn>ntor*nfp:
+ continue
+
+ for jj in range(0,mnmax):
+ if mm==xm[jj] and nn==xn[jj]:
+ lmns[jj] = lambdamn[ii]
+ continue
+
+
+ bsubumnc = np.array([list(d.output.Btemn[1,:])]).transpose()
+ bsubvmnc = np.array([list(d.output.Bzemn[1,:])]).transpose()
+ bsubumns = np.array([])
+ bsubvmns = np.array([])
+ mboz = np.max(xm)
+ nboz = int(1/nfp * np.max(xn))
+ aspect = np.nan
+ toroidal_flux = d.input.physics.phiedge
+
+ # modB computation
+ Nt = d.grid.Nt
+ Nz = d.grid.Nz
+ sarr = np.linspace(0,1,2)
+ tarr = np.linspace(0,2*np.pi,Nt)
+ zarr = np.linspace(0,2*np.pi/nfp,Nz)
+
+ Bcontrav = d.get_B(lvol = 0, sarr = sarr, tarr = tarr, zarr = zarr)
+ [R, Z, jac, g] = d.get_grid_and_jacobian_and_metric(lvol = 0, sarr = sarr, tarr= tarr, zarr = zarr)
+
+ modB = d.get_modB(Bcontrav, g)
+ modBsurf = modB[1][:][:]
+ modBcos = np.zeros(np.shape(modBsurf))
+ K = 2*np.pi**2/nfp
+ Bmn_ = np.zeros((mpol,2*ntor+1))
+
+ for m in range (0,mpol):
+ for n in range (-ntor,ntor+1):
+ if m == 0 and n<0:
+ continue
+ for line in range (0,Nt):
+ for column in range (0,Nz):
+ modBcos[line,column] = modBsurf[line][column]* np.cos(np.double(m)*tarr[line] - np.double(n)*np.double(nfp)*zarr[column])
+
+ tmp = np.trapz(modBcos, x = tarr, axis = 0)
+ Bmn_[m,n+ntor] = 1/K*np.trapz(tmp, x=zarr)
+
+
+ Bmn_[0,ntor] = 1/2*Bmn_[0,ntor]
+
+
+ Bmnc = np.zeros((mnmax,ns_in))
+ jj = 0 #index of surface
+ for ii in range(0,mnmax):
+ m = xm[ii]
+ n = int(xn[ii] / nfp)
+ Bmnc[ii,jj] = Bmn_[m,n+ntor]
+
+ Bmns = np.array([])
+
+
+ ##########################################################
+ # Initialisation of a Booz_xform instance b #
+ ##########################################################
+
+ b = bx.Booz_xform()
+
+ if ns_in<1:
+ raise ValueError('ns has to be larger than zero')
+
+ if nfp<1:
+ raise ValueError('Nfp has to be larger than zero')
+
+ if iota.size!=ns_in:
+ raise ValueError('Iota has not the size ns_in')
+
+ if xm.size!=mnmax:
+ raise ValueError('xm has not the size mnmax')
+ if xn.size!=mnmax:
+ raise ValueError('xn has not the size mnmax')
+ if xm_nyq.size!=mnmax_nyq:
+ raise ValueError('xm_nyq has not the size mnmax')
+ if xn_nyq.size!=mnmax_nyq:
+ raise ValueError('xn_nyq has not the size mnmax')
+
+ if xm[0]!=0:
+ raise ValueError('xm first element is not right')
+ if xn[0]!=0:
+ raise ValueError('xn first element is not right')
+ if xm_nyq[0]!=0:
+ raise ValueError('xm_nyq first element is not right')
+ if xn_nyq[0]!=0:
+ raise ValueError('xn_nyq first element is not right')
+
+ if xm[-1]!=mpol-1:
+ raise ValueError('xm last element is not right')
+ if xn[-1]!=nfp*ntor:
+ raise ValueError('xn last element is not right')
+ if xm_nyq[-1]!=mpol_nyq-1:
+ raise ValueError('xm_nyq last element is not right')
+ if xn_nyq[-1]!=nfp*ntor_nyq:
+ raise ValueError('xn_nyq last element is not right')
+
+ if rmnc.shape[0]!=mnmax:
+ raise ValueError('Rmnc should have mnmax rows')
+ if zmns.shape[0]!=mnmax:
+ raise ValueError('Zmns should have mnmax rows')
+ if asym:
+ if rmns.shape[0]!=mnmax:
+ raise ValueError('Rmns should have mnmax rows')
+ if zmnc.shape[0]!=mnmax:
+ raise ValueError('Zmnc should have mnmax rows')
+
+ if rmnc.shape[1]!=ns_in:
+ raise ValueError('Rmnc should have ns_in columns')
+ if zmns.shape[1]!=ns_in:
+ raise ValueError('Zmns should have ns_in columns')
+ if asym:
+ if rmns.shape[1]!=ns_in:
+ raise ValueError('Rmns should have ns_in columns')
+ if zmnc.shape[1]!=ns_in:
+ raise ValueError('Zmnc should have ns_in columns')
+
+ if bsubumnc.shape[0]!=mnmax:
+ raise ValueError('Rmnc should have mnmax rows')
+ if bsubvmnc.shape[0]!=mnmax:
+ raise ValueError('Rmns should have mnmax rows')
+ if asym:
+ if bsubumns.shape[0]!=mnmax:
+ raise ValueError('Zmnc should have mnmax rows')
+ if bsubvmns.shape[0]!=mnmax:
+ raise ValueError('Zmns should have mnmax rows')
+
+ if bsubumnc.shape[1]!=ns_in:
+ raise ValueError('Rmnc should have ns_in columns')
+ if bsubvmnc.shape[1]!=ns_in:
+ raise ValueError('Rmns should have ns_in columns')
+ if asym:
+ if bsubumns.shape[1]!=ns_in:
+ raise ValueError('Zmnc should have ns_in columns')
+ if bsubvmns.shape[1]!=ns_in:
+ raise ValueError('Zmns should have ns_in columns')
+
+ if Bmnc.shape[0]!=mnmax:
+ raise ValueError('Invalid number of modes for Bmnc')
+ if Bmnc.shape[1]!=ns_in:
+ raise ValueError('Invalid number of surfaces for Bmnc')
+ if asym:
+ if Bmns.shape[0]!=mnmax:
+ raise ValueError('Invalid number of modes for Bmns')
+ if Bmns.shape[1]!=ns_in:
+ raise ValueError('Invalid number of surfaces for Bmns')
+
+ if lmns.shape[0]!=mnmax:
+ raise ValueError('Invalid number of modes for lmns')
+ if lmns.shape[1]!=ns_in:
+ raise ValueError('Invalid number of surfaces for lmns')
+ if asym:
+ if lmnc.shape[0]!=mnmax:
+ raise ValueError('Invalid number of modes for lmnc')
+ if lmnc.shape[1]!=ns_in:
+ raise ValueError('Invalid number of surfaces for lmnc')
+
+ if any(compute_surfs<0):
+ raise ValueError('Compute_surfs should be zero or positive')
+ if any(compute_surfs>=ns_in):
+ raise ValueError('Compute_surfs should be smaller than ns_in')
+
+
+
+
+
+
+ b.verbose = verbose
+ b.asym = 0.0;
+ b.nfp = nfp
+ b.mpol = mpol
+ b.ntor = ntor
+ b.mnmax = mnmax
+ b.mpol_nyq = mpol_nyq
+ b.ntor_nyq = ntor_nyq
+ b.mnmax_nyq = mnmax_nyq
+ b.xn = xn
+ b.xm=xm
+ b.xm_nyq = xm_nyq
+ b.xn_nyq = xn_nyq
+ b.ns_in = ns_in
+ b.s_in = s_in
+ b.iota = iota
+ b.rmnc = rmnc
+ b.rmns = rmns
+ b.zmnc = zmnc
+ b.zmns = zmns
+ b.lmns = lmns
+ b.lmnc = lmnc
+ b.bmnc = Bmnc
+ b.bmns = Bmns
+ b.bsubumnc = bsubumnc
+ b.bsubvmnc = bsubvmnc
+ b.bsubumns = bsubumns
+ b.bsubvmns = bsubvmns
+ b.mboz = mboz
+ b.nboz = nboz
+ b.compute_surfs = compute_surfs
+ b.aspect = aspect
+ b.toroidal_flux = toroidal_flux
+
+
+
+ return b
diff --git a/Utilities/BoozerXForms/run_boz.py b/Utilities/BoozerXForms/run_boz.py
new file mode 100644
index 00000000..20671fcc
--- /dev/null
+++ b/Utilities/BoozerXForms/run_boz.py
@@ -0,0 +1,121 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+Created on Mon May 9 17:50:56 2022
+
+This file initialises a booz_xForms instance
+and runs it before writing all outputs to
+an hdf5 file.
+
+@author: S.Guinchard
+"""
+
+############
+# PACKAGES #
+############
+
+from init_from_spec import init_from_spec
+import matplotlib.pyplot as plt
+import booz_xform as bx
+import numpy as np
+import h5py as h5
+
+##############
+# INIT + RUN #
+##############
+
+file = 'Name'
+filename = file + '.sp.h5'
+bozout = file +'.boz.h5'
+b = init_from_spec('path_to_file'+filename)
+b.verbose = 2
+print("Selected surfaces:", b.compute_surfs)
+b.run()
+
+##########################
+# CREATE OUTPUT DATASETS #
+##########################
+
+f = h5.File('path_to_Boozer_out_file'+ bozout, 'w')
+print(f.filename)
+grp = f.create_group('Booz_xForms')
+grp.create_group('Inputs')
+inputs = grp['Inputs']
+inputs['verbose'] = b.verbose
+inputs['asym'] = b.asym
+inputs['nfp'] = b.nfp
+inputs['ntor'] = b.ntor
+inputs['mpol'] = b.mpol
+inputs['mnmax'] = b.mnmax
+inputs['mnmax_nyq'] = b.mnmax_nyq
+inputs['mpol_nyq'] = b.mpol_nyq
+inputs['ntor_nyq'] = b.ntor_nyq
+inputs['xn'] = b.xn
+inputs['xm'] = b.xm
+inputs['xn_nyq'] = b.xn_nyq
+inputs['xm_nyq'] = b.xm_nyq
+inputs['ns_in'] = b.ns_in
+inputs['iota'] = b.iota
+inputs['rmnc'] = b.rmnc
+inputs['rmns'] = b.rmns
+inputs['zmnc'] = b.zmnc
+inputs['zmns'] = b.zmns
+inputs['bmn'] = b.bmnc
+inputs['bsubumnc'] = b.bsubumnc
+inputs['bsubvmnc'] = b.bsubvmnc
+inputs['compute_surfs'] = b.compute_surfs
+inputs['aspect'] = b.aspect
+inputs['toroidal_flux'] = b.toroidal_flux
+inputs['mboz'] = b.mboz
+inputs['nboz'] = b.nboz
+inputs['lmns'] = b.lmns
+inputs['lmnc'] = b.lmnc
+
+grp.create_group('Outputs')
+outputs = grp['Outputs']
+outputs.create_dataset('ns_b', data = b.ns_b)
+outputs.create_dataset('s_b', data = b.s_b)
+outputs.create_dataset('mnboz', data = b.mnboz)
+outputs.create_dataset('xm_b', data = b.xm_b)
+outputs.create_dataset('xn_b', data = b.xn_b)
+outputs.create_dataset('bmnc_b', data = b.bmnc_b)
+outputs.create_dataset('bmns_b', data = b.bmns_b)
+outputs.create_dataset('gmnc_b', data = b.gmnc_b)
+outputs.create_dataset('gmns_b', data = b.gmns_b)
+outputs.create_dataset('rmnc_b', data = b.rmnc_b)
+outputs.create_dataset('zmnc_b', data = b.zmnc_b)
+outputs.create_dataset('rmns_b', data = b.rmns_b)
+outputs.create_dataset('zmns_b', data = b.zmns_b)
+outputs.create_dataset('numnc_b', data = b.numnc_b)
+outputs.create_dataset('numns_b', data = b.numns_b)
+outputs.create_dataset('boozer_g', data = b.Boozer_G)
+outputs.create_dataset('boozer_g_all', data = b.Boozer_G_all)
+outputs.create_dataset('boozer_i', data = b.Boozer_I)
+outputs.create_dataset('boozer_i_all', data = b.Boozer_I_all)
+
+
+f.close()
+
+
+
+###########
+# FIGURES #
+###########
+
+plt.figure
+bx.surfplot(b, js=0, fill=False, cmap=plt.cm.jet, ntheta=50, nphi=90, ncontours=25)
+plt.savefig('Contour.eps')
+plt.show()
+
+
+plt.figure
+bx.surfplot(b, js=0, cmap=plt.cm.jet, shading = 'gouraud')
+plt.savefig('Filled.eps')
+plt.show()
+
+# ANOTHER EXAMPLE
+# plt.figure
+# bx.surfplot(b, js=0, fill=False, cmap=plt.cm.jet, levels=np.arange(0.8, 1.3, 0.05))
+# plt.show()
+
+
diff --git a/Utilities/BoozerXForms/testBmn.py b/Utilities/BoozerXForms/testBmn.py
new file mode 100644
index 00000000..9272ce94
--- /dev/null
+++ b/Utilities/BoozerXForms/testBmn.py
@@ -0,0 +1,100 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+Created on Mon May 9 13:32:45 2022
+
+This file enables to test if the modB
+Fourier modes were correctly implemented
+in Python, in order to pass them as a
+Booz_X_Form input
+
+@author: S.Guinchard
+"""
+import py_spec as sp
+import booz_xform as bx
+import numpy as np
+import matplotlib.pyplot as plt
+import h5py as h5
+
+
+d = sp.SPECout('Filename.sp.h5')
+
+verbose = 1
+asym = False
+nfp = d.input.physics.Nfp
+mpol = d.input.physics.Mpol
+ntor = d.input.physics.Ntor
+nvol = d.input.physics.Nvol
+mnmax = d.output.mn
+mpol_nyq = mpol
+ntor_nyq = ntor
+mnmax_nyq = mnmax
+xm = d.output.im
+xn = d.output.in_
+xm_nyq = xm
+xn_nyq = xn
+ns_in = int(2*nvol-1)
+s_in = np.ndarray(ns_in, dtype = np.float64)
+s_in[0] = d.output.tflux;
+iota = d.transform.fiota[1][:]
+rmnc = d.output.Rbc
+rmns = d.output.Rbs
+zmnc = d.output.Zbc
+zmns = d.output.Zbs
+lmns = d.output.lambdamn[1][:]
+
+bsubumnc = d.output.Btemn
+bsubvmnc = d.output.Bzemn
+mboz = np.max(xm)
+nboz = int(1/nfp * np.max(xn))
+aspect = np.nan
+toroidal_flux = d.input.physics.phiedge
+
+######## MOD B ########
+
+Nt = d.grid.Nt
+Nz = d.grid.Nz
+sarr = np.linspace(0,1,2)
+tarr = np.linspace(0,2*np.pi,Nt)
+zarr = np.linspace(0,2*np.pi/nfp,Nz)
+
+Bcontrav = d.get_B(lvol = 0, sarr = sarr, tarr = tarr, zarr = zarr)
+[R, Z, jac, g] = d.get_grid_and_jacobian_and_metric(lvol = 0, sarr = sarr, tarr= tarr, zarr = zarr)
+modB = d.get_modB(Bcontrav, g)
+modBsurf = modB[1][:][:]
+modBcos = np.zeros(np.shape(modBsurf))
+K = 2*np.pi**2/nfp
+Bmn_ = np.zeros((mpol+1,2*ntor+1))
+X,Y = np.meshgrid(tarr, zarr)
+
+
+
+for m in range (0,mpol):
+ for n in range (-ntor,ntor):
+ if m == 0 and n<0:
+ continue
+
+ modBcos = modBsurf * np.cos(np.double(m)*X - np.double(n)*np.double(nfp)*Y)
+ tmp = np.trapz(modBcos, x=tarr, axis = 0)
+ Bmn_[m,n+ntor] = 1/K*np.trapz(tmp, x=zarr)
+
+Bmn_[0,ntor] = 1/2*Bmn_[0,ntor]
+
+
+Bmn = np.zeros((mnmax_nyq,))
+Bmn_trunc = np.zeros((mpol,2*ntor+1))
+
+for jj in range(0,mpol):
+ Bmn_trunc[jj][:] = Bmn_[jj+1][:]
+Bmn_trunc = np.reshape(Bmn_trunc, np.size(Bmn_trunc))
+
+for ii in range(-ntor,0):
+ Bmn[ii+ntor] = Bmn_[0][ii+2*ntor]
+
+
+for ll in range(0,np.size(Bmn_trunc)):
+ Bmn[ll+ntor+1] = Bmn_trunc[ll]
+
+
+print('Bmn_ = ', Bmn_)
+
diff --git a/Utilities/matlabtools/SPEC_Namelist/SPEC_Namelist.m b/Utilities/matlabtools/SPEC_Namelist/SPEC_Namelist.m
new file mode 100644
index 00000000..49c1609f
--- /dev/null
+++ b/Utilities/matlabtools/SPEC_Namelist/SPEC_Namelist.m
@@ -0,0 +1,1760 @@
+classdef SPEC_Namelist
+ properties (Access=public)
+ lists
+ physicslist
+ numericlist
+ locallist
+ globallist
+ diagnosticslist
+ screenlist
+ initial_guess
+ end
+
+ properties (Access=private)
+ mpol = 0;
+ ntor = 0;
+ array_size = [0, 0];
+ Mvol = 0;
+ nvol = 0;
+ verbose = true;
+ lboundary = 0;
+
+ end
+
+ methods (Access=public)
+ % Class constructor
+ function obj = SPEC_Namelist( filename, varargin )
+ %
+ % SPEC_NAMELIST( FILENAME )
+ % =========================
+ %
+ % Class constructor of the class SPEC_Namelist. This class
+ % reads the SPEC input file, checks that the data is correctly
+ % formatted, allow some plottings and easy changes in the input
+ % file, and provides a routine to write SPEC input file.
+ %
+ % INPUTS
+ % ------
+ % -FILENAME: SPEC input file (.sp)
+ % -VArArGIN: Any couple of input:
+ % - 'Liniguess': set to true to read initial guess, false
+ % to skip it. default: true
+ %
+ %
+ % OUTPUTS
+ % -------
+ % -OBJ: An instance of the class SPEC_Namelist
+ %
+ %
+
+ % read optional input
+ l = length(varargin);
+ if mod(l,2)~=0
+ error('InputError: invalid number of inputs')
+ end
+
+ opt.Liniguess = true; % Decide whether or not we read initial guess
+ opt.verbose = true; % Print additional warnings
+ for ii=1:l/2
+ opt.(varargin{2*ii-1}) = varargin{2*ii};
+ end
+
+ obj.verbose = opt.verbose;
+
+ % read input file
+ work = read_namelist( filename );
+ obj.lists = fields(work);
+ for ii=1:length(obj.lists)
+ obj.(obj.lists{ii}) = work.(obj.lists{ii});
+ end
+
+ % Check that the size of arrays makes sense, fills with zeros
+ % otherwise
+ obj = obj.initialize_structure();
+
+ % Find the largest Fourier resolution used in the input file;
+ % reformat all spectral quantities to have the same resolution
+ obj = obj.set_fourier_resolution();
+
+ % read initial guess
+ if opt.Liniguess
+ obj = obj.read_initial_guess( filename );
+ else
+ obj.initial_guess = struct([]);
+ end
+
+ end
+
+ function obj = read_initial_guess( obj, filename )
+ %
+ % READ_INITIAL_GUESS( FILENAME )
+ % ==============================
+ %
+ % read the initial guess from the input file filename.
+ %
+ % If the Fourier resolution of the initial guess is larger than
+ % the Fourier resolution of the other physical qunatities, these
+ % are extended with zeros.
+ %
+ % If the initial guess requires less Fourier harmonics, then it
+ % is extended with zeros to match the Fourier resolution of the
+ % other physical quantities
+ %
+ % If no initial guess are provided in filename, return an empty
+ % structure.
+
+
+ % First, open file and read relevant portion. We look for the
+ % end of the category "screenlist" and then read each line.
+ % Each line is then saved as a string in a structure.
+ fid = fopen( filename, 'r' );
+ save_line = false; % This is switched to true once
+ % we are at the end of the screelist
+ category = ''; % Save the name of the category
+
+ initial_guess_str = {};
+
+ while( ~feof(fid) ) % while it is not the end of the file
+
+ tline = fgetl(fid);
+ tline = strtrim(tline);
+
+ if isempty( tline )
+ continue
+ end
+
+ if( save_line ) % write line
+ initial_guess_str{end+1} = tline;
+
+ else % otherwise look for beginning of initial guess
+ if( strcmp(tline, '/') )
+ if( strcmp(category,'screenlist') )
+ save_line = true;
+ end
+
+ else
+ % read category
+ if strcmp(tline(end-3:end),'list')
+ category = tline(2:end);
+ end
+
+ end
+ end
+ end % end of while
+
+ fclose(fid); % Close file
+
+ % Check if structure is empty - i.e. no initial guess is
+ % provided
+ if isempty( initial_guess_str )
+ obj.initial_guess = struct([]); % generate empty structure
+ return
+ end
+
+ % Check size. The number of elements should be 2 + 4 * Nvol.
+ % The first two elements are the mode numbers m and n, then we
+ % have Rbc, Zbs, Rbs, Zbc for each volume interface
+ l = length(str2num( initial_guess_str{1} ));
+ l = l-2; % remove m, n
+ if mod(l,4)~=0
+ error('Invalid number of modes in initial guess')
+ end
+
+ if l/4obj.nvol
+ error('Too many volumes in initial guess')
+ end
+
+ % read format of initial guess
+ tmp = SPEC_Namelist( filename, 'Liniguess', false );
+
+ if tmp.physicslist.lboundary~=obj.physicslist.lboundary
+ error(['The initial guess from file %s does not use the',...
+ 'same boundary representation.'], filename)
+ end
+
+ % Check if there is an initial guess
+ nlines = length(initial_guess_str);
+ if nlines<1
+ obj.initial_guess = struct([]); % generate empty structure
+ return
+ end
+
+ % read mpol, ntor
+ mpol_in = 0; ntor_in = 0;
+ for iline=1:nlines
+ % Scan line
+ line_data = str2num( initial_guess_str{iline} );
+
+ % Find corresponding index
+ mm = line_data(1); nn = line_data(2);
+ mpol_in = max([mm, mpol_in]);
+ ntor_in = max([abs(nn), ntor_in]);
+ end
+
+ % Check if resolution is smaller or larger than inner
+ % resolution. This changes obj.mpol and obj.ntor if
+ % necessary
+ if (mpol_in>obj.mpol) || (ntor_in>obj.ntor)
+ obj = obj.change_fourier_resolution( mpol_in, ntor_in );
+ end
+
+ % Now format initial guess in a structure
+ switch obj.physicslist.lboundary
+ case 0 % rmn, zmn representation
+
+ % Allocate memory
+ ric = zeros(2*obj.ntor+1, obj.mpol+1, obj.Mvol);
+ ris = zeros(2*obj.ntor+1, obj.mpol+1, obj.Mvol);
+ zic = zeros(2*obj.ntor+1, obj.mpol+1, obj.Mvol);
+ zis = zeros(2*obj.ntor+1, obj.mpol+1, obj.Mvol);
+
+ % Fill initial guess arrays
+ for iline=1:nlines
+
+ % Scan line
+ line_data = str2num( initial_guess_str{iline} );
+
+ % Find corresponding index
+ m = line_data(1); n = line_data(2);
+ im = m+1;
+ in = n+obj.ntor+1;
+
+ for ivol=1:obj.nvol
+ ric(in,im,ivol) = line_data(ivol*4-1);
+ zis(in,im,ivol) = line_data(ivol*4 );
+ ris(in,im,ivol) = line_data(ivol*4+1);
+ zic(in,im,ivol) = line_data(ivol*4+2);
+ end
+ end
+
+ % Fill structure
+ obj.initial_guess.ric = ric;
+ obj.initial_guess.zis = zis;
+ obj.initial_guess.ris = ris;
+ obj.initial_guess.zic = zic;
+
+ case 1 % Henneberg representation
+
+ rhoi = zeros(2*obj.ntor+1, obj.mpol+1, obj.nvol);
+ bin = zeros(obj.ntor+1, obj.nvol);
+ r0ic = zeros(obj.ntor+1, obj.nvol);
+ z0is = zeros(obj.ntor+1, obj.nvol);
+
+ for iline=1:nlines
+
+ line_data = str2num( initial_guess_str{iline} );
+
+ m = line_data(1); n = line_data(2);
+ im = m+1;
+ in = n+obj.ntor+1;
+
+ for ivol=1:obj.nvol
+
+ if n>=0 && m==0
+ bin( n+1, ivol) = line_data(ivol*4-1);
+ r0ic(n+1, ivol) = line_data(ivol*4 );
+ z0is(n+1, ivol) = line_data(ivol*4+1);
+ end
+
+ if m>0
+ rhoi(in, im, ivol ) = line_data( ivol*4+2 );
+ end
+ end
+
+ end
+
+
+ obj.initial_guess.rhoi = rhoi;
+ obj.initial_guess.bin = bin;
+ obj.initial_guess.r0ic = r0ic;
+ obj.initial_guess.z0is = z0is;
+
+ otherwise
+ error('Invalid lboundary!')
+ end
+
+ end
+
+
+ function obj = set_boundary_from_namelist( obj, filename, boundary )
+ %
+ % SET_BOUNDARY_FROM_NAMELIST( FILENAME )
+ % ======================================
+ %
+ % Read the plasma or computational boundary from another SPEC
+ % namelist and use it for the current instance
+ %
+ % INPUT
+ % -----
+ % -filename: Filename of the other SPEC input namelist
+ % -boundary: PB for Plasma Boundary or CB for computational
+ % boundary
+ %
+ % OUTPUT
+ % ------
+ % -obj: Updated output of SPEC Namelist
+
+
+ % Read input SPEC Namelist
+ nm = SPEC_Namelist( filename );
+
+ % Get relevant boundary
+ switch boundary
+ case 'PB'
+ Remn = nm.physicslist.rbc;
+ Romn = nm.physicslist.rbs;
+ Zemn = nm.physicslist.zbc;
+ Zomn = nm.physicslist.zbs;
+ case 'CB'
+ Remn = nm.physicslist.rwc;
+ Romn = nm.physicslist.rws;
+ Zemn = nm.physicslist.zwc;
+ Zomn = nm.physicslist.zws;
+ otherwise
+ error('InputError: Invalid boundary')
+ end
+
+ % Check size
+ if any(size(Remn)~=size(Romn))
+ error('Size mismatch')
+ end
+ if any(size(Remn)~=size(Zemn))
+ error('Size mismatch')
+ end
+ if any(size(Remn)~=size(Zomn))
+ error('Size mismatch')
+ end
+
+ % Get Fourier resolution
+ s = size(Remn);
+ ntor_in = (s(1)-1) / 2.0;
+ mpol_in = s(2)-1;
+
+ % Change FOurier resolution to the largest one between obj and
+ % nm
+ if mpol_in>obj.mpol
+ obj = obj.change_fourier_resolution( mpol_in, obj.ntor );
+ elseif mpol_inobj.ntor
+ obj = obj.change_fourier_resolution( obj.mpol, ntor_in );
+ elseif ntor_inobj.mpol
+ warning('M is larger than the Fourier resolution')
+ out = 0;
+ return
+ end
+
+ if abs(n)>obj.ntor
+ warning('M is larger than the Fourier resolution')
+ out = 0;
+ return
+ end
+
+ % Need to make the difference between initial guess harmonics
+ % or harmonics from the physics list. rhoi, bin, R0ic and Z0is
+ % are related to the Henneberg representation
+ if strcmp(field, 'ric') || strcmp(field, 'ris') ...
+ || strcmp(field, 'zic') || strcmp(field, 'zis') ...
+ || strcmp(field, 'rhoi') || strcmp(field, 'bin') ...
+ || strcmp(field, 'r0ic') || strcmp(field, 'z0is')
+
+ if isempty(obj.initial_guess)
+ error('No initial guess available')
+ end
+
+ ivol = varargin{1};
+
+ if ivol<1 || ivol>obj.nvol
+ error('Invalid ivol')
+ end
+
+ cat = 'initial_guess';
+
+ else
+ cat = 'physicslist';
+ ivol = 1;
+
+ end
+
+ % Read relevant harmonic
+ out = obj.(cat).(field)(n+obj.ntor+1, m+1, ivol);
+
+ end
+
+ % =================================================================
+ % Setter
+ function obj = set_harmonics_to_zero( obj, field )
+ %
+ % SET_HARMONICS_TO_ZERO( FIELD )
+ % ==============================
+ %
+ % Set all Fourier harmonics of the field to zero
+ %
+ % INPUT
+ % -----
+ % -FIELD: Field to set harmonics to zero
+ %
+ % OUTPUT
+ % ------
+ % -OBJ: Updated instance of SPEC_Namelist\
+ %
+
+
+ if strcmp(field, 'ric') || strcmp(field, 'ris') ...
+ || strcmp(field, 'zic') || strcmp(field, 'zis') ...
+ || strcmp(field, 'rhoi') || strcmp(field, 'bin') ...
+ || strcmp(field, 'r0ic') || strcmp(field, 'z0is')
+
+ cat = 'initial_guess';
+ else
+ cat = 'physicslist';
+ end
+
+ obj.(cat).(field) = zeros( obj.array_size );
+
+ end
+
+
+
+ function obj = set_fourier_harmonics( obj, field, im, in, value, varargin )
+ %
+ % SET_FOURiER_HARMONICS( FIELD, M, N, (IVOL) )
+ % ============================================
+ %
+ % Sets the fourier harmonics associated to the field,
+ % poloidal mode number m and toroidal mode number n
+ %
+ % INPUTS
+ % ------
+ % -field: 'rbc', 'zws', 'ric', ...
+ % -im : Poloidal mode number, size 1xmn
+ % -in : Toroidal mode number, size 1xmn
+ % -value: Value for the mode, size 1xmn
+ % -(ivol): Optional argument, required for fourier harmonics
+ % of the initial guess
+
+
+ % First check the input size
+ mn = length(im);
+ if length(in)~=mn
+ error('The array in has not the same length as im')
+ end
+ if length(value)~=mn
+ error('The array value has not the same length as im')
+ end
+
+ % If some modes are greater than the actual resolution,
+ % increase the resolution accordingly
+ mpol_in = max(im);
+ if mpol_in>obj.mpol
+ warning('Poloidal resolution has to be increased ...')
+ obj = obj.change_fourier_resolution( mpol_in, obj.ntor );
+ end
+
+ ntor_in = max(abs(in));
+ if ntor_in>obj.ntor
+ warning('Toroidal resolution has to be increased ...')
+ obj = obj.change_fourier_resolution( obj.mpol, ntor_in );
+ end
+
+ % Loop over the input harmonics
+ for imn=1:mn
+ m = im(imn);
+ n = in(imn);
+
+
+ % Check if the quantity is located in the initial guess
+ % structure or in the physicslist structure.
+ if strcmp(field, 'ric') || strcmp(field, 'ris') ...
+ || strcmp(field, 'zic') || strcmp(field, 'zis') ...
+ || strcmp(field, 'rhoi') || strcmp(field, 'bin') ...
+ || strcmp(field, 'r0ic') || strcmp(field, 'z0is')
+
+ if isempty(obj.initial_guess)
+ warning('No initial guess available... filling with zeros')
+
+ % If the initial guess is empty (i.e. no initial guess
+ % are available), then we create one filled with zeros
+ if obj.lboundary == 0
+ obj.initial_guess.ric = zeros( obj.array_size(1), obj.array_size(2), obj.nvol );
+ obj.initial_guess.ris = zeros( obj.array_size(1), obj.array_size(2), obj.nvol );
+ obj.initial_guess.zic = zeros( obj.array_size(1), obj.array_size(2), obj.nvol );
+ obj.initial_guess.zis = zeros( obj.array_size(1), obj.array_size(2), obj.nvol );
+ else
+ obj.initial_guess.rhoi = zeros( obj.array_size(1), obj.array_size(2), obj.nvol );
+ obj.initial_guess.bin = zeros( obj.ntor+1, obj.nvol );
+ obj.initial_guess.r0ic = zeros( obj.ntor+1, obj.nvol );
+ obj.initial_guess.z0is = zeros( obj.ntor+1, obj.nvol );
+ end
+ end
+
+ ivol = varargin{1};
+
+ if ivol<1 || ivol>obj.nvol
+ error('Invalid ivol')
+ end
+
+ obj.initial_guess.(field)(n+obj.ntor+1, m+1, ivol) = value(imn);
+
+ else
+
+ obj.physicslist.(field)(n+obj.ntor+1, m+1) = value(imn);
+
+
+ end
+ end
+
+ end
+
+ function obj = truncate_fourier_series( obj, mpol, ntor )
+ %
+ % TRUNCATE_FOURiER_SERiES( mpol, ntor )
+ % =====================================
+ %
+ % Truncates all spectral quantities to the requested poloidal
+ % and toroidal resolution This can also be used to increase
+ % the Fourier resolution.
+ %
+ % INPUTS
+ % ------
+ % -mpol: Poloidal resolution
+ % -ntor: Toroidal resolution
+ %
+ % OUTPUT
+ % ------
+ % -OBJ: Truncated instance of SPEC_Namelist
+ %
+
+ obj = obj.change_fourier_resolution( mpol, ntor );
+
+ end
+
+ function obj = change_boundary_representation( obj, new_lboundary )
+ %
+ % CHANGE_BOUNDArY_rEPrESENTATION( NEW_lbOUNDArY )
+ % ===============================================
+ %
+ % Changes from the hudson representation to the henneberg's one
+ % and vice versa.
+ %
+ % INPUT
+ % -----
+ % -new_lboundary: New value for lboundary
+
+
+ if obj.lboundary==0 && new_lboundary==1
+
+ obj.physicslist.rhomn = zeros(2*obj.ntor+1, obj.mpol);
+ obj.physicslist.shift.rhomn = [obj.ntor+1, 1];
+ obj.physicslist.bn = zeros(obj.ntor+1, 1);
+ obj.physicslist.r0c = zeros(obj.ntor+1, 1);
+ obj.physicslist.z0s = zeros(obj.ntor+1, 1);
+
+ obj.physicslist = rmfield( obj.physicslist, 'rbc' );
+ obj.physicslist = rmfield( obj.physicslist, 'rbs' );
+ obj.physicslist = rmfield( obj.physicslist, 'zbc' );
+ obj.physicslist = rmfield( obj.physicslist, 'zbs' );
+
+ elseif obj.lboundary==1 && new_lboundary==0
+ obj.physicslist.rbc = zeros(2*obj.ntor+1, obj.mpol);
+ obj.physicslist.rbs = zeros(2*obj.ntor+1, obj.mpol);
+ obj.physicslist.zbc = zeros(2*obj.ntor+1, obj.mpol);
+ obj.physicslist.zbs = zeros(2*obj.ntor+1, obj.mpol);
+
+ obj.physicslist = rmfield( obj.physicslist, 'rhomn' );
+ obj.physicslist = rmfield( obj.physicslist, 'bn' );
+ obj.physicslist = rmfield( obj.physicslist, 'r0c' );
+ obj.physicslist = rmfield( obj.physicslist, 'z0s' );
+
+ obj.physicslist.shift.rbc = [obj.ntor+1, 1];
+ obj.physicslist.shift.rbs = [obj.ntor+1, 1];
+ obj.physicslist.shift.zbc = [obj.ntor+1, 1];
+ obj.physicslist.shift.zbs = [obj.ntor+1, 1];
+
+ end
+
+ obj.physicslist.lboundary = new_lboundary;
+ obj.lboundary = new_lboundary;
+
+
+
+
+ end
+
+ % =================================================================
+ % Plotters
+ function plot_plasma_boundary( obj, nt, phi, newfig, varargin )
+ %
+ % PLOT_PLASMA_BOUNDArY
+ % ====================
+ %
+ % Plot the boundary given by rbc, zbs, rbs, zbc
+ %
+ % INPUTS
+ % ------
+ % -NT: Number of poloidal points
+ % -PHI: Toroidal angle
+ % -NEWFIG: =0: plot on gca
+ % =1: plot on a new figure
+ % =2: erase and plot on gca
+ % -varargin: Any input you could give to plot()
+ %
+ %
+
+ if obj.lboundary==0
+ rbc = obj.physicslist.rbc;
+ rbs = obj.physicslist.rbs;
+ zbc = obj.physicslist.zbc;
+ zbs = obj.physicslist.zbs;
+
+ obj.plot_surface_lb0( rbc, zbs, rbs, zbc, nt, phi, newfig, varargin{:} )
+ else
+ rhomn = obj.physicslist.rhomn;
+ bn = obj.physicslist.bn;
+ r0c = obj.physicslist.r0c;
+ z0s = obj.physicslist.z0s;
+
+ obj.plot_surface_lb1( rhomn, bn, r0c, z0s, nt, phi, newfig, varargin{:} )
+ end
+ end
+
+ function plot_computational_boundary( obj, nt, phi, VorB, newfig, varargin )
+ %
+ % PLOT_PLASMA_BOUNDArY
+ % ====================
+ %
+ % Plot the boundary given by rbc, zbs, rbs, zbc
+ %
+ % INPUTS
+ % ------
+ % -NT: Number of poloidal points
+ % -PHI: Toroidal angle
+ % -VorB: ='V'
+ % ='B'
+ % ='F'
+ % ='N'
+ % -NEWFIG: =0: plot on gca
+ % =1: plot on a new figure
+ % =2: erase and plot on gca
+ % -varargin: Any input you could give to plot()
+ %
+ %
+
+ if obj.lboundary == 0
+ rwc = obj.physicslist.rwc;
+ rws = obj.physicslist.rws;
+ zwc = obj.physicslist.zwc;
+ zws = obj.physicslist.zws;
+
+ obj.plot_surface_lb0( rwc, zws, rws, zwc, nt, phi, newfig, varargin{:} )
+ else
+ error('Not implemented')
+ end
+
+ if VorB~='N'
+ newfig = 0;
+ obj.plot_normal_field( floor(nt/10), phi, VorB, newfig )
+ end
+ end
+
+ function plot_initial_guess( obj, nt, phi, newfig, varargin )
+ %
+ % PLOT_PLASMA_BOUNDArY( NT, PHI, NEWFIG, VArArGIN )
+ % =================================================
+ %
+ % Plot the boundary given by rbc, zbs, rbs, zbc
+ %
+ % INPUTS
+ % ------
+ % -NT: Number of poloidal points
+ % -PHI: Toroidal angle
+ % -NEWFIG: =0: plot on gca
+ % =1: plot on a new figure
+ % =2: erase and plot on gca
+ % -varargin: Any input you could give to plot()
+ %
+ %
+
+ if isempty(obj.initial_guess)
+ error('No initial guess is provided')
+ end
+
+ if obj.lboundary == 0
+ for ivol=1:obj.nvol
+ ric = obj.initial_guess.ric(:,:,ivol);
+ ris = obj.initial_guess.ris(:,:,ivol);
+ zic = obj.initial_guess.zic(:,:,ivol);
+ zis = obj.initial_guess.zis(:,:,ivol);
+
+ if ivol>=2
+ newfig=0;
+ end
+
+ obj.plot_surface_lb0( ric, zis, ris, zic, nt, phi, newfig, varargin{:} )
+ end
+ else
+ for ivol=1:obj.nvol
+ rhoi = obj.initial_guess.rhoi(:,:,ivol);
+ bin = obj.initial_guess.bin(:, ivol);
+ r0ic = obj.initial_guess.r0ic(:, ivol);
+ z0is = obj.initial_guess.z0is(:, ivol);
+
+ if ivol>=2
+ newfig=0;
+ end
+
+ obj.plot_surface_lb1( rhoi, bin, r0ic, z0is, nt, phi, newfig, varargin{:} )
+ end
+ end
+ end
+
+ % =================================================================
+ % Write method
+ function write_input_file(obj, filename )
+ %
+ % WriTE_INPUT_FILE( filename )
+ % ============================
+ %
+ % Write namelist in an input file. Be careful: if the file filename
+ % provided as input exist, it will be overwritten!
+ %
+ % INPUT
+ % -----
+ % - filename: path where to save the input file.
+ %
+
+ % Set minimal toroidal resolution to one, otherwise writting
+ % routine does not detect arrays. This is not ideal and should
+ % be fixed
+ if obj.ntor==0
+ obj = obj.change_fourier_resolution( obj.mpol, 1 );
+ end
+
+ % Create a structure with the different lists
+ nlists = length(obj.lists);
+ S = struct;
+ for ii=1:nlists
+ S.(obj.lists{ii}) = obj.(obj.lists{ii});
+ end
+
+ % Create a shift quantity - this tells the writing routine how
+ % much each index has to be shifted. In MATLAB, indices start
+ % at 1, while in the FORTRAN Namelist, we want to write
+ S.shift.rbc = [obj.ntor+1, 1];
+ S.shift.rbs = [obj.ntor+1, 1];
+ S.shift.zbc = [obj.ntor+1, 1];
+ S.shift.zbs = [obj.ntor+1, 1];
+ S.shift.rwc = [obj.ntor+1, 1];
+ S.shift.rws = [obj.ntor+1, 1];
+ S.shift.zws = [obj.ntor+1, 1];
+ S.shift.zwc = [obj.ntor+1, 1];
+ S.shift.vnc = [obj.ntor+1, 1];
+ S.shift.vns = [obj.ntor+1, 1];
+ S.shift.bnc = [obj.ntor+1, 1];
+ S.shift.bns = [obj.ntor+1, 1];
+ S.shift.rhomn = [obj.ntor+1, 1];
+
+ % remove unnecessary fields
+ if obj.lboundary == 0
+ if isfield( S.physicslist, 'rhomn' )
+ S.physicslist = rmfield(S.physicslist, 'rhomn');
+ end
+ if isfield( S.physicslist, 'bn' )
+ S.physicslist = rmfield(S.physicslist, 'bn');
+ end
+ if isfield( S.physicslist, 'r0c' )
+ S.physicslist = rmfield(S.physicslist, 'r0c');
+ end
+ if isfield( S.physicslist, 'z0s' )
+ S.physicslist = rmfield(S.physicslist, 'z0s');
+ end
+
+ else % lboundary==1
+ if isfield( S.physicslist, 'rbc' )
+ S.physicslist = rmfield(S.physicslist, 'rbc');
+ end
+ if isfield( S.physicslist, 'rbs' )
+ S.physicslist = rmfield(S.physicslist, 'rbs');
+ end
+ if isfield( S.physicslist, 'zbc' )
+ S.physicslist = rmfield(S.physicslist, 'zbc');
+ end
+ if isfield( S.physicslist, 'zbs' )
+ S.physicslist = rmfield(S.physicslist, 'zbs');
+ end
+
+ end
+
+ if obj.physicslist.lfreebound==0 % Then no need to freeboundary info
+ if isfield( S.physicslist, 'rwc' )
+ S.physicslist = rmfield(S.physicslist, 'rwc');
+ end
+ if isfield( S.physicslist, 'rws' )
+ S.physicslist = rmfield(S.physicslist, 'rws');
+ end
+ if isfield( S.physicslist, 'zwc' )
+ S.physicslist = rmfield(S.physicslist, 'zwc');
+ end
+ if isfield( S.physicslist, 'zws' )
+ S.physicslist = rmfield(S.physicslist, 'zws');
+ end
+ if isfield( S.physicslist, 'vnc' )
+ S.physicslist = rmfield(S.physicslist, 'vnc');
+ end
+ if isfield( S.physicslist, 'vns' )
+ S.physicslist = rmfield(S.physicslist, 'vns');
+ end
+ if isfield( S.physicslist, 'bnc' )
+ S.physicslist = rmfield(S.physicslist, 'bnc');
+ end
+ if isfield( S.physicslist, 'bns' )
+ S.physicslist = rmfield(S.physicslist, 'bns');
+ end
+
+ end
+
+
+ % Build initial guess strings
+ if obj.physicslist.lboundary==0
+ if ~isempty(obj.initial_guess)
+ s = size(obj.initial_guess.ric);
+ initialguess = cell(1, s(1)*s(2));
+ iline=0;
+ for ii=1:s(1)
+ for jj=1:s(2)
+ iline = iline+1;
+ mm = jj-1;
+ nn = ii-obj.ntor-1;
+
+ initialguess{iline} = sprintf( '%i %i ', mm, nn );
+ for ivol=1:s(3)
+ initialguess{iline} = sprintf( '%s %0.12E %0.12E %0.12E %0.12E', initialguess{iline}, ...
+ obj.initial_guess.ric(ii,jj,ivol), ...
+ obj.initial_guess.zis(ii,jj,ivol), ...
+ obj.initial_guess.ris(ii,jj,ivol), ...
+ obj.initial_guess.zic(ii,jj,ivol) );
+ end
+ end
+ end
+ else
+ initialguess = cell(0);
+ end
+
+ else
+
+ % Now prepare initial guess...
+ if isfield(obj.initial_guess, 'bin')
+ sb = size(obj.initial_guess.bin);
+ srho = size(obj.initial_guess.rhoi);
+ ntor = (srho(2)-1)/2.0;
+ initialguess = cell(1, sb(1) + srho(1)*srho(2));
+
+ % Modes m=0, n
+ for ii=1:sb(1)
+ nn = ii-1;
+ initialguess{ii} = sprintf('0 %i ', nn);
+ for ivol=1:sb(2)
+ initialguess{ii} = sprintf('%s %0.12E %0.12E %0.12E %0.12E', initialguess{ii}, ...
+ obj.initial_guess.bin( ii, ivol ), ...
+ obj.initial_guess.r0ic(ii, ivol ), ...
+ obj.initial_guess.z0is(ii, ivol ), 0.0 );
+ end
+ end
+
+ it = sb(1);
+ for ii=1:srho(2)
+
+ nn = ii-ntor-1;
+
+ for jj=1:srho(1)
+
+ it = it+1;
+
+ mm = jj;
+
+ initialguess{it} = sprintf('%i %i ', mm, nn);
+
+ for ivol=1:srho(3)
+
+ initialguess{it} = sprintf('%s %0.12E %0.12E %0.12E %0.12E', initialguess{ii},...
+ 0.0, 0.0, 0.0, obj.initial_guess.rhoi(ii, jj, ivol));
+
+ end
+ end
+ end
+ else
+ initialguess = cell(0);
+
+ end
+
+
+
+ end
+
+ % Call namelist writer
+ write_namelist( S, filename, initialguess );
+
+
+ end
+ end
+
+ methods (Access=private)
+
+ function obj = initialize_structure( obj )
+ %
+ % INITIALIzE_STrUCTUrE( OBJ )
+ % ===========================
+ %
+ % Use to check that all required inputs are correctly set;
+ % check that the sizes of arrays are correct. raise errors in
+ % case crucial informations is missing.
+ %
+ %
+
+ % Fill some important inputs
+ if ~isfield(obj.physicslist, 'nvol')
+ error('Missing nvol')
+ end
+ if ~isfield(obj.physicslist, 'lfreebound')
+ error('Missing lfreebound')
+ end
+
+ obj.Mvol = obj.physicslist.nvol + obj.physicslist.lfreebound;
+ obj.nvol = obj.physicslist.nvol;
+
+ if isfield(obj.physicslist, 'lboundary')
+ obj.lboundary = obj.physicslist.lboundary;
+ else
+ warning('lboundary not provided. Setting with 0...')
+ obj.lboundary = 0;
+ end
+
+ % PHYSICSLIST
+ % -----------
+ % lrad
+ if ~isfield(obj.physicslist, 'lrad') && obj.verbose
+ warning('Missing lrad. Filling with 4...')
+ obj.physicslist.lrad = ones(1,obj.Mvol) * 4;
+ else
+ % Fill potential missing elements with 4s
+ obj.physicslist.lrad(end+1:obj.Mvol) = 4;
+ end
+
+ % tflux
+ if ~isfield(obj.physicslist, 'tflux') && obj.verbose
+ warning('Missing tflux. Filling equal radial distances')
+ obj.physicslist.tflux = (1:obj.Mvol).^2;
+ else
+ if length(obj.physicslist.tflux)~=obj.Mvol
+ error('Invalid number of tflux elements')
+ end
+ end
+
+ % pflux
+ if ~isfield(obj.physicslist, 'pflux')
+ warning('Missing pflux. Filling with 0...')
+ obj.physicslist.pflux = zeros(1,obj.Mvol);
+ else
+ % Fill potential missing elements with zeros
+ obj.physicslist.pflux(end+1:obj.Mvol) = 0;
+ end
+
+ % helicity
+ if ~isfield(obj.physicslist, 'helicity')
+ warning('Missing lrad. Filling with 0...')
+ obj.physicslist.helicity = zeros(1,obj.Mvol);
+ else
+ % Fill potential missing elements with zeros
+ obj.physicslist.helicity(end+1:obj.Mvol) = 0;
+ end
+
+ % pscale
+ if ~isfield(obj.physicslist, 'pscale')
+ warning('Missing pscale. Setting to zero...')
+ obj.physicslist.pscale = 0.0;
+ end
+
+ % ladiabatic
+ if ~isfield(obj.physicslist, 'ladiabatic')
+ warning('Missing ladiabatic. Setting to zero...')
+ obj.physicslist.ladiabatic = 0.0;
+ end
+
+ % Pressure
+ if ~isfield(obj.physicslist, 'pressure')
+ warning('Missing pressure. Filling with 0...')
+ obj.physicslist.pressure = zeros(1,obj.Mvol);
+ else
+ % Fill potential missing elements with zeros
+ obj.physicslist.pressure(end+1:obj.Mvol) = 0;
+ end
+
+ % Adiabatic
+ if obj.physicslist.ladiabatic==1
+ if ~isfield(obj.physicslist, 'adiabatic')
+ warning('Missing adiabatic. Filling with 0...')
+ obj.physicslist.adiabatic = zeros(1,obj.Mvol);
+ else
+ % Fill potential missing elements with zeros
+ obj.physicslist.adiabatic(end+1:obj.Mvol) = 0;
+ end
+ end
+
+ % mu
+ if ~isfield(obj.physicslist, 'mu')
+ warning('Missing mu. Filling with 0...')
+ obj.physicslist.mu = zeros(1,obj.Mvol);
+ else
+ % Fill potential missing elements with zeros
+ obj.physicslist.mu(end+1:obj.Mvol) = 0;
+ end
+
+ % lconstraint
+ if ~isfield(obj.physicslist, 'lconstraint')
+ warning('Missing lconstraint. Setting to 0...')
+ obj.physicslist.lconstraint = 0;
+ end
+
+ if ~any(obj.physicslist.lconstraint==[0,1,2,3])
+ error('Invalid lconstraint')
+ end
+
+
+ % Ivolume, Isurf
+ if obj.physicslist.lconstraint==3
+ if ~isfield(obj.physicslist, 'Ivolume')
+ warning('Missing Ivolume. Filling with 0...')
+ obj.physicslist.Ivolume = zeros(1,obj.Mvol);
+ else
+ % Fill potential missing elements with zeros
+ obj.physicslist.Ivolume(end+1:obj.Mvol) = 0;
+ end
+ if ~isfield(obj.physicslist, 'Isurf')
+ warning('Missing Isurf. Filling with 0...')
+ obj.physicslist.Isurf = zeros(1,obj.Mvol);
+ else
+ % Fill potential missing elements with zeros
+ obj.physicslist.Isurf(end+1:obj.Mvol) = 0;
+ end
+ end
+
+ if obj.physicslist.lconstraint==1
+ if ~isfield(obj.physicslist, 'iota')
+ warning('Missing iota. Filling with sqrt(2)...')
+ obj.physicslist.iota = sqrt(2)*ones(1,obj.Mvol);
+ else
+ % Fill potential missing elements with zeros
+ obj.physicslist.iota(end+1:obj.Mvol) = sqrt(2);
+ end
+ if ~isfield(obj.physicslist, 'oita')
+ warning('Missing oita. Filling with sqrt(2)...')
+ obj.physicslist.oita = sqrt(2)*ones(1,obj.Mvol);
+ else
+ % Fill potential missing elements with zeros
+ obj.physicslist.oita(end+1:obj.Mvol) = sqrt(2);
+ end
+ end
+
+ % mupftol
+ if ~isfield(obj.physicslist, 'mupftol')
+ warning('Missing mupftol. Setting to 1E-12...')
+ obj.physicslist.mupftol = 1E-12;
+ end
+
+ % mupfits
+ if ~isfield(obj.physicslist, 'mupfits')
+ warning('Missing mupfits. Setting to 128...')
+ obj.physicslist.mupfits = 128;
+ end
+
+ % Check geometry
+ if ~isfield(obj.physicslist, 'mpol')
+ error('Missing mpol information')
+ end
+ if ~isfield(obj.physicslist, 'ntor')
+ error('Missing ntor information')
+ end
+ if ~isfield(obj.physicslist, 'lboundary')
+ warning('Missing lboundary. Setting to zero')
+ obj.physicslist.lboundary = 0;
+ end
+
+ mpol_in = obj.physicslist.mpol;
+ ntor_in = obj.physicslist.ntor;
+
+ if obj.lboundary==0
+ if ~isfield(obj.physicslist, 'rbc')
+ obj.physicslist.shift.rbc = [ntor_in+1, 1];
+ obj.physicslist.rbc = zeros(2*ntor_in+1, mpol_in);
+ end
+ if ~isfield(obj.physicslist, 'rbs')
+ obj.physicslist.shift.rbs = [ntor_in+1, 1];
+ obj.physicslist.rbs = zeros(2*ntor_in+1, mpol_in);
+ end
+ if ~isfield(obj.physicslist, 'zbc')
+ obj.physicslist.shift.zbc = [ntor_in+1, 1];
+ obj.physicslist.zbc = zeros(2*ntor_in+1, mpol_in);
+ end
+ if ~isfield(obj.physicslist, 'zbs')
+ obj.physicslist.shift.zbs = [ntor_in+1, 1];
+ obj.physicslist.zbs = zeros(2*ntor_in+1, mpol_in);
+ end
+
+ % Check that sizes are consistent with each others
+ if any(size(obj.physicslist.rbc)~=size(obj.physicslist.rbs))
+ error('Size mismatch between rbc and rbs')
+ end
+ if any(size(obj.physicslist.rbc)~=size(obj.physicslist.zbc))
+ error('Size mismatch between rbc and zbc')
+ end
+ if any(size(obj.physicslist.rbc)~=size(obj.physicslist.zbs))
+ error('Size mismatch between rbc and zbs')
+ end
+
+
+ else %lboundary==1
+ if ~isfield( obj.physicslist, 'bn' )
+ obj.physicslist.bn = zeros( ntor_in+1, 1 );
+ end
+
+ % Now fill missing elements with zeros
+ obj.physicslist.bn(end+1:ntor_in+1) = 0.0;
+
+ if ~isfield( obj.physicslist, 'r0c' )
+ obj.physicslist.r0c = zeros( ntor_in+1, 1 );
+ end
+
+ % Now fill missing elements with zeros
+ obj.physicslist.r0c(end+1:ntor_in+1) = 0.0;
+
+ if ~isfield( obj.physicslist, 'z0s' )
+ obj.physicslist.z0s = zeros( ntor_in+1, 1 );
+ end
+
+ % Now fill missing elements with zeros
+ obj.physicslist.z0s(end+1:ntor_in+1) = 0.0;
+
+ if ~isfield( obj.physicslist, 'rhomn' )
+ obj.physicslist.shift.rhomn = [ntor_in+1, 1];
+ obj.physicslist.rhomn = zeros( 2*ntor_in+1, mpol_in+1 );
+ end
+
+ % Check sizes
+ if any(length(obj.physicslist.bn)~=ntor_in+1)
+ obj.physicslist.bn(end+1:ntor_in+1) = 0;
+ obj.physicslist.bn = obj.physicslist.bn(ntor_in+1);
+ end
+ if any(length(obj.physicslist.r0c)~=ntor_in+1)
+ obj.physicslist.r0c(end+1:ntor_in+1) = 0;
+ obj.physicslist.r0c = obj.physicslist.r0c(ntor_in+1);
+ end
+ if any(length(obj.physicslist.z0s)~=ntor_in+1)
+ obj.physicslist.z0s(end+1:ntor_in+1) = 0;
+ obj.physicslist.z0s = obj.physicslist.z0s(ntor_in+1);
+ end
+
+
+ end
+
+
+
+ if ~isfield(obj.physicslist, 'rwc')
+ obj.physicslist.shift.rwc = [ntor_in+1, 1];
+ obj.physicslist.rwc = zeros(2*ntor_in+1, mpol_in);
+ end
+ if ~isfield(obj.physicslist, 'rws')
+ obj.physicslist.shift.rws = [ntor_in+1, 1];
+ obj.physicslist.rws = zeros(2*ntor_in+1, mpol_in);
+ end
+ if ~isfield(obj.physicslist, 'zwc')
+ obj.physicslist.shift.zwc = [ntor_in+1, 1];
+ obj.physicslist.zwc = zeros(2*ntor_in+1, mpol_in);
+ end
+ if ~isfield(obj.physicslist, 'zws')
+ obj.physicslist.shift.zws = [ntor_in+1, 1];
+ obj.physicslist.zws = zeros(2*ntor_in+1, mpol_in);
+ end
+
+ % Check that sizes are consistent with each others
+ if any(size(obj.physicslist.rwc)~=size(obj.physicslist.rws))
+ error('Size mismatch between rwc and rws')
+ end
+ if any(size(obj.physicslist.rwc)~=size(obj.physicslist.zwc))
+ error('Size mismatch between rwc and zwc')
+ end
+ if any(size(obj.physicslist.rwc)~=size(obj.physicslist.zws))
+ error('Size mismatch between rwc and zws')
+ end
+
+
+
+ if ~isfield(obj.physicslist, 'vnc')
+ obj.physicslist.shift.vnc = [ntor_in+1, 1];
+ obj.physicslist.vnc = zeros(2*ntor_in+1, mpol_in);
+ end
+ if ~isfield(obj.physicslist, 'vns')
+ obj.physicslist.shift.vns = [ntor_in+1, 1];
+ obj.physicslist.vns = zeros(2*ntor_in+1, mpol_in);
+ end
+ if ~isfield(obj.physicslist, 'bnc')
+ obj.physicslist.shift.bnc = [ntor_in+1, 1];
+ obj.physicslist.bnc = zeros(2*ntor_in+1, mpol_in);
+ end
+ if ~isfield(obj.physicslist, 'bns')
+ obj.physicslist.shift.bns = [ntor_in+1, 1];
+ obj.physicslist.bns = zeros(2*ntor_in+1, mpol_in);
+ end
+
+ % Check that sizes are consistent with each others
+ if any(size(obj.physicslist.vnc)~=size(obj.physicslist.vns))
+ error('Size mismatch between vnc and vns')
+ end
+ if any(size(obj.physicslist.bnc)~=size(obj.physicslist.bnc))
+ error('Size mismatch between bnc and bns')
+ end
+
+ % DIAGNOSTICSLIST
+ % ---------------
+ if ~isfield(obj.diagnosticslist, 'nppts')
+ warning('Missing nppts. Setting to zero')
+ obj.diagnosticslist.nppts = 0;
+ end
+
+ if ~isfield(obj.diagnosticslist, 'nptrj')
+ warning('Missing nptrj. Setting to zero')
+ obj.diagnosticslist.nptrj = 0;
+ end
+ end
+
+
+ function obj = change_fourier_resolution( obj, mpol_new, ntor_new )
+ %
+ % CHANGE_FOUriEr_rESOLUTION( mpol_NEW, ntor_NEW )
+ % ===============================================
+ %
+ % Change inner Fourier resolution of an instance of
+ % SPEC_Namelist.
+ %
+ % INPUTS
+ % ------
+ % -mpol_new: New poloidal resolution
+ % -ntor_new: New toroidal resolution
+ %
+ % OUTPUT
+ % ------
+ % -obj: Updated instance of SPEC_Namelist
+ %
+
+ if mpol_new<1
+ error('InputError, mpol_new should be larger than 0')
+ end
+ if ntor_new<0
+ error('InputError, ntor_new should be larger or equal to zero')
+ end
+
+ obj.mpol = mpol_new;
+ obj.ntor = ntor_new;
+ obj.array_size = [2*obj.ntor+1, obj.mpol+1];
+
+ % Check that all arrays have the same size; otherwise, fill
+ % with zeros the missing elements
+ if obj.lboundary == 0
+ if any(size(obj.physicslist.rbc)~=obj.array_size)
+ obj = obj.reshape_array( 'rbc' );
+ obj = obj.reshape_array( 'rbs' );
+ obj = obj.reshape_array( 'zbc' );
+ obj = obj.reshape_array( 'zbs' );
+ end
+
+ if any(size(obj.physicslist.rwc)~=obj.array_size)
+ obj = obj.reshape_array( 'rwc' );
+ obj = obj.reshape_array( 'rws' );
+ obj = obj.reshape_array( 'zwc' );
+ obj = obj.reshape_array( 'zws' );
+ end
+ else
+ if any(size(obj.physicslist.rhomn)~=obj.array_size)
+ obj = obj.reshape_array( 'rhomn' );
+ end
+
+ if any(size(obj.physicslist.bn)~=[obj.ntor+1, 1])
+ obj.physicslist.bn(end+1:obj.ntor+1) = 0;
+ obj.physicslist.bn = obj.physicslist.bn(1:obj.ntor+1);
+ end
+ if any(size(obj.physicslist.r0c)~=[obj.ntor+1, 1])
+ obj.physicslist.r0c(end+1:obj.ntor+1) = 0;
+ obj.physicslist.r0c = obj.physicslist.r0c(1:obj.ntor+1);
+ end
+ if any(size(obj.physicslist.z0s)~=[obj.ntor+1, 1])
+ obj.physicslist.z0s(end+1:obj.ntor+1) = 0;
+ obj.physicslist.z0s = obj.physicslist.z0s(1:obj.ntor+1);
+ end
+
+ end
+
+
+ if any(size(obj.physicslist.vnc)~=obj.array_size)
+ obj = obj.reshape_array( 'vnc' );
+ obj = obj.reshape_array( 'vns' );
+ end
+
+ if any(size(obj.physicslist.bnc)~=obj.array_size)
+ obj = obj.reshape_array( 'bnc' );
+ obj = obj.reshape_array( 'bns' );
+ end
+ end
+
+
+ function obj = set_fourier_resolution( obj )
+ %
+ % SET_FOUriEr_rESOLUTION( OBJ )
+ % =============================
+ %
+ % Set the obj internal Fourier resolution to the maximal value
+ % required to store the given data; then, reshapees all arrays
+ % to have the size obj.array_size.
+ %
+ % Check beforehand that the resolution of rbc is the same as
+ % rbs, zbc and zbs. Do something similar for vnc, vns, bnc, bns
+ % and rwc, rws, zws, zwc.
+ %
+
+
+ % Find largest Fourier resolution in the input file
+ mpol_in = obj.physicslist.mpol;
+ ntor_in = obj.physicslist.ntor;
+
+ if obj.lboundary == 0
+ s_bc = size(obj.physicslist.rbc);
+ shift = obj.physicslist.shift.rbc(1);
+ mpol_bc = s_bc(2)-1 ;
+ ntor_bc = max([abs(1-shift), s_bc(1)-shift]);
+ else
+ s_bc = size(obj.physicslist.rhomn);
+ shift = obj.physicslist.shift.rhomn(1);
+ mpol_bc = s_bc(2)-1;
+
+ lbn = length( obj.physicslist.bn );
+ lrc = length( obj.physicslist.r0c );
+ lzs = length( obj.physicslist.z0s );
+ ntor_bc = max([abs(1-shift), s_bc(1)-shift, lbn, lrc, lzs]);
+ end
+
+ s_wc = size(obj.physicslist.rwc);
+ shift = obj.physicslist.shift.rwc(1);
+ mpol_wc = s_wc(2)-1 ;
+ ntor_wc = max([abs(1-shift), s_wc(1)-shift]);
+
+ s_vb = size(obj.physicslist.vnc);
+ shift = obj.physicslist.shift.vnc(1);
+ mpol_vb = s_vb(2)-1 ;
+ ntor_vb = max([abs(1-shift), s_vb(1)-shift]);
+
+ mpol_new = max([mpol_in, mpol_bc, mpol_wc, mpol_vb]);
+ ntor_new = max([ntor_in, ntor_bc, ntor_wc, ntor_vb]);
+ obj = obj.change_fourier_resolution( mpol_new, ntor_new );
+ end
+
+
+ function obj = reshape_array( obj, field )
+ %
+ % rESHAPE_ArrAY( OBJ, FIELD )
+ % =======================================
+ %
+ % reshape the input array in a an array of size obj.array_size
+ % and fills missing elements with zeros
+ %
+ % INPUTS
+ % ------
+ % -field: Field, in obj.physicslist, to be modified
+ %
+ % OUTPUT
+ % ------
+ % -obj: Updated instance of SPEC_Namelist
+ %
+
+ array = obj.physicslist.(field);
+ shift = obj.physicslist.shift.(field);
+
+ s = size(array);
+
+ new_array = zeros(obj.array_size);
+ for ii=1:s(1)
+ for jj=1:s(2)
+ nn = ii-shift(1);
+ mm = jj-shift(2);
+
+ if abs(nn)>obj.ntor || mm>obj.mpol
+ continue
+ end
+
+ new_array(nn+obj.ntor+1, mm+1) = array(ii, jj);
+ end
+ end
+
+ obj.physicslist.(field) = new_array;
+ end
+
+
+ function plot_surface_lb0( obj, rmnc, zmns, rmns, zmnc, nt, phi, ...
+ newfig, varargin )
+ %
+ % PLOT_SUrFACE( rMNC, zMNS, rMNS, zMNC, NT, NEWFIG, VArArGIN )
+ % ===========================================================
+ %
+ % Plot a surface parametrized by the standard representation
+ %
+ % INPUTS
+ % ------
+ % -rmnc: Even Fourier modes of r, format (2*ntor+1, mpol+1)
+ % -zmns: Odd Fourier modes of z, format (2*ntor+1, mpol+1)
+ % -rmns: Odd Fourier modes of r, format (2*ntor+1, mpol+1)
+ % -zmnc: Even Fourier modes of z, format (2*ntor+1, mpol+1)
+ % -NT : Number of poloidal points
+ % -PHI : Toroidal angle
+ % -newfig: =0: plot on gca
+ % =1: plot on a new figure
+ % =2: erase and plot on gca
+ % - varargin: Any input you could give to plot()
+
+ switch newfig
+ case 0
+ hold on
+ case 1
+ figure('Color','w','Position',[200 200 900 700])
+ hold on
+ case 2
+ hold off
+ otherwise
+ error('InputError: invalid newfig')
+ end
+
+ s = size(rmnc);
+
+ if any(s~=size(rmns))
+ error('InputError: rmnc has not the same size as rmns')
+ end
+ if any(s~=size(zmns))
+ error('InputError: rmnc has not the same size as zmns')
+ end
+ if any(s~=size(zmnc))
+ error('InputError: rmnc has not the same size as zmnc')
+ end
+ if nt<1
+ error('InputError: nt should be larger than 1')
+ end
+
+ N = (s(1)-1) / 2.0;
+
+ tarr = linspace( 0, 2*pi, nt );
+ r = zeros( 1, nt );
+ z = zeros( 1, nt );
+ nfp = double(obj.physicslist.nfp);
+
+
+ for in=1:s(1)
+ nn = in-1-N;
+ for im=1:s(2)
+ mm = im-1;
+
+ arg = mm*tarr - nn*nfp*phi;
+
+ r = r + rmnc(in,im) * cos(arg) + rmns(in,im) * sin(arg);
+ z = z + zmnc(in,im) * cos(arg) + zmns(in,im) * sin(arg);
+ end
+ end
+
+ plot( r, z, varargin{:} )
+
+ axis equal
+ end
+
+
+ function plot_surface_lb1( obj, rhomn, bn, r0c, z0s, nt, phi, newfig, varargin )
+ %
+ % PLOT_SUrFACE_lb1( rHOMN, bn, r0C, z0S, NT, PHI, NEWFIG, VArArGIN )
+ % ==================================================================
+ %
+ % Plots a surface using the Henneberg representation
+ %
+ % INPUTS
+ % ------
+ % -rhomn: rho_mn harmonics, format (2*ntor+1, mpol+1)
+ % -bn: b_n harmonics, format (ntor+1, 1)
+ % -r0c: r_0c harmonics, format (ntor+1, 1)
+ % -z0s: z_0s harmonics, format (ntor+1, 1)
+ % -nt: Number of poloidal points
+ % -phi: Toroidal angle
+ % -newfig: =0: plot on gca
+ % =1: plot on a new figure
+ % =2: erase and plot on gca
+ % -varargin: Optionnal input arguments, used as inputs to
+ % plot()
+ %
+ %
+
+
+
+ switch newfig
+ case 0
+ hold on
+ case 1
+ figure('Color','w','Position',[200 200 900 700])
+ hold on
+ case 2
+ hold off
+ otherwise
+ error('InputError: invalid newfig')
+ end
+
+ s = size(rhomn);
+ N = (s(1)-1) / 2.0;
+
+ if any(length(bn)~=N+1)
+ error('InputError: bn has not the size ntor+1')
+ end
+ if any(length(r0c)~=N+1)
+ error('InputError: r0c has not the size ntor+1')
+ end
+ if any(length(z0s)~=N+1)
+ error('InputError: z0s has not the size ntor+1')
+ end
+ if nt<1
+ error('InputError: nt should be larger than 1')
+ end
+
+ tarr = linspace(0, 2*pi, nt);
+ rho = zeros(1, nt);
+ alpha = obj.physicslist.twoalpha / 2.0;
+ nfp = double(obj.physicslist.nfp);
+
+ for im=1:s(2)
+ mm = im-1;
+ for in=1:s(1)
+ nn = in-N-1;
+ rho = rho + rhomn(in,im) * cos(mm*tarr + nn*nfp*phi - alpha*nfp*phi);
+ end
+ end
+
+ r0 = 0;
+ z0 = 0;
+ b = 0;
+ for nn=0:N
+ r0 = r0 + r0c(nn+1) * cos(nn*nfp*phi);
+ b = b + bn(nn+1 ) * cos(nn*nfp*phi);
+ z0 = z0 + z0s(nn+1) * sin(nn*nfp*phi);
+ end
+
+ zeta = b.*sin( tarr - alpha*nfp*phi );
+
+ r = r0 + rho * cos(alpha*nfp*phi) - zeta * sin(alpha*nfp*phi);
+ z = z0 + rho * sin(alpha*nfp*phi) + zeta * cos(alpha*nfp*phi);
+
+ plot(r, z, varargin{:})
+ axis equal
+ end
+
+ function plot_normal_field( obj, nt, phi, VorB, newfig )
+ %
+ % PLOT_NORMAL_FIELD( NT, PHI, VORB, NEWFIG )
+ % ====================================
+ %
+ % Plots the normal field on the computational boundary as a
+ % vector field
+ %
+ % INPUTS
+ % ------
+ % -NT: Number of poloidal points
+ % -PHI: Toroidal angle
+ % -VORB: ='V': Only vacuum field
+ % ='B': Only plasma field
+ % ='F': Add vacuum to plasma field
+ % -NEWFIG: =0: plot on gca
+ % =1: plot on a new figure
+ % =2: erase and plot on gca
+
+ % First, build coordinate
+ tarr = linspace( 0, 2*pi, nt );
+ r = zeros( 1, nt );
+ z = zeros( 1, nt );
+
+ rmnc = obj.physicslist.rwc;
+ rmns = obj.physicslist.rws;
+ zmnc = obj.physicslist.zwc;
+ zmns = obj.physicslist.zws;
+
+ Nfp = double(obj.physicslist.nfp);
+
+ s = size(rmnc);
+
+ if any(s~=size(rmns))
+ error('InputError: rmnc has not the same size as rmns')
+ end
+ if any(s~=size(zmns))
+ error('InputError: rmnc has not the same size as zmns')
+ end
+ if any(s~=size(zmnc))
+ error('InputError: rmnc has not the same size as zmnc')
+ end
+ if nt<1
+ error('InputError: nt should be larger than 1')
+ end
+
+ N = (s(1)-1) / 2.0;
+ nfp = double(obj.physicslist.nfp);
+
+
+ for in=1:s(1)
+ nn = in-1-N;
+ for im=1:s(2)
+ mm = im-1;
+
+ arg = mm*tarr - nn*nfp*phi;
+
+ r = r + rmnc(in,im) * cos(arg) + rmns(in,im) * sin(arg);
+ z = z + zmnc(in,im) * cos(arg) + zmns(in,im) * sin(arg);
+ end
+ end
+
+ % Then evaluate norm of normal field
+ switch VorB
+ case 'V'
+ fmnc = obj.physicslist.vnc;
+ fmns = obj.physicslist.vns;
+ case 'B'
+ fmnc = obj.physicslist.bnc;
+ fmns = obj.physicslist.bns;
+ case 'F'
+ fmnc = obj.physicslist.bnc + obj.physicslist.vnc;
+ fmns = obj.physicslist.bns + obj.physicslist.vns;
+ otherwise
+ error('InputError: Invalid VorB')
+ end
+
+ bnorm = zeros(1, nt);
+ for mm=0:obj.mpol
+ for nn=-obj.ntor:obj.ntor
+ if mm==0 && nn<0
+ continue
+ end
+ im = mm+1;
+ in = nn+obj.ntor+1;
+ arg = mm*tarr - nn*Nfp*phi;
+
+ bnorm = bnorm + fmnc(in,im) * cos( arg ) ...
+ + fmns(in,im) * sin( arg );
+ end
+ end
+
+ bnorm = bnorm / max(bnorm);
+
+ % Evaluate normal direction
+ bnormal = zeros(2, nt);
+ dt = 1e-5;
+ for it = 1:nt
+
+ rj = 0; zj = 0; tj = tarr(it)-dt;
+ rk = 0; zk = 0; tk = tarr(it)+dt;
+ for in=1:s(1)
+ nn = in-1-N;
+ for im=1:s(2)
+ mm = im-1;
+
+ argj = mm*tj - nn*nfp*phi;
+ rj = rj + rmnc(in,im) * cos(argj) + rmns(in,im) * sin(argj);
+ zj = zj + zmnc(in,im) * cos(argj) + zmns(in,im) * sin(argj);
+
+ argk = mm*tk - nn*nfp*phi;
+ rk = rk + rmnc(in,im) * cos(argk) + rmns(in,im) * sin(argk);
+ zk = zk + zmnc(in,im) * cos(argk) + zmns(in,im) * sin(argk);
+ end
+ end
+
+ bnormal(1,it) = zk-zj ;
+ bnormal(2,it) = -(rk-rj);
+
+ bnormal(:,it) = bnorm(it) * bnormal(:,it) / sqrt(bnormal(1,it)^2+bnormal(2,it)^2);
+ end
+
+
+
+ % Plot
+ quiver( r, z, bnormal(1,:), bnormal(2,:) )
+
+
+
+ end
+ end
+
+end
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Utilities/matlabtools/SPEC_Namelist/nm_tutorial_001.md b/Utilities/matlabtools/SPEC_Namelist/nm_tutorial_001.md
new file mode 100644
index 00000000..9bd20c13
--- /dev/null
+++ b/Utilities/matlabtools/SPEC_Namelist/nm_tutorial_001.md
@@ -0,0 +1,146 @@
+# Introduction
+
+The class SPEC\_Namelist is a matlab tool to read, edit and write SPEC input files. Be careful though, always double check what kind of input file you generate - some errors are spotted by some tests in SPEC\_Namelist, but not everything is covered!
+
+In this tutorial, we will show how to read a namelist, edit its Fourier resolution and change some specific Fourier harmonics, plot the initial guess and finally write the namelist.
+
+# Reading a Namelist
+
+## Adding SPEC\_Namelist path to MATLAB
+First of all, make sure that the path to SPEC\_Namelist is provided to MATLAB. To do so, you can write
+```Matlab
+addpath(genpath('my/path/to/SPEC/Utilities/matlabtools'))
+```
+
+to check that MATLAB is using the right SPEC\_Namelist class, you can check which file it is using with the command
+```Matlab
+which SPEC_Namelist
+```
+
+## Read a SPEC input file
+To create a SPEC\_Namelist instance from a SPEC input file, you need to give its absolute or relative path to the constructor of the class. For example, try
+```Matlab
+nm = SPEC_Namelist('path/to/SPEC/InputFiles/TestCases/G3V08L3Fr.001.sp')
+```
+
+This will read the SPEC\_Namelist, create a MATLAB structure with all the input in a specific format, and check that some crucial inputs are provided. In case of missing inputs, it will print a few warnings:
+
+```Matlab
+nm = SPEC_Namelist('~/SPEC/InputFiles/TestCases/G3V08L3Fr.001.sp')
+Warning: lboundary not provided. Setting with 0...
+> In SPEC_Namelist/initialize_structure (line 972)
+ In SPEC_Namelist (line 73)
+Warning: Missing Ivolume. Filling with 0...
+> In SPEC_Namelist/initialize_structure (line 1070)
+ In SPEC_Namelist (line 73)
+Warning: Missing Isurf. Filling with 0...
+> In SPEC_Namelist/initialize_structure (line 1077)
+ In SPEC_Namelist (line 73)
+Warning: Missing lboundary. Setting to zero
+> In SPEC_Namelist/initialize_structure (line 1122)
+ In SPEC_Namelist (line 73)
+Warning: lboundary not provided. Setting with 0...
+> In SPEC_Namelist/initialize_structure (line 972)
+ In SPEC_Namelist (line 73)
+ In SPEC_Namelist/read_initial_guess (line 172)
+ In SPEC_Namelist (line 81)
+Warning: Missing Ivolume. Filling with 0...
+> In SPEC_Namelist/initialize_structure (line 1070)
+ In SPEC_Namelist (line 73)
+ In SPEC_Namelist/read_initial_guess (line 172)
+ In SPEC_Namelist (line 81)
+Warning: Missing Isurf. Filling with 0...
+> In SPEC_Namelist/initialize_structure (line 1077)
+ In SPEC_Namelist (line 73)
+ In SPEC_Namelist/read_initial_guess (line 172)
+ In SPEC_Namelist (line 81)
+Warning: Missing lboundary. Setting to zero
+> In SPEC_Namelist/initialize_structure (line 1122)
+ In SPEC_Namelist (line 73)
+ In SPEC_Namelist/read_initial_guess (line 172)
+ In SPEC_Namelist (line 81)
+
+nm =
+
+ SPEC_Namelist with properties:
+
+ lists: {6x1 cell}
+ physicslist: [1x1 struct]
+ numericlist: [1x1 struct]
+ locallist: [1x1 struct]
+ globallist: [1x1 struct]
+ diagnosticslist: [1x1 struct]
+ screenlist: [1x1 struct]
+ initial_guess: [1x1 struct]
+```
+
+## Data structure format
+SPEC\_Namelist stores SPEC input data in nested structures. All structure and data names uses lower case - be careful whenever you access the data!
+
+In addition, the class has an internal Fourier resolution, which is set by default to the largest poloidal and toroidal mode number in the input file. This resolution is a private attribute of the class and is not accessible to the user; to change it and increase or truncate all physical quantities in Fourier space to the resolution `mpol`, `ntor`, you can use
+
+```Matlab
+nm = nm.truncate_fourier_series( mpol, ntor )
+```
+
+All Fourier modes are stored in matrices of size `2*ntor+1 x mpol+1`. To get a specific mode, for example `Rbc(n,m)`, use
+```Matlab
+nm.get_fourier_harmonics( 'rbc', m, n )
+```
+
+# Modifying a SPEC\_Namelist
+To modify any input, you can simply access it as you would with any MATLAB structure. For example, to change the toroidal flux in the third volume to one, write
+```Matlab
+nm.physicslist.tflux(3) = 1;
+```
+
+For the Fourier modes, setters routines are provided. For example, to change the mode Rbc(n,m) to a value `value`, write
+```Matlab
+nm = nm.set_fourier_harmonics( 'rbc', 1, 0, value );
+```
+
+If you want to set multiple modes, you can set them by providing arrays of values for `m`, `n` and `value`. Finally, if you want to use a computational boundary, a plasma boundary or the initial guess for the internal interfaces geometry from another SPEC input, you can use respectively `nm.set_boundary_from_namelist( filename, 'CB' )`, `nm.set_boundary_from_namelist( filename, 'PB' )` or `nm.read_initial_guess(filename)`. More information can be obtained by reading the documentation.
+
+**DO NOT CHANGE HARMONICS WITHOUT THESE ROUTINES!** This might break the class and some of your input will be ignored.
+
+# Visualizing the geometry of an input
+Sometimes, SPEC crashes and it is difficult to know why. Some information can be obtained by plotting the geometry of computational boundary, the plasma boundary and the initial guess from the input file.
+
+## Plotting the plasma boundary
+To plot the plasma boundary, write
+```Matlab
+nt = 1024; %Number of poloidal points
+phi = 0; %Toroidal angle
+nm.plot_plasma_boundary( nt, phi, 1 );
+```
+
+The initial guess, if any, can be plotted with
+```Matlab
+nm.plot_initial_guess( nt, phi, 0 );
+```
+
+## Plotting the computational boundary
+Similarly, the computational boundary can be plotted with
+```Matlab
+nm.plot_computational_boundary( nt, phi, 'N', 1 );
+```
+
+If you want to see the normal field on the computational boundary, switch `'N'` to (i) `'V'` to see the coils contribution, (ii) `'B'` to see the initial guess for the plasma contribution and (iii) `'F'` for the sum of both.
+
+
+# Writing the namelist into a file
+To write the Namelist, use the built in subroutine `write_input_file(filename)`. For example, do
+```Matlab
+nm.write_input_file( 'test.sp' )
+```
+
+will write an input file called test.sp with all the relevant quantities. Some input won\'t be written if not required - for example, if `nm.physicslist.Lfreebound` is set to zero, the fields `rwc`, `rws`, `zwc` and `zws` will not be written.
+
+
+
+
+
+
+
+
+
diff --git a/Utilities/matlabtools/SPEC_Namelist/rw_namelist/license.txt b/Utilities/matlabtools/SPEC_Namelist/rw_namelist/license.txt
new file mode 100644
index 00000000..793f7d6b
--- /dev/null
+++ b/Utilities/matlabtools/SPEC_Namelist/rw_namelist/license.txt
@@ -0,0 +1,24 @@
+Copyright (c) 2012, Darien Pardinas Diaz
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the distribution
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
diff --git a/Utilities/matlabtools/SPEC_Namelist/rw_namelist/read_namelist.m b/Utilities/matlabtools/SPEC_Namelist/rw_namelist/read_namelist.m
new file mode 100755
index 00000000..7bce09c3
--- /dev/null
+++ b/Utilities/matlabtools/SPEC_Namelist/rw_namelist/read_namelist.m
@@ -0,0 +1,340 @@
+function S = read_namelist(filename)
+% S = READ_NAMELIST(FILENAME) returns the struct S containg namelists and
+% variables in the file FILENAME organised in hierachical way:
+%
+% |--VAR1
+% |--VAR2
+% |-- NMLST_A--|...
+% | |--VARNa
+% |
+% | |--VAR1
+% |-- NMLST_B--|--VAR2
+% | |...
+% S --| ... |--VARNb
+% |
+% | |--VAR1
+% |-- NMLST_M--|--VAR2
+% |...
+% |--VARNm
+%
+% Note: The function can read multidimensioal variables as well. The
+% function assumes that there is no more than one namelist section per
+% line. At this time there is no syntax checking functionality so the
+% function will crash in case of errors.
+%
+% Example:
+% NMLST = read_namelist('OPTIONS.nam');
+% NMLST.NAM_FRAC.XUNIF_NATURE = 0.1;
+% write_namelist(NMlST, 'MOD_OPTIONS.nam');
+%
+% Written by: Darien Pardinas Diaz (darien.pardinas-diaz@monash.edu)
+% Version: 1.0
+% Date: 16 Dec 2011
+
+S = struct();
+% Open and read the text file containing the namelists
+fid = fopen(filename,'r');
+c = 0;
+lines = cell(1);
+
+% Read all the text lines in namelist file
+while ~feof(fid)
+ line = fgetl(fid);
+ % Remove comments if any on the line
+ idx = find(line == '!');
+ if ~isempty(idx),
+ line = line(1:idx(1)-1);
+ end
+ if ~isempty(line),
+ c = c + 1;
+ lines{c} = line;
+ end
+end
+fclose(fid);
+
+i = 0;
+while i < c;
+ % Find a record
+ i = i + 1;
+ line = lower(lines{i});
+ idx = find(line == '&');
+ if ~isempty(idx), % i.e. a namelist start
+ line = line(idx(1) + 1:end);
+ % find next space
+ idx = find(line == ' ');
+ if ~isempty(idx),
+ namelst = lower(line(1:idx(1) - 1));
+ line = line(idx(1) + 1:end);
+ else
+ namelst = lower(line);
+ line = [];
+ end
+ nmlst_bdy = [];
+ idx = strfind(line,'/');
+ % Get the variable specification section
+ while isempty(idx) && i < c,
+ nmlst_bdy = [nmlst_bdy ' ' line];
+ i = i + 1;
+ line = lines{i};
+ idx = strfind(line,'/');
+ end
+ if ~isempty(idx) && idx(1) > 1,
+ nmlst_bdy = [nmlst_bdy ' ' line];
+ end
+ if nmlst_bdy==' '
+ S.(namelst) = struct;
+ continue
+ end
+ % Parse current namelist (set of variables)
+ [S.(namelst), shift] = parse_namelist(nmlst_bdy);
+ S.(namelst).shift = shift;
+ end
+end
+function [S, shift] = parse_namelist(strng)
+% Internal function to parse the body text of a namelist section.
+% Limitations: the following patterns are prohibited inside the literal
+% strings: '.t.' '.f.' '.true.' '.false.' '(:)'
+
+% Get all .true., .t. and .false., .f. to T and F
+strng = regexprep(strng,'\.true\.' ,'T','ignorecase');
+strng = regexprep(strng,'\.false\.','F','ignorecase');
+strng = regexprep(strng,'\.t\.','T','ignorecase');
+strng = regexprep(strng,'\.f\.','F','ignorecase');
+
+% Make evaluable the (:) expression in MATLAB if any
+strng = regexprep(strng, '\(:\)', '(1,:)');
+[strng, islit] = parse_literal_strings([strng ' ']);
+
+% Find the position of all the '='
+eq_idx = find(strng == '=');
+nvars = length(eq_idx);
+
+arg_start = eq_idx + 1;
+arg_end = zeros(size(eq_idx));
+vars = cell(nvars,1);
+S = struct;
+
+% Loop through every variable
+for k = 1:nvars
+ i = eq_idx(k) - 1;
+ % Move to the left and discard blank spaces
+ while strng(i) == ' ', i = i - 1; end
+ % Now we are over the variable name or closing parentesis
+ j = i;
+ if strng(i) == ')'
+ while strng(i) ~= '(', i = i - 1; end
+ i = i - 1;
+ % Move to the left and discard any possible blank spaces
+ while strng(i) == ' ', i = i - 1; end
+ end
+
+ % Now we are over the last character of the variable name
+ while strng(i) ~= ' ', i = i - 1; end
+
+ if k > 1, arg_end(k - 1) = i; end
+ vars{k} = ['S.' lower(strng(i + 1: j))];
+end
+
+arg_end(end) = length(strng);
+
+
+% Find all array, shift indices
+shift = struct;
+k_array = zeros(1,nvars);
+for k=1:nvars
+ v = lower(vars{k});
+
+ % Check if it is an array
+ ind_open = find(v=='(');
+ if isempty(ind_open)
+ continue
+ end
+
+ ind_close = find(v==')');
+ if isempty(ind_close)
+ continue
+ end
+
+ % Store info
+ k_array(k) = 1;
+
+ % get how many dimensions
+ v_name = lower(v(3:ind_open-1));
+ v_ind = v(ind_open+1:ind_close-1);
+
+ indices = str2num(v_ind);
+ dim = length(indices);
+
+
+ % Loop on dimensions
+ if( isfield(shift, v_name) )
+ for idim = 1:dim
+ ind = indices(idim);
+
+ % Check if shift larger
+ new_shift = 1 - ind;
+ old_shift = shift.(v_name)(idim);
+ shift.(v_name)(idim) = max( new_shift, old_shift );
+ end
+ else % First encounter with this variable
+ for idim = 1:dim
+ ind = indices(idim);
+ if ind>0
+ shift.(v_name)(idim) = 0.0;
+ else
+ shift.(v_name)(idim) = 1-ind;
+ end
+ end
+ end
+
+
+
+end
+
+
+
+% This variables are used in the eval function to evaluate True/False,
+% so don't remove it!
+T = '.true.';
+F = '.false.';
+% Loop through every variable guess variable type
+for k = 1:nvars
+ arg = strng(arg_start(k):arg_end(k));
+ arglit = islit(arg_start(k):arg_end(k))';
+
+ % Remove commas in non literal string...
+ commas = ~arglit & arg == ',';
+ if any(commas)
+ arg(commas) = ' ';
+ end
+
+ if any(arglit)
+ % We are parsing a variable that is literal string
+ arg = ['{' arg '};'];
+ elseif ~isempty(find( arg == 'T' | arg == 'F', 1))
+ % We are parsing a boolean variable
+ arg = ['{' arg '};'];
+ else
+ % We are parsing a numerical array
+ arg = ['[' arg '];'];
+ end
+
+
+ % Eval the modified syntax in Matlab
+ if k_array(k)==0
+ eval([vars{k} ' = ' arg]);
+ else % apply shift
+ v = lower(vars{k});
+ ind_open = find(v=='(');
+ ind_close = find(v==')');
+ v_name = lower(v(3:ind_open-1));
+ v_ind = v(ind_open+1:ind_close-1);
+
+ tmp = find(v_ind==',');
+ dim = length(tmp)+1;
+
+
+ %indices = str2num(v_ind);
+
+ newstr = ['S.', lower(v_name), '('];
+ for idim = 1:dim
+ if idim==1
+ ind_start=1;
+ else
+ ind_start=tmp(idim-1)+1;
+ end
+
+ if idim==dim
+ ind_end=length(v_ind);
+ else
+ ind_end=tmp(idim)-1;
+ end
+
+ strdim = v_ind(ind_start:ind_end);
+
+ indsmcl = find(strdim==':');
+
+ if isempty(indsmcl)
+ new_ind = str2num(strdim) + shift.(v_name)(idim);
+ new_ind = sprintf('%i', new_ind);
+ else
+ a = str2num(strdim(1:indsmcl-1)) + shift.(v_name)(idim);
+ b = str2num(strdim(indsmcl+1:end)) + shift.(v_name)(idim);
+ new_ind = sprintf('%i:%i', a, b);
+ end
+
+ if idim==1
+ newstr = sprintf( '%s%s', newstr, new_ind );
+ else
+ newstr = sprintf( '%s,%s', newstr, new_ind );
+ end
+
+ end
+ newstr = sprintf( '%s) = %s', newstr, arg );
+
+ eval(newstr);
+ end
+end
+function [strng, is_lit] = parse_literal_strings(strng)
+% Parse the literal declarations of strings and change to Matlab syntax
+
+len = length(strng);
+add_squote = []; % Positions to add a scape single quote on syntax
+rem_dquote = []; % Positions to remove a double quote scape on syntax
+i = 1;
+while i < len
+ if strng(i) == '''', % Opening string with single quote...
+ i = i + 1;
+ while i < len && strng(i) ~= '''' || strcmp(strng(i:i+1),'''''') ,
+ i = i + 1;
+ if strcmp(strng(i-1:i),''''''),
+ i = i + 1;
+ end
+ end
+ end
+ if strng(i) == '"', % Opening string with double quote...
+ strng(i) = ''''; % Change to single quote
+ i = i + 1;
+ while strng(i) ~= '"' || strcmp(strng(i:i+1),'""') && i < len,
+ % Check for a possible sigle quote here
+ if strng(i) == '''',
+ add_squote = [add_squote i];
+ end
+ i = i + 1;
+ if strcmp(strng(i-1:i),'""'),
+ rem_dquote = [rem_dquote i-1];
+ i = i + 1;
+ end
+ end
+ strng(i) = ''''; % Change to single quote
+ end
+ i = i + 1;
+end
+for i = 1:length(add_squote);
+ strng = [strng(1:add_squote(i)) strng(add_squote(i):end)];
+end
+for i = 1:length(rem_dquote);
+ strng = [strng(1:rem_dquote(i)-1) strng(rem_squote(i)+1:end)];
+end
+
+% Now everything should be in Matlab string syntax
+% Classify syntax as literal or regular expression
+i = 1;
+len = length(strng);
+is_lit = zeros(len,1);
+while i < len,
+ if strng(i) == '''', % Opening string with single quote...
+ is_lit(i) = 1;
+ i = i + 1;
+ while i < len && strng(i) ~= '''' || strcmp(strng(i:i+1),''''''),
+ is_lit(i) = 1;
+ i = i + 1;
+ if strcmp(strng(i-1:i),''''''),
+ is_lit(i) = 1;
+ i = i + 1;
+ end
+ end
+ is_lit(i) = 1;
+ end
+ i = i + 1;
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/SPEC_Namelist/rw_namelist/write_namelist.m b/Utilities/matlabtools/SPEC_Namelist/rw_namelist/write_namelist.m
new file mode 100755
index 00000000..9f0dedb1
--- /dev/null
+++ b/Utilities/matlabtools/SPEC_Namelist/rw_namelist/write_namelist.m
@@ -0,0 +1,100 @@
+function write_namelist(S, filename, endlines)
+% WRITE_NAMELIST(S, FILENAME) writes a namelist data structure S to a
+% file FILENAME. S should follow the following structure:
+%
+% |--VAR1
+% |--VAR2
+% |-- NMLST_A--|...
+% | |--VARNa
+% |
+% | |--VAR1
+% |-- NMLST_B--|--VAR2
+% | |...
+% S --| ... |--VARNb
+% |
+% | |--VAR1
+% |-- NMLST_M--|--VAR2
+% |...
+% |--VARNm
+%
+% Notes: Only supports variables of type:
+% Scalars, vectors and 2D numeric arrays (integers and floating points)
+% Scalars and 1D boolean arrays specified as '.true.' and '.false.' strings
+% Single and 1D arrays of strings
+%
+% Example:
+% NMLST = read_namelist('OPTIONS.nam');
+% NMLST.NAM_FRAC.XUNIF_NATURE = 0.1;
+% write_namelist(NMlST, 'MOD_OPTIONS.nam');
+%
+% Written by: Darien Pardinas Diaz (darien.pardinas-diaz@monash.edu)
+% Version: 1.0
+% Date: 16 Dec 2011
+
+fid = fopen(filename, 'w');
+name_lists = fieldnames(S);
+n_name_lists = length(name_lists);
+
+for i = 1:n_name_lists
+ % Write individual namelist records
+ if strcmp(name_lists{i}, 'shift')
+ continue
+ end
+
+ fprintf(fid, '&%s\n', name_lists{i});
+ rcrds = S.(name_lists{i});
+
+
+ rcrds_name = fieldnames(rcrds);
+ n_rcrds = length(rcrds_name);
+
+ for j = 1:n_rcrds
+ if strcmp(rcrds_name{j},'shift')
+ continue
+ end
+
+ var = rcrds.(rcrds_name{j});
+ % Find variable type...
+ if iscell(var)
+ fprintf(fid, ' %s =', rcrds_name{j});
+ if strcmp(var{1},'.true.') || strcmp(var{1},'.false.')
+ for k = 1:length(var)
+ fprintf(fid, ' %s,', var{k});
+ end
+ else
+ for k = 1:length(var)
+ fprintf(fid, ' %s,', ['''' var{k} '''']);
+ end
+ end
+ fprintf(fid, '%s\n', '');
+ else
+ [n,m] = size(var);
+ if m == 1 || n == 1
+ % Variable is a scalar or vector
+ fprintf(fid, ' %s =', rcrds_name{j});
+ fprintf(fid, ' %g,', var);
+ fprintf(fid, '%s\n', '');
+ else
+ % Varible is a two dimensional array
+ for k = 1:n
+ fprintf(fid, ' %s(%i,%i:%i) =', rcrds_name{j}, k-S.shift.(rcrds_name{j})(1), ...
+ 1-S.shift.(rcrds_name{j})(2), ...
+ m-S.shift.(rcrds_name{j})(2) );
+ fprintf(fid, ' %g,', var(k,:));
+ fprintf(fid, '%s\n', '');
+ end
+ end
+ end
+ end
+ fprintf(fid, '%s\n', '/');
+end
+
+s = length(endlines);
+for ii=1:s
+
+ fprintf(fid, '%s\n', endlines{ii});
+
+end
+
+
+
diff --git a/Utilities/matlabtools/Tutorial.01.txt b/Utilities/matlabtools/Tutorial.01.txt
index 9594c413..92391167 100644
--- a/Utilities/matlabtools/Tutorial.01.txt
+++ b/Utilities/matlabtools/Tutorial.01.txt
@@ -22,11 +22,11 @@
3. Call ploting routine for Poincare section:
- plot_spec_poincare(data,1,5,0,1);
+ plot_spec_poincare(data,1,1,1);
4. Call ploting routine for ideal-interfaces on Poincare section:
- plot_spec_kam(data,0,0);
+ plot_spec_kam(data,1,0);
%%% More details %%%
diff --git a/Utilities/matlabtools/Tutorial.02.txt b/Utilities/matlabtools/Tutorial.02.txt
index b7420250..8aaaff1a 100644
--- a/Utilities/matlabtools/Tutorial.02.txt
+++ b/Utilities/matlabtools/Tutorial.02.txt
@@ -21,7 +21,7 @@
3. Call ploting routine for |B| on the boundary surface:
- plot_spec_modB_boundary(data,2,32,64);
+ plot_spec_modB_boundary(data, 2, 0, 64, 64, 3);
3. Call ploting routine for |B| on a cross-section for volumes lvol=2 and lvol=1:
diff --git a/Utilities/matlabtools/compare_spec_outputs.m b/Utilities/matlabtools/compare_spec_outputs.m
index d4588b30..30da8e99 100644
--- a/Utilities/matlabtools/compare_spec_outputs.m
+++ b/Utilities/matlabtools/compare_spec_outputs.m
@@ -1,19 +1,27 @@
-function [Dabs, Drel, df] = compare_spec_outputs(fname1,fname2)
+function [Dabs, Drel, df] = compare_spec_outputs(data1,data2)
+%
+% COMPARE_SPEC_OUTPUTS( DATA1, DATA2 )
+% ====================================
+%
% Compares the interface geometry of two spec outputs
% Two outputs are considered "the same" if df ~ 1e-15 (or less)
%
% INPUT
-% - fname1 : path to the hdf5 output file #1
-% - fname2 : path to the hdf5 output file #2
+% -----
+% - data1: data obtained via read_spec( fname1 )
+% - data2: data obtained via read_spec( fname2 )
%
% OUTPUT
+% ------
% - Dabs : absolute maximum distance
% - Drel : relative maximum distance
% - df : expected change in force-balance if one output is used as input for the other run
%
% written by J.Loizu (08.2017)
% modified by J.Loizu (10.2017)
+%
+% TODO: UPDATE - IS THIS STILL CORRECT ?
%
% Rmn1 = h5read(fname1,'/Rbc');
@@ -23,13 +31,13 @@
% Rmn2 = h5read(fname2,'/Rbc');
% Zmn2 = h5read(fname2,'/Zbs');
-data = read_spec(fname1);
-Rmn1 = data.output.Rbc;
-Zmn1 = data.output.Zbs;
+%data = read_spec(fname1);
+Rmn1 = data1.output.Rbc;
+Zmn1 = data1.output.Zbs;
-data = read_spec(fname2);
-Rmn2 = data.output.Rbc;
-Zmn2 = data.output.Zbs;
+%data = read_spec(fname2);
+Rmn2 = data2.output.Rbc;
+Zmn2 = data2.output.Zbs;
maxR = max(max(abs(Rmn1-Rmn2)));
diff --git a/Utilities/matlabtools/contra2cov.m b/Utilities/matlabtools/contra2cov.m
index ae42ec42..be901b7c 100644
--- a/Utilities/matlabtools/contra2cov.m
+++ b/Utilities/matlabtools/contra2cov.m
@@ -8,11 +8,10 @@
%
% INPUT
% -----
-% data: via read_spec(filename)
+% data: via read_spec(filename)
% vol: volume
+% vcontrav: structure containing contravariant components as a function of r, size = 3xlength(r)
% s: radial coordinate
-% vcontrav: contravariant vector as a function of r, size = 3xlength(r)
-% ns: number of point in each volume for interpolation
% theta: theta angle
% phi: phi angle
% norm: use the unitary (canonical) basis (=1) or the general
@@ -21,74 +20,61 @@
% OUTPUT
% ------
% vcov: covariant vector as a function v
+%
+%
-% Read geometry
-G = data.input.physics.Igeometry;
-
-
-% Get R derivatives
-[s, R] = get_spec_R_derivatives(data, vol, s, theta, phi, 'R');
-[s, Z] = get_spec_R_derivatives(data, vol, s, theta, phi, 'Z');
-
-
-nt = length(theta);
-np = length(phi);
-ns = length(s);
-
-% transform in covariant basis
-g = get_spec_metric(data, vol, s, theta, phi);
-
-switch G
- case 1
- norm1 = sqrt(1 + R{3}.^2 + R{4}.^2) ./ R{2};
- norm2 = ones(size(R{1}));
- norm3 = ones(size(R{1}));
-
- case 2
- norm1 = sqrt(R{3}.^2 + R{1}.^2 + (R{1}.*R{4}).^2) ./ (R{2}.*R{1});
- norm2 = 1 ./ R{1};
- norm3 = ones(size(R{1}));
-
- case 3
- norm1 = sqrt((R{3}.*Z{4}).^2 + (R{4}.*Z{3}).^2 + (R{1}.*Z{3}).^2 ...
- -2*R{3}.*R{4}.*Z{3}.*Z{4} + (R{1}.*R{3}).^2);
- norm2 = sqrt((R{4}.*Z{2}).^2 + (R{1}.*Z{2}).^2 + (R{2}.*Z{4}).^2 + (R{1}.*R{2}).^2 ...
- -2*R{2}.*R{4}.*Z{2}.*Z{4});
- norm3 = sqrt((R{2}.*Z{3}).^2 + (R{3}.*Z{2}).^2 -2*R{2}.*R{3}.*Z{2}.*Z{3});
-
-end
+% TODO: test - is this useful ?
-% Compute covariant components
-temp = cell(1,3);
-vcov = cell(1,3);
-for ii=1:3
- temp{ii} = zeros(ns, nt, np);
- vcov{ii} = zeros(ns, nt, np);
-end
+ % Read geometry
+ G = data.input.physics.Igeometry;
+ % Get R derivatives
+ R = get_spec_R_derivatives(data, vol, s, theta, phi, 'R');
+ Z = get_spec_R_derivatives(data, vol, s, theta, phi, 'Z');
-for is = 1:ns
- for it = 1:nt
- for ip = 1:np
- temp{1} = vcontrav{1}.*g{1}{1} + vcontrav{2}.*g{1}{2} + vcontrav{3}.*g{1}{3};
- temp{2} = vcontrav{1}.*g{2}{1} + vcontrav{2}.*g{2}{2} + vcontrav{3}.*g{2}{3};
- temp{3} = vcontrav{1}.*g{3}{1} + vcontrav{2}.*g{3}{2} + vcontrav{3}.*g{3}{3};
- end
+ % transform in covariant basis
+ g = get_spec_metric(data, vol, s, theta, phi);
+
+ % Compute covariant components
+ vcov = cell(1,3);
+
+ for ii=1:3
+ vcov{ii} = zeros(size(vcontrav));
end
-end
-% Normalize to canonical basis if necessary
-if norm
- vcov{1} = temp{1} .* norm1;
- vcov{2} = temp{2} .* norm2;
- vcov{3} = temp{3} .* norm3;
-else
- vcov = temp;
-end
+ vcov{1} = vcontrav{1}.*g{1,1} + vcontrav{2}.*g{1,2} + vcontrav{3}.*g{1,3};
+ vcov{2} = vcontrav{1}.*g{2,1} + vcontrav{2}.*g{2,2} + vcontrav{3}.*g{2,3};
+ vcov{3} = vcontrav{1}.*g{3,1} + vcontrav{2}.*g{3,2} + vcontrav{3}.*g{3,3};
+
+ % Normalize to canonical basis (unit vector) if necessary
+ if norm
+
+ switch G
+ case 1
+ norm1 = sqrt(1 + R{3}.^2 + R{4}.^2) ./ R{2};
+ norm2 = ones(size(R{1}));
+ norm3 = ones(size(R{1}));
+
+ case 2
+ norm1 = sqrt(R{3}.^2 + R{1}.^2 + (R{1}.*R{4}).^2) ./ (R{2}.*R{1});
+ norm2 = 1 ./ R{1};
+ norm3 = ones(size(R{1}));
+ case 3
+ norm1 = sqrt((R{3}.*Z{4}).^2 + (R{4}.*Z{3}).^2 + (R{1}.*Z{3}).^2 ...
+ -2*R{3}.*R{4}.*Z{3}.*Z{4} + (R{1}.*R{3}).^2);
+ norm2 = sqrt((R{4}.*Z{2}).^2 + (R{1}.*Z{2}).^2 + (R{2}.*Z{4}).^2 + (R{1}.*R{2}).^2 ...
+ -2*R{2}.*R{4}.*Z{2}.*Z{4});
+ norm3 = sqrt((R{2}.*Z{3}).^2 + (R{3}.*Z{2}).^2 -2*R{2}.*R{3}.*Z{2}.*Z{3});
+ end
+
+ vcov{1} = vcov{1} .* norm1;
+ vcov{2} = vcov{2} .* norm2;
+ vcov{3} = vcov{3} .* norm3;
+ end
end
diff --git a/Utilities/matlabtools/extract_shear.m b/Utilities/matlabtools/extract_shear.m
new file mode 100644
index 00000000..8632529f
--- /dev/null
+++ b/Utilities/matlabtools/extract_shear.m
@@ -0,0 +1,39 @@
+%% extract_shear(DATA, n, shift, n_surf)
+% =======================================
+%
+% Compute the shear (from iota) out of
+% a SPEC out data
+%
+% INPUT
+% -----
+% -data : must be produced using read_spec
+% -n : length(iota) - (n_surf+shift-1);
+% -shift : shift of the indices we take into account when computing
+% shear (1st indices might not be relevant (too close to axis))
+% -n_surf : index of the first surface that encircles the magnetic axis
+%
+% ------------------------------------%
+% Written by S.Guinchard (05/12/22) %
+% ------------------------------------%
+function out = extract_shear(d, n, shift, n_surf)
+
+ id = n_surf+shift;
+ radial_coord = (d.transform.fiota(:,1)); % extract radial coordinate
+ out.mat_iota = d.transform.fiota(id:end,2); % extract iota
+ out.mat_r_coord = radial_coord(id:end); % truncates the radial coordinates (remove 5 first terms)
+ out.mat_s_coord = ((out.mat_r_coord + 1)./2); % change of variable r <--> s
+ out.scan_11 = d.output.Rbc(11,2); % Value of R11
+ out.scan_10 = d.output.Rbc(2,2); % Value of R10
+
+ % CENTERED FINITE DIFFERENCES
+ out.derivatives(1) = (out.mat_iota(2) - out.mat_iota(1)) / (out.mat_s_coord(2) - out.mat_s_coord(1));
+ out.derivatives(n) = (out.mat_iota(n) - out.mat_iota(n-1)) / (out.mat_s_coord(n) - out.mat_s_coord(n-1));
+
+ for j=2:n-1
+ out.derivatives(j) = (out.mat_iota(j+1) - out.mat_iota(j-1)) / (out.mat_s_coord(j+1) - out.mat_s_coord(j-1));
+ end
+
+ out.coeff = out.mat_s_coord ./ (out.mat_iota) ;
+ out.shear = (out.coeff)' .* out.derivatives;
+ out.avg_shear = mean(out.shear); % Avg shear
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/get_SFL_fourier_modB.m b/Utilities/matlabtools/get_SFL_fourier_modB.m
new file mode 100644
index 00000000..462dd245
--- /dev/null
+++ b/Utilities/matlabtools/get_SFL_fourier_modB.m
@@ -0,0 +1,82 @@
+%% get_SFL_fourier_modB( DATA, NTHETA, NPHI, )
+% =============================================
+%
+% Generates an output data struct for the fourier
+% coefficients Bmn of mod(B)in SFL coordinates
+%
+% INPUT
+% -----
+% -data : must be produced by calling read_spec(filename)
+% -Ntheta : number of meshpoints for theta array
+% -Nphi : number of meshpoints for phi array
+%
+% ------------------------------------%
+% Written by S.Guinchard (05/23/22) %
+% ------------------------------------%
+function data_Bmn = get_SFL_fourier_modB(d, Ntheta, Nphi)
+
+
+ Nfp = d.input.physics.Nfp;
+ Ntor = d.input.physics.Ntor;
+ Mpol = d.input.physics.Mpol;
+ K = 2*pi^2/double(Nfp);
+
+ lambdamn = squeeze(d.output.lambdamn);
+ lambdamn = lambdamn(1:end,2);
+ mprime = d.output.ims;
+ nprime = d.output.ins/double(Nfp);
+
+ data_Bmn.Theta = linspace(0, 2*pi, Ntheta);
+ %data_Bmn.Phi = linspace(0, 2*pi/double(Nfp), Nphi); %change accordingly
+ data_Bmn.Phi = linspace(0, 2*pi, Nphi);
+
+
+ data_Bmn.modB = zeros(Ntheta, Nphi);
+ modB_SPEC = squeeze(get_spec_modB(d,1,1,data_Bmn.Theta,data_Bmn.Phi));
+
+ sumlmn = 0.0;
+
+ for ind =2:length(lambdamn)
+ for line = 1:Ntheta
+ for column = 1:Nphi
+ sumlmn = sumlmn + mprime(ind)*lambdamn(ind)*cos(double(mprime(ind))*data_Bmn.Theta(line)-double(nprime(ind))*data_Bmn.Phi(column));
+ end
+ end
+ end
+
+ data_Bmn.jacobian = abs(double(1+sumlmn));
+
+ for m=0:Mpol
+ for n=-Ntor:Ntor
+ if m == 0 && n<0
+ continue
+ end
+ for line = 1:Ntheta
+ for column = 1:Nphi
+ % evaluate modB_SPEC*cos(m theta - n phi) on the grid (theta, phi)
+ data_Bmn.modBcos(line,column) = modB_SPEC(line,column)* data_Bmn.jacobian ...
+ * cos(double(m)*data_Bmn.Theta(line) - double(Nfp)*double(n)*data_Bmn.Phi(column));
+ end
+ end
+
+ data_Bmn.Bmn(m+1,n+Ntor+1) = 1/K*trapz(data_Bmn.Phi,trapz(data_Bmn.Theta,data_Bmn.modBcos,1));
+ end
+ end
+% introduce missing 1/2 coefficient for mode (0,0)
+ data_Bmn.Bmn(1,Ntor+1) = 1/2*data_Bmn.Bmn(1,Ntor+1);
+
+ for i=1:Ntheta
+ for m=0:Mpol
+ for n=-Ntor:Ntor
+ if m == 0 && n<0
+ continue
+ end
+ data_Bmn.modB(i,:) = data_Bmn.modB(i,:) + data_Bmn.Bmn(m+1,n+Ntor+1)* ...
+ cos(double(m)*data_Bmn.Theta(i) - double(Nfp)*double(n)*data_Bmn.Phi);
+ end
+ end
+ end
+ data_Bmn.modB = data_Bmn.modB/2;
+
+%end of function
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/get_boozer_coordinates.m b/Utilities/matlabtools/get_boozer_coordinates.m
new file mode 100644
index 00000000..7ae57333
--- /dev/null
+++ b/Utilities/matlabtools/get_boozer_coordinates.m
@@ -0,0 +1,43 @@
+%% get_boozer_coordinates( BDATA, DATA, NPOINTS, NPERIODS )
+% =============================================
+%
+% Computes the Boozer coordinates from a .boz.h5 file
+% .boz.h5 file must be generated using run_boz.py (see corresponding repo)
+%
+% INPUT
+% -----
+% -bdata : must be produced by calling read_boozer(filename, root)
+% -data : must be produced using read_spec(filename)
+% -Npoints : number of points to be used for the grid
+% -Nperiods : Number of toroidal periods
+%
+% OUTPUT
+% ------
+% -coordb : matlab struct with 2 fields - phi_boz, theta_boz
+% ------------------------------------%
+% Written by S.Guinchard (03/29/22) %
+% ------------------------------------%
+
+function coordb = get_boozer_coordinates(b,d, Npoints, Nperiods)
+
+m = b.Booz_xForms.Outputs.xm_b;
+n = b.Booz_xForms.Outputs.xn_b;
+
+coord = get_spec_straight_fieldlines(d,Npoints,Nperiods);
+iota = b.Booz_xForms.Inputs.iota;
+phi = coord.phi;
+theta = coord.theta_sfl;
+numns = b.Booz_xForms.Outputs.numns_b;
+theta_b = theta;
+
+for i = 1:Npoints
+ for j =1:length(n)
+ phi(i) = phi(i) + numns(j) * sin(double(m(j))*theta(i) - double(n(j))*phi(i));
+ theta_b(i) = theta_b(i) + iota * numns(j) * sin(double(m(j))*theta(i) - double(n(j))*phi(i));
+ end
+end
+
+coordb.phib = wrapTo2Pi(phi);
+coordb.thetab = wrapTo2Pi(theta_b);
+
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/get_boozer_modB.m b/Utilities/matlabtools/get_boozer_modB.m
new file mode 100644
index 00000000..2622e76e
--- /dev/null
+++ b/Utilities/matlabtools/get_boozer_modB.m
@@ -0,0 +1,45 @@
+%% get_boozer_modB( BDATA, NTHETA, NPHI )
+% =============================================
+%
+% Generates an output data struct for the fourier
+% coefficients Bmn of mod(B) in Boozer coordinates
+%
+% INPUT
+% -----
+% -bdata : must be produced by calling read_boozer(filename,root)
+% -Ntheta : number of meshpoints for theta array
+% -Nphi : number of meshpoints for phi array
+%
+% ------------------------------------%
+% Written by S.Guinchard (05/18/22) %
+% ------------------------------------%
+
+function modB = get_boozer_modB(b, Ntheta, Nphi)
+
+ xm = double(b.Booz_xForms.Outputs.xm_b);
+ xn = double(b.Booz_xForms.Outputs.xn_b);
+ BmnB = b.Booz_xForms.Outputs.bmnc_b;
+ Nfp = double(b.Booz_xForms.Inputs.nfp);
+
+ theta = linspace(0, 2*pi, Ntheta);
+ %phi = linspace(0, 2*pi/double(Nfp), Nphi); % (for 2D plot of modB boozer)
+ phi = linspace(0, 2*pi, Nphi); % (for 3D plot of modB boozer)
+
+ [modB.Phi, modB.Theta] = meshgrid(phi, theta);
+
+
+ modB.modB = zeros(size(modB.Theta));
+ for i =1:length(xm)
+ m = xm(i);
+ n = xn(i);
+ angle = (m* modB.Theta - n*modB.Phi);
+ modB.modB = modB.modB + BmnB(i)*cos(angle);
+ % case of stellarator symmetry (see init.from.spec.py)
+ if b.Booz_xForms.Inputs.asym == 1.0
+ modB.modB = modB.modB + BmnB(i)*sin(angle);
+ end
+ end
+
+
+end
+
\ No newline at end of file
diff --git a/Utilities/matlabtools/get_full_field.m b/Utilities/matlabtools/get_full_field.m
deleted file mode 100644
index 0fbb0138..00000000
--- a/Utilities/matlabtools/get_full_field.m
+++ /dev/null
@@ -1,104 +0,0 @@
-function B = get_full_field(data, r, theta, zeta, nr)
-
-%
-% GET_FULL_FIELD( DATA, R, THETA, ZETA, NR )
-% ==========================================
-%
-% Return SPEC magnetic field solution componants as a function of r, theta,
-% zeta. The coordinate r is constructed from the radial position of the
-% volume interface for a given pair (theta, zeta) and from the coordinate
-% s.
-%
-% INPUT
-% -----
-% data: data obtained from read_spec(filename)
-% r: Radial coordinate (array of doubles)
-% theta: Theta coordinate (double)
-% zeta: Zeta coordinate (double)
-% nr: Number of points in each volume for radial interpolation
-%
-% OUTPUT
-% ------
-% B: 3xlength(r)xlength(theta)xlength array containing the B field solution
-% interpolated at r
-%
-% Written by A.Baillod(2019)
-
-
-% Load data
-G = data.input.physics.Igeometry;
-Nvol = data.output.Mvol;
-
-epsilon = 1E-16;
-
-nt = length(theta);
-nz = length(zeta);
-
-B_temp = zeros(3, nr*Nvol, nt, nz); % Allocate memory
-r_temp = zeros(1, nr*Nvol, nt, nz); % Allocate memory
-
-iimin = 1;
-iimax = 0;
-
-r0 = get_spec_radius(data, theta, zeta, 0);
-B = zeros(3,length(r),nt,nz);
-for i=1:Nvol
-
- % if first volume, don't take rmin=0
- if i==1
- rmin = epsilon;
- else
- [ri, zi] = get_spec_radius(data, theta, zeta, i-1);
- rmin = sqrt((ri-r0)^2+zi^2);
- end
-
- [ri, zi] = get_spec_radius(data, theta, zeta, i);
- rmax = sqrt((ri-r0)^2+zi^2);
-
- r_vol = linspace(rmin, rmax, nr+1); % Minor radius
- r_vol = r_vol(2:end);
-
- if i==1
- if G == 1
- sarr = 2.0 * (r_vol - rmin) ./ (rmax - rmin) - 1;
- else
- sarr = 2.0 * ((r_vol - rmin) ./ (rmax - rmin)).^2 - 1;
- end
- else
- sarr = 2.0 * (r_vol - rmin) ./ (rmax - rmin) - 1;
- end
- Bcontrav = get_spec_magfield(data, i, sarr, theta, zeta);
-
- % Generate radial coordinate array
- iimax = iimax + length(r_vol);
- r_temp(iimin:iimax) = r_vol;
-
- % And convert it to covariant basis (normalized here)
- B_cov = contra2cov(data, i, Bcontrav, sarr, theta, zeta, 1);
-
- B_temp(1, iimin:iimax, :, :) = B_cov{1};
- B_temp(2, iimin:iimax, :, :) = B_cov{2};
- B_temp(3, iimin:iimax, :, :) = B_cov{3};
-
- iimin = iimin + length(r_vol);
-
-
- for comp = 1:3
- ind = find(r<=rmax);
- r_int = r(ind);
- ind = find(r_int>=rmin);
- r_int = r_int(ind);
-
- for j = 1:nt
- for k = 1:nz
- B(comp, ind, j, k) = interp1(r_vol, B_cov{comp}(:,j,k), r_int, 'spline');
- end
- end
- end
-end
-
-
-
-
-
-
diff --git a/Utilities/matlabtools/get_metric_QA.m b/Utilities/matlabtools/get_metric_QA.m
new file mode 100644
index 00000000..7997b880
--- /dev/null
+++ b/Utilities/matlabtools/get_metric_QA.m
@@ -0,0 +1,27 @@
+%% get_metric_QA(BDATA)
+% ======================
+%
+% Extract the QA metric from a Booz_xForms output
+%
+% INPUT
+% -----
+% -bdata: must be produced calling read_boozer
+%
+% OUTPUT
+% ------
+% -metric: the value of the QA_metric
+% computed summing all bmnc_b^2 modes
+% s.t n=!0 and normalising by mn_b*bmnc_b(0)^2
+%
+% ------------------------------------%
+% Written by S.Guinchard (05/12/22) %
+% ------------------------------------%
+function metric = get_metric_QA(b)
+
+ bmnc_b = b.Booz_xForms.Outputs.bmnc_b;
+ xn_b = b.Booz_xForms.Outputs.xn_b;
+ ind = find(xn_b ~= 0);
+ metric = sum(bmnc_b(ind).^2)/(bmnc_b(1)^2); % Not divide enables convergence of metric w.r.t mpol
+ %metric = sum(bmnc_b(ind).^2)/(length(ind)*bmnc_b(1)^2);
+
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/get_metric_QH.m b/Utilities/matlabtools/get_metric_QH.m
new file mode 100644
index 00000000..1349b5fc
--- /dev/null
+++ b/Utilities/matlabtools/get_metric_QH.m
@@ -0,0 +1,36 @@
+%% get_metric_QH(BDATA, C)
+% ======================
+%
+% Extract the QH metric from a Booz_xForms output
+%
+% INPUT
+% -----
+% -bdata: must be produced calling read_boozer
+% -c : constant s.t c*m = n (Fourier modes)
+%
+% OUTPUT
+% ------
+% -metric: the value of the QH_metric
+%
+% ------------------------------------%
+% Written by S.Guinchard (05/12/22) %
+% ------------------------------------%
+function metric = get_metric_QH(b, c)
+
+bmnc_b = b.Booz_xForms.Outputs.bmnc_b;
+xn_b = b.Booz_xForms.Outputs.xn_b;
+xm_b = b.Booz_xForms.Outputs.xm_b;
+nfp = double(b.Booz_xForms.Inputs.nfp);
+
+Mpol = b.Booz_xForms.Inputs.mpol;
+Ntor = b.Booz_xForms.Inputs.ntor;
+eq = find(xn_b ~= c*xm_b); % indices s.t c*m ~= n
+m = find(abs(xm_b) <= Mpol ); % indices s.t abs(m) < Mpol
+n = find(abs(xn_b) <= Ntor*nfp); % indices s.t abs(n) < Ntor
+[val, indm, indn] = intersect(m,n); % val = indices s.t abs(m) < Mpol & abs(n) < Ntor
+ind_to_sum = intersect(val,eq); % ind_to_sum = indices s.t c*m=!n and previous conditions
+
+metric = sum(bmnc_b(ind_to_sum).^2)/bmnc_b(1)^2;
+
+
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/get_spec_Bgrid.m b/Utilities/matlabtools/get_spec_Bgrid.m
deleted file mode 100644
index 3a23c259..00000000
--- a/Utilities/matlabtools/get_spec_Bgrid.m
+++ /dev/null
@@ -1,46 +0,0 @@
-function bdata = get_spec_Bgrid(data,nz0,lvol)
-
-%
-% GET_SPEC_BGRID( DATA, NZ0, LVOL )
-% =================================
-%
-% Obtains the canonical cylindrical components of B, namely (B^R, R*B^phi, B^Z), on the coordinate grid points
-%
-% INPUT
-% -----
-% -data : must be produced by calling read_spec(filename)
-% -nz0 : toroidal plane number at which B is obtained (nz0=1 at toroidal angle phi=0)
-% -lvol : volume number in which B is obtained
-%
-% OUTPUT
-% ------
-% -bdata : cell of size 5 containing the values of R, Z, B^R, R*B^phi, B^Z on the grid points
-%
-% written by J.Loizu (2018)
-
-Lrad = data.input.physics.Lrad;
-Nt = data.grid.Nt;
-Nz = data.grid.Nz;
-
-Rij = data.grid.Rij;
-Zij = data.grid.Zij;
-BR = data.grid.BR;
-Bp = data.grid.Bp;
-BZ = data.grid.BZ;
-
-iz = nz0-1;
-ngrid = Lrad(lvol)+1;
-
-if(lvol==1)
- nstart = 2;
-else
- nstart = 1;
-end
-
-bdata{1} = squeeze(Rij(lvol,1+Nt*iz:(iz+1)*Nt,nstart:ngrid));
-bdata{2} = squeeze(Zij(lvol,1+Nt*iz:(iz+1)*Nt,nstart:ngrid));
-bdata{3} = squeeze(BR(lvol,1+Nt*iz:(iz+1)*Nt,nstart:ngrid));
-bdata{4} = squeeze(Bp(lvol,1+Nt*iz:(iz+1)*Nt,nstart:ngrid)).*bdata{1};
-bdata{5} = squeeze(BZ(lvol,1+Nt*iz:(iz+1)*Nt,nstart:ngrid));
-
-
diff --git a/Utilities/matlabtools/get_spec_Bxyz.m b/Utilities/matlabtools/get_spec_Bxyz.m
new file mode 100644
index 00000000..726afb79
--- /dev/null
+++ b/Utilities/matlabtools/get_spec_Bxyz.m
@@ -0,0 +1,104 @@
+function xyz = get_spec_Bxyz( data, lvol, sarr, tarr, zarr )
+%
+% GET_SPEC_BXYZ( DATA, LVOL, SARR, TARR, ZARR )
+% =============================================
+%
+% Write the cartesian components of the magnetic field on a
+% (x,y,z) grid on the outer side of the plasma-vacuum interface
+% given a SPEC equilibrium.
+%
+% INPUTS
+% ------
+% * DATA: data read from spec output via read_spec( fname )
+% * LVOL: volume
+% * SARR: Array of s-coordinate
+% * TARR: Array of poloidal angles
+% * ZARR: Array of toroidal angles
+%
+% Written by A. Baillod (2021)
+%
+
+% Check input
+Igeometry = data.input.physics.Igeometry;
+if Igeometry~=3
+ error('Invalide geometry')
+end
+
+% Read some input from data
+Mvol = data.output.Mvol;
+
+if( lvol<1 || lvol>Mvol )
+ error('invalid volume')
+end
+
+% Reshape input
+ns = length(sarr);
+sarr = reshape( sarr, 1, ns);
+
+nt = length(tarr);
+theta = reshape( tarr, 1, nt );
+
+nz = length(zarr);
+phi = reshape( zarr, 1, nz );
+
+Rarr = get_spec_R_derivatives( data, Mvol, sarr, theta, phi, 'R' );
+Zarr = get_spec_R_derivatives( data, Mvol, sarr, theta, phi, 'Z' );
+
+
+% Transform to cartesian coordinates (x,y,z)
+x = zeros(ns,nt,nz);
+y = zeros(ns,nt,nz);
+for is = 1:ns
+ for it = 1:nt
+ Rtmp = reshape(Rarr{1}(is,it,:), 1, nz);
+
+ x(is,it,:) = Rtmp.*cos(phi);
+ y(is,it,:) = Rtmp.*sin(phi);
+ end
+end
+z = Zarr{1};
+z = reshape(z, ns, nt, nz);
+
+% Now evaluate field on each grid point
+Bcontrav = get_spec_magfield( data, Mvol, sarr, theta, phi );
+
+Bx = zeros(ns,nt,nz);
+By = zeros(ns,nt,nz);
+Bz = zeros(ns,nt,nz);
+
+for is = 1:ns
+ for it=1:nt
+ Bs = reshape( Bcontrav{1}(is,it,:), 1, nz);
+ Bt = reshape( Bcontrav{2}(is,it,:), 1, nz);
+ Bphi = reshape( Bcontrav{3}(is,it,:), 1, nz);
+
+ R = reshape( Rarr{1}(is,it,:), 1, nz );
+ Rs = reshape( Rarr{2}(is,it,:), 1, nz );
+ Rt = reshape( Rarr{3}(is,it,:), 1, nz );
+ Rz = reshape( Rarr{4}(is,it,:), 1, nz );
+
+ Zs = reshape( Zarr{2}(is,it,:), 1, nz );
+ Zt = reshape( Zarr{3}(is,it,:), 1, nz );
+ Zz = reshape( Zarr{4}(is,it,:), 1, nz );
+
+ Bx(is,it,:) = Bs.*(Rs.*cos(phi) ) ...
+ + Bt.*(Rt.*cos(phi) ) ...
+ + Bphi.*(Rz.*cos(phi) - R.*sin(phi));
+ By(is,it,:) = Bs.*(Rs.*sin(phi) ) ...
+ + Bt.*(Rt.*sin(phi) ) ...
+ + Bphi.*(Rz.*sin(phi) + R.*cos(phi));
+ Bz(is,it,:) = Bs.*Zs ...
+ + Bt.*Zt ...
+ + Bphi.*Zz;
+ end
+
+xyz.theta = theta;
+xyz.phi = phi;
+xyz.x = x;
+xyz.y = y;
+xyz.z = z;
+xyz.Bx = Bx;
+xyz.By = By;
+xyz.Bz = Bz;
+
+end
diff --git a/Utilities/matlabtools/get_spec_R_derivatives.m b/Utilities/matlabtools/get_spec_R_derivatives.m
index 0fc30dfc..089279c1 100644
--- a/Utilities/matlabtools/get_spec_R_derivatives.m
+++ b/Utilities/matlabtools/get_spec_R_derivatives.m
@@ -1,4 +1,4 @@
-function [sarr, out] = get_spec_R_derivatives(data, vol, sarr, tarr, zarr, RorZ)
+function out = get_spec_R_derivatives(data, vol, sarr, tarr, zarr, RorZ)
%
% GET_SPEC_R_DERIVATIVES( DATA, VOL, SARR, TARR, ZARR, RORZ )
@@ -25,70 +25,82 @@
% Written by A.Baillod (2019)
%
+ % Test input
+ Istellsym = data.input.physics.Istellsym;
+ if Istellsym~=1
+ error('Only implemented for stellarator symmetric equilibria')
+ end
-% Load geometry
-mn = data.output.mn;
-im = double(data.output.im);
-in = double(data.output.in);
-Rmn = data.output.Rbc(:,vol );
-Rmn_p = data.output.Rbc(:,vol+1);
-Zmn = data.output.Zbs(:,vol );
-Zmn_p = data.output.Zbs(:,vol+1);
-
-% Allocate data for R and its derivative in s, theta and phi (4), for each
-% and for ns points
-if(size(sarr,1)==1)
-sarr = transpose(sarr);
-end
-ns = length(sarr);
-nt = length(tarr);
-nz = length(zarr);
-Rarr = cell(2);
-Zarr = cell(2);
-
-for ii=1:4
- Rarr{ii} = zeros(ns, nt, nz);
- Zarr{ii} = zeros(ns, nt, nz);
-end
-% Compute the regularisation factor
-factor = get_spec_regularization_factor(data, vol, sarr, 'G');
-
-% And R derivatives
-if RorZ=='R'
- for imn=1:mn
- for it=1:nt
- for iz=1:nz
- cosa = cos(double(im(imn)*tarr(it) - in(imn)*zarr(iz)));
- sina = sin(double(im(imn)*tarr(it) - in(imn)*zarr(iz)));
-
- Rarr{1}(:,it,iz) = Rarr{1}(:,it,iz) + ( Rmn(imn) + (Rmn_p(imn) - Rmn(imn)) .* factor{imn}{1}) * cosa;
- Rarr{2}(:,it,iz) = Rarr{2}(:,it,iz) + ( (Rmn_p(imn) - Rmn(imn)) .* factor{imn}{2}) * cosa;
- Rarr{3}(:,it,iz) = Rarr{3}(:,it,iz) - ( Rmn(imn) + (Rmn_p(imn) - Rmn(imn)) .* factor{imn}{1}) * double(im(imn)) * sina;
- Rarr{4}(:,it,iz) = Rarr{4}(:,it,iz) + ( Rmn(imn) + (Rmn_p(imn) - Rmn(imn)) .* factor{imn}{1}) * double(in(imn)) * sina;
- end
+ % Load geometry
+ mn = data.output.mn;
+ im = double(data.output.im);
+ in = double(data.output.in);
+ Rmn = data.output.Rbc(:,vol );
+ Rmn_p = data.output.Rbc(:,vol+1);
+ Zmn = data.output.Zbs(:,vol );
+ Zmn_p = data.output.Zbs(:,vol+1);
+
+ % Allocate data for R and its derivative in s, theta and phi (4), for each
+ % and for ns points
+ ns = length(sarr);
+ nt = length(tarr);
+ nz = length(zarr);
+
+ sarr = reshape(sarr, ns, 1);
+ tarr = reshape(tarr, nt, 1);
+ zarr = reshape(zarr, nz, 1);
+
+ Rarr = cell(1,4);
+ Zarr = cell(1,4);
+
+ for ii=1:4
+ Rarr{ii} = zeros(ns, nt, nz);
+ Zarr{ii} = zeros(ns, nt, nz);
end
- end
- out = Rarr;
-
-elseif RorZ=='Z'
- for imn=1:mn
- for it=1:nt
- for iz=1:nz
- cosa = cos(double(im(imn)*tarr(it) - in(imn)*zarr(iz)));
- sina = sin(double(im(imn)*tarr(it) - in(imn)*zarr(iz)));
-
- Zarr{1}(:,it,iz) = Zarr{1}(:,it,iz) + ( Zmn(imn) + (Zmn_p(imn) - Zmn(imn)) .* factor{imn}{1}) * sina;
- Zarr{2}(:,it,iz) = Zarr{2}(:,it,iz) + ( (Zmn_p(imn) - Zmn(imn)) .* factor{imn}{2}) * sina;
- Zarr{3}(:,it,iz) = Zarr{3}(:,it,iz) + ( Zmn(imn) + (Zmn_p(imn) - Zmn(imn)) .* factor{imn}{1}) * double(im(imn))* cosa;
- Zarr{4}(:,it,iz) = Zarr{4}(:,it,iz) - ( Zmn(imn) + (Zmn_p(imn) - Zmn(imn)) .* factor{imn}{1}) * double(in(imn))* cosa;
+
+ % Compute the regularisation factor
+ factor = get_spec_regularisation_factor(data, vol, sarr, 'G');
+
+
+
+ % And R derivatives
+ if RorZ=='R'
+ for imn=1:mn
+ for it=1:nt
+ for iz=1:nz
+ cosa = cos(double(im(imn)*tarr(it) - in(imn)*zarr(iz)));
+ sina = sin(double(im(imn)*tarr(it) - in(imn)*zarr(iz)));
+
+ Rarr{1}(:,it,iz) = Rarr{1}(:,it,iz) + ( Rmn(imn) + (Rmn_p(imn) - Rmn(imn)) .* factor{imn}{1}) * cosa;
+ Rarr{2}(:,it,iz) = Rarr{2}(:,it,iz) + ( (Rmn_p(imn) - Rmn(imn)) .* factor{imn}{2}) * cosa;
+ Rarr{3}(:,it,iz) = Rarr{3}(:,it,iz) - ( Rmn(imn) + (Rmn_p(imn) - Rmn(imn)) .* factor{imn}{1}) * double(im(imn)) * sina;
+ Rarr{4}(:,it,iz) = Rarr{4}(:,it,iz) + ( Rmn(imn) + (Rmn_p(imn) - Rmn(imn)) .* factor{imn}{1}) * double(in(imn)) * sina;
+ end
+ end
end
+ out = Rarr;
+
+ elseif RorZ=='Z'
+ for imn=1:mn
+ for it=1:nt
+ for iz=1:nz
+ cosa = cos(double(im(imn)*tarr(it) - in(imn)*zarr(iz)));
+ sina = sin(double(im(imn)*tarr(it) - in(imn)*zarr(iz)));
+
+ Zarr{1}(:,it,iz) = Zarr{1}(:,it,iz) + ( Zmn(imn) + (Zmn_p(imn) - Zmn(imn)) .* factor{imn}{1}) * sina;
+ Zarr{2}(:,it,iz) = Zarr{2}(:,it,iz) + ( (Zmn_p(imn) - Zmn(imn)) .* factor{imn}{2}) * sina;
+ Zarr{3}(:,it,iz) = Zarr{3}(:,it,iz) + ( Zmn(imn) + (Zmn_p(imn) - Zmn(imn)) .* factor{imn}{1}) * double(im(imn))* cosa;
+ Zarr{4}(:,it,iz) = Zarr{4}(:,it,iz) - ( Zmn(imn) + (Zmn_p(imn) - Zmn(imn)) .* factor{imn}{1}) * double(in(imn))* cosa;
+ end
+ end
+ end
+ out = Zarr;
+
+ else
+ error(['Not defined for RorZ=',RorZ]);
end
- end
- out = Zarr;
-else
- error(['Not defined for RorZ=',RorZ]);
end
diff --git a/Utilities/matlabtools/get_spec_area.m b/Utilities/matlabtools/get_spec_area.m
index 7a0e4772..a2389a41 100644
--- a/Utilities/matlabtools/get_spec_area.m
+++ b/Utilities/matlabtools/get_spec_area.m
@@ -1,4 +1,4 @@
-function Avol = get_spec_area(data,lvol,ns,nt,phi0)
+function Avol = get_spec_area(data,lvol,smax,ns,nt,phi0)
%
% GET_SPEC_AREA( DATA, LVOL, NS, NT, PHI0 )
@@ -10,6 +10,7 @@
% -----
% -data : must be produced by calling read_spec(filename)
% -lvol : volume number
+% -smax : max s
% -ns : is the resolution in the s-coordinate (e.g. 64)
% -nt : is the resolution in the theta-coordinate (e.g. 64)
% -phi0 : toroidal angle defining a toroidal plane
@@ -25,14 +26,16 @@
smin = -0.999; %avoids singular inversion of the metric matrix
-sarr = linspace(smin,1,ns);
+% Define arrays
+sarr = linspace(smin,smax,ns);
tarr = linspace(0,2*pi,nt);
+% Evaluate Jacobian and metric
jacobian = get_spec_jacobian(data,lvol,sarr,tarr,phi0);
gcontrav = get_spec_metric_contrav(data,lvol,sarr,tarr,phi0);
-
sqrtgradphi = sqrt(gcontrav{3}{3});
-Avol = sum(sum(jacobian(2:end,:).*sqrtgradphi(2:end,:)))*(2*2*pi)/(ns*nt);
+% Evaluate area
+Avol = trapz(tarr, trapz(sarr, jacobian.*sqrtgradphi, 1) );
end
diff --git a/Utilities/matlabtools/get_spec_beta.m b/Utilities/matlabtools/get_spec_beta.m
index 016247b3..3a9ef50b 100644
--- a/Utilities/matlabtools/get_spec_beta.m
+++ b/Utilities/matlabtools/get_spec_beta.m
@@ -14,7 +14,8 @@
%
% OUTPUT
% ------
-% -beta : value of beta on axis
+% -beta_ax : value of beta on axis
+% -beta_av : value of beta on average
%
% written by J.Loizu (2016)
% modified by J.Loizu (05.2017)
@@ -60,13 +61,12 @@
beta_av = sum(av_beta) / volume;
ind = find(vols==1);
-if length(ind)==0 volume_number = vols(lvol);
+if length(ind)==0
volume_number = 1;
volume = get_spec_volume(data,volume_number,64,64,64);
modB = get_spec_modB(data,volume_number,sarr,tarr,zarr);
jacobian = get_spec_jacobian(data, volume_number, sarr, tarr, zarr);
arg = jacobian ./ (modB.^2);
- av_beta(lvol) = press(volume_number)*trapz(zarr, trapz(tarr, trapz(sarr, arg, 1), 2), 3) / volume;
beta_ax = av_beta(1);
else
beta_ax = av_beta(ind);
diff --git a/Utilities/matlabtools/get_spec_energy_slab.m b/Utilities/matlabtools/get_spec_energy_slab.m
index 222efe14..fab2d59d 100644
--- a/Utilities/matlabtools/get_spec_energy_slab.m
+++ b/Utilities/matlabtools/get_spec_energy_slab.m
@@ -22,44 +22,41 @@
%
% written by J.Loizu (2018)
-Nvol = data.input.physics.Nvol;
-
-W = 0;
-
-sarr = linspace(-1,1,ns);
-tarr = linspace(0,2*pi,nt);
-zarr = linspace(0,2*pi,nz);
-
-if(lv==0)
-
- for lvol=1:Nvol
-
- modB = get_spec_modB(data,lvol,sarr,tarr,zarr);
-
- jac = get_spec_jacobian_slab(data,lvol,sarr,tarr,zarr);
-
- F = jac.*modB.^2;
-
- dW = trapz(sarr,trapz(tarr,trapz(zarr,F,3),2));
-
- W = W + 0.5*dW;
-
- end
-
-else
-
- lvol = lv;
-
- modB = get_spec_modB(data,lvol,sarr,tarr,zarr);
-
- jac = get_spec_jacobian_slab(data,lvol,sarr,tarr,zarr);
-
- F = jac.*modB.^2;
-
- dW = trapz(sarr,trapz(tarr,trapz(zarr,F,3),2));
-
- W = W + 0.5*dW;
-
-end
+ % Test input
+ Igeometry = data.input.physics.Igeometry;
+ if Igeometry~=1
+ error('This routine is only for slab geometries')
+ end
+
+ % Read data
+ Nvol = data.input.physics.Nvol;
+
+ W = 0;
+
+ sarr = linspace(-1,1,ns);
+ tarr = linspace(0,2*pi,nt);
+ zarr = linspace(0,2*pi,nz);
+
+ if(lv==0)
+ lvol_start=1;
+ lvol_end =Nvol;
+ else
+ lvol_start=lv;
+ lvol_end =lv;
+ end
+
+
+ for lvol=lvol_start:lvol_end
+
+ % Evaluate mod B and jacobian
+ modB = get_spec_modB(data,lvol,sarr,tarr,zarr);
+ jac = get_spec_jacobian(data,lvol,sarr,tarr,zarr);
+
+ % Integrate
+ F = jac.*modB.^2;
+
+ dW = trapz(sarr,trapz(tarr,trapz(zarr,F,3),2));
+ W = W + 0.5*dW;
+ end
diff --git a/Utilities/matlabtools/get_spec_fractaldim.m b/Utilities/matlabtools/get_spec_fractaldim.m
new file mode 100644
index 00000000..1bb4ad48
--- /dev/null
+++ b/Utilities/matlabtools/get_spec_fractaldim.m
@@ -0,0 +1,401 @@
+function [x, y, Dfrac, N, Lmin, Lmax] = get_spec_fractaldim(data, numline, mth, polyfit_degree, varargin)
+
+%
+% GET_FRACTALDIM( N, L, CASE_TITLE, POLYFIT_DEGREE, N_PTS, PLOTFIG )
+% ==================================================================
+%
+% Plot the N, L parameters resulting from get_NL_boxcount and deduce the fractal dimension
+% Ex :
+% [D_polyfit, D_num, D_slope, Lmin_polyfit, Lmax_polyfit, Lmin_num, Lmax_num] = get_fractaldim(N_cantor, L_cantor, 1, 'Cantor', 6);
+%
+% INPUT
+% -----
+% -data : SPEC output data, read from read_spec(filename)
+% -numline : Line number
+% -mth : 0: uses the mean value to get the fractal dim
+% 1: evaluates numerically the curvature and
+% extract the linear part
+% 2: polyfits the curve and evaluate the curvature
+% analytically to extract the linear part.
+% -polyfit_degree : degree of the polyfit used to approximate the fractal
+% dim. Only used if mth=2
+%
+% OUTPUT
+% ------
+% -x : log10( Lmax/L )
+% -y : log10( N )
+% -Dfrac : fractal dimension
+% -N : Number of points as function of L
+% -Lmin : Maximal L taken into account for evaluation of Dfrac
+% -Lmax : Minimal L taken into account for evaluation of Dfrac
+%
+
+ % Optional input
+ % ---------------
+ torplane = 1;
+ base_exponent = 2;
+ kmin = 2;
+ kmax = 8;
+ newfig = 0;
+
+ % Optional outputs
+ % ----------------
+ Lmin = 0;
+ Lmax = 0;
+
+ l = length(varargin);
+ if mod(l,2)~=0
+ error('Invalid number of input arguments')
+ end
+
+ for ii=1:l/2
+ field = varargin{2*ii-1};
+ value = varargin{2*ii };
+
+ switch field
+ case 'torplane'
+ torplane = value;
+ case 'base_exponent'
+ base_exponent = value;
+ case 'kmin'
+ kmin = value;
+ case 'kmax'
+ kmax = value;
+ case 'newfig'
+ newfig = value;
+ otherwise
+ warning(['Inknown input field: ', field, '. Ignored...'])
+ end
+ end
+
+
+ % Read some important input
+ % --------------------------
+ R = data.poincare.R(numline,torplane,:);
+ Z = data.poincare.Z(numline,torplane,:);
+
+ s = size( R );
+ n_pts = s(3);
+
+ % Perform box counting
+ % ---------------------
+ [N, L] = get_NL_boxcount(base_exponent, kmin, kmax, R, Z);
+
+ % Set up...
+ idx = 1:length(N);
+
+ % Get slopes between each datapoints
+ xp = diff(-log(L));
+ yp = diff(log(N));
+
+ if newfig
+ figure('Color','w')
+ loglog( L, N, 'o', 'MarkerFaceColor', 'b')
+ ylabel('Number of box with a point N')
+ xlabel('Box size')
+
+ end
+
+ switch mth
+ case 0 % mean slope
+
+ % take the centered finite differences and having forward and backward
+ % finite diff for the last points
+ xp_ = (xp(1:end-1) + xp(2:end))/2;
+ yp_ = (yp(1:end-1) + yp(2:end))/2;
+ slopes = [yp(1)/xp(1), yp_./xp_, yp(end)/xp(end)];
+
+ % For output...
+ Lmax = max(L);
+ Lmin = min(L);
+
+ % polyf_1d = polyfit(-log(L),log(N), 1);
+ % D_slope = polyf_1d(1);
+ Dfrac = mean(slopes);
+
+
+ case 1 % numerical curvature
+ % idea is to remove the saturation plateau
+ % the -1 comes from the correspondance between the curvature and the slopes
+ min_plateau_idx_num = min(idx(N>0.95*n_pts))-1;
+
+ % take the centered finite differences and having forward and backward
+ % finite diff for the last points
+ xp_ = (xp(1:end-1) + xp(2:end))/2;
+ yp_ = (yp(1:end-1) + yp(2:end))/2;
+ slopes = [yp(1)/xp(1), yp_./xp_, yp(end)/xp(end)];
+
+ % curvature
+ curv_num = curvature(-log(L),log(N));
+
+ % threshold (kind of arbitrary for the moment)
+ % we take the max w.r.t. a very low curvature in the case where the
+ % points are already all well aligned
+ threshold_num = max(max(curv_num)/2, 0.2);
+
+ % find min, max indices
+ % there are always at least two points in between
+ [idx_min_num, idx_max_num] = find_idx_min_max(curv_num, threshold_num, min_plateau_idx_num);
+
+ % we take the best points to compute the dimension
+ % the +1 are due to the correspondance between the curvature and the slopes
+ % taking a polyfit yields a similar accuracy than the mean slope
+ Dfrac = mean(slopes(idx_min_num+1:idx_max_num+1));
+
+ % determine the corresponding Lmin_num and Lmax_num
+ Lmin = L(idx_max_num+1);
+ Lmax = L(idx_min_num+1);
+
+ case 2 % polyfit curvature
+
+ % 100 logarithmically spaced values exp(x) with x between [beg, end]
+ Lfit = exp(linspace(log(L(1)), log(L(end)), 100));
+ one_over_L = 1./Lfit;
+
+ % the -1 comes from the correspondance between the curvature and the slopes
+ min_plateau_idx_polyfit = uint64((min(idx(N>0.95*n_pts))-1)*100/length(N));
+
+ % fit the whole data
+ p = polyfit(-log(L),log(N), polyfit_degree);
+ pp = polyder(p);
+ ppp = polyder(pp);
+
+ curv_polyfit = abs(polyval(ppp,log(one_over_L)))./(1+polyval(pp,log(one_over_L)).^2).^(3/2);
+
+ % threshold (kind of arbitrary for the moment)
+ threshold_polyfit = max(max(curv_polyfit)/10, 0.2);
+
+ % find all zones (min, max indices) with curvature below threshold
+ [idx_min_polyfit, idx_max_polyfit] = find_idx_min_max(curv_polyfit, threshold_polyfit, min_plateau_idx_polyfit);
+
+ % determine the corresponding Lmin_polyfit and Lmax_polyfit associated
+ % with kmax_edge and kmin_edge respectively if idx_min_polyfit or
+ % idx_max_polyfit is empty, it is a consequence of a too low threshold !
+ Lmin = 1/one_over_L(idx_max_polyfit);
+ Lmax = 1/one_over_L(idx_min_polyfit);
+
+ % taking a polyfit yields a similar accuracy than the mean slope
+ Dfrac = mean(polyval(pp,log(one_over_L(idx_min_polyfit:idx_max_polyfit-1))));
+
+ if newfig
+ hold on;
+ xx = log(Lfit);
+ yy = polyval(p, -xx);
+ loglog( exp(xx), exp(yy), 'LineWidth', 2 )
+ ax = gca;
+ yy = ax.YLim;
+ loglog( Lmin_polyfit*[1,1], yy, 'k--' )
+ loglog( Lmax_polyfit*[1,1], yy, 'k--' )
+ end
+
+ otherwise
+
+ error('Invalid input')
+
+ end
+
+ x = log10(Lmax./L);
+ y = log10( N );
+
+end
+
+% =========================================================================
+% =========================================================================
+function curv = curvature(x, y)
+
+ %
+ % CURV = CURVATURE( X, Y )
+ % ========================
+ %
+ % Compute the curvature of the curve defined by x,y (the starting point and the endpoints have not defined curvature here, it is not checked whether the starting point and the endpoint coincide)
+ %
+ % INPUT
+ % -----
+ % -x,y : coordinates of the curve
+ %
+ % OUTPUT
+ % ------
+ % -curv : curvature of the curve
+ %
+
+ xp = diff(x); xpp = diff(xp);
+ yp = diff(y); ypp = diff(yp);
+
+ curv = zeros(1, length(x)-2);
+ % take the centered finite differences
+ xp_ = (xp(1:end-1) + xp(2:end))/2;
+ yp_ = (yp(1:end-1) + yp(2:end))/2;
+
+ curv = abs(xp_.*ypp - yp_.*xpp)./(xp_.^2 + yp_.^2).^(3/2);
+
+ % can also be implemented such as the following (exact same formula actually)
+ % for i = 1:length(xp)-1
+ % % twice the area of the triangle between these 3 pts
+ % D = norm(xp(i)*yp(i+1)-yp(i)*xp(i+1));
+ % a = (x(i)-x(i+1))^2 + (y(i)-y(i+1))^2;
+ % b = (x(i+1)-x(i+2))^2 + (y(i+1)-y(i+2))^2;
+ % c = (x(i)-x(i+2))^2 + (y(i)-y(i+2))^2;
+ % curv(i) = 2*D/(a*b*c);
+ % end
+end
+
+% ==============================================
+% ==============================================
+function [idx_min, idx_max] = find_idx_min_max(curv, threshold, min_plateau_idx)
+
+ %
+ % FIND_IDX_MIN_MAX( CURV, threshold, min_plateau_idx )
+ % =================================================
+ %
+ % Find the zones (min and max indices) associated with the minimal curvature under the threshold (one of them is the best linear zone)
+ %
+ % INPUT
+ % -----
+ % -curv : curvature of the curve
+ % -threshold : threshold for the minimal curvature
+ % -plateau_idx : indices of the pts near the saturation plateau at log(n_pts)
+ %
+ % OUTPUT
+ % ------
+ % -idx_min,idx_max : min and max indices for the linear zone
+ %
+
+ n_curv = length(curv);
+
+ % find all the indices such that both neighbours are below the threshold
+ start_pt_2_idx_below_threshold = [];
+ end_pt_2_idx_below_threshold = [];
+ for i = 1:n_curv
+ % finds the pts such that \_
+ if i>1 && curv(i) < threshold && curv(i-1) > threshold || i==1 && curv(1) < threshold
+ start_pt_2_idx_below_threshold(end+1) = i;
+ end
+ % finds the pts such that _/
+ if i threshold && curv(i) < threshold || i==n_curv && curv(n_curv) < threshold
+ end_pt_2_idx_below_threshold(end+1) = i;
+ end
+ end
+
+ if length(end_pt_2_idx_below_threshold) > 1
+ if ~isempty(min_plateau_idx)
+ % remove the plateau from the possibilities
+ while start_pt_2_idx_below_threshold(end) >= min_plateau_idx && length(end_pt_2_idx_below_threshold) > 1
+ start_pt_2_idx_below_threshold(end) = [];
+ end_pt_2_idx_below_threshold(end) = [];
+ end
+ end
+
+ % find the largest zone delta L
+ [~, idx_largest_delta_L] = max(end_pt_2_idx_below_threshold-start_pt_2_idx_below_threshold);
+ % as indices of curv
+ idx_min = start_pt_2_idx_below_threshold(idx_largest_delta_L);
+ idx_max = end_pt_2_idx_below_threshold(idx_largest_delta_L);
+ else
+ % as indices of curv
+ idx_min = start_pt_2_idx_below_threshold;
+ idx_max = end_pt_2_idx_below_threshold;
+ end
+end
+
+function [N, L] = get_NL_boxcount(base_exponent, kmin, kmax, x, y)
+
+ %
+ % GET_NL_BOXCOUNT( BASE_EXPONENT, KMIN, KMAX, X, Y )
+ % ==================================================
+ %
+ % Get the N, L parameters necessary for fractal dimension computation using box-counting
+ %
+ % INPUT
+ % -----
+ % -base_exponent : base of the exponential factor by which the box sizes are reduced (1 < base <= 2 is good)
+ % -kmin : min exponent linked to the size of the boxes (integer >= 0)
+ % -kmax : max exponent linked to the size of the boxes
+ % -x,y : coordinates of the points in the set to analyse (y optional)
+ %
+ % OUTPUT
+ % ------
+ % -N : number of box counted
+ % -L : size of the box counted (normalized by the max size of the boxes Lmax)
+ %
+
+ switch nargin
+ case 4
+ dim = 1;
+ case 5
+ dim = 2;
+ otherwise
+ error('Too many or not enough input arguments. Type "help get_NL_fractaldim" for more informations')
+ end
+
+ n_pts = length(x);
+ N = zeros(1,kmax-kmin+1);
+ L = zeros(1,kmax-kmin+1);
+ x_min = min(x);
+ x_max = max(x);
+ p = 1;
+
+ switch dim
+ case 1 % fractal is represented in 1D
+ Lmax = x_max-x_min;
+
+ for k = kmin:kmax
+ s = base_exponent^k;
+ L(p) = Lmax/s;
+
+ counter = zeros(1,ceil(s));
+
+ for i = 1:n_pts
+ % x-y indices of the i-th pt
+ is = 1+floor((x(i)-x_min)/L(p) );
+
+ try
+ counter(1,is) = 1;
+ catch
+ error(';problem')
+ end
+ end
+
+ N(p) = sum(counter);
+ % increment p (boxsize parameter)
+ p = p+1;
+ end
+
+ case 2 % fractal is represented in 2D
+ y_min = min(y);
+ y_max = max(y);
+
+ % At least 1 box in each coordinate - total of 100 boxes
+ % Better precision than if one takes :
+ % Lmax = max([x_max-x_min, y_max-y_min]);
+ % However one must be careful with the memory allocation!
+ Lmax_x = x_max - x_min;
+ Lmax_y = y_max - y_min;
+ Lmax = min([Lmax_x, Lmax_y]);
+ if abs(Lmax) < 1e-7
+ % due to points being possible
+ Lmax = 1;
+ end
+ for k = kmin:kmax
+ s = base_exponent^k;
+ L(p) = Lmax/s;
+
+ counter = zeros(ceil(s * Lmax_x / Lmax), ceil(s * Lmax_y / Lmax));
+
+ for i = 1:n_pts
+ % x-y indices of the i-th pt
+ is = 1+floor((x(i)-x_min)/L(p) );
+ js = 1+floor((y(i)-y_min)/L(p) );
+
+ try
+ counter(is,js) = 1;
+ catch
+ error(';problem')
+ end
+ end
+
+ N(p) = sum(sum(counter));
+ % increment p (boxsize parameter)
+ p = p+1;
+ end
+ end
+end
diff --git a/Utilities/matlabtools/get_spec_helicity_slab.m b/Utilities/matlabtools/get_spec_helicity_slab.m
index 737aa935..2249257e 100644
--- a/Utilities/matlabtools/get_spec_helicity_slab.m
+++ b/Utilities/matlabtools/get_spec_helicity_slab.m
@@ -23,65 +23,70 @@
%
% written by J.Loizu (2018)
-Ate = data.vector_potential.Ate{lvol};
-Aze = data.vector_potential.Aze{lvol};
+ % Test input
+ Igeometry = data.input.physics.Igeometry;
+ if( Igeometry~=1 )
+ error('Invalid geometry. Only available for slab')
+ end
-sarr = linspace(-1,1,ns);
-tarr = linspace(0,2*pi,nt);
-zarr = linspace(0,2*pi,nz);
-sarr = transpose(sarr);
-sbar = (sarr+1)/2;
+ % Read data
+ Ate = data.vector_potential.Ate{lvol};
+ Aze = data.vector_potential.Aze{lvol};
-Lrad = data.input.physics.Lrad(lvol);
-mn = data.output.mn;
-im = double(data.output.im);
-in = double(data.output.in);
+ sarr = linspace(-1,1,ns);
+ tarr = linspace(0,2*pi,nt);
+ zarr = linspace(0,2*pi,nz);
+ sarr = transpose(sarr);
-h1 = zeros(ns,nt,nz); % allocate data for magnetic helicity integrand 1
-h2 = zeros(ns,nt,nz); % allocate data for magnetic helicity integrand 2
-h3 = zeros(ns,nt,nz); % allocate data for magnetic helicity integrand 3
-h4 = zeros(ns,nt,nz); % allocate data for magnetic helicity integrand 4
+ Lrad = data.input.physics.Lrad(lvol);
+ mn = data.output.mn;
+ im = double(data.output.im);
+ in = double(data.output.in);
-% Construct Chebyshev polynomials and their derivatives
+ h1 = zeros(ns,nt,nz); % allocate data for magnetic helicity integrand 1
+ h2 = zeros(ns,nt,nz); % allocate data for magnetic helicity integrand 2
+ h3 = zeros(ns,nt,nz); % allocate data for magnetic helicity integrand 3
+ h4 = zeros(ns,nt,nz); % allocate data for magnetic helicity integrand 4
-T = get_spec_polynomial_basis(data, lvol, sarr);
+ % Construct Chebyshev polynomials and their derivatives
-% Construct regularization factors and their derivatives
+ T = get_spec_polynomial_basis(data, lvol, sarr);
-fac = get_spec_regularization_factor(data,lvol,sarr,'F');
+ % Construct regularization factors and their derivatives
-% Construct magnetic helicity integrand
+ fac = get_spec_regularisation_factor(data,lvol,sarr,'F');
-Lsingularity = false;
-if (lvol==1) && (data.input.physics.Igeometry~=1)
- Lsingularity = true;
-end
+ % Construct magnetic helicity integrand
-for l=1:Lrad+1
- for j=1:mn
- if Lsingularity
- basis = T{l}{1}(im(j)+1);
- dbasis = T{l}{2}(im(j)+1);
- else
- basis = T{l}{1};
- dbasis = T{l}{2};
+ Lsingularity = false;
+ if (lvol==1) && (data.input.physics.Igeometry~=1)
+ Lsingularity = true;
end
- for it=1:nt
- for iz=1:nz
- cosa = cos(im(j)*tarr(it)-in(j)*zarr(iz));
- sina = sin(im(j)*tarr(it)-in(j)*zarr(iz));
- h1(:,it,iz) = h1(:,it,iz) + fac{j}{1}.* basis.*Ate(l,j)*cosa; %A_t
- h2(:,it,iz) = h2(:,it,iz) - (fac{j}{1}.*dbasis+fac{j}{2}.* basis).*Aze(l,j)*cosa; % -dA_z/ds
- h3(:,it,iz) = h3(:,it,iz) + fac{j}{1}.* basis.*Aze(l,j)*cosa; %A_z
- h4(:,it,iz) = h4(:,it,iz) + (fac{j}{1}.*dbasis+fac{j}{2}.* basis).*Ate(l,j)*cosa; % +dA_t/ds
+ for l=1:Lrad+1
+ for j=1:mn
+ if Lsingularity
+ basis = T{l}{1}(im(j)+1);
+ dbasis = T{l}{2}(im(j)+1);
+ else
+ basis = T{l}{1};
+ dbasis = T{l}{2};
+ end
+
+ for it=1:nt
+ for iz=1:nz
+ cosa = cos(im(j)*tarr(it)-in(j)*zarr(iz));
+ h1(:,it,iz) = h1(:,it,iz) + fac{j}{1}.* basis .*Ate(l,j)*cosa; %A_t
+ h2(:,it,iz) = h2(:,it,iz) - (fac{j}{1}.*dbasis+fac{j}{2}.* basis).*Aze(l,j)*cosa; % -dA_z/ds
+ h3(:,it,iz) = h3(:,it,iz) + fac{j}{1}.* basis .*Aze(l,j)*cosa; %A_z
+ h4(:,it,iz) = h4(:,it,iz) + (fac{j}{1}.*dbasis+fac{j}{2}.* basis).*Ate(l,j)*cosa; % +dA_t/ds
+ end
+ end
end
end
- end
-end
-
-h = h1.*h2 + h3.*h4;
-
-H = trapz(sarr,trapz(tarr,trapz(zarr,h,3),2));
+ % Evaluate helicity
+ h = h1.*h2 + h3.*h4;
+ H = trapz(sarr,trapz(tarr,trapz(zarr,h,3),2));
+end
diff --git a/Utilities/matlabtools/get_spec_jacobian.m b/Utilities/matlabtools/get_spec_jacobian.m
index ea11664d..5ce74412 100644
--- a/Utilities/matlabtools/get_spec_jacobian.m
+++ b/Utilities/matlabtools/get_spec_jacobian.m
@@ -23,17 +23,24 @@
% written by J.Loizu (2016)
% modified by A. Baillod (2019)
-[sarr, Rarr] = get_spec_R_derivatives(data, lvol, sarr, tarr, zarr, 'R');
+ % Check input
+ Istellsym = data.input.physics.Istellsym;
+ if Istellsym==0
+ error('Non stellarator symmetric not implemented')
+ end
-switch data.input.physics.Igeometry
- case 1
- jacobian = Rarr{2};
- case 2
- jacobian = Rarr{1}.*Rarr{2};
- case 3
- [sarr, Zarr] = get_spec_R_derivatives(data, lvol, sarr, tarr, zarr, 'Z');
- jacobian = Rarr{1}.*(Rarr{3}.*Zarr{2} - Rarr{2}.*Zarr{3});
- otherwise
- error('Unsupported geometry in get_spec_jacobian')
-end
+ Rarr = get_spec_R_derivatives(data, lvol, sarr, tarr, zarr, 'R');
+ switch data.input.physics.Igeometry
+ case 1
+ jacobian = Rarr{2};
+ case 2
+ jacobian = Rarr{1}.*Rarr{2};
+ case 3
+ Zarr = get_spec_R_derivatives(data, lvol, sarr, tarr, zarr, 'Z');
+ jacobian = Rarr{1}.*(Rarr{3}.*Zarr{2} - Rarr{2}.*Zarr{3});
+ otherwise
+ error('Unsupported geometry in get_spec_jacobian')
+ end
+
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/get_spec_magfield.m b/Utilities/matlabtools/get_spec_magfield.m
index 91e4cce2..ef7f6e59 100644
--- a/Utilities/matlabtools/get_spec_magfield.m
+++ b/Utilities/matlabtools/get_spec_magfield.m
@@ -48,11 +48,7 @@
T = get_spec_polynomial_basis(data, lvol, sarr');
-% Construct regularization factors and their derivatives
-%fac = get_spec_regularisation_factor(data, lvol, sarr, 'F');
-
% Construct magnetic field contravariant components
-
Lsingularity = false;
if (lvol==1) && (data.input.physics.Igeometry~=1)
Lsingularity = true;
diff --git a/Utilities/matlabtools/get_spec_metric.m b/Utilities/matlabtools/get_spec_metric.m
index 09022d54..31dd8263 100644
--- a/Utilities/matlabtools/get_spec_metric.m
+++ b/Utilities/matlabtools/get_spec_metric.m
@@ -21,57 +21,65 @@
% Note: Stellarator symmetry is assumed
%
% written by J.Loizu (2016)
-% modified by A. Baillod (2019)
+% modified by A. Baillod (2019)]
-% Allocate data for the metric matrix
-ns = length(sarr);
-nt = length(tarr);
-nz = length(zarr);
+ % Check input
+ Istellsym = data.input.physics.Istellsym;
+ if Istellsym==0
+ error('Non stellarator symmetric not implemented')
+ end
+
+ % Allocate data for the metric matrix
+ ns = length(sarr);
+ nt = length(tarr);
+ nz = length(zarr);
-gmat = cell(3,3);
+ gmat = cell(3,3);
-for k=1:3
- for p=1:3
- gmat{k}{p} = zeros(ns,nt,nz);
- end
-end
-
-% Get R and Z and their derivatives
+ for k=1:3
+ for p=1:3
+ gmat{k,p} = zeros(ns,nt,nz);
+ end
+ end
-[out, Rarr] = get_spec_R_derivatives(data,lvol,sarr,tarr,zarr,'R');
-[out, Zarr] = get_spec_R_derivatives(data,lvol,sarr,tarr,zarr,'Z');
+ % Get R and its derivatives
+ Rarr = get_spec_R_derivatives(data,lvol,sarr,tarr,zarr,'R');
+ % Construct metric elements
-% Construct metric elements
-
-switch data.input.physics.Igeometry
- case 1
- gmat{1}{1} = Rarr{2}.^2;
- gmat{2}{2} = 1 + Rarr{3}.^2;
- gmat{3}{3} = 1 + Rarr{4}.^2;
- gmat{1}{2} = Rarr{2}.*Rarr{3};
- gmat{1}{3} = Rarr{2}.*Rarr{4};
- gmat{2}{3} = Rarr{3}.*Rarr{4};
- case 2
- gmat{1}{1} = Rarr{2}.^2; %gss
- gmat{2}{2} = Rarr{3}.^2 + Rarr{1}.^2; %gtt
- gmat{3}{3} = Rarr{4}.^2 + 1; %gzz
- gmat{1}{2} = Rarr{2}.*Rarr{3}; %gst
- gmat{1}{3} = Rarr{2}.*Rarr{4}; %gsz
- gmat{2}{3} = Rarr{3}.*Rarr{4}; %gtz
- case 3
- gmat{1}{1} = Rarr{2}.^2 + Zarr{2}.^2; %gss
- gmat{2}{2} = Rarr{3}.^2 + Zarr{3}.^2; %gtt
- gmat{3}{3} = Rarr{1}.^2 + Rarr{4}.^2 + Zarr{4}.^2; %gzz
- gmat{1}{2} = Rarr{2}.*Rarr{3} + Zarr{2}.*Zarr{3}; %gst
- gmat{1}{3} = Rarr{2}.*Rarr{4} + Zarr{2}.*Zarr{4}; %gsz
- gmat{2}{3} = Rarr{3}.*Rarr{4} + Zarr{3}.*Zarr{4}; %gtz
- otherwise
- error('Unsupported geometry in get_spec_metric.m')
-end
+ switch data.input.physics.Igeometry
+ case 1 % Slab geometry
+ gmat{1,1} = Rarr{2}.^2;
+ gmat{2,2} = 1 + Rarr{3}.^2;
+ gmat{3,3} = 1 + Rarr{4}.^2;
+ gmat{1,2} = Rarr{2}.*Rarr{3};
+ gmat{1,3} = Rarr{2}.*Rarr{4};
+ gmat{2,3} = Rarr{3}.*Rarr{4};
+
+ case 2 % Cylindrical geometry
+ gmat{1,1} = Rarr{2}.^2; %gss
+ gmat{2,2} = Rarr{3}.^2 + Rarr{1}.^2; %gtt
+ gmat{3,3} = Rarr{4}.^2 + 1; %gzz
+ gmat{1,2} = Rarr{2}.*Rarr{3}; %gst
+ gmat{1,3} = Rarr{2}.*Rarr{4}; %gsz
+ gmat{2,3} = Rarr{3}.*Rarr{4}; %gtz
+
+ case 3 %Toroidal geometry
+ % Get Z and its derivatives
+ Zarr = get_spec_R_derivatives(data,lvol,sarr,tarr,zarr,'Z');
+
+ gmat{1,1} = Rarr{2}.^2 + Zarr{2}.^2; %gss
+ gmat{2,2} = Rarr{3}.^2 + Zarr{3}.^2; %gtt
+ gmat{3,3} = Rarr{1}.^2 + Rarr{4}.^2 + Zarr{4}.^2; %gzz
+ gmat{1,2} = Rarr{2}.*Rarr{3} + Zarr{2}.*Zarr{3}; %gst
+ gmat{1,3} = Rarr{2}.*Rarr{4} + Zarr{2}.*Zarr{4}; %gsz
+ gmat{2,3} = Rarr{3}.*Rarr{4} + Zarr{3}.*Zarr{4}; %gtz
+ otherwise
+ error('Unsupported geometry in get_spec_metric.m')
+ end
-gmat{2}{1} = gmat{1}{2}; % by symmetry of g
-gmat{3}{1} = gmat{1}{3};
-gmat{3}{2} = gmat{2}{3};
+ gmat{2,1} = gmat{1,2}; % by symmetry of g
+ gmat{3,1} = gmat{1,3};
+ gmat{3,2} = gmat{2,3};
end
diff --git a/Utilities/matlabtools/get_spec_metric_contrav.m b/Utilities/matlabtools/get_spec_metric_contrav.m
index 8ca27c04..e3589062 100644
--- a/Utilities/matlabtools/get_spec_metric_contrav.m
+++ b/Utilities/matlabtools/get_spec_metric_contrav.m
@@ -15,12 +15,16 @@
%
% OUTPUT
% ------
-% gmatcon{i}{j}(s,theta,zeta)
+% gmatcon{i,j}(s,theta,zeta)
%
% Note: Stellarator symmetry is assumed
%
% written by J.Loizu (2017)
+Istellsym = data.input.physics.Istellsym;
+if Istellsym~=1
+ error('Only valid for stellarator symmetric equilibria')
+end
% Auxiliary variables
@@ -30,19 +34,11 @@
nz = length(zarr);
% First get the covariant metric matrix
-
gmatcov = get_spec_metric(data,lvol,sarr,tarr,zarr);
% Allocate space for contravariant metric matrix
-
gmatcon = cell(3,3);
-for k=1:3
- for p=1:3
- gmatcon{k}{p} = zeros(ns,nt,nz);
- end
-end
-
% Initiate calculation loop (over each position on the surface)
for is=1:ns
@@ -53,66 +49,51 @@
% Define arrays of gcov, gcon, and rhs
rhs = transpose([1 1 1 0 0 0]);
- gcon = zeros(6,1);
- gcov = zeros(6,1);
-
- gcov(1) = gmatcov{1}{1}(is,it,iz);
- gcov(2) = gmatcov{2}{2}(is,it,iz);
- gcov(3) = gmatcov{3}{3}(is,it,iz);
- gcov(4) = gmatcov{1}{2}(is,it,iz);
- gcov(5) = gmatcov{1}{3}(is,it,iz);
- gcov(6) = gmatcov{2}{3}(is,it,iz);
% Define transformation matrix G
-
G = zeros(6,6);
- G(1,1) = gmatcov{1}{1}(is,it,iz);
- G(2,2) = gmatcov{2}{2}(is,it,iz);
- G(3,3) = gmatcov{3}{3}(is,it,iz);
- G(4,4) = gmatcov{1}{1}(is,it,iz);
- G(5,5) = gmatcov{1}{1}(is,it,iz);
- G(6,6) = gmatcov{2}{2}(is,it,iz);
+ G(1,1) = gmatcov{1,1}(is,it,iz);
+ G(2,2) = gmatcov{2,2}(is,it,iz);
+ G(3,3) = gmatcov{3,3}(is,it,iz);
+ G(4,4) = gmatcov{1,1}(is,it,iz);
+ G(5,5) = gmatcov{1,1}(is,it,iz);
+ G(6,6) = gmatcov{2,2}(is,it,iz);
- G(1,4) = gmatcov{1}{2}(is,it,iz);
- G(1,5) = gmatcov{1}{3}(is,it,iz);
+ G(1,4) = gmatcov{1,2}(is,it,iz);
+ G(1,5) = gmatcov{1,3}(is,it,iz);
- G(2,4) = gmatcov{1}{2}(is,it,iz);
- G(2,6) = gmatcov{2}{3}(is,it,iz);
+ G(2,4) = gmatcov{1,2}(is,it,iz);
+ G(2,6) = gmatcov{2,3}(is,it,iz);
- G(3,5) = gmatcov{1}{3}(is,it,iz);
- G(3,6) = gmatcov{2}{3}(is,it,iz);
-
- G(4,2) = gmatcov{1}{2}(is,it,iz);
- G(4,6) = gmatcov{1}{3}(is,it,iz);
+ G(3,5) = gmatcov{1,3}(is,it,iz);
+ G(3,6) = gmatcov{2,3}(is,it,iz);
- G(5,3) = gmatcov{1}{3}(is,it,iz);
- G(5,6) = gmatcov{1}{2}(is,it,iz);
+ G(4,2) = gmatcov{1,2}(is,it,iz);
+ G(4,6) = gmatcov{1,3}(is,it,iz);
- G(6,3) = gmatcov{2}{3}(is,it,iz);
- G(6,5) = gmatcov{1}{2}(is,it,iz);
+ G(5,3) = gmatcov{1,3}(is,it,iz);
+ G(5,6) = gmatcov{1,2}(is,it,iz);
- % Invert transformation matrix
-
- Ginv = inv(G);
+ G(6,3) = gmatcov{2,3}(is,it,iz);
+ G(6,5) = gmatcov{1,2}(is,it,iz);
% Calculate gcon elements
-
- gcon = Ginv*rhs;
+ gcon = G\rhs;
% Construct contravariant metric matrix
- gmatcon{1}{1}(is,it,iz) = gcon(1); %g^ss
- gmatcon{2}{2}(is,it,iz) = gcon(2); %g^tt
- gmatcon{3}{3}(is,it,iz) = gcon(3); %g^zz
- gmatcon{1}{2}(is,it,iz) = gcon(4); %g^st
- gmatcon{1}{3}(is,it,iz) = gcon(5); %g^sz
- gmatcon{2}{3}(is,it,iz) = gcon(6); %g^tz
+ gmatcon{1,1}(is,it,iz) = gcon(1); %g^ss
+ gmatcon{2,2}(is,it,iz) = gcon(2); %g^tt
+ gmatcon{3,3}(is,it,iz) = gcon(3); %g^zz
+ gmatcon{1,2}(is,it,iz) = gcon(4); %g^st
+ gmatcon{1,3}(is,it,iz) = gcon(5); %g^sz
+ gmatcon{2,3}(is,it,iz) = gcon(6); %g^tz
- gmatcon{2}{1}(is,it,iz) = gmatcon{1}{2}(is,it,iz); % by symmetry of g
- gmatcon{3}{1}(is,it,iz) = gmatcon{1}{3}(is,it,iz);
- gmatcon{3}{2}(is,it,iz) = gmatcon{2}{3}(is,it,iz);
+ gmatcon{2,1}(is,it,iz) = gmatcon{1,2}(is,it,iz); % by symmetry of g
+ gmatcon{3,1}(is,it,iz) = gmatcon{1,3}(is,it,iz);
+ gmatcon{3,2}(is,it,iz) = gmatcon{2,3}(is,it,iz);
end
end
diff --git a/Utilities/matlabtools/get_spec_modB.m b/Utilities/matlabtools/get_spec_modB.m
index c773366a..38525908 100644
--- a/Utilities/matlabtools/get_spec_modB.m
+++ b/Utilities/matlabtools/get_spec_modB.m
@@ -40,15 +40,15 @@
for is=1:ns
for it=1:nt
for iz=1:nz
- a0 = gmat{1}{1}(is,it,iz);
- b0 = gmat{1}{2}(is,it,iz);
- c0 = gmat{1}{3}(is,it,iz);
- d0 = gmat{2}{1}(is,it,iz);
- e0 = gmat{2}{2}(is,it,iz);
- f0 = gmat{2}{3}(is,it,iz);
- g0 = gmat{3}{1}(is,it,iz);
- h0 = gmat{3}{2}(is,it,iz);
- i0 = gmat{3}{3}(is,it,iz);
+ a0 = gmat{1,1}(is,it,iz);
+ b0 = gmat{1,2}(is,it,iz);
+ c0 = gmat{1,3}(is,it,iz);
+ d0 = gmat{2,1}(is,it,iz);
+ e0 = gmat{2,2}(is,it,iz);
+ f0 = gmat{2,3}(is,it,iz);
+ g0 = gmat{3,1}(is,it,iz);
+ h0 = gmat{3,2}(is,it,iz);
+ i0 = gmat{3,3}(is,it,iz);
bs = bvec{1}(is,it,iz);
bt = bvec{2}(is,it,iz);
diff --git a/Utilities/matlabtools/get_spec_polflux.m b/Utilities/matlabtools/get_spec_polflux.m
index 690051a3..f8579c31 100644
--- a/Utilities/matlabtools/get_spec_polflux.m
+++ b/Utilities/matlabtools/get_spec_polflux.m
@@ -1,11 +1,12 @@
-function psipol = get_spec_polflux(data,lvol,theta,start,send,ns,nz)
+function psipol = get_spec_polflux(data,lvol,theta,sarr,nz)
%
-% GET_SPEC_POLFLUX( DATA, LVOL, THETA, START, SEND, NS, NZ )
-% ==========================================================
+% GET_SPEC_POLFLUX( DATA, LVOL, THETA, SARR, NZ )
+% ===============================================
%
% Computes total enclosed poloidal flux in the surface defined by theta
-% inside the volume number lvol and across the radial extension defined by start and send
+% inside the volume number lvol and across the radial extension defined by
+% start and send
%
% INPUT
% -----
@@ -22,24 +23,21 @@
% -psipol : total enclosed poloidal flux
%
% written by J.Loizu (2016)
-% modified by A. Baillod (2019) - Added switch for geometry
-sarr = linspace(start,send,ns);
+% Check input
+Igeometry = data.input.physics.Igeometry;
+if (sarr(1)==-1) && (lvol==1) && (Igeometry~=1)
+ error('Singularity in first volume for s=-1. Set sarr to start from >-1')
+end
+% Build zeta array
zarr = linspace(0,2*pi,nz);
-ds = sarr(2)-sarr(1);
-
-dz = zarr(2)-zarr(1);
-
-
+% Get B theta contravariant and the jacobian
Bcontrav = get_spec_magfield(data,lvol,sarr,theta,zarr);
+Btheta = squeeze(Bcontrav{2});
jac = squeeze(get_spec_jacobian(data,lvol,sarr,theta,zarr));
-
-
-Btheta = Bcontrav{2};
-
+
% Compute surface integral
-
-psipol = sum(sum( jac(2:end,:).*Btheta(2:end,:) ))*ds*dz;
+psipol = trapz(zarr, trapz(sarr, jac.*Btheta, 1 ) );
diff --git a/Utilities/matlabtools/get_spec_polynomial_basis.m b/Utilities/matlabtools/get_spec_polynomial_basis.m
index 4524d04f..edf20287 100644
--- a/Utilities/matlabtools/get_spec_polynomial_basis.m
+++ b/Utilities/matlabtools/get_spec_polynomial_basis.m
@@ -15,101 +15,111 @@
% OUTPUT
% ------
% T{i}{j}: Polynom of order i (j=1) and its derivative (j=2)
+% T{i}{j}: Polynom of order i (j=1)
+% and its derivative with respect to s (j=2)
%
%
% Written by A. Baillod (2020)
%
-Lrad = double(data.input.physics.Lrad(lvol));
-ns = length(sarr);
-Mpol = data.input.physics.Mpol;
-
-Lzernike = false;
-if ((lvol==1) && (data.input.physics.Igeometry~=1))
- Lzernike = true;
-end
-
-
-T = cell(Lrad+1,2); % allocate data for Chebyshev polynomials and their derivatives
-
-T{1}{1} = ones(ns,1);
-T{1}{2} = zeros(ns,1);
-
-T{2}{1} = sarr;
-T{2}{2} = ones(ns,1);
-
-
-if( Lzernike ) % Build zernike polynomials
-% Copy pasted from Frotran source, translated to Matlab language
-% Tested on the 16.09.2020 (A. Baillod) against SPEC source. perfect match
- zernike = zeros(Lrad+1,Mpol+1,2,length(sarr));
- rm = ones(size(sarr));
- rm1 = zeros(size(sarr));
-
- sbar = (1 + sarr ) / 2.0;
- ns = length(sbar);
-
- for m = 0:Mpol
- if (Lrad >= m)
- zernike(m+1,m+1,1,:) = rm;
- zernike(m+1,m+1,2,:) = double(m)*rm1;
+ % Read input data
+ Lrad = double(data.input.physics.Lrad(lvol));
+ ns = length(sarr);
+ Mpol = data.input.physics.Mpol;
+
+ % Check if zernike or Chebychev polynomials are required
+ Lzernike = false;
+ if ((lvol==1) && (data.input.physics.Igeometry~=1))
+ if data.version<3.0
+ Lzernike = false;
+ else
+ Lzernike = true;
+ end
end
- if (Lrad >= m+2)
- zernike(m+3,m+1,1,:) = double(m+2) *rm.*sbar.^2 - double(m+1) *rm;
- zernike(m+3,m+1,2,:) = double((m+2)^2) *rm.*sbar - double((m+1)*m)*rm1;
- end
- for n = m+4:2:Lrad
- factor1 = double(n) / double(n^2 - m^2);
- factor2 = double(4 * (n-1));
- factor3 = double((n-2+m)^2)/double(n-2) + double((n-m)^2)/double(n);
- factor4 = double((n-2)^2-m^2) / double(n-2);
-
- zernike(n+1, m+1, 1, :) = factor1 * ((factor2*sbar.^2 - factor3) .* reshape(zernike(n-1, m+1, 1, :), [ns,1]) - factor4 * reshape(zernike(n-3, m+1, 1, :), [ns, 1]));
- zernike(n+1, m+1, 2, :) = factor1 * (2.0*factor2*sbar .* reshape(zernike(n-1, m+1, 1, :), [ns,1]) + (factor2*sbar.^2 - factor3) .* reshape(zernike(n-1, m+1, 2, :), [ns,1]) - factor4 * reshape(zernike(n-3, m+1, 2, :), [ns,1]));
- end
-
- rm1 = rm;
- rm = rm .* sbar;
- end
-
- for n = 2:2:Lrad
- zernike(n+1,1,1,:) = zernike(n+1,1,1, :) - (-1)^(n/2);
- end
-
- if (Mpol >= 1)
- for n = 3:2:Lrad
- zernike(n+1,2,1,:) = reshape(zernike(n+1,2,1,:), [ns,1]) - (-1)^((n-1)/2) * double((n+1)/2) * sbar;
- zernike(n+1,2,2,:) = reshape(zernike(n+1,2,2,:), [ns,1]) - (-1)^((n-1)/2) * double((n+1)/2);
+ % Allocate memory
+ T = cell(Lrad+1,2);
+
+ T{1}{1} = ones(ns,1);
+ T{1}{2} = zeros(ns,1);
+
+ T{2}{1} = sarr;
+ T{2}{2} = ones(ns,1);
+
+
+ if( Lzernike ) % Build zernike polynomials
+ % Copy pasted from Frotran source, translated to Matlab language
+ % Tested on the 16.09.2020 (A. Baillod) against SPEC source. perfect match
+ zernike = zeros(Lrad+1,Mpol+1,2,length(sarr));
+ rm = ones(size(sarr));
+ rm1 = zeros(size(sarr));
+
+ sbar = (1 + sarr ) / 2.0;
+ ns = length(sbar);
+
+ for m = 0:Mpol
+ if (Lrad >= m)
+ zernike(m+1,m+1,1,:) = rm;
+ zernike(m+1,m+1,2,:) = double(m)*rm1;
+ end
+
+ if (Lrad >= m+2)
+ zernike(m+3,m+1,1,:) = double(m+2) *rm.*sbar.^2 - double(m+1) *rm;
+ zernike(m+3,m+1,2,:) = double((m+2)^2) *rm.*sbar - double((m+1)*m)*rm1;
+ end
+
+ for n = m+4:2:Lrad
+ factor1 = double(n) / double(n^2 - m^2);
+ factor2 = double(4 * (n-1));
+ factor3 = double((n-2+m)^2)/double(n-2) + double((n-m)^2)/double(n);
+ factor4 = double((n-2)^2-m^2) / double(n-2);
+
+ zernike(n+1, m+1, 1, :) = factor1 * ((factor2*sbar.^2 - factor3) .* reshape(zernike(n-1, m+1, 1, :), [ns,1]) - factor4 * reshape(zernike(n-3, m+1, 1, :), [ns, 1]));
+ zernike(n+1, m+1, 2, :) = factor1 * (2.0*factor2*sbar .* reshape(zernike(n-1, m+1, 1, :), [ns,1]) + (factor2*sbar.^2 - factor3) .* reshape(zernike(n-1, m+1, 2, :), [ns,1]) - factor4 * reshape(zernike(n-3, m+1, 2, :), [ns,1]));
+ end
+
+ rm1 = rm;
+ rm = rm .* sbar;
+ end
+
+ for n = 2:2:Lrad
+ zernike(n+1,1,1,:) = zernike(n+1,1,1, :) - (-1)^(n/2);
+ end
+
+ if (Mpol >= 1)
+ for n = 3:2:Lrad
+ zernike(n+1,2,1,:) = reshape(zernike(n+1,2,1,:), [ns,1]) - (-1)^((n-1)/2) * double((n+1)/2) * sbar;
+ zernike(n+1,2,2,:) = reshape(zernike(n+1,2,2,:), [ns,1]) - (-1)^((n-1)/2) * double((n+1)/2);
+ end
+ end
+
+ for m = 0:Mpol
+ for n = m:2:Lrad
+ zernike(n+1,m+1,:,:) = zernike(n+1,m+1,:,:) / double(n+1);
+ end
+ end
+
+ % Store in T{}{} structure
+ for ll = 1:Lrad+1
+ T{ll}{1} = reshape(zernike(ll,:,1,:) , Mpol+1, length(sarr));
+ T{ll}{2} = reshape(zernike(ll,:,2,:) / 2.0, Mpol+1, length(sarr));
+ end
+
+ else % Otherwise construct Chebychev basis
+
+ for l=3:Lrad+1
+ T{l}{1} = 2*sarr.*T{l-1}{1} - T{l-2}{1};
+ T{l}{2} = 2*T{l-1}{1} + 2*sarr.*T{l-1}{2} - T{l-2}{2};
+ end
+
+ for l = 1:Lrad
+ T{l+1}{1} = T{l+1}{1} - (-1)^l;
+ end
+
+ for l = 0:Lrad
+ T{l+1}{1} = T{l+1}{1} / double(l+1); % scale for better conditioning
+ T{l+1}{2} = T{l+1}{2} / double(l+1); % scale for better conditioning
+ end
end
- end
-
- for m = 0:Mpol
- for n = m:2:Lrad
- zernike(n+1,m+1,:,:) = zernike(n+1,m+1,:,:) / double(n+1);
- end
- end
-
- % Store in T{}{} structure
- for ll = 1:Lrad+1
- T{ll}{1} = reshape(zernike(ll,:,1,:) , Mpol+1, length(sarr));
- T{ll}{2} = reshape(zernike(ll,:,2,:) / 2.0, Mpol+1, length(sarr));
- end
-
-else % Otherwise construct Chebychev basis
-
- for l=3:Lrad+1
- T{l}{1} = 2*sarr.*T{l-1}{1} - T{l-2}{1};
- T{l}{2} = 2*T{l-1}{1} + 2*sarr.*T{l-1}{2} - T{l-2}{2};
- end
-
- for l = 1:Lrad
- T{l+1}{1} = T{l+1}{1} - (-1)^l;
- end
-
- for l = 0:Lrad
- T{l+1}{1} = T{l+1}{1} / double(l+1); % scale for better conditioning
- T{l+1}{2} = T{l+1}{2} / double(l+1); % scale for better conditioning
- end
end
diff --git a/Utilities/matlabtools/get_spec_radius.m b/Utilities/matlabtools/get_spec_radius.m
deleted file mode 100644
index 09db55be..00000000
--- a/Utilities/matlabtools/get_spec_radius.m
+++ /dev/null
@@ -1,56 +0,0 @@
-function [r_out, z_out] = get_spec_radius(data, theta, zeta, vol)
-
-%
-% GET_SPEC_RADIUS( DATA, THETA, ZETA, VOL )
-% =========================================
-%
-% Return the radial position of a KAM surface for a given theta, zeta and
-% Nvol
-%
-% INPUT
-% -----
-% data Obtained via read_spec(filename)
-% theta: Poloidal angle
-% zeta: Toroidal angle
-% vol: Volume number
-%
-% OUPUT
-% -----
-% r_out: Radial position of the KAM surface
-
-
-% Load a bunch of stuff
-
-mn = data.output.mn;
-im = data.output.im;
-in = data.output.in;
-Rmn = data.output.Rbc;
-Zmn = data.output.Zbs;
-G = data.input.physics.Igeometry;
-
-
-switch G
- case 1
- r_out = 0;
-
- for k=1:mn
- r_out = r_out + Rmn(k, vol+1) * cos(double(im(k)) * theta - double(in(k)) * zeta);
- end
- z_out = 0;
- case 2
- r_out = 0;
-
- for k=1:mn
- r_out = r_out + Rmn(k, vol+1) * cos(double(im(k)) * theta - double(in(k)) * zeta);
- end
- z_out = 0;
- case 3
- r_out = 0;
- z_out = 0;
-
- for k=1:mn
- r_out = r_out + Rmn(k, vol+1) * cos(double(im(k)) * theta - double(in(k)) * zeta);
- z_out = z_out + Zmn(k, vol+1) * sin(double(im(k)) * theta - double(in(k)) * zeta);
- end
-
-end
diff --git a/Utilities/matlabtools/get_spec_regularisation_factor.m b/Utilities/matlabtools/get_spec_regularisation_factor.m
new file mode 100644
index 00000000..57516880
--- /dev/null
+++ b/Utilities/matlabtools/get_spec_regularisation_factor.m
@@ -0,0 +1,90 @@
+function fac = get_spec_regularisation_factor(data, lvol, sarr, ForG)
+
+%
+% GET_SPEC_REGULARISATION_FACTOR( DATA, LVOL, SARR, FORG )
+% ========================================================
+%
+% Computes the regularisation factor in the correct geometry
+%
+% INPUT
+% -----
+% data: Produced by read_spec(filename);
+% lvol: Volume number
+% sarr: s-coordinate array, shape (ns, 1)
+% ForG: 'F' for field reg. factor, 'G' for geometry reg. factor
+%
+% OUPUT
+% -----
+% fac: mnx2 cell array composed of fj and its derivatives
+%
+%
+% Written by A.Baillod (2019)
+%
+
+ ns = length( sarr );
+ sarr = reshape( sarr, ns, 1 );
+
+ Igeometry = data.input.physics.Igeometry;
+ mn = data.output.mn;
+ im = double(data.output.im);
+ ns = length(sarr);
+ fac = cell(mn,2);
+ sbar = (1+sarr)/2.0;
+
+ if ForG=='G'
+ switch Igeometry
+ case 1 % Slab geometry
+
+ for j=1:mn
+ fac{j}{1} = sbar;
+ fac{j}{2} = 0.5*ones(ns,1);
+ end
+
+ case 2 % Cylindrical geometry
+ for j=1:mn
+ if(lvol==1)
+ if im(j)==0
+ fac{j}{1} = sbar;
+ fac{j}{2} = 0.5*ones(ns,1);
+ else
+ fac{j}{1} = sbar.^(im(j)+1);
+ fac{j}{2} = reshape(0.5 * (im(j)+1) * fac{j}{1} ./ sbar, ns, 1);
+ end
+ else
+ fac{j}{1} = sbar;
+ fac{j}{2} = 0.5 * ones(ns,1);
+ end
+ end
+
+ case 3 % Toroidal geometry
+
+ for j=1:mn
+ if lvol==1 %coordinate singularity
+ if im(j)==0
+ fac{j}{1} = sbar.^2;
+ fac{j}{2} = sbar;
+ else
+ fac{j}{1} = sbar.^im(j);
+ fac{j}{2} = reshape(0.5 * im(j) * fac{j}{1} ./ sbar, ns, 1);
+ end
+ else
+ fac{j}{1} = sbar;
+ fac{j}{2} = 0.5 * ones(ns,1);
+ end
+ end
+ otherwise
+ error('Unsupported geometry in get_spec_regularisation_factor')
+ end
+
+
+
+ elseif ForG=='F'
+ for j=1:mn
+ fac{j}{1} = ones(ns,1);
+ fac{j}{2} = zeros(ns,1);
+ end
+
+ else
+ error('Unsupported ForG value in get_spec_regularisation_factor.')
+ end
+end
diff --git a/Utilities/matlabtools/get_spec_regularization_factor.m b/Utilities/matlabtools/get_spec_regularization_factor.m
deleted file mode 100644
index e64f4f04..00000000
--- a/Utilities/matlabtools/get_spec_regularization_factor.m
+++ /dev/null
@@ -1,137 +0,0 @@
-function fac = get_spec_regularization_factor(data, lvol, sarr, ForG)
-%
-%
-% Computes the regularisation factor in the correct geometry
-%
-% INPUT
-% -----
-% data: Produced by fdata_from_data(data);
-% lvol: Volume number
-% sarr: s-coordinate array, shape (ns, 1)
-% ForG: 'F' for field reg. factor, 'G' for geometry reg. factor
-%
-% OUPUT
-% -----
-% fac: mnx2 cell array composed of fj and its derivatives
-%
-%
-% Written by A.Baillod (2019)
-%
-%
-
-%sarr = transpose(sarr);
-
-Igeometry= data.input.physics.Igeometry;
-mn = data.output.mn;
-im = double(data.output.im);
-ns = length(sarr);
-fac = cell(mn,2);
-sbar = (1+sarr)/2.0;
-Mregular= double(data.input.numerics.Mregular);
-
-
-regumm = im / 2.0;
-if Mregular>1
- ind = find(regumm>Mregular);
- regumm(ind) = Mregular / 2.0;
-end
-
-halfmm = im / 2.0;
-
-
-
-if ForG=='G'
- switch Igeometry
- case 1 % Slab geometry
-
- for j=1:mn
- fac{j}{1} = sbar;
- fac{j}{2} = 0.5*ones(ns,1);
- end
-
- case 2 % Cylindrical geometry
- %TODO: add glab if Lextrap is not set to 1!
- for j=1:mn
- if(lvol==1)
- if im(j)==0
- fac{j}{1} = sqrt(sbar);
- fac{j}{2} = 0.25 * fac{j}{1} ./ sbar;
- else
- fac{j}{1} = sbar.^halfmm(j);
- fac{j}{2} = 0.5 * halfmm(j) * fac{j}{1} ./ sbar;
- end
- else
- fac{j}{1} = sbar;
- fac{j}{2} = 0.5 * ones(ns,1);
- end
- end
-
- case 3 % Toroidal geometry
-
- for j=1:mn
- if lvol==1 %coordinate singularity
- if im(j)==0
- fac{j}{1} = sbar;
- fac{j}{2} = 0.5;
- else
- fac{j}{1} = sbar.^halfmm(j);
- fac{j}{2} = 0.5 * halfmm(j) * fac{j}{1} ./ sbar;
- end
- else
- fac{j}{1} = sbar;
- fac{j}{2} = 0.5 * ones(ns,1);
- end
- end
- otherwise
- error('Unsupported geometry in get_spec_regularisation_factor')
- end
-
-
-
-elseif ForG=='F'
- switch Igeometry
- case 1
- for j=1:mn
- fac{j}{1} = ones(ns,1);
- fac{j}{2} = zeros(ns,1);
- end
-
- case 2
- for j=1:mn
- if lvol==1 % coordinate singularity
- if im(j)==0
- fac{j}{1} = 1;
- fac{j}{2} = 0;
- else
- fac{j}{1} = sbar.^regumm(j);
- fac{j}{2} = 0.5 * regumm(j) * fac{j}{1} ./ sbar;
- end
- else
- fac{j}{1} = 1;
- fac{j}{2} = 0;
- end
- end
-
- case 3
- for j=1:mn
- if lvol==1 % coordinate singularity
- if im(j)==0
- fac{j}{1} = 1;
- fac{j}{2} = 0;
- else
- fac{j}{1} = sbar.^regumm(j);
- fac{j}{2} = 0.5 * regumm(j) * fac{j}{1} ./ sbar;
- end
- else
- fac{j}{1} = 1;
- fac{j}{2} = 0;
- end
- end
-
- otherwise
- error('Unsupported geometry in get_spec_regularisation_factor')
- end
-
-else
- error('Unsupported ForG value in get_spec_regularisation_factor.')
-end
diff --git a/Utilities/matlabtools/get_spec_rtarr.m b/Utilities/matlabtools/get_spec_rtarr.m
deleted file mode 100644
index f9e557f3..00000000
--- a/Utilities/matlabtools/get_spec_rtarr.m
+++ /dev/null
@@ -1,66 +0,0 @@
-function rtdata = get_spec_rtarr(data,lvol,sarr,tarr,zarr0)
-
-%
-% GET_SPEC_RTARR( DATA, LVOL, SARR, TARR, ZARR0 )
-% ===============================================
-%
-% Transforms (s,theta) array into (R,theta) array in volume number lvol in slab or cylindrical geometry
-%
-% INPUT
-% -----
-% -data : must be produced by calling e.g. read_spec(filename)
-% -lvol : volume number
-% -sarr : is the array of values for the s-coordinate
-% -tarr : is the array of values for the theta-coordinate
-% -zarr : is the array of values for the zeta-coordinate
-%
-% OUTPUT
-% ------
-% -rtdata : array with (R,theta,dRds) data array with size 3*ns*nt where ns=length(sarr),nt=length(tarr)
-%
-% Note: Stellarator symmetry is assumed
-%
-% written by J.Loizu (2018)
-% updated by J.Loizu (2020)
-
-
-Rac = data.output.Rbc(:,lvol); % inner volume boundary harmonics
-Rbc = data.output.Rbc(:,lvol+1); % outer volume boundary harmonics
-
-if(size(sarr,1)==1)
-sarr = transpose(sarr);
-end
-
-ns = length(sarr);
-nt = length(tarr);
-sbar = (sarr+1)/2;
-
-mn = data.output.mn;
-im = double(data.output.im);
-in = double(data.output.in);
-
-Rarr = zeros(ns,nt); % allocate data for R-array
-Tarr = zeros(ns,nt); % allocate data for theta-array
-dRarr = zeros(ns,nt); % allocate data for R-array derivative (in s)
-
-
-
-% Construct regularization factors
-
-fac = get_spec_regularization_factor(data, lvol, sarr, 'G');
-
-% Construct (R,theta) coordinates array
-
-for j=1:mn
- for it=1:nt
- cosa = cos(im(j)*tarr(it)-in(j)*zarr0);
- sina = sin(im(j)*tarr(it)-in(j)*zarr0);
- Rarr(:,it) = Rarr(:,it) + (Rac(j) + fac{j}{1}.*(Rbc(j)-Rac(j)) )*cosa;
- dRarr(:,it) = dRarr(:,it) + fac{j}{2}*(Rbc(j)-Rac(j))*cosa;
- Tarr(:,it) = tarr(it);
- end
-end
-
-rtdata{1} = Rarr;
-rtdata{2} = Tarr;
-rtdata{3} = dRarr;
diff --git a/Utilities/matlabtools/get_spec_rzarr.m b/Utilities/matlabtools/get_spec_rzarr.m
deleted file mode 100644
index 65dc9b8e..00000000
--- a/Utilities/matlabtools/get_spec_rzarr.m
+++ /dev/null
@@ -1,63 +0,0 @@
-function rzdata = get_spec_rzarr(data,lvol,sarr,tarr,zarr)
-
-%
-% GET_SPEC_RZARR( DATA, LVOL, SARR, TARR, ZARR )
-% ==============================================
-%
-% Transforms (s,theta,zeta) array into (R,Z) array in volume number lvol
-%
-% INPUT
-% -----
-% -data : must be produced by calling e.g. read_spec(filename)
-% -lvol : volume number
-% -sarr : is the array of values for the s-coordinate
-% -tarr : is the array of values for the theta-coordinate
-% -zarr : is the array of values for the zeta-coordinate
-%
-% OUTPUT
-% ------
-% -rzdata : array with (R,Z) data array with size 2*ns*nt*nz where ns=length(sarr),nt=length(zarr),nt=length(zarr)
-%
-% Note: Stellarator symmetry is assumed
-%
-% written by J.Loizu (2016)
-
-
-Rac = data.output.Rbc(:,lvol); % inner volume boundary harmonics
-Zas = data.output.Zbs(:,lvol);
-Rbc = data.output.Rbc(:,lvol+1); % outer volume boundary harmonics
-Zbs = data.output.Zbs(:,lvol+1);
-
-sarr = transpose(sarr);
-ns = length(sarr);
-nt = length(tarr);
-nz = length(zarr);
-sbar = (sarr+1)/2;
-
-mn = data.output.mn;
-im = double(data.output.im);
-in = double(data.output.in);
-
-Rarr = zeros(ns,nt,nz); % allocate data for R-array
-Zarr = zeros(ns,nt,nz); % allocate data for Z-array
-
-
-% Construct REG FACTOR
-
-fac = get_spec_regularisation_factor(data, lvol, sarr', 'G');
-
-% Construct (R,Z) coordinates array
-
-for j=1:mn
- for it=1:nt
- for iz=1:nz
- cosa = cos(im(j)*tarr(it)-in(j)*zarr(iz));
- sina = sin(im(j)*tarr(it)-in(j)*zarr(iz));
- Rarr(:,it,iz) = Rarr(:,it,iz) + (Rac(j) + fac{j}{1}.*(Rbc(j)-Rac(j)) )*cosa;
- Zarr(:,it,iz) = Zarr(:,it,iz) + (Zas(j) + fac{j}{1}.*(Zbs(j)-Zas(j)) )*sina;
- end
- end
-end
-
-rzdata{1} = Rarr;
-rzdata{2} = Zarr;
diff --git a/Utilities/matlabtools/get_spec_straight_fieldlines.m b/Utilities/matlabtools/get_spec_straight_fieldlines.m
new file mode 100644
index 00000000..3f396096
--- /dev/null
+++ b/Utilities/matlabtools/get_spec_straight_fieldlines.m
@@ -0,0 +1,37 @@
+%% GET_SPEC_STRAIGHT_FIELDLINES( d, NPOINTS, Nperiods )
+% =======================================================
+%
+% Gives as output the straightfieldlines coordinates from SPEC out file
+%
+% INPUT
+% -----
+% -data : must be produced by calling read_boozer(filename, root)
+% -Npoints : number of points for toroidal resolution
+% -Nperiods : number of toroidal periods
+%
+% ------------------------------------%
+% Written by S.Guinchard (05/17/22) %
+% ------------------------------------%
+function SFL_coord = get_spec_straight_fieldlines(d,Npoints,Nperiods)
+
+ m = double(d.output.ims);
+ n = double(d.output.ins);
+ lambda_mn = d.output.lambdamn(1:end,1,2);
+
+ coord = plot_spec_fieldlines(d,Npoints,Nperiods,0);
+ theta = coord.theta;
+ phi = coord.phi;
+
+ theta_sfl = theta;
+
+ for i = 1:length(phi)
+ for j = 1:length(lambda_mn)
+
+ theta_sfl(i) = theta_sfl(i) + lambda_mn(j,1,1)*sin(m(j)*theta(i) - n(j)*phi(i));
+
+ end
+ end
+
+ SFL_coord.theta_sfl = wrapTo2Pi(theta_sfl);
+ SFL_coord.phi = wrapTo2Pi(phi);
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/get_spec_surface_current.m b/Utilities/matlabtools/get_spec_surface_current.m
deleted file mode 100644
index f7ebf12e..00000000
--- a/Utilities/matlabtools/get_spec_surface_current.m
+++ /dev/null
@@ -1,66 +0,0 @@
-function [tflux, IPDt] = get_spec_surface_current(data, ns, nt, zeta)
-
-%
-% GET_SPEC_SURFACE_CURRENT( DATA, NS, NT, ZETA )
-% ==============================================
-%
-% OUTDATED - should directly do 2*pi*[[B_\theta]]
-%
-% Returns the sheet current flowing through each interface, normalized by
-% mu_0. This routine computes the actual integral of the poloidal field to
-% compute the current via Ampere's law. This requires to specify zeta;
-% however, since the surface current is a flux function, zeta should not
-% have any influence on the result.
-%
-% INPUT
-% -----
-% data: data obtained via read_spec(filename)
-% ns: Radial resolution
-% nt: Poloidal resolution
-% zeta: Toroidal angle - see introduction remark
-%
-% OUTPUT
-% ------
-% tflux: The toroidal flux enclosed by each interface (1xNvol)
-% IPDt: The toroidal surface current in each interface (1xNvol-1),
-% normalized by mu_0
-%
-% Written by A.Baillod (2019)
-
-
-% Constant definition
-mu0 = 4*pi*1E-7;
-epsilon = 1E-5;
-
-% Data loading
-Nvol = data.output.Mvol; % Total number of volumes
-sarr = linspace(-1, 1, ns);
-
-% Allocate memory
-Bcov = cell(1, Nvol);
-
-theta = linspace(0, 2*pi, nt);
-
-IPDt = zeros(1, Nvol-1);
-
-% Get magnetic field
-for ivol=1:Nvol
- if ivol==1
- sarr(1)=-1+epsilon;
- else
- sarr(1)=-1;
- end
-
- temp = get_spec_magfield(data, ivol, sarr, theta, zeta);
-
- Bcov{ivol} = contra2cov(data, ivol, temp, sarr, theta, zeta, 0);
-end
-
-for ivol=1:Nvol-1
- dBtheta = -Bcov{ivol}{2}(end,:,1) + Bcov{ivol+1}{2}(1,:,1);
- IPDt(ivol) = trapz(theta, dBtheta);
-end
-
-tflux = data.output.tflux;
-
-end
diff --git a/Utilities/matlabtools/get_spec_torcurr_kam_net.m b/Utilities/matlabtools/get_spec_torcurr_kam_net.m
index 36e68f7c..08303b6d 100644
--- a/Utilities/matlabtools/get_spec_torcurr_kam_net.m
+++ b/Utilities/matlabtools/get_spec_torcurr_kam_net.m
@@ -20,17 +20,16 @@
% written by J.Loizu (2017)
-Nvol = data.input.physics.Nvol;
-Itor = zeros(1,Nvol-1);
+Mvol = data.output.Mvol;
+Itor = zeros(1,Mvol-1);
zarr = 0;
tarr = linspace(0,2*pi,ntheta);
-dtheta = tarr(2)-tarr(1);
sarr = [1 -1];
intB = [0 0];
-for ikam=1:Nvol-1
+for ikam=1:Mvol-1
lvol = [ikam ikam+1];
@@ -43,9 +42,9 @@
Bt = Bcontrav{2};
Bz = Bcontrav{3};
- gst = gmat{1}{2};
- gtt = gmat{2}{2};
- gzt = gmat{3}{2};
+ gst = gmat{1,2};
+ gtt = gmat{2,2};
+ gzt = gmat{3,2};
intB(i) = trapz(tarr, Bs.*gst + Bt.*gtt + Bz.*gzt);
diff --git a/Utilities/matlabtools/get_spec_torflux.m b/Utilities/matlabtools/get_spec_torflux.m
index 141ef64d..d90e7ebc 100644
--- a/Utilities/matlabtools/get_spec_torflux.m
+++ b/Utilities/matlabtools/get_spec_torflux.m
@@ -26,28 +26,55 @@
% modified by J.Loizu (06.2017)
% modified by A.Baillod (06.2019) - added switch for geometry
+ %Check inputs
+ Igeometry = data.input.physics.Igeometry;
+ if lvol==1 && Igeometry~=1 && start==1
+ error('InputError: start should be >1 in first volume')
+ end
-sarr = linspace(start,send,ns);
+ Mvol = data.output.Mvol;
+ if lvol<1 || lvol>Mvol
+ error('InputError: Invalid lvol')
+ end
-tarr = linspace(0,2*pi,nt);
+ if start<-1 || start>send
+ error('InputError: invalid start')
+ end
-ds = sarr(2)-sarr(1);
+ if send1
+ error('InputError: invalid send')
+ end
-dth = tarr(2)-tarr(1);
+ if ns<1
+ error('InputError: invalid ns')
+ end
-if(ds==0 || dth==0)
+ if nt<1
+ error('InputError: invalid nt')
+ end
- psitor = 0;
-
-else
+ % Prepare coordinate arrays
+ sarr = linspace(start,send,ns);
+ tarr = linspace(0,2*pi,nt);
-Bcontrav = get_spec_magfield(data,lvol,sarr,tarr,zeta);
-jac = get_spec_jacobian(data,lvol,sarr,tarr,zeta);
-
+ ds = sarr(2)-sarr(1);
- % Compute surface integral
+ dth = tarr(2)-tarr(1);
- Bzeta = Bcontrav{3};
- psitor = sum(sum( jac(2:end,:).*Bzeta(2:end,:) ))*ds*dth;
+ if(ds==0 || dth==0)
+
+ psitor = 0;
+
+ else
+
+ Bcontrav = get_spec_magfield(data,lvol,sarr,tarr,zeta);
+ jac = get_spec_jacobian(data,lvol,sarr,tarr,zeta);
+
+
+ % Compute surface integral
+
+ Bzeta = Bcontrav{3};
+ psitor = trapz( sarr, trapz( tarr, jac.*Bzeta, 2 ) );
+ end
end
diff --git a/Utilities/matlabtools/get_spec_vecpot.m b/Utilities/matlabtools/get_spec_vecpot.m
index d594a2d4..66ef9035 100644
--- a/Utilities/matlabtools/get_spec_vecpot.m
+++ b/Utilities/matlabtools/get_spec_vecpot.m
@@ -20,67 +20,74 @@
%
% written by J.Loizu (2018)
+ % Test input
+ Mvol = data.output.Mvol;
+ if lvol<1 || lvol>Mvol
+ error('InputError: invalid lvol')
+ end
-Ate = data.vector_potential.Ate{lvol};
-Aze = data.vector_potential.Aze{lvol};
-Ato = data.vector_potential.Ato{lvol};
-Azo = data.vector_potential.Azo{lvol};
-
-Lrad = data.input.physics.Lrad(lvol);
-
-if(size(sarr,1)==1)
-sarr = transpose(sarr);
-end
-ns = length(sarr);
-nt = length(tarr);
-nz = length(zarr);
-sbar = (sarr+1)/2;
-
-mn = data.output.mn;
-im = double(data.output.im);
-in = double(data.output.in);
-
-At = zeros(ns,nt,nz); % allocate data for vector potential along theta
-Az = zeros(ns,nt,nz); % allocate data for vector potential along zeta
-
-
-% Construct Chebyshev polynomials
-
-T = get_spec_polynomial_basis(data, lvol, sarr);
-
-% Construct regularization factors
-
-fac = get_spec_regularization_factor(data, lvol, sarr, 'F');
+ if isempty(sarr)
+ error('InputError: empty sarr')
+ end
+ if isempty(tarr)
+ error('InputError: empty tarr')
+ end
+ if isempty(zarr)
+ error('InputError: empty zarr')
+ end
-% Construct vector potential covariant components
+ if sarr(1)<-1 || sarr(end)>1
+ error('InputError: invalid sarr')
+ end
-Lsingularity = false;
-if (lvol==1) && (data.input.physics.Igeometry~=1)
- Lsingularity = true;
-end
+ % Read data
+ Ate = data.vector_potential.Ate{lvol};
+ Aze = data.vector_potential.Aze{lvol};
+ Ato = data.vector_potential.Ato{lvol};
+ Azo = data.vector_potential.Azo{lvol};
+ Lrad = data.input.physics.Lrad(lvol);
-for l=1:Lrad+1
- for j=1:mn
- if( Lsingularity )
- basis = T{l}{1}(im(j)+1);
- dbasis = T{l}{2}(im(j)+1);
- else
- basis = T{l}{1};
- dbasis = T{l}{2};
+ if(size(sarr,1)==1)
+ sarr = transpose(sarr);
end
-
- for it=1:nt
- for iz=1:nz
- cosa = cos(im(j)*tarr(it)-in(j)*zarr(iz));
- sina = sin(im(j)*tarr(it)-in(j)*zarr(iz));
- At(:,it,iz) = At(:,it,iz) + fac{j}{1}.* basis.*( Ate(l,j)*cosa + Ato(l,j)*sina );
- Az(:,it,iz) = Az(:,it,iz) + fac{j}{1}.* basis.*( Aze(l,j)*cosa + Azo(l,j)*sina );
- end
+ ns = length(sarr);
+ nt = length(tarr);
+ nz = length(zarr);
+
+ mn = data.output.mn;
+ im = double(data.output.im);
+ in = double(data.output.in);
+
+ At = zeros(ns,nt,nz); % allocate data for vector potential along theta
+ Az = zeros(ns,nt,nz); % allocate data for vector potential along zeta
+
+ % Construct vector potential covariant components
+ T = get_spec_polynomial_basis(data, lvol, sarr);
+
+ % Construct vector potential covariant components
+ Lsingularity = (lvol==1) && (data.input.physics.Igeometry~=1);
+
+ for l=1:Lrad+1
+ for j=1:length(im)
+ if( Lsingularity )
+ basis = T{l}{1}(im(j)+1);
+ else
+ basis = T{l}{1};
+ end
+
+ for it=1:nt
+ for iz=1:nz
+ cosa = cos(im(j)*tarr(it)-in(j)*zarr(iz));
+ sina = sin(im(j)*tarr(it)-in(j)*zarr(iz));
+ At(:,it,iz) = At(:,it,iz) + basis.*( Ate(l,j)*cosa + Ato(l,j)*sina );
+ Az(:,it,iz) = Az(:,it,iz) + basis.*( Aze(l,j)*cosa + Azo(l,j)*sina );
+ end
+ end
+ end
end
- end
-end
-Acov{1} = At;
-Acov{2} = Az;
+ Acov{1} = At;
+ Acov{2} = Az;
+end
diff --git a/Utilities/matlabtools/get_spec_volume.m b/Utilities/matlabtools/get_spec_volume.m
index 72c281da..0697cfb4 100644
--- a/Utilities/matlabtools/get_spec_volume.m
+++ b/Utilities/matlabtools/get_spec_volume.m
@@ -22,11 +22,33 @@
%
% written by J.Loizu (2016)
+ % Test input
+ Mvol = data.output.Mvol;
+ if lvol<1 || lvol>Mvol
+ error('InputError: invalid lvol')
+ end
+ if ns<1
+ error('Invalid ns')
+ end
+ if nt<1
+ error('Invalid nt')
+ end
+ if nz<1
+ error('Invalid nz')
+ end
-sarr = linspace(-1,1,ns);
-tarr = linspace(0,2*pi,nt);
-zarr = linspace(0,2*pi,nz);
+ Igeometry=data.input.physics.Igeometry;
+ if lvol==1 && Igeometry~=1
+ start=-0.999;
+ else
+ start=-1;
+ end
+
+ sarr = linspace(start,1,ns);
+ tarr = linspace(0,2*pi,nt);
+ zarr = linspace(0,2*pi,nz);
-jacobian = get_spec_jacobian(data,lvol,sarr,tarr,zarr);
+ jacobian = get_spec_jacobian(data,lvol,sarr,tarr,zarr);
-volume = sum(sum(sum(jacobian(2:end,:,:))))*(2*2*pi*2*pi)/(ns*nt*nz);
+ volume = trapz(sarr, trapz(tarr, trapz(zarr, jacobian, 3), 2) );
+end
diff --git a/Utilities/matlabtools/get_spec_volume_current.m b/Utilities/matlabtools/get_spec_volume_current.m
index 136d196f..8c3868e9 100644
--- a/Utilities/matlabtools/get_spec_volume_current.m
+++ b/Utilities/matlabtools/get_spec_volume_current.m
@@ -9,47 +9,47 @@
% INPUT
% -----
% data: data obtained via read_spec(filename)
+% cumul: Choose if quantity is cumulative or not
%
% OUTPUT
% ------
% psi_coord: The toroidal flux enclosed by each interface
% I_vol: The toroidal volume current flowing in each volume
-% (cumulative)
%
% Written by A.Baillod (2019)
-% Data loading
-Nvol = data.input.physics.Nvol; % Total number of volumes
+ % Data loading
+ Mvol = data.output.Mvol; % Total number of volumes
-% Data processing
+ % Data processing
-% First, get the current in each volume
-psi_coord = zeros(1, Nvol); % Allocate memory
-I_vol = zeros(1, Nvol);
+ % First, get the current in each volume
+ psi_coord = zeros(1, Mvol); % Allocate memory
+ I_vol = zeros(1, Mvol);
-mu = data.output.mu;
-tflux = data.output.tflux;
-sumI = 0;
-phiedge = data.input.physics.phiedge;
-
-for ivol=1:Nvol
+ mu = data.output.mu;
+ tflux = data.output.tflux;
+ sumI = 0;
+ phiedge = data.input.physics.phiedge;
- if ivol==1
- I_vol(ivol) = mu(ivol) * tflux(ivol) * phiedge;
- else
- % Add previous current volumes (sumI) since we use a cumulative
- % representation
- if cumul
- I_vol(ivol) = mu(ivol) * (tflux(ivol) - tflux(ivol-1)) * phiedge + sumI;
+ for ivol=1:Mvol
+
+ if ivol==1
+ I_vol(ivol) = mu(ivol) * tflux(ivol) * phiedge;
else
- I_vol(ivol) = mu(ivol) * (tflux(ivol) - tflux(ivol-1)) * phiedge;
+ % Add previous current volumes (sumI) since we use a cumulative
+ % representation
+ if cumul
+ I_vol(ivol) = mu(ivol) * (tflux(ivol) - tflux(ivol-1)) * phiedge + sumI;
+ else
+ I_vol(ivol) = mu(ivol) * (tflux(ivol) - tflux(ivol-1)) * phiedge;
+ end
end
+
+ psi_coord(ivol) = tflux(ivol);
+
+ sumI = I_vol(ivol);
end
-
- psi_coord(ivol) = tflux(ivol);
-
- sumI = I_vol(ivol);
-end
end
diff --git a/Utilities/matlabtools/plot_SFL_modB.m b/Utilities/matlabtools/plot_SFL_modB.m
new file mode 100644
index 00000000..207414d5
--- /dev/null
+++ b/Utilities/matlabtools/plot_SFL_modB.m
@@ -0,0 +1,53 @@
+%% plot_SFL_modB( DATA, NTHETA, NPHI, FILLED, NEWFIG )
+% =============================================
+%
+% Plot of modB in SFL coordinates
+%
+% INPUT
+% -----
+% -data : must be produced by calling read_spec(filename)
+% -Ntheta : number of meshpoints for theta array
+% -Nphi : number of meshpoints for phi array
+% -filled : (=1) pcolor, (=2) contourplot
+% -newfig : opens (=1) or not (=0) a newfig or overwrites (=2)
+% previous figure
+%
+% ------------------------------------%
+% Written by S.Guinchard (05/23/22) %
+% ------------------------------------%
+function plot_SFL_modB(b, Ntheta, Nphi, filled, Newfig)
+
+ modB = get_SFL_fourier_modB(b,Ntheta,Nphi);
+ Theta = modB.Theta;
+ Phi = modB.Phi;
+ modB = modB.modB;
+
+ switch Newfig
+
+ case 0
+ hold on
+
+ case 1
+ figure
+
+ case 2
+ hold off
+
+ end
+
+ switch filled
+
+ case 1
+ pcolor(Phi, Theta, modB);
+ shading interp
+ colorbar
+ hold on
+ contour(Phi, Theta, modB, 6, 'k', 'linewidth', 1)
+
+ case 2
+ %contourf(Theta, Phi, modB,linspace(min(min(modB)), max(max(modB)),20));
+ contour(Phi, Theta, modB,linspace(min(min(modB)), max(max(modB)),20), 'linewidth', 1.5)
+ colorbar
+ colormap(jet)
+ end
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/plot_SFL_modB_boundary.m b/Utilities/matlabtools/plot_SFL_modB_boundary.m
new file mode 100644
index 00000000..b6b812b6
--- /dev/null
+++ b/Utilities/matlabtools/plot_SFL_modB_boundary.m
@@ -0,0 +1,104 @@
+function plot_SFL_modB_boundary(data,interface,innout,nt,nz,dimension)
+
+%
+% PLOT_SPEC_MODB_BOUNDARY( BDATA, DATA, VOL, NT, NZ )
+% ============================================
+%
+% Produces plot of |B|_b on the full boundary surface in toroidal geometry.
+%
+% INPUT
+% -----
+% -bdata : data obtained via read_boozer(filename, root)
+% -data : data obtained via read_spec(filename)
+% -interface : Volume on which modB should be plotted
+% -innout: (0) - inner side of interface
+% (1) - outer side of interface
+% -nt : poloidal resolution for the plotting (e.g. nt=64)
+% -nz : toroidal resolution for the plotting (e.g. nz=64)
+% -dimension: (2) - plot a colorplot on a theta-phi grid
+% (3) - plot a colorplot on a 3d surface
+%
+% ------------------------------------%
+% Written by S.Guinchard (05/30/22) %
+% ------------------------------------%
+%
+% TODO: adapt for more than 1 volume
+% when booz_xform has been adapted
+innout =0;
+interface = 1;
+Mvol = data.output.Mvol;
+
+if interface<1 || interface>Mvol
+ error('Invalid interface')
+end
+
+switch innout
+ case 0
+ vol = interface;
+ sarr = 1;
+ case 1
+ if interface==Mvol
+ error('Cannot plot on the outer side of last interface!')
+ end
+ vol = interface+1;
+ sarr = -1;
+ otherwise
+ error('Interface should be 0 or 1')
+end
+
+tarr = linspace(0,2*pi,nt);
+zarr = linspace(0,2*pi,nz);
+
+if(vol>Mvol || vol<1)
+ error('vol not valid')
+end
+
+
+switch dimension
+ case 2
+
+ plot_SFL_modB(data,nt,nz,1,1)
+ xlabel('$\phi_b$', 'Interpreter', 'latex')
+ ylabel('$\theta_b$', 'Interpreter', 'latex')
+ set(gca,'FontSize',20)
+ set(gcf,'Position',[200 200 900 700])
+
+
+ case 3
+
+ % Compute |B|
+ modB = get_SFL_fourier_modB(data,nt,nz);
+
+ % Compute function (R,Z)(s,theta,zeta)
+ sarr = 1;
+ rzdata = get_spec_rzarr(data,vol,sarr,tarr,zarr);
+
+ R = squeeze(rzdata{1});
+ Z = squeeze(rzdata{2});
+
+
+ % Construct cartesian corrdinates
+
+ X = zeros(nt,nz);
+ Y = zeros(nt,nz);
+
+ for it=1:nt
+ for iz=1:nz
+ X(it,iz) = R(it,iz)*cos(zarr(iz));
+ Y(it,iz) = R(it,iz)*sin(zarr(iz));
+ end
+ end
+
+
+ % Plot
+
+ figure
+ h=surf(X,Y,Z,squeeze(modB.modB));
+ axis equal
+ shading interp
+ colorbar
+ title('$| B_b |$', 'interpreter', 'latex')
+
+ otherwise
+ error('Invalid dimension')
+end
diff --git a/Utilities/matlabtools/plot_boozer_fieldlines.m b/Utilities/matlabtools/plot_boozer_fieldlines.m
new file mode 100644
index 00000000..53a89108
--- /dev/null
+++ b/Utilities/matlabtools/plot_boozer_fieldlines.m
@@ -0,0 +1,72 @@
+%% plot_boozer_fieldlines( COORDB, NEWFIG )
+% =============================================
+%
+% Plots a magnetic fieldline in Boozer coordinates
+% starting from the point (thetab, phib) = (0,0)
+%
+% INPUT
+% -----
+%
+% -coordb : must be produced using get_boozer_coordinates
+% -Newfig : opens (=1) or not (=0) a new figure, or overwrites (=2)
+% last plot
+%
+% ------------------------------------%
+% Written by S.Guinchard (05/15/22) %
+% ------------------------------------%
+
+function plot_boozer_fieldlines(coordb, Newfig)
+
+ phiB = coordb.phib;
+ thetaB = coordb.thetab;
+ Fs = 18;
+ switch Newfig
+
+ case 0
+ hold on
+ scatter(phiB, thetaB, 'k.')
+ ax = gca;
+ ax.TickLabelInterpreter = 'latex';
+ xticks([0 pi/3 2*pi/3 pi 4*pi/3 5*pi/3 2*pi])
+ xticklabels({'$0$','$\frac{\pi}{3}$','$\frac{2\pi}{3}$','$\pi$', '$\frac{4\pi}{3}$','$\frac{5\pi}{3}$','$2\pi$'});
+ yticks([0 pi/3 2*pi/3 pi 4*pi/3 5*pi/3 2*pi])
+ yticklabels({'$0$','$\frac{\pi}{3}$','$\frac{2\pi}{3}$','$\pi$', '$\frac{4\pi}{3}$','$\frac{5\pi}{3}$','$2\pi$'});
+ xlim([0 2*pi])
+ ylim([0 2*pi])
+ set (gca, 'fontsize', Fs)
+ xlabel('$\phi_B$', 'FontSize', Fs+10 , 'Interpreter', 'latex')
+ ylabel('$\theta_B$', 'FontSize', Fs+10 , 'Interpreter', 'latex')
+
+ case 1
+ figure
+ scatter(phiB, thetaB, 'k.')
+ ax = gca;
+ ax.TickLabelInterpreter = 'latex';
+ xticks([0 pi/3 2*pi/3 pi 4*pi/3 5*pi/3 2*pi])
+ xticklabels({'$0$','$\frac{\pi}{3}$','$\frac{2\pi}{3}$','$\pi$', '$\frac{4\pi}{3}$','$\frac{5\pi}{3}$','$2\pi$'});
+ yticks([0 pi/3 2*pi/3 pi 4*pi/3 5*pi/3 2*pi])
+ yticklabels({'$0$','$\frac{\pi}{3}$','$\frac{2\pi}{3}$','$\pi$', '$\frac{4\pi}{3}$','$\frac{5\pi}{3}$','$2\pi$'});
+ xlim([0 2*pi])
+ ylim([0 2*pi])
+ set (gca, 'fontsize', Fs)
+ xlabel('$\phi_B$', 'FontSize', Fs+10 , 'Interpreter', 'latex')
+ ylabel('$\theta_B$', 'FontSize', Fs+10 , 'Interpreter', 'latex')
+
+ case 2
+ hold off
+ scatter(phiB, thetaB, 'k.')
+ ax = gca;
+ ax.TickLabelInterpreter = 'latex';
+ xticks([0 pi/3 2*pi/3 pi 4*pi/3 5*pi/3 2*pi])
+ xticklabels({'$0$','$\frac{\pi}{3}$','$\frac{2\pi}{3}$','$\pi$', '$\frac{4\pi}{3}$','$\frac{5\pi}{3}$','$2\pi$'});
+ yticks([0 pi/3 2*pi/3 pi 4*pi/3 5*pi/3 2*pi])
+ yticklabels({'$0$','$\frac{\pi}{3}$','$\frac{2\pi}{3}$','$\pi$', '$\frac{4\pi}{3}$','$\frac{5\pi}{3}$','$2\pi$'});
+ xlim([0 2*pi])
+ ylim([0 2*pi])
+ set (gca, 'fontsize', Fs)
+ xlabel('$\phi_B$', 'FontSize', Fs+10 , 'Interpreter', 'latex')
+ ylabel('$\theta_B$', 'FontSize', Fs+10 , 'Interpreter', 'latex')
+
+ end
+
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/plot_boozer_modB.m b/Utilities/matlabtools/plot_boozer_modB.m
new file mode 100644
index 00000000..6ffeb0cc
--- /dev/null
+++ b/Utilities/matlabtools/plot_boozer_modB.m
@@ -0,0 +1,53 @@
+%% plot_boozer_modB( BDATA, NTHETA, NPHI, FILLED, NEWFIG )
+% =============================================
+%
+% Plot of modB in Boozer coordinates
+%
+% INPUT
+% -----
+% -bdata : must be produced by calling read_boozer(filename,root)
+% -Ntheta : number of meshpoints for theta array
+% -Nphi : number of meshpoints for phi array
+% -filled : (=1) pcolor, (=2) contourplot
+% -newfig : opens (=1) or not (=0) a newfig or overwrites (=2)
+% previous figure
+%
+% ------------------------------------%
+% Written by S.Guinchard (05/18/22) %
+% ------------------------------------%
+function plot_boozer_modB(b, Ntheta, Nphi, filled, Newfig)
+
+ modB = get_boozer_modB(b,Ntheta,Nphi);
+ Theta = modB.Theta;
+ Phi = modB.Phi;
+ modB = modB.modB;
+
+ switch Newfig
+
+ case 0
+ hold on
+
+ case 1
+ figure
+
+ case 2
+ hold off
+
+ end
+
+ switch filled
+
+ case 1
+ pcolor(Phi, Theta, modB);
+ shading interp
+ colorbar
+ hold on
+ contour(Phi, Theta, modB, 6, 'k', 'linewidth', 1)
+
+ case 2
+
+ contour(Phi, Theta, modB,linspace(min(min(modB)), max(max(modB)),20), 'linewidth', 1.5)
+ colorbar
+ colormap(jet)
+ end
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/plot_boozer_modB_boundary.m b/Utilities/matlabtools/plot_boozer_modB_boundary.m
new file mode 100644
index 00000000..8701c155
--- /dev/null
+++ b/Utilities/matlabtools/plot_boozer_modB_boundary.m
@@ -0,0 +1,123 @@
+function plot_boozer_modB_boundary(b,data,interface,innout,nt,nz,dimension, newfig)
+
+% PLOT_BOOZER_MODB_BOUNDARY( BDATA, DATA, INTERFACE, INNOUT, NT, NZ, DIM, NEWFIG )
+% ============================================
+%
+% Produces plot of |B|_b on the full boundary surface in toroidal geometry.
+%
+% INPUT
+% -----
+% -bdata : data obtained via read_boozer(filename, root)
+% -data : data obtained via read_spec(filename)
+% -interface : Volume on which modB should be plotted
+% -innout: (0) - inner side of interface
+% (1) - outer side of interface
+% -nt : poloidal resolution for the plotting (e.g. nt=64)
+% -nz : toroidal resolution for the plotting (e.g. nz=64)
+% -dimension: (2) - plot a colorplot on a theta-phi grid
+% (3) - plot a colorplot on a 3d surface
+% -newfig: opens (=1) or not (=0) a new figure or ovewrites (=2) previous
+% plot
+%
+% ------------------------------------%
+% Written by S.Guinchard (05/30/22) %
+% ------------------------------------%
+%
+% TODO: adapt for more than 1 volume
+% when booz_xform has been adapted
+
+innout = 0; % will be changed when adapted
+interface = 1;
+Mvol = (b.Booz_xForms.Inputs.ns_in+1)/2;
+
+if interface<1 || interface>Mvol
+ error('Invalid interface')
+end
+
+switch innout
+ case 0
+ vol = interface;
+ sarr = 1;
+ case 1
+ if interface==Mvol
+ error('Cannot plot on the outer side of last interface!')
+ end
+ vol = interface+1;
+ sarr = -1;
+ otherwise
+ error('Interface should be 0 or 1')
+end
+
+tarr = linspace(0,2*pi,nt);
+zarr = linspace(0,2*pi,nz);
+
+if(vol>Mvol || vol<1)
+ error('vol not valid')
+end
+
+
+switch dimension
+ case 2
+
+ switch newfig
+ case 0
+ hold on
+ case 1
+ figure
+ case 2
+ hold off
+ end
+ plot_boozer_modB(b,nt,nz,1,0)
+ xlabel('$\phi_b$', 'Interpreter', 'latex')
+ ylabel('$\theta_b$', 'Interpreter', 'latex')
+ set(gca,'FontSize',20)
+ set(gcf,'Position',[200 200 900 700])
+
+
+ case 3
+
+ switch newfig
+ case 0
+ hold on
+ case 1
+ figure
+ case 2
+ hold off
+ end
+ % Compute |B|
+
+ modB = get_boozer_modB(b,nt,nz);
+ % Compute function (R,Z)(s,theta,zeta)
+ sarr = 1;
+ rzdata = get_spec_rzarr(data,vol,sarr,tarr,zarr);
+
+ R = squeeze(rzdata{1});
+ Z = squeeze(rzdata{2});
+
+
+ % Construct cartesian coordinates
+
+ X = zeros(nt,nz);
+
+ Y = zeros(nt,nz);
+
+ for it=1:nt
+ for iz=1:nz
+ X(it,iz) = R(it,iz)*cos(zarr(iz));
+ Y(it,iz) = R(it,iz)*sin(zarr(iz));
+ end
+ end
+
+
+ % Plot
+
+ h=surf(X,Y,Z,squeeze(modB.modB));
+
+ axis equal
+ shading interp
+ colorbar
+ title('$| B_b |$', 'interpreter', 'latex')
+
+ otherwise
+ error('Invalid dimension')
+end
diff --git a/Utilities/matlabtools/plot_spec_Bfield.m b/Utilities/matlabtools/plot_spec_Bfield.m
deleted file mode 100644
index 4d97c366..00000000
--- a/Utilities/matlabtools/plot_spec_Bfield.m
+++ /dev/null
@@ -1,66 +0,0 @@
-function plot_spec_Bfield(data, component, theta, phi, nr, newfig)
-
-%
-% PLOT_SPEC_BFIELD( DATA, COMPONENT, THETA, PHI, NR, NEWFIG )
-% ===========================================================
-%
-% Plot SPEC magnetic field solution
-%
-% INPUT
-% -----
-% data: data obtained from read_spec(filename)
-% component: ='psi' to plot r-component, 'theta' to plot theta component
-% and 'phi' to plot phi component, ='all' for all components
-% theta: Angle theta at which the field is plotted
-% phi: Angle phi at which the field is plotted
-% nr: Number of radial points
-% newfig: open (=1) a new figure or use the current figure and hold
-% on (=0) or old off (=2)
-%
-%
-% Written by A.Baillod (2019)
-
- switch newfig
- case 0
- hold on;
- case 1
- figure
- hold on;
- case 2
- hold off;
- end
-
- [r_end, z_end] = get_spec_radius(data, theta, phi, data.output.Mvol);
- [r_start, z_start] = get_spec_radius(data, theta, phi, 0);
- a = sqrt((r_end-r_start)^2 + (z_end-z_start)^2);
-
- r = linspace(0, a, nr);
- B = get_full_field(data, r, theta, phi, nr);
-
- switch component
- case 'psi'
- plot(r, B(1,:))
- ylab = ylabel('$B_\psi$ [T]');
- case 'theta'
- plot(r, B(2,:))
- ylab = ylabel('$B_\theta$ [T]');
- case 'phi'
- plot(r, B(3,:))
- ylab = ylabel('$B_\zeta$ [T]');
- case 'all'
- plot(r, B(1,:))
- hold on;
- plot(r, B(2,:))
- plot(r, B(3,:))
- ylab = ylabel('B [T]');
- leg = legend('$B_\psi$', '$B_\theta$','$B_\zeta$' );
- set(leg,'Interpreter','latex');
- end
-
- xlab = xlabel('Distance to magnetic axis [m]');
-
- set(gca, 'FontSize', 14)
- set(xlab,'Interpreter','latex');
- set(ylab,'Interpreter','latex');
-
-end
diff --git a/Utilities/matlabtools/plot_spec_Bgrid.m b/Utilities/matlabtools/plot_spec_Bgrid.m
index 4f0a5f73..c8cd178c 100644
--- a/Utilities/matlabtools/plot_spec_Bgrid.m
+++ b/Utilities/matlabtools/plot_spec_Bgrid.m
@@ -19,109 +19,151 @@ function plot_spec_Bgrid(data,nz0,plotstyle,newfig)
%
% OUTDATED - NEED DEBUG
-if(newfig==1)
-figure
+% Check inputs
+if ~strcmp(string(plotstyle),string('pcolor')) && ~strcmp(string(plotstyle),string('scatter'))
+ error('InputError: Invalid plotstyle')
+end
+if nz0<1
+ error('nzo should be greater than zero')
+end
+switch newfig
+ case 0
+ hold on
+ case 1
+ figure('Color','w','Position',[200 200 1500, 600])
+ hold on
+ case 2
+ hold off
+ otherwise
+ error('Invalide newfig')
end
-nvol = data.output.Mvol;
+Mvol = data.output.Mvol;
Lrad = data.input.physics.Lrad;
Nt = data.grid.Nt;
-Nz = data.grid.Nz;
Nfp = data.input.physics.Nfp;
-Rij = data.grid.Rij;
-Zij = data.grid.Zij;
-BR = data.grid.BR;
-Bp = data.grid.Bp;
-BZ = data.grid.BZ;
iz = nz0-1;
phi0 = double((2*pi/Nfp)*(iz/Nt));
-rzdata = get_spec_rzarr(data,nvol,1,linspace(0,2*pi,32),phi0);
-rmax = max(rzdata{1});
-rmin = min(rzdata{1});
-zmax = max(rzdata{2});
-zmin = min(rzdata{2});
+R = get_spec_R_derivatives(data, Mvol, 1, linspace(0,2*pi,64), phi0, 'R');
+Z = get_spec_R_derivatives(data, Mvol, 1, linspace(0,2*pi,64), phi0, 'Z');
+
+rmax = max(R{1});
+rmin = min(R{1});
+zmax = max(Z{1});
+zmin = min(Z{1});
if(strcmp(plotstyle,'pcolor')==1)
-for i=1:nvol
- ngrid = Lrad(i)+1;
-
- if(i==1)
- nstart = 2;
- else
- nstart = 1;
- end
-
- np1 = Nt;
- np2 = 1+ngrid-nstart;
-
- Rc = reshape(Rij(i,1+Nt*iz:(iz+1)*Nt,nstart:ngrid),np1,np2);
- Zc = reshape(Zij(i,1+Nt*iz:(iz+1)*Nt,nstart:ngrid),np1,np2);
- br = reshape(BR(i,1+Nt*iz:(iz+1)*Nt,nstart:ngrid),np1,np2);
- bp = reshape(Bp(i,1+Nt*iz:(iz+1)*Nt,nstart:ngrid).*Rij(i,1+Nt*iz:(iz+1)*Nt,nstart:ngrid),np1,np2);
- bz = reshape(BZ(i,1+Nt*iz:(iz+1)*Nt,nstart:ngrid),np1,np2);
-
- subplot(3,1,1)
- pcolor(Rc,Zc,br)
- axis equal; colorbar; hold on
- xlim([0.95*rmin 1.05*rmax])
- ylim([1.05*zmin 1.05*zmax])
- title('B_R')
- subplot(3,1,2)
- pcolor(Rc,Zc,bp)
- axis equal; colorbar; hold on
- xlim([0.95*rmin 1.05*rmax])
- ylim([1.05*zmin 1.05*zmax])
- title('B_{\phi}')
- subplot(3,1,3)
- pcolor(Rc,Zc,bz)
- axis equal; colorbar; hold on
- xlim([0.95*rmin 1.05*rmax])
- ylim([1.05*zmin 1.05*zmax])
- title('B_Z')
-end
+ for i=1:Mvol
+ ngrid = Lrad(i)+1;
+
+ % Read data corresponding to correct volume
+ Rij = data.grid.Rij{i};
+ Zij = data.grid.Zij{i};
+ BR = data.grid.BR{i};
+ Bp = data.grid.Bp{i};
+ BZ = data.grid.BZ{i};
+
+ % Reshape as an array
+ if(i==1)
+ nstart = 2;
+ else
+ nstart = 1;
+ end
+
+ np1 = Nt;
+ np2 = 1+ngrid-nstart;
+
+ Rc = reshape(Rij(1+Nt*iz:(iz+1)*Nt,nstart:ngrid),np1,np2);
+ Zc = reshape(Zij(1+Nt*iz:(iz+1)*Nt,nstart:ngrid),np1,np2);
+ br = reshape(BR( 1+Nt*iz:(iz+1)*Nt,nstart:ngrid),np1,np2);
+ bp = reshape(Bp( 1+Nt*iz:(iz+1)*Nt,nstart:ngrid) ...
+ .*Rij(1+Nt*iz:(iz+1)*Nt,nstart:ngrid),np1,np2);
+ bz = reshape(BZ( 1+Nt*iz:(iz+1)*Nt,nstart:ngrid),np1,np2);
+
+ % Double first entry to fill entire plane
+ Rc(end+1,:) = Rc(1,:);
+ Zc(end+1,:) = Zc(1,:);
+ br(end+1,:) = br(1,:);
+ bp(end+1,:) = bp(1,:);
+ bz(end+1,:) = bz(1,:);
+
+ % Plots
+ subplot(1,3,1)
+ pcolor(Rc,Zc,br)
+ shading interp
+ axis equal; colorbar; hold on
+ xlim([0.95*rmin 1.05*rmax])
+ ylim([1.05*zmin 1.05*zmax])
+ title('B_R')
+
+ subplot(1,3,2)
+ pcolor(Rc,Zc,bp)
+ shading interp
+ axis equal; colorbar; hold on
+ xlim([0.95*rmin 1.05*rmax])
+ ylim([1.05*zmin 1.05*zmax])
+ title('B_{\phi}')
+
+ subplot(1,3,3)
+ pcolor(Rc,Zc,bz)
+ shading interp
+ axis equal; colorbar; hold on
+ xlim([0.95*rmin 1.05*rmax])
+ ylim([1.05*zmin 1.05*zmax])
+ title('B_Z')
+ end
elseif(strcmp(plotstyle,'scatter')==1)
-cthick = 12 ;
-
-for i=1:nvol
- ngrid = Lrad(i)+1;
- if(i==1)
- nstart = 2;
- else
- nstart = 1;
- end
- for l=nstart:ngrid
- Rc = Rij(i,1+Nt*iz:(iz+1)*Nt,l);
- Zc = Zij(i,1+Nt*iz:(iz+1)*Nt,l);
- colR = BR(i,1+Nt*iz:(iz+1)*Nt,l);
- colp = Bp(i,1+Nt*iz:(iz+1)*Nt,l).*Rc;
- colZ = BZ(i,1+Nt*iz:(iz+1)*Nt,l);
-
- subplot(3,1,1)
- scatter(Rc,Zc,cthick,colR)
- axis equal; colorbar; hold on
- xlim([0.95*rmin 1.05*rmax])
- ylim([1.05*zmin 1.05*zmax])
- title('B_R')
- subplot(3,1,2)
- scatter(Rc,Zc,cthick,colp)
- axis equal; colorbar; hold on
- xlim([0.95*rmin 1.05*rmax])
- ylim([1.05*zmin 1.05*zmax])
- title('B_{\phi}')
- subplot(3,1,3)
- scatter(Rc,Zc,cthick,colZ)
- axis equal; colorbar; hold on
- xlim([0.95*rmin 1.05*rmax])
- ylim([1.05*zmin 1.05*zmax])
- title('B_Z')
- end
-end
+ cthick = 12 ;
+
+ for i=1:Mvol
+ % Read data corresponding to correct volume
+ Rij = data.grid.Rij{i};
+ Zij = data.grid.Zij{i};
+ BR = data.grid.BR{i};
+ Bp = data.grid.Bp{i};
+ BZ = data.grid.BZ{i};
+
+ ngrid = Lrad(i)+1;
+ if(i==1)
+ nstart = 2;
+ else
+ nstart = 1;
+ end
+ for l=nstart:ngrid
+ Rc = Rij(1+Nt*iz:(iz+1)*Nt,l);
+ Zc = Zij(1+Nt*iz:(iz+1)*Nt,l);
+ colR = BR(1+Nt*iz:(iz+1)*Nt,l);
+ colp = Bp(1+Nt*iz:(iz+1)*Nt,l).*Rc;
+ colZ = BZ(1+Nt*iz:(iz+1)*Nt,l);
+
+ subplot(1,3,1)
+ scatter(Rc,Zc,cthick,colR)
+ axis equal; colorbar; hold on
+ xlim([0.95*rmin 1.05*rmax])
+ ylim([1.05*zmin 1.05*zmax])
+ title('B_R')
+
+ subplot(1,3,2)
+ scatter(Rc,Zc,cthick,colp)
+ axis equal; colorbar; hold on
+ xlim([0.95*rmin 1.05*rmax])
+ ylim([1.05*zmin 1.05*zmax])
+ title('B_{\phi}')
+
+ subplot(1,3,3)
+ scatter(Rc,Zc,cthick,colZ)
+ axis equal; colorbar; hold on
+ xlim([0.95*rmin 1.05*rmax])
+ ylim([1.05*zmin 1.05*zmax])
+ title('B_Z')
+ end
+ end
end
diff --git a/Utilities/matlabtools/plot_spec_Ivolume.m b/Utilities/matlabtools/plot_spec_Ivolume.m
index f0a07f9a..e051d39b 100644
--- a/Utilities/matlabtools/plot_spec_Ivolume.m
+++ b/Utilities/matlabtools/plot_spec_Ivolume.m
@@ -16,30 +16,29 @@ function plot_spec_Ivolume(data, cumul, newfig)
% Written by A. Baillod (2019)
%
+ if ~any(cumul==[0,1])
+ error('InputError: invalid cumul')
+ end
-[psi_coord, I_vol] = get_spec_volume_current(data, cumul);
+ switch newfig
+ case 0
+ hold on
+ case 1
+ figure
+ hold on
+ case 2
+ hold off
+ end
-% some plots
+ [~, I_vol] = get_spec_volume_current(data, cumul);
-switch newfig
- case 0
- hold on
- case 1
- figure
- hold on
- case 2
- hold off
-end
-%plot(psi_coord, I_vol, '*', 'DisplayName', '$I^{vol}_\phi$')
-bar(I_vol);
-%leg = legend('Location','northwest');
-ylab = ylabel('$I_\mathcal{V}$[A]');
-%xlab = xlabel('$\psi_t / \psi_{edge}$');
-xlab = xlabel('Volume label');
-set(gca, 'FontSize', 14)
-%set(leg,'Interpreter','latex');
-set(xlab,'Interpreter','latex');
-set(ylab,'Interpreter','latex');
-grid on;
+ bar(I_vol);
+ xlab = xlabel('Volume label');
+ ylab = ylabel('$\mu_0I_\mathcal{V}$[A]');
+ set(gca, 'FontSize', 14)
+ set(xlab,'Interpreter','latex');
+ set(ylab,'Interpreter','latex');
+ grid on;
+end
diff --git a/Utilities/matlabtools/plot_spec_boundary.m b/Utilities/matlabtools/plot_spec_boundary.m
new file mode 100644
index 00000000..b3cd6937
--- /dev/null
+++ b/Utilities/matlabtools/plot_spec_boundary.m
@@ -0,0 +1,97 @@
+%% plot_spec_boundary( DATA, NPOINTS, NEWFIG )
+% =======================================================
+%
+% Traces the plasma boundary in the (R,Z) plane
+% with the specified number of points
+%
+% INPUT
+% -----
+% -data : must be produced by calling read_spec(filename)
+% -Npoints : number of points for theta
+% -phi0 : toroidal angle at which the boundary is plotted
+% -Newfig : opens (=1) or not (=0) a new figure, or overwrites (=2)
+% last plot
+%
+% ------------------------------------%
+% Written by S.Guinchard (05/17/22) %
+% ------------------------------------%
+
+function plot_spec_boundary(d, Npoints, phi0, Newfig)
+
+ Rbc = d.output.Rbc(:,2);
+ Zbs = d.output.Zbs(:,2);
+
+ N = 10000;
+ theta = linspace(0,2*pi, N);
+ phi = linspace(0,2*pi, N);
+
+ m = double(d.output.im);
+ n = double(d.output.in/d.input.physics.Nfp);
+ R = zeros(size(theta));
+ Z = zeros(size(phi));
+
+ R_ = zeros(1,Npoints);
+ Z_ = R_;
+
+ for i=1:length(m)
+ for j =1:length(theta)
+ R(j) = R(j) + Rbc(i)*cos(m(i)*theta(j) - n(i)*phi0);
+ Z(j) = Z(j) + Zbs(i)*sin(m(i)*theta(j) - n(i)*phi0);
+ end
+ end
+
+
+ for ii = 1:Npoints
+ R_(ii) = R((ii-1)*floor(N/Npoints)+1);
+ Z_(ii) = Z((ii-1)*floor(N/Npoints)+1);
+ end
+
+ p = polyshape(R,Z);
+
+ switch Newfig
+ case 0
+ hold on
+ pg=plot(p);
+ pg.FaceColor = ([1 1 1]);
+ pg.EdgeColor = ([1 0 0]);
+ pg.LineWidth = 3;
+ hold on
+ scatter(R_,Z_, 'filled', 'ko')
+ xlabel('R')
+ ylabel('Z')
+ legend(strcat('$\phi_0$ = ', num2str(phi0)), 'Location','best','Interpreter','latex');
+ set(legend,'FontSize',18);
+ set (gca, 'fontsize', 20)
+
+ case 1
+ figure
+ pg=plot(p);
+ pg.FaceColor = ([1 1 1]);
+ pg.EdgeColor = ([1 0 0]);
+ pg.LineWidth = 3;
+ hold on
+ scatter(R_,Z_, 'filled', 'ko')
+ xlabel('R', 'Interpreter', 'Latex')
+ ylabel('Z', 'Interpreter', 'Latex')
+ legend(strcat('$\phi_0$ = ', num2str(phi0)), 'Location','best','Interpreter','latex');
+ set(legend,'FontSize',18);
+ set (gca, 'fontsize', 20)
+
+ case 2
+ hold off
+ pg=plot(p);
+ pg.FaceColor = ([1 1 1]);
+ pg.EdgeColor = ([1 0 0]);
+ pg.LineWidth = 3;
+ hold on
+ scatter(R_,Z_, 'filled', 'ko')
+ xlabel('R')
+ ylabel('Z')
+ legend(strcat('$\phi_0$ = ', num2str(phi0)), 'Location','best','Interpreter','latex');
+ set(legend,'FontSize',18);
+ set (gca, 'fontsize', 20)
+
+ end
+
+
+end
diff --git a/Utilities/matlabtools/plot_spec_current_profile.m b/Utilities/matlabtools/plot_spec_current_profile.m
new file mode 100644
index 00000000..088f6478
--- /dev/null
+++ b/Utilities/matlabtools/plot_spec_current_profile.m
@@ -0,0 +1,133 @@
+function plot_spec_current_profile( data, iflag, newfig, varargin )
+%
+% PLOT_SPEC_CURRENT_PROFILE( DATA, NEWFIG )
+% =========================================
+%
+% Plot the total enclosed toroidal current as a function of the minor
+% radius for a given SPEC equilibrium.
+%
+% INPUTS
+% ------
+% * data: SPEC output data obtained with read_spec(filename)
+% * iflag: (0) plots Ivolume
+% (1) plots Isurf
+% (2) plots both
+% * newfig: (0) plot on current figure
+% (1) open a new figure
+% (2) Erase current figure and use it
+% * Optional input: any combination of
+% -'LineWidth', value (default 2)
+% -'Color', value (default 'r')
+% -'Marker', value (default 'none')
+% -'MarkerSize', value (default 8)
+% -'LineStyle', value (default '-')
+%
+% Written by A. Baillod (2020)
+%
+
+ % Check inputs
+ if ~any(iflag==[0,1,2])
+ error('InputError: Invalid iflag')
+ end
+
+ switch newfig
+ case 0
+ hold on
+ case 1
+ figure('Position', [200 200 900 700],'Color','w')
+ hold on
+ case 2
+ hold off
+ otherwise
+ error('InputError: invalid newfig')
+ end
+
+
+ l = length(varargin);
+ if mod(l,2)~=0
+ error('Invalid number of argument')
+ end
+
+ opt.LineWidth = 2;
+ opt.Color = 'r';
+ opt.Marker = 'none';
+ opt.MarkerSize = 8;
+ opt.LineStyle = '-';
+ for ii=1:l/2
+ field = varargin{2*ii-1};
+ value = varargin{2*ii };
+
+ opt.(field) = value;
+ end
+
+
+ nsucctrj = length(data.poincare.R(:,1,1)); % number of successfully followed trajectories
+ sval = data.transform.fiota(1:nsucctrj,1);
+ nvol = data.input.physics.Nvol;
+ mvol = data.output.Mvol;
+ nptrj = zeros(1,mvol);
+ count = 1;
+
+ ind = find(sval==-2); %Remove wrongly written data
+ sval(ind) = [];
+
+ for is=1:length(sval)-1
+ if(sval(is)>0 && sval(is+1)<0) %Reached the end of a volume
+ if(count==1)
+ nptrj(count) = is;
+ else
+ nptrj(count) = is-sum(nptrj);
+ end
+ count = count+1;
+ end
+ end
+ nptrj(mvol) = length(sval)-sum(nptrj);
+
+
+ ns = 32;
+ nt = 32;
+ cumflux = 0;
+ cumcur = 0;
+ kstart = 1;
+ psitor = zeros(1,length(sval));
+
+ Iphi = zeros(1, length(sval) );
+ mu = data.output.mu;
+
+ for lvol=1:mvol
+ start = -1;
+ if lvol==1
+ start=-0.999;
+ end
+
+ for k=kstart:kstart-1+nptrj(lvol)
+ tflux = get_spec_torflux(data,lvol,0,start,sval(k),ns,nt);
+ psitor(k) = cumflux + tflux;
+
+ if iflag==0 || iflag==2
+ Iphi(k) = cumcur + mu(lvol) * tflux;
+ else
+ Iphi(k) = cumcur;
+ end
+ end
+ cumflux = psitor(k);
+ kstart = kstart+nptrj(lvol);
+ %cumcur = Iphi(k);
+
+ if iflag==1 || iflag==2
+ cumcur = Iphi(k) + data.output.IPDt(lvol); % add surface current
+ else
+ cumcur = Iphi(k);
+ end
+ end
+
+ phiedge=psitor(end);
+
+
+ plot( sqrt(psitor / phiedge), Iphi, 'LineWidth', opt.LineWidth, 'Color', opt.Color, 'Marker', opt.Marker, 'LineStyle', opt.LineStyle )
+ xlabel('$(\Psi_t / \Psi_{edge})^{1/2}$', 'Interpreter', 'latex')
+ ylabel('$\mu_0I_\phi$[Tm]', 'Interpreter', 'latex')
+ set(gca, 'FontSize', 18)
+ hold on;
+
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/plot_spec_fieldlines.m b/Utilities/matlabtools/plot_spec_fieldlines.m
new file mode 100644
index 00000000..3816d1c9
--- /dev/null
+++ b/Utilities/matlabtools/plot_spec_fieldlines.m
@@ -0,0 +1,86 @@
+%% plot_spec_fieldlines( DATA, NPOINTS, NPERIODS, NEWFIG )
+% =======================================================
+%
+% Traces magnetic field lines in the (phi, theta) plane
+% and gives an output containing the coordinates
+% (used e.g with the code get_spec_straightfieldlines)
+%
+% INPUT
+% -----
+% -data : must be produced by calling read_spec(filename)
+% -Npoints : number of points along the field line
+% -Nperiods : number of toroidal periods over which the field line is
+% traced
+% -Newfig : opens (=1) or not (=0) a new figure, or overwrites (=2)
+% last plot
+%
+% ------------------------------------%
+% Written by S.Guinchard (03/01/22) %
+% Last modified (05/15/22) %
+% ------------------------------------%
+
+function coord = plot_spec_fieldlines(d,Npoints,Nperiods,newfig)
+
+ phi = linspace(0,2*Nperiods*pi,Npoints);
+ dphi = phi(2)-phi(1);
+ s = 1;
+ Fs = 18;
+ theta_temp(1) = 0;
+
+ for i = 1:length(phi)-1
+ Bfield_temp = get_spec_magfield(d,1,s,theta_temp(i),phi(i));
+ theta_temp(i+1) = theta_temp(i)+dphi*(cell2mat(Bfield_temp(2))/cell2mat(Bfield_temp(3)));
+ end
+
+ coord.theta = wrapTo2Pi(theta_temp);
+ coord.phi = wrapTo2Pi(phi);
+ switch newfig
+
+ case 0
+ hold on
+ scatter(coord.phi, coord.theta, 'b.')
+ ax = gca;
+ ax.TickLabelInterpreter = 'latex';
+ xticks([0 pi/3 2*pi/3 pi 4*pi/3 5*pi/3 2*pi])
+ xticklabels({'$0$','$\frac{\pi}{3}$','$\frac{2\pi}{3}$','$\pi$', '$\frac{4\pi}{3}$','$\frac{5\pi}{3}$','$2\pi$'});
+ yticks([0 pi/3 2*pi/3 pi 4*pi/3 5*pi/3 2*pi])
+ yticklabels({'$0$','$\frac{\pi}{3}$','$\frac{2\pi}{3}$','$\pi$', '$\frac{4\pi}{3}$','$\frac{5\pi}{3}$','$2\pi$'});
+ xlim([0 2*pi])
+ ylim([0 2*pi])
+ set (gca, 'fontsize', Fs)
+ xlabel('$\phi$', 'FontSize', Fs+10 , 'Interpreter', 'latex')
+ ylabel('$\theta$', 'FontSize', Fs+10 , 'Interpreter', 'latex')
+
+ case 1
+ figure
+ scatter(coord.phi, coord.theta, 'b.')
+ ax = gca;
+ ax.TickLabelInterpreter = 'latex';
+ xticks([0 pi/3 2*pi/3 pi 4*pi/3 5*pi/3 2*pi])
+ xticklabels({'$0$','$\frac{\pi}{3}$','$\frac{2\pi}{3}$','$\pi$', '$\frac{4\pi}{3}$','$\frac{5\pi}{3}$','$2\pi$'});
+ yticks([0 pi/3 2*pi/3 pi 4*pi/3 5*pi/3 2*pi])
+ yticklabels({'$0$','$\frac{\pi}{3}$','$\frac{2\pi}{3}$','$\pi$', '$\frac{4\pi}{3}$','$\frac{5\pi}{3}$','$2\pi$'});
+ xlim([0 2*pi])
+ ylim([0 2*pi])
+ set (gca, 'fontsize', Fs)
+ xlabel('$\phi$', 'FontSize', Fs+10 , 'Interpreter', 'latex')
+ ylabel('$\theta$', 'FontSize', Fs+10 , 'Interpreter', 'latex')
+
+ case 2
+ hold off
+ scatter(coord.phi, coord.theta, 'b.')
+ ax = gca;
+ ax.TickLabelInterpreter = 'latex';
+ xticks([0 pi/3 2*pi/3 pi 4*pi/3 5*pi/3 2*pi])
+ xticklabels({'$0$','$\frac{\pi}{3}$','$\frac{2\pi}{3}$','$\pi$', '$\frac{4\pi}{3}$','$\frac{5\pi}{3}$','$2\pi$'});
+ yticks([0 pi/3 2*pi/3 pi 4*pi/3 5*pi/3 2*pi])
+ yticklabels({'$0$','$\frac{\pi}{3}$','$\frac{2\pi}{3}$','$\pi$', '$\frac{4\pi}{3}$','$\frac{5\pi}{3}$','$2\pi$'});
+ xlim([0 2*pi])
+ ylim([0 2*pi])
+ set (gca, 'fontsize', Fs)
+ xlabel('$\phi$', 'FontSize', Fs+10 , 'Interpreter', 'latex')
+ ylabel('$\theta$', 'FontSize', Fs+10 , 'Interpreter', 'latex')
+
+ end
+
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/plot_spec_fluxfun.m b/Utilities/matlabtools/plot_spec_fluxfun.m
new file mode 100644
index 00000000..221588a0
--- /dev/null
+++ b/Utilities/matlabtools/plot_spec_fluxfun.m
@@ -0,0 +1,70 @@
+function plot_spec_fluxfun(data,lvol,ns,nt,z0,ncont,newfig)
+
+%
+% PLOT_SPEC_OUTFLUXFUN( DATA, NS, NT, Z0, NCONT, NEWFIG )
+% =======================================================
+%
+% Plots iso-contours of Az on a given cross-section
+%
+% INPUT
+% -----
+% -data : must be produced by calling read_spec(filename)
+% -lvol : volume number
+% -ns : radial resolution for construction of Az
+% -nt : poloidal resolution for construction of Az
+% -z0 : toroidal angle at which Az is evaluated
+% -ncont : number of iso-contour lines
+% -newfig : flag for whether a new figure should be open (=1) or not(=0)
+%
+% Note: should only work for free-boundary equilibria
+% Note: poloidal flux function is psi=-A_phi if A_phi is the covariant component and psi=-R*A_phi if A_phi is the canonical component
+%
+% written by J.Loizu (2018)
+
+
+ % Check input
+ if lvol>data.output.Mvol || lvol<1
+ error('Invalid lvol')
+ end
+
+ if ns<1
+ error('Invalid ns')
+ end
+
+ if nt<1
+ error('Invalid nt')
+ end
+
+ if ncont<1
+ error('Invalid ncont')
+ end
+
+ switch newfig
+ case 0
+ hold on
+ case 1
+ figure
+ hold on
+ case 2
+ hold off
+ otherwise
+ error('Invalid newfig')
+ end
+
+ % Generate coordinate arrays
+ sarr = linspace(-1,1,ns);
+ tarr = linspace(0,2*pi,nt);
+
+ acov = get_spec_vecpot(data,lvol,sarr,tarr,z0);
+ R = get_spec_R_derivatives(data,lvol,sarr,tarr,z0,'R');
+ Z = get_spec_R_derivatives(data,lvol,sarr,tarr,z0,'Z');
+
+ ffun = -acov{2};
+
+ if(newfig==1)
+ figure; hold on;
+ end
+
+ contour(R{1},Z{1},ffun,ncont,'k')
+
+end
diff --git a/Utilities/matlabtools/plot_spec_grid.m b/Utilities/matlabtools/plot_spec_grid.m
index 88ecac72..a38611f1 100644
--- a/Utilities/matlabtools/plot_spec_grid.m
+++ b/Utilities/matlabtools/plot_spec_grid.m
@@ -11,7 +11,7 @@ function plot_spec_grid(data,nz0,newfig)
% -data : must be produced by calling read_spec(filename)
% -nz0 : toroidal plane number at which coordinates are shown (nz0=1 at toroidal angle phi=0)
% -newfig : opens(=1) or not(=0) a new figure, or overwrite selected
-% figure (=2)
+% figure (=2)
%
% written by J.Loizu (2015)
%
@@ -24,23 +24,24 @@ function plot_spec_grid(data,nz0,newfig)
hold on
case 2
hold off
+ otherwise
+ error('InputError: invalid newfig')
end
-nvol = data.input.physics.Nvol+data.input.physics.Lfreebound;
+Mvol = data.output.Mvol;
Lrad = data.input.physics.Lrad;
Nt = data.grid.Nt;
-Nz = data.grid.Nz;
Rij = data.grid.Rij;
Zij = data.grid.Zij;
ccol = 'm';
-cthick = 12;
+cthick = 6;
iz = nz0-1;
-for i=1:nvol
+for i=1:Mvol
for l=1:Lrad(i)+1
R_tmp = Rij{i};
diff --git a/Utilities/matlabtools/plot_spec_hessian.m b/Utilities/matlabtools/plot_spec_hessian.m
deleted file mode 100644
index 49b58995..00000000
--- a/Utilities/matlabtools/plot_spec_hessian.m
+++ /dev/null
@@ -1,21 +0,0 @@
-function plot_spec_hessian(data)
-
-%
-% PLOT_SPEC_HESSIAN( DATA )
-% =========================
-%
-% Plots the hessian matrix elements
-%
-% INPUT
-% -----
-% -data : must be produced by calling read_spec_hessian(filename)
-%
-% written by J.Loizu (2017)
-
-figure
-
-imagesc(data)
-
-colorbar
-
-%set(gca, 'CLim', [-0.1 0.1]);
diff --git a/Utilities/matlabtools/plot_spec_iota.m b/Utilities/matlabtools/plot_spec_iota.m
index 2a65626b..b8db004e 100644
--- a/Utilities/matlabtools/plot_spec_iota.m
+++ b/Utilities/matlabtools/plot_spec_iota.m
@@ -1,4 +1,4 @@
-function out = plot_spec_iota(data,iorq,xaxis,newfig)
+function out = plot_spec_iota(data,iorq,xaxis,newfig,varargin)
%
% PLOT_SPEC_IOTA( DATA, IORQ, XAXIS, NEWFIG )
@@ -8,13 +8,20 @@
%
% INPUT
% -----
-% -data : produced by calling read_spec(fname)
-% -iorq : plot iota('i') or safety factor ('q')
-% -xaxis='s' : plots s-coordinnate as the x-axis
-% -xaxis='R' : plots R-coordinnate as the x-axis
-% -xaxis='f' : plots toroidal flux as the x-axis
-% -xaxis='r' : plots sqrt(toroidal flux) as the x-axis
-% -newfig : opens(=1) or not(=0) a new figure, or overwrites(=2) current plot
+% -data : produced by calling read_spec(fname)
+% -iorq : plot iota('i') or safety factor ('q')
+% -xaxis : 's' plots s-coordinnate as the x-axis
+% 'R' plots R-coordinnate as the x-axis
+% 'f' plots toroidal flux as the x-axis
+% 'r' plots sqrt(toroidal flux) as the x-axis
+% -newfig: opens (=1) or not (=0) a new figure, or overwrites (=2)
+% current plot
+% -varargin: Optional arguments. Can be any of the following pairs,
+% 'LineWidth', linewidth
+% 'Color', color
+% 'Marker', marker
+% 'MarkerSize', makersize
+% 'LineStyle', linestyle
%
% OUTPUT
% ------
@@ -26,139 +33,196 @@
% modified by A.Baillod (01.2019)
% modified by J.Loizu (01.2020)
-if(newfig==1)
- figure
- hold on;
-elseif newfig==0
- hold on;
-elseif newfig==2 % A.Baillod (06.2019)
- hold off;
-end
+ % Check inputs
+ if ~any(iorq==['iq'])
+ error('InputError: invalid iorq')
+ end
+
+ if ~any(xaxis==['sRfr'])
+ error('InputError: invalid xaxis')
+ end
-if(iorq=='i')
-F = data.transform.fiota(1:end,2);
-Flabel='\iota';
-elseif(iorq=='q')
-F = 1./data.transform.fiota(1:end,2);
-Flabel='q';
-end
+ l = length(varargin);
+ if mod(l,2)~=0
+ error('InputError: invalid number of argument')
+ end
+
+ switch newfig
+ case 1
+ figure('Position', [200 200 900 700], 'Color', 'w')
+ hold on;
+ case 0
+ hold on;
+ case 2
+ hold off;
+ otherwise
+ error('InputError: invalid newfig')
+ end
+
+ % Read optional inputs
+ opt.LineWidth = 2;
+ opt.Color = 'r';
+ opt.Marker = '*';
+ opt.MarkerSize = 8;
+ opt.LineStyle = 'none';
+ for ii=1:l/2
+ field = varargin{2*ii-1};
+ value = varargin{2*ii };
-nsucctrj = length(data.poincare.R(:,1,1)); % number of successfully followed trajectories
-
-switch xaxis
- case 's'
- plot(data.transform.fiota(1:nsucctrj,1),F(1:nsucctrj),'*','MarkerSize',8,'LineWidth',2)
- ylabel(Flabel)
- out = cell(2);
- out{1} = data.transform.fiota(:,1);
- out{2} = F;
-
- case 'R'
- plot(transpose(data.poincare.R(:,1,1)),F(1:nsucctrj),'*','MarkerSize',8,'LineWidth',2)
- ylabel(Flabel)
- out = cell(2);
- out{1} = data.poincare.R(:,1,1);
- out{2} = F(1:nsucctrj);
-
- case 'f'
- sval = data.transform.fiota(1:nsucctrj,1);
- nvol = data.output.Mvol;
- nptrj = zeros(1,nvol);
- count = 1;
-
- ind = find(sval==-2); %Remove wrongly written data
- sval(ind) = [];
- F(ind) = [];
- nsucctrj = nsucctrj - length(ind);
-
- for is=1:length(sval)-1
- if(sval(is)>0 && sval(is+1)<0) %Reached the end of a volume
- if(count==1)
- nptrj(count) = is;
- else
- nptrj(count) = is-sum(nptrj);
+ opt.(field) = value;
end
- count = count+1;
- end
- end
- nptrj(nvol) = length(sval)-sum(nptrj);
-
- ns = 32;
- nt = 32;
- cumflux = 0;
- kstart = 1;
- psitor = zeros(1,length(sval));
-
-
- for lvol=1:nvol
-
- if lvol==nvol % Required if last value had a -2 (often in free bound)
- phiedge = cumflux + get_spec_torflux(data, nvol, 0, -1, 1, ns, nt);
+
+
+
+ if(iorq=='i')
+ F = data.transform.fiota(1:end,2);
+ Flabel='\iota';
+ elseif(iorq=='q')
+ F = 1./data.transform.fiota(1:end,2);
+ Flabel='q';
+ end
+
+ nsucctrj = length(data.poincare.R(:,1,1)); % number of successfully followed trajectories
+
+ switch xaxis
+ case 's'
+ plot(data.transform.fiota(1:nsucctrj,1),F(1:nsucctrj),'Marker',opt.Marker,...
+ 'MarkerSize',opt.MarkerSize,'LineWidth',opt.LineWidth,'MarkerEdgeColor',...
+ opt.Color,'LineStyle',opt.LineStyle,'Color',opt.Color)
+ ylabel(Flabel)
+ out = cell(2);
+ out{1} = data.transform.fiota(:,1);
+ out{2} = F;
+
+ case 'R'
+ plot(transpose(data.poincare.R(:,1,1)),F(1:nsucctrj),'Marker',opt.Marker,...
+ 'MarkerSize',opt.MarkerSize,'LineWidth',opt.LineWidth,'MarkerEdgeColor',...
+ opt.Color,'LineStyle',opt.LineStyle,'Color',opt.Color)
+ ylabel(Flabel)
+ out = cell(2);
+ out{1} = data.poincare.R(:,1,1);
+ out{2} = F(1:nsucctrj);
+
+ case 'f'
+ sval = data.transform.fiota(1:nsucctrj,1);
+ nvol = data.input.physics.Nvol;
+ mvol = data.output.Mvol;
+ nptrj = zeros(1,mvol);
+ count = 1;
+
+ ind = find(sval==-2); %Remove wrongly written data
+ sval(ind) = [];
+ F(ind) = [];
+ nsucctrj = nsucctrj - length(ind);
+
+ for is=1:length(sval)-1
+ if(sval(is)>0 && sval(is+1)<0) %Reached the end of a volume
+ if(count==1)
+ nptrj(count) = is;
+ else
+ nptrj(count) = is-sum(nptrj);
+ end
+ count = count+1;
+ end
end
-
- for k=kstart:kstart-1+nptrj(lvol)
- psitor(k) = cumflux + get_spec_torflux(data,lvol,0,-1,sval(k),ns,nt);
+ nptrj(mvol) = length(sval)-sum(nptrj);
+
+ ns = 32;
+ nt = 32;
+ cumflux = 0;
+ kstart = 1;
+ psitor = zeros(1,length(sval));
+
+ for lvol=1:mvol
+
+ start = -1;
+ if lvol==1
+ start = -0.999;
+ end
+
+ if lvol==nvol % Required if last value had a -2 (often in free bound)
+ phiedge = cumflux + get_spec_torflux(data, nvol, 0, start, 1 , ns, nt);
+ end
+
+ for k=kstart:kstart-1+nptrj(lvol)
+ psitor(k) = cumflux + get_spec_torflux(data,lvol,0, start, sval(k),ns,nt);
+ end
+ cumflux = psitor(k);
+ kstart = kstart+nptrj(lvol);
end
- cumflux = psitor(k);
- kstart = kstart+nptrj(lvol);
- end
-
- plot(psitor/phiedge,F(1:nsucctrj),'*','MarkerSize',8,'LineWidth',2)
- ylabel(Flabel)
- xlabel('\Psi / \Psi_{edge}')
-
- out = cell(2);
- out{1} = psitor/psitor(end);
- out{2} = F(1:nsucctrj);
-
-case 'r'
- sval = data.transform.fiota(1:nsucctrj,1);
- nvol = data.output.Mvol;
- nptrj = zeros(1,nvol);
- count = 1;
-
- ind = find(sval==-2); %Remove wrongly written data
- sval(ind) = [];
- F(ind) = [];
- nsucctrj = nsucctrj - length(ind);
-
- for is=1:length(sval)-1
- if(sval(is)>0 && sval(is+1)<0)
- if(count==1)
- nptrj(count) = is;
- else
- nptrj(count) = is-sum(nptrj);
- end
- count = count+1;
- end
- end
- nptrj(nvol) = length(sval)-sum(nptrj);
-
- ns = 32;
- nt = 32;
- cumflux = 0;
- kstart = 1;
- psitor = zeros(1,length(sval));
-
- for lvol=1:nvol
-
- if lvol==nvol % Required if last value had a -2 (often in free bound)
- phiedge = cumflux + get_spec_torflux(data, nvol, 0, -1, 1, ns, nt);
+
+ plot(psitor/phiedge,F(1:nsucctrj),'Marker',opt.Marker,'MarkerSize',opt.MarkerSize,...
+ 'LineWidth',opt.LineWidth,'MarkerEdgeColor',opt.Color,...
+ 'LineStyle',opt.LineStyle,'Color',opt.Color)
+ ylabel(Flabel)
+ xlabel('\Psi / \Psi_{edge}')
+
+ out = cell(2);
+ out{1} = psitor/psitor(end);
+ out{2} = F(1:nsucctrj);
+
+ case 'r'
+ sval = data.transform.fiota(1:nsucctrj,1);
+ nvol = data.input.physics.Nvol;
+ mvol = data.output.Mvol;
+ nptrj = zeros(1,nvol);
+ count = 1;
+
+ ind = find(sval==-2); %Remove wrongly written data
+ sval(ind) = [];
+ F(ind) = [];
+ nsucctrj = nsucctrj - length(ind);
+
+ for is=1:length(sval)-1
+ if(sval(is)>0 && sval(is+1)<0)
+ if(count==1)
+ nptrj(count) = is;
+ else
+ nptrj(count) = is-sum(nptrj);
+ end
+ count = count+1;
+ end
end
-
- for k=kstart:kstart-1+nptrj(lvol)
- psitor(k) = cumflux + get_spec_torflux(data,lvol,0,-1,sval(k),ns,nt);
+ nptrj(mvol) = length(sval)-sum(nptrj);
+
+ ns = 32;
+ nt = 32;
+ cumflux = 0;
+ kstart = 1;
+ psitor = zeros(1,length(sval));
+
+ for lvol=1:mvol
+
+ start = -1;
+ if lvol==1
+ start = -0.999;
+ end
+
+ if lvol==nvol % Required if last value had a -2 (often in free bound)
+ phiedge = cumflux + get_spec_torflux(data, nvol, 0, start, 1 , ns, nt);
+ end
+
+ for k=kstart:kstart-1+nptrj(lvol)
+ psitor(k) = cumflux + get_spec_torflux(data,lvol,0, start, sval(k),ns,nt);
+ end
+ cumflux = psitor(k);
+ kstart = kstart+nptrj(lvol);
end
- cumflux = psitor(k);
- kstart = kstart+nptrj(lvol);
- end
+
+ % phiedge = data.input.physics.phiedge;
+
+ plot(sqrt(psitor/phiedge),F(1:nsucctrj),'Marker',opt.Marker,'MarkerSize',...
+ opt.MarkerSize,'LineWidth',opt.LineWidth,'MarkerEdgeColor',...
+ opt.Color,'LineStyle',opt.LineStyle,'Color',opt.Color)
+ ylabel(Flabel)
+ xlabel('(\Psi / \Psi_{edge})^{1/2}')
+
+ out = cell(2);
+ out{1} = sqrt(psitor/psitor(end));
+ out{2} = F(1:nsucctrj);
+
+ end
+
+ set(gca,'FontSize',18)
- plot(sqrt(psitor/phiedge),F(1:nsucctrj),'*','MarkerSize',8,'LineWidth',2)
- ylabel(Flabel)
- xlabel('(\Psi / \Psi_{edge})^{1/2}')
-
- out = cell(2);
- out{1} = psitor/psitor(end);
- out{2} = F(1:nsucctrj);
-
end
diff --git a/Utilities/matlabtools/plot_spec_iotakam.m b/Utilities/matlabtools/plot_spec_iotakam.m
index 52b78707..f4f7d168 100644
--- a/Utilities/matlabtools/plot_spec_iotakam.m
+++ b/Utilities/matlabtools/plot_spec_iotakam.m
@@ -8,70 +8,79 @@ function plot_spec_iotakam(data,iorq,xaxis,newfig)
%
% INPUT
% -----
-% -data : produced by calling read_spec(fname)
-% -iorq : plot iota('i') or safety factor ('q')
-% -xaxis='R' : plots R-position of interfaces (at phi=0) as the x-axis
-% -xaxis='f' : plots toroidal flux as the x-axis
-% -xaxis='r' : plots sqrt(toroidal flux) as the x-axis
-% -newfig : opens(=1) or not(=0) a new figure
+% -data : produced by calling read_spec(fname)
+% -iorq : plot iota('i') or safety factor ('q')
+% -xaxis : 'R' plots R-position of interfaces (at phi=0) as the x-axis
+% 'f' plots toroidal flux as the x-axis
+% 'r' plots sqrt(toroidal flux) as the x-axis
+% -newfig: opens(=1) or not(=0) a new figure
%
% written by J.Loizu (2017)
+ % Check input
+ if ~any(iorq==['i','q'])
+ error('InputError: invalid iorq')
+ end
+ if ~any(xaxis==['R','f','r'])
+ error('InputError: invalid xaxis')
+ end
-Nvol = data.input.physics.Nvol;
-tflux = data.input.physics.tflux;
-iota = data.input.physics.iota;
-oita = data.input.physics.oita;
-Rmn = data.output.Rbc;
-im = data.output.im;
-in = data.output.in;
-mn = data.output.mn;
-freeb = data.input.physics.Lfreebound;
+ switch newfig
+ case 0
+ hold on
+ case 1
+ figure('Color','w')
+ hold on
+ case 2
+ hold off
+ otherwise
+ error('InputError: invalid newfig')
+ end
-R0 = zeros(1,Nvol);
+ Nvol = data.input.physics.Nvol;
+ tflux = data.input.physics.tflux;
+ iota = data.input.physics.iota;
+ oita = data.input.physics.oita;
+ Rmn = data.output.Rbc;
+ freeb = data.input.physics.Lfreebound;
-for l=1:Nvol
- R0(l) = sum(Rmn(:,l+1));
-end
+ R0 = zeros(1,Nvol);
-switch newfig
-case 0
- hold on
-case 1
- figure
-case 2
- hold off
-end
+ for l=1:Nvol
+ R0(l) = sum(Rmn(:,l+1));
+ end
-if(iorq=='i')
-F = iota(2:end);
-G = oita(2:end);
-Flabel='\iota';
-elseif(iorq=='q')
-F = 1./iota(2:end);
-G = 1./oita(2:end);
-Flabel='q';
-end
+ if(iorq=='i')
+ F = iota(2:end);
+ G = oita(2:end);
+ Flabel='\iota';
+ elseif(iorq=='q')
+ F = 1./iota(2:end);
+ G = 1./oita(2:end);
+ Flabel='q';
+ end
-switch xaxis
- case 'R'
- plot(R0,F,'r+','MarkerSize',6,'LineWidth',2)
- hold on;
- plot(R0,G,'m+','MarkerSize',6,'LineWidth',2)
- xlabel('R')
- ylabel(Flabel)
- case 'f'
- plot(tflux(1:end-freeb),F,'r+','MarkerSize',6,'LineWidth',2)
- hold on;
- plot(tflux(1:end-freeb),G,'m+','MarkerSize',6,'LineWidth',2)
- xlabel('\Psi / \Psi_{edge}')
- ylabel(Flabel)
- case 'r'
- plot(sqrt(tflux(1:end-freeb)),F,'r+','MarkerSize',6,'LineWidth',2)
- hold on;
- plot(sqrt(tflux(1:end-freeb)),G,'m+','MarkerSize',6,'LineWidth',2)
- xlabel('(\Psi / \Psi_{edge})^{1/2}')
- ylabel(Flabel)
+ switch xaxis
+ case 'R'
+ plot(R0,F,'r+','MarkerSize',6,'LineWidth',2)
+ hold on;
+ plot(R0,G,'m+','MarkerSize',6,'LineWidth',2)
+ xlabel('R')
+ ylabel(Flabel)
+ case 'f'
+ plot(tflux(1:end-freeb),F,'r+','MarkerSize',6,'LineWidth',2)
+ hold on;
+ plot(tflux(1:end-freeb),G,'m+','MarkerSize',6,'LineWidth',2)
+ xlabel('\Psi / \Psi_{edge}')
+ ylabel(Flabel)
+ case 'r'
+ plot(sqrt(tflux(1:end-freeb)),F,'r+','MarkerSize',6,'LineWidth',2)
+ hold on;
+ plot(sqrt(tflux(1:end-freeb)),G,'m+','MarkerSize',6,'LineWidth',2)
+ xlabel('(\Psi / \Psi_{edge})^{1/2}')
+ ylabel(Flabel)
+ end
+
end
diff --git a/Utilities/matlabtools/plot_spec_iterations.m b/Utilities/matlabtools/plot_spec_iterations.m
new file mode 100644
index 00000000..01cf2a12
--- /dev/null
+++ b/Utilities/matlabtools/plot_spec_iterations.m
@@ -0,0 +1,138 @@
+function plot_spec_iterations( data, xl, yl )
+
+% PLOT_SPEC_ITERATIONS( DATA, XL, YL )
+% ====================================
+%
+% Plot the volumes interfaces at any iteration of SPEC. Change the
+% iteration using a slider
+%
+% INPUT
+% -----
+% -DATA: Obtained from read_spec( filename )
+% -xl : xlimit
+% -yl : ylimit
+%
+% OUTPUT
+% ------
+% A magnificient plot!
+%
+
+ % Open figure
+ figure( 'Position', [200 200 900 700], 'Color', 'w' )
+ fig = gcf;
+ ax = gca;
+ ax.Position = [0.1300 0.2386 0.7750 0.6864];
+
+ % Read size
+ Nfp = double(data.input.physics.Nfp);
+ [~, ~, Niter] = size(data.iterations.iRbc);
+
+ if Niter==0
+ error('No iterations available')
+ end
+
+ % Create some sliders for controling the iteration and the toroidal
+ % angle
+ sld_phi = uicontrol(fig, 'style', 'slider', 'Position', [200 25 500 20],'units','pixel', ...
+ 'Value',0,'Max',2*pi / Nfp,'Min',0);
+ sld_it = uicontrol(fig, 'style', 'slider', 'Position', [200 63 500 20],'units','pixel', ...
+ 'Value',1,'Max', Niter,'Min',1, 'SliderStep', [1/(Niter-1), 1/(Niter-1)]);
+
+ addlistener( sld_phi, 'ContinuousValueChange', @(sld_phi, event) updatePlot(sld_phi, sld_it, data, xl, yl) );
+ addlistener( sld_it , 'ContinuousValueChange', @(sld_it , event) updatePlot(sld_phi, sld_it, data, xl, yl) );
+
+ % Plot
+ plot_iteration( data, 1, 0, xl, yl )
+ mytitle = sprintf('%s=%2.3f, iteration %05i', '\phi', 0, 1);
+ title(mytitle,'FontSize',18)
+end
+
+
+
+
+function updatePlot(sld_phi, sld_it, data, xl, yl)
+%
+% UPDATEPLOT( SLD_PHI, SLD_IT, DATA, XL, YL )
+% ===========================================
+%
+% Update plot when a slider value has changed
+%
+% INPUTS
+% ------
+% -sld_phi: handle to toroidal angle slider
+% -sld_it : handle to iteration slider
+% -data : obtained from read_spec(filename)
+% -xl : xlimit
+% -yl : ylimit
+%
+
+ phi = sld_phi.Value;
+ iter = round(sld_it.Value);
+
+ plot_iteration( data, iter, phi, xl, yl )
+
+ mytitle = sprintf('%s=%2.3f, iteration %05i', '\phi', phi, iter);
+ title(mytitle,'FontSize',18)
+end
+
+
+function plot_iteration( data, iter, phi, xl, yl )
+%
+% PLOT_ITERATION( DATA, ITER, PHI, XL, YL )
+% =========================================
+%
+% Generate plot from SPEC data
+%
+% INPUTS
+% ------
+% -data: obtained from read_spec( filename )
+% -iter: iteration number
+% -phi : toroidal angle
+% -xl : xlimit
+% -yl : ylimit
+%
+
+ Nfp = double(data.input.physics.Nfp);
+ im = double(data.output.im);
+ in = double(data.output.in) / Nfp;
+ Mvol = double(data.output.Mvol);
+ Ntor = double(data.input.physics.Ntor);
+
+ % Erase previous plot
+ hold off
+
+ % Axis
+ Ra = 0;
+ Za = 0;
+ for nn=0:Ntor
+ Ra = Ra + data.iterations.iRbc(nn+1,1,iter) * cos( nn*Nfp*phi );
+ Za = Za - data.iterations.iZbs(nn+1,1,iter) * sin( nn*Nfp*phi );
+ end
+
+ scatter( Ra, Za, 50, 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'r' )
+
+ hold on
+ % volume boundaries
+ for ivol=2:Mvol+1
+ Rmn = data.iterations.iRbc(:,ivol,iter);
+ Zmn = data.iterations.iZbs(:,ivol,iter);
+
+ tarr = linspace( 0, 2*pi, 1024 );
+ R = zeros(1,1024);
+ Z = zeros(1,1024);
+ for ii=1:length(Rmn)
+ arg = im(ii) * tarr - in(ii) * Nfp * phi;
+ R = R + Rmn(ii) * cos( arg );
+ Z = Z + Zmn(ii) * sin( arg );
+ end
+
+ scatter( R, Z )
+ hold on
+ axis equal
+ end
+
+
+ xlim(xl)
+ ylim(yl)
+end
+
diff --git a/Utilities/matlabtools/plot_spec_jacobian.m b/Utilities/matlabtools/plot_spec_jacobian.m
index 82c84fe4..7910d29c 100644
--- a/Utilities/matlabtools/plot_spec_jacobian.m
+++ b/Utilities/matlabtools/plot_spec_jacobian.m
@@ -9,7 +9,7 @@
% INPUT
% -----
% -data : data obtained via read_spec(filename)
-% -lvol : volume number
+% -lvol : volume number. Set to 0 for plotting all volumes
% -sarr : is the array of values for the s-coordinate ('d' for default)
% -tarr : is the array of values for the theta-coordinate ('d' for default)
% -zarr : is the array of values for the zeta-coordinate ('d' for default)
@@ -23,70 +23,113 @@
% written by J.Loizu (2016)
if(sarr=='d')
-sarr=linspace(-1,1,64);
+ sarr=linspace(-1,1,64);
end
if(tarr=='d')
-tarr=linspace(0,2*pi,64);
+ tarr=linspace(0,2*pi,64);
end
if(zarr=='d')
-zarr=0;
+ zarr=0;
end
-rzbdata = cell(3);
-
-% Compute sqrt(g)
-
-jac = get_spec_jacobian(data,lvol,sarr,tarr,zarr);
-
-% Compute function (R,Z)(s,theta,zeta)
+% Check inputs
+if lvol<1 || lvol>data.output.Mvol
+ error('InputError: invalid lvol')
+end
-rzdata = get_spec_rzarr(data,lvol,sarr,tarr,zarr);
+if isempty(sarr)
+ error('InputError: sarr is empty')
+end
+if isempty(tarr)
+ error('InputError: tarr is empty')
+end
+if isempty(zarr)
+ error('InputError: zarr is empty')
+end
-R = rzdata{1};
-Z = rzdata{2};
+if sarr(1)<-1 || sarr(end)>1
+ error('InputError: invalid sarr')
+end
-% Plot
+if any(diff(sarr)<0)
+ error('InputError: sarr is not monotonic')
+end
switch newfig
case 0
hold on
case 1
- figure
+ figure('Color','w','Position',[200 200 900 700])
hold on
case 2
hold off
+ otherwise
+ error('InputError: invalid newfig')
end
-Rtemp = R;
-Ztemp = Z;
-switch data.input.physics.Igeometry
- case 1
- R = tarr;
- Z = Rtemp;
- case 2
- for it=1:length(tarr)
- R(:,it,:) = Rtemp(:,it,:) .* cos(tarr(it));
- Z(:,it,:) = Rtemp(:,it,:) .* sin(tarr(it));
- end
- case 3
- R = Rtemp;
- Z = Ztemp;
+
+
+% Check input
+if (length(sarr)>1) && length(tarr)>1 && length(zarr)>1
+ error('This is a 2d plotting routine; one input array has to be a scalar')
end
-
-for iz=1:length(zarr)
-
- pcolor(R(:,:,iz),Z(:,:,iz),jac(:,:,iz)); shading interp; colorbar
- hold on
- axis equal
- title('|B|');
- xlabel('R');
- ylabel('Z');
+% Allocate memory
+rzbdata = cell(3);
+
+if lvol==0
+ lstart=1;
+ lend =data.output.Mvol;
+else
+ lstart=lvol;
+ lend =lvol;
+end
+
+for ivol=lstart:lend
+ % Compute sqrt(g)
+ jac = squeeze(get_spec_jacobian(data,ivol,sarr,tarr,zarr));
+
+ % Compute function (R,Z)(s,theta,zeta)
+ R = get_spec_R_derivatives(data,ivol,sarr,tarr,zarr,'R');
+ Z = get_spec_R_derivatives(data,ivol,sarr,tarr,zarr,'Z');
+
+ R = R{1};
+ Z = Z{1};
+
+ % Plot
+ Rtemp = R;
+ Ztemp = Z;
+ switch data.input.physics.Igeometry
+ case 1
+ R = tarr;
+ Z = Rtemp;
+ case 2
+ for it=1:length(tarr)
+ R(:,it,:) = Rtemp(:,it,:) .* cos(tarr(it));
+ Z(:,it,:) = Rtemp(:,it,:) .* sin(tarr(it));
+ end
+ case 3
+ R = squeeze(Rtemp);
+ Z = squeeze(Ztemp);
+ end
+
+
+ pcolor(R,Z,jac);
+ shading interp;
+ colorbar
+ hold on
end
+axis equal
+title('|B|');
+xlabel('R');
+ylabel('Z');
+set(gca, 'FontSize', 18)
+
+
% Output data
rzbdata{1} = R;
diff --git a/Utilities/matlabtools/plot_spec_kam.m b/Utilities/matlabtools/plot_spec_kam.m
index 28226ae5..d5d3f4bb 100644
--- a/Utilities/matlabtools/plot_spec_kam.m
+++ b/Utilities/matlabtools/plot_spec_kam.m
@@ -1,107 +1,121 @@
-function plot_spec_kam(data,zetaov2pi,newfig)
+function plot_spec_kam(data, zeta, newfig, varargin)
%
-% PLOT_SPEC_KAM( DATA, ZETAOV2PI, NEWFIG )
-% ========================================
+% PLOT_SPEC_KAM( DATA, NZ0, NEWFIG )
+% ==================================
%
% Produces a "Poincare plot" of the KAM surfaces.
%
% INPUT
% -----
% -data : obtained from read_spec(fname)
-% -zetaov2pi : shows the toroidal plane at zeta=2*pi*(zetaov2pi)
+% -zeta : toroidal angle
% -newfig : opens(=1) or not(=0) a new figure, or overplots(=2) on existing figure
%
% written by J.Loizu (2016)
-% upgraded by J.Loizu (07.2017)
-% modified by A. Baillod (06.2019)
-% modified by J.Loizu (01.2020)
-
-
-Nvol = double(data.input.physics.Nvol);
-mn = data.output.mn;
-im = data.output.im;
-in = data.output.in;
-Rbcmn = data.output.Rbc;
-Rbsmn = data.output.Rbs;
-Zbcmn = data.output.Zbc;
-Zbsmn = data.output.Zbs;
-Igeometry = data.input.physics.Igeometry;
-try
- rpol = data.input.physics.rpol;
-catch
- rpol = 1;
-end
-
-% Compute (x,y) coordinates of each KAM surface
-
-zeta = zetaov2pi*(2*pi);
-
-nth = 2048;
-dth = 2*pi/nth;
-theta = dth:dth:2*pi;
-
-X = zeros(Nvol,nth);
-Y = zeros(Nvol,nth);
-
-
-switch Igeometry
- case 1
- X = zeros(Nvol+1,nth);
- Y = zeros(Nvol+1,nth);
- for i=1:Nvol+1
- X(i,:) = rpol*theta;
- for k=1:mn
- alpha = double(im(k))*theta-double(in(k))*zeta;
- Y(i,:) = Y(i,:) + Rbcmn(k,i)*cos(alpha) + Rbsmn(k,i)*sin(alpha);
+
+ % Check inputs
+ switch newfig
+ case 0
+ hold on
+ case 1
+ figure
+ hold on
+ case 2
+ hold off
+ otherwise
+ error('InputError: invalid newfig')
+ end
+
+
+ l = length(varargin);
+ if mod(l,2)~=0
+ error('InputError: Invalid number of argument')
+ end
+
+ opt.InterfaceColor = 'r';
+ for ii=1:l/2
+ field = varargin{2*ii-1};
+ value = varargin{2*ii };
+
+ opt.(field)=value;
+ end
+
+ Ndiscrete = double(data.input.numerics.Ndiscrete);
+ Ntor = double(max(abs(data.output.in)));
+ Nplan = max(Ndiscrete*4*Ntor, 1);
+
+ Nvol = double(data.input.physics.Nvol);
+ mn = data.output.mn;
+ im = data.output.im;
+ in = data.output.in;
+ Rbcmn = data.output.Rbc;
+ Rbsmn = data.output.Rbs;
+ Zbcmn = data.output.Zbc;
+ Zbsmn = data.output.Zbs;
+ Igeometry = data.input.physics.Igeometry;
+ try
+ rpol = data.input.physics.rpol;
+ catch
+ rpol = 1;
+ end
+
+ % Compute (x,y) coordinates of each KAM surface
+ nth = 2048;
+ dth = 2*pi/nth;
+ theta = dth:dth:2*pi;
+
+ X = zeros(Nvol,nth);
+ Y = zeros(Nvol,nth);
+
+
+ switch Igeometry
+ case 1
+ X = zeros(Nvol+1,nth);
+ Y = zeros(Nvol+1,nth);
+ for i=1:Nvol+1
+ X(i,:) = rpol*theta;
+ for k=1:mn
+ alpha = double(im(k))*theta-double(in(k))*zeta;
+ Y(i,:) = Y(i,:) + Rbcmn(k,i)*cos(alpha) + Rbsmn(k,i)*sin(alpha);
+ end
end
- end
- case 2
- for i=1:Nvol
- for k=1:mn
- alpha = double(im(k))*theta-double(in(k))*zeta;
- X(i,:) = X(i,:) + (Rbcmn(k,i+1)*cos(alpha) + Rbsmn(k,i+1)*sin(alpha)).*cos(theta);
- Y(i,:) = Y(i,:) + (Rbcmn(k,i+1)*cos(alpha) + Rbsmn(k,i+1)*sin(alpha)).*sin(theta);
+ case 2
+ for i=1:Nvol
+ for k=1:mn
+ alpha = double(im(k))*theta-double(in(k))*zeta;
+ X(i,:) = X(i,:) + (Rbcmn(k,i+1)*cos(alpha) + Rbsmn(k,i+1)*sin(alpha)).*cos(theta);
+ Y(i,:) = Y(i,:) + (Rbcmn(k,i+1)*cos(alpha) + Rbsmn(k,i+1)*sin(alpha)).*sin(theta);
+ end
end
- end
- case 3
- for i=1:Nvol
- for k=1:mn
- alpha = double(im(k))*theta-double(in(k))*zeta;
- X(i,:) = X(i,:) + Rbcmn(k,i+1)*cos(alpha) + Rbsmn(k,i+1)*sin(alpha);
- Y(i,:) = Y(i,:) + Zbsmn(k,i+1)*sin(alpha) + Zbcmn(k,i+1)*cos(alpha);
+ case 3
+ for i=1:Nvol
+ for k=1:mn
+ alpha = double(im(k))*theta-double(in(k))*zeta;
+ X(i,:) = X(i,:) + Rbcmn(k,i+1)*cos(alpha) + Rbsmn(k,i+1)*sin(alpha);
+ Y(i,:) = Y(i,:) + Zbsmn(k,i+1)*sin(alpha) + Zbcmn(k,i+1)*cos(alpha);
+ end
end
- end
- otherwise
- error('Unsupported geometry')
-end
-
-
-% Plot Poincare section
-
-switch newfig
- case 0
- hold on
- case 1
- figure
- hold on
- case 2
- hold off
-end
-
-for i=1:size(X,1)
- scatter(X(i,:),Y(i,:),3,'filled','r')
- hold on
-end
-
-hold on
-set(gca,'FontSize',12)
-
-if Igeometry~=1
- axis equal
- xlabel('R','FontSize',12)
- ylabel('Z','FontSize',12)
-else
- xlabel('\theta r_{pol}','FontSize',12)
- ylabel('R','FontSize',12)
-end
+ otherwise
+ error('Unsupported geometry')
+ end
+
+
+ % Plot Poincare section
+ for i=1:size(X,1)
+ scatter(X(i,:),Y(i,:),3,'filled','MarkerFaceColor',opt.InterfaceColor,'MarkerEdgeColor',opt.InterfaceColor)
+ hold on
+ end
+
+ hold on
+ set(gca,'FontSize',12)
+
+ if Igeometry~=1
+ axis equal
+ xlabel('R','FontSize',12)
+ ylabel('Z','FontSize',12)
+ else
+ xlabel('\theta r_{pol}','FontSize',12)
+ ylabel('R','FontSize',12)
+ end
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/plot_spec_modB.m b/Utilities/matlabtools/plot_spec_modB.m
index 4034f956..fcfda5f0 100644
--- a/Utilities/matlabtools/plot_spec_modB.m
+++ b/Utilities/matlabtools/plot_spec_modB.m
@@ -4,7 +4,7 @@
% PLOT_SPEC_MODB( DATA, LVOL, SARR, TARR, ZARR, NEWFIG )
% ======================================================
%
-% Produces plot of |B| in (R,Z,zarr) cross-section(s)
+% Produces plot of |B| in (R,Z) cross-section(s), for any toroidal angle
%
% INPUT
% -----
@@ -14,7 +14,7 @@
% -tarr : is the array of values for the theta-coordinate ('d' for default)
% -zarr : is the array of values for the zeta-coordinate ('d' for default)
% -newfig : opens(=1) or not(=0) a new figure, or overwrite existing one
-% (=2)
+% (=2)
%
% OUTPUT
% ------
@@ -22,75 +22,100 @@
%
% written by J.Loizu (2016)
-if(sarr=='d')
-sarr=linspace(-1,1,64);
-end
-
-if(tarr=='d')
-tarr=linspace(0,2*pi,64);
-end
-
-if(zarr=='d')
-zarr=0;
-end
-
-rzbdata = cell(3);
-
-
-% Compute |B|
-
-modB = get_spec_modB(data,lvol,sarr,tarr,zarr);
-
-% Compute function (R,Z)(s,theta,zeta)
-
-rzdata = get_spec_rzarr(data,lvol,sarr,tarr,zarr);
-
-R = rzdata{1};
-Z = rzdata{2};
-
-% Plot
+ % Default inputs
+ if(sarr=='d')
+ sarr=linspace(-1,1,64);
+ end
+
+ if(tarr=='d')
+ tarr=linspace(0,2*pi,64);
+ end
+
+ if(zarr=='d')
+ zarr=0;
+ end
+
+ % Check inputs
+ Mvol = data.output.Mvol;
+ if lvol<1 || lvol>Mvol
+ error('InputError: invalid lvol')
+ end
+
+ if isempty(sarr)
+ error('InputError: sarr is empty')
+ end
+ if isempty(tarr)
+ error('InputError: tarr is empty')
+ end
+ if isempty(zarr)
+ error('InputError: zarr is empty')
+ end
+
+ if sarr(1)<-1 || sarr(end)>1
+ error('InputError: invalid sarr')
+ end
+ if any(diff(sarr)<0)
+ error('InputError: sarr is not monotonic')
+ end
+
+ rzbdata = cell(3);
+
+
+ % Compute |B|
+
+ modB = get_spec_modB(data,lvol,sarr,tarr,zarr);
+
+ % Compute function (R,Z)(s,theta,zeta)
+ R = get_spec_R_derivatives(data,lvol,sarr,tarr,zarr,'R');
+ Z = get_spec_R_derivatives(data,lvol,sarr,tarr,zarr,'Z');
+
+ R = R{1};
+ Z = Z{1};
+
+ % Plot
+ Rtemp = R;
+ Ztemp = Z;
+ switch data.input.physics.Igeometry
+ case 1
+ R = tarr;
+ Z = Rtemp;
+ case 2
+ for it=1:length(tarr)
+ R(:,it,:) = Rtemp(:,it,:) .* cos(tarr(it));
+ Z(:,it,:) = Rtemp(:,it,:) .* sin(tarr(it));
+ end
+ case 3
+ R = Rtemp;
+ Z = Ztemp;
+ end
+
+
+ for iz=1:length(zarr)
+ switch newfig
+ case 0
+ hold on
+ case 1
+ figure
+ hold on
+ case 2
+ hold off
+ otherwise
+ error('InputError: Invalid newfig')
+ end
-switch newfig
- case 0
- hold on
- case 1
- figure
+ pcolor(R(:,:,iz),Z(:,:,iz),modB(:,:,iz)); shading interp; colorbar
hold on
- case 2
- hold off
-end
-Rtemp = R;
-Ztemp = Z;
-switch data.input.physics.Igeometry
- case 1
- R = tarr;
- Z = Rtemp;
- case 2
- for it=1:length(tarr)
- R(:,it,:) = Rtemp(:,it,:) .* cos(tarr(it));
- Z(:,it,:) = Rtemp(:,it,:) .* sin(tarr(it));
- end
- case 3
- R = Rtemp;
- Z = Ztemp;
-end
-
+ axis equal
+ title('|B|');
+ xlabel('R');
+ ylabel('Z');
+ end
-for iz=1:length(zarr)
-
- pcolor(R(:,:,iz),Z(:,:,iz),modB(:,:,iz)); shading interp; colorbar
- hold on
+ % Output data
- axis equal
- title('|B|');
- xlabel('R');
- ylabel('Z');
+ rzbdata{1} = R;
+ rzbdata{2} = Z;
+ rzbdata{3} = modB;
end
-% Output data
-
-rzbdata{1} = R;
-rzbdata{2} = Z;
-rzbdata{3} = modB;
-
diff --git a/Utilities/matlabtools/plot_spec_modB_boundary.m b/Utilities/matlabtools/plot_spec_modB_boundary.m
index a92feb89..43addcda 100644
--- a/Utilities/matlabtools/plot_spec_modB_boundary.m
+++ b/Utilities/matlabtools/plot_spec_modB_boundary.m
@@ -1,68 +1,128 @@
-function plot_spec_modB_boundary(data,vol,nt,nz)
+function plot_spec_modB_boundary(data,interface,innout,nt,nz,dimension)
%
-% PLOT_SPEC_MODB_BOUNDARY( DATA, VOL, NT, NZ )
-% ============================================
+% PLOT_SPEC_MODB_BOUNDARY( DATA, INTERFACE, INNOUT, NT, NZ, DIMENSION )
+% =====================================================================
%
% Produces plot of |B| on the full boundary surface in toroidal geometry.
%
% INPUT
% -----
% -data : data obtained via read_spec(filename)
-% -vol : Volume on which modB should be plotted
+% -interface : Interface on which modB should be plotted
+% -innout: (0) - inner side of interface
+% (1) - outer side of interface
% -nt : poloidal resolution for the plotting (e.g. nt=64)
% -nz : toroidal resolution for the plotting (e.g. nz=64)
+% -dimension: (2) - plot a colorplot on a theta-phi grid
+% (3) - plot a colorplot on a 3d surface
%
% written by J.Loizu (2016)
% modified by J.Loizu (01.2017)
-sarr = 1;
+ Mvol = data.output.Mvol;
+ if interface<1 || interface>Mvol
+ error('InputError: invalid interface')
+ end
+
+ switch innout
+ case 0
+ vol = interface;
+ sarr = 1;
+ case 1
+ if interface==Mvol
+ error('InputError: Cannot plot on the outer side of last interface!')
+ end
+ vol = interface+1;
+ sarr = -1;
+ otherwise
+ error('InputError: interface should be 0 or 1')
+ end
+
+ if nt<1
+ error('InputError: invalid nt')
+ end
+ if nz<1
+ error('InputError: invalid nz')
+ end
+ if ~any(dimension==[2,3])
+ error('InputError: invalid dimension')
+ end
+
+ tarr = linspace(0,2*pi,nt);
+ zarr = linspace(0,2*pi,nz);
+
+ if(vol>Mvol || vol<1)
+ error('vol not valid')
+ end
-tarr = linspace(0,2*pi,nt);
+if(vol>Mvol)
+ % Compute |B|
+end
-zarr = linspace(0,2*pi,nz);
+ modB = get_spec_modB(data,vol,sarr,tarr,zarr);
+ switch dimension
+ case 2
+ figure
-Mvol = data.output.Mvol;
-if(vol>Mvol)
- error('vol not valid')
-end
+ [t,z] = meshgrid(tarr, zarr);
+ modB = reshape(modB, nt, nz);
-% Compute |B|
+ pcolor( z, t, modB' )
+ shading interp
-modB = get_spec_modB(data,vol,sarr,tarr,zarr);
+ colorbar
+ xlabel('$\phi$', 'Interpreter', 'latex')
+ ylabel('$\theta$', 'Interpreter', 'latex')
+ ax = gca;
+ ax.YTick = [pi/4,pi/2,3*pi/4,pi,5*pi/4,3*pi/2,7*pi/4];
+ ax.YTickLabel = {'$\frac{\pi}{4}$','$\frac{\pi}{2}$','$\frac{3\pi}{4}$','$\pi$','$\frac{5\pi}{4}$', '$\frac{3\pi}{2}$','$\frac{7\pi}{4}$'};
+ ax.XTick = [pi/4,pi/2,3*pi/4,pi,5*pi/4,3*pi/2,7*pi/4];
+ ax.XTickLabel = {'$\frac{\pi}{4}$','$\frac{\pi}{2}$','$\frac{3\pi}{4}$','$\pi$','$\frac{5\pi}{4}$', '$\frac{3\pi}{2}$','$\frac{7\pi}{4}$'};
+ ax.TickLabelInterpreter = 'latex';
-% Compute function (R,Z)(s,theta,zeta)
+ set(gca,'FontSize',18)
+ set(gcf,'Position',[200 200 900 700])
-rzdata = get_spec_rzarr(data,vol,sarr,tarr,zarr);
-R = squeeze(rzdata{1});
-Z = squeeze(rzdata{2});
+ case 3
+ % Compute function (R,Z)(s,theta,zeta)
+ R = get_spec_R_derivatives(data,vol,sarr,tarr,zarr,'R');
+ Z = get_spec_R_derivatives(data,vol,sarr,tarr,zarr,'Z');
+ R = squeeze(R{1});
+ Z = squeeze(Z{1});
-% Construct cartesian corrdinates
-X = zeros(nt,nz);
+ % Construct cartesian corrdinates
-Y = zeros(nt,nz);
-
-for it=1:nt
- for iz=1:nz
- X(it,iz) = R(it,iz)*cos(zarr(iz));
- Y(it,iz) = R(it,iz)*sin(zarr(iz));
- end
-end
-
-
-% Plot
+ X = zeros(nt,nz);
+
+ Y = zeros(nt,nz);
-figure
+ for it=1:nt
+ for iz=1:nz
+ X(it,iz) = R(it,iz)*cos(zarr(iz));
+ Y(it,iz) = R(it,iz)*sin(zarr(iz));
+ end
+ end
-h=surf(X,Y,Z,squeeze(modB(1,:,:)));
-axis equal
-shading interp
-colorbar
-title('| B |')
+ % Plot
+
+ figure
+
+ h=surf(X,Y,Z,squeeze(modB(1,:,:)));
+
+ axis equal
+ shading interp
+ colorbar
+ title('| B |')
+
+ otherwise
+ error('Invalid dimension')
+ end
+end
diff --git a/Utilities/matlabtools/plot_spec_outfluxfun.m b/Utilities/matlabtools/plot_spec_outfluxfun.m
deleted file mode 100644
index c3e28d75..00000000
--- a/Utilities/matlabtools/plot_spec_outfluxfun.m
+++ /dev/null
@@ -1,41 +0,0 @@
-function plot_spec_outfluxfun(data,ns,nt,z0,ncont,newfig)
-
-%
-% PLOT_SPEC_OUTFLUXFUN( DATA, NS, NT, Z0, NCONT, NEWFIG )
-% =======================================================
-%
-% Plots iso-contours of Az on a given cross-section
-%
-% INPUT
-% -----
-% -data : must be produced by calling read_spec(filename)
-% -ns : radial resolution for construction of Az
-% -nt : poloidal resolution for construction of Az
-% -z0 : toroidal angle at which Az is evaluated
-% -ncont : number of iso-contour lines
-% -newfig : flag for whether a new figure should be open (=1) or not(=0)
-%
-% Note: should only work for free-boundary equilibria
-% Note: poloidal flux function is psi=-A_phi if A_phi is the covariant component and psi=-R*A_phi if A_phi is the canonical component
-%
-% written by J.Loizu (2018)
-
-
-Nvol = data.input.physics.Nvol;
-
-lvol = Nvol+1;
-
-sarr = linspace(-1,1,ns);
-
-tarr = linspace(0,2*pi,nt);
-
-acov = get_spec_vecpot(data,lvol,sarr,tarr,z0);
-rz = get_spec_rzarr( data,lvol,sarr,tarr,z0);
-
-ffun = -acov{2};
-
-if(newfig==1)
- figure; hold on;
-end
-
-contour(rz{1},rz{2},ffun,ncont,'k')
diff --git a/Utilities/matlabtools/plot_spec_poincare.m b/Utilities/matlabtools/plot_spec_poincare.m
index 2bbda005..7cb9842c 100644
--- a/Utilities/matlabtools/plot_spec_poincare.m
+++ b/Utilities/matlabtools/plot_spec_poincare.m
@@ -1,35 +1,72 @@
-function plot_spec_poincare(data,nz0,nfp,arr,newfig)
+function phi = plot_spec_poincare(data,nz0,arr,kam,newfig,varargin)
%
-% PLOT_SPEC_POINCARE( DATA, NZ0, NFP, ARR, NEWFIG )
-% =================================================
+% PLOT_SPEC_POINCARE( DATA, NZ0, NFP, ARR, NEWFIG, VARARGIN )
+% ===========================================================
%
-% Produces Poincare plots of the field lines on different sections (within one field period)
+% Produces Poincare plots of the field lines on different sections (within
+% one field period)
%
% INPUT
% -----
% -data : must be produced by calling read_spec(fname)
% -nz0 : shows the nz0 toroidal plane or equidistant planes (nz0=-1)
% -nfp : number of field periods
-% -arr : step to skip field-line trajectories when ploting (arr=1 means all trajectories are ploted)
-% : can be an array of which field line should be plotted, if size(arra)>1
-% -newfig : opens(=1) or not(=0) a new figure, or overwrites (=2) last plot
+% -arr : step to skip field-line trajectories when ploting (arr=1
+% means all trajectories are ploted)
+% : can be an array of which field line should be plotted, if
+% size(arra)>1
+% -kam : Plots (=1) or not (=0) the KAM surfaces.
+% -newfig : opens(=1) or not(=0) a new figure, or overwrites (=2) last
+% plot
+% -varargin : Optional arguments. Any of the following pairs are
+% supported:
+% - 'BoundaryColor', value: color of the plasma boundary or
+% wall. default: red
+% - 'step', n: plot one every n toroidal transit. This allows
+% lighter plts when exporting to eps. By
+% default, all toroidal transit are plotted
+% (n=1)
%
% written by J.Loizu (2015)
% modified by A.Baillod (2019)
% modified by J.Loizu (2020)
-try
- rpol = data.input.physics.rpol; % get size of slab
-catch
- rpol = 1;
+ll = length(varargin);
+if mod(ll,2)~=0
+ error('InputError: invalid number of optional arguments')
end
-nptraj = size(data.poincare.R,1); % # of poincare trajectories (field lines)
+opt.BoundaryColor = 'r';
+opt.step = 1;
+for ii=1:ll/2
+ opt.(varargin{2*ii-1}) = varargin{2*ii};
+end
+stp = opt.step;
+
+% Check that Poincare data is available
+if data.input.diagnostics.nPpts==0 || all(data.input.diagnostics.nPtrj==0)
+ error('No Poincare data available')
+end
+% Read some data...
+nfp = data.input.physics.Nfp;
+
+if data.input.physics.Igeometry==1
+ try
+ rpol = data.input.physics.rpol; % get size of slab
+ catch
+ rpol = 1;
+ end
+end
+
+% Read size
+nptraj = size(data.poincare.R,1); % # of poincare trajectories (field lines)
nz = size(data.poincare.R,2); % # of toroidal planes
+if nz0<1 || nz0>nz
+ error('InputError: invalid toroidal plane. Should be 0nptraj);
if ~isempty(ind)
@@ -40,62 +77,26 @@ function plot_spec_poincare(data,nz0,nfp,arr,newfig)
arr = 1:arr:nptraj;
end
-
-
-disp(' ');
-disp('Number of toroidal planes available: (one field period)');
-nz
-disp(' ');
-
-
-rmax = max(max(max(data.poincare.R)));
-rmin = min(min(min(data.poincare.R)));
-zmax = max(max(max(data.poincare.Z)));
-zmin = min(min(min(data.poincare.Z)));
-
-switch data.input.physics.Igeometry
- case 1
- xmin = 0;
- xmax = 2*pi*rpol;
- ymin = -0.1;
- ymax = data.output.Rbc(1,end)+0.1;
- case 2
- xmin = -1.1*rmax;
- xmax = 1.1*rmax;
- ymin = -1.1*rmax;
- ymax = 1.1*rmax;
- case 3
- xmin = 0.9*rmin;
- xmax = 1.1*rmax;
- ymin = 1.1*zmin;
- ymax = 1.1*zmax;
-end
-
-
-nth = 5096; %ploting options for the boundary
-bcol = 'r';
+%ploting options for the boundary
+nth = 5096;
+bcol = opt.BoundaryColor;
bthick = 3;
+lthick = 1;
if(data.input.physics.Lfreebound==1)
-bcol = 'k';
-bthick = 1;
-end
-
-
-
-if(flag2col=='T')
- pcol = ['k' 'b'];
-else
- pcol = ['k' 'k'];
+ bcol = opt.BoundaryColor;
+ bthick = 1;
end
switch newfig
case 0
hold on
case 1
- figure
+ figure('Color','w','Position',[200 200 900 700])
hold on
case 2
hold off
+ otherwise
+ error('InputError: invalid newfig')
end
switch nz0
@@ -116,21 +117,21 @@ function plot_spec_poincare(data,nz0,nfp,arr,newfig)
R = squeeze(data.poincare.R(:,j,:));
T = rpol*mod(squeeze(data.poincare.t(:,j,:)),2*pi);
for i=arr %for each field line trajectory
- scatter(T(i,:),R(i,:),10,'.k')
+ scatter(T(i,:),R(i,:),lthick,'.k')
hold on
end
case 2
R = squeeze(data.poincare.R(:,j,:));
T = squeeze(data.poincare.t(:,j,:));
for i=arr %for each field line trajectory
- scatter(R(i,:).*cos(T(i,:)),R(i,:).*sin(T(i,:)),10,'.k')
+ scatter(R(i,:).*cos(T(i,:)),R(i,:).*sin(T(i,:)),lthick,'.k')
hold on;
end
case 3
R = squeeze(data.poincare.R(:,j,:));
Z = squeeze(data.poincare.Z(:,j,:));
for i=arr %for each field line trajectory
- scatter(R(i,:),Z(i,:),10,'.k')
+ scatter(R(i,:),Z(i,:),lthick,'.k')
hold on;
end
otherwise
@@ -140,6 +141,7 @@ function plot_spec_poincare(data,nz0,nfp,arr,newfig)
dth = 2*pi/nth;
theta = dth:dth:2*pi;
zeta = (j-1)*(2*pi/nz)/nfp;
+ phi = NaN;
switch data.input.physics.Igeometry
case 1
@@ -187,31 +189,28 @@ function plot_spec_poincare(data,nz0,nfp,arr,newfig)
ylabel('R','FontSize',12)
end
- xlim([xmin xmax])
- ylim([ymin ymax])
-
end
otherwise %if nz0>0
switch data.input.physics.Igeometry
case 1
- R = squeeze(data.poincare.R(:,nz0,:));
- T = rpol*mod(squeeze(data.poincare.t(:,nz0,:)),2*pi);
+ R = squeeze(data.poincare.R(:,nz0,1:stp:end));
+ T = rpol*mod(squeeze(data.poincare.t(:,nz0,1:stp:end)),2*pi);
for i=arr %for each field line trajectory
scatter(T(i,:),R(i,:),10,'.k')
hold on
end
case 2
- R = squeeze(data.poincare.R(:,nz0,:));
- T = squeeze(data.poincare.t(:,nz0,:));
+ R = squeeze(data.poincare.R(:,nz0,1:stp:end));
+ T = squeeze(data.poincare.t(:,nz0,1:stp:end));
for i=arr %for each field line trajectory
scatter(R(i,:).*cos(T(i,:)),R(i,:).*sin(T(i,:)),10,'.k')
hold on;
end
case 3
- R = squeeze(data.poincare.R(:,nz0,:));
- Z = squeeze(data.poincare.Z(:,nz0,:));
+ R = squeeze(data.poincare.R(:,nz0,1:stp:end));
+ Z = squeeze(data.poincare.Z(:,nz0,1:stp:end));
for i=arr %for each field line trajectory
scatter(R(i,:),Z(i,:),10,'.k')
hold on;
@@ -224,6 +223,7 @@ function plot_spec_poincare(data,nz0,nfp,arr,newfig)
dth = 2*pi/nth;
theta = dth:dth:2*pi;
zeta = (nz0-1.0)*(2.0*pi/nz)/double(nfp);
+ phi = zeta;
switch data.input.physics.Igeometry
@@ -257,7 +257,7 @@ function plot_spec_poincare(data,nz0,nfp,arr,newfig)
end
if data.input.physics.Igeometry ~= 1
- scatter(Rb,Zb,bthick,'*',bcol)
+ scatter(Rb,Zb,bthick,'*','MarkerFaceColor',bcol,'MarkerEdgeColor',bcol)
hold on
set(gca,'FontSize',12)
axis equal
@@ -272,11 +272,14 @@ function plot_spec_poincare(data,nz0,nfp,arr,newfig)
ylabel('R','FontSize',12)
end
- xlim([xmin xmax])
- ylim([ymin ymax])
+ set(gca,'FontSize',18)
end
+if kam
+ phi = 2*pi*(nz0-1) / (double(nfp)*nz);
+ plot_spec_kam(data, phi, 0 )
+end
disp(' ');
disp('--- end of program ---');
diff --git a/Utilities/matlabtools/plot_spec_poincare_3d.m b/Utilities/matlabtools/plot_spec_poincare_3d.m
new file mode 100644
index 00000000..90f58483
--- /dev/null
+++ b/Utilities/matlabtools/plot_spec_poincare_3d.m
@@ -0,0 +1,174 @@
+function plot_spec_poincare_3d( data, varargin )
+%
+% PLOT_SPEC_POINCARE_3D( DATA )
+% -----------------------------
+%
+% Plot parts of the 3d stellarator geometry, the Poincare plot and traces a
+% field line
+%
+% INPUTS
+% ------
+% * data: Obtained with read_spec(filename)
+% * varargin: optional inputs. Can be any pairs of
+% 'nt': Number of poloidal points. Default is 64
+% 'nz': Number of toroidal points. Default is 64
+% 'phiend': Plots 3d shape from phi=0 to phiend. Default is 2pi/Nfp
+% 'tstart': Start field line tracing at this value of theta. Can be
+% an array. Default is 0.
+
+
+ % Load the colors and some data
+ col = EPFL_colors;
+ Nvol = double(data.input.physics.Nvol);
+ Nfp = double(data.input.physics.Nfp);
+
+ % Set up options
+ opt.nt = 64;
+ opt.nz = 64;
+ opt.phiend = 2*pi / max(Nfp,2);
+ opt.tstart = 0;
+
+ l = length(varargin);
+ if mod(l,2)~=0
+ error('Invalid number of arguments')
+ end
+
+ for ii=1:l/2
+ opt.(varargin{2*ii-1}) = varargin{2*ii};
+ end
+
+ opt.tstart = reshape(opt.tstart, length(opt.tstart), 1);
+
+ % Define coordinate arrays in real space
+ sarr = 1; % We plot on the outermost surface, i.e. the plasma boundary
+ tarr = linspace(0,2*pi ,opt.nt);
+ zarr = linspace(0,opt.phiend ,opt.nz);
+
+ R = get_spec_R_derivatives(data,Nvol,sarr,tarr,zarr,'R');
+ Z = get_spec_R_derivatives(data,Nvol,sarr,tarr,zarr,'Z');
+
+ R = squeeze(R{1});
+ Z = squeeze(Z{1});
+
+
+ % Construct cartesian corrdinates
+
+ X = zeros(opt.nt,opt.nz);
+ Y = zeros(opt.nt,opt.nz);
+
+ for it=1:opt.nt
+ for iz=1:opt.nz
+ X(it,iz) = R(it,iz)*cos(zarr(iz));
+ Y(it,iz) = R(it,iz)*sin(zarr(iz));
+ end
+ end
+
+
+ % Plot
+
+ figure('Position', [200 200 900 700], 'Color', 'w')
+
+ s = size(X);
+ c = zeros(s(1), s(2), 3);
+ c(:,:,1) = 1;
+ mesh(X,Y,Z,c);
+ hold on
+
+ axis equal
+ shading interp
+
+ xlabel('X')
+ ylabel('Y')
+ zlabel('Z')
+ set(gca, 'FontSize', 18 )
+
+ % Add white surface on plane y=0
+ M = makehgtform('xrotate',pi/2);
+ t = hgtransform('Matrix', M);
+
+ pshape = polyshape(X(:,1), Z(:,1));
+ plot(pshape, 'Parent', t, 'FaceColor', 'w', 'FaceAlpha', 0.9 )
+
+
+
+
+ % Add Poincare plot
+ X = squeeze(data.poincare.R(:,1,:));
+
+ s = size(X);
+
+ Y = zeros(size(X));
+ Z = squeeze(data.poincare.Z(:,1,:));
+ for i=1:s(1) %for each field line trajectory
+ scatter3(X(i,:),Y(i,:),Z(i,:),10,'.k')
+ hold on;
+ end
+
+ % Add KAM surfaces
+ mn = data.output.mn;
+ im = data.output.im;
+ Rbcmn = data.output.Rbc;
+ Rbsmn = data.output.Rbs;
+ Zbcmn = data.output.Zbc;
+ Zbsmn = data.output.Zbs;
+
+ nt = 1024;
+ tarr = linspace(0, 2*pi, nt);
+
+ X = zeros(Nvol,nt);
+ Y = zeros(Nvol,nt);
+ for i=1:Nvol
+ for k=1:mn
+ alpha = double(im(k))*tarr; %phi = 0
+ X(i,:) = X(i,:) + Rbcmn(k,i+1)*cos(alpha) + Rbsmn(k,i+1)*sin(alpha);
+ Y(i,:) = Y(i,:) + Zbsmn(k,i+1)*sin(alpha) + Zbcmn(k,i+1)*cos(alpha);
+ end
+ end
+
+ for i=1:size(X,1)
+ scatter3(X(i,:),zeros(nt,1),Y(i,:),3,'filled','MarkerFaceColor','r','MarkerEdgeColor','r')
+ hold on
+ end
+
+ % Add a field line
+ tarr = opt.tstart;
+
+
+ if ~isempty(tarr)
+ phi = 0;
+
+ nstep = 1024;
+ dstep = opt.phiend/1024;
+
+ for istep=1:nstep
+ phi(istep+1) = phi(istep) + dstep;
+
+ B = get_spec_magfield( data, Nvol, 1, tarr(:,istep), phi(istep) );
+
+ Bt = reshape(B{2}, length(B{2}), 1);
+ Bz = reshape(B{3}, length(B{2}), 1);
+
+ tarr(:,istep+1) = tarr(:,istep) + Bt./Bz * dstep;
+
+ end
+
+ nline = length(opt.tstart);
+ for jj=1:nline
+ X = [];
+ Y = [];
+ Z = [];
+ for ii = 1:nstep
+ Rd = get_spec_R_derivatives(data,Nvol,sarr,tarr(jj,ii),phi(ii),'R');
+ Zd = get_spec_R_derivatives(data,Nvol,sarr,tarr(jj,ii),phi(ii),'Z');
+
+ X(ii) = squeeze(Rd{1}) * cos(phi(ii));
+ Y(ii) = squeeze(Rd{1}) * sin(phi(ii));
+ Z(ii) = squeeze(Zd{1});
+ end
+
+ scatter3( X, Y, Z, 10, 'MarkerFaceColor', col.Leman, 'MarkerEdgeColor', col.Leman)
+ end
+ end
+
+
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/plot_spec_polflux.m b/Utilities/matlabtools/plot_spec_polflux.m
index 9b4f3824..26280b48 100644
--- a/Utilities/matlabtools/plot_spec_polflux.m
+++ b/Utilities/matlabtools/plot_spec_polflux.m
@@ -1,4 +1,4 @@
-function plot_spec_polflux(data, zeta, cumulative, newfig)
+function plot_spec_polflux(data, theta, cumulative, newfig)
%
%
% PLOT_SPEC_POLFLUX( FILENAME, ZETA, CUMULATIVE, NEWFIG )
@@ -10,7 +10,7 @@ function plot_spec_polflux(data, zeta, cumulative, newfig)
% INPUTS
% ------
% data: data obtained from read_spec(filename);
-% zeta: Toroidal angle
+% theta: Poloidal angle
% cumulative: True to get cumulative plot (\psi_a = \int_0^a B_\phi dS)
% or False to get a non-cumulative plot (\psi_a =
% \int_{a-1}^a B_\phi dS)
@@ -24,44 +24,45 @@ function plot_spec_polflux(data, zeta, cumulative, newfig)
%
%
-Nvol = data.input.physics.Nvol;
+ Nvol = data.input.physics.Nvol;
-polflux = zeros(1,Nvol);
+ polflux = zeros(1,Nvol);
-% Start at one only if slab geometry (otherwise it is zero by definition)
-if data.input.physics.Igeometry==1
- polflux(1) = get_spec_polflux(data,1,zeta,-1,1,64,64);
-end
+ % Start at one only if slab geometry (otherwise it is zero by definition)
+ sarr = linspace(-1, 1, 64);
+ if data.input.physics.Igeometry==1
+ polflux(1) = get_spec_polflux(data,1,theta,sarr,64);
+ end
+
+ for lvol=2:Nvol
+ tmp = get_spec_polflux(data,lvol,theta,sarr,64);
+
+ if cumulative
+ polflux(lvol) = polflux(lvol-1) + tmp;
+ else
+ polflux(lvol)=tmp;
+ end
-for lvol=2:Nvol
- tmp = get_spec_polflux(data,lvol,zeta,-1,1,64,64);
-
- if cumulative
- polflux(lvol) = polflux(lvol-1) + tmp;
- else
- polflux(lvol)=tmp;
end
-
-end
-switch newfig
- case 0
- hold on;
- case 1
- figure
- hold on;
- case 2
- hold off;
- otherwise
- error('Unsupported newfig value')
-end
+ switch newfig
+ case 0
+ hold on;
+ case 1
+ figure
+ hold on;
+ case 2
+ hold off;
+ otherwise
+ error('InputError: invalid newfig')
+ end
-bar(polflux)
-xlabel('Volume label')
-ylabel('Poloidal flux')
-set(gca, 'FontSize', 14)
-xticks(1:1:Nvol)
-grid on;
+ bar(polflux)
+ xlabel('Volume label')
+ ylabel('Poloidal flux')
+ set(gca, 'FontSize', 14)
+ xticks(1:1:Nvol)
+ grid on;
end
diff --git a/Utilities/matlabtools/plot_spec_pressure.m b/Utilities/matlabtools/plot_spec_pressure.m
index ce4f235f..0e3f9959 100644
--- a/Utilities/matlabtools/plot_spec_pressure.m
+++ b/Utilities/matlabtools/plot_spec_pressure.m
@@ -1,21 +1,47 @@
-function plot_spec_pressure(data, newfig)
+function plot_spec_pressure(data, norm, newfig, varargin)
%
-% PLOT_SPEC_PRESSURE( DATA, NEWFIG )
-% ==================================
+% PLOT_SPEC_PRESSURE( DATA, NORM, NEWFIG, VARARGIN )
+% ==================================================
%
% Plots stepped-pressure profile versus normalized toroidal flux used in SPEC
%
% INPUT
% -----
% -data : data obtained from read_spec(fname)
+% -norm : (0) plot p, (1) plot p / p0
% -newfig : open a new figue (=1), plots on an existing one (=0) or overwrite last plot (=2)
%
% written by J.Loizu (2018)
% modified by A. Baillod (2019)
+if ~any(norm==[0,1])
+ error('InputError: invalid norm')
+end
+
+l = length(varargin);
+if mod(l,2)~=0
+ error('InputError: invalid number of argument')
+end
+
+opt.Color='b';
+opt.LineWidth=2.0;
+for ii=1:l/2
+ value = varargin{2*ii};
+ field = varargin{2*ii-1};
+
+ opt.(field)=value;
+end
+
+
pvol = data.input.physics.pressure * data.input.physics.pscale;
+
+if norm
+ pvol = pvol / pvol(1);
+end
+
+
pmax = max(pvol);
pmin = min(pvol);
@@ -35,28 +61,30 @@ function plot_spec_pressure(data, newfig)
hold off
end
+% First volume
p0(1:end) = pvol(1);
tmin = 0;
tmax = tfl(1);
tarr = linspace(tmin,tmax,10);
-plot(tarr,p0,'b')
+plot(tarr,p0,'Color',opt.Color,'LineWidth',opt.LineWidth)
hold on
x = [tfl(1),tfl(1)];
if Nvol>1
y = [pvol(2) pvol(1)];
- plot(x,y,'b')
+ plot(x,y,'Color',opt.Color,'LineWidth',opt.LineWidth)
end
+% Next volumes
for i=2:Nvol-1
p0(1:end) = pvol(i);
tmin = tfl(i-1);
tmax = tfl(i);
tarr = linspace(tmin,tmax,10);
- plot(tarr,p0,'b')
+ plot(tarr,p0,'Color',opt.Color,'LineWidth',opt.LineWidth)
x = [tfl(i),tfl(i)];
y = [pvol(i+1) pvol(i)];
- plot(x,y,'b')
+ plot(x,y,'Color',opt.Color,'LineWidth',opt.LineWidth)
end
@@ -65,18 +93,25 @@ function plot_spec_pressure(data, newfig)
tmin = tfl(Nvol-1);
tmax = tfl(Nvol);
tarr = linspace(tmin,tmax,10);
- plot(tarr,p0,'b')
+ plot(tarr,p0,'Color',opt.Color,'LineWidth',opt.LineWidth)
x = [tfl(Nvol),tfl(Nvol)];
y = [0 pvol(Nvol)];
- plot(x,y,'b')
+ plot(x,y,'Color',opt.Color,'LineWidth',opt.LineWidth)
end
-ylabel('p')
-xlabel('\Psi / \Psi_{edge}')
+if( norm )
+ ylabel('$p / p_0$', 'Interpreter', 'latex')
+else
+ ylabel('$p$', 'Interpreter', 'latex')
+end
+xlabel('$\Psi / \Psi_{edge}$', 'Interpreter', 'latex')
if (pmin~=0 || pmax~=0)
- ylim([0.9*pmin, 1.1*pmax]);
+ ylim([0, 1.1*pmax]);
end
+set(gcf, 'Color', 'w')
+set(gcf,'Position',[200 200 900 700])
+set(gca,'FontSize',18)
diff --git a/Utilities/matlabtools/plot_spec_surface_current.m b/Utilities/matlabtools/plot_spec_surface_current.m
new file mode 100644
index 00000000..f364eb68
--- /dev/null
+++ b/Utilities/matlabtools/plot_spec_surface_current.m
@@ -0,0 +1,56 @@
+function plot_spec_surface_current(data, nt, newfig)
+
+%
+% PLOT_SPEC_SURFACE_CURRENT( DATA, NS, NT, NEWFIG )
+% ===================================================
+%
+% Plot pressure-driven currents located at each volume interface
+%
+% INPUT
+% -----
+% -data : data obtained via read_spec(filename)
+% -nt : number of poloidal interpolation points
+% -newfig : plots on an existing figure (=0), a new figure (=1) or
+% overwrites last figure (=2)
+%
+% written by A.Baillod (2019)
+%
+
+ % Test input
+ if nt<1
+ error('InputError: Invalid nt')
+ end
+
+
+ switch newfig
+ case 0
+ hold on
+ case 1
+ figure
+ hold on
+ case 2
+ hold off
+ otherwise
+ error('InputError: Invalid newfig')
+ end
+
+ % Evaluate toroidal current
+ Itor = get_spec_torcurr_kam_net(data, nt);
+ Mvol = data.output.Mvol;
+
+
+ %plot(tflux(1:end-1), IPDt, '*')
+ bar(Itor, 'BarWidth', 0.3);
+ grid on
+ %xl = xlabel('$\psi_t / \psi_{edge}$');
+ xl = xlabel('Surface label');
+ yl = ylabel('$\mu_0 I_\mathcal{S}$[A]');
+ xlim([0, Mvol])
+
+ set(xl, 'Interpreter', 'latex');
+ set(yl, 'Interpreter', 'latex');
+
+ set(gca, 'FontSize', 14)
+
+
+end
diff --git a/Utilities/matlabtools/plot_spec_surfcurent.m b/Utilities/matlabtools/plot_spec_surfcurent.m
deleted file mode 100644
index feb04142..00000000
--- a/Utilities/matlabtools/plot_spec_surfcurent.m
+++ /dev/null
@@ -1,49 +0,0 @@
-function plot_spec_surfcurent(data, ns, nt, zeta, newfig)
-
-%
-% PLOT_SPEC_SURFCURRENT( DATA, NS, NT, ZETA, NEWFIG )
-% ===================================================
-%
-% Plot pressure-driven currents located at each volume interface
-%
-% INPUT
-% -----
-% -data : data obtained via read_spec(filename)
-% -ns : number of radial interpolation points
-% -nt : number of poloidal interpolation points
-% -zeta : toroidal angle
-% -newfig : plots on an existing figure (=0), a new figure (=1) or
-% overwrites last figure (=2)
-%
-% written by A.Baillod (2019)
-%
-
-[tflux, IPDt] = get_spec_surface_current(data, ns, nt, zeta);
-
-Nvol = data.input.physics.Nvol + data.input.physics.Lfreebound;
-
-switch newfig
- case 0
- hold on
- case 1
- figure
- hold on
- case 2
- hold off
-end
-
-%plot(tflux(1:end-1), IPDt, '*')
-bar(IPDt, 'BarWidth', 0.3);
-grid on
-%xl = xlabel('$\psi_t / \psi_{edge}$');
-xl = xlabel('Surface label');
-yl = ylabel('$\mu_0 I_\mathcal{S}$[A]');
-xlim([0, Nvol])
-
-set(xl, 'Interpreter', 'latex');
-set(yl, 'Interpreter', 'latex');
-
-set(gca, 'FontSize', 14)
-
-
-end
diff --git a/Utilities/matlabtools/plot_spec_torflux.m b/Utilities/matlabtools/plot_spec_torflux.m
index bf15f342..c757f2a3 100644
--- a/Utilities/matlabtools/plot_spec_torflux.m
+++ b/Utilities/matlabtools/plot_spec_torflux.m
@@ -11,8 +11,8 @@ function plot_spec_torflux(data, zeta, cumulative, newfig)
% ------
% data: data obtained from read_spec(filename)
% zeta: Toroidal angle
-% cumulative: True to get cumulative plot (\psi_a = \int_0^a B_\phi dS)
-% or False to get a non-cumulative plot (\psi_a =
+% cumulative: true to get cumulative plot (\psi_a = \int_0^a B_\phi dS)
+% or false to get a non-cumulative plot (\psi_a =
% \int_{a-1}^a B_\phi dS)
% newfig: 0: plots on an existing figure without erasing previous
% plot
@@ -22,44 +22,46 @@ function plot_spec_torflux(data, zeta, cumulative, newfig)
%
% Written by A. Baillod (2019)
%
+ Mvol = data.output.Mvol;
+ torflux = zeros(1,Mvol);
+ for lvol=1:Mvol
+ start=-1;
+ if(lvol==1)
+ start=-0.999;
+ end
+ tmp = get_spec_torflux(data,lvol,zeta,start,1,64,64);
Nvol = data.input.physics.Nvol;
-
-torflux = zeros(1,Nvol);
-
-for lvol=1:Nvol
- tmp = get_spec_torflux(data,lvol,zeta,-1,1,64,64);
-
- if cumulative
- if lvol==1
- torflux(lvol)=tmp;
+ if cumulative
+ if lvol==1
+ torflux(lvol)=tmp;
+ else
+ torflux(lvol) = torflux(lvol-1) + tmp;
+ end
else
- torflux(lvol) = torflux(lvol-1) + tmp;
+ torflux(lvol)=tmp;
end
- else
- torflux(lvol)=tmp;
+
end
-
-end
-switch newfig
- case 0
- hold on;
- case 1
- figure
- hold on;
- case 2
- hold off;
- otherwise
- error('Unsupported newfig value')
-end
+ switch newfig
+ case 0
+ hold on;
+ case 1
+ figure
+ hold on;
+ case 2
+ hold off;
+ otherwise
+ error('InputError: Invalid newfig')
+ end
-bar(torflux)
-xlabel('Volume label')
-ylabel('Toroidal flux')
-set(gca, 'FontSize', 14)
-xticks(1:1:Nvol)
-grid on;
+ bar(torflux)
+ xlabel('Volume label')
+ ylabel('Toroidal flux')
+ set(gca, 'FontSize', 14)
+ xticks(1:1:Nvol)
+ grid on;
end
diff --git a/Utilities/matlabtools/plot_spec_wall.m b/Utilities/matlabtools/plot_spec_wall.m
index 6786af3b..7660cb16 100644
--- a/Utilities/matlabtools/plot_spec_wall.m
+++ b/Utilities/matlabtools/plot_spec_wall.m
@@ -4,7 +4,7 @@ function plot_spec_wall(data,zetaov2pi,newfig)
% PLOT_SPEC_WALL( DATA, ZETAOV2PI, NEWFIG )
% =========================================
%
-% Produces a "Poincare plot" of the computational boundary surface in toroidal geometry.
+% Plots the computational boundary surface in toroidal geometry.
%
% INPUT
% -----
@@ -14,53 +14,70 @@ function plot_spec_wall(data,zetaov2pi,newfig)
%
% written by J.Loizu (2018)
% modified by J.Loizu (2020)
+%
+ if data.input.physics.Igeometry~=3
+ error('InputError: only works in toroidal geometry')
+ end
-mn = data.output.mn;
-im = data.output.im;
-in = data.output.in;
-Rbcmn = data.output.Rbc;
-Rbsmn = data.output.Rbs;
-Zbcmn = data.output.Zbc;
-Zbsmn = data.output.Zbs;
+ if data.input.physics.Lfreebound==0
+ warning(['This will plot the plasma boundary, since no walls are' ...
+ 'defined in fixed-boundary equilibria'])
+ end
-Rwcmn = Rbcmn(:,end);
-Rwsmn = Rbsmn(:,end);
-Zwcmn = Zbcmn(:,end);
-Zwsmn = Zbsmn(:,end);
-% Compute (x,y) coordinates of the boundary surface
+ mn = data.output.mn;
+ im = data.output.im;
+ in = data.output.in;
+ Rbcmn = data.output.Rbc;
+ Rbsmn = data.output.Rbs;
+ Zbcmn = data.output.Zbc;
+ Zbsmn = data.output.Zbs;
-zeta = zetaov2pi*(2*pi);
+ Rwcmn = Rbcmn(:,end);
+ Rwsmn = Rbsmn(:,end);
+ Zwcmn = Zbcmn(:,end);
+ Zwsmn = Zbsmn(:,end);
-nth = 2048;
-dth = 2*pi/nth;
-theta = dth:dth:2*pi;
+ % Compute (x,y) coordinates of the boundary surface
-X = zeros(1,nth);
-Y = zeros(1,nth);
+ zeta = zetaov2pi*(2*pi);
-for k=1:mn
- alpha = double(im(k))*theta-double(in(k))*zeta;
- X = X + Rwcmn(k)*cos(alpha) + Rwsmn(k)*sin(alpha);
- Y = Y + Zwsmn(k)*sin(alpha) + Zwcmn(k)*cos(alpha);
-end
+ nth = 2048;
+ dth = 2*pi/nth;
+ theta = dth:dth:2*pi;
+ X = zeros(1,nth);
+ Y = zeros(1,nth);
+ for k=1:mn
+ alpha = double(im(k))*theta-double(in(k))*zeta;
+ X = X + Rwcmn(k)*cos(alpha) + Rwsmn(k)*sin(alpha);
+ Y = Y + Zwsmn(k)*sin(alpha) + Zwcmn(k)*cos(alpha);
+ end
-% Plot Poincare section
-if(newfig==1)
-figure
-end
-hold on
-scatter(X,Y,3,'filled', 'b')
+ % Plot Poincare section
-axis equal
-hold on
-set(gca,'FontSize',12)
-xlabel('R','FontSize',12)
-ylabel('Z','FontSize',12)
-%xlim([-1.1*rmax 1.1*rmax])
-%ylim([-1.1*zmax 1.1*zmax])
+ switch newfig
+ case 0
+ hold on
+ case 1
+ figure('Color','w','Position',[200 200 900 700])
+ case 2
+ hold off
+ otherwise
+ error('InputError: invalid newfig')
+ end
+
+ scatter(X,Y,3,'filled', 'b')
+
+ axis equal
+ hold on
+ set(gca,'FontSize',12)
+ xlabel('R','FontSize',12)
+ ylabel('Z','FontSize',12)
+ %xlim([-1.1*rmax 1.1*rmax])
+ %ylim([-1.1*zmax 1.1*zmax])
+end
diff --git a/Utilities/matlabtools/produce_spec_movie.m b/Utilities/matlabtools/produce_spec_movie.m
index 428edfd5..4433b424 100644
--- a/Utilities/matlabtools/produce_spec_movie.m
+++ b/Utilities/matlabtools/produce_spec_movie.m
@@ -25,6 +25,7 @@ function produce_spec_movie(inputroot,seqstart,seqstep,seqend,framerate,nfp,nz0,
% written by J.Loizu (2017)
% modified by J.Loizu (2019)
+error('DEPRECATED: this needs to be reviewed')
%
writerObj = VideoWriter('spec_movie.avi');
diff --git a/Utilities/matlabtools/read_boozer.m b/Utilities/matlabtools/read_boozer.m
new file mode 100644
index 00000000..7432cff3
--- /dev/null
+++ b/Utilities/matlabtools/read_boozer.m
@@ -0,0 +1,36 @@
+%% read_boozer( FILENAME, ROOT)
+% =============================
+%
+% Reads hdf5 output from Boozer_xForms
+% and produces data struct
+%
+% INPUT
+% -----
+% -filename : name of Boz output
+% -root : root directory
+%
+% ------------------------------------%
+% Written by S.Guinchard (05/22) %
+% from read_spec routine %
+% ------------------------------------%
+
+function g_data = read_boozer(filename, root )
+ g_data_info = h5info(filename, root);
+ ngroups = length(g_data_info.Groups);
+ nvars = length(g_data_info.Datasets);
+ % Get datasets in root node
+ for i = 1: nvars
+ g_data.([g_data_info.Datasets(i).Name]) = h5read(filename,[root '/' g_data_info.Datasets(i).Name]);
+ natts = length(g_data_info.Datasets(i).Attributes);
+ for j=1:natts
+ g_data.([g_data_info.Datasets(i).Attributes(j).Name]) = g_data_info.Datasets(i).Attributes(j).Value{1};
+ end
+ end
+ % get groups in root node
+ if ngroups > 0
+ for i = 1 : ngroups
+ g_path = strsplit(g_data_info.Groups(i).Name, '/');
+ g_data.([g_path{end}]) = read_boozer(filename, g_data_info.Groups(i).Name);
+ end
+ end
+end
diff --git a/Utilities/matlabtools/read_hdf5.m b/Utilities/matlabtools/read_hdf5.m
deleted file mode 100644
index 7390b05f..00000000
--- a/Utilities/matlabtools/read_hdf5.m
+++ /dev/null
@@ -1,81 +0,0 @@
-function data = read_hdf5(filename)
-
-%
-% OUTDATED ?
-%
-% READ_HDF5( FILENAME )
-% =====================
-%
-% The READ_HDF5 function reads an HDF5 file and returns the contents of
-% that file as the fields of a structure. Groups are treated as elements
-% of their parent structure. If the file file cannot be opened a -1 is
-% returned.
-%
-% Example
-% data=read_hdf5('input.h5');
-%
-% Version 1.0
-% Maintained by: Samuel Lazerson (lazerson@pppl.gov)
-% Date 05/02/2012
-
-
-% Try to read the file first
-try
- data_info = h5info(filename,'/');
-catch h5info_error
- data=-1;
- disp(['ERROR: Opening HDF5 File: ' filename]);
- disp([' -identifier: ' h5info_error.identifier]);
- disp([' -message: ' h5info_error.message]);
- disp(' For information type: help read_hdf5');
- return
-end
-
-ngroups = length(data_info.Groups);
-nvars = length(data_info.Datasets);
-% Get root datasets
-for i = 1: nvars
- data.([data_info.Datasets(i).Name]) = h5read(filename,['/' data_info.Datasets(i).Name]);
- natts = length(data_info.Datasets(i).Attributes);
- for j=1:natts
- data.([data_info.Datasets(i).Attributes(j).Name]) = data_info.Datasets(i).Attributes(j).Value{1};
- end
- % Fix by Weatherby,Gerard 10/17/13
- %for j=2:natts
- % data.([data_info.Datasets(i).Attributes(j).Name]) = data_info.Datasets(i).Attributes(j).Value{1};
- %end
- %if natts == 1
- % data.([data_info.Datasets(i).Attributes(1).Name]) = data_info.Datasets(i).Attributes(1);
- %end
-end
-
-% Get each subgroup
-if ngroups > 0
- for i = 1 : ngroups
- data.([data_info.Groups(i).Name]) = getGroup(['/' data_info.Groups(i).Name]);
- end
-end
-return
-end
-
-function data = getGroup(root)
-data_info = h5info(filename,root);
-ngroups = length(data_info.Groups);
-nvars = length(data_info.Datasets);
-% Get root datasets
-for i = 1: nvars
- data.([data_info.Datasets(i).Name]) = h5read(filename,[root data_info.Datasets(i).Name]);
- natts = length(data_info.Datasets(i).Attributes);
- for j=1:natts
- data.([data_info.Datasets(i).Attributes(j).Name]) = data_info.Datasets(i).Attributes(j).Value{1};
- end
-end
-
-% Get each subgroup
-if ngroups > 0
- for i = 1 : ngroups
- data.([data_info.Groups(i).Name]) = getGroup(['/' data_info.Groups(i).Name]);
- end
-end
-return
-end
diff --git a/Utilities/matlabtools/read_spec.m b/Utilities/matlabtools/read_spec.m
index e155d329..84192599 100644
--- a/Utilities/matlabtools/read_spec.m
+++ b/Utilities/matlabtools/read_spec.m
@@ -25,7 +25,6 @@
disp(['ERROR: Opening HDF5 File: ' filename]);
disp([' -identifier: ' h5info_error.identifier]);
disp([' -message: ' h5info_error.message]);
- disp(' For information type: help read_hdf5');
return
end
@@ -150,5 +149,6 @@
data.grid.Bp = cBp;
data.grid.BZ = cBZ;
+
end
diff --git a/Utilities/matlabtools/read_spec_hessian.m b/Utilities/matlabtools/read_spec_hessian.m
deleted file mode 100644
index 7a7d805b..00000000
--- a/Utilities/matlabtools/read_spec_hessian.m
+++ /dev/null
@@ -1,82 +0,0 @@
-function Hmatrix = read_spec_hessian(filename)
-
-%
-% READ_SPEC_HESSIAN( FILENAME )
-% =============================
-%
-% Reads Hessian matrix using output from SPEC
-%
-% INPUT
-% -----
-% - filename : path to the hdf5 output file (e.g. 'testcase.sp.h5')
-%
-% OUTPUT
-% ------
-% - Hmatrix : Hessian matrix, which can be fed into several routines for analyzing and ploting
-%
-% written by J.Loizu (2017)
-% updated by J.Loizu (2020)
-
-
-global machform;
-
-machform = 's';
-
-
-% Read the hessian file
-
-machine_format = machform; % needs to be 's' (intel) or 'a' (gnu); format is swapped if an error occurs
-triedallform = 0; % whether all formats have been tried (1) or not (0)
-success = 0;
-int_format = 'int32';
-float_format = 'float64';
-spacer_format = 'int32';
-
-
-while(success==0)
-try
-
- if(machine_format ~= machform)
- machine_format = machform; % update value
- end
- hessian_file = ['.' filename(1:length(filename)-6) '.GF.ma'];
- fid = fopen(hessian_file,'r',machine_format);
- if (fid > 0)
- % Read through NGdof
- fread(fid,1,spacer_format);
- ngdof = fread(fid,1,int_format); % NGdof
- fread(fid,1,spacer_format);
- else
- disp(' - File does not exist'); break;
- end
-
- fread(fid,1,spacer_format);
- Hmatrix = fread(fid,[ngdof ngdof],float_format);
- fread(fid,1,spacer_format);
-
- success=1;
-
-catch
-
- if(triedallform==1)
- disp(' - Could not read hessian file'); break;
- end
- if(machform~='s')
- machform ='s';
- triedallform = 1;
- else
- machform ='a';
- triedallform = 1;
- end
- if (fid ~= -1)
- fclose(fid);
- fid = -1;
- end
-end
-
-end
-
-if (fid ~= -1)
- fclose(fid);
-end
-
diff --git a/Utilities/matlabtools/run_spec_iter_fixtorcurr.m b/Utilities/matlabtools/run_spec_iter_fixtorcurr.m
deleted file mode 100644
index 94d61684..00000000
--- a/Utilities/matlabtools/run_spec_iter_fixtorcurr.m
+++ /dev/null
@@ -1,137 +0,0 @@
-function currents = run_spec_iter_fixtorcurr(execom,inputroot,Nvol,Lrad,nptr,startit,nit,Iref)
-
-
-% Runs SPEC iteratively to find nearby equilibria with mu=0 in each volume and net toroidal surface-current Iref (units mu0*I).
-% Target current is achieved by iterating on the enclosed poloidal flux.
-%
-% INPUT
-% - execom : command for the execution of SPEC executable (e.g. './xspec' or 'mpirun -n 2 ./xspec')
-% - inputroot : spec input file name of the form 'somename_iter', and 'somename_iter0.sp.end/.h5' must already exist.
-% - Nvol : number of volumes
-% - Lrad : radial resolution in each volume (one value)
-% - nptr : number of poincare trajectories traced in each volume
-% - startit : starting iteration number
-% - nit : number of iterations
-% - Iref : targeted net-toroidal-current (array of size Nvol-1)
-%
-% OUTPUT
-% - currents : array of net-toroidal-currents obtained on each interface at each interation step
-%
-% written by J.Loizu (2017)
-% upgraded by J.Loizu (2018)
-
-
-specexec = strcat(execom,{' '});
-
-specexec = specexec{1};
-
-currents = zeros(nit+1,Nvol-1);
-
-pfac = 1e-9; % factor for the amplitude of the perturbation in pflux for Jacobian evaluation (reference: 1e-6)
-
-ntheta = 128; % poloidal resolution for the loop integral evaluating the current
-
-mu = zeros(1,Nvol); % as of now zero volume-currents are imposed
-
-
-for i=1+startit:startit+nit
-
- display(' ');
- display(['START OF CURRENT ITERATION ' num2str(i)]);
- display(' ');
-
- %-------- Initial input and hdf5 files --------
-
- spec_input = strcat(inputroot,num2str(i-1),'.sp.end');
- spec_hdf5 = strcat(inputroot,num2str(i-1),'.sp.h5');
-
- tflux = h5read(spec_hdf5,'/tflux');
- pflux = h5read(spec_hdf5,'/pflux');
- pre = h5read(spec_hdf5,'/pressure');
- IKAMtor = get_spec_torcurr_kam_net(spec_hdf5,ntheta);
-
- currents(i-startit,1:Nvol-1) = IKAMtor;
-
- %-------- Evaluation of J=dI/dX ---------
-
- tfl = zeros(1,Nvol);
-
- pfl = zeros(1,Nvol);
-
- dX = zeros(1,Nvol);
-
- dIdX = zeros(Nvol-1,Nvol-1);
-
- dX = pflux*pfac;
-
- lrad = Lrad*ones(1,Nvol);
-
- template = spec_input;
-
-
- % jacobian evaluation runs
-
- for lvol=2:Nvol
-
- display(' ');
- display(['JACOBIAN EVALUATION...' num2str(lvol-1)]);
- display(' ');
-
- tfl = tflux;
-
- pfl = pflux;
-
- pfl(lvol) = pfl(lvol) + dX(lvol);
-
- newinput = strcat(inputroot,'jacobian',num2str(lvol),'.sp');
-
- write_spec_input_L0(template,newinput,Nvol,tfl,pfl,mu,pre,lrad,nptr);
-
- system(strcat([specexec newinput(1:end-3)]));
-
- spec_hdf5 = strcat(newinput(1:end-3),'.sp.h5');
-
- newIKAMtor = get_spec_torcurr_kam_net(spec_hdf5,ntheta);
-
- dIdX(:,lvol-1) = (newIKAMtor-IKAMtor)/dX(lvol);
-
- end
-
-
- %-------- Evaluation of dX steps from Newton method ---------
-
- Jinv = inv(dIdX);
- curr(1:Nvol-1) = IKAMtor;
- zfun(1:Nvol-1) = IKAMtor-Iref;
-
- dX(2:Nvol) = -Jinv*transpose(zfun);
-
- display(' ');
- display(['CALCULATED STEP: ' num2str(transpose(dX)) ]);
- display(' ');
-
- %-------- Final run with appropriate X+dXstep ---------
-
- tfl = tflux;
- pfl = pflux;
- pfl(2:Nvol) = pfl(2:Nvol) + dX(2:Nvol);
-
- newinput = strcat(inputroot,num2str(i),'.sp');
-
- write_spec_input_L0(template,newinput,Nvol,tfl,pfl,mu,pre,lrad,nptr);
-
- system(strcat([specexec newinput(1:end-3)]));
-
-
- %-------- Update .DF file from last output --------
-
- system(strcat(['cp ' '.' inputroot num2str(i) '.sp.DF' ' .sp.DF']));
-
-
-end
-
-spec_hdf5 = strcat(inputroot,num2str(startit+nit),'.sp.h5');
-IKAMtor = get_spec_torcurr_kam_net(spec_hdf5,ntheta);
-currents(nit+1,1:Nvol-1) = IKAMtor;
-
-
diff --git a/Utilities/matlabtools/scan_shear_auto_optim.m b/Utilities/matlabtools/scan_shear_auto_optim.m
new file mode 100644
index 00000000..65e03d9b
--- /dev/null
+++ b/Utilities/matlabtools/scan_shear_auto_optim.m
@@ -0,0 +1,253 @@
+%% SCRIPT SCANNING R10 and R11 FROM SPEC AND EXTRACTING MAGNETIC SHEAR %%
+%-----------------------------------------%
+% Created by Salomon Guinchard (04/26/22) %
+% Last modified (10/10/22) %
+%-----------------------------------------%
+
+%% Paths to get_spec_mat_iota_torsion and other SPEC analysis routines (change path according to output folder)
+addpath(genpath('/path_to_OutputSPEC'))
+addpath(genpath('/path_to_/OutputBOZ'))
+fs=18; lw=1.5; % Fontsize, linewidth
+
+
+%% PARAMETERS %%
+nscan = 20;
+f = strings(nscan,nscan);
+nn = length(f(:,1));
+parfor i=1:nn
+ for j=1:nn
+ f(i,j) = ['File', num2str(i), '_', num2str(j) '.sp.h5'];
+ end
+end
+filenames = reshape(f,1,nn^2);
+ll = length(filenames);
+d0 = read_spec(char(filenames(1)));
+
+l = d0.transform.fiota(:,2);
+avg_shear = zeros(1,ll) ;
+shift = 5;
+
+disp 'Done initialising...'
+%% DISCRETISATION OF SPACE %%
+scan__11 = linspace(-0.7,0.7,nscan); % values between which the mode 11 will be scanned
+scan__10 = linspace(-3,3,nscan); % same for 10 mode (01 - see SPEC input format)
+
+%% RUN %%
+tic % set timer on
+parfor ii=1:ll
+ try
+ d = read_spec(char(filenames(ii)));
+ phi = 0;
+
+ Nfp = double(d.input.physics.Nfp); % Number of field periods
+ Ntor = double(d.input.physics.Ntor); % Number of toroidal planes
+ Nppts = d.input.diagnostics.nPpts; % # points Poincare plots
+
+ R0n = double(d.output.Rbc(1:Ntor+1,1));
+ Z0n = double(d.output.Zbs(1:Ntor+1,1));
+
+ % Define coordinate axis position
+ Raxis = double(0);
+ Zaxis = double(0);
+ for i=0:Ntor
+ Raxis = Raxis + R0n(i+1) * cos(i * phi);
+ Zaxis = Zaxis + Z0n(i+1) * sin(i * phi);
+ end
+
+ Pos_Axis = [Raxis Zaxis];
+
+ tt = length(d.poincare.R(:,1,1));
+ jj=1;
+ X = reshape(d.poincare.R(jj,1,:),[1 ,Nppts]);
+ Y = reshape(d.poincare.Z(jj,1,:),[1 ,Nppts]);
+ Xbar = mean(X);
+ Ybar = mean(Y);
+ theta = atan2(Y-Ybar , X-Xbar);
+ theta = mod(theta, 2*pi);
+
+ [theta, ind] = sort(theta);
+
+ X = X(ind);
+ Y = Y(ind);
+ p = polyshape(X,Y);
+ %clc
+ is = isinterior(p,Pos_Axis);
+
+ while is == 0
+ jj = jj+1;
+
+ X = reshape(d.poincare.R(jj,1,:),[1 ,Nppts]);
+ Y = reshape(d.poincare.Z(jj,1,:),[1 ,Nppts]);
+
+ Xbar = mean(X);
+ Ybar = mean(Y);
+ theta = atan2(Y-Ybar , X-Xbar);
+ theta = mod(theta, 2*pi);
+
+ [theta, ind] = sort(theta);
+
+ X = X(ind);
+ Y = Y(ind);
+ p = polyshape(X,Y);
+ %clc
+ is = isinterior(p,Pos_Axis);
+
+ end
+ n_surf = jj;
+ n = length(l) - (n_surf+shift-1);
+
+ mat_iota = zeros(1,n);
+ mat_r_coord = zeros(1,n);
+ mat_s_coord = zeros(1,n);
+ derivatives = zeros(1,n);
+ shear = zeros(1,n);
+ coeff = zeros(1,n);
+
+ out = extract_shear(d,n,shift, n_surf);
+ mat_iota = out.mat_iota;
+ mat_r_coord = out.mat_r_coord;
+ mat_s_coord = out.mat_s_coord;
+ scan_11(ii) = out.scan_11;
+ scan_10(ii) = out.scan_10;
+ derivatives = out.derivatives;
+ avg_shear(ii) = out.avg_shear;
+ catch
+ warning('Problem extracting shear. Assigning a value of -1 to d and all parameters to NaN');
+ d = -1;
+ n = 1;
+ mat_iota = NaN(1,n);
+ mat_r_coord = NaN(1,n);
+ mat_s_coord = NaN(1,n);
+ scan_11(ii) = NaN;
+ scan_10(ii) = NaN;
+ derivatives = NaN(1,n);
+ avg_shear(ii) = NaN;
+ end
+
+end
+
+disp 'Done running...'
+toc % set timer off
+%% Plot last polyshape and coordinate axis %%
+ figure('color','w')
+ pg=plot(p);
+ pg.FaceColor = ([1 1 1]);
+ pg.EdgeColor = ([1 0 0]);
+ pg.LineWidth = 3;
+ hold on
+ plot(Pos_Axis(1), Pos_Axis(2), 'k+', 'linewidth' , 3, 'MarkerSize',8)
+ set (gca, 'fontsize', 16)
+ xlabel('R', 'interpreter', 'latex', 'FontSize', 24)
+ ylabel('Z', 'interpreter', 'latex','FontSize', 24)
+
+%% Shear %%
+
+shear_mat = reshape(avg_shear,[nn,nn])';
+r10_tilde = reshape(scan_10, [nn,nn]);
+r11_tilde = reshape(scan_11, [nn,nn]);
+parfor i=1:nn
+ r11(i) = r11_tilde(1,i);
+ r10(i) = r10_tilde(i,1);
+
+ for j=1:nn
+ S(i,j) = shear_mat(i,j);
+ end
+end
+[R10,R11] = meshgrid(r10,r11);
+
+
+%% PCOLOR SHEAR %%
+figure
+pcolor(R11,R10,S)
+shading interp
+hold on
+contour(R11,R10,S,[0,0], 'r', 'LineWidth', 3)
+set (gca, 'fontsize', fs)
+colorbar
+xlabel('$R_{11}$', 'interpreter', 'latex')
+ylabel('$R_{10}$', 'interpreter', 'latex')
+
+
+%% PLOT PROFIL IOTA ACROSS ZERO SHEAR LEVEL CURVE %%
+
+filename_1 = ['File1', num2str(index_R10_1), '_' num2str(index_R11) '.sp.h5'];
+filename_2 = ['File2', num2str(index_R10_2), '_' num2str(index_R11) '.sp.h5'];
+
+shift = 8; % shift in extract shear function. Has to be determined from iota profile
+
+d_bel = read_spec(filename_1);
+d_abov = read_spec(filename_2);
+
+coord_1 = d_bel.transform.fiota(shift:end,1);
+coord_2 = d_abov.transform.fiota(shift:end,1);
+
+iota_1 = d_bel.transform.fiota(shift:end,2);
+iota_2 = d_abov.transform.fiota(shift:end,2);
+
+figure
+plot(coord_1,iota_1,'b+', 'linewidth', 2, 'MarkerSize', 7)
+grid on
+hold on
+plot(coord_2,iota_2,'r+', 'linewidth', 2, 'MarkerSize', 7)
+set(gca, 'fontsize', 17)
+xlabel('$r$', 'Interpreter','latex', 'FontSize',30)
+ylabel('$\iota$', 'Interpreter','latex', 'FontSize',30)
+legend('$\iota_{a}$', '$\iota_{b}$', 'Interpreter', 'latex', 'FontSize', 27)
+
+
+%% PCOLOR & SURF MULTIPLOT %%
+
+figure
+subplot(1,2,1)
+%----------------------------------------------------------
+pcolor(R11,R10, S)
+title('Shear($R_{11},R_{10}$)', 'interpreter', 'latex')
+shading interp
+hold on
+contour(R11,R10,S,[0,0], 'r', 'LineWidth', 3)
+hold on
+plot(scan11_trunc, scan10_trunc, 'w--', 'linewidth', 1);
+hold on
+plot(scan11_trunc2, scan10_trunc2, 'w--', 'linewidth', 1);
+set (gca, 'fontsize', fs)
+colorbar
+xlabel('$R_{11}$', 'interpreter', 'latex')
+ylabel('$R_{10}$', 'interpreter', 'latex')
+
+subplot(1,2,2)
+%---------------------------------------------------------
+surf(R11,R10,S)
+shading interp
+hold on
+contour(R11,R10,S,[0,0], 'r', 'LineWidth', 3)
+set (gca, 'fontsize', fs)
+colorbar
+xlabel('$R_{11}$', 'interpreter', 'latex')
+ylabel('$R_{10}$', 'interpreter', 'latex')
+
+clc
+
+
+%% Extract %%
+function out = extract_shear(d, n, shift, n_surf) % can be found in extract_shear.m file too
+
+ id = n_surf+shift;
+ radial_coord = (d.transform.fiota(:,1)); % extract radial coordinate
+ out.mat_iota = d.transform.fiota(id:end,2); % extract iota
+ out.mat_r_coord = radial_coord(id:end); % truncates the radial coordinates (remove 5 first terms)
+ out.mat_s_coord = ((out.mat_r_coord + 1)./2); % change of variable r <--> s
+ out.scan_11 = d.output.Rbc(11,2); % Value of R11
+ out.scan_10 = d.output.Rbc(2,2); % Value of R10
+
+ % CENTERED FINITE DIFFERENCES
+ out.derivatives(1) = (out.mat_iota(2) - out.mat_iota(1)) / (out.mat_s_coord(2) - out.mat_s_coord(1));
+ out.derivatives(n) = (out.mat_iota(n) - out.mat_iota(n-1)) / (out.mat_s_coord(n) - out.mat_s_coord(n-1));
+
+ for j=2:n-1
+ out.derivatives(j) = (out.mat_iota(j+1) - out.mat_iota(j-1)) / (out.mat_s_coord(j+1) - out.mat_s_coord(j-1));
+ end
+
+ out.coeff = out.mat_s_coord ./ (out.mat_iota) ;
+ out.shear = (out.coeff)' .* out.derivatives;
+ out.avg_shear = mean(out.shear); % Avg shear
+end
\ No newline at end of file
diff --git a/Utilities/matlabtools/write_spec_input_L0.m b/Utilities/matlabtools/write_spec_input_L0.m
deleted file mode 100644
index bacc7797..00000000
--- a/Utilities/matlabtools/write_spec_input_L0.m
+++ /dev/null
@@ -1,113 +0,0 @@
-function write_spec_input_L0(template,inputname,Nvol,phiedge,tfl,pfl,mu,pre,lrad,nptr)
-
-%
-% WRITE_SPEC_INPUT_L0( TEMPLATE, INPUTNAME, NVOL, PHIEDGE, TFL, PFL, MU, PRE, LRAD, NPTR )
-% ========================================================================================
-%
-% Writes spec input file from template with constraints corresponding to Lconstraint=0 (tfl,pfl,mu)
-%
-% INPUT
-% -----
-% -template : template input file name with .sp format
-% -inputname : new input file name with .sp format
-% -Nvol : number of volumes
-% -tfl : toroidal flux enclosed by each interface
-% -pfl : poloidal flux enclosed by each interface
-% -mu : beltrami parameter in each volume
-% -pre : pressure in each volume
-% -lrad : radial resolution in each volume
-% -nptr : number of Poincare trajectories in each volume
-%
-% written by J.Loizu (2016)
-
-nlmod = 8;
-
-sref{1} = ' pressure =';
-sref{2} = ' tflux =';
-sref{3} = ' pflux =';
-sref{4} = ' mu =';
-sref{5} = ' Lrad =';
-sref{6} = ' nPtrj =';
-sref{7} = ' phiedge =';
-sref{8} = ' Nvol =';
-
-snew1 = sref{1};
-snew2 = sref{2};
-snew3 = sref{3};
-snew4 = sref{4};
-snew5 = sref{5};
-snew6 = sref{6};
-snew7 = strcat(sref{7},{' '}, num2str(phiedge));
-snew8 = strcat(sref{8}, {' '}, num2str(Nvol));
-
-for i=1:Nvol
- snew1 = strcat(snew1,{' '},num2str(pre(i),16), {' '});
- snew2 = strcat(snew2,{' '},num2str(tfl(i),16), {' '});
- snew3 = strcat(snew3,{' '},num2str(pfl(i),16), {' '});
- snew4 = strcat(snew4,{' '},num2str(mu(i),16), {' '});
- snew5 = strcat(snew5,{' '},num2str(lrad(i),16),{' '});
- snew6 = strcat(snew6,{' '},num2str(nptr(i),16),{' '});
-end
-
-snew{1} = snew1{1};
-snew{2} = snew2{1};
-snew{3} = snew3{1};
-snew{4} = snew4{1};
-snew{5} = snew5{1};
-snew{6} = snew6{1};
-snew{7} = snew7{1};
-snew{8} = snew8{1};
-
-% Open template file for reading
-
-fid = fopen(template,'rt');
-
-tline = fgetl(fid);
-
-count = 1;
-
-lnum = zeros(1,nlmod);
-
-A{1} = tline;
-
-
-% Read template file, copy lines in A, and identify reference lines
-
-while ischar(tline)
- for i=1:nlmod
- if(size(tline)>=size(sref{i}))
- if(strcmp(tline(1:length(sref{i})),sref{i})==1)
- lnum(i) = count;
- end
- end
- end
- tline = fgetl(fid);
- count = count + 1;
- A{count} = tline;
-end
-
-fclose(fid);
-
-
-% Modify cell A at reference lines
-
-for i=1:nlmod
- A{lnum(i)} = sprintf('%s',snew{i});
-end
-
-% Write cell A into new input file
-
-fid = fopen(inputname, 'w');
-
-for i = 1:numel(A)
- if(A{i+1} == -1)
- fprintf(fid,'%s', A{i});
- break
- else
- fprintf(fid,'%s\n', A{i});
- end
-end
-
-fclose(fid);
-
-
diff --git a/Utilities/matlabtools/write_spec_input_L1.m b/Utilities/matlabtools/write_spec_input_L1.m
deleted file mode 100644
index c4d6fa71..00000000
--- a/Utilities/matlabtools/write_spec_input_L1.m
+++ /dev/null
@@ -1,125 +0,0 @@
-function write_spec_input_L1(template, inputname, Nvol, tfl, pfl, iota, oita, phit_edge, pre, mu, lrad, nptr)
-
-%
-% WRITE_SPEC_INPUT_L1( TEMPLATE, INPUTNAME, NVOL, TFL, PFL, IOTA, OITA, PHIT_EDGE, PRE, MU, LRAD, NPTR )
-% ======================================================================================================
-%
-% Writes spec input file from template with constraints corresponding to
-% Lconstraint=1 (tfl,iota,oita)
-%
-% INPUT
-% -----
-% -template : template input file name with .sp format
-% -inputname : new input file name with .sp format
-% -Nvol : number of volumes
-% -tfl : toroidal flux enclosed by each interface
-% -pfl : poloidal flux enclosed by each interface
-% -iota : rotational transform on the inner side of the interface
-% -oita : rotational transform on the outer side of the interface
-% -phit_edge : total toroidal flux
-% -pre : pressure in each volume
-% -mu : Lagrange multiplier in each volume
-% -lrad : radial resolution in each volume
-% -nptr : number of Poincare trajectories in each volume
-%
-% written by A.Baillod (2019)
-
-nlmod = 10;
-
-sref{1} = ' pressure =';
-sref{2} = ' tflux =';
-sref{3} = ' iota =';
-sref{4} = ' oita =';
-sref{5} = ' Lrad =';
-sref{6} = ' nPtrj =';
-sref{7} = ' Nvol =';
-sref{8} = ' pflux =';
-sref{9} = ' mu =';
-sref{10} = ' phiedge =';
-
-snew1 = sref{1};
-snew2 = sref{2};
-snew3 = strcat(sref{3}, {' '}, num2str(iota(1), 16), {' '});
-snew4 = strcat(sref{4}, {' '}, num2str(oita(1), 16), {' '});
-snew5 = sref{5};
-snew6 = sref{6};
-snew7 = strcat(sref{7},{' '},num2str(Nvol), {' '});
-snew8 = sref{8};
-snew9 = sref{9};
-snew10 = strcat(sref{10}, {' '}, num2str(phit_edge), {' '});
-
-for i=1:Nvol
- snew1 = strcat(snew1, {' '},num2str(pre(i) ,16), {' '});
- snew2 = strcat(snew2, {' '},num2str(tfl(i) ,16), {' '});
- snew3 = strcat(snew3, {' '},num2str(iota(i),16), {' '});
- snew4 = strcat(snew4, {' '},num2str(oita(i),16), {' '});
- snew5 = strcat(snew5, {' '},num2str(lrad(i),16), {' '});
- snew6 = strcat(snew6, {' '},num2str(nptr(i),16), {' '});
- snew8 = strcat(snew8, {' '},num2str(pfl(i) ,16), {' '});
- snew9 = strcat(snew9, {' '},num2str(mu(i) ,16), {' '});
-end
-
-snew{1} = snew1{1};
-snew{2} = snew2{1};
-snew{3} = snew3{1};
-snew{4} = snew4{1};
-snew{5} = snew5{1};
-snew{6} = snew6{1};
-snew{7} = snew7{1};
-snew{8} = snew8{1};
-snew{9} = snew9{1};
-snew{10} = snew10{1};
-
-
-
-% Open template file for reading
-
-fid = fopen(template,'rt');
-
-tline = fgetl(fid);
-
-count = 1;
-
-lnum = zeros(1,nlmod);
-
-A{1} = tline;
-
-
-% Read template file, copy lines in A, and identify reference lines
-
-while ischar(tline)
- for i=1:nlmod
- if(size(tline)>=size(sref{i}))
- if(strcmp(tline(1:length(sref{i})),sref{i})==1)
- lnum(i) = count;
- end
- end
- end
- tline = fgetl(fid);
- count = count + 1;
- A{count} = tline;
-end
-
-fclose(fid);
-
-
-% Modify cell A at reference lines
-
-for i=1:nlmod
- A{lnum(i)} = sprintf('%s',snew{i});
-end
-
-% Write cell A into new input file
-
-fid = fopen(inputname, 'w');
-
-for i = 1:numel(A)
- if(A{i+1} == -1)
- fprintf(fid,'%s', A{i});
- break
- else
- fprintf(fid,'%s\n', A{i});
- end
-end
-
-fclose(fid);
diff --git a/Utilities/matlabtools/write_spec_input_L3.m b/Utilities/matlabtools/write_spec_input_L3.m
deleted file mode 100644
index 7a214914..00000000
--- a/Utilities/matlabtools/write_spec_input_L3.m
+++ /dev/null
@@ -1,131 +0,0 @@
-function write_spec_input_L3(template, inputname, Nvol, Lfreebound, tfl, phit_edge, ...
- pflux, Ivol, Isurf, curtor, pressure, lrad, nptr, Linitialize)
-
-%
-% WRITE_SPEC_INPUT_L3( TEMPLATE, INPUTNAME, NVOL, LFREEBOUND, TFL, PHIT_EDGE, ... )
-% =================================================================================
-%
-% Writes spec input file from template with constraints corresponding to
-% Lconstraint=1 (tfl,iota,oita)
-%
-% INPUT
-% -----
-% -template : template input file name with .sp format
-% -inputname : new input file name with .sp format
-% -Nvol : number of volume
-% -Lfreebound : Flag for free boundary
-% -tfl : toroidal flux enclosed by each interface
-% -phit_edge : total toroidal flux
-% -pflux : Poloidal flux (used as guess)
-% -Ivol : volume current in each volume
-% -Isurf : surface current at each interface
-% -curtor : Total plasma current. only relevant if Lfreebound=1
-% -pressure : pressure in each volume
-% -lrad : radial resolution in each volume
-% -nptr : number of Poincare trajectories in each volume
-% -Linitialize: How to initialize interfaces
-%
-% written by A.Baillod (2019)
-
-Mvol = Nvol+Lfreebound;
-
-nlmod = 11;
-
-sref{1} = ' pressure =';
-sref{2} = ' tflux =';
-sref{3} = ' Lrad =';
-sref{4} = ' nPtrj =';
-sref{5} = ' Nvol =';
-sref{6} = ' phiedge =';
-sref{7} = ' Ivolume =';
-sref{8} = ' Isurf =';
-sref{9} = ' curtor =';
-sref{10} = ' pflux =';
-sref{11} = ' Linitialize =';
-
-snew1 = sref{1};
-snew2 = sref{2};
-snew3 = sref{3};
-snew4 = sref{4};
-snew5 = strcat(sref{5}, {' '}, num2str(Nvol) , {' '});
-snew6 = strcat(sref{6}, {' '}, num2str(phit_edge), {' '});
-snew7 = sref{7};
-snew8 = sref{8};
-snew9 = strcat(sref{9}, {' '}, num2str(curtor), {' '});
-snew10 = sref{10};
-snew11 = strcat(sref{11}, {' '}, num2str(Linitialize), {' '});
-
-for i=1:Mvol
- snew1 = strcat(snew1, {' '},num2str(pressure(i) ,16), {' '});
- snew2 = strcat(snew2, {' '},num2str(tfl(i) ,16), {' '});
- snew3 = strcat(snew3, {' '},num2str(lrad(i) ,16), {' '});
- snew4 = strcat(snew4, {' '},num2str(nptr(i) ,16), {' '});
- snew7 = strcat(snew7, {' '},num2str(Ivol(i) ,16), {' '});
- snew8 = strcat(snew8, {' '},num2str(Isurf(i) ,16), {' '});
- snew10 = strcat(snew10, {' '},num2str(pflux(i) ,16), {' '});
-end
-
-snew{1} = snew1{1};
-snew{2} = snew2{1};
-snew{3} = snew3{1};
-snew{4} = snew4{1};
-snew{5} = snew5{1};
-snew{6} = snew6{1};
-snew{7} = snew7{1};
-snew{8} = snew8{1};
-snew{9} = snew9{1};
-snew{10} = snew10{1};
-snew{11} = snew11{1};
-
-
-% Open template file for reading
-
-fid = fopen(template,'rt');
-
-tline = fgetl(fid);
-
-count = 1;
-
-lnum = zeros(1,nlmod);
-
-A{1} = tline;
-
-
-% Read template file, copy lines in A, and identify reference lines
-
-while ischar(tline)
- for i=1:nlmod
- if(size(tline)>=size(sref{i}))
- if(strcmp(tline(1:length(sref{i})),sref{i})==1)
- lnum(i) = count;
- end
- end
- end
- tline = fgetl(fid);
- count = count + 1;
- A{count} = tline;
-end
-
-fclose(fid);
-
-
-% Modify cell A at reference lines
-
-for i=1:nlmod
- A{lnum(i)} = sprintf('%s',snew{i});
-end
-
-% Write cell A into new input file
-
-fid = fopen(inputname, 'w');
-
-for i = 1:numel(A)
- if(A{i+1} == -1)
- fprintf(fid,'%s', A{i});
- break
- else
- fprintf(fid,'%s\n', A{i});
- end
-end
-
-fclose(fid);
diff --git a/Utilities/matlabtools/write_spec_rzgrid.m b/Utilities/matlabtools/write_spec_rzgrid.m
index 61f9cf5f..c4f95849 100644
--- a/Utilities/matlabtools/write_spec_rzgrid.m
+++ b/Utilities/matlabtools/write_spec_rzgrid.m
@@ -5,7 +5,8 @@ function write_spec_rzgrid(data, nz0,lvol,outfname)
% WRITE_SPEC_RZGRID( DATA, NZ0, LVOL, OUTFNAME )
% ==============================================
%
-% Writes text file with grid coordinate data points R,Z on a given volume, on a toroidal plane, as two columns
+% Writes text file with grid coordinate data points R,Z on a given volume,
+% on a toroidal plane, as two columns
%
% INPUT
% -----
diff --git a/Utilities/pythontools/py_spec/__init__.py b/Utilities/pythontools/py_spec/__init__.py
index 260f4170..412e22fa 100644
--- a/Utilities/pythontools/py_spec/__init__.py
+++ b/Utilities/pythontools/py_spec/__init__.py
@@ -1,6 +1,13 @@
-# import of all SPEC-related python scripts.
-__version__ = "3.1.0"
+try:
+ from importlib import metadata
+except ImportError:
+ # Running on pre-3.8 Python; use importlib-metadata package
+ import importlib_metadata as metadata
+
+__version__ = metadata.version(__package__ or __name__)
from .ci import test
from .input.spec_namelist import SPECNamelist
from .output.spec import SPECout
+from .math.spec_fft import spec_fft
+from .math.spec_invfft import spec_invfft
diff --git a/Utilities/pythontools/py_spec/input/spec_namelist.py b/Utilities/pythontools/py_spec/input/spec_namelist.py
index 9b843796..d40605e0 100644
--- a/Utilities/pythontools/py_spec/input/spec_namelist.py
+++ b/Utilities/pythontools/py_spec/input/spec_namelist.py
@@ -10,7 +10,7 @@
from f90nml import Namelist
import numpy as np
-
+import matplotlib.pyplot as plt
class SPECNamelist(Namelist):
"""The SPEC namelist class
@@ -428,14 +428,32 @@ def get_interface_guess(self, m, n, ivol, key="Rbc"):
return self.interface_guess[(m, n)][key][ivol]
- def set_interface_guess(self, value, m, n, ivol, key="Rbc"):
+ def set_vacuum_field( self, value, m, n, mykey='Bns'):
+ """Set the guess of the coils field harmonics
+ parameters:
+ value -- the value that one wants to set
+ m,n -- the m and n number of the guess, must be within the allowed Mpol and Ntor range
+ the n number is the one without multiplying by Nfp
+ mykey -- which guess, can be 'Bnc' or 'Bns'
+ """
+ if m > self._Mpol or m < 0:
+ raise ValueError("0 <= m <= Mpol")
+ if n > self._Ntor or n < -self._Ntor:
+ raise ValueError("-Ntor <= n <= Ntor")
+ if mykey not in ['Bns', 'Bnc']:
+ raise ValueError("mykey must be in ['Bns', 'Bnc']")
+
+ self['physicslist'][mykey][m][n+self._Ntor] = value
+
+
+ def set_interface_guess(self, value, m, n, ivol, mykey="Rbc"):
"""Set the guess of the interface Fourier harmonic
parameters:
value -- the value that one wants to set
m,n -- the m and n number of the guess, must be within the allowed Mpol and Ntor range
the n number is the one without multiplying by Nfp
ivol -- which volume, Python convention, starting from 0
- key -- which guess, can be 'Rbc', 'Zbs', 'Rbs', 'Zbc'
+ mykey -- which guess, can be 'Rbc', 'Zbs', 'Rbs', 'Zbc'
"""
if ivol >= self._Nvol or ivol < 0:
raise ValueError("ivol must be between 0 and Nvol-1")
@@ -443,8 +461,8 @@ def set_interface_guess(self, value, m, n, ivol, key="Rbc"):
raise ValueError("0 <= m <= Mpol")
if n > self._Ntor or n < -self._Ntor:
raise ValueError("-Ntor <= n <= Ntor")
- if key not in ["Rbc", "Rbs", "Zbc", "Zbs"]:
- raise ValueError("key must be in ['Rbc', 'Rbs', 'Zbc', 'Zbs']")
+ if mykey not in ["Rbc", "Rbs", "Zbc", "Zbs"]:
+ raise ValueError("mykey must be in ['Rbc', 'Rbs', 'Zbc', 'Zbs']")
if (m, n) not in self.interface_guess.keys():
# add a new item
@@ -452,7 +470,88 @@ def set_interface_guess(self, value, m, n, ivol, key="Rbc"):
for key in ["Rbc", "Rbs", "Zbc", "Zbs"]:
self.interface_guess[(m, n)][key] = np.zeros([self._Nvol])
- self.interface_guess[(m, n)][key][ivol] = value
+ self.interface_guess[(m, n)][mykey][ivol] = value
+
+ def set_plasma_boundary(self, value, m, n, key='Rbc'):
+ """Set the value of the plasma boundary
+
+ parameters:
+ value -- the new value
+ m,n -- poloidal and toroidal mode number. Has to be within the allowed Mpol and Ntor Fourier resolution
+ n is has to be a multiple of Nfp
+ key -- any of 'Rbc', 'Rbs', 'Zbc', 'Zbs'.
+ """
+
+ if m > self._Mpol or m < 0:
+ raise ValueError("0 <= m <= Mpol")
+ if n > self._Ntor or n < -self._Ntor:
+ raise ValueError("-Ntor <= n <= Ntor")
+ if key not in ["Rbc", "Rbs", "Zbc", "Zbs"]:
+ raise ValueError("key must be in ['Rbc', 'Rbs', 'Zbc', 'Zbs']")
+
+ if type(m)!=int: m=int(m)
+ if type(n)!=int: n=int(n)
+ if type(value)!=float: value = float(value)
+
+ self['physicslist'][key][m][n+self._Ntor] = value
+
+
+ def get_plasma_boundary(self, m, n, key="Rbc"):
+ """Get the guess of the interface Fourier harmonic
+ parameters:
+ m,n -- the m and n number of the guess, must be within the allowed Mpol and Ntor range
+ the n number is the one without multiplying by Nfp
+ ivol -- which volume, Python convention, starting from 0
+ key -- which item, can be 'Rbc', 'Zbs', 'Rbs', 'Zbc'
+ Returns:
+ guess -- the initial guess of the interface harmonic used in SPEC
+ """
+ if key not in ["Rbc", "Rbs", "Zbc", "Zbs"]:
+ raise ValueError("key must be in ['Rbc', 'Rbs', 'Zbc', 'Zbs']")
+
+ ll = self['physicslist'][key]
+
+ if m>=len(ll):
+ return 0
+ else:
+ nl = len(ll[m])
+ ntor = int((nl-1)/2)
+ if abs(n)>ntor:
+ return 0
+ else:
+ return ll[m][n+ntor]
+
+ def set_plasma_boundary(self, value, m, n, key="Rbc"):
+ """Set the guess of the interface Fourier harmonic
+ parameters:
+ value -- the value that one wants to set
+ m,n -- the m and n number of the guess, must be within the allowed Mpol and Ntor range
+ the n number is the one without multiplying by Nfp
+ ivol -- which volume, Python convention, starting from 0
+ key -- which guess, can be 'Rbc', 'Zbs', 'Rbs', 'Zbc'
+ """
+ if key not in ["Rbc", "Rbs", "Zbc", "Zbs"]:
+ raise ValueError("key must be in ['Rbc', 'Rbs', 'Zbc', 'Zbs']")
+
+ ll = self['physicslist'][key]
+
+ if m>=len(ll):
+ for m in range(len(ll), m+1):
+ self['physicslist'][key].append([0]*(2*self._Ntor+1))
+ else:
+ nl = len(ll[m])
+ ntor = int((nl-1)/2)
+ if abs(n)>ntor:
+ for n in range(ntor+1, abs(n)+1):
+ self['physicslist'][key][m].append(0)
+ self['physicslist'][key][m].insert(0, 0)
+
+ # Change indexing
+ self['physicslist'].start_index[key][0] = -abs(n)
+
+ nl = len(self['physicslist'][key][m])
+ ntor = int((nl-1)/2)
+ self['physicslist'][key][m][n+ntor] = value
def remove_interface_guess(self, m, n):
"""Remove the guess of the interface Fourier harmonic with some m,n
@@ -465,6 +564,57 @@ def remove_interface_guess(self, m, n):
raise ValueError("unknown m or n")
else:
del self.interface_guess[(m, n)]
+ def plot_initial_guess(self, phi=0, nt=1024, **kwargs):
+ """
+ Plot the guess for the inner interfaces on a toroidal plane
+
+ parameters:
+ phi -- toroidal angle
+ nt -- number of points per interface, 1024 by default
+ """
+
+ fig, ax = plt.subplots()
+
+ tarr = np.linspace(0, 2*np.pi, nt)
+ nvol = self['physicslist']['Nvol']
+ nfp = self['physicslist']['Nfp']
+
+ nmodes = len(self.interface_guess)
+ for ivol in range(0,nvol-1):
+ r = np.zeros(nt)
+ z = np.zeros(nt)
+
+ for key in self.interface_guess.keys():
+ mm = key[0]
+ nn = key[1] * nfp
+
+ if mm>self['physicslist']['Mpol'] or abs(nn)>self['physicslist']['Ntor']: continue
+
+ cosa = np.cos(mm*tarr - nn*phi)
+ sina = np.sin(mm*tarr - nn*phi)
+ r += self.interface_guess[key]['Rbc'][ivol] * cosa + \
+ self.interface_guess[key]['Rbs'][ivol] * sina
+ z += self.interface_guess[key]['Zbc'][ivol] * cosa + \
+ self.interface_guess[key]['Zbs'][ivol] * sina
+
+ ax.scatter( r, z, **kwargs )
+
+ # Plot plasma boundary
+ r = np.zeros(nt)
+ z = np.zeros(nt)
+ for mm in range(0, self._Mpol+1):
+ for nn in range(-self._Ntor, self._Ntor+1):
+ cosa = np.cos(mm*tarr - nn*phi)
+ sina = np.sin(mm*tarr - nn*phi)
+ r += self['physicslist']['Rbc'][mm][nn+self._Ntor] * cosa \
+ +self['physicslist']['Rbs'][mm][nn+self._Ntor] * sina
+ z += self['physicslist']['Zbc'][mm][nn+self._Ntor] * cosa \
+ +self['physicslist']['Zbs'][mm][nn+self._Ntor] * sina
+
+ ax.scatter( r, z, **kwargs )
+
+ plt.draw()
+
def _rectify_namelist(self):
"""correct the size/type of the namelist objects and so on"""
@@ -487,7 +637,7 @@ def _rectify_namelist(self):
for key in self.boundary_keys:
if key.lower() not in self["physicslist"].keys():
self["physicslist"][key] = np.zeros(
- [self._Mpol, self._Ntor * 2 + 1], dtype=np.float
+ [self._Mpol, self._Ntor * 2 + 1], dtype=np.float64
).tolist()
self["physicslist"].start_index[key.lower()] = [-self._Ntor, 0]
else:
@@ -501,7 +651,7 @@ def _rectify_namelist(self):
for key in self.axis_keys:
if key.lower() not in self["physicslist"].keys():
self["physicslist"][key] = np.zeros(
- [self._Ntor + 1], dtype=np.float
+ [self._Ntor + 1], dtype=np.float64
).tolist()
self["physicslist"].start_index[key.lower()] = [0]
else:
@@ -596,7 +746,7 @@ def _read_interface_guess(self, file_object):
# ignore empty lines
if len(line_split) == 0:
- break
+ continue
# check if this line meet our expectation
valid_line = True
diff --git a/Utilities/pythontools/py_spec/math/spec_fft.py b/Utilities/pythontools/py_spec/math/spec_fft.py
new file mode 100644
index 00000000..a1c0c187
--- /dev/null
+++ b/Utilities/pythontools/py_spec/math/spec_fft.py
@@ -0,0 +1,192 @@
+import numpy as np
+import copy
+import warnings
+
+def spec_fft(tarr: np.array,
+ zarr: np.array,
+ freal: np.array,
+ Mpol: int=None,
+ Ntor: int=None,
+ output: str='1D'):
+ """
+ Fourier transform as in SPEC fortran source
+
+ Args:
+ - tarr: 1D numpy array of size nt. Poloidal angle coordinate, each point
+ should be equidistant
+ - zarr: 1D numpy array of size nz. Toroidal angle coordinate, each point
+ should be equidistant
+ - freal: 2D numpy array of size (nz,nt). Function, in real space, for which
+ Fourier harmonics should be evaluated
+ - Mpol: integer. Poloidal resolution. Default is nt/2.
+ - Ntor: integer. Toroidal resolution. Default is nz/2.
+ - output: either '1D' or '2D'. Determine the form of the output.
+
+ Output:
+ If output=='1D', the output is a 4-tuple 1D numpy array, with modes
+ organized as in SPEC (first increasing n, then increasing m). First
+ tuple element are the even modes, second are the odd modes, third
+ are the poloidal mode number, and fourth the toroidal mode number.
+ If output=='2D', the output is tuple of 2D numpy array, with modes (m,n)
+ in element (Ntor+n,m). First tuple elements are the even modes,
+ seconds are the odd modes
+ """
+
+ # Check input
+ # -----------
+ # tarr
+ if not isinstance(tarr, np.ndarray):
+ raise ValueError('tarr should be a numpy array')
+ if tarr.ndim>1:
+ raise ValueError('tarr should be one-dimensional')
+
+ nt = tarr.size
+ if nt<3:
+ raise ValueError('Not enough points in tarr')
+
+ # zarr
+ if not isinstance(zarr, np.ndarray):
+ raise ValueError('zarr should be a numpy array')
+ if zarr.ndim>1:
+ raise ValueError('zarr should be one-dimensional')
+
+ nz = zarr.size
+ if nz<3:
+ raise ValueError('Not enough points in zarr')
+
+ # freal
+ if not isinstance(freal, np.ndarray):
+ raise ValueError('freal should be a numpy array')
+ if freal.ndim!=2:
+ raise ValueError('freal should be two-dimensional')
+ if freal.shape!=(nz,nt):
+ raise ValueError('freal should be of size (nz,nt)')
+
+ if tarr[0]+2*np.pi==tarr[-1]:
+ warnings.warn('tarr[-1] should not be equal to tarr[0]. Removing last element...')
+ tarr = tarr[:-1]
+ nt -= 1
+ freal = freal[:,:-1]
+
+ if zarr[0]+2*np.pi==zarr[-1]:
+ warnings.warn('zarr[-1] should not be equal to zarr[0]. Removing last element...')
+ zarr = zarr[:-1]
+ nz -= 1
+ freal = freal[:-1,:]
+
+ if not np.all(np.abs(np.diff(np.diff(tarr)))<1e-14):
+ raise ValueError('Points should be equidistant in tarr')
+ if not np.all(np.abs(np.diff(np.diff(zarr)))<1e-14):
+ raise ValueError('Points should be equidistant in zarr')
+
+ # Mpol
+ M = int(np.floor(nt/2))
+ if Mpol is None:
+ Mpol = M
+ if not isinstance(Mpol, int):
+ raise ValueError('Mpol should be an integer')
+ if Mpol<1 or Mpol>nt/2:
+ raise ValueError('Mpol should be at least 1 and smaller than nt/2')
+
+ # Ntor
+ N = int(np.floor(nz/2))
+ if Ntor is None:
+ Ntor = N
+ if not isinstance(Ntor, int):
+ raise ValueError('Ntor should be an integer')
+ if Ntor<1 or Ntor>nz/2:
+ raise ValueError('Ntor should be at least 1 and smaller than nt=z/2')
+
+ # output
+ if not isinstance(output, str):
+ raise ValueError('output should be a string')
+ if not (output=='1D' or output=='2D'):
+ raise ValueError('output should be 1D or 2D')
+
+ # Do the fft
+ # ----------
+ # Actual fft
+ fmn = np.fft.fft2( freal ) / (nt*nz)
+
+ # Now construct 2D array. Negative m-modes have to be added to positive
+ # m-modes, i.e. (m,n)+(-m,-n) for even modes, and (m,n)-(-m,-n) for odd
+ # modes.
+ # Difference if the number of elements (either nt or nz) is odd - this is
+ # due to the internal implementation of numpy.fft.fft.
+ efmn = copy.deepcopy(fmn)
+ efmn[1:,1:] = fmn[1:,1:] + np.flip(fmn[1:,1:])
+
+ ofmn = copy.deepcopy(fmn)
+ ofmn[1:,1:] = fmn[1:,1:] - np.flip(fmn[1:,1:])
+ if np.mod(nt,2)==0:
+ efmn[0,1:M+1] += np.flip(fmn[0,M:]) #n=0
+ ofmn[0,1:M+1] -= np.flip(fmn[0,M:])
+ else:
+ efmn[0,1:M+1] += np.flip(fmn[0,M+1:]) #n=0
+ ofmn[0,1:M+1] -= np.flip(fmn[0,M+1:])
+
+ if np.mod(nz,2)==0:
+ efmn[1:N+1,0] += np.flip(fmn[N:,0]) # m=0
+ ofmn[1:N+1,0] -= np.flip(fmn[N:,0])
+ else:
+ efmn[1:N+1,0] += np.flip(fmn[N+1:,0]) # m=0
+ ofmn[1:N+1,0] -= np.flip(fmn[N+1:,0])
+
+ efmn = (np.absolute(efmn) * np.cos(np.angle(efmn)))[:,0:M+1]
+ ofmn = (np.absolute(ofmn) * np.sin(np.angle(ofmn)))[:,0:M+1]
+
+ # Change sign of m>0 odd modes
+ ofmn[:,1:] = -ofmn[:,1:]
+
+ # Shift result to be centered around n=0 mode
+ efmn = np.fft.fftshift(efmn, axes=0)
+ ofmn = np.fft.fftshift(ofmn, axes=0)
+
+ # Invert n -> -n
+ if np.mod(nz,2)==0:
+ efmn[1:,1:] = np.flip(efmn[1:,1:],axis=0)
+ ofmn[1:,1:] = np.flip(ofmn[1:,1:],axis=0)
+ else:
+ efmn[:,1:] = np.flip(efmn[:,1:],axis=0)
+ ofmn[:,1:] = np.flip(ofmn[:,1:],axis=0)
+
+
+ # Prepare output
+ # --------------
+ if output=='2D':
+ # 2D - truncate efmn, ofmn to the required resolution
+ even_out = efmn[N-Ntor:N+Ntor+1,0:Mpol+1]
+ odd_out = ofmn[N-Ntor:N+Ntor+1,0:Mpol+1]
+ return (even_out, odd_out)
+
+ elif output=='1D':
+ # 1D - construct array mode by mode
+ nmn = Ntor+1 + Mpol*(2*Ntor+1)
+ even_out = np.zeros((nmn,))
+ odd_out = np.zeros((nmn,))
+ _im = np.zeros((nmn,), dtype=int)
+ _in = np.zeros((nmn,), dtype=int)
+
+ ind = -1
+ for mm in range(0,Mpol+1):
+ for nn in range(-Ntor,Ntor+1):
+ if mm==0 and nn<0:
+ continue
+
+ ind += 1
+
+ _im[ind]=mm
+ _in[ind]=nn
+ even_out[ind] = efmn[N+nn,mm]
+ odd_out[ind] = ofmn[N+nn,mm]
+
+ return (even_out, odd_out, _im, _in)
+
+ else:
+ raise ValueError('Invalid output')
+
+
+
+
+
+
diff --git a/Utilities/pythontools/py_spec/math/spec_invfft.py b/Utilities/pythontools/py_spec/math/spec_invfft.py
new file mode 100644
index 00000000..14022777
--- /dev/null
+++ b/Utilities/pythontools/py_spec/math/spec_invfft.py
@@ -0,0 +1,89 @@
+import numpy as np
+
+def spec_invfft(tarr:np.ndarray, zarr:np.ndarray,
+ efmn:np.ndarray, ofmn:np.ndarray,
+ _im:np.ndarray, _in:np.ndarray):
+ """
+ Inverse Fourier transform as in SPEC Fortran source.
+
+ Args:
+ - tarr: 1D numpy array of size nt. Poloidal angle coordinate.
+ - zarr: 1D numpy array of size nz. Toroidal angle coordinate.
+ - efmn: 1D numpy array of size nmn. Even mode numbers.
+ - ofmn: 1D numpy array of size nmn. Odd mode numbers.
+ - _im: 1D numpy array of size nmn. Poloidal mode numbers
+ - _in: 1D numpy array of size nmn. Toroidal mode numbers (multiples of Nfp)
+
+ Output:
+ - freal: 2D numpy array of size nz x nt. Function evaluation in real space.
+ """
+
+ # Check input
+ # -----------
+ # tarr
+ if not isinstance(tarr, np.ndarray):
+ raise ValueError('tarr should be a numpy array')
+ if tarr.ndim>1:
+ raise ValueError('tarr should be one-dimensional')
+
+ nt = tarr.size
+
+ # zarr
+ if not isinstance(zarr, np.ndarray):
+ raise ValueError('zarr should be a numpy array')
+ if zarr.ndim>1:
+ raise ValueError('zarr should be one-dimensional')
+
+ nz = zarr.size
+
+ # efmn
+ if not isinstance(efmn, np.ndarray):
+ raise ValueError('efmn should be a numpy array')
+ if efmn.ndim>1:
+ raise ValueError('efmn should be one-dimensional')
+
+ nmn = efmn.size
+
+ # ofmn
+ if not isinstance(ofmn, np.ndarray):
+ raise ValueError('ofmn should be a numpy array')
+ if ofmn.ndim>1:
+ raise ValueError('ofmn should be one-dimensional')
+ if ofmn.size!=nmn:
+ raise ValueError('ofmn should have the same size as efmn')
+
+ # _im
+ if not isinstance(_im, np.ndarray):
+ raise ValueError('_im should be a numpy array')
+ if _im.ndim>1:
+ raise ValueError('_im should be one-dimensional')
+ if _im.size!=nmn:
+ raise ValueError('_im should have the same size as efmn')
+ if not np.all(_im>=0):
+ raise ValueError('_im should not have any negative values')
+
+ # _in
+ if not isinstance(_in, np.ndarray):
+ raise ValueError('_in should be a numpy array')
+ if _in.ndim>1:
+ raise ValueError('_in should be one-dimensional')
+ if _in.size!=nmn:
+ raise ValueError('_in should have the same size as efmn')
+
+ # Inverse Fourier transform
+ # -------------------------
+
+ # Generate grid:
+ tgrid, zgrid = np.meshgrid(tarr, zarr)
+
+ # Evaluate function:
+ freal = np.zeros((nz,nt))
+ for mm, nn, emode, omode in zip(_im, _in, efmn, ofmn):
+ freal += emode * np.cos(mm*tgrid - nn*zgrid) \
+ + omode * np.sin(mm*tgrid - nn*zgrid)
+
+ # Output
+ return freal
+
+
+
diff --git a/Utilities/pythontools/py_spec/output/_plot_iota.py b/Utilities/pythontools/py_spec/output/_plot_iota.py
index 8de0c2e3..362075e5 100644
--- a/Utilities/pythontools/py_spec/output/_plot_iota.py
+++ b/Utilities/pythontools/py_spec/output/_plot_iota.py
@@ -29,7 +29,7 @@ def plot_iota(self, xaxis="R", yaxis="i", ax=None, **kwargs):
xlabel = r"s"
elif xaxis == "R":
xdata = self.poincare.R[:, 0, 0]
- ydata = self.transform.fiota[1, :]
+ ydata = self.transform.fiota[1, self.poincare.success == 1]
xlabel = r"R"
else:
raise ValueError("xaxis should be one of ['R', 's'].")
diff --git a/Utilities/pythontools/py_spec/output/_plot_poincare.py b/Utilities/pythontools/py_spec/output/_plot_poincare.py
index d1002931..6de93211 100644
--- a/Utilities/pythontools/py_spec/output/_plot_poincare.py
+++ b/Utilities/pythontools/py_spec/output/_plot_poincare.py
@@ -73,4 +73,4 @@ def plot_poincare(self, toroidalIdx=0, prange="full", ax=None, **kwargs):
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
- return
\ No newline at end of file
+ return ax
diff --git a/Utilities/pythontools/py_spec/output/_plot_pressure.py b/Utilities/pythontools/py_spec/output/_plot_pressure.py
index cb459a05..97d51d0b 100644
--- a/Utilities/pythontools/py_spec/output/_plot_pressure.py
+++ b/Utilities/pythontools/py_spec/output/_plot_pressure.py
@@ -9,8 +9,8 @@ def plot_pressure(self, normalize=True, ax=None, **kwargs):
import numpy as np
import matplotlib.pyplot as plt
- pressure = self.input.physics.pressure * self.input.physics.pscale
- tflux = self.output.tflux[: len(pressure)]
+ pressure = np.atleast_1d(self.input.physics.pressure) * self.input.physics.pscale
+ tflux = np.atleast_1d(self.output.tflux)[: len(pressure)]
if not normalize:
# remove mu_0
pressure /= 4 * np.pi * 1.0e-7
diff --git a/Utilities/pythontools/py_spec/output/_processing.py b/Utilities/pythontools/py_spec/output/_processing.py
index 6479a6fe..3e481f78 100644
--- a/Utilities/pythontools/py_spec/output/_processing.py
+++ b/Utilities/pythontools/py_spec/output/_processing.py
@@ -1,5 +1,132 @@
import numpy as np
+from scipy import integrate
+import typing
+def get_RZ_derivatives(
+ self,
+ lvol=0,
+ sarr=np.linspace(1, 1, 1),
+ tarr=np.linspace(0, 0, 1),
+ zarr=np.linspace(0, 0, 1),
+ input1D=False
+):
+
+ Igeometry = self.input.physics.Igeometry
+
+ if lvol==0 and (sarr==-1).any() and Igeometry!=0:
+ raise ValueError('Cannot evaluate coordinate derivative on magnetic axis !')
+
+ sym = self.input.physics.Istellsym == 1
+
+ Rac, Rbc = self.output.Rbc[lvol : lvol + 2]
+ Ras, Rbs = self.output.Rbs[lvol : lvol + 2]
+ Zas, Zbs = self.output.Zbs[lvol : lvol + 2]
+ Zac, Zbc = self.output.Zbc[lvol : lvol + 2]
+
+ mn = Rac.size # s.output.mn
+ im = self.output.im
+ in_ = self.output.in_
+
+ #sbar = (sarr + 1) / 2
+ sbar = np.divide(np.add(sarr, 1.0), 2.0)
+ fac = []
+
+ rpol = self.input.physics.rpol
+ rtor = self.input.physics.rtor
+
+ if Igeometry == 1:
+ for j in range(mn):
+ fac.append([sbar, 0.5 * np.ones(sarr.size), np.zeros(sarr.size)])
+ elif Igeometry == 2:
+ for j in range(mn):
+ if lvol > 0 or im[j] == 0:
+ fac.append([sbar, 0.5 * np.ones(sarr.size), np.zeros(sarr.size)])
+ else:
+ fac.append(
+ [
+ sbar ** (im[j] + 1.0),
+ (im[j] + 1.0) / 2.0 * sbar ** (im[j]),
+ (im[j] + 1.0) * (im[j]) / 4.0 * sbar ** (im[j] - 1),
+ ]
+ )
+ elif Igeometry == 3:
+ for j in range(mn):
+ if lvol == 0 and im[j] == 0:
+ fac.append([sbar ** 2, sbar, 0.5 * np.ones(sarr.size)])
+ elif lvol == 0 and im[j] > 0:
+ fac.append(
+ [
+ sbar ** im[j],
+ (im[j] / 2.0) * sbar ** (im[j] - 1.0),
+ (im[j] * (im[j] - 1) / 4.0) * sbar ** (im[j] - 2.0),
+ ]
+ )
+ else:
+ fac.append([sbar, 0.5 * np.ones(sarr.size), np.zeros(sarr.size)])
+
+ # now fac has the dimension (number of modes, number of derivatives, number of s points)
+ fac = np.array(fac)
+ # transpose to (number of derivatives, number of modes, number of s points)
+ fac = np.moveaxis(fac, 0, 1)
+
+ nax = np.newaxis
+ if not input1D:
+ im = im[:, nax, nax, nax]
+ in_ = in_[:, nax, nax, nax]
+ ang_arg = +im * tarr[nax, nax, :, nax] - in_ * zarr[nax, nax, nax, :]
+ else:
+ im = im[:, nax]
+ in_ = in_[:, nax]
+ ang_arg = im * tarr[nax, :] - in_ * zarr[nax, :]
+
+ cos = np.cos(ang_arg)
+ sin = np.sin(ang_arg)
+
+ if not input1D:
+ fac = fac[:, :, :, nax, nax]
+ Rac = Rac[:, nax, nax, nax]
+ Rbc = Rbc[:, nax, nax, nax]
+ Zas = Zas[:, nax, nax, nax]
+ Zbs = Zbs[:, nax, nax, nax]
+ if not sym:
+ Ras = Ras[:, nax, nax, nax]
+ Rbs = Rbs[:, nax, nax, nax]
+ Zac = Zac[:, nax, nax, nax]
+ Zbc = Zbc[:, nax, nax, nax]
+ else:
+ Rac = Rac[:, nax]
+ Rbc = Rbc[:, nax]
+ Zas = Zas[:, nax]
+ Zbs = Zbs[:, nax]
+ if not sym:
+ Ras = Ras[:, nax]
+ Rbs = Rbs[:, nax]
+ Zac = Zac[:, nax]
+ Zbc = Zbc[:, nax]
+
+ dR1 = Rac + fac[0] * (Rbc - Rac)
+ Rarr0 = np.sum(dR1 * cos, axis=0)
+
+ Rarr1 = np.sum(fac[1] * (Rbc - Rac) * cos, axis=0)
+ Rarr2 = np.sum(-im * dR1 * sin, axis=0)
+ Rarr3 = np.sum(in_ * dR1 * sin, axis=0)
+
+ Rarr = np.array([Rarr1, Rarr2, Rarr3])
+
+ # We only need Z for Igeometry=3
+ if Igeometry == 3:
+ dZ1 = Zas + fac[0] * (Zbs - Zas)
+ Zarr0 = np.sum(dZ1 * sin, axis=0)
+
+ Zarr1 = np.sum(fac[1] * (Zbs - Zas) * sin, axis=0)
+ Zarr2 = np.sum(im * dZ1 * cos, axis=0)
+ Zarr3 = np.sum(-in_ * dZ1 * cos, axis=0)
+
+ Zarr = np.array([Zarr1, Zarr2, Zarr3])
+ else:
+ Zarr0 = None
+
+ return Rarr0, Rarr1, Rarr2, Rarr3, Zarr0, Zarr1, Zarr2, Zarr3
def get_grid_and_jacobian_and_metric(
self,
@@ -231,7 +358,6 @@ def get_grid_and_jacobian_and_metric(
else:
return Rarr0, Zarr0, jacobian, g
-
def grid(
self,
lvol=0,
@@ -246,7 +372,6 @@ def grid(
)
return Rarr0, Zarr0
-
def jacobian(
self,
lvol=0,
@@ -261,7 +386,6 @@ def jacobian(
)
return jacobian
-
def metric(
self,
lvol=0,
@@ -276,7 +400,6 @@ def metric(
)
return g
-
def get_B(
self,
lvol=0,
@@ -353,12 +476,114 @@ def get_modB(self, Bcontrav, g, derivative=False, dBcontrav=None, dg=None):
) + np.einsum("...i,...kji,...j->...k", Bcontrav, dg, Bcontrav)
return modB, dmodB2
-
def get_B_covariant(self, Bcontrav, g, derivative=False):
"""Get covariant component of B"""
Bco = np.einsum("...i,...ji->...j", Bcontrav, g)
return Bco
+def get_volume(self, ivol, ns=64, nt=64, nz=64):
+ """Returns volume occupied by volume ivol"""
+
+ # Create coordinate grid
+ nfp = self.input.physics.Nfp
+ tarr = np.linspace(0, 2*np.pi, nt, endpoint=True)
+ zarr = np.linspace(0, 2*np.pi / nfp, nz, endpoint=True)
+
+ if ivol==0: sarr=np.linspace(-0.999,1,ns)
+ else: sarr=np.linspace(-1, 1, ns)
+
+ # Get jacobian
+ j = self.jacobian(lvol=ivol, sarr=sarr, tarr=tarr, zarr=zarr)
+
+ # Integrate
+ dt = tarr[1]-tarr[0]
+ dz = zarr[1]-zarr[0]
+ ds = sarr[1]-sarr[0]
+ return nfp * integrate.simpson( y=integrate.simpson( y=integrate.simpson( y=j, x=zarr ), x=tarr ), x=sarr )
+
+def get_average_beta(self, ns=64, nt=64, nz=64):
+ """Get beta averaged in plasma volume"""
+
+ # Read pressure
+ press = np.atleast_1d(self.input.physics.pressure) * self.input.physics.pscale
+
+ # Create coordinate grid
+ nfp = self.input.physics.Nfp
+ tarr = np.linspace(0, 2*np.pi, nt)
+ zarr = np.linspace(0, 2*np.pi / nfp, nz)
+
+ # Get beta in each volume
+ nvol = self.input.physics.Nvol
+
+ vols = np.zeros((nvol,))
+ betavol = np.zeros((nvol,))
+
+ if (press==0).all(): return 0
+
+ if nvol==1:
+ sarr=np.linspace(-0.999,1, ns)
+ vols = self.get_volume( 0 )
+ _, _, sg, g = self.get_grid_and_jacobian_and_metric(
+ lvol=0, sarr=sarr, tarr=tarr, zarr=zarr
+ )
+ Bcontrav = self.get_B(
+ lvol=0, jacobian=sg, sarr=sarr, tarr=tarr, zarr=zarr
+ )
+ modB = self.get_modB( Bcontrav, g )
+
+ betavol = 2 * nfp * press * integrate.simpson(
+ y=integrate.simpson(
+ y=integrate.simpson(
+ y=sg / modB**2, x=zarr ), x=tarr ), x=sarr )
+
+ return betavol / vols
+ else:
+ for ivol in range(0,nvol):
+ if ivol==0: sarr=np.linspace(-0.999,1, ns)
+ if ivol!=0: sarr=np.linspace(-1, 1, ns)
+
+ vols[ivol] = self.get_volume( ivol )
+
+ _, _, sg, g = self.get_grid_and_jacobian_and_metric(
+ lvol=ivol, sarr=sarr, tarr=tarr, zarr=zarr
+ )
+ Bcontrav = self.get_B(
+ lvol=ivol, jacobian=sg, sarr=sarr, tarr=tarr, zarr=zarr
+ )
+ modB = self.get_modB( Bcontrav, g )
+
+ betavol[ivol] = 2 * nfp * press[ivol] * integrate.simpson(
+ y=integrate.simpson(
+ y=integrate.simpson(
+ y=sg / modB**2, x=zarr ), x=tarr ), x=sarr )
+
+ return betavol.sum() / vols.sum()
+
+def get_peak_beta(self, ns=64, nt=64, nz=64):
+ if self.input.physics.pressure.size>1:
+ press = self.input.physics.pressure[0] * self.input.physics.pscale
+ else:
+ press = self.input.physics.pressure * self.input.physics.pscale
+
+ nfp = self.input.physics.Nfp
+ tarr = np.linspace(0, 2*np.pi, nt)
+ zarr = np.linspace(0, 2*np.pi / nfp, nz)
+ sarr=np.linspace(-0.999,1, ns)
+
+ vol = self.get_volume( 0 )
+ _, _, sg, g = self.get_grid_and_jacobian_and_metric(
+ lvol=0, sarr=sarr, tarr=tarr, zarr=zarr
+ )
+ Bcontrav = self.get_B(
+ lvol=0, jacobian=sg, sarr=sarr, tarr=tarr, zarr=zarr
+ )
+ modB = self.get_modB( Bcontrav, g )
+
+ return 2 * nfp * press * integrate.simpson(
+ y=integrate.simpson(
+ y=integrate.simpson(
+ y=sg / modB**2, x=zarr ), x=tarr ), x=sarr ) / vol
+
def test_derivatives(self, lvol=0, s=0.3, t=0.4, z=0.5, delta=1e-6, tol=1e-6):
ds = delta
R, Z, j, g = self.get_grid_and_jacobian_and_metric(lvol, np.array([s-ds, s+ds]), np.array([t-ds, t+ds]), np.array([z-ds, z+ds]))
@@ -381,3 +606,201 @@ def test_derivatives(self, lvol=0, s=0.3, t=0.4, z=0.5, delta=1e-6, tol=1e-6):
print((g[1,0,0,:,:] - g[0,0,0,:,:])/ds/2-dg[0,0,0,0,:,:])
print((g[0,1,0,:,:] - g[0,0,0,:,:])/ds/2-dg[0,0,0,1,:,:])
print((g[0,0,1,:,:] - g[0,0,0,:,:])/ds/2-dg[0,0,0,2,:,:])
+
+def _validate_lsurf(lsurf:np.ndarray, mvol:int)->np.ndarray:
+ """Check
+
+ Args:
+ - lsurf: Interface number(s), between 1 and Mvol-1. default is np.arange(1, mvol)
+ - mvol: Number of volumes
+ Returns:
+ - lsurf: 1d array of interface numbers
+
+ Raises:
+ - ValueError: if input is outside of range or wrong type (lsurf)
+ """
+
+ if lsurf is None:
+ lsurf = np.arange(1,mvol)
+ else:
+ lsurf = np.atleast_1d(lsurf)
+ if (lsurf<1).any() or (lsurf>mvol-1).any(): raise ValueError('lsurf should be in [1,mvol-1]')
+
+ return lsurf
+
+def get_surface_current_density(self, lsurf:np.ndarray, nt:int=64, nz:int=64)->typing.Tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Compute j_surf.B on each side of the provided interfaces
+
+ Args:
+ - lsurf: Interface number(s), between 1 and Mvol-1. default is np.arange(1, mvol)
+ - nt: Number of poloidal points
+ - nz: Number of toroidal points
+
+ Returns:
+ - j_dot_B: mu0*j_surf.B evaluated on the grid. Shape (nsurf, nt, nz),
+ with nsurf the size of lsurf
+ - tarr: theta array, size (nt,)
+ - zarr: zeta array, size (nz,)
+
+ Raises:
+ - ValueError: if input is wrong (invalid lsurf, nt<=0, nz<=0)
+ """
+
+ mvol = self.output.Mvol
+ nfp = self.input.physics.Nfp
+
+ if mvol==1: raise ValueError('Mvol=1; no interface current!')
+ lsurf = _validate_lsurf(lsurf, mvol)
+ if nt<1: raise ValueError('nt should greater than zero')
+ if nz<1: raise ValueError('nz should greater than zero')
+
+ # Construct grid
+ tarr = np.linspace(0, 2*np.pi, nt, endpoint=True)
+ zarr = np.linspace(0, 2*np.pi/nfp, nz, endpoint=True)
+
+ # Evaluate geometry elements
+ nsurf = lsurf.size*2
+ j_dot_B = np.zeros((mvol-1, 2, nt, nz))
+ for s in lsurf:
+ # Construct geometry elements - these are independent of the
+ # interface side
+ R0, R1, R2, R3, Z0, Z1, Z2, Z3 = self.get_RZ_derivatives(
+ lvol=int(s-1),
+ sarr=np.asarray([1]),
+ tarr=tarr,
+ zarr=zarr
+ )
+ et_x_ez = np.sqrt((R2*Z3)**2 + (R3*Z2)**2 + (R0*Z2)**2 + (R0*R2)**2 - 2*R2*R3*Z2*Z3)
+
+ gtt = R2**2+Z2**2
+ gzz = R0**2 + R3**2 + Z3**2
+ gtz = R2*R3 + Z2*Z3
+ g = gtt*gzz - gtz**2
+
+ # project on each side of interface
+ Bcontrav = np.zeros((2,nt,nz,3))
+ for innout in [0,1]:
+ # if innout=0, inner side of interface, thus vvol=s-1 and sarr=1
+ # if innout=1, outer side of interface, thus vvol=s and sarr=-1
+ lvol = s - np.mod(innout+1,2)
+ sarr = np.asarray([-innout*2+1])
+
+ # Get magnetic field
+ Bcontrav[innout,:,:,:] = self.get_B(
+ lvol=lvol,
+ sarr=sarr,
+ tarr=tarr,
+ zarr=zarr
+ )[0]
+
+ Bcontrav_jump = Bcontrav[1]-Bcontrav[0]
+
+ for innout in [0,1]:
+ j_dot_B[s-1, innout] = g / et_x_ez * (
+ Bcontrav[innout, :, :, 1]*Bcontrav_jump[:, :, 2]
+ - Bcontrav[innout, :, :, 2]*Bcontrav_jump[:, :, 1]
+ )
+
+ return j_dot_B, tarr, zarr
+
+def get_surface(self, lsurf:np.ndarray=None, nt:int=64, nz:int=64):
+ """Compute the surface area of a volume interface
+
+ Args:
+ - lsurf: Interface number(s), between 1 and Mvol-1. default is np.arange(1, mvol)
+ - nt: Number of poloidal points for integration, default is 64
+ - nz: Number of toroidal points for integration, default is 64
+
+ Returns:
+ - S: the surface area
+
+ Raises:
+ - ValueError: if input is wrong (invalid lsurf, nt<=0, nz<=0)
+ """
+
+ mvol = self.output.Mvol
+ nfp = self.input.physics.Nfp
+
+ if mvol==1:
+ raise ValueError('Mvol=1; no interface current!')
+ lsurf = _validate_lsurf(lsurf, mvol)
+ if nt<1:
+ raise ValueError('nt should greater than zero')
+ if nz<1:
+ raise ValueError('nz should greater than zero')
+
+ # Construct grid
+ tarr = np.linspace(0, 2*np.pi, nt, endpoint=True)
+ zarr = np.linspace(0, 2*np.pi/nfp, nz, endpoint=True)
+
+ # Create variable for storing the surface area
+ S = np.zeros((mvol-1,))
+
+ # Loop on interfaces
+ for s in lsurf:
+ # Construct geometry elements
+ R0, R1, R2, R3, Z0, Z1, Z2, Z3 = self.get_RZ_derivatives(
+ lvol=int(s-1),
+ sarr=np.asarray([1]),
+ tarr=tarr,
+ zarr=zarr
+ )
+ #e theta x e phi
+ et_x_ez = np.sqrt((R2*Z3)**2 + (R3*Z2)**2 + (R0*Z2)**2 + (R0*R2)**2 - 2*R2*R3*Z2*Z3)
+
+ S = nfp*integrate.simps(integrate.simps(et_x_ez,zarr,axis=2),tarr,axis=1)
+
+ return S
+
+def get_flux_surface_average( self, lsurf, f, tarr, zarr ):
+ """Returns the flux surface average of a function f.
+
+ For each surface lsurf, the average is made by computing the jacobian on the
+ inner side of the interface (i.e. lvol=lsurf-1, sarr=1)
+
+ Args:
+ - lsurf: Interface number(s), between 1 and Mvol-1. default is np.arange(1, mvol)
+ - f (2D numpy array): function evaluated on a grid
+ - tgrid (2D numpy array): theta grid
+ - zgrid (2D numpy array): phi grid
+
+ Returns>
+ - fsavg (1D numpy array): The flux surface average of f on each surface
+ given in lsurf
+ Raises:
+ - ValueError: if input is wrong (invalid lsurf)
+ """
+
+ lsurf = _validate_lsurf(lsurf, self.output.Mvol)
+
+ # Get jacobian
+ output = np.zeros(lsurf.shape)
+ for ii, ll in enumerate(lsurf):
+ sqrtg = self.jacobian(
+ lvol=ll-1,
+ sarr=np.array([1]),
+ tarr=tarr,
+ zarr=zarr
+ )
+
+ qrtg = np.squeeze(sqrtg)
+
+ numerator = integrate.simps(
+ integrate.simps(np.multiply(f, qrtg), tarr, axis=0), zarr
+ )
+ denumerator = integrate.simps(
+ integrate.simps(qrtg, tarr, axis=0), zarr
+ )
+
+ output[ii] = numerator / denumerator
+
+ return output
+
+
+
+
+
+
+
+
+
diff --git a/Utilities/pythontools/py_spec/output/spec.py b/Utilities/pythontools/py_spec/output/spec.py
index 733c48e0..428b59a3 100644
--- a/Utilities/pythontools/py_spec/output/spec.py
+++ b/Utilities/pythontools/py_spec/output/spec.py
@@ -37,7 +37,14 @@ class SPECout:
get_B,
get_modB,
get_B_covariant,
- test_derivatives
+ test_derivatives,
+ get_surface_current_density,
+ get_surface,
+ get_RZ_derivatives,
+ get_volume,
+ get_average_beta,
+ get_peak_beta,
+ get_flux_surface_average
)
from ._plot_modB import plot_modB
from ._plot_iota import plot_iota
@@ -88,21 +95,15 @@ def __init__(self, *args, **kwargs):
if isinstance(_content, h5py.File):
_content.close()
- # make sure that Lrad is always an array
- if np.isscalar(self.input.physics.Lrad):
- self.input.physics.Lrad = np.array([self.input.physics.Lrad])
- # make sure that im always an array
- if np.isscalar(self.output.im):
- self.output.im = np.array([self.output.im])
- # make sure that in_ is always an array
- if np.isscalar(self.output.in_):
- self.output.in_ = np.array([self.output.in_])
+ self.input.physics.Lrad = np.atleast_1d(self.input.physics.Lrad)
+ self.output.im = np.atleast_1d(self.output.im)
+ self.output.in_ = np.atleast_1d(self.output.in_)
# these define the target dimensions in the radial direction
Nvol = self.input.physics.Nvol
+ Mvol = Nvol
if self.input.physics.Lfreebound:
- Nvol += 1
- self.input.physics.Nvol += 1
+ Mvol += 1
Lrad = self.input.physics.Lrad
@@ -122,7 +123,7 @@ def __init__(self, *args, **kwargs):
# split up radial matrix dimension into list of matrices for each of the nested volumes
start = 0
- for i in range(Nvol):
+ for i in range(Mvol):
# vector potential
cAte.append(
np.atleast_2d(self.vector_potential.Ate)[
diff --git a/Utilities/pythontools/py_spec/tests/README.md b/Utilities/pythontools/py_spec/tests/README.md
new file mode 100644
index 00000000..2211cf31
--- /dev/null
+++ b/Utilities/pythontools/py_spec/tests/README.md
@@ -0,0 +1,4 @@
+To run tests, do
+```
+python -m unittest -v test_math.test_spec_fft
+```
diff --git a/Utilities/pythontools/py_spec/tests/test_math/test_spec_fft.py b/Utilities/pythontools/py_spec/tests/test_math/test_spec_fft.py
new file mode 100644
index 00000000..03cc77c6
--- /dev/null
+++ b/Utilities/pythontools/py_spec/tests/test_math/test_spec_fft.py
@@ -0,0 +1,99 @@
+import unittest
+import numpy as np
+from py_spec.math.spec_fft import spec_fft as fft
+from py_spec.math.spec_invfft import spec_invfft as invfft
+
+
+class fftTests(unittest.TestCase):
+ def test_fft_1d(self):
+ """
+ Test spec_fft on an analytical function, 1D output
+ """
+
+ nt = 33 # Number of theta points
+ nz = 17 # Number of zeta points
+ tarr = np.linspace(0, 2*np.pi, nt, endpoint=False)
+ zarr = np.linspace(0, 2*np.pi, nz, endpoint=False)
+
+ tgrid, zgrid = np.meshgrid( tarr, zarr ) # grid
+
+ f = 0.3 \
+ + 2*np.cos(tgrid) \
+ - 3*np.cos(2*tgrid-zgrid) \
+ + 1*np.cos(2*tgrid+zgrid) \
+ - 3.8*np.sin(tgrid+2*zgrid) \
+ - 2.4*np.sin(3*zgrid)
+
+ efmn, ofmn, _, _ = fft( tarr, zarr, f, Mpol=2, Ntor=3 )
+
+ places=8
+ self.assertAlmostEqual(efmn[ 0], 0.3, places=places)
+ self.assertAlmostEqual(efmn[ 7], 2, places=places)
+ self.assertAlmostEqual(efmn[13], 1, places=places)
+ self.assertAlmostEqual(efmn[15], -3, places=places)
+ self.assertAlmostEqual(ofmn[ 3], 2.4, places=places)
+ self.assertAlmostEqual(ofmn[ 5],-3.8, places=places)
+
+
+ def test_fft_2d(self):
+ """
+ Test spec_fft on an analytical function, 2D output
+ """
+
+ nt = 32 # Number of theta points
+ nz = 21 # Number of zeta points
+ tarr = np.linspace(0, 2*np.pi, nt, endpoint=False)
+ zarr = np.linspace(0, 2*np.pi, nz, endpoint=True)
+
+ tgrid, zgrid = np.meshgrid( tarr, zarr ) # grid
+
+ f = 0.3 \
+ + 2*np.cos(tgrid) \
+ - 3*np.cos(2*tgrid-zgrid) \
+ + 1*np.cos(2*tgrid+zgrid) \
+ - 3.8*np.sin(tgrid+2*zgrid) \
+ - 2.4*np.sin(3*zgrid)
+
+ Mpol=4
+ Ntor=8
+ efmn, ofmn = fft( tarr, zarr, f, Mpol=Mpol, Ntor=Ntor, output='2D' )
+
+ places=8
+ self.assertAlmostEqual(efmn[Ntor,0], 0.3, places=places)
+ self.assertAlmostEqual(efmn[Ntor,1], 2, places=places)
+ self.assertAlmostEqual(efmn[Ntor-1,2], 1, places=places)
+ self.assertAlmostEqual(efmn[Ntor+1,2], -3, places=places)
+ self.assertAlmostEqual(ofmn[Ntor-2,1],-3.8, places=places)
+ self.assertAlmostEqual(ofmn[Ntor+3,0], 2.4, places=places)
+
+
+ def test_invfft(self):
+ """
+ Test spec_invfft using analytical function.
+ """
+
+ nt = 64 # Number of theta points
+ nz = 48 # Number of zeta points
+ tarr = np.linspace(0, 2*np.pi, nt, endpoint=False)
+ zarr = np.linspace(0, 2*np.pi, nz, endpoint=True)
+
+ tgrid, zgrid = np.meshgrid( tarr, zarr ) # grid
+
+ f = 0.3 \
+ + 2*np.cos(tgrid) \
+ - 3*np.cos(2*tgrid-zgrid) \
+ + 1*np.cos(2*tgrid+zgrid) \
+ - 3.8*np.sin(tgrid+2*zgrid) \
+ - 2.4*np.sin(3*zgrid)
+
+ Mpol=8
+ Ntor=8
+ efmn, ofmn, _im, _in = fft( tarr, zarr, f, Mpol=Mpol, Ntor=Ntor, output='1D' )
+
+ freal = invfft(tarr, zarr, efmn, ofmn, _im, _in)
+
+ self.assertTrue( np.max(np.max(np.abs((freal-f)/f)))<1e-8 )
+
+
+
+
\ No newline at end of file
diff --git a/Utilities/pythontools/pyproject.toml b/Utilities/pythontools/pyproject.toml
new file mode 100644
index 00000000..60e6e551
--- /dev/null
+++ b/Utilities/pythontools/pyproject.toml
@@ -0,0 +1,31 @@
+[build-system]
+requires = ["setuptools"]
+build-backend = "setuptools.build_meta"
+
+
+[project]
+name="py_spec"
+version="3.3.5"
+dependencies = ["numpy>=1.21.1",
+ "f90nml",
+ "h5py",
+ "matplotlib",
+ "coilpy; python_version<'3.12'",
+ "scipy>=1.7.0"]
+description="SPEC(Stepped-Pressure Equilibrium Code) python utilities"
+readme="README.md"
+authors = [
+ { name = "Christopher Berg Smiet", email = "christopher.smiet@epfl.ch" },
+ { name = "Caoxiang Zhu", email = "caoxiangzhu@gmail.com" },
+ { name = "SPEC developers"}
+]
+maintainers = [
+ { name = "Christopher Berg Smiet", email = "christopher.smiet@epfl.ch" },
+]
+classifiers=[
+ "Development Status :: 3 - Alpha",
+ "License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)",
+ "Programming Language :: Python :: 3",
+ "Topic :: Scientific/Engineering",
+]
+license = {text = "GNU 3.0"}
diff --git a/Utilities/pythontools/requirements.txt b/Utilities/pythontools/requirements.txt
index 932ff2c4..987fc86c 100644
--- a/Utilities/pythontools/requirements.txt
+++ b/Utilities/pythontools/requirements.txt
@@ -1,5 +1,8 @@
h5py
matplotlib
f90nml
-numpy
-coilpy
\ No newline at end of file
+
+# Version 1.7.0 or higher is required - otherwise scipy.integrate.simpson does not exist
+scipy>=1.7.0
+
+coilpy
diff --git a/Utilities/pythontools/setup.py b/Utilities/pythontools/setup.py
index 8ffdf9b1..7aa39660 100644
--- a/Utilities/pythontools/setup.py
+++ b/Utilities/pythontools/setup.py
@@ -1,23 +1,6 @@
import setuptools
-from py_spec import __version__
-
-with open("README.md", "r") as fh:
- long_description = fh.read()
setuptools.setup(
name="py_spec",
- version=__version__,
- description="SPEC(Stepped-Pressure Equilibrium Code) python utilities",
- long_description=long_description,
- long_description_content_type="text/markdown",
- classifiers=[
- "Development Status :: 3 - Alpha",
- "License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)",
- "Programming Language :: Python :: 3",
- "Topic :: Scientific/Engineering",
- ],
- url="https://princetonuniversity.github.io/SPEC/",
- author="SPEC developers",
- license="GNU 3.0",
- packages=setuptools.find_packages(),
+ packages=['py_spec', 'py_spec.input', 'py_spec.output', 'py_spec.ci', 'py_spec.math']
)
diff --git a/cmake_machines/intel_SUSE.json b/cmake_machines/intel_SUSE.json
new file mode 100644
index 00000000..398c9534
--- /dev/null
+++ b/cmake_machines/intel_SUSE.json
@@ -0,0 +1,8 @@
+{
+ "cmake_args": [
+ "-DCMAKE_C_COMPILER=mpicc",
+ "-DCMAKE_CXX_COMPILER=mpicc",
+ "-DCMAKE_Fortran_COMPILER=mpif90",
+ "-DBLA_VENDOR=Intel10_64lp"
+ ]
+}
diff --git a/compilation_instructions.md b/compilation_instructions.md
new file mode 100644
index 00000000..181af979
--- /dev/null
+++ b/compilation_instructions.md
@@ -0,0 +1,181 @@
+# SPEC compilation instructions
+
+The default installation method for SPEC uses CMake and installs
+the python wrappers and an xspec executable.
+
+## Installation using Anaconda
+
+We recommend you use Anaconda to create a coherent build environment and prevent
+dependency conflicts.
+
+Control over the installation can be had by editing `cmake_config.json`, to guide
+CMake to the right compilers etc.
+Configurations for different machines are stored in `${SPEC_ROOT}/cmake_machines`,
+to use these, link them to cmake_config.json: `ln -s cmake_config cmake_machines/`
+
+>[!TIP]
+>install as much as possible in your environment using the `conda` command,
+>only use 'pip' at the very end for the last packages.
+>if you have not added the `conda-forge` channel do so by
+>`conda config --add channels conda-forge`
+
+Get the repository and install the necessary compilers and libraries
+```bash
+git clone git@github.com:PrincetonUniversity/SPEC.git
+conda create -n "spec_wrapper" python=3.11 # create your environment for SPEC
+conda activate spec_wrapper
+conda install gcc_linux-64 gxx_linux-64 gfortran_linux-64 # or macOS versions, see note below
+conda install hdf5 openblas libopenblas fftw scalapack openmpi cmake ninja
+conda install h5py matplotlib f90nml scipy scikit-build mpi4py ipython
+pip install f90wrap
+```
+
+>[!NOTE]
+> for macOS users use the respective compiler packages;
+> `conda install clang_osx-64 clangxx_osx-64 gfortran_osx-64`
+
+
+Finally, install SPEC and the wrapper (logs will be in `compile.log`)
+```
+pip install -v . 2>&1 | tee compile.log
+```
+
+Install the `py_spec` python library
+```
+cd Utilities/pythontools/
+pip install -e .
+```
+
+### Troubleshooting Anaconda install
+If using a newer version of python, `f2py3` is no longer shipped. If your system contains an old python install (for example from your OS), CMake can find its `f2py3` and give try to use it to compile the wrappers instead of your environments `f2py`.
+Test this by looking if you have an `f2py3` in your path: `$which f2py3`.
+The easiest workaround is to create a link called f2py3 that links to f2py so it is found first.
+```
+ln -s ~/anaconda3/envs/spec_wrapper/bin/f2py ~/anaconda3/envs/spec_wrapper/bin/f2py3
+```
+
+You might have HDF5 or FFTW environment variables set (for example for a VMEC install). This can throw off CMake, which we want to use only anaconda.
+```
+unset HDF5, HDF5_ROOT, HDF5_HOME, FFTW, FFTW_DIR
+```
+
+
+
+### Testing your SPEC installation
+
+First, verify that the stand-alone executable is usable.
+A few test cases are provided in `InputFiles/TestCases`.
+
+Create a new directory for SPEC runs and change into it
+
+```bash
+mkdir ~/SPEC_runs
+cd ~/SPEC_runs
+```
+
+Copy a demo input file into the current working directory:
+
+```bash
+cp ~/SPEC/InputFiles/TestCases/G3V01L0Fi.001.sp .
+```
+
+Call SPEC with an input file (`*.sp`) as argument on the command line:
+
+```bash
+xspec G3V01L0Fi.001.sp
+```
+
+You should see the screen output of the SPEC run.
+Among the last lines should be something similar to this:
+
+```
+ending : 0.88 : myid= 0 ; completion ; time= 0.88s = 0.01m = 0.00h = 0.00d ; date= 2022/02/17 ; time= 17:35:33 ; ext = G1V02L0Fi.001
+ending : :
+xspech : :
+xspech : 0.88 : myid= 0 : time= 0.01m = 0.00h = 0.00d ;
+```
+
+This indicates that the stand-alone executable is usable.
+
+Next, the python wrapper is tested.
+
+1. Check that the SPEC version can be found:
+
+ ```bash
+ python -c "from spec import spec_f90wrapped as spec; print('SPEC version: {:}'.format(spec.constants.version))"
+ ```
+
+ This should print a message like "SPEC version: 3.1" on the screen.
+
+2. Check that the Python wrapper can be used as a stand-alone code:
+
+ ```bash
+ OMP_NUM_THREADS=1 python ~/SPEC/Utilities/python_wrapper/spec/core.py G3V01L0Fi.001.sp
+ ```
+
+ This should conclude with the message `SPEC called from python finished!`.
+
+3. Run the optimization example code:
+
+ ```bash
+ OMP_NUM_THREADS=1 python ~/SPEC/Utilities/python_wrapper/examples/example.py
+ ```
+
+ This should run a basic optimization problem,
+ where the SPEC inputs are controlled via `scipy.optimize`.
+
+4. Run the interactive re-convergence example code:
+
+ ```bash
+ OMP_NUM_THREADS=1 python ~/SPEC/Utilities/python_wrapper/examples/example_2.py
+ ```
+
+ This should compute a SPEC equilibrium, then change the central pressure,
+ re-converge SPEC, etc. for a set of five values of the central pressure
+ in a two-volume classical Stellarator case.
+ After the pressure scan with re-convergence,
+ a plot of the MHD energy vs. the central pressure is shown.
+
+
+## Other legacy installations
+It is still possible to compile SPEC using `make` or `cmake` directly, and bypass the wrapper installation.
+
+### CMake installation
+Spec can be installed using CMake to find the relevant libraries to link against.
+You can control
+in the root directory of SPEC do the following:
+```bash
+mkdir build
+cd build
+cmake ..
+make
+```
+This will compile SPEC (not the wrappers). The `xspec` executable is found in ${SPEC_ROOT}/build/build/bin/xspec
+
+### Make installation
+SPEC can also be installed using the `make` command in the root directory.
+
+The `make` install is controlled by the `BUILD_ENV` environment variable.
+Available options are found in the `SPECfile`
+where different link and compile flags for many machines are found.
+
+If you cannot find your machine in the list, copy a similar machine and adapt as needed.
+Then compile by running the command
+
+```bash
+BUILD_ENV= make
+```
+
+The `make` process creates files in the SPEC_ROOT directory, and creates the `xspec` executable there.
+
+
+## Build process
+the source files are found in the `${SPEC_ROOT}/src/ directory`.
+The `.f90` files contain macros that are expanded during the make process using the `m4` command.
+
+Depending on the build type, the macro-expanded code is either found in `build/src/`, in the root directory, or in the `_skbuild` folder.
+
+>[!TIP]
+>The line numbers in error messages correspond to the macro-expanded code
+
+The macros are defined in `src/macros`
diff --git a/Compile.md b/outdated_compilation_instructions.md
similarity index 100%
rename from Compile.md
rename to outdated_compilation_instructions.md
diff --git a/setup.py b/setup.py
index 8af1e4f2..e0ac7fad 100644
--- a/setup.py
+++ b/setup.py
@@ -38,7 +38,7 @@
setup(
name="spec",
- version="0.0.1",
+ version="0.0.3",
#license="MIT",
packages=['spec'],
package_dir={'': 'Utilities/python_wrapper'},
diff --git a/setup_conda.sh b/setup_conda.sh
deleted file mode 100755
index 12d93104..00000000
--- a/setup_conda.sh
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-# create conda environment for SPEC
-conda env create -f spec_conda_env.yml
-
-# make sure environment variables get managed correctly
-pushd ~/anaconda3/envs/spec_env
-mkdir -p ./etc/conda/activate.d
-mkdir -p ./etc/conda/deactivate.d
-
-echo "
-export OLD_LD_LIBRARY_PATH=\${LD_LIBRARY_PATH}
-export LD_LIBRARY_PATH=\${HOME}/anaconda3/envs/spec_env/lib:\${LD_LIBRARY_PATH}
-
-export FFTW_ROOT=\${HOME}/anaconda3/envs/spec_env
-" > ./etc/conda/activate.d/env_vars.sh
-
-echo "
-export LD_LIBRARY_PATH=\${OLD_LD_LIBRARY_PATH}
-unset OLD_LD_LIBRARY_PATH
-
-unset FFTW_ROOT
-" > ./etc/conda/deactivate.d/env_vars.sh
-
-popd
-
diff --git a/spec_conda_env.yml b/spec_conda_env.yml
deleted file mode 100644
index a34a03dd..00000000
--- a/spec_conda_env.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-name: spec_env
-channels:
- - conda-forge
- - defaults
-dependencies:
- - c-compiler
- - fortran-compiler
- - mpi4py
- - ninja
- - cmake
- - scikit-build
- - fftw
- - hdf5
- - numpy
- - openmp
- - openblas
- - matplotlib
- - scipy
-
diff --git a/src/bfield.f90 b/src/bfield.f90
index f0d000a5..5c2daa8c 100644
--- a/src/bfield.f90
+++ b/src/bfield.f90
@@ -167,7 +167,9 @@ subroutine bfield( zeta, st, Bst )
cput-cpus, lvol, zeta, st(1:2), dBu(3)
FATAL( bfield, abs(dBu(3)).lt.vsmall, field is not toroidal )
-
+ !if( abs( dBu(3)).lt.vsmall ) then
+ ! write(ounit,'("WARNING: bfield: field is not toroidal")')
+ !endif
endif
!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!
diff --git a/src/dfp200.f90 b/src/dfp200.f90
index 2015b3b6..311a7dfa 100644
--- a/src/dfp200.f90
+++ b/src/dfp200.f90
@@ -2110,12 +2110,12 @@ subroutine hessian3D_dFFdRZ(lvol, idof, innout, issym, irz, ii, dBB, XX, YY, len
!write(ounit,1000) 'values are:' Mvol, efcol1mn(1:mn)
!write(90,1000) efcol1mn(1:mn)
!1000 format(" "10x" "es23.15" ")
- !open(nm1unit, file="."//trim(ext)//".GF.hcol1", status="unknown", form="unformatted")
+ !open(nm1unit, file=trim(get_hidden(ext))//".GF.hcol1", status="unknown", form="unformatted")
!write(nm1unit) NGdof, Mvol
!write(nm1unit) efcol1mn(1:Ntz)
!close(nm1unit)
- !open(nm2unit, file="."//trim(ext)//".GF.hcol2", status="unknown", form="unformatted")
+ !open(nm2unit, file=trim(get_hidden(ext))//".GF.hcol2", status="unknown", form="unformatted")
!!write(nm2unit) NGdof, Mvol
!write(nm2unit) efcol2mn(1:Ntz)
!close(nm2unit)
diff --git a/src/global.f90 b/src/global.f90
index c69c6eb5..b02862b1 100644
--- a/src/global.f90
+++ b/src/global.f90
@@ -66,7 +66,7 @@ module constants
REAL, parameter :: mu0 = 2.0E-07 * pi2 !< \f$4\pi\cdot10^{-7}\f$
REAL, parameter :: goldenmean = 1.618033988749895 !< golden mean = \f$( 1 + \sqrt 5 ) / 2\f$ ;
- REAL, parameter :: version = 3.20 !< version of SPEC
+ REAL, parameter :: version = 3.23 !< version of SPEC
end module constants
@@ -246,10 +246,11 @@ module allglobal
!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!
- CHARACTER(LEN=1000) :: ext ! extension of input filename, i.e., "G3V01L1Fi.001" for an input file G3V01L1Fi.001.sp
+ CHARACTER(LEN=1000) :: ext ! extension of input filename, i.e., "path/G3V01L1Fi.001" for an input file path/G3V01L1Fi.001.sp
REAL :: ForceErr !< total force-imbalance
REAL :: Energy !< MHD energy
+ REAL :: BnsErr !< (in freeboundary) error in self-consistency of field on plasma boundary (Picard iteration)
REAL , allocatable :: IPDt(:), IPDtDpf(:,:) !< Toroidal pressure-driven current
@@ -948,6 +949,26 @@ subroutine set_mpi_comm(comm)
!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!
+pure function get_hidden(ext) result(hidden_ext)
+ implicit none
+ CHARACTER(len=1000), intent(in) :: ext
+ ! ext with a "." prefix added to the basename "path/.G3V01L1Fi.001" for an input file path/G3V01L1Fi.001.sp
+ CHARACTER(LEN=1000) :: hidden_ext
+ INTEGER :: basename_start_index
+
+ ! Prepare the "hidden" ext filepath that has a "." prefix.
+ ! Split ext into directory path and basename using INDEX function, then concatenate them again with a "." inbetween
+#ifdef _WIN32
+ basename_start_index = INDEX(ext, '\', .TRUE.)
+#else
+ basename_start_index = INDEX(ext, '/', .TRUE.)
+#endif
+ ! folder + . + filename
+ hidden_ext = trim(ext(1:basename_start_index))//"."//trim(ext(basename_start_index+1:))
+end function get_hidden
+
+!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!
+
subroutine read_inputlists_from_file()
use constants
@@ -1654,7 +1675,7 @@ subroutine wrtend
write(iunit,'(" adiabatic = ",257es23.15)') adiabatic(1:Mvol)
write(iunit,'(" mu = ",257es23.15)') mu(1:Mvol)
write(iunit,'(" Ivolume = ",257es23.15)') Ivolume(1:Mvol)
- write(iunit,'(" Isurf = ",257es23.15)') Isurf(1:Mvol-1)
+ write(iunit,'(" Isurf = ",257es23.15)') Isurf(1:Mvol-1), 0.0
write(iunit,'(" Lconstraint = ",i9 )') Lconstraint
write(iunit,'(" pl = ",257i23 )') pl(0:Mvol)
write(iunit,'(" ql = ",257i23 )') ql(0:Mvol)
diff --git a/src/hesian.f90 b/src/hesian.f90
index d4fb9e33..a9a15b81 100644
--- a/src/hesian.f90
+++ b/src/hesian.f90
@@ -1,7 +1,7 @@
!> \file
-!> \brief Computes eigenvalues and eigenvectors of derivative matrix, \f$\nabla_{\bf \xi}{\bf F}\f$.
+!> \brief Computes eigenvalues and eigenvectors of derivative matrix, \f$\nabla_{\bf xi}{\bf F}\f$.
-!> \brief Computes eigenvalues and eigenvectors of derivative matrix, \f$\nabla_{\bf \xi}{\bf F}\f$.
+!> \brief Computes eigenvalues and eigenvectors of derivative matrix, \f$\nabla_{\bf xi}{\bf F}\f$.
!> \ingroup grp_diagnostics
!>
!> @param[in] NGdof number of global degrees of freedom
@@ -26,7 +26,7 @@ subroutine hesian( NGdof, position, Mvol, mn, LGdof )
use cputiming, only : Thesian
- use allglobal, only : ncpu, myid, cpus, MPI_COMM_SPEC, ext, &
+ use allglobal, only : ncpu, myid, cpus, MPI_COMM_SPEC, ext, get_hidden, &
im, in, &
iRbc, iZbs, iRbs, iZbc, &
dRbc, dZbs, dRbs, dZbc, &
@@ -260,7 +260,7 @@ subroutine hesian( NGdof, position, Mvol, mn, LGdof )
xx(0,-2:2)= zero ; dRZ = 1.0E-04
write(svol,'(i3.3)')myid
-! open(lunit+myid,file="."//trim(ext)//".hessian."//svol,status="unknown")
+! open(lunit+myid,file=trim(get_hidden(ext))//".hessian."//svol,status="unknown")
! lmu(1:Nvol) = mu(1:Nvol) ; lpflux(1:Nvol) = pflux(1:Nvol) ; lhelicity(1:Nvol) = helicity(1:Nvol) ! save original profile information; 20 Jun 14;
@@ -402,7 +402,7 @@ subroutine hesian( NGdof, position, Mvol, mn, LGdof )
!> The eigenvalues and eigenvectors (if required) are written to the file \c .ext.GF.ev as follows:
!>
!> ```
-!> open(hunit,file="."//trim(ext)//".GF.ev",status="unknown",form="unformatted")
+!> open(hunit,file=trim(get_hidden(ext))//".GF.ev",status="unknown",form="unformatted")
!> write(hunit)NGdof,Ldvr,Ldvi ! integers; if only the eigenvalues were computed then Ldvr=Ldvi=1;
!> write(hunit)evalr(1:NGdof) ! reals ; real part of eigenvalues;
!> write(hunit)evali(1:NGdof) ! reals ; imaginary part of eigenvalues;
@@ -419,7 +419,7 @@ subroutine hesian( NGdof, position, Mvol, mn, LGdof )
if( LHmatrix ) then
if( myid.eq.0 ) then ; cput = GETTIME ; write(ounit,'("hesian : ",f10.2," : LHmatrix="L2" ;")')cput-cpus, LHmatrix ;
- open(munit, file="."//trim(ext)//".GF.ma", status="unknown", form="unformatted")
+ open(munit, file=trim(get_hidden(ext))//".GF.ma", status="unknown", form="unformatted")
write(munit) NGdof
write(munit) ohessian(1:NGdof,1:NGdof)
close(munit)
@@ -574,7 +574,7 @@ subroutine hesian( NGdof, position, Mvol, mn, LGdof )
if( myid.eq.0 ) then ! write to file; 04 Dec 14;
- open(hunit, file="."//trim(ext)//".GF.ev", status="unknown", form="unformatted")
+ open(hunit, file=trim(get_hidden(ext))//".GF.ev", status="unknown", form="unformatted")
write(hunit) NGdof, Ldvr, Ldvi
write(hunit) evalr
write(hunit) evali
diff --git a/src/newton.f90 b/src/newton.f90
index 7bd26216..ee2fadde 100644
--- a/src/newton.f90
+++ b/src/newton.f90
@@ -64,7 +64,7 @@ subroutine newton( NGdof, position, ihybrd )
use cputiming, only : Tnewton
- use allglobal, only : myid, ncpu, cpus, MPI_COMM_SPEC, ext, &
+ use allglobal, only : myid, ncpu, cpus, MPI_COMM_SPEC, ext, get_hidden, &
NOTstellsym, &
ForceErr, Energy, &
mn, im, in, iRbc, iZbs, iRbs, iZbc, Mvol, &
@@ -313,7 +313,7 @@ subroutine writereadgf( readorwrite, NGdof , ireadhessian )
use cputiming, only : Tnewton
- use allglobal, only : myid, cpus, MPI_COMM_SPEC, ext, &
+ use allglobal, only : myid, cpus, MPI_COMM_SPEC, ext, get_hidden, &
mn, im, in, hessian, Lhessianallocated
LOCALS
@@ -336,7 +336,7 @@ subroutine writereadgf( readorwrite, NGdof , ireadhessian )
! reset I/O state
ios = 0
- open( dunit, file="."//trim(ext)//".sp.DF", status="replace", form="unformatted", iostat=ios ) ! save derivative matrix to file;
+ open( dunit, file=trim(get_hidden(ext))//".sp.DF", status="replace", form="unformatted", iostat=ios ) ! save derivative matrix to file;
FATAL( newton, ios.ne.0, error opening derivative matrix file )
write( dunit, iostat=ios ) Igeometry, Istellsym, Lfreebound, Nvol, Mpol, Ntor, NGdof ! enable resolution consistency check;
@@ -352,11 +352,11 @@ subroutine writereadgf( readorwrite, NGdof , ireadhessian )
cput = GETTIME
- inquire( file="."//trim(ext)//".sp.DF", exist=exist ) ! the derivative matrix;
+ inquire( file=trim(get_hidden(ext))//".sp.DF", exist=exist ) ! the derivative matrix;
if( exist ) then ! 01234567890123456789012345678901
write(ounit,2000) cput-cpus, myid, "reading .ext.sp.DF ; "
- open( dunit, file="."//trim(ext)//".sp.DF", status="old", form="unformatted", iostat=ios )
+ open( dunit, file=trim(get_hidden(ext))//".sp.DF", status="old", form="unformatted", iostat=ios )
else ! 01234567890123456789012345678901
write(ounit,2000) cput-cpus, myid, ".ext.sp.DF does not exist ; "
inquire( file=".sp.DF", exist=exist ) ! the derivative matrix;
@@ -442,7 +442,7 @@ subroutine fcn1( NGdof, xx, fvec, irevcm )
use cputiming, only : Tnewton
- use allglobal, only : wrtend, myid, ncpu, cpus, MPI_COMM_SPEC, ext, &
+ use allglobal, only : wrtend, myid, ncpu, cpus, MPI_COMM_SPEC, ext, get_hidden, &
NOTstellsym, &
ForceErr, Energy, &
mn, im, in, iRbc, iZbs, iRbs, iZbc, Mvol, &
diff --git a/src/pp00aa.f90 b/src/pp00aa.f90
index dc91ff31..7d59bbb7 100644
--- a/src/pp00aa.f90
+++ b/src/pp00aa.f90
@@ -25,7 +25,7 @@
!>
!>~~~~~~~~~~~~
!> write(svol,'(i4.4)')lvol ! lvol labels volume;
-!> open(lunit+myid,file="."//trim(ext)//".poincare."//svol,status="unknown",form="unformatted")
+!> open(lunit+myid,file=trim(get_hidden(ext))//".poincare."//svol,status="unknown",form="unformatted")
!> do until end of file
!> write(lunit+myid) Nz, nPpts ! integers
!> write(lunit+myid) data(1:4,0:Nz-1,1:nPpts) ! doubles
@@ -55,7 +55,7 @@
!> The rotational-transform data is written to \c .ext.transform:xxxx , where \c xxxx is an integer indicating the volume.
!> The format of this file is as follows:
!> ```
-!> open(lunit+myid,file="."//trim(ext)//".sp.t."//svol,status="unknown",form="unformatted")
+!> open(lunit+myid,file=trim(get_hidden(ext))//".sp.t."//svol,status="unknown",form="unformatted")
!> write(lunit+myid) lnPtrj-ioff+1 ! integer
!> write(lunit+myid) diotadxup(0:1,0,lvol) ! doubles
!> write(lunit+myid) ( fiota(itrj,1:2), itrj = ioff, lnPtrj ) ! doubles
@@ -145,7 +145,7 @@ subroutine pp00aa
SALLOCATE( utflag, (ioff:lnPtrj ), 0 ) ! error flag that indicates if fieldlines successfully followed; 22 Apr 13;
SALLOCATE( fiota, (ioff:lnPtrj, 1:2 ), zero ) ! will always need fiota(0,1:2);
-!$OMP PARALLEL DO SHARED(lnPtrj,ioff,Wpp00aa,Nz,data,fiota,utflag,iota,oita,myid,vvol,cpus,Lconstraint,nPpts,ppts) PRIVATE(itrj,sti)
+!$OMP PARALLEL DO SHARED(lnPtrj,ioff,Wpp00aa,Nz,data,fiota,utflag,iota,oita,myid,vvol,cpus,Lconstraint,nPpts,ppts) PRIVATE(itrj,sti) SCHEDULE(dynamic)
do itrj = ioff, lnPtrj ! initialize Poincare plot with trajectories regularly spaced between interfaces along \t=0;
; sti(1:2) = (/ - one + itrj * two / lnPtrj , Ppts*pi /)
diff --git a/src/ra00aa.f90 b/src/ra00aa.f90
index 81553e76..0cc88505 100644
--- a/src/ra00aa.f90
+++ b/src/ra00aa.f90
@@ -24,7 +24,7 @@
!>
!> - The format of the files containing the vector potential is as follows:
!> ```
-!> open(aunit, file="."//trim(ext)//".sp.A", status="replace", form="unformatted" )
+!> open(aunit, file=trim(get_hidden(ext))//".sp.A", status="replace", form="unformatted" )
!> write(aunit) Mvol, Mpol, Ntor, mn, Nfp ! integers;
!> write(aunit) im(1:mn) ! integers; poloidal modes;
!> write(aunit) in(1:mn) ! integers; toroidal modes;
@@ -57,7 +57,7 @@ subroutine ra00aa( writeorread )
use cputiming, only : Tra00aa
- use allglobal, only : myid, ncpu, cpus, MPI_COMM_SPEC, ext, Mvol, mn, im, in, Ate, Aze, Ato, Azo
+ use allglobal, only : myid, ncpu, cpus, MPI_COMM_SPEC, ext, get_hidden, Mvol, mn, im, in, Ate, Aze, Ato, Azo
use sphdf5, only : write_vector_potential
@@ -148,12 +148,12 @@ subroutine ra00aa( writeorread )
if( myid.eq.0 ) then
- inquire(file="."//trim(ext)//".sp.A",exist=exist)
+ inquire(file=trim(get_hidden(ext))//".sp.A",exist=exist)
if( .not.exist ) then ; write(ounit,'("ra00aa : ",f10.2," : myid=",i3," ; error ; .ext.sp.A does not exist ;")') cput-cpus, myid ; goto 9998
endif
- open(aunit,file="."//trim(ext)//".sp.A",status="old",form="unformatted",iostat=ios) ! this will contain initial guess for vector potential;
+ open(aunit,file=trim(get_hidden(ext))//".sp.A",status="old",form="unformatted",iostat=ios) ! this will contain initial guess for vector potential;
if( ios.ne.0 ) then ; write(ounit,'("ra00aa : ",f10.2," : myid=",i3," ; error ; opening .ext.sp.A ;")') cput-cpus, myid ; goto 9997
endif
diff --git a/src/sphdf5.f90 b/src/sphdf5.f90
index 43aca629..756414c9 100644
--- a/src/sphdf5.f90
+++ b/src/sphdf5.f90
@@ -365,6 +365,7 @@ subroutine mirror_input_to_outfile
HWRITELV( grpInputDiagnostics, 1, LHevalues , (/ LHevalues /))
HWRITELV( grpInputDiagnostics, 1, LHevectors , (/ LHevectors /))
HWRITELV( grpInputDiagnostics, 1, LHmatrix , (/ LHmatrix /))
+ HWRITELV( grpInputDiagnostics, 1, Ltransform , (/ Ltransform /))
HWRITEIV( grpInputDiagnostics, 1, Lperturbed , (/ Lperturbed /))
HWRITEIV( grpInputDiagnostics, 1, dpp , (/ dpp /))
HWRITEIV( grpInputDiagnostics, 1, dqq , (/ dqq /))
@@ -981,7 +982,7 @@ subroutine hdfint
use fileunits, only : ounit
use inputlist
use allglobal, only : ncpu, cpus, &
- Mvol, ForceErr, &
+ Mvol, ForceErr, BnsErr,&
mn, im, in, iRbc, iZbs, iRbs, iZbc, &
mns, ims, ins, &
dRbc, dZbs, dRbs, dZbc, &
@@ -1041,8 +1042,8 @@ subroutine hdfint
HWRITERA( grpOutput, mn, (Mvol+1), Rbs, iRbs(1:mn,0:Mvol) )
!latex \type{iZbc(1:mn,0:Mvol)} & real & \pb{Fourier harmonics, $Z_{m,n}$, of interfaces} \\
HWRITERA( grpOutput, mn, (Mvol+1), Zbc, iZbc(1:mn,0:Mvol) )
-!l tex \type{forcetol} & real & \pb{force-balance error across interfaces} \\
-! HWRITERV( grpOutput, 1, forcetol, (/ forcetol /)) ! already in /input/global
+!latex \type{BnsErr} & real & \pb{error in self-consistency of field on plasma boundary (in freeboundary)} \\
+ HWRITERV( grpOutput, 1, BnsErr, (/ BnsErr /)) ! already in /input/global
!latex \type{ForceErr} & real & \pb{force-balance error across interfaces} \\
HWRITERV( grpOutput, 1, ForceErr, (/ ForceErr /))
!latex \type{Ivolume} & real & \pb{Volume current at output (parallel, externally induced)}
diff --git a/src/tr00ab.f90 b/src/tr00ab.f90
index 8a6b973b..260f19ce 100644
--- a/src/tr00ab.f90
+++ b/src/tr00ab.f90
@@ -767,6 +767,7 @@ subroutine tr00ab( lvol, mn, NN, Nt, Nz, iflag, ldiota ) ! construct straight-fi
work(1:Lwork), Lwork, iwork(1:Liwork), idgelsd )
ldiota(innout,0) = dlambda(1,0)
+ dlambdaout(1:NN, lvol, innout) = dlambda(1:NN,0)
case( 1 ) ! Lsvdiota = 1; jderiv = 1; 02 Sep 14;
diff --git a/src/xspech.f90 b/src/xspech.f90
index 05fbcc0a..1389b232 100644
--- a/src/xspech.f90
+++ b/src/xspech.f90
@@ -204,7 +204,7 @@ subroutine read_command_args
use fileunits, only: ounit
use inputlist, only: Wreadin
- use allglobal, only: cpus, myid, ext, MPI_COMM_SPEC, write_spec_namelist
+ use allglobal, only: cpus, myid, ext, get_hidden, MPI_COMM_SPEC, write_spec_namelist
LOCALS
@@ -308,7 +308,7 @@ subroutine spec
Lcoordinatesingularity, Lplasmaregion, Lvacuumregion, &
dtflux, dpflux, &
ImagneticOK, &
- ForceErr, &
+ ForceErr, BnsErr,&
efmn, ofmn, cfmn, sfmn, &
iBns, iBnc, iVns, iVnc, &
Ate, Aze, Ato, Azo, & ! only required for debugging; 09 Mar 17;
@@ -326,7 +326,7 @@ subroutine spec
LOGICAL :: LComputeDerivatives, LContinueFreeboundaryIterations, exist, LupdateBn, LComputeAxis
INTEGER :: imn, lmn, lNfp, lim, lin, ii, ideriv, stat
INTEGER :: vvol, ifail, wflag, iflag, vflag
- REAL :: rflag, lastcpu, bnserr, lRwc, lRws, lZwc, lZws, lItor, lGpol, lgBc, lgBs
+ REAL :: rflag, lastcpu, lRwc, lRws, lZwc, lZws, lItor, lGpol, lgBc, lgBs
REAL, allocatable :: position(:), gradient(:)
CHARACTER :: pack
INTEGER :: Lfindzero_old, mfreeits_old
@@ -770,7 +770,7 @@ end subroutine spec
subroutine final_diagnostics
use inputlist, only: nPtrj, nPpts, Igeometry, Lcheck, Nvol, odetol, &
- Isurf, Ivolume, mu, Wmacros, Ltransform
+ Isurf, Ivolume, mu, Wmacros, Ltransform, Lsvdiota
use fileunits, only: ounit
use constants, only: zero
use allglobal, only: pi2, myid, ncpu, MPI_COMM_SPEC, cpus, Mvol, Ntz, mn, &
@@ -838,6 +838,8 @@ subroutine final_diagnostics
! Evaluate rotational transform and straight field line coordinate transformation
if( Ltransform ) then
+ FATAL(xspech, Lsvdiota.ne.1, Lsvdiota needs to be one for s.f.l transformation)
+
do vvol=1,Mvol
call brcast(vvol)
enddo
@@ -876,7 +878,8 @@ subroutine final_diagnostics
LREGION(vvol)
do iocons = 0, 1
- if( ( Lcoordinatesingularity .and. iocons.eq.0 ) .or. ( Lvacuumregion .and. iocons.eq.1 ) ) cycle
+ if( Lcoordinatesingularity .and. iocons.eq.0 ) cycle
+ if( vvol.eq.Nvol+1 .and. iocons.eq.1 ) cycle
! Compute covariant magnetic field at interface
call lbpol(vvol, Bt00(1:Mvol, 0:1, -1:2), 0, iocons)