Merged in dev_312 (pull request #3)

Raiju additions + Documentation fixes

Approved-by: Eric Winter
Approved-by: Michael Wiltberger
This commit is contained in:
Nikhil Rao
2025-06-18 19:10:12 +00:00
51 changed files with 2603 additions and 637 deletions

View File

@@ -1,13 +1,30 @@
Copyright 2023 Johns Hopkins University Applied Physics Laboratory
Copyright 2023 US National Science Foundation National Center for Atmospheric Research
Copyright 2023 Rice University
Copyright 2023 Johns Hopkins University Applied Physics Laboratory
Copyright 2023 US National Science Foundation National Center for Atmospheric Research
Copyright 2023 Rice University
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
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.
1. 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.
2. 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.
Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
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 HOLDER 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.
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
HOLDER 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.

View File

@@ -1,17 +1,9 @@
<p align="center">
<img src="docs/source/_static/kaipy-logo.png" alt="Logo" width="200"/>
</p>
<p align="center">
Python Tools for Analyzing and Visualizing Kaiju Results
</p>
# README #
Kaipy is a Python package for analysis and visualization of simulation
results from a scientific software package Kaiju. Kaiju includes the
[Multiscale Atmosphere-Geospace Environment (MAGE)
](https://cgs.jhuapl.edu/Models/mage.php) model developed by the NASA
](https://cgs.jhuapl.edu/Models/) model developed by the NASA
DRIVE [Center for Geospace Storms](https://cgs.jhuapl.edu/) as well as
other scientific software for simulation of heliospheric environments such
as planetary magnetospheres and the solar wind.
@@ -22,7 +14,7 @@ Current documentation for this package available via our [Read The Docs website]
### License ###
Kaipy is distributed under the [BSD 3-Clause license](https://bitbucket.org/aplkaiju/kaipy/src/master/LICENSE.md).
Kaipy is distributed under the [BSD 3-Clause license](LICENSE.md).
### What is this repository for? ###
@@ -32,14 +24,14 @@ pip from [https://pypi.org/project/kaipy/](PyPi).
### How do I get set up? ###
* ```pip install kaipy```.
```pip install kaipy```.
### Contribution guidelines ###
* All contributions should be made by forking this repository and submitting a pull request.
All contributions should be made by forking this repository and submitting a pull request.
### Who do I talk to? ###
* For more information about the Kaipy project contact [Michael Wiltberger](mailto:wiltbemj@ucar.edu?subject=Kaipy).
For more information about the Kaipy project contact [Michael Wiltberger](mailto:wiltbemj@ucar.edu?subject=Kaipy).

View File

@@ -68,7 +68,7 @@ html_theme_options = {
'logo_only': True,
'display_version': False,
'collapse_navigation': False,
'navigation_depth': 3,
'navigation_depth': 4,
}
html_css_files = [

View File

@@ -14,7 +14,7 @@ other scientific software for simulation of heliospheric environments such
as planetary magnetospheres and the solar wind.
.. toctree::
:maxdepth: 3
:maxdepth: 4
:caption: Kaipy:
kaipy/installation

View File

@@ -1,8 +1,8 @@
Chimp package
===================
================================================
kaipy.chimp.chimph5p module
---------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.chimp.chimph5p
:members:
@@ -10,7 +10,7 @@ kaipy.chimp.chimph5p module
:show-inheritance:
kaipy.chimp.chimpviz module
---------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.chimp.chimpviz
:members:
@@ -18,17 +18,10 @@ kaipy.chimp.chimpviz module
:show-inheritance:
kaipy.chimp.kCyl module
-----------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.chimp.kCyl
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: kaipy.chimp
:members:
:undoc-members:
:show-inheritance:

View File

@@ -1,8 +1,8 @@
Gamera package
====================
================================================
kaipy.gamera.deltabViz module
-----------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamera.deltabViz
:members:
@@ -10,7 +10,7 @@ kaipy.gamera.deltabViz module
:show-inheritance:
kaipy.gamera.gamGrids module
----------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamera.gamGrids
:members:
@@ -18,7 +18,7 @@ kaipy.gamera.gamGrids module
:show-inheritance:
kaipy.gamera.gampp module
-------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamera.gampp
:members:
@@ -26,7 +26,7 @@ kaipy.gamera.gampp module
:show-inheritance:
kaipy.gamera.magsphere module
-----------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamera.magsphere
:members:
@@ -34,7 +34,7 @@ kaipy.gamera.magsphere module
:show-inheritance:
kaipy.gamera.magsphereRescale module
------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamera.magsphereRescale
:members:
@@ -42,7 +42,7 @@ kaipy.gamera.magsphereRescale module
:show-inheritance:
kaipy.gamera.msphViz module
---------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamera.msphViz
:members:
@@ -50,7 +50,7 @@ kaipy.gamera.msphViz module
:show-inheritance:
kaipy.gamera.rcmpp module
-------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamera.rcmpp
:members:
@@ -58,17 +58,9 @@ kaipy.gamera.rcmpp module
:show-inheritance:
kaipy.gamera.remixpp module
---------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamera.remixpp
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: kaipy.gamera
:members:
:undoc-members:
:show-inheritance:

View File

@@ -1,85 +0,0 @@
kaipy.gamhelio.lib package
==========================
Submodules
----------
kaipy.gamhelio.lib.ace module
-----------------------------
.. automodule:: kaipy.gamhelio.lib.ace
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.cspice module
--------------------------------
.. automodule:: kaipy.gamhelio.lib.cspice
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.lfmhlib module
---------------------------------
.. automodule:: kaipy.gamhelio.lib.lfmhlib
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.mas module
-----------------------------
.. automodule:: kaipy.gamhelio.lib.mas
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.msgr module
------------------------------
.. automodule:: kaipy.gamhelio.lib.msgr
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.poisson module
---------------------------------
.. automodule:: kaipy.gamhelio.lib.poisson
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.util module
------------------------------
.. automodule:: kaipy.gamhelio.lib.util
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.wsa module
-----------------------------
.. automodule:: kaipy.gamhelio.lib.wsa
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.wsa2h5 module
--------------------------------
.. automodule:: kaipy.gamhelio.lib.wsa2h5
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: kaipy.gamhelio.lib
:members:
:undoc-members:
:show-inheritance:

View File

@@ -1,20 +1,11 @@
Gamhelio package
======================
Subpackages
-----------
.. toctree::
:maxdepth: 4
kaipy.gamhelio.lib
kaipy.gamhelio.wsa2gamera
================================================
Primary Package
----------
------------------------------------------------
kaipy.gamhelio.helioViz module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamhelio.helioViz
:members:
@@ -22,7 +13,7 @@ kaipy.gamhelio.helioViz module
:show-inheritance:
kaipy.gamhelio.heliosphere module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamhelio.heliosphere
:members:
@@ -30,96 +21,24 @@ kaipy.gamhelio.heliosphere module
:show-inheritance:
Lib Package
----------
kaipy.gamhelio.lib.ace module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamhelio.lib.ace
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.cspice module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamhelio.lib.cspice
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.lfmhlib module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamhelio.lib.lfmhlib
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.mas module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamhelio.lib.mas
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.msgr module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamhelio.lib.msgr
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.poisson module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamhelio.lib.poisson
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.util module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamhelio.lib.util
:members:
:undoc-members:
:show-inheritance:
------------------------------------------------
kaipy.gamhelio.lib.wsa module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamhelio.lib.wsa
:members:
:undoc-members:
:show-inheritance:
kaipy.gamhelio.lib.wsa2h5 module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamhelio.lib.wsa2h5
:members:
:undoc-members:
:show-inheritance:
wsa2gamera Package
----------
------------------------------------------------
kaipy.gamhelio.wsa2gamera.params module
---------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.gamhelio.wsa2gamera.params
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: kaipy.gamhelio
:members:
:undoc-members:
:show-inheritance:

View File

@@ -1,21 +0,0 @@
kaipy.gamhelio.wsa2gamera package
=================================
Submodules
----------
kaipy.gamhelio.wsa2gamera.params module
---------------------------------------
.. automodule:: kaipy.gamhelio.wsa2gamera.params
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: kaipy.gamhelio.wsa2gamera
:members:
:undoc-members:
:show-inheritance:

View File

@@ -1,11 +1,9 @@
Paraview package
======================
================================================
Submodules
----------
kaipy.paraview.pvGam module
---------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.paraview.pvGam
:members:
@@ -13,17 +11,9 @@ kaipy.paraview.pvGam module
:show-inheritance:
kaipy.paraview.pvutils module
-----------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.paraview.pvutils
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: kaipy.paraview
:members:
:undoc-members:
:show-inheritance:

View File

@@ -0,0 +1,83 @@
Raiju package
================================================
Primary Package
------------------------------------------------
kaipy.raiju.dst module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.raiju.dst
:members:
:undoc-members:
:show-inheritance:
kaipy.raiju.m2m module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.raiju.m2m
:members:
:undoc-members:
:show-inheritance:
kaipy.raiju.raijuUtils module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.raiju.raijuUtils
:members:
:undoc-members:
:show-inheritance:
Lambdautils Package
------------------------------------------------
kaipy.raiju.lambdautils.AlamData module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.raiju.lambdautils.AlamData
:members:
:undoc-members:
:show-inheritance:
kaipy.raiju.lambdautils.AlamParams module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.raiju.lambdautils.AlamParams
:members:
:undoc-members:
:show-inheritance:
kaipy.raiju.lambdautils.DistTypes module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.raiju.lambdautils.DistTypes
:members:
:undoc-members:
:show-inheritance:
kaipy.raiju.lambdautils.fileIO module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.raiju.lambdautils.fileIO
:members:
:undoc-members:
:show-inheritance:
waveModel Package
------------------------------------------------
kaipy.raiju.waveModel.genWM module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.raiju.waveModel.genWM
:members:
:undoc-members:
:show-inheritance:
kaipy.raiju.waveModel.wmData module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.raiju.waveModel.wmData
:members:
:undoc-members:
:show-inheritance:

View File

@@ -1,61 +0,0 @@
kaipy.rcm.lambdautils package
=============================
Submodules
----------
kaipy.rcm.lambdautils.AlamData module
-------------------------------------
.. automodule:: kaipy.rcm.lambdautils.AlamData
:members:
:undoc-members:
:show-inheritance:
kaipy.rcm.lambdautils.AlamParams module
---------------------------------------
.. automodule:: kaipy.rcm.lambdautils.AlamParams
:members:
:undoc-members:
:show-inheritance:
kaipy.rcm.lambdautils.DistTypes module
--------------------------------------
.. automodule:: kaipy.rcm.lambdautils.DistTypes
:members:
:undoc-members:
:show-inheritance:
kaipy.rcm.lambdautils.fileIO module
-----------------------------------
.. automodule:: kaipy.rcm.lambdautils.fileIO
:members:
:undoc-members:
:show-inheritance:
kaipy.rcm.lambdautils.genAlam module
------------------------------------
.. automodule:: kaipy.rcm.lambdautils.genAlam
:members:
:undoc-members:
:show-inheritance:
kaipy.rcm.lambdautils.plotter module
------------------------------------
.. automodule:: kaipy.rcm.lambdautils.plotter
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: kaipy.rcm.lambdautils
:members:
:undoc-members:
:show-inheritance:

View File

@@ -1,20 +1,11 @@
RCM package
=================
Subpackages
-----------
.. toctree::
:maxdepth: 4
kaipy.rcm.lambdautils
kaipy.rcm.wmutils
================================================
Primary Package
----------
------------------------------------------------
kaipy.rcm.rcminit module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.rcm.rcminit
:members:
@@ -22,7 +13,7 @@ kaipy.rcm.rcminit module
:show-inheritance:
kaipy.rcm.rcmutils module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.rcm.rcmutils
:members:
@@ -30,7 +21,7 @@ kaipy.rcm.rcmutils module
:show-inheritance:
kaipy.rcm.rcmxdmf module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.rcm.rcmxdmf
:members:
@@ -38,10 +29,10 @@ kaipy.rcm.rcmxdmf module
:show-inheritance:
Lambdautils Package
----------
------------------------------------------------
kaipy.rcm.lambdautils.AlamData module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.rcm.lambdautils.AlamData
:members:
@@ -49,7 +40,7 @@ kaipy.rcm.lambdautils.AlamData module
:show-inheritance:
kaipy.rcm.lambdautils.AlamParams module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.rcm.lambdautils.AlamParams
:members:
@@ -57,7 +48,7 @@ kaipy.rcm.lambdautils.AlamParams module
:show-inheritance:
kaipy.rcm.lambdautils.DistTypes module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.rcm.lambdautils.DistTypes
:members:
@@ -65,7 +56,7 @@ kaipy.rcm.lambdautils.DistTypes module
:show-inheritance:
kaipy.rcm.lambdautils.fileIO module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.rcm.lambdautils.fileIO
:members:
@@ -73,7 +64,7 @@ kaipy.rcm.lambdautils.fileIO module
:show-inheritance:
kaipy.rcm.lambdautils.genAlam module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.rcm.lambdautils.genAlam
:members:
@@ -81,7 +72,7 @@ kaipy.rcm.lambdautils.genAlam module
:show-inheritance:
kaipy.rcm.lambdautils.plotter module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.rcm.lambdautils.plotter
:members:
@@ -90,10 +81,10 @@ kaipy.rcm.lambdautils.plotter module
Wmutils Package
----------
------------------------------------------------
kaipy.rcm.wmutils.genWM module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.rcm.wmutils.genWM
:members:
@@ -101,16 +92,9 @@ kaipy.rcm.wmutils.genWM module
:show-inheritance:
kaipy.rcm.wmutils.wmData module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.rcm.wmutils.wmData
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: kaipy.rcm
:members:
:undoc-members:
:show-inheritance:

View File

@@ -1,29 +0,0 @@
kaipy.rcm.wmutils package
=========================
Submodules
----------
kaipy.rcm.wmutils.genWM module
------------------------------
.. automodule:: kaipy.rcm.wmutils.genWM
:members:
:undoc-members:
:show-inheritance:
kaipy.rcm.wmutils.wmData module
-------------------------------
.. automodule:: kaipy.rcm.wmutils.wmData
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: kaipy.rcm.wmutils
:members:
:undoc-members:
:show-inheritance:

View File

@@ -1,21 +1,10 @@
Remix package
===================
Submodules
----------
================================================
kaipy.remix.remix module
------------------------
------------------------------------------------
.. automodule:: kaipy.remix.remix
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: kaipy.remix
:members:
:undoc-members:
:show-inheritance:

View File

@@ -1,26 +1,8 @@
kaipy package
=============
Subpackages
-----------
.. toctree::
:maxdepth: 4
kaipy.chimp
kaipy.gamera
kaipy.gamhelio
kaipy.paraview
kaipy.rcm
kaipy.remix
kaipy.satcomp
kaipy.solarWind
Submodules
----------
================================================
kaipy.cdaweb\_utils module
--------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.cdaweb_utils
:members:
@@ -28,7 +10,7 @@ kaipy.cdaweb\_utils module
:show-inheritance:
kaipy.embiggenUtils module
--------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.embiggenUtils
:members:
@@ -36,7 +18,7 @@ kaipy.embiggenUtils module
:show-inheritance:
kaipy.kJobs module
------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.kJobs
:members:
@@ -44,7 +26,7 @@ kaipy.kJobs module
:show-inheritance:
kaipy.kaiH5 module
------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.kaiH5
:members:
@@ -52,7 +34,7 @@ kaipy.kaiH5 module
:show-inheritance:
kaipy.kaiTools module
---------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.kaiTools
:members:
@@ -60,7 +42,7 @@ kaipy.kaiTools module
:show-inheritance:
kaipy.kaiViz module
-------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.kaiViz
:members:
@@ -68,7 +50,7 @@ kaipy.kaiViz module
:show-inheritance:
kaipy.kaijson module
--------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.kaijson
:members:
@@ -76,7 +58,7 @@ kaipy.kaijson module
:show-inheritance:
kaipy.kaixdmf module
--------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.kaixdmf
:members:
@@ -84,23 +66,15 @@ kaipy.kaixdmf module
:show-inheritance:
kaipy.kdefs module
------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.kdefs
:members:
:undoc-members:
:show-inheritance:
kaipy.lfm2kaiju module
----------------------
.. automodule:: kaipy.lfm2kaiju
:members:
:undoc-members:
:show-inheritance:
kaipy.supermage module
----------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.supermage
:members:
@@ -108,17 +82,9 @@ kaipy.supermage module
:show-inheritance:
kaipy.transform module
----------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.transform
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: kaipy
:members:
:undoc-members:
:show-inheritance:

View File

@@ -1,8 +1,8 @@
Satcomp package
===================
================================================
kaipy.satcomp.scRCM module
---------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.satcomp.scRCM
:members:
@@ -10,17 +10,9 @@ kaipy.satcomp.scRCM module
:show-inheritance:
kaipy.satcomp.scutils module
---------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.satcomp.scutils
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: kaipy.satcomp
:members:
:undoc-members:
:show-inheritance:

View File

@@ -1,19 +1,8 @@
SolarWind package
=======================
Submodules
----------
kaipy.solarWind.CUSTOM module
-----------------------------
.. automodule:: kaipy.solarWind.CUSTOM
:members:
:undoc-members:
:show-inheritance:
================================================
kaipy.solarWind.OMNI module
---------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.solarWind.OMNI
:members:
@@ -21,7 +10,7 @@ kaipy.solarWind.OMNI module
:show-inheritance:
kaipy.solarWind.SolarWind module
--------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.solarWind.SolarWind
:members:
@@ -29,7 +18,7 @@ kaipy.solarWind.SolarWind module
:show-inheritance:
kaipy.solarWind.TimeSeries module
---------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.solarWind.TimeSeries
:members:
@@ -37,7 +26,7 @@ kaipy.solarWind.TimeSeries module
:show-inheritance:
kaipy.solarWind.WIND module
---------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.solarWind.WIND
:members:
@@ -46,17 +35,9 @@ kaipy.solarWind.WIND module
kaipy.solarWind.swBCplots module
--------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: kaipy.solarWind.swBCplots
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: kaipy.solarWind
:members:
:undoc-members:
:show-inheritance:
:show-inheritance:

View File

@@ -1,9 +1,10 @@
Developers
=====
================================================
Kaipy developers will need to use a different setup process then users. This section will go over the steps needed to setup a development environment for Kaipy. The main difference here is that you not use the `pip install` command to install Kaipy. Instead you will need to clone the repository, install the dependencies, and setup the environment variables.
Clone repository
---------
------------------------------------------------
The first step is to clone the Kaipy repository. You can do this by running the following command in your terminal:
.. code-block:: bash
@@ -13,7 +14,8 @@ The first step is to clone the Kaipy repository. You can do this by running the
For beta testers using the kaipy-private repository and the kaiju-private repository you will need to switch both repositories to the `kaipy-amputation` branch.
Install python dependencies
---------
------------------------------------------------
Next you will need to install the dependencies for Kaipy. You can do this by running the following command in your terminal after navigating to the Kaipy repository:
.. code-block:: bash
@@ -23,7 +25,8 @@ Next you will need to install the dependencies for Kaipy. You can do this by ru
pip install -r requirements.txt
Setup environment variables
---------
------------------------------------------------
Finally you will need to setup the environment variables for Kaipy. You can do this by running the following command in your terminal after navigating to the Kaipy repository:
For bash shell:

View File

@@ -1,8 +1,8 @@
Installation
============
================================================
Conda Installation
~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Download Miniconda Installer
@@ -48,7 +48,7 @@ Conda Installation
- To apply the changes, close and reopen your terminal window.
Creating Environment
~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create python environment. We support using python 3.10 through python 3.12.
@@ -61,7 +61,7 @@ Create python environment. We support using python 3.10 through python 3.12.
conda create --name kaipy python=3.12
Installing kaipy
~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To install kaipy, run the following command:

View File

@@ -1,5 +1,5 @@
Requirements
============
================================================
kaipy requires:

View File

@@ -1,13 +1,16 @@
Usage
=====
================================================
The Kaipy package comes with a variety of tools to help you load and analyze data from the MAGE model. This page will walk you through the basic usage of the package. This includes using the API to load datasets and create plots as well as using the command line interface to run scripts.
Kaipy API Package
---------
------------------------------------------------
We will go over the basics of loading datasets and creating plots using the Kaipy API package. You can try this out for yourself using our `Google Colab notebook <https://colab.research.google.com/drive/1Y559nAryHyX5R9wgqSLvZ-87QRmazGLD#scrollTo=0bOWk7gnNzd2>`_.
Loading datasets
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In order to load data for the GAMERA and MIX components of the MAGE model you will need to import the following modules:
.. code-block:: python
@@ -40,7 +43,8 @@ Importing the ionospheric data from REMIX follow the same format as the import o
ion.init_vars('NORTH')
Plots
~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The msphViz portion of the kaipy library has numerous routines for visualizing the magnetosphere. Here will demostrate usage of plotXY and plotXZ which make plots of the equatorial and meridional cuts of the magnetosphere. For both of these routines and others in system you need to provide the instance of the magnetosphere object, the step number you want to display, the extent of the domain, and two sets of axes. The first axes object is for the plot and the second is for the colorbar. For plotXZ we will use the minimal set arguments which results in a plot density. For the plotXY example we will specify options so that we end up with Vx on Red/Blue color palette with a mid point normalization.
First the plotXZ example
@@ -88,7 +92,8 @@ The mix object includes an extensive plotting routine that has the capability fo
:align: center
Kaipy Command Line Interface
---------
------------------------------------------------
The Kaipy package also comes with a command line interface that allows you to run scripts to analyze MAGE model data. The CLI is a great way to automate the analysis of large datasets. The CLI is run from the terminal and has a variety of options to customize the analysis.
A complete list of the available scripts can be found at the `Scripts documentation <https://kaipy-docs.readthedocs.io/en/latest/scripts.html>`_.

View File

@@ -1,7 +0,0 @@
module list
=====
.. toctree::
:maxdepth: 4
kaipy

View File

@@ -1,14 +1,16 @@
Kaipy Package API Index
========================
================================================
.. toctree::
:maxdepth: 1
Kaipy Package <kaipy>
Chimp Package <kaipy.chimp>
Gamera Package <kaipy.gamera>
Gamhelio Package <kaipy.gamhelio>
Paraview Package <kaipy.paraview>
RCM Package <kaipy.rcm>
Raiju Package <kaipy.raiju>
Remix Package <kaipy.remix>
Satcomp Package <kaipy.satcomp>
SolarWind Package <kaipy.solarWind>

View File

@@ -1,167 +1,189 @@
Command Line Scripts
================
================================================
Quicklook
---------
------------------------------------------------
The quicklook directory has scripts that are used to quickly look at the data. The scripts are written in python and use the matplotlib library to plot the data. The scripts are:
.. .. autoprogram:: dbpic:create_command_line_parser()
:prog: dbpic.py
.. autoprogram:: dbVid:create_command_line_parser()
:prog: dbVid.py
:prog: dbVid
.. autoprogram:: dstpic:create_command_line_parser()
:prog: dstpic.py
:prog: dstpic
.. autoprogram:: gamerrpic:create_command_line_parser()
:prog: gamerrpic.py
:prog: gamerrpic
.. autoprogram:: gamerrVid:create_command_line_parser()
:prog: gamerrVid.py
:prog: gamerrVid
.. autoprogram:: gamsphVid:create_command_line_parser()
:prog: gamsphVid.py
:prog: gamsphVid
.. autoprogram:: heliomovie:create_command_line_parser()
:prog: heliomovie.py
:prog: heliomovie
.. autoprogram:: heliopic:create_command_line_parser()
:prog: heliopic.py
:prog: heliopic
.. autoprogram:: mixpic:create_command_line_parser()
:prog: mixpic.py
:prog: mixpic
.. autoprogram:: msphpic:create_command_line_parser()
:prog: msphpic.py
:prog: msphpic
.. autoprogram:: raijupic:create_command_line_parser()
:prog: raijupic
.. autoprogram:: rcmDataProbe:create_command_line_parser()
:prog: rcmDataProbe.py
:prog: rcmDataProbe
.. autoprogram:: rcmpic:create_command_line_parser()
:prog: rcmpic.py
:prog: rcmpic
.. autoprogram:: remixTimeSeries:create_command_line_parser()
:prog: remixTimeSeries.py
:prog: remixTimeSeries
.. autoprogram:: swpic:create_command_line_parser()
:prog: swpic.py
:prog: swpic
.. autoprogram:: vizTrj:create_command_line_parser()
:prog: vizTrj.py
:prog: vizTrj
Preprocessing
-------------
------------------------------------------------
The preprocessing directory has scripts that are used to setup MAGE simulations including grid generation and solar wind input file. The scripts are:
.. autoprogram:: cda2wind:create_command_line_parser()
:prog: cda2wind.py
:prog: cda2wind
.. autoprogram:: genLFM:create_command_line_parser()
:prog: genLFM.py
:prog: genLFM
.. autoprogram:: genRCM:create_command_line_parser()
:prog: genRCM.py
:prog: genRCM
.. autoprogram:: genRAIJU:create_command_line_parser()
:prog: genRAIJU
.. .. autoprogram:: INIGenerator:parse_args()
:prog: INIGenerator.py
.. autoprogram:: wsa2gamera:create_command_line_parser()
:prog: wsa2gamera.py
:prog: wsa2gamera
.. autoprogram:: XMLGenerator:create_command_line_parser()
:prog: XMLGenerator.py
:prog: XMLGenerator
Postprocessing
----------------
------------------------------------------------
The postprocessing directory has scripts that are used to process MAGE simulations including data analysis and visualization. The scripts are:
.. .. autoprogram:: block_genmpiXDMF:create_command_line_parser()
:prog: block_genmpiXDMF.py
.. autoprogram:: embiggen:create_command_line_parser()
:prog: embiggen.py
:prog: embiggen
.. autoprogram:: embiggenMIX:create_command_line_parser()
:prog: embiggenMIX.py
:prog: embiggenMIX
.. autoprogram:: embiggenRCM:create_command_line_parser()
:prog: embiggenRCM.py
:prog: embiggenRCM
.. autoprogram:: embiggenVOLT:create_command_line_parser()
:prog: embiggenVOLT.py
:prog: embiggenVOLT
.. autoprogram:: genmpiXDMF:create_command_line_parser()
:prog: genmpiXDMF.py
:prog: genmpiXDMF
.. autoprogram:: genXDMF:create_command_line_parser()
:prog: genXDMF.py
:prog: genXDMF
.. autoprogram:: genXLine:create_command_line_parser()
:prog: genXLine.py
:prog: genXLine
.. autoprogram:: numSteps:create_command_line_parser()
:prog: numSteps.py
:prog: numSteps
.. autoprogram:: pitmerge:create_command_line_parser()
:prog: pitmerge.py
:prog: pitmerge
.. autoprogram:: printResTimes:create_command_line_parser()
:prog: printResTimes.py
:prog: printResTimes
.. autoprogram:: run_calcdb:create_command_line_parser()
:prog: run_calcdb.py
:prog: run_calcdb
.. autoprogram:: run_ground_deltaB_analysis:create_command_line_parser()
:prog: run_ground_deltaB_analysis.py
:prog: run_ground_deltaB_analysis
.. autoprogram:: slimFL:create_command_line_parser()
:prog: slimFL.py
:prog: slimFL
.. autoprogram:: slimh5:create_command_line_parser()
:prog: slimh5.py
:prog: slimh5
.. autoprogram:: slimh5_classic:create_command_line_parser()
:prog: slimh5_classic.py
:prog: slimh5_classic
.. autoprogram:: supermag_comparison:create_command_line_parser()
:prog: supermag_comparison.py
:prog: supermag_comparison
.. autoprogram:: supermage_analysis:create_command_line_parser()
:prog: supermage_analysis.py
:prog: supermage_analysis
.. autoprogram:: ut2mjd:create_command_line_parser()
:prog: ut2mjd.py
:prog: ut2mjd
Datamodel
----------
Edit this: The datamodel directory has scripts that are used to generate the datamodel for MAGE simulations. The scripts are:
------------------------------------------------
The datamodel directory scripts are:
.. .. autoprogram:: helioSatComp:create_command_line_parser()
:prog: helioSatComp.py
.. autoprogram:: msphParallelSatComp:create_command_line_parser()
:prog: msphParallelSatComp.py
:prog: msphParallelSatComp
.. autoprogram:: msphPbsSatComp:create_command_line_parser()
:prog: msphPbsSatComp.py
:prog: msphPbsSatComp
.. autoprogram:: msphSatComp:create_command_line_parser()
:prog: msphSatComp.py
:prog: msphSatComp
.. autoprogram:: rbspSCcomp:create_command_line_parser()
:prog: rbspSCcomp.py
:prog: rbspSCcomp
.. .. autoprogram:: rcm_rbsp_satcomp:create_command_line_parser()
:prog: rcm_rbsp_satcomp.py
OHelio
-------
Edit this: The OHelio directory has scripts that are used to generate the OHelio for MAGE simulations. The scripts are:
------------------------------------------------
The OHelio directory scripts are:
.. autoprogram:: ih2oh:create_command_line_parser()
:prog: ih2oh.py
:prog: ih2oh
Raiju
------------------------------------------------
Raiju directory scripts are:
.. autoprogram:: kaipy.raiju.dst:create_command_line_parser()
:prog: raijudst
.. autoprogram:: kaipy.raiju.m2m:create_command_line_parser()
:prog: raijum2m

View File

@@ -318,9 +318,10 @@ class GameraPipe(object):
self.X = np.zeros((self.Ni+1,self.Nj+1))
self.Y = np.zeros((self.Ni+1,self.Nj+1))
else:
self.X = np.zeros((self.Ni+1,self.Nj+1,self.Nk+1))
self.Y = np.zeros((self.Ni+1,self.Nj+1,self.Nk+1))
self.Z = np.zeros((self.Ni+1,self.Nj+1,self.Nk+1))
self.X = np.zeros((self.Ni+1,self.Nj+1,self.Nk+1))
self.Y = np.zeros((self.Ni+1,self.Nj+1,self.Nk+1))
self.Z = np.zeros((self.Ni+1,self.Nj+1,self.Nk+1))
self.dV = np.zeros((self.Ni ,self.Nj ,self.Nk ))
if (doVerbose):
#print("Del = (%d,%d,%d)"%(self.dNi,self.dNj,self.dNk))
titStr = "%s/Grid"%(self.ftag)
@@ -347,6 +348,7 @@ class GameraPipe(object):
self.X[iS:iE+1,jS:jE+1,kS:kE+1] = kh5.PullVar(fIn,"X")
self.Y[iS:iE+1,jS:jE+1,kS:kE+1] = kh5.PullVar(fIn,"Y")
self.Z[iS:iE+1,jS:jE+1,kS:kE+1] = kh5.PullVar(fIn,"Z")
self.dV[iS:iE , jS:jE , kS:kE ] = kh5.PullVar(fIn, "dV")
bar()
else:
print("Grid Previously Loaded")

View File

@@ -470,7 +470,7 @@ def PlotMerid(gsph, nStp, xyBds, Ax, doDen=False, doRCM=False, AxCB=None, doClea
else:
vN = kv.genNorm(0, 25)
if doSrc:
vID = "SrcD"
vID = "SrcD_RING"
cbStr = "Source Density [#/cc]"
else:
vID = "D"
@@ -479,7 +479,7 @@ def PlotMerid(gsph, nStp, xyBds, Ax, doDen=False, doRCM=False, AxCB=None, doClea
else:
vN = vP
if doSrc:
vID = "SrcP"
vID = "SrcP_RING"
cbStr = "Source Pressure [nPa]"
else:
vID = "P"

View File

@@ -222,6 +222,8 @@ def RCMInset(AxRCM, rcmdata, nStp, vP, pCol="k", doPP=True):
AxRCM.set_title("RCM Pressure",fontsize="small",color=rcmCol)
return rcBds
#Add RCM box to other plot
def AddRCMBox(Ax):
"""

View File

@@ -37,14 +37,13 @@ class H5Info(object):
May or may not include subseconds based on constructor args
"""
def __init__(self, h5fname: str, noSubsec:bool=True):
def __init__(self, h5fname: str, noSubsec:bool=True, useTAC=True, useBars=True):
# h5fname = h5fname.split('/')[-1]
self.fname = h5fname
self.Nt, self.steps = cntSteps(self.fname)
print("Found {} steps in {}".format(self.Nt, self.fname))
self.Nt, self.steps = cntSteps(self.fname, useTAC=useTAC, useBars=useBars)
self.stepStrs = ['Step#'+str(s) for s in self.steps]
self.times = getTs(self.fname, self.steps, "time")
self.MJDs = getTs(self.fname, self.steps, "MJD" )
self.times = getTs(self.fname, self.steps, "time", useTAC=useTAC, useBars=useBars)
self.MJDs = getTs(self.fname, self.steps, "MJD" , useTAC=useTAC, useBars=useBars)
f5 = h5py.File(h5fname)
if noSubsec:
@@ -70,8 +69,8 @@ class H5Info(object):
Returns: None
"""
print("Step Info for {}:".format(self.fname))
print(" Step start/end/stride : {} / {} / {}".format(self.steps[0], self.steps[-1], self.steps[1]-self.steps[0]))
print(" Time start/end/stride : {:1.2f} / {:1.2f} / {:1.2f}".format(self.times[0], self.times[-1], self.times[1]-self.times[0]))
print(" Step start/end/stride : {} / {} / {}".format(self.steps[0], self.steps[-1], self.steps[-1]-self.steps[-2]))
print(" Time start/end/stride : {:1.2f} / {:1.2f} / {:1.2f}".format(self.times[0], self.times[-1], self.times[-1]-self.times[-2]))
print(" MJD start/end : {:1.8f} / {:1.8f}".format(self.MJDs[0], self.MJDs[-1]))
print(" UT start/end : {} / {}".format(self.UTs[0], self.UTs[-1]))
@@ -301,7 +300,7 @@ def tStep(fname, nStp=0, aID="time", aDef=0.0):
return t
def cntSteps(fname, doTryRecover=True, s0=0):
def cntSteps(fname, doTryRecover=True, s0=0, useTAC=True, useBars=True):
'''
Count the number of steps and retrieve the step IDs from an h5 file.
@@ -323,17 +322,21 @@ def cntSteps(fname, doTryRecover=True, s0=0):
try:
CheckOrDie(fname)
with h5py.File(fname, 'r') as hf:
if kdefs.grpTimeCache in hf.keys() and 'step' in hf[kdefs.grpTimeCache].keys():
if useTAC and kdefs.grpTimeCache in hf.keys() and 'step' in hf[kdefs.grpTimeCache].keys():
sIds = np.asarray(hf[kdefs.grpTimeCache]['step'])
nSteps = sIds.size
else:
Steps = [grp for grp in alive_it(hf.keys(), title="#-Steps".ljust(kdefs.barLab), length=kdefs.barLen, bar=kdefs.barDef) if "Step#" in grp]
iterator = hf.keys()
if useBars:
iterator = alive_it(iterator, title="#-Steps".ljust(kdefs.barLab), length=kdefs.barLen, bar=kdefs.barDef)
Steps = [grp for grp in iterator if "Step#" in grp]
sIds = np.array([str.split(s, "#")[-1] for s in Steps], dtype=int)
sIds.sort()
nSteps = len(Steps)
return nSteps, sIds
except (ValueError, IndexError) as e:
print(e)
print("!!Warning: h5 file contains unreadable steps")
if not doTryRecover:
@@ -395,7 +398,7 @@ def cntX(fname, gID=None, StrX="/Step#"):
return nSteps, sIds
def getTs(fname, sIds=None, aID="time", aDef=0.0):
def getTs(fname, sIds=None, aID="time", aDef=0.0, useTAC=True, useBars=True):
'''
Retrieve time series data from an HDF5 file.
@@ -421,17 +424,19 @@ def getTs(fname, sIds=None, aID="time", aDef=0.0):
titStr = "Time series: %s" % (aID)
with h5py.File(fname, 'r') as hf:
if kdefs.grpTimeCache in hf.keys():
if useTAC and kdefs.grpTimeCache in hf.keys():
if aID in hf[kdefs.grpTimeCache]:
T = np.asarray(hf[kdefs.grpTimeCache][aID])
else:
T[:] = aDef
else:
with alive_bar(Nt, title=titStr.ljust(kdefs.barLab), length=kdefs.barLen, bar=kdefs.barDef) as bar:
for idx, n in enumerate(sIds):
gId = "/Step#%d" % (n)
T[idx] = hf[gId].attrs.get(aID, aDef)
bar()
iterator = enumerate(sIds)
if useBars:
iterator = alive_it(iterator, title="#-Steps".ljust(kdefs.barLab), length=kdefs.barLen, bar=kdefs.barDef)
for idx, n in iterator:
gId = "/Step#%d" % (n)
T[idx] = hf[gId].attrs.get(aID, aDef)
#bar()
return T
#Used by MageStep to find closest datetime

View File

@@ -162,6 +162,24 @@ def xyz2rtp(phi, theta, Ax, Ay, Az):
At = Ax * np.cos(phi) * np.cos(theta) + Ay * np.sin(phi) * np.cos(theta) - Az * np.sin(theta)
return Ar, At, Ap
def rtp2rt(r, theta, phi):
"""
Convert spherical coordinates (r, theta, phi) to 2D polar (r, phi)
Parameters:
r (float): radial dimension
theta (float): [rad] meridional/zenith direction
phi (float): [rad] azimuthal direciton
Returns:
r (float): radial dimension
theta (float): [rad]azimuthal dimenison
"""
Ar = r*np.sin(theta)
Atheta = phi
return Ar, Atheta
# Use the Burton 1975 Formula to compute Dst from solar wind parameters
def burtonDst(secs, n, vx, vy, vz, bx, by, bz):
"""
@@ -356,5 +374,36 @@ def interpTSCWeights(gridX, gridY, x, y):
for i in range(3):
for j in range(3):
w2D[i,j] = wX[i]*wY[j]
return w2D
def dipoleShift(xyz, r):
#Find L of this point
L = dipoleL(xyz)
# Avoid bad values if L<r, push as far as possible
L = max(L,r)
# Use r = L*cos^2(latitude)
mlat = np.abs(np.acos(np.sqrt(r/L)))
mlon = np.atan2(xyz[1],xyz[0]) # No change in longitude
if (mlon<0): mlon = mlon+2*np.pi
if (xyz[2]<0):
mlat = -np.abs(mlat)
# Get cartesian coordinates
xyz_out = [r*np.cos(mlat)*np.cos(mlon),
r*np.cos(mlat)*np.sin(mlon),
r*np.sin(mlat)]
return xyz_out
def dipoleL(xyz):
z = xyz[2]
rad = np.linalg.norm(xyz)
lat = abs( np.arcsin(z/rad) )
Leq = rad/( np.cos(lat)*np.cos(lat) )
return Leq

0
kaipy/raiju/__init__.py Normal file
View File

223
kaipy/raiju/dst.py Normal file
View File

@@ -0,0 +1,223 @@
#%%
# Standard modules
import os
import argparse
# Third-party modules
import h5py as h5
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
# Kaipy modules
import kaipy.kdefs as kd
import kaipy.kaiTools as kt
import kaipy.kaiViz as kv
import kaipy.kaiH5 as kh5
import kaipy.raiju.raijuUtils as ru
def calcMRIonoVars(s5):
f5 = s5.file
thetaIono = kt.to_center2D((90 - f5['Y'][:])*np.pi/180)
phiIono = kt.to_center2D((f5['X'][:])*np.pi/180)
Ri_m = kd.RionE*1e6
br = np.zeros(thetaIono.shape)
for i in range(thetaIono.shape[0]):
br[i,:] = kd.EarthM0g*kd.G2nT \
/ (Ri_m/kd.REarth)**3 \
* 2*np.cos(thetaIono[i,:])
areaCC = np.zeros(thetaIono.shape)
dTheta = thetaIono[0,1] - thetaIono[0,0]
dPhi = phiIono[1,0] - phiIono[0,0]
for i in range(areaCC.shape[1]):
areaCC[:,i] = (Ri_m/kd.REarth)**2*np.sin(thetaIono[:,i])*dTheta*dPhi
return br, areaCC
def DPSDst_raiju(raiI: ru.RAIJUInfo, s5: h5.Group, rmax=6):
"""
Calculate DPSDst [nT] for a raiju step
If return2D=True, gives back full 2D map, where each value is that cell's contribution to DPSDst.
This will ignore isGood, if provided, but will manually ignore RAIJUINACTIVE cells
If return2D=False (default), returns single value that sums over all isGood=True
"""
xmin = ru.getVar(s5,'xmin')
ymin = ru.getVar(s5,'ymin')
xmcc = kt.to_center2D(xmin)
ymcc = kt.to_center2D(ymin)
rmin = np.sqrt(xmcc**2+ymcc**2)
active = ru.getVar(s5, 'active')
isGood = np.logical_and(rmin<rmax, active == ru.domain['ACTIVE'])
idx_ele = ru.spcIdx(raiI.species, ru.flavs_s['HOTE'])
f5 = s5.file
Ri_m = f5['Planet'].attrs['Rad_ionosphere']
Rp_m = f5['Planet'].attrs['Rad_surface']
areaCC = ru.getVar(f5, 'Grid/areaCC')
brcc = ru.getVar(f5, 'Grid/BrCC')
press_tot = ru.getVar(s5, 'Pressure', mask = isGood==False, broadcast_dims=(2,))[:,:,0] # Total pressure
press_ele = ru.getVar(s5, 'Pressure', mask = isGood==False, broadcast_dims=(2,))[:,:,idx_ele+1] # Electron pressure
#bvolcc = np.ma.masked_where(isGood==False, kt.to_center2D(ru.getVar(s5, 'bVol')))
bvolcc = ru.getVar(s5, 'bVol_cc', mask=isGood==False)
energyDen_tot = (press_tot*1e-9)*(bvolcc*Rp_m*1e9)*(brcc*1e-9)/ kd.kev2J
energyDen_ele = (press_ele*1e-9)*(bvolcc*Rp_m*1e9)*(brcc*1e-9)/ kd.kev2J
energy_tot = (press_tot*1e-9)*(bvolcc*Rp_m*1e9)*(brcc*1e-9)*(areaCC*Ri_m**2) / kd.kev2J # p[J/m^3] * bVol[m/T] * B[T] * Re^2[m^2] = [J] * keV/J = [keV]
energy_ele = (press_ele*1e-9)*(bvolcc*Rp_m*1e9)*(brcc*1e-9)*(areaCC*Ri_m**2) / kd.kev2J # p[J/m^3] * bVol[m/T] * B[T] * Re^2[m^2] = [J] * keV/J = [keV]
dpsdst_2D_tot = -4.2*(1.0e-30)*energy_tot # [nT]
dpsdst_2D_ele = -4.2*(1.0e-30)*energy_ele # [nT]
#dpsdst_sum = np.ma.sum(dpsdst_2D)
return energyDen_tot, energyDen_ele, dpsdst_2D_tot, dpsdst_2D_ele
def DPSDst_mhdrcm(rmI: kh5.H5Info, s5: h5.Group, rmax=6, doMHD=False, br=None, areaCC=None):
"""
Same as DPSDst_raiju but for RCM
"""
f5 = s5.file
xmin = s5['xMin'][:]
ymin = s5['yMin'][:]
rmin = np.sqrt(xmin**2+ymin**2)
iopen = s5['IOpen'][:]
active = np.full(iopen.shape, ru.domain['BUFFER'])
active[iopen > 0.5] = ru.domain['INACTIVE']
active[iopen < -0.5] = ru.domain['ACTIVE']
isGood = np.logical_and(rmin < rmax, active == ru.domain['ACTIVE'])
press_tot = s5['P'][:]
press_ele = s5['Pe'][:]
press_tot = np.ma.masked_where(isGood==False, press_tot)
press_ele = np.ma.masked_where(isGood==False, press_ele)
bvol = np.ma.masked_where(isGood==False, s5['bVol'][:])
if br is None or areaCC is None:
br, areaCC = calcMRIonoVars(s5)
Ri_m = kd.RionE*1e6
energyDen_tot = (press_tot*1e-9)*(bvol*Ri_m*1e9)*(br*1e-9)/ kd.kev2J
energyDen_ele = (press_ele*1e-9)*(bvol*Ri_m*1e9)*(br*1e-9)/ kd.kev2J
energy_tot = (press_tot*1e-9)*(bvol*Ri_m*1e9)*(br*1e-9)*(areaCC*Ri_m**2) / kd.kev2J # p[J/m^3] * bVol[m/T] * B[T] * Re^2[m^2] = [J] * keV/J = [keV]
energy_ele = (press_ele*1e-9)*(bvol*Ri_m*1e9)*(br*1e-9)*(areaCC*Ri_m**2) / kd.kev2J # p[J/m^3] * bVol[m/T] * B[T] * Re^2[m^2] = [J] * keV/J = [keV]
dpsdst_2D_tot = -4.2*(1.0e-30)*energy_tot # [nT]
dpsdst_2D_ele = -4.2*(1.0e-30)*energy_ele # [nT]
#dpsdst_sum = np.ma.sum(dpsdst_2D)
return energyDen_tot, energyDen_ele, dpsdst_2D_tot, dpsdst_2D_ele
def plotDstTS(raiI: ru.RAIJUInfo, rmax=6, mrI: kh5.H5Info = None):
doMR = isinstance(mrI, kh5.H5Info)
rai5 = h5.File(raiI.fname, 'r')
dps_rai_ts = np.zeros(raiI.Nt)
dps_rai_ts_ele = np.zeros(raiI.Nt)
if doMR:
mr5 = h5.File(mrI.fname)
t0 = raiI.times[0]
t1 = raiI.times[-1]
i0 = np.abs(mrI.times - t0).argmin()
i1 = np.abs(mrI.times - t1).argmin()
Nt_mr = i1-i0+1
dps_mr_ts = np.zeros(Nt_mr)
dps_mr_ts_ele = np.zeros(Nt_mr)
for t in tqdm(range(raiI.Nt), desc="Calculating RAIJU DPS-Dst"):
_, _, dst_tot, dst_ele = DPSDst_raiju(raiI, rai5[raiI.stepStrs[t]], rmax=rmax)
dps_rai_ts[t] = np.sum(dst_tot)
dps_rai_ts_ele[t] = np.sum(dst_ele)
dps_rai_noEle = dps_rai_ts - dps_rai_ts_ele
if doMR:
br, areaCC = calcMRIonoVars(mr5[mrI.stepStrs[0]])
for t in tqdm(range(Nt_mr), desc="Calculating MHDRCM DPS-Dst"):
_, _, dst_tot, dst_ele = DPSDst_mhdrcm(mrI, mr5[mrI.stepStrs[i0+t]], rmax=rmax, br=br, areaCC=areaCC)
dps_mr_ts[t] = np.sum(dst_tot)
dps_mr_ts_ele[t] = np.sum(dst_ele)
dps_mr_noEle = dps_mr_ts - dps_mr_ts_ele
print("Plotting")
plt.figure(figsize=(8,4))
plt.plot(raiI.UTs[1:], dps_rai_noEle[1:] , 'b-' , label='RAIJU (Tot-ele)')
plt.plot(raiI.UTs[1:], dps_rai_ts_ele[1:], 'b--', label='RAIJU (Ele)')
if doMR:
plt.plot(mrI.UTs[i0:i1+1], dps_mr_noEle ,'r-' , label='RCM (Tot-ele)')
plt.plot(mrI.UTs[i0:i1+1], dps_mr_ts_ele,'r--', label='RCM (Ele)')
plt.legend()
plt.grid(alpha=0.3)
kv.savePic("DPSDst.png")
#%%
def create_command_line_parser():
fdir = '.'
ftag = 'raijuOWD'
ftag_mr = 'msphere'
rmax = 6
doMR = True
MainS = """Creates series of XMF files from MPI-decomposed Gamera run
"""
parser = argparse.ArgumentParser(description=MainS, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-d',type=str,metavar="directory",default=fdir,help="Directory to read from (default: %(default)s)")
parser.add_argument('-id',type=str,metavar="runid",default=ftag,help="RunID of raiju h5 (default: %(default)s)")
parser.add_argument('-mr',type=str,metavar="runid",default=ftag_mr,help="RunID of mhdrcm h5 (default: %(default)s)")
parser.add_argument('-rmax',type=float,metavar="Re",default=rmax,help="Maximum Req value to eval DPSDst out to (default: %(default)s)")
parser.add_argument('--nomr',action='store_true',default=False,help="Don't do mhdrcm stuff (default: %(default)s)")
return parser
#%%
def main():
fdir = '.'
ftag = 'raijuOWD'
ftag_mr = 'msphere'
rmax = 6
doMR = True
parser = create_command_line_parser()
args = parser.parse_args()
#args = parser.parse_args(args=['-d', '/glade/derecho/scratch/sciola/raijudev/owdTests/dinoKO', '-id', 'raijuOWD_bvolFix'])
fdir = args.d
ftag = args.id
ftag_mr = args.mr
rmax = args.rmax
doMR = not args.nomr
print("Reading RAIJU info")
rai_fname = ftag+".raiju.h5"
raiI = ru.RAIJUInfo(os.path.join(fdir, rai_fname))
if doMR:
print("Reading mhdrcm info")
mrfname = ftag_mr+'.mhdrcm.h5'
mrI = kh5.H5Info(os.path.join(fdir, mrfname))
else:
mrI = None
#%%
plotDstTS(raiI, rmax, mrI)
# %%
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,51 @@
# Contains the datastructures that include the fully realized lambda distributions
from dataclasses import dataclass
from dataclasses import asdict as dc_asdict
from typing import Optional, List
import kaipy.raiju.lambdautils.AlamParams as aP
# dataclasses_json isn't a default package. Since its only used for reading, don't want to make it a requirement for everyone
try:
from dataclasses_json import dataclass_json
dataclasses_json_module_imported = True
except ModuleNotFoundError:
dataclass_json = None
dataclasses_json_module_imported = False
def conditional_decorator(dec, dataclasses_json_module_imported):
def decorator(func):
if not dataclasses_json_module_imported:
# Return the function unchanged, not decorated.
return func
return dec(func)
return decorator
@dataclass
class Species:
"""
Initialize by giving a SpecParam object
Species will generate alam dist using the params
"""
params: aP.SpecParams # Parameters used to generate this instance of Species
def __post_init__(self):
# len(n+1), because n in specParams is number of channels, and these are interfaces
self.alami = self.params.genAlami()
#@dataclass_json
@conditional_decorator(dataclass_json, dataclasses_json_module_imported)
@dataclass
class AlamData:
"""
Initialize by giving a list of SpecParams
AlamData will generate all of them and hold as a list of Species
"""
params: List[aP.SpecParams]
def __post_init__(self):
self.species = [Species(p) for p in self.params]

View File

@@ -0,0 +1,50 @@
# Structures to specify a species in raiju. Populate and give to genAlam.py to get what goes into raijuconfig.h5
from dataclasses import dataclass
from dataclasses import asdict as dc_asdict
from typing import Optional, List
# Import other things from this package space
import kaipy.raiju.lambdautils.DistTypes as dT
# dataclasses_json isn't a default package. Since its only used for reading, don't want to make it a requirement for everyone
try:
from dataclasses_json import dataclass_json
dataclasses_json_module_imported = True
except ModuleNotFoundError:
dataclass_json = None
dataclasses_json_module_imported = False
def conditional_decorator(dec, dataclasses_json_module_imported):
def decorator(func):
if not dataclasses_json_module_imported:
# Return the function unchanged, not decorated.
return func
return dec(func)
return decorator
#------
# Actual classes/structures
#------
@conditional_decorator(dataclass_json, dataclasses_json_module_imported)
@dataclass
class SpecParams:
""" Defines a single species
A full species parameter set is defined by the combination of the params listed here AND the ones in whatever DistType is chosen
"""
n: int # Number of channels
amin: float # Lower lambda bound for species
amax: float # Upper lambda bound for species
distType: dT.DistType # DistType params used to generate final lambda distribution
flav: int # "Flavor", used to distinguish species types in RCM
# 0 = 0-channel plasmasphere, 1 = electrons, 2 = protons
numNuc_p : int # Number of protons in nucleus
numNuc_n : int # Number of neutrons in nucleus
q : int # Net charge of species
fudge: Optional[float] = 0 # "Fudge factor" loss ratio
name: Optional[str] = None
def genAlami(self): # This will call the given DistType's 'required' function to generate alams based on its rules
specData = self.distType.genAlami(self)
return specData

View File

@@ -0,0 +1,101 @@
# Defines distribution types explicitly, so we can always take a config file and know exactly how the distribution was generated
from dataclasses import dataclass
from dataclasses import asdict as dc_asdict
from typing import Optional, List
# dataclasses_json isn't a default package. Since its only used for reading, don't want to make it a requirement for everyone
try:
from dataclasses_json import dataclass_json
dataclasses_json_module_imported = True
except ModuleNotFoundError:
dataclass_json = None
dataclasses_json_module_imported = False
def conditional_decorator(dec, dataclasses_json_module_imported):
def decorator(func):
if not dataclasses_json_module_imported:
# Return the function unchanged, not decorated.
return func
return dec(func)
return decorator
#------
# Parameters needed to determine lambda distribution
#------
@dataclass
class DistType: # Empty class just so we can force the type in dataclasses below
name: str = "Empty"
#------
# Specific implementations of DistType
#------
#@dataclass_json
@conditional_decorator(dataclass_json, dataclasses_json_module_imported)
@dataclass
class DT_Manual(DistType):
"""
If you want to completely ignore all this generator stuff, you could use this
and do whatever you want. But if you were doing all that anyways, its probably
just easier to manually edit the h5 dataset directly
"""
def __post_init__(self):
if self.name == "Empty": self.name = "Manual"
#@dataclass_json
@conditional_decorator(dataclass_json, dataclasses_json_module_imported)
@dataclass
class DT_Single(DistType):
"""
Just a single channel, pretty boring
"""
def __post_init__(self):
self.name = "Single"
def genAlami(self, sP):
return [sP.amin, sP.amax]
#@dataclass_json
@conditional_decorator(dataclass_json, dataclasses_json_module_imported)
@dataclass
class DT_Wolf(DistType):
""" Lambda channel spacing based on Wolf's notes
(ask Anthony Sciola or Frank Toffoletto for a copy)
With the addition that there can be 2 p values for the start and end, and pStar transitions between them
kmin, kmax let you set what part of the full distribution you actually generate
"""
p1: float = None
p2: float = None
kmin: int = 0
kmax: int = -1
def __post_init__(self):
self.name = "Wolf"
def genAlami(self, sP):
"""
Takes a filled out SpecParams and returns the lambda interfaces
"""
# Get/set needed variables
kmin = self.kmin
kmax = sP.n+1 if self.kmax == -1 else self.kmax # Add 1 because sP.n is # channels and we are generating lambda interfaces
amin = sP.amin
amax = sP.amax
# Do math
alams = []
for k in range(sP.n+1):
kfrac = (k-kmin)/(kmax-kmin) # How far through the channel range are we
pstar = (1-kfrac)*self.p1 + kfrac*self.p2
lammax = amax-amin
lam = lammax*((k - kmin + 0.5)/(kmax-kmin + 0.5))**pstar + amin
alams.append(lam)
return alams
# TODO: There's another DistType in the previous RCM generator, should port over

View File

@@ -0,0 +1,10 @@
Set of scripts to generate lambda distributions for raiju
It seems like overkill (maybe it is), but the idea is to have a structured way of taking any previously generated raijuconfig.h5 file and know exactly how it was generated. That way, e.g. if we want to tweak the energy bounds or change the distribution between two values, we have a way of doing that while making sure everything else stays the same
The overall procedure for specifying a lambda distribution is:
1) Fill out as many specParams as you want (one for each species)
1a) First choose and fill out a DistType for each one, then create your specParams object
2) Give a list of your specParams to AlamData.py:AlamData. It will use the params to generate a list of Species objects, which will contain the fully realized lambda distributions for each alamParam
3) Call fileIO.SaveAlamConfig(...) to write the alam configuration to file

View File

View File

@@ -0,0 +1,49 @@
# Standard modules
from dataclasses import asdict as dc_asdict
# Third-party modules
import h5py as h5
# Kaipy modules
import kaipy.kaijson as kj
import kaipy.raiju.lambdautils.AlamData as aD
def saveAlamParams(f5name: str, alamData: aD.AlamData):
with h5.File(f5name, 'a') as f5:
print("Adding params used to generate lambda distribution as root attribute")
f5.attrs['AlamParams'] = [kj.dumps(dc_asdict(p),noIndent=True) for p in alamData.params]
def saveAlamData(f5name: str, alamData: aD.AlamData):
""" Takes an AlamData object, formats it to raijuconfig.h5 style, and saves it
Will also call saveAlamParams above if it did write AlamData to file
"""
with h5.File(f5name, 'a') as f5:
# Only add species if one doesn't already exist
if "Species" in f5.keys():
print("'Species' group already in {}, not writing new one".format(f5name))
return
# If it doens't exist yet, we add
print("Adding Species to",f5name)
gSpec = f5.create_group("Species")
for i, spec in enumerate(alamData.species):
gFlav = gSpec.create_group(str(i))
gFlav.create_dataset('alami', data=spec.alami)
gFlav['alami'].attrs['units'] = "eV * (Rp/nT)^(2/3)"
gFlav.attrs['Name' ] = spec.params.name
gFlav.attrs['N' ] = spec.params.n
gFlav.attrs['flav' ] = spec.params.flav
gFlav.attrs['numNuc_p' ] = spec.params.numNuc_p
gFlav.attrs['numNuc_n' ] = spec.params.numNuc_n
gFlav.attrs['q' ] = spec.params.q
gFlav.attrs['fudge' ] = spec.params.fudge
# If we successfully added AlamData, save the params as well
saveAlamParams(f5name, alamData)

346
kaipy/raiju/m2m.py Normal file
View File

@@ -0,0 +1,346 @@
"""
Diagnostic tools to check mapping MHD moments to etas and back
"""
# Standard modules
import os
import argparse
import datetime
# Third-party modules
import h5py as h5
import numpy as np
import matplotlib.pyplot as plt
from dataclasses import dataclass
from tqdm import tqdm
# Kaipy modules
import kaipy.kdefs as kd
import kaipy.kaiViz as kv
import kaipy.kaiTools as kt
import kaipy.raiju.raijuUtils as ru
import kaipy.raiju.raijuViz as rv
@dataclass
class m2mData_pnt: # Maybe overkill idk
p_mhd: float
d_mhd: float
kt_mhd: float
p_rai: float
d_rai: float
kt_rai: float
@dataclass
class m2mData_step:
frac_P: np.ndarray
frac_D: np.ndarray
isotfmt = '%Y-%m-%dT%H:%M:%S'
def create_command_line_parser():
"""
"""
description = """Do some diagnostics for mapping MHD moments to etas and back.
"""
default_runid = "msphere"
default_nStride = 10
default_uts = -1
default_ute = -1
mode_choices = ["summary", "step", "point"]
parser = argparse.ArgumentParser(
description=description,
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument(
"-d", type=str, metavar="directory", default=os.getcwd(),
help="Directory containing data to read (default: %(default)s)"
)
parser.add_argument(
"-id", type=str, metavar="runid", default=default_runid,
help="Run ID of data (default: %(default)s)"
)
parser.add_argument(
"-uts", type=str, metavar=isotfmt, default=default_uts,
help="First UT (default: %(default)s)"
)
parser.add_argument(
"-ute", type=str, metavar=isotfmt, default=default_ute,
help="Last UT (default: %(default)s)"
)
parser.add_argument(
"-dt", type=int, metavar="stride", default=default_nStride,
help="Step stride (in minutes) (default: %(default)s)"
)
parser.add_argument(
"-phi0", type=int, metavar="int", default=180,
help=" Phi value [deg] to probe in 'point' mode (default: %(default)s)"
)
parser.add_argument(
"-mode", choices=mode_choices, default=mode_choices[0],
help="What do you wanna do? (default: %(default)s)."
)
parser.add_argument(
"-v", "--verbose", action="store_true", default=False,
help="Print verbose output (default: %(default)s)."
)
return parser
def checkMom2Mom_pnt(raiI: ru.RAIJUInfo, s5: h5.Group,
i0: int, j0: int, spcID="BLK",
doIntenPlot=False, doConsoleIO=False) -> m2mData_pnt:
tiote = 4.0
iStep = np.argmin(np.abs(raiI.times - s5.attrs['time']))
if spcID=="BLK":
idx_mhd = 0
idx_rai = 0
doIntenPlot = False
if spcID=="HOTP":
idx_mhd = 0
idx_rai = ru.spcIdx(raiI.species, ru.flavs_s["HOTP"])+1
spc = raiI.species[idx_rai-1]
mass = kd.Mp_cgs*1e-3
if spcID=="HOTE":
idx_mhd = 0
idx_rai = ru.spcIdx(raiI.species, ru.flavs_s["HOTE"])+1
spc = raiI.species[idx_rai-1]
mass = kd.Me_cgs*1e-3
p_mhd = ru.getVar(s5, "Pavg_in")[i0,j0,idx_mhd]
d_mhd = ru.getVar(s5, "Davg_in")[i0,j0,idx_mhd]
p_rai = ru.getVar(s5, "Pressure")[i0,j0,idx_rai]
d_rai = ru.getVar(s5, "Density" )[i0,j0,idx_rai]
if spcID=="HOTP": p_mhd = p_mhd / (1 + 1/tiote) # Get just ions
if spcID=="HOTE": p_mhd = p_mhd / (1 + tiote) # Get just electrons
t_mhd = 6.25*p_mhd/d_mhd
t_rai = 6.25*p_rai/d_rai
if doConsoleIO:
print("MHD:")
print(" P={:0.6f} nPa, D={:0.6f} #/cc, T={:0.6f} keV".format(p_mhd,d_mhd,t_mhd))
print("RAIJU:")
print(" P={:0.6f} nPa, D={:0.6f} #/cc, T={:0.6f} keV".format(p_rai,d_rai,t_rai))
if doIntenPlot:
inten = ru.getVar(s5, "intensity")[i0,j0,spc.kStart:spc.kEnd]
bVol_cc = ru.getVar(s5,'bVol_cc')[i0,j0]
xmin_cc = kt.to_center2D(ru.getVar(s5, 'xmin'))[i0,j0]
ymin_cc = kt.to_center2D(ru.getVar(s5, 'ymin'))[i0,j0]
energies = np.abs(spc.alami)*bVol_cc**(-2./3.)*1e-3 # [keV]
energies_cc = np.abs(spc.alamc)*bVol_cc**(-2./3.)*1e-3 # [keV]
Nk = energies_cc.shape[0]
inten_maxwell = np.zeros(Nk)
for i in range(Nk):
inten_maxwell[i] = ru.intensity_maxwell(d_mhd, mass,energies_cc[i], t_mhd)
plt.figure(figsize=(8,8))
plt.plot(energies_cc, inten_maxwell, '--',linewidth=3,alpha=0.8,label='MHD (Maxwellian)')
plt.scatter(energies_cc, inten_maxwell, s=20,alpha=0.8)
plt.plot(energies_cc, inten, label='RAIJU')
plt.scatter(energies_cc, inten,s=10)
plt.xlabel("Energy [keV]")
plt.ylabel("Intensity [...]")
plt.legend()
plt.grid(alpha=0.3)
plt.xscale('log')
plt.yscale('log')
plt.ylim([1e4,1e8])
plt.title("{}\ni0={}, j0={}\n(X,Y)=({:0.2f},{:0.2f}) R$_E$".format(raiI.UTs[iStep],i0,j0,xmin_cc,ymin_cc))
fname = f"mom2mom_{i0}_{j0}.png"
kv.savePic(fname)
print(f"Saved plot {fname}")
return m2mData_pnt(p_mhd,d_mhd,t_mhd,p_rai,d_rai,t_rai)
def checkMom2Mom_step(raiI: ru.RAIJUInfo, s5: h5.Group,
mask_cc:np.ndarray = None, spcID="BLK",
doPlot=False,doConsoleIO=False) -> m2mData_step:
active = ru.getVar(s5, 'active')
if mask_cc is None:
mask_cc = active != ru.domain['BUFFER']
frac_P = np.ma.ones((raiI.Ni, raiI.Nj))
frac_D = np.ma.ones((raiI.Ni, raiI.Nj))
kt_mhd = np.ma.ones((raiI.Ni, raiI.Nj))
frac_P.mask = mask_cc
frac_D.mask = mask_cc
for j in range(raiI.Nj):
for i in range(raiI.Ni):
if mask_cc[i,j]: continue
m2m = checkMom2Mom_pnt(raiI, s5, i, j, spcID=spcID,doIntenPlot=False)
frac_P[i,j] = m2m.p_rai/m2m.p_mhd
frac_D[i,j] = m2m.d_rai/m2m.d_mhd
kt_mhd[i,j] = m2m.kt_mhd
if doPlot:
iStep = np.argmin(np.abs(raiI.times - s5.attrs['time']))
plt.figure(figsize=(8,8))
norm = kv.genNorm(0.8,1.2)
cmap = 'RdBu_r'
colat2D = ru.getVar(s5.file,'X')
lon2D = ru.getVar(s5.file,'Y')
mp = rv.plotLonColat(plt.gca(),lon2D,colat2D,frac_P,norm=norm,cmap=cmap)
plt.colorbar(mappable=mp,label='frac_P')
plt.title(raiI.UTs[iStep])
fname = "frac_P.png"
kv.savePic(fname)
print(f"Saved plot {fname}")
plt.clf()
mp = rv.plotLonColat(plt.gca(),lon2D,colat2D,frac_D,norm=norm,cmap=cmap)
plt.colorbar(mappable=mp,label='frac_D')
plt.title(raiI.UTs[iStep])
fname = "frac_D.png"
kv.savePic(fname)
print(f"Saved plot {fname}")
plt.clf()
plt.scatter(kt_mhd,frac_P,facecolors='none',edgecolors='r',alpha=0.2)
xlim = plt.xlim()
plt.plot(xlim,[1,1],'k--',alpha=0.5)
plt.xlabel('Temp [keV]')
plt.ylabel('P$_{rai}$/P$_{mhd}$')
plt.xscale('log')
plt.title(raiI.UTs[iStep])
fname = "kt_vs_fracP.png"
kv.savePic(fname)
print(f"Saved plot {fname}")
plt.clf()
plt.scatter(kt_mhd,frac_D,facecolors='none',edgecolors='r',alpha=0.2)
xlim = plt.xlim()
plt.plot(xlim,[1,1],'k--',alpha=0.5)
plt.xlabel('Temp [keV]')
plt.ylabel('D$_{rai}$/D$_{mhd}$')
plt.xscale('log')
plt.title(raiI.UTs[iStep])
fname = "kt_vs_fracD.png"
kv.savePic(fname)
print(f"Saved plot {fname}")
if doConsoleIO:
print("frac_P:")
print(" min={:06f}, max={:06f}, avg={:06f}".format(np.min(frac_P), np.max(frac_P), np.average(frac_P)))
print("frac_D:")
print(" min={:06f}, max={:06f}, avg={:06f}".format(np.min(frac_D), np.max(frac_D), np.average(frac_D)))
return m2mData_step(frac_P,frac_D)
def checkMom2Mom_summary(raiI:ru.RAIJUInfo, ut_start:datetime.datetime=None, ut_end:datetime.datetime=None, stride_minutes:float=5):
f5 = h5.File(raiI.fname,'r')
if ut_start is None:
iStart = 0
else:
iStart = np.argmin(np.abs(raiI.UTs-ut_start))
if ut_end is None:
iEnd = raiI.Nt - 1
else:
iEnd = np.argmin(np.abs(raiI.UTs-ut_end))
if stride_minutes is None:
iStep = 10
else:
iStep = int( (stride_minutes*60) / (raiI.UTs[-1]-raiI.UTs[-2]).seconds )
Nt = int( (iEnd - iStart)/iStep )+1
timeArr = np.empty(Nt,dtype=datetime.datetime)
min_P = np.zeros(Nt)
max_P = np.zeros(Nt)
avg_P = np.zeros(Nt)
min_D = np.zeros(Nt)
max_D = np.zeros(Nt)
avg_D = np.zeros(Nt)
for i, iRai in enumerate(tqdm(range(iStart,iEnd,iStep))):
s5 = f5[raiI.stepStrs[iRai]]
m2m = checkMom2Mom_step(raiI,s5,spcID="HOTP")
timeArr[i] = raiI.UTs[iRai]
min_P[i] = np.min(m2m.frac_P)
max_P[i] = np.max(m2m.frac_P)
avg_P[i] = np.average(m2m.frac_P)
min_D[i] = np.min(m2m.frac_D)
max_D[i] = np.max(m2m.frac_D)
avg_D[i] = np.average(m2m.frac_D)
clr_P = "red"
clr_D = "blue"
alpha = 0.4
plt.figure(figsize=(12,8))
plt.plot(timeArr, avg_P ,c=clr_P,label="Pressure")
plt.plot(timeArr, min_P,'--',c=clr_P,alpha=alpha)
plt.plot(timeArr, max_P,'--',c=clr_P,alpha=alpha)
plt.plot(timeArr, avg_D ,c=clr_D,label="Density")
plt.plot(timeArr, min_D,'--',c=clr_D,alpha=alpha)
plt.plot(timeArr, max_D,'--',c=clr_D,alpha=alpha)
plt.legend()
plt.grid(alpha=0.3)
fname = "m2m_summary.png"
kv.savePic(fname)
print(f"Saved plot {fname}")
def main(config=None):
if config is None:
parser = create_command_line_parser()
args = parser.parse_args()
config = {
"indir" : args.d,
"id" : args.id,
"ut_start" : args.uts,
"ut_end" : args.ute,
"del_min" : args.dt,
"phi0" : args.phi0,
"mode" : args.mode,
"doVerbose" : args.verbose,
}
indir = os.getcwd()
fname = "msphere.raiju.h5"
raiI = ru.RAIJUInfo(os.path.join(indir,fname),useTAC=True)
if config['ut_start'] == -1:
config['ut_start'] = raiI.UTs[0]
else:
config['ut_start'] = datetime.datetime.strptime(config['ut_start'],isotfmt)
if config['ut_end'] == -1:
config['ut_end'] = raiI.UTs[-1]
else:
config['ut_end'] = datetime.datetime.strptime(config['ut_end'],isotfmt)
if config['mode']=="summary":
checkMom2Mom_summary(raiI,config['ut_start'],config['ut_end'],config['del_min'])
if config['mode']=="step":
iUT = np.argmin(np.abs(raiI.UTs - config['ut_end']))
f5 = h5.File(raiI.fname, 'r')
s5 = f5[raiI.stepStrs[iUT]]
checkMom2Mom_step(raiI, s5, doConsoleIO=True,doPlot=True)
if config['mode']=="point":
iUT = np.argmin(np.abs(raiI.UTs - config['ut_end']))
f5 = h5.File(raiI.fname, 'r')
s5 = f5[raiI.stepStrs[iUT]]
phicc = kt.to_center1D(ru.getVar(f5,'Y')[0,:])*180/np.pi
iPhi = np.argmin(np.abs(phicc - config['phi0']))
active = ru.getVar(s5,'active')[:,iPhi]
iColat = np.argmin(np.abs(active - ru.domain['BUFFER']))
checkMom2Mom_pnt(raiI, s5, iColat, iPhi,spcID="HOTP",doIntenPlot=True,doConsoleIO=True)
if __name__=="__main__":
main()

241
kaipy/raiju/raijuUtils.py Normal file
View File

@@ -0,0 +1,241 @@
#Standard modules
# Third-party modules
import h5py as h5
import numpy as np
from typing import List
import scipy.special as sp
#from bidict import bidict
# Kaipy modules
import kaipy.kdefs as kd
import kaipy.kaiTools as kt
import kaipy.kaiH5 as kh5
import kaipy.raiju.lambdautils.AlamParams as aP
dim = {"THETA": 0,
"PHI": 1}
topo = {"OPEN" : 0,
"CLOSED" : 1}
domain = {"INACTIVE" : -1,
"BUFFER" : 0,
"ACTIVE" : 1}
flavs_s = {"PSPH" : 0, # Flav dict, lookup by string name
"HOTE" : 1,
"HOTP" : 2}
#flavs_n = bidict(flavs_s).inv # Flav dict, lookup by index
flavs_n = {0 : "PSPH",
1 : "HOTE",
2 : "HOTP"}
spcs_s = {"IDK": 0,
"ELE": 1,
"H+" : 2,
"O+" : 3}
spcs_n = {0: "IDK",
1: "ELE",
2: "H+" ,
3: "O+" }
#------
# Containers
#------
class SpeciesInfo(object):
def __init__(self, grp):
"""
grp: h5 Species group to read from
"""
att = grp.attrs
self.N = att['N']
self.flav = att['flav']
self.spcType = att['spcType']
self.kStart = att['kStart']
self.kEnd = att['kEnd']+1
self.numNuc_p = att['numNuc_p']
self.numNuc_n = att['numNuc_p']
self.amu = att['amu']
self.q = att['q']
self.alami = grp['alami'][:]
self.alamc = 0.5*(self.alami[1:] + self.alami[:-1])
class RAIJUInfo(kh5.H5Info):
"""
Extends H5Info to grab RAIJU-specific info
"""
species: SpeciesInfo
def __init__(self, h5fname, noSubsec=True, useTAC=False, useBars=True):
super().__init__(h5fname, noSubsec, useTAC=useTAC, useBars=useBars)
self.species = []
with h5.File(h5fname) as f5:
# Spatial info
Ni_corner, Nj_corner = getVar(f5, 'X').shape
self.Ni = Ni_corner - 1
self.Nj = Nj_corner - 1
# Species things
for spc_key in f5['Species'].keys():
self.species.append(SpeciesInfo(f5['Species'][spc_key]))
self.nSpc = len(self.species)
self.Nk = 0
for s in self.species: self.Nk += s.N
# Planet info
self.planetInfo = {}
for k in f5['Planet'].attrs.keys():
v = f5['Planet'].attrs[k]
if isinstance(v, bytes):
v = v.decode('utf-8')
self.planetInfo[k] = v
def getSpcFromFlav(self, flav: int) -> SpeciesInfo:
idx = spcIdx(self.species, flav)
if idx == -1:
return None
return self.species[idx]
#------
# Data handlers
#------
def getVar(grp: h5.Group, varName: str, mask:bool=None, broadcast_dims=None) -> np.ndarray:
""" Get vars from h5 file this way so that we're sure everyone agrees on type and shape
"""
try:
var = grp[varName][:].T # .T to go from Fortran to python indexing order
if mask is not None:
if broadcast_dims is not None:
for d in broadcast_dims:
mask = np.expand_dims(mask, axis=d)
mask = np.broadcast_to(mask, var.shape)
var = np.ma.masked_where(mask, var)
return var
except KeyError:
print("Error: {} not in keys".format(varName))
return None
#------
# Species helpers
#------
def spcIdx(spcList: List[SpeciesInfo], flav: int) -> int:
# Get index of a certain species based on its flavor
# spcList: list of SpeciesInfo
for idx, s in enumerate(spcList):
if s.flav == flav:
return idx
# If here, we didn't find index. Complain
print("Warning: spcIdx didn't find flav '{}' in spcList".format(flav))
return -1
def getSpcFromNkArr():
pass
def getMask(s5, dom="ACTIVE"):
# s5 = step#X group object
mask = getVar(s5, 'active') != domain[dom]
# Only include domain specified by caller
return mask
def getMask_cornerByCellCondition(s5, condition):
Ni, Nj = getVar(s5.file,'X').shape
is_active = condition
# True = good point while we do our operations, convert to true np.mask meaning on return
mask_corner = np.full((Ni,Nj),False)
# Any corner bordering an active cell is a good point
mask_corner[:-1,:-1] = is_active
mask_corner[1:,:-1] = np.logical_or(mask_corner[1:,:-1], is_active)
mask_corner[:-1,1:] = np.logical_or(mask_corner[:-1,1:], is_active)
mask_corner[1:,1:] = np.logical_or(mask_corner[1:,1:] , is_active)
return ~mask_corner
#------
# Some analytic stuff
#------
def intensity_maxwell(n, mass, E, kT):
""" Intensity for energy E in an analytic Maxwellian profile
n: density in #/cc
mass: mass in kg
E: energy in keV
kT: temp in keV
j: Intensity [1/(s*sr*keV*cm^2)]
"""
f = n * (mass/(2*np.pi*kT))**(3/2) * np.exp(-E/kT)
j = 2*E/mass**2 * f * 1e2 * np.sqrt(kd.kev2J)
return j
def intensity_kappa(n, mass, E, kT, kappa=6):
""" Intensity for energy E in an analytic Maxwellian profile
n: density in #/cc
mass: mass in kg
E: energy in keV
kT: temp in keV
j: Intensity [1/(s*sr*keV*cm^2)]
"""
gamfac = sp.gamma(kappa+1)/sp.gamma(kappa-0.5)
#f = n * (mass/(2*np.pi*kappa*kT))**(3/2) * gamfac * (1+(E/kappa/kT))**(-kappa-1) # From Baumjohann & Treumann
kap15 = kappa-1.5
E0 = kT*kap15/kappa
kArg = 1 + (E/E0)/kap15
f = n * (mass/(2*np.pi*E0*kap15))**(3/2) * gamfac * kArg**(-kappa-1)
j = 2*E/mass**2 * f * 1e2 * np.sqrt(kd.kev2J)
return j
#------
# Conversions
#------
def lambda2Energy(lambdas, bvol):
"""
lambdas = [eV*(Rx/nT)^(2/3)]
bVol = [Rx/nT]
return: energy [keV]
"""
return lambdas*bvol**(-2/3)*1e-3
def etak2Press(etak, alamc, bVol):
"""
etak [#/cc * Rx/T]
alamc: [eV*(Rx/nT)^(2/3)]
bVol [Rx/nT]
Returns: pressure [nPa]
"""
return 2./3.*etak*alamc*bVol**(-5./3.) * kd.ev2J * 1.e6
def etak2Den(etak, bVol):
"""
etak [#/cc * Rx/T]
bVol [Rx/nT]
Returns: density [#/cc]
"""
return (etak*1.0E-9)/bVol # [#/cc]
# TODO:
# Calc vcorot, vgc, veffective

150
kaipy/raiju/raijuViz.py Normal file
View File

@@ -0,0 +1,150 @@
# Standard modules
# Third-party modules
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
# Kaipy modules
import kaipy.kaiTools as kt
import kaipy.kaiViz as kv
import kaipy.raiju.raijuUtils as ru
inset_bnds = [-15,10,-12.5,12.5]
inset_border_color="dodgerblue"
def plotLonColat(Ax: plt.Axes, lon: np.ndarray, colat: np.ndarray, var: np.ndarray, unit="deg", norm=None, cmap='viridis') -> mpl.collections.QuadMesh:
""" Simple plot function in longitude - colatitude projection
lon and colat inputs should be in radians
lon and colat should be size Ni+1,Nj+1
"""
if unit=="deg":
uStr = "[deg]"
colat = colat*180/np.pi
lon = lon *180/np.pi
else:
uStr = "[rad]"
cMin = np.min(colat)
cMax = np.max(colat)
mp = Ax.pcolormesh(lon, colat, var, norm=norm, cmap=cmap)
Ax.set_xlabel("Longitude " + uStr)
Ax.set_ylabel("Colatitude " + uStr)
Ax.set_ylim([cMax, cMin])
return mp
def plotIono(Ax: plt.Axes, lon: np.ndarray, colat: np.ndarray, var: np.ndarray, norm=None, cmap='viridis', Riono=1) -> mpl.collections.QuadMesh:
""" Simple plot function to show ionosphere projection
lon and colat inputs should be in radians
lon and colat should be size Ni+1,Nj+1
"""
# First get coordinates in polar projection
r, theta = kt.rtp2rt(Riono, colat, lon)
mp = Ax.pcolormesh(theta, r, var, norm=norm, cmap=cmap)
Ax.axis([0,2*np.pi,0,r.max()])
Ax.grid(True)
# Re-do Colat labels
colatStride = 10*np.pi/180 # rad
colatMax = np.max(colat) # rad
colatTickLocs_rad = np.arange(10*np.pi/180, colatMax, colatStride)
rTickLocs = Riono*np.sin(colatTickLocs_rad)
rTickLabels = ["{:2n}".format(c*180/np.pi) for c in colatTickLocs_rad]
Ax.set_yticks(rTickLocs)
Ax.set_yticklabels(rTickLabels)
return mp
def plotXYMin(Ax: plt.Axes, xmin: np.ndarray, ymin: np.ndarray, var: np.ndarray, shading='auto',
norm=None, cmap='viridis', bnds=None,
alpha_grid = 0.25, lblsize=None)-> mpl.collections.QuadMesh:
""" Simple plot function to show xy bmin projection
If xBnds or yBnds is not none, it will use x or y bnds and rescale the other so that aspect ratio is 1
"""
if (type(xmin)==np.ma.core.MaskedArray):
mp = Ax.pcolor(xmin, ymin, var, norm=norm, cmap=cmap, shading=shading, rasterized=True)
else:
mp = Ax.pcolormesh(xmin, ymin, var, norm=norm, cmap=cmap, shading=shading, rasterized=True)
if alpha_grid > 0:
Ax.grid(alpha=alpha_grid)
if lblsize is not None:
Ax.set_xlabel('X [R$_p$]', fontsize=lblsize)
Ax.set_ylabel('Y [R$_p$]', fontsize=lblsize)
if bnds is not None:
#kv.SetAx(bnds,ax=Ax,Adj='datalim')
kv.SetAx(bnds,ax=Ax,Adj='datalim')
#Ax.set_xlim([bnds[0],bnds[1]])
#Ax.set_ylim([bnds[2],bnds[3]])
kv.addEarth2D(ax=Ax)
return mp
def drawGrid(ax, X, Y, color='slategrey', linewidth='0.15', alpha=0.8, mask=None):
if mask is not None:
Xplt = np.ma.masked_where(mask, X)
Yplt = np.ma.masked_where(mask, Y)
else:
Xplt = X
Yplt = Y
ax.plot(Xplt , Yplt , color=color, alpha=alpha, linewidth=linewidth)
ax.plot(Xplt.T, Yplt.T, color=color, alpha=alpha, linewidth=linewidth)
def plotInset(ax: plt.Axes, raiI: ru.RAIJUInfo, stepStr: str, norm_press: mpl.colors.Normalize, ax_gam = None) -> list:
import h5py as h5
f5 = h5.File(raiI.fname)
rai_idx = raiI.stepStrs.index(stepStr)
s5 = f5[stepStr]
idx_psph = ru.spcIdx(raiI.species, ru.flavs_s["PSPH"])
xmin = ru.getVar(s5, 'xmin')
ymin = ru.getVar(s5, 'ymin')
xmcc = kt.to_center2D(xmin)
ymcc = kt.to_center2D(ymin)
active = ru.getVar(s5, 'active')
mask_cc = active != ru.domain['ACTIVE']
mask_corner = ru.getMask_cornerByCellCondition(s5, active == ru.domain['ACTIVE'])
press_tot = ru.getVar(s5,'Pressure',mask=mask_cc,broadcast_dims=(2,))[:,:,0] # Bulk
density_psph = ru.getVar(s5,'Density',mask=mask_cc,broadcast_dims=(2,))[:,:,idx_psph+1] # +1 to account for bulk at idx 0
plotXYMin(ax, xmin, ymin, press_tot, norm=norm_press, cmap='viridis',bnds=inset_bnds)
drawGrid(ax, xmin, ymin, mask=mask_corner,alpha=0.4)
psph_lvls = [1,10,100,1000]
ax.contour(xmcc,ymcc,density_psph,levels=psph_lvls,colors='white',alpha=0.5,linewidths=1)
# Decoration
kv.SetAxLabs(ax,xLab=None,yLab=None)
kv.addEarth2D(ax=ax)
ax.spines['bottom'].set_color(inset_border_color)
ax.spines['top'].set_color(inset_border_color)
ax.spines['right'].set_color(inset_border_color)
ax.spines['left'].set_color(inset_border_color)
ax.grid(alpha=0.4)
ax.set_title("RAIJU Pressure",fontsize="small",color=inset_border_color)
# Axes grid
gCol = "cyan"
gLW = 0.15
xS = [-10,-5,0,5]
yS = [-10,-5,0,5,10]
for x in xS:
ax.axvline(x,linewidth=gLW,color=gCol)
for y in yS:
ax.axhline(y,linewidth=gLW,color=gCol)
# Extra stuff on gam eq panel
if ax_gam is not None:
ax_gam.contour(xmcc, ymcc, active, levels=[ru.domain['ACTIVE']-0.9],colors='orange',linewidths=0.5,alpha=0.7)
ax.contour( xmcc, ymcc, active, levels=[ru.domain['ACTIVE']-0.5],colors='orange',linewidths=0.5,alpha=1.0)
#ax.contour(xmin,ymin,mask_corner.astype(int),levels=[0], colors='orange',linewidths=0.5,alpha=1.0)
return inset_bnds

View File

View File

@@ -0,0 +1,169 @@
MLT Kp Intercept L log10(E) L^2 log10(E)^2 L^3 log10(E)^3 log10(E)*L log10(E)*L^2 log10(E)^2*L Adjusted R2
0 1 -9.717181e+00 7.204274e+00 -3.773921e+00 -1.496923e+00 -8.897443e-01 1.122206e-01 1.720684e-01 7.319817e-01 7.886410e-02 3.525678e-01 0.82448
0 2 -2.945411e+00 3.066352e+00 -3.141152e+00 -6.402161e-01 -1.039579e+00 5.404518e-02 1.168904e-01 9.266642e-01 5.994503e-02 3.966304e-01 0.93159
0 3 9.890714e-01 6.886358e-01 -1.466153e+00 -1.451928e-01 -4.153113e-01 2.069758e-02 1.924237e-01 9.012235e-01 5.583555e-02 3.945901e-01 0.95829
0 4 3.852039e+00 -1.176268e+00 -4.278696e-01 2.504448e-01 9.717711e-02 -5.547521e-03 2.740005e-01 9.408564e-01 5.187616e-02 4.049745e-01 0.96932
0 5 6.006599e+00 -2.177471e+00 1.988820e+00 4.797396e-01 1.590386e+00 -2.211532e-02 5.205646e-01 1.016683e+00 3.518574e-02 3.863031e-01 0.97468
0 6 9.362199e+00 -4.631816e+00 2.171715e+00 9.973425e-01 1.628007e+00 -5.584455e-02 5.182470e-01 9.777994e-01 3.918595e-02 3.857173e-01 0.97183
0 7 1.407725e+01 -7.921180e+00 2.665594e+00 1.685897e+00 1.719137e+00 -1.007732e-01 5.024012e-01 8.108719e-01 4.952734e-02 3.557380e-01 0.96121
1 1 -7.359401e+00 5.884180e+00 -2.919064e+00 -1.280964e+00 -7.194898e-01 1.004658e-01 1.848896e-01 4.476771e-01 9.795562e-02 3.246588e-01 0.8113
1 2 -9.211592e-01 1.879919e+00 -2.331452e+00 -4.555934e-01 -9.799721e-01 4.440510e-02 9.607246e-02 5.884254e-01 8.034954e-02 3.569996e-01 0.93061
1 3 2.214357e+00 -1.302451e-01 -1.253408e+00 -2.825422e-02 -6.760874e-01 1.478623e-02 1.114119e-01 6.211463e-01 6.977352e-02 3.569444e-01 0.95885
1 4 4.602497e+00 -1.757413e+00 -5.268525e-01 3.225730e-01 -3.095982e-01 -8.982241e-03 1.642781e-01 7.068561e-01 5.973179e-02 3.663537e-01 0.96771
1 5 5.647597e+00 -2.090594e+00 2.072220e+00 4.521858e-01 1.630797e+00 -2.093337e-02 5.073641e-01 9.731945e-01 2.705271e-02 3.561372e-01 0.9769
1 6 9.041642e+00 -4.539197e+00 2.387552e+00 9.639003e-01 1.697711e+00 -5.406964e-02 5.076273e-01 8.951338e-01 3.382134e-02 3.521105e-01 0.97444
1 7 1.358006e+01 -7.724426e+00 2.883817e+00 1.632235e+00 1.787948e+00 -9.760212e-02 4.934266e-01 7.232415e-01 4.596935e-02 3.247448e-01 0.96432
2 1 -3.874943e+00 4.102231e+00 -1.373509e+00 -1.041292e+00 -4.183570e-01 9.227025e-02 2.361563e-01 -1.138304e-01 1.485082e-01 3.037375e-01 0.7916
2 2 1.135135e+00 8.053878e-01 -1.219720e+00 -3.253353e-01 -8.572429e-01 4.055670e-02 9.456559e-02 1.233136e-01 1.146499e-01 3.188955e-01 0.92407
2 3 3.470548e+00 -8.068562e-01 -5.982210e-01 3.832536e-02 -7.467759e-01 1.380794e-02 7.074457e-02 2.502543e-01 9.399586e-02 3.198763e-01 0.95775
2 4 5.298927e+00 -2.116907e+00 -7.789224e-02 3.310106e-01 -4.724148e-01 -6.974028e-03 9.885310e-02 3.806822e-01 7.604378e-02 3.223885e-01 0.96672
2 5 5.390708e+00 -2.080829e+00 1.977300e+00 4.387184e-01 1.568525e+00 -2.012174e-02 4.844172e-01 9.273081e-01 2.346362e-02 3.360744e-01 0.97834
2 6 8.740577e+00 -4.493841e+00 2.354275e+00 9.429094e-01 1.665505e+00 -5.276517e-02 4.895662e-01 8.388821e-01 3.088775e-02 3.306408e-01 0.97598
2 7 1.312859e+01 -7.579869e+00 2.884980e+00 1.591603e+00 1.778583e+00 -9.498086e-02 4.806610e-01 6.638055e-01 4.400758e-02 3.043388e-01 0.96631
3 1 -3.007360e+00 3.878241e+00 -2.503594e-01 -1.104900e+00 -2.463186e-01 1.027349e-01 2.620712e-01 -5.812605e-01 1.875912e-01 2.802112e-01 0.76887
3 2 1.428129e+00 7.946179e-01 -4.736181e-01 -4.029787e-01 -8.095079e-01 5.002179e-02 9.131136e-02 -2.468938e-01 1.429859e-01 2.920961e-01 0.91249
3 3 3.492771e+00 -7.037845e-01 -6.385505e-02 -4.812099e-02 -7.847110e-01 2.270458e-02 4.455866e-02 -6.340309e-02 1.147853e-01 2.888142e-01 0.95362
3 4 5.076508e+00 -1.881944e+00 3.548632e-01 2.252584e-01 -5.466503e-01 2.435504e-03 5.898316e-02 1.014577e-01 9.081530e-02 2.853255e-01 0.96397
3 5 5.003611e+00 -1.994916e+00 1.763108e+00 4.165897e-01 1.480360e+00 -1.889926e-02 4.619276e-01 9.120572e-01 1.959584e-02 3.219342e-01 0.97861
3 6 8.287509e+00 -4.367077e+00 2.157762e+00 9.136333e-01 1.595472e+00 -5.121285e-02 4.693425e-01 8.258174e-01 2.614249e-02 3.146205e-01 0.97598
3 7 1.256192e+01 -7.383831e+00 2.689740e+00 1.549352e+00 1.722078e+00 -9.259352e-02 4.643921e-01 6.559621e-01 3.934115e-02 2.896038e-01 0.96627
4 1 1.050305e+00 7.848777e-01 9.479916e-01 -3.083059e-01 1.306091e+00 3.153739e-02 4.688779e-01 -2.334505e-01 6.162030e-02 7.291783e-02 0.68054
4 2 4.040210e+00 -1.134349e+00 -1.503822e-01 7.706201e-02 -9.964354e-02 6.942414e-03 1.651045e-01 -2.702495e-02 5.874122e-02 1.475941e-01 0.89639
4 3 4.404270e+00 -1.469072e+00 1.979190e-03 1.664247e-01 -4.765612e-01 -5.731605e-05 3.152533e-02 7.061707e-02 5.191952e-02 1.669078e-01 0.95584
4 4 4.323673e+00 -1.548876e+00 2.847488e-01 2.024510e-01 -4.088867e-01 -3.419682e-03 -1.370144e-03 2.202261e-01 3.701387e-02 1.739477e-01 0.96832
4 5 2.515772e+00 -4.929388e-01 1.519877e+00 1.045296e-01 1.563366e+00 1.304891e-03 4.611017e-01 9.923663e-01 8.081022e-03 3.041743e-01 0.97983
4 6 3.614171e+00 -1.434655e+00 2.191388e+00 3.093934e-01 2.156221e+00 -1.268924e-02 5.007234e-01 1.031511e+00 -8.471922e-03 2.473691e-01 0.97928
4 7 1.181002e+00 8.305165e-02 4.211134e+00 5.334156e-04 3.472403e+00 6.208793e-03 4.135005e-01 8.435557e-01 -4.340292e-02 -2.193345e-02 0.90882
5 1 -3.635509e-01 1.537124e+00 6.839448e-01 -4.374485e-01 1.477097e+00 3.619611e-02 5.420787e-01 -3.200998e-02 4.117443e-02 1.085585e-01 0.66573
5 2 2.730877e+00 -4.037838e-01 -3.262462e-01 -5.815076e-02 8.927091e-02 1.267726e-02 2.225624e-01 1.105053e-01 3.799409e-02 1.519576e-01 0.85975
5 3 3.130800e+00 -7.408152e-01 -8.019317e-03 2.688265e-02 -2.800136e-01 6.361500e-03 6.581481e-02 1.283701e-01 3.327723e-02 1.422884e-01 0.94739
5 4 2.955802e+00 -7.650633e-01 2.303200e-01 5.182572e-02 -2.653012e-01 3.848474e-03 1.075704e-02 2.684518e-01 1.739558e-02 1.381535e-01 0.96545
5 5 2.124358e+00 -4.028353e-01 1.101238e+00 9.212299e-02 1.452351e+00 2.396013e-03 4.613711e-01 1.037621e+00 1.078170e-02 3.217369e-01 0.97517
5 6 5.591571e+00 -2.882277e+00 1.412788e+00 6.001848e-01 1.516588e+00 -3.005855e-02 4.286400e-01 9.915549e-01 1.723768e-02 3.235609e-01 0.95989
5 7 4.501496e-01 3.031204e-01 3.365214e+00 -1.985564e-02 3.409760e+00 6.876650e-03 4.318068e-01 1.082152e+00 -5.730041e-02 1.509701e-03 0.90629
6 1 -1.082603e+00 1.875584e+00 9.310370e-01 -4.950986e-01 1.787906e+00 3.858447e-02 6.521055e-01 1.961963e-02 4.202852e-02 1.523830e-01 0.71376
6 2 2.226915e+00 -1.704689e-01 -3.963971e-01 -1.029844e-01 3.216038e-01 1.479182e-02 3.368555e-01 1.955210e-01 3.696059e-02 1.988433e-01 0.8417
6 3 2.709992e+00 -5.353846e-01 -5.663882e-02 -1.585543e-02 -1.096716e-01 8.494261e-03 1.598446e-01 1.609246e-01 3.461982e-02 1.766625e-01 0.9334
6 4 2.586263e+00 -5.847657e-01 1.943038e-01 1.230286e-02 -1.479929e-01 5.925418e-03 8.955435e-02 2.580448e-01 2.255908e-02 1.664718e-01 0.95531
6 5 1.504292e+00 -1.921066e-01 4.736238e-01 4.748769e-02 1.344912e+00 6.977116e-03 5.404359e-01 1.107407e+00 2.810924e-02 4.008609e-01 0.96374
6 6 4.466400e+00 -2.382881e+00 6.159318e-01 5.076358e-01 1.471883e+00 -2.276222e-02 5.221047e-01 1.166062e+00 2.602738e-02 4.047381e-01 0.94311
6 7 2.351494e-01 1.666321e-01 2.214849e+00 2.901656e-02 3.314877e+00 4.447027e-03 5.253594e-01 1.391421e+00 -5.814033e-02 9.645109e-02 0.91061
7 1 -1.609647e+00 2.138282e+00 9.978059e-01 -5.454796e-01 2.010335e+00 4.129492e-02 7.025682e-01 7.441586e-02 3.843694e-02 1.605779e-01 0.74681
7 2 1.205435e+00 4.161637e-01 -6.240078e-01 -2.239074e-01 5.056336e-01 2.247393e-02 4.051097e-01 2.968045e-01 3.199971e-02 2.171849e-01 0.82391
7 3 1.735397e+00 2.397207e-02 -2.982400e-01 -1.309153e-01 3.509832e-02 1.574091e-02 2.127733e-01 2.436606e-01 2.895244e-02 1.849069e-01 0.91497
7 4 1.747765e+00 -1.078381e-01 -6.498805e-02 -8.557804e-02 -6.364141e-02 1.200978e-02 1.234992e-01 3.194689e-01 1.761723e-02 1.681927e-01 0.94378
7 5 5.800442e-01 2.740269e-01 -1.060418e-01 -3.751396e-02 1.318171e+00 1.332550e-02 5.758035e-01 1.244108e+00 3.008228e-02 4.363843e-01 0.95472
7 6 3.240336e+00 -1.725721e+00 5.217625e-02 3.879902e-01 1.535061e+00 -1.431980e-02 5.734181e-01 1.338752e+00 2.441768e-02 4.362915e-01 0.9364
7 7 -3.419454e-01 3.364636e-01 1.162533e+00 2.115812e-02 3.261958e+00 5.064395e-03 5.677576e-01 1.717444e+00 -7.004800e-02 1.465979e-01 0.91279
8 1 -1.308247e+00 1.888381e+00 9.812949e-01 -4.930137e-01 2.128228e+00 3.763054e-02 7.285720e-01 1.276625e-01 3.701688e-02 1.744106e-01 0.78102
8 2 6.496435e-01 7.090310e-01 -9.210358e-01 -2.847685e-01 6.275309e-01 2.650405e-02 4.616605e-01 4.027105e-01 2.954339e-02 2.436590e-01 0.81642
8 3 1.224925e+00 2.956671e-01 -5.856631e-01 -1.880907e-01 1.435859e-01 1.951742e-02 2.621966e-01 3.290408e-01 2.645165e-02 2.028016e-01 0.89064
8 4 1.362127e+00 9.646588e-02 -2.953666e-01 -1.299670e-01 2.750683e-02 1.496309e-02 1.621236e-01 3.674189e-01 1.694558e-02 1.768604e-01 0.92377
8 5 4.360637e-02 5.273507e-01 -5.878643e-01 -8.277919e-02 1.336013e+00 1.756848e-02 6.253131e-01 1.358198e+00 3.779334e-02 4.803578e-01 0.94084
8 6 2.251631e+00 -1.218175e+00 -5.475816e-01 3.014285e-01 1.634329e+00 -7.652272e-03 6.444620e-01 1.540731e+00 2.635283e-02 4.850513e-01 0.92387
8 7 -6.076540e-01 3.305252e-01 1.344023e-01 4.882027e-02 3.284135e+00 3.630749e-03 6.318609e-01 2.061262e+00 -8.015682e-02 2.045887e-01 0.91829
9 1 -5.066641e-01 1.329285e+00 9.461658e-01 -3.763959e-01 2.240101e+00 2.978094e-02 7.368882e-01 1.972342e-01 3.197202e-02 1.768036e-01 0.81157
9 2 9.160371e-02 1.003259e+00 -1.122999e+00 -3.433058e-01 8.014770e-01 3.033769e-02 5.132520e-01 4.999701e-01 2.610510e-02 2.586349e-01 0.82344
9 3 6.441270e-01 6.074673e-01 -8.280261e-01 -2.502328e-01 3.001515e-01 2.354826e-02 3.102515e-01 4.242577e-01 2.217524e-02 2.137150e-01 0.86982
9 4 9.621762e-01 3.067436e-01 -4.664940e-01 -1.727513e-01 1.712550e-01 1.775645e-02 2.018135e-01 4.221124e-01 1.508525e-02 1.801912e-01 0.90089
9 5 -5.807546e-01 8.358583e-01 -9.227595e-01 -1.324629e-01 1.486863e+00 2.185117e-02 6.931474e-01 1.487158e+00 4.400470e-02 5.199000e-01 0.92804
9 6 9.998263e-01 -5.206567e-01 -9.205089e-01 1.792725e-01 1.868123e+00 1.036909e-03 7.270077e-01 1.728786e+00 2.663989e-02 5.212735e-01 0.91573
9 7 -1.395993e+00 6.936340e-01 -5.686723e-01 6.332513e-04 3.424236e+00 7.041325e-03 7.011817e-01 2.342476e+00 -8.797079e-02 2.473096e-01 0.92407
10 1 6.079346e-01 5.764501e-01 8.115558e-01 -2.184695e-01 2.348472e+00 1.915197e-02 7.311287e-01 3.106179e-01 2.082615e-02 1.686596e-01 0.838
10 2 -7.268649e-01 1.466423e+00 -1.092733e+00 -4.325192e-01 1.038170e+00 3.593924e-02 5.489411e-01 5.537068e-01 2.192478e-02 2.517090e-01 0.83772
10 3 2.556828e-01 7.956948e-01 -1.003445e+00 -2.837742e-01 5.126386e-01 2.553391e-02 3.518927e-01 5.288852e-01 1.452997e-02 2.116595e-01 0.86064
10 4 7.065774e-01 4.202723e-01 -6.093885e-01 -1.918654e-01 3.621433e-01 1.879915e-02 2.357079e-01 5.007935e-01 8.970089e-03 1.736803e-01 0.88263
10 5 -9.592237e-01 1.000408e+00 -1.082641e+00 -1.462954e-01 1.769092e+00 2.324966e-02 7.676456e-01 1.630683e+00 4.522151e-02 5.448054e-01 0.92157
10 6 -5.821246e-02 8.253724e-02 -1.046605e+00 8.037739e-02 2.225443e+00 7.622167e-03 8.093918e-01 1.903019e+00 2.274182e-02 5.378206e-01 0.91615
10 7 -2.338184e+00 1.223269e+00 -7.855223e-01 -8.592414e-02 3.651338e+00 1.259107e-02 7.501100e-01 2.502162e+00 -9.368997e-02 2.579936e-01 0.93182
11 1 1.584285e+00 -9.233146e-02 4.913702e-01 -7.566464e-02 2.481888e+00 9.490070e-03 7.329837e-01 4.912006e-01 3.914822e-03 1.591060e-01 0.85812
11 2 -1.233141e+00 1.724787e+00 -9.581509e-01 -4.738511e-01 1.320496e+00 3.796105e-02 5.644950e-01 6.102217e-01 1.219256e-02 2.222982e-01 0.85947
11 3 1.827068e-01 7.765828e-01 -1.183786e+00 -2.699423e-01 7.669048e-01 2.408920e-02 3.812356e-01 6.690887e-01 2.258100e-04 1.942093e-01 0.86762
11 4 6.871972e-01 3.742267e-01 -7.970033e-01 -1.730136e-01 5.907723e-01 1.701475e-02 2.586978e-01 6.313598e-01 -4.919297e-03 1.544219e-01 0.87667
11 5 -9.381048e-01 9.140218e-01 -1.186769e+00 -1.013428e-01 2.127841e+00 1.981853e-02 8.292878e-01 1.814266e+00 3.555110e-02 5.461664e-01 0.92408
11 6 -4.972398e-01 3.141483e-01 -1.051545e+00 5.992790e-02 2.625577e+00 8.281900e-03 8.692018e-01 2.075338e+00 1.109089e-02 5.285473e-01 0.92303
11 7 -2.912724e+00 1.566532e+00 -7.009429e-01 -1.358704e-01 3.905999e+00 1.504579e-02 7.656498e-01 2.588276e+00 -1.026651e-01 2.357367e-01 0.94093
12 1 3.795952e+00 -1.609479e+00 -3.957772e-01 2.542400e-01 2.626393e+00 -1.324950e-02 7.607905e-01 8.914563e-01 -3.213962e-02 1.607167e-01 0.81496
12 2 9.414399e-01 7.276113e-03 -2.638211e+00 -4.937976e-02 2.464290e+00 5.299087e-03 5.154030e-01 1.694110e+00 -1.217717e-01 1.060381e-02 0.92512
12 3 -1.826336e+00 2.001220e+00 -1.062499e+00 -5.044658e-01 1.421460e+00 3.846524e-02 3.475318e-01 8.563474e-01 -3.515948e-02 7.200227e-02 0.93612
12 4 1.091590e-01 6.744938e-01 -1.006791e+00 -2.180554e-01 1.035742e+00 1.896149e-02 2.513562e-01 8.626383e-01 -3.680987e-02 8.137101e-02 0.90779
12 5 -2.650530e-01 3.934711e-01 -1.363908e+00 4.468812e-02 2.491388e+00 8.265016e-03 8.734229e-01 2.064115e+00 1.198487e-02 5.295803e-01 0.92943
12 6 1.403355e+00 -9.923685e-01 -1.340616e+00 3.576970e-01 2.578394e+00 -1.248317e-02 9.303741e-01 2.201778e+00 1.047900e-02 5.851626e-01 0.89932
12 7 2.509748e+00 -1.973148e+00 -1.179463e+00 5.883023e-01 2.987827e+00 -2.935602e-02 1.016046e+00 2.393637e+00 -1.646417e-02 5.747707e-01 0.92602
13 1 4.746942e+00 -2.558156e+00 -1.186727e+00 4.880320e-01 2.900345e+00 -2.996777e-02 6.265849e-01 1.273604e+00 -7.816415e-02 5.587602e-02 0.88353
13 2 4.831451e+00 -2.725641e+00 -2.085771e+00 5.398800e-01 2.502417e+00 -3.465279e-02 3.921621e-01 1.614453e+00 -1.319834e-01 -6.435277e-02 0.95219
13 3 3.992977e+00 -2.157449e+00 -1.657250e+00 4.149461e-01 1.869796e+00 -2.561423e-02 2.871417e-01 1.343384e+00 -1.034915e-01 -3.756972e-02 0.95133
13 4 2.400486e+00 -1.090502e+00 -1.266064e+00 1.786835e-01 1.361613e+00 -8.450192e-03 2.460354e-01 1.080190e+00 -6.583955e-02 2.563368e-02 0.92219
13 5 -9.144487e-01 8.800053e-01 -1.485896e+00 -2.665061e-02 2.909180e+00 1.033890e-02 9.077201e-01 2.325317e+00 -2.244458e-02 4.854397e-01 0.94403
13 6 -3.069663e+00 2.301743e+00 -2.144761e+00 -3.388892e-01 2.369229e+00 3.262324e-02 9.135671e-01 2.383983e+00 -4.136037e-03 5.984553e-01 0.9073
13 7 -1.111552e+01 7.990864e+00 -3.070002e+00 -1.549400e+00 1.867375e+00 1.118725e-01 9.435024e-01 2.560170e+00 -1.446240e-02 6.814598e-01 0.88757
14 1 1.242540e+00 -2.369845e-01 -1.419802e+00 8.260015e-03 2.972485e+00 1.156809e-03 5.212952e-01 1.408200e+00 -1.014738e-01 -2.296493e-02 0.89436
14 2 1.368811e+00 -4.145601e-01 -2.280856e+00 5.740560e-02 2.450007e+00 -2.985853e-03 3.109832e-01 1.682819e+00 -1.424004e-01 -1.039245e-01 0.96163
14 3 1.228625e+00 -3.074402e-01 -1.908024e+00 3.084710e-02 1.861609e+00 -7.324499e-04 2.322341e-01 1.454456e+00 -1.170960e-01 -6.583994e-02 0.95624
14 4 9.318505e-01 -8.583122e-02 -1.478347e+00 -2.767564e-02 1.499320e+00 4.344851e-03 2.301372e-01 1.230955e+00 -8.575766e-02 -3.931169e-03 0.94057
14 5 1.432796e+00 -7.039165e-01 -1.539426e+00 3.447957e-01 3.325479e+00 -1.743970e-02 9.270213e-01 2.570657e+00 -6.012586e-02 4.282312e-01 0.94925
14 6 8.747952e+00 -5.660286e+00 -1.996150e+00 1.383810e+00 2.770045e+00 -8.538469e-02 9.037252e-01 2.494688e+00 -4.085627e-02 5.001229e-01 0.86508
14 7 2.967365e+00 -1.483125e+00 -2.468505e+00 4.985097e-01 2.507725e+00 -2.839179e-02 9.571531e-01 2.559916e+00 -4.860509e-02 5.434484e-01 0.85267
15 1 1.994942e+00 -6.555317e-01 -9.786397e-01 9.222377e-02 2.990598e+00 -4.051119e-03 5.103009e-01 1.267481e+00 -9.162911e-02 -3.369420e-02 0.89008
15 2 1.963584e+00 -7.859760e-01 -2.306874e+00 1.416005e-01 2.554944e+00 -8.779408e-03 3.022099e-01 1.737735e+00 -1.513754e-01 -1.268836e-01 0.9563
15 3 1.458040e+00 -4.180364e-01 -1.778768e+00 5.630375e-02 1.907537e+00 -2.330213e-03 2.224492e-01 1.426373e+00 -1.165456e-01 -7.909000e-02 0.95286
15 4 2.745900e+00 -1.327290e+00 -1.972995e+00 2.563148e-01 1.682334e+00 -1.611474e-02 2.078639e-01 1.520069e+00 -1.218943e-01 -4.948951e-02 0.93794
15 5 1.826867e+00 -9.040947e-01 -1.520564e+00 4.006556e-01 3.544015e+00 -2.263840e-02 9.401753e-01 2.685085e+00 -7.891802e-02 4.005182e-01 0.94983
15 6 9.225378e+00 -5.938465e+00 -2.074143e+00 1.459699e+00 3.004200e+00 -9.190359e-02 9.271197e-01 2.649451e+00 -6.093322e-02 4.793848e-01 0.86549
15 7 3.091311e+00 -1.498489e+00 -2.306911e+00 5.168763e-01 2.754097e+00 -3.127343e-02 9.674050e-01 2.639684e+00 -6.627824e-02 5.084716e-01 0.85807
16 1 3.455794e+00 -1.486545e+00 -4.241646e-01 2.553252e-01 2.897685e+00 -1.393926e-02 4.953749e-01 1.043180e+00 -7.239104e-02 -3.229877e-02 0.88572
16 2 2.605198e+00 -1.151861e+00 -2.244961e+00 2.195486e-01 2.583749e+00 -1.359540e-02 2.940331e-01 1.720754e+00 -1.512312e-01 -1.393042e-01 0.94717
16 3 1.819715e+00 -5.552250e-01 -1.492429e+00 7.627047e-02 1.815396e+00 -2.575816e-03 2.228693e-01 1.269107e+00 -9.778961e-02 -6.373164e-02 0.94071
16 4 1.261123e+00 -1.728350e-01 -1.180981e+00 -1.378674e-02 1.472255e+00 4.495729e-03 2.288470e-01 1.093459e+00 -6.965027e-02 1.820913e-03 0.92354
16 5 1.662075e+00 -5.909674e-01 -1.032808e+00 3.036510e-01 3.420686e+00 -1.432329e-02 9.422668e-01 2.419683e+00 -5.111377e-02 4.185730e-01 0.93755
16 6 9.062144e+00 -5.641461e+00 -1.647969e+00 1.368319e+00 2.893126e+00 -8.392754e-02 9.367054e-01 2.409603e+00 -3.379991e-02 5.021036e-01 0.83891
16 7 2.972117e+00 -1.238725e+00 -1.911060e+00 4.349748e-01 2.623632e+00 -2.402190e-02 9.727758e-01 2.407711e+00 -3.981335e-02 5.321525e-01 0.8466
17 1 6.065370e+00 -3.036624e+00 -1.204084e-02 5.641127e-01 2.756971e+00 -3.286474e-02 4.653054e-01 8.509755e-01 -5.683971e-02 -3.862627e-02 0.87655
17 2 3.923084e+00 -1.907470e+00 -2.128049e+00 3.679667e-01 2.450187e+00 -2.189545e-02 2.936385e-01 1.601658e+00 -1.351094e-01 -1.236702e-01 0.92472
17 3 1.621678e+00 -2.015437e-01 -6.733390e-01 -3.357035e-02 1.440304e+00 8.215388e-03 2.342461e-01 7.653045e-01 -3.439944e-02 5.107264e-03 0.91385
17 4 1.111911e+00 1.243552e-01 -5.019693e-01 -1.052095e-01 1.134048e+00 1.355940e-02 2.308674e-01 6.698652e-01 -1.594878e-02 5.972407e-02 0.88394
17 5 1.171040e+00 2.179109e-02 -3.418401e-01 1.133921e-01 2.971660e+00 2.502135e-03 9.291163e-01 1.896026e+00 9.636920e-03 4.748118e-01 0.90471
17 6 8.870233e+00 -5.244293e+00 -1.112737e+00 1.223429e+00 2.451975e+00 -6.975656e-02 9.381103e-01 1.935719e+00 2.655594e-02 5.699057e-01 0.78699
17 7 3.603072e+00 -1.434442e+00 -1.722606e+00 4.197760e-01 2.101419e+00 -1.864621e-02 9.686834e-01 2.030916e+00 1.464855e-02 6.122669e-01 0.83498
18 1 1.082397e+01 -5.971812e+00 -4.770886e-01 1.146059e+00 2.577005e+00 -6.751868e-02 4.057286e-01 8.848197e-01 -6.116616e-02 -7.655496e-02 0.83153
18 2 6.135939e+00 -3.064357e+00 -1.681550e+00 5.476164e-01 1.634596e+00 -2.726348e-02 2.771841e-01 1.006313e+00 -5.079006e-02 -1.432417e-02 0.83838
18 3 1.724760e+00 -8.414072e-03 -3.017019e-01 -1.301847e-01 7.400475e-01 2.104870e-02 2.109209e-01 2.444144e-01 4.343080e-02 1.012454e-01 0.85289
18 4 2.442864e+00 -5.483793e-01 -5.906341e-01 -6.476063e-03 5.333321e-01 1.231103e-02 2.145601e-01 3.817825e-01 3.833219e-02 1.472210e-01 0.83846
18 5 1.344505e+00 9.699000e-02 -6.337698e-01 5.032382e-02 2.277124e+00 1.129115e-02 9.031503e-01 1.626972e+00 5.876497e-02 5.640278e-01 0.85781
18 6 9.111154e+00 -5.207996e+00 -1.319588e+00 1.167587e+00 1.705285e+00 -6.148092e-02 8.926992e-01 1.622487e+00 7.799110e-02 6.537055e-01 0.76933
18 7 3.367097e+00 -1.055645e+00 -1.444817e+00 2.936776e-01 1.358158e+00 -6.841480e-03 8.764732e-01 1.570444e+00 6.559029e-02 6.528755e-01 0.85086
19 1 1.045173e+01 -4.941345e+00 2.088544e+00 7.367673e-01 1.576796e+00 -2.060349e-02 3.211369e-01 -6.732945e-01 1.313307e-01 3.047173e-02 0.62546
19 2 3.703805e+00 -5.375542e-01 8.605968e-01 -2.386394e-01 2.000571e-01 5.240058e-02 2.518747e-01 -8.312531e-01 2.203020e-01 2.530480e-01 0.76811
19 3 3.272628e+00 -4.558256e-01 -2.863843e-01 -2.107743e-01 -2.212628e-01 4.758636e-02 2.495467e-01 -3.954864e-01 1.979005e-01 3.445951e-01 0.83723
19 4 4.151799e+00 -1.163107e+00 -7.815812e-01 -3.602281e-02 -3.369410e-01 3.421682e-02 2.939125e-01 -1.301308e-01 1.840421e-01 4.095479e-01 0.84295
19 5 2.430916e+00 -5.853717e-01 -1.651001e+00 1.615683e-01 1.360993e+00 7.354574e-03 8.027559e-01 1.550617e+00 8.437972e-02 6.310538e-01 0.8633
19 6 9.589982e+00 -5.442344e+00 -1.902050e+00 1.178300e+00 7.118181e-01 -5.898198e-02 7.425192e-01 1.372019e+00 1.104244e-01 6.923491e-01 0.81967
19 7 3.876753e+00 -1.278652e+00 -1.571642e+00 3.014910e-01 3.879600e-01 -5.220906e-03 6.825008e-01 1.184419e+00 9.635829e-02 6.463116e-01 0.89373
20 1 8.818423e+00 -3.885616e+00 1.977768e+00 5.171642e-01 3.360926e-01 -6.969479e-05 3.518455e-01 -1.178708e+00 2.501245e-01 2.894164e-01 0.40912
20 2 4.558966e+00 -1.402672e+00 -9.888905e-01 3.233388e-02 -4.743974e-01 3.207056e-02 1.957514e-01 -3.101404e-01 2.026337e-01 3.518889e-01 0.78776
20 3 5.278691e+00 -1.976263e+00 -2.136653e+00 1.696426e-01 -8.774690e-01 2.264980e-02 2.230293e-01 1.211223e-01 1.908473e-01 4.719043e-01 0.87646
20 4 7.510426e+00 -3.536111e+00 -2.728126e+00 5.091674e-01 -9.617025e-01 -2.305694e-05 2.979294e-01 4.199695e-01 1.829638e-01 5.617737e-01 0.8876
20 5 4.348244e+00 -1.800377e+00 -2.704540e+00 3.893456e-01 3.900327e-01 -2.537683e-03 6.766795e-01 1.545482e+00 1.164300e-01 7.199897e-01 0.91058
20 6 1.124045e+01 -6.484624e+00 -2.881991e+00 1.373009e+00 -2.577640e-01 -6.712893e-02 6.072741e-01 1.352019e+00 1.407729e-01 7.735385e-01 0.8799
20 7 4.717043e+00 -1.737761e+00 -1.978561e+00 3.722787e-01 -4.753988e-01 -6.761770e-03 5.151032e-01 1.002508e+00 1.231074e-01 6.697817e-01 0.92448
21 1 4.640154e+00 -2.058466e+00 -2.997508e+00 3.229845e-01 -3.267520e-01 7.138257e-03 5.035649e-01 4.081604e-01 1.794630e-01 5.391301e-01 0.67759
21 2 2.121799e+00 -2.683458e-01 -3.333377e+00 -5.632149e-02 -8.802042e-01 2.931274e-02 1.548270e-01 6.114660e-01 1.282823e-01 4.094238e-01 0.86667
21 3 6.281104e+00 -3.060090e+00 -3.968978e+00 5.414357e-01 -1.146769e+00 -1.021923e-02 1.901006e-01 9.614629e-01 1.213459e-01 5.239261e-01 0.92484
21 4 8.247573e+00 -4.368089e+00 -3.711893e+00 8.203851e-01 -1.261375e+00 -2.889684e-02 2.156578e-01 9.815061e-01 1.295587e-01 5.859233e-01 0.94245
21 5 6.556615e+00 -3.025109e+00 -2.490098e+00 6.514720e-01 -2.943759e-02 -2.238848e-02 5.300817e-01 1.512397e+00 1.036178e-01 6.936618e-01 0.94549
21 6 6.664013e+00 -3.151148e+00 -2.756030e+00 6.730895e-01 -5.035543e-01 -2.392248e-02 5.015257e-01 1.426664e+00 1.177137e-01 7.459815e-01 0.93986
21 7 2.741656e+00 -2.924058e-01 -2.782497e+00 4.167455e-02 -1.626785e+00 1.572766e-02 2.898142e-01 9.446596e-01 1.393182e-01 7.278788e-01 0.93601
22 1 -4.590363e+00 3.849984e+00 -3.307862e+00 -8.018508e-01 -5.969935e-01 6.933581e-02 2.171315e-01 6.565482e-01 9.535360e-02 3.544051e-01 0.77153
22 2 -2.609181e+00 2.507249e+00 -5.141995e+00 -5.146901e-01 -1.571547e+00 5.116362e-02 1.732032e-01 1.201708e+00 8.957430e-02 5.433813e-01 0.9206
22 3 1.080075e+00 3.236284e-01 -3.718565e+00 -5.764888e-02 -1.178401e+00 1.959957e-02 1.928291e-01 1.188282e+00 8.092215e-02 5.341144e-01 0.95301
22 4 4.479736e+00 -1.791747e+00 -2.497527e+00 3.837625e-01 -7.002120e-01 -9.574992e-03 2.565598e-01 1.158360e+00 8.196728e-02 5.367337e-01 0.96423
22 5 7.115847e+00 -2.980620e+00 8.689305e-02 6.478047e-01 7.610591e-01 -2.795117e-02 4.940494e-01 1.193656e+00 7.286485e-02 5.257920e-01 0.96623
22 6 1.034411e+01 -5.385961e+00 1.065337e-01 1.161385e+00 7.716018e-01 -6.171584e-02 4.895997e-01 1.208054e+00 7.274434e-02 5.283104e-01 0.96174
22 7 1.527996e+01 -8.823876e+00 5.233917e-01 1.885894e+00 9.122497e-01 -1.095329e-01 4.840952e-01 1.107045e+00 7.496147e-02 4.965770e-01 0.94807
23 1 -9.118623e+00 6.724055e+00 -3.965887e+00 -1.375352e+00 -8.335226e-01 1.046972e-01 2.009562e-01 8.231081e-01 8.124472e-02 3.770911e-01 0.80809
23 2 -3.740883e+00 3.467194e+00 -3.997971e+00 -7.001114e-01 -1.237937e+00 5.863242e-02 1.334926e-01 1.117128e+00 6.114471e-02 4.509570e-01 0.93032
23 3 5.376906e-01 9.692099e-01 -2.061007e+00 -1.823208e-01 -5.029704e-01 2.387347e-02 2.247389e-01 1.071661e+00 5.850010e-02 4.461086e-01 0.95698
23 4 3.849287e+00 -1.117338e+00 -7.892561e-01 2.559385e-01 8.074780e-02 -5.009557e-03 3.151658e-01 1.066045e+00 5.871764e-02 4.531396e-01 0.96842
23 5 6.541330e+00 -2.454719e+00 1.481125e+00 5.404290e-01 1.340032e+00 -2.428085e-02 5.163963e-01 1.067777e+00 5.079943e-02 4.374805e-01 0.9716
23 6 9.778494e+00 -4.861683e+00 1.537440e+00 1.053167e+00 1.355536e+00 -5.796366e-02 5.118758e-01 1.069339e+00 5.137129e-02 4.387966e-01 0.96811
23 7 1.467645e+01 -8.275620e+00 1.985977e+00 1.769856e+00 1.458738e+00 -1.049781e-01 4.988052e-01 9.306013e-01 5.826336e-02 4.082278e-01 0.95666

View File

@@ -0,0 +1,179 @@
# Standard modules
# Third-party modules
import numpy as np
import h5py as h5
from scipy.interpolate import RectBivariateSpline
# Kaipy modules
import kaipy.raiju.waveModel.wmData as wmD
def genWM(params: wmD.wmParams):
import os
fInChorus = 'chorus_polynomial.txt'
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
fInChorus = os.path.join(__location__,fInChorus)
print("Reading %s"%fInChorus)
return genChorus(params,fInChorus)
# Add wpi-induced electron lifetime model to input file and create an output file
# Writes arrays to file in raijuconfig.h5 format
def genh5(fOut: str, inputParams: wmD.wmParams):
oH5 = h5.File(fOut, 'a')
if 'waveModel' in oH5.keys():
print("'waveModel' group already in {}, not writing new one".format(fOut))
return
print("Adding waveModel to",fOut)
kpi, mlti, li, eki, taui = genWM(inputParams)
wmGrp = oH5.create_group("waveModel")
wmGrp.create_dataset('Kp', data=kpi)
wmGrp.create_dataset('MLT', data=mlti)
wmGrp.create_dataset('L', data=li)
wmGrp.create_dataset('Ek', data=eki)
wmGrp.create_dataset('Tau', data=taui)
wmGrp['L' ].attrs['units'] = 'Re'
wmGrp['Ek' ].attrs['units'] = 'MeV'
wmGrp['Tau'].attrs['units'] = 's'
attrs = inputParams.getAttrs()
for key in attrs.keys():
wmGrp.attrs[key] = attrs[key]
oH5.close()
#read parameters of the polynomial fit, Wang+,2023
def readPoly(fIn):
table = []
with open(fIn, 'r') as file:
# Skip the first row
next(file)
for line in file:
row = line.strip().split('\t')[2:-1] # Discard the first two elements of each row
row = [float(x) for x in row] # Convert the strings to float
rowLen = len(row)
table.append(np.array(row))
return (rowLen,np.array(table))
#Chorus polynomial fit for the electron lifetime
def ChorusPoly(Li,Eki,polyArray):
# The 3-rd Order Polynomial Fit Coefficients of Electron Lifetime Caused by Interaction with Chorus Waves
#(https://doi.org/will be provided)
# Dedong Wang et al., in preparation
# For each Kp (0,1,2...,7) and each MLT (0,1,2,...,23), tau has a polynomial fit of Ek and L.
lenKp,lenMLT,lenParam = polyArray.shape
#Extend polyArray
polyArrayX = polyArray[:,:,:,np.newaxis,np.newaxis]
#Extend Li and Ki
lenL = len(Li)
lenEki = len(Eki)
Lx = np.tile(Li, (lenEki, 1)).T
Lx = Lx[np.newaxis,np.newaxis,:,:]
Ex = np.tile(Eki, (lenL, 1))
Ex = Ex[np.newaxis,np.newaxis,:,:]
tau = np.ones((lenKp,lenMLT,lenL,lenEki))
c0 = polyArrayX[:,:,0,:,:]#Intercept
c1 = polyArrayX[:,:,1,:,:] #L
c2 = polyArrayX[:,:,2,:,:]#log10(E)
c3 = polyArrayX[:,:,3,:,:]# L^2
c4 = polyArrayX[:,:,4,:,:]#log10(E)^2
c5 = polyArrayX[:,:,5,:,:]#L^3
c6 = polyArrayX[:,:,6,:,:]#log10(E)^3
c7 = polyArrayX[:,:,7,:,:]#log10(E)*L
c8 = polyArrayX[:,:,8,:,:]#log10(E)*L^2
c9 = polyArrayX[:,:,9,:,:]#log10(E)^2*L
tau = c0*tau+\
c1*Lx+c2*Ex+\
c3*np.power(Lx,2)+\
c4*np.power(Ex,2)+\
c5*np.power(Lx,3)+\
c6*np.power(Ex,3)+\
c7*Lx*Ex+\
c8*np.power(Lx,2)*Ex+\
c9*Lx*np.power(Ex,2) #in log10(days)
tau = 10.0**tau*(60.*60.*24.) #in seconds
return tau
def ReSample(L,MLT,Qp,xMLT):
Nr,Np = Qp.shape
#Add ghosts in MLT to handle periodic boundary
Ng = 2
Npg = Np+Ng*2
gMLT = np.arange(0-Ng,24+Ng+1)
Qpg = np.zeros((Nr,Npg))
#Set center and then left/right strips
Qpg[:,2:-2] = Qp
Qpg[:,1] = Qp[:,-1]
Qpg[:,0] = Qp[:,-2]
Qpg[:,-1] = Qp[:,0]
Qpg[:,-2] = Qp[:,1]
Q = np.log10(Qpg)
upQ = RectBivariateSpline(L,gMLT,Q,s=10)
Qu = upQ(L,xMLT)
xQp = 10.0**(Qu)
#Enforce equality at overlap point
tauP = 0.5*(xQp[:,0]+xQp[:,-1])
xQp[:, 0] = tauP
xQp[:,-1] = tauP
return xQp
def genChorus(params,fInChorus):
rowLen,paramArray = readPoly(fInChorus)
polyArray = paramArray.reshape(24,7,rowLen) #Dim MLT: 24, Dim Kp: 7
polyArray = polyArray.transpose(1, 0, 2) # shape (7,24,rowLen)
lenMLT = 24
#Kpi
startValue = 1.0
endValue = 7.0
lenKp = 7
Kpi = np.linspace(startValue, endValue, num=lenKp)
#Eki
startValue = 1.0e-3 #in MeV
endValue = 2.0
lenEk = 155
Eki = np.linspace(np.log10(startValue), np.log10(endValue), lenEk) #in log10(MeV)
#Li
startValue = 3.0 #in Re
endValue = 7.0
lenL = 41
Li = np.linspace(startValue, endValue, num=lenL)
#Tau from polynomial fit
tauP = ChorusPoly(Li,Eki,polyArray)
#expand MLT from 0-23 to 0-24
extraMLT0 = tauP[:, 0, :, :][:,np.newaxis,:,:]
tauE = np.concatenate((tauP, extraMLT0), axis=1)
tauE = tauE.T
#Interpolation in the MLT dimesion
xFac = 4
lenMLTx = lenMLT*xFac+1 # 97
MLTi = np.linspace(0,24,lenMLT+1)
xMLTi = np.linspace(0,24,lenMLTx)
tauX = np.zeros((lenEk,lenL,lenMLTx,lenKp))
# Smoothing in MLT
for i, j in np.ndindex(tauX.shape[0], tauX.shape[3]):
Q = tauE[i, :, :, j]
tauX[i, :, :, j] = ReSample(Li, MLTi, Q, xMLTi)
Eki = 10.0**Eki #in MeV
return Kpi,xMLTi,Li,Eki,tauX

View File

@@ -0,0 +1,24 @@
# Standard modules
# Third-party modules
import h5py as h5
import numpy as np
class wmParams:
#All energies in eV
def __init__(self, dim = 4, nKp = 7, nMLT = 97, nL = 41, nEk = 155):
self.dim = dim
self.nKp = nKp
self.nMLT = nMLT
self.nL = nL
self.nEk = nEk
def getAttrs(self):
return {
'tauDim': self.dim,
'nKp': self.nKp,
'nMLT': self.nMLT,
'nL': self.nL,
'nEk': self.nEk,
}

View File

@@ -8,6 +8,8 @@ import subprocess
import glob
import argparse
from argparse import RawTextHelpFormatter
import h5py as h5
import kaipy.kaiTools as kt
def sortFn(elem): #Used to sort final list in order of nRes
return int(elem['nRes'])
@@ -22,22 +24,12 @@ def getAttrKeyValue(lineList):
#Return dictionary of attrs for a single restart file
def getKVsFromFile(fName):
spOutput = subprocess.check_output(['h5dump','-a','nRes','-a','t','-a','DATETIME',fName])
output = spOutput.decode('utf-8').split('\n')
#Parse attributes (this could be better)
attrLocs = []
for i in range(len(output)):
if 'ATTRIBUTE' in output[i]:
attrLocs.append(i)
attrs = {}
for i in range(len(attrLocs)):
if i == len(attrLocs)-1:
k,v = getAttrKeyValue(output[attrLocs[i]:])
else:
k,v = getAttrKeyValue(output[attrLocs[i]:attrLocs[i+1]])
attrs[k] = v
f5 = h5.File(fName)
attrs = {}
attrs['nRes'] = f5.attrs['nRes']
attrs['time'] = f5.attrs['time']
attrs['UT'] = kt.MJD2UT(f5.attrs['MJD'])
return attrs
def create_command_line_parser():
@@ -46,8 +38,7 @@ def create_command_line_parser():
Returns:
argparse.ArgumentParser: Command-line argument parser for this script.
"""
idStr_noMPI = ".gam.Res.*.h5"
idStrMPI = "_0*_0*_0*_0000_0000_0000.gam.Res.*.h5"
idStr_noMPI = ".volt.Res.*.h5"
ftag = "msphere"
timeFmt = "m"
@@ -57,13 +48,11 @@ def create_command_line_parser():
parser = argparse.ArgumentParser(description=MainS, formatter_class=RawTextHelpFormatter)
parser.add_argument('-id',type=str,metavar="runid",default=ftag,help="RunID of data (default: %(default)s)")
parser.add_argument('-f',type=str,metavar="timeFmt",default=timeFmt,help="Time format [s,m,h] (default: %(default)s)")
parser.add_argument('-dt',action='store_true',default=False,help="Print the datetime instead of simulation time (default: %(default)s)")
parser.add_argument('-ut',action='store_true',default=False,help="Print UT instead of simulation time (default: %(default)s)")
return parser
def main():
idStr_noMPI = ".gam.Res.*.h5"
idStrMPI = "_0*_0*_0*_0000_0000_0000.gam.Res.*.h5"
idStr_noMPI = ".volt.Res.*.h5"
ftag = "msphere"
timeFmt = "m"
MainS = """Overengineered script to print the time of each restart file by parsing h5dump output
@@ -73,29 +62,25 @@ def main():
args = parser.parse_args()
ftag = args.id
timeFormat = args.f
doDatetime = args.dt
doUT = args.ut
if timeFormat not in ['s','m','h']:
print('Unrecognized value "%s" for time format. Using "%s"'%(timeFormat, timeFmt))
timeFormat = timeFmt
if timeFormat == 's':
timeFormat = 'sec'
timeMult = 60
timeMult = 1
elif timeFormat == 'h':
timeFormat = 'hr'
timeMult = 1./60
timeMult = 1./3600
else:
timeFormat = 'min'
timeMult = 1
timeMult = 1./60
#Get list of files
globStr = ftag + idStr_noMPI
print("Looking for nonMPI restarts...",end='')
print("Looking for voltron restarts...",end='')
fileList = glob.glob(globStr)
if len(fileList) == 0:
globStr = ftag + idStrMPI
print("Not found\nLooking for MPI restarts...",end='')
fileList = glob.glob(globStr)
if len(fileList) == 0:
print("Not found\nCheck id (globStr = %s)"%(globStr))
quit()
@@ -113,10 +98,10 @@ def main():
#Print list (time from Gam restarts only, for now)
attrList.sort(key=sortFn)
for entry in attrList:
if doDatetime:
formatString = " {}: {}".format(entry['fname'], entry['DATETIME'])
if doUT:
formatString = " {}: {}".format(entry['fname'], entry['UT'])
else:
formatString = " {}: {:4.2f} [{}]".format(entry['fname'], float(entry['t'])*timeMult, timeFormat)
formatString = " {}: {:4.2f} [{}]".format(entry['fname'], float(entry['time'])*timeMult, timeFormat)
print(formatString)

180
kaipy/scripts/preproc/genRAIJU.py Executable file
View File

@@ -0,0 +1,180 @@
#!/usr/bin/env python
# Generates RAIJU config data
import os
import h5py as h5
import argparse
from argparse import RawTextHelpFormatter
import kaipy.kaiTools as kT
import kaipy.kaijson as kj
import kaipy.kaiH5 as kh5
import kaipy.raiju.lambdautils.AlamData as aD
import kaipy.raiju.lambdautils.AlamParams as aP
import kaipy.raiju.lambdautils.DistTypes as dT
import kaipy.raiju.lambdautils.fileIO as fileIO
from kaipy.raiju.waveModel.wmData import wmParams
import kaipy.raiju.waveModel.genWM as genWM
#import kaipy.rcm.lambdautils.plotter as plotter
EFLAV = 1
PFLAV = 2
EFUDGE = 1./3.
PFUDGE = 0.0
def create_command_line_parser():
"""Create the command-line argument parser.
Create the parser for command-line arguments.
Returns:
argparse.ArgumentParser: Command-line argument parser for this script.
"""
#Arg parsing
fOut = "raijuconfig.h5"
num_e = 39
num_p = 120
nPSpc = 1 # Number of proton species to include
eminp = 1 # [eV]
emine = 1 # [eV]
emaxp = 100 # [keV]
emaxe = 25 # [keV] , 1/4 of 100 keV
L_kt = 10
wolfP1 = 3
wolfP2 = 1
plotChoices = ['none', 'spec', 'vs']
MainS = """Generates RAIJU configuration data
"""
parser = argparse.ArgumentParser(description=MainS, formatter_class=RawTextHelpFormatter)
parser.add_argument('-o',type=str,default=fOut,metavar="fOut",help="Output file name (default: %(default)s)")
parser.add_argument('-ne', type=int,default=num_e, help="Number of electron channels (default: %(default)s)")
parser.add_argument('-np', type=int,default=num_p, help="Number of proton channels (default: %(default)s)")
parser.add_argument('-mine', type=float,default=emine, help="Min. energy [eV] for electrons at L_kt (default: %(default)s)")
parser.add_argument('-minp', type=float,default=eminp, help="Min. energy [eV] for protons at L_kt (default: %(default)s)")
parser.add_argument('-maxe', type=float,default=emaxe, help="Max. energy [keV] for electrons at L_kt (default: %(default)s)")
parser.add_argument('-maxp', type=float,default=emaxp, help="Max. energy [keV] for protons at L_kt (default: %(default)s)")
parser.add_argument('-L', type=float,default=L_kt, help="L shell [R_e] at which kt should be resolved (default: %(default)s [R_e])")
parser.add_argument('-p1', type=float,default=wolfP1, help="Wolf low-energy p* (default: %(default)s)")
parser.add_argument('-p2', type=float,default=wolfP2, help="Wolf high-energy p* (default: %(default)s)")
parser.add_argument('-plotType', choices=plotChoices,default=plotChoices[0], help="Plot mode (default: %(default)s)")
parser.add_argument('-npSpc',type=int,default=nPSpc, help="Number of proton species to include (default: %(default)s)")
parser.add_argument('--nop',action='store_true',default=False,help="Do not add zero energy first channel (default: %(default)s)")
parser.add_argument('--noWaveModel',action='store_true',default=False, help="Don't use wave models in the electron/ion loss (default: %(default)s)")
parser.add_argument('--append',action='store_true',default=False, help="Append existing file rather than make a new one (default: %(default)s)")
return parser
def main():
parser = create_command_line_parser()
# Finalize parsing
args = parser.parse_args()
fOut = args.o
num_e = args.ne
num_p = args.np
emine = args.mine
eminp = args.minp
emaxe = args.maxe*1e3 # [keV -> eV]
emaxp = args.maxp*1e3 # [keV -> eV]
L_kt = float(args.L)
wolfP1 = args.p1
wolfP2 = args.p2
nPSpc = args.npSpc
plotType = args.plotType
noPsph = args.nop
noWaveModel = args.noWaveModel
doAppend = args.append
if doAppend:
if not os.path.exists(fOut):
# Will only append to a file that exists
# i.e. we will not make a new file if the --append arg was used
print("Couldn't find {} to append to, quitting.".format(fOut))
quit()
# If append == True and file is there, we'll just add any data the file doesn't already have
else:
# Othewise, we will make a new file
# Since all writing functions open in 'a' mode, we need to ensure we have a fresh file to work with
print("Making new {}, destroying pre-existing file if there".format(fOut))
with h5.File(fOut, 'w') as tmpF:
pass
# Tag the output file with latest info
with h5.File(fOut, 'a') as f5:
print("Stamping file with git hash and branch, and script args")
kh5.StampHash(fOut)
kh5.StampBranch(fOut)
f5.attrs['ScriptArgs'] = kj.dumps(vars(args),noIndent=True)
# Add wavemodel if desired
if not noWaveModel:
tauParams = wmParams(dim = 4, nKp = 7, nMLT = 97, nL = 41, nEk = 155)
genWM.genh5(fOut,tauParams)
# Now add species
# Determine lambda limits using desired energy limits at given L
bVol = kT.L_to_bVol(L_kt)
vm = bVol**(-2/3) # [(Rp/nT)^(-2/3)]
alamMin_p = eminp/vm # [eV * (Rp/nT)^(2/3)]
alamMax_p = emaxp/vm
alamMin_e = -1*emine/vm
alamMax_e = -1*emaxe/vm
dtSingle = dT.DT_Single()
dtWolf = dT.DT_Wolf(p1=wolfP1,p2=wolfP2) # Lambda channels will have a (slightly modified) Wolf distribution type
# For reference: SpecParams(n, amin, amax, distType,
# flav, numNuc_p, numNuc_n, q,
# fudge, name)
spcParamList = []
if not noPsph:
sPsphere = aP.SpecParams(1, 0, 0, dtSingle,
0, numNuc_p=1, numNuc_n=0, q=1,
fudge=0, name="0_Plasmasphere") # Zero-energy plasmasphere channel
spcParamList.append(sPsphere)
sPe = aP.SpecParams(num_e, alamMin_e, alamMax_e, dtWolf,
EFLAV, numNuc_p=0, numNuc_n=0, q=-1,
fudge=EFUDGE, name='Hot Electrons') # Parameters to create electron channels
sPp = aP.SpecParams(num_p, alamMin_p, alamMax_p, dtWolf,
PFLAV, numNuc_p=1, numNuc_n=0, q=1,
fudge=PFUDGE, name='Hot Protons' ) # Parameters to create proton channels
spcParamList.append(sPe)
spcParamList.append(sPp)
if nPSpc > 1:
guestFlavor = 10
for i in range(2,nPSpc+1):
print(i)
sp = aP.SpecParams(num_p, alamMin_p, alamMax_p, dtWolf,
guestFlavor, numNuc_p=1, numNuc_n=0, q=1,
fudge=PFUDGE, name=f'Hot Protons_{i}' )
spcParamList.append(sp)
guestFlavor += 1
# Stuff into an AlamData object, which will automatically generate the fully realized species distribution for us
# NOTE: ORDER MATTERS. They will show up in the 1D lamc in this order
#if noPsph:
# alamData = aD.AlamData([sPe, sPp])
#else:
# alamData = aD.AlamData([sPsphere, sPe, sPp])
alamData = aD.AlamData(spcParamList)
# Save lambda data to file (will also save params as a root attribute)
fileIO.saveAlamData(fOut, alamData)
if __name__ == "__main__":
main()

View File

@@ -20,6 +20,7 @@ import os
import matplotlib as mpl
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
import warnings
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
@@ -59,6 +60,46 @@ default_step = -1
SPACECRAFT_COLOR = 'red'
def findIM(indir: str, tag: str) -> str:
"""Determine whether run used RCM, RAIJU, or no Inner Mag
Inputs:
indir [str]: directory to search
tag [str]: run tag (e.g. msphere)
Returns:
modelName [str]: Imag model used, or None if no Imag model
"""
strfmt = os.path.join(indir, "{}.{}.h5")
if os.path.exists(strfmt.format(tag, "raiju")):
return "RAIJU"
elif os.path.exists(strfmt.format(tag, "mhdrcm")):
return "RCM"
else:
return None
def addIMBox(Ax, bnds):
"""
Add a rectangular box to the given Axes object.
Args:
Ax: The Axes object to which the rectangle will be added.
Returns:
None
"""
if (Ax is None):
Ax = plt.gca()
xy0 = (bnds[0],bnds[2])
H = bnds[3]-bnds[2]
W = bnds[1]-bnds[0]
rcmRec = patches.Rectangle( (xy0),W,H, fill=False,edgecolor="dodgerblue")
Ax.add_patch(rcmRec)
def create_command_line_parser():
"""Create the command-line argument parser.
@@ -112,11 +153,11 @@ def create_command_line_parser():
help="Don't show MPI boundaries (default: %(default)s)."
)
parser.add_argument(
"-norcm", action="store_true", default=False,
help="Don't show RCM data (default: %(default)s)."
"-noIM", action="store_true", default=False,
help="Don't show Inner Mag data (default: %(default)s)."
)
parser.add_argument(
"-bigrcm", action="store_true", default=False,
"-bigIM", action="store_true", default=False,
help="Show entire RCM domain (default: %(default)s)."
)
parser.add_argument(
@@ -248,7 +289,7 @@ def makePlot(i,spacecraft,nStp, args, varDict):
elif doEphi:
mviz.PlotEqEphi(gsph, nStp, xyBds, AxR, AxC3)
else:
mviz.PlotMerid(gsph, nStp, xyBds, AxR, doDen, doRCM, AxC3, doSrc=doSrc)
mviz.PlotMerid(gsph, nStp, xyBds, AxR, doDen, doIM, AxC3, doSrc=doSrc)
# Add the date and time for the plot.
gsph.AddTime(nStp, AxL, xy=[0.025, 0.89], fs="x-large")
@@ -256,17 +297,22 @@ def makePlot(i,spacecraft,nStp, args, varDict):
# Add the solar wind description text.
gsph.AddSW(nStp, AxL, xy=[0.625, 0.025], fs="small")
# If available, add the inset RCM plot.
if not noRCM:
AxRCM = inset_axes(AxL, width="30%", height="30%", loc=3)
rcmpp.RCMInset(AxRCM, rcmdata, nStp, mviz.vP)
# If available, add the inset Inner Mag plot.
if imName is not None:
if imName=="RAIJU":
stepStr = "Step#"+str(nStp)
AxIM = inset_axes(AxL, width="30%", height="30%", loc=3)
inset_bnds = rv.plotInset(AxIM, raiI, stepStr, mviz.vP, ax_gam=AxL)
if imName=="RCM":
AxIM = inset_axes(AxL, width="30%", height="30%", loc=3)
inset_bnds = rcmpp.RCMInset(AxIM, rcmdata, nStp, mviz.vP)
# Add dBz contours.
AxRCM.contour(
AxIM.contour(
kv.reWrap(gsph.xxc), kv.reWrap(gsph.yyc), kv.reWrap(Bz), [0.0],
colors=mviz.bz0Col, linewidths=mviz.cLW
)
# Show the RCM region as a box.
rcmpp.AddRCMBox(AxL)
# Show the IM region as a box.
addIMBox(AxL,inset_bnds)
# Plot the REMIX data, if requested.
if doIon:
@@ -378,8 +424,8 @@ def main():
doEphi = args.ephi
doSrc = args.src
doBz = args.bz
noRCM = args.norcm
doBigRCM = args.bigrcm
doIM = not args.noIM
doBigIM = args.bigIM
do_vid = args.vid
do_overwrite = args.overwrite
do_hash = not args.nohash
@@ -401,12 +447,11 @@ def main():
# Open the gamera results pipe.
gsph = msph.GamsphPipe(fdir, ftag, doFast=doFast)
# Check for the presence of RCM results.
rcmChk = os.path.join(fdir, "%s.mhdrcm.h5" % ftag)
doRCM = os.path.exists(rcmChk)
# Check for the presence of IM results.
imName = findIM(fdir, ftag)
if debug:
print("rcmChk = %s" % rcmChk)
print("doRCM = %s" % doRCM)
print("imName = %s" % imName)
# Check for the presence of remix results.
rmxChk = os.path.join(fdir, "%s.mix.h5" % ftag)
@@ -422,12 +467,20 @@ def main():
if debug:
print(f'branch/commit: {branch}/{githash}')
# Open RCM data if available, and initialize visualization.
if doRCM:
# Open inner mag data if available, and initialize visualization.
if imName=="RAIJU":
print("Found RAIJU data")
import kaipy.raiju.raijuUtils as ru
import kaipy.raiju.raijuViz as rv
raiI = ru.RAIJUInfo(os.path.join(fdir, ftag + ".raiju.h5"))
mviz.vP = kv.genNorm(1.0e-2, 100.0, doLog=True)
else:
raiI = None
if imName=="RCM":
print("Found RCM data")
rcmdata = gampp.GameraPipe(fdir, ftag + ".mhdrcm")
mviz.vP = kv.genNorm(1.0e-2, 100.0, doLog=True)
rcmpp.doEll = not doBigRCM
rcmpp.doEll = not doBigIM
if debug:
print("rcmdata = %s" % rcmdata)
else:

View File

@@ -0,0 +1,370 @@
#!/usr/bin/env python
# Import standard modules.
import os
import argparse
import sys
import datetime
# Import supplemental modules.
import h5py as h5
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import cmasher as cmr
import tqdm
from functools import partial
from concurrent.futures import ProcessPoolExecutor
# Import project-specific modules.
import kaipy.kaiTools as kt
import kaipy.kaiViz as kv
import kaipy.kaiH5 as kh5
import kaipy.raiju.raijuUtils as ru
import kaipy.raiju.raijuViz as rv
# Program constants and defaults
# Program description.
description = """Creates simple multi-panel RAIJU figure MAGE run.
"""
# Default identifier for results to read.
default_runid = "msphere"
default_vidOut = "qkRaijuVid"
default_step = -1
default_ut = -1
default_nStride = 10
domain_opts = ["ACTIVE", "BUFFER"]
default_domain="ACTIVE"
default_ncpus = 1
default_start = 1
def get_bVol_dipole(f5):
colats = ru.getVar(f5,'X') # [rad]
R = f5['Grid']['ShellGrid'].attrs['radius'] # [Rp]
Leq = R/( np.sin(colats[:,0])*np.sin(colats[:,0]) )
Ni, Nj = colats.shape
bVol_dipole_1D = np.zeros(Ni)
for i in range(Ni):
bVol_dipole_1D[i] = kt.L_to_bVol(Leq[i])
bVol_dipole_2D = np.broadcast_to(bVol_dipole_1D[:,np.newaxis], (Ni,Nj))
return bVol_dipole_2D
def create_command_line_parser():
"""Create the command-line argument parser.
Create the parser for command-line arguments.
Returns:
argparse.ArgumentParser: Command-line argument parser for this script.
"""
parser = argparse.ArgumentParser(
description=description,
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument(
"-d", type=str, metavar="directory", default=os.getcwd(),
help="Directory containing data to read (default: %(default)s)"
)
parser.add_argument(
"-id", type=str, metavar="runid", default=default_runid,
help="Run ID of data (default: %(default)s)"
)
parser.add_argument(
"-n", "-ne", type=int, metavar="step", default=default_step,
help="Time slice to plot (last slice if video; default: %(default)s)"
)
parser.add_argument(
"-ns", type=int, metavar="startstep", default=default_start,
help="First slice of video; default: %(default)s)"
)
parser.add_argument(
"-dn", type=int, metavar="stride", default=default_nStride,
help="Step stride in case of vid (default: %(default)s)"
)
parser.add_argument(
"-uts", type=str, metavar=kt.isotfmt, default=default_ut,
help="First UT of video (default: %(default)s)"
)
parser.add_argument(
"-ut", "-ute", type=str, metavar=kt.isotfmt, default=default_ut,
help="UT to plot (overrides -n if provided; last UT if video; default: %(default)s)"
)
parser.add_argument(
'-domain', choices=domain_opts, default=default_domain,
help="Domain to include (always includes active) (default: %(default)s)"
)
parser.add_argument(
'-diff',action='store_true', default=False,
help="Do difference of some quantities from dipole (default: %(default)s)"
)
parser.add_argument(
"-v", "--verbose", action="store_true", default=False,
help="Print verbose output (default: %(default)s)."
)
parser.add_argument(
'-vid', action='store_true', default=False,
help="Make a video and store in mixVid directory (default: %(default)s)"
)
parser.add_argument(
"-vidOut", type=str, metavar="dir", default=default_vidOut,
help="Output directory if doing video (default: %(default)s)"
)
parser.add_argument(
'-overwrite', action='store_true', default=False,
help="Overwrite existing vid files (default: %(default)s)"
)
parser.add_argument(
'-nohash', action='store_true', default=False,
help="Don't display branch/hash info (default: %(default)s)"
)
parser.add_argument(
'--ncpus', type=int, default=default_ncpus,
help="Number of threads for parallel vid (default: %(default)s)"
)
return parser
def plot_frame(pairs,raiI: ru.RAIJUInfo, config):
iPlt, nPlt = pairs
f5 = h5.File(raiI.fname,'r')
fgSize = (13,7)
eqBnds = [-15,10,-10,10]
norm_press = kv.genNorm(05e-2,50,doLog=False)
norm_den = kv.genNorm(0,10, doLog=False)
norm_bvol = kv.genNorm(1e-4,1e0,doLog=True)
norm_diff_bvol = kv.genNorm(-1e2,1e2,doSymLog=True)
norm_ent = kv.genNorm(1e-4,0.5,doLog=True)
norm_wimag = kv.genNorm(0,1,doLog=False)
norm_bMin = kv.genNorm(0.1,1000,doLog=True)
norm_Tb = kv.genNorm(0,180,doLog=False)
cmap_diff = 'RdBu_r'
cmap_press = cmr.lilac
cmap_bvol = cmr.dusk
cmap_ent = 'gist_earth'
tickIn_pad = -15
nRows = 4
nCols = 4
fig = plt.figure(figsize=fgSize)
gs = gridspec.GridSpec(nRows,nCols,height_ratios=[0.1,1,1,0.1],hspace=0.2,wspace=0.18)
axs = []
for iRow in range(nRows):
axRow = []
for iCol in range(nCols):
axRow.append(fig.add_subplot(gs[iCol,iRow]))
axs.append(axRow)
axCol = axs[0]
kv.genCB(axCol[0], norm_press, "Proton Pressure [nPa]",cmap_press)
axCol[0].xaxis.set_ticks_position("top")
axCol[0].xaxis.set_label_position("top")
kv.genCB(axCol[3], norm_press, "Electron Pressure [nPa]",cmap_press)
axCol = axs[1]
kv.genCB(axCol[0], norm_den, "Proton Density [#/cc]")
axCol[0].xaxis.set_ticks_position("top")
axCol[0].xaxis.set_label_position("top")
kv.genCB(axCol[3], norm_den, "Electron Density [#/cc]")
axCol = axs[2]
if config['doDiff']:
bVol_dipole = get_bVol_dipole(f5)
bVol_dip_cc = kt.to_center2D(bVol_dipole)
kv.genCB(axCol[0], norm_diff_bvol, "(V-V$_d$)/V$_d$",cM=cmap_diff)
else:
kv.genCB(axCol[0], norm_bvol, "bVol",cmap_bvol)
axCol[0].xaxis.set_ticks_position("top")
axCol[0].xaxis.set_label_position("top")
kv.genCB(axCol[3], norm_ent , "Flux tube entropy",cmap_ent)
axCol = axs[3]
kv.genCB(axCol[0], norm_wimag, "wIMAG")
#kv.genCB(axCol[0], norm_bMin, "bMin [nT]")
axCol[0].xaxis.set_ticks_position("top")
axCol[0].xaxis.set_label_position("top")
kv.genCB(axCol[3], norm_Tb, "Tbounce [s]")
def fillPlots(nPlt):
for iRow in range(1,nRows-1):
for iCol in range(nCols):
axs[iCol][iRow].clear()
if raiI.stepStrs[nPlt] == "Step#0":
print("WE HAVE ZERO????", nPlt, raiI.stepStrs[nPlt])
return
s5 = f5[raiI.stepStrs[nPlt]]
# H+ press | H+ den | bVol | wIMAG
# Ele press | Ele den | entropy | Tbounce
#spc_p = raiI.getSpcFromFlav(ru.flavs_s['HOTP'])
#spc_e = raiI.getSpcFromFlav(ru.flavs_s['HOTE'])
#spc_psph = raiI.getSpcFromFlav(ru.flavs_s['PSPH'])
spcIdx_p = ru.spcIdx(raiI.species, ru.flavs_s['HOTP'])
spcIdx_e = ru.spcIdx(raiI.species, ru.flavs_s['HOTE'])
spcIdx_psph = ru.spcIdx(raiI.species, ru.flavs_s['PSPH'])
fig.suptitle(raiI.UTs[nPlt])
xmin = ru.getVar(s5,'xmin')
ymin = ru.getVar(s5,'ymin')
xmincc = kt.to_center2D(xmin)
ymincc = kt.to_center2D(ymin)
topo = ru.getVar(s5,'topo')
active = ru.getVar(s5,'active')
if config['domain'] == "ACTIVE":
mask_cc = active != ru.domain['ACTIVE']
elif config['domain'] == "BUFFER":
mask_cc = active != ru.domain['INACTIVE']
mask_corner = topo==ru.topo['OPEN']
press_all = ru.getVar(s5,'Pressure',mask=mask_cc,broadcast_dims=(2,))
den_all = ru.getVar(s5,'Density' ,mask=mask_cc,broadcast_dims=(2,))
tBounce = ru.getVar(s5,'Tbounce',mask=mask_cc)
vaFrac = ru.getVar(s5,'vaFrac',mask=mask_corner)
pstd_rc = ru.getVar(s5,'Pstd_in',mask=mask_cc,broadcast_dims=(2,))[:,:,0]
bMin = ru.getVar(s5,'bminZ',mask=mask_corner)
bVol = ru.getVar(s5,'bVol' ,mask=mask_corner)
bVol_cc = kt.to_center2D(bVol)
pot_corot = ru.getVar(s5, 'pot_corot', mask=mask_corner)
pot_iono = ru.getVar(s5, 'pot_iono' , mask=mask_corner)
pot_total = pot_corot + pot_iono
press_p = press_all[:,:,spcIdx_p+1] # First slot is bulk
press_e = press_all[:,:,spcIdx_e+1]
den_p = den_all[:,:,spcIdx_p+1]
den_e = den_all[:,:,spcIdx_e+1]
entropy = press_all[:,:,0]*bVol_cc**(5./3.) # Wolf units [nPa * (Rx/nT)^(5/3)]
den_psph = den_all[:,:,spcIdx_psph+1]
levels_psphDen = [1,10,100,1000]
levels_pot = np.arange(-250, 255, 5)
axCol = axs[0]
rv.plotXYMin(axCol[1], xmin, ymin, press_p,norm=norm_press,bnds=eqBnds,cmap=cmap_press)
axCol[1].contour(xmin, ymin, pot_total, levels=levels_pot, colors='white',linewidths=0.5, alpha=0.3)
rv.plotXYMin(axCol[2], xmin, ymin, press_e,norm=norm_press,bnds=eqBnds,cmap=cmap_press)
axCol[2].contour(xmin, ymin, pot_total, levels=levels_pot, colors='white',linewidths=0.5, alpha=0.3)
axCol = axs[1]
rv.plotXYMin(axCol[1], xmin, ymin, den_p,norm=norm_den,bnds=eqBnds)
axCol[1].contour(xmincc, ymincc, den_psph,levels=levels_psphDen,colors='white',linewidths=0.5,alpha=0.4)
rv.plotXYMin(axCol[2], xmin, ymin, den_e,norm=norm_den,bnds=eqBnds)
axCol = axs[2]
if config['doDiff']:
d_bVol_cc = (bVol_cc - bVol_dip_cc)/bVol_dip_cc
rv.plotXYMin(axCol[1], xmin, ymin, d_bVol_cc,norm=norm_diff_bvol,cmap=cmap_diff,bnds=eqBnds)
else:
rv.plotXYMin(axCol[1], xmin, ymin, bVol_cc,norm=norm_bvol,bnds=eqBnds,cmap=cmap_bvol)
axCol[1].contour(xmincc,ymincc,active,levels=[0.5],colors='orange')
rv.plotXYMin(axCol[2], xmin, ymin, entropy,norm=norm_ent ,bnds=eqBnds,cmap=cmap_ent)
axCol = axs[3]
rv.plotXYMin(axCol[1], xmin, ymin, vaFrac,norm=norm_wimag,bnds=eqBnds)
#axCol[1].contour(xmin, ymin, vaFrac, levels=np.arange(0,1.1,0.1),colors='black',alpha=0.4)
#axCol[1].contour(xmin, ymin, bMin, levels=[5,10], colors='black', alpha=0.4)
#axCol[1].contour(xmincc, ymincc, pstd_rc, levels=[0.5], colors='black', alpha=0.4)
axCol[1].contour(xmincc,ymincc,active,levels=[0.5],colors='orange')
rv.plotXYMin(axCol[2], xmin, ymin, tBounce,norm=norm_Tb,bnds=eqBnds)
#axCol[1].tick_params(axis="x",direction="in", pad=tickIn_pad)
#axCol[2].tick_params(axis="x",direction="in", pad=tickIn_pad)
#axCol[1].yaxis.set_major_formatter(mtk.NullFormatter())
#axCol[2].yaxis.set_major_formatter(mtk.NullFormatter())
# Add Branch and Hash info
if not config['noHash']:
fig.text(0.1,0.95,f"branch/commit: {config['branch']}/{config['hash']}", fontsize=6)
if config['doVid'] == False:
fillPlots(nPlt)
kv.savePic('qkraijupic.png')
else:
if nPlt == 0:
print("WE HAVE ZERO??")
outdir = config['vidOut']
kh5.CheckDirOrMake(outdir)
fillPlots(nPlt)
fname = "vid.{:>04d}.png".format(iPlt)
kv.savePic(os.path.join(outdir, fname))
# Clean up
plt.close()
def makeSuperPlot(raiI, config):
if not config['doVid']:
plot_frame((0,config['nPlt']),raiI, config) # keep your original single-frame mode
return
# Create the plots in a memory buffer.
mpl.use('Agg')
# Set global plot font options.
mpl.rc('mathtext', fontset='stixsans', default='regular')
mpl.rc('font', size=10)
os.makedirs(config['vidOut'], exist_ok=True)
frame_indices = list(range(config['nStart'], config['nPlt'], config['nStride']))
frame_pairs = list(enumerate(frame_indices))
# Pass only necessary lightweight args
worker = partial(
plot_frame,
raiI=raiI,
config=config
)
nCPU = config.get("nCPU", os.cpu_count() or 8)
with ProcessPoolExecutor(max_workers=nCPU) as executor:
list(tqdm.tqdm(executor.map(worker, frame_pairs), total=len(frame_pairs)))
def main():
"""Main function to run the script."""
parser = create_command_line_parser()
args = parser.parse_args()
config = {
"indir" : args.d,
"id" : args.id,
"nPlt" : args.n,
"nStride" : args.dn,
"utPlt" : args.ut,
"domain" : args.domain,
"doDiff" : args.diff,
"doVerbose" : args.verbose,
"doVid" : args.vid,
"vidOut" : args.vidOut,
"doOverwrite": args.overwrite,
"noHash" : args.nohash,
"nCPU" : args.ncpus,
"nStart" : args.ns,
}
print(config)
fname = os.path.join(config['indir'],
config['id']+".raiju.h5")
raiI = ru.RAIJUInfo(fname,useTAC=True)
if (config['doVerbose']): raiI.printStepInfo()
# Determine plot time
if config['utPlt'] != default_ut:
utPlot = datetime.datetime.strptime(config['utPlt'],kt.isotfmt)
config['nPlt'] = np.abs(raiI.UTs-utPlot).argmin()
else:
if config['nPlt'] == -1 or config['nPlt'] > raiI.Nt:
config['nPlt'] = raiI.Nt-1
#nPlot = raiI.steps[config['nPlt']]
# Get branch/hash info
if not config['noHash']:
config['branch'] = kh5.GetBranch(fname)
config['hash'] = kh5.GetHash(fname)
print("Plotting RAIJU step {} (t={}, UT={})".format(config['nPlt'],raiI.times[config['nPlt']], raiI.UTs[config['nPlt']]))
makeSuperPlot(raiI, config)
if __name__ == "__main__":
main()

View File

@@ -7,13 +7,13 @@ include-package-data = true
[project]
name = "kaipy"
version = "1.0.8"
version = "1.1.0"
authors = [
{name = "Eric Winter", email = "eric.winter@jhuapl.edu"},
]
description = "Python software for CGS MAGE and other Kaiju models"
readme = "README.md"
requires-python = ">=3.9,<=3.13"
requires-python = ">=3.9,<3.13"
keywords = ["CGS", "MAGE", "KAIJU"]
license = {text = "BSD 3-Clause"}
classifiers = [
@@ -76,6 +76,7 @@ ut2mjd = "kaipy.scripts.postproc.ut2mjd:main"
cda2wind = "kaipy.scripts.preproc.cda2wind:main"
genLFM = "kaipy.scripts.preproc.genLFM:main"
genRCM = "kaipy.scripts.preproc.genRCM:main"
genRAIJU = "kaipy.scripts.preproc.genRAIJU:main"
wsa2gamera = "kaipy.scripts.preproc.wsa2gamera:main"
XMLGenerator = "kaipy.scripts.preproc.XMLGenerator:main"
@@ -89,13 +90,12 @@ heliomovie = "kaipy.scripts.quicklook.heliomovie:main"
heliopic = "kaipy.scripts.quicklook.heliopic:main"
mixpic = "kaipy.scripts.quicklook.mixpic:main"
msphpic = "kaipy.scripts.quicklook.msphpic:main"
raijupic = "kaipy.scripts.quicklook.raijupic:main"
rcmDataProbe = "kaipy.scripts.quicklook.rcmDataProbe:main"
rcmpic = "kaipy.scripts.quicklook.rcmpic:main"
remixTimeSeries = "kaipy.scripts.quicklook.remixTimeSeries:main"
swpic = "kaipy.scripts.quicklook.swpic:main"
vizTrj = "kaipy.scripts.quicklook.vizTrj:main"
OMNI = "kaipy.solarWind.OMNI:main"
SWPC = "kaipy.solarWind.SWPC:main"
TimeSeries = "kaipy.solarWind.TimeSeries:main"
WIND = "kaipy.solarWind.WIND:main"
raijudst = "kaipy.raiju.dst:main"
raijum2m = "kaipy.raiju.m2m:main"

View File

@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
setup(
name='kaipy',
version='1.0.8',
version='1.1.0',
description='Python software for CGS MAGE and other Kaiju models',
author='Kaiju team',
author_email='wiltbemj@ucar.edu',
@@ -12,7 +12,7 @@ setup(
package_data={'kaipy': ['scripts/*', 'scripts/*/*'],
'kaipy.satcomp': ['sc_helio.json']
},
python_requires='>=3.9,<=3.13',
python_requires='>=3.9,<3.13',
install_requires=[
'alive_progress',
'astropy',
@@ -72,6 +72,7 @@ setup(
'cda2wind=kaipy.scripts.preproc.cda2wind:main',
'genLFM=kaipy.scripts.preproc.genLFM:main',
'genRCM=kaipy.scripts.preproc.genRCM:main',
'genRAIJU=kaipy.scripts.preproc.genRAIJU:main',
'wsa2gamera=kaipy.scripts.preproc.wsa2gamera:main',
'XMLGenerator=kaipy.scripts.preproc.XMLGenerator:main',
'dbVid=kaipy.scripts.quicklook.dbVid:main',
@@ -84,15 +85,14 @@ setup(
'heliopic=kaipy.scripts.quicklook.heliopic:main',
'mixpic=kaipy.scripts.quicklook.mixpic:main',
'msphpic=kaipy.scripts.quicklook.msphpic:main',
'raijupic=kaipy.scripts.quicklook.raijupic:main',
'rcmDataProbe=kaipy.scripts.quicklook.rcmDataProbe:main',
'rcmpic=kaipy.scripts.quicklook.rcmpic:main',
'remixTimeSeries=kaipy.scripts.quicklook.remixTimeSeries:main',
'swpic=kaipy.scripts.quicklook.swpic:main',
'vizTrj=kaipy.scripts.quicklook.vizTrj:main',
'OMNI=kaipy.solarWind.OMNI:main',
'SWPC=kaipy.solarWind.SWPC:main',
'TimeSeries=kaipy.solarWind.TimeSeries:main',
'WIND=kaipy.solarWind.WIND:main'
'raijudst=kaipy.raiju.dst:main',
'raijum2m=kaipy.raiju.m2m:main'
]
}
)