{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "Nick Featherstone (January, 2018)\n", "\n", "**NOTE:** This document can be viewed in PDF or HTML (recommended) form. It can also be run as an interactive Jupyter notebook.\n", "\n", "The HTML and PDF versions are located in Rayleigh/doc/Diagnostic_Plotting.{html,pdf} \n", "The Jupyter notebook is located in Rayleigh/post_processing/Diagnostic_Plotting.ipynb \n", "Standalone Python example scripts for each output type may also found in Rayleigh/post_processing/\n", "\n", "Contents\n", "=======\n", "1. Running a Benchmark with Sample Output\n", "2. Configuring your Python environment\n", "3. Overview of Rayleigh's Diagnostic Package\n", "4. Global Averages\n", "5. Shell Averages\n", "6. Azimuthal Averages\n", "7. Simulation Slices \n", "8. Spherical Harmonic Spectra\n", "9. Point Probes\n", "10. Modal Outputs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "I. Running a Benchmark with Sample Output\n", "=======================\n", "\n", "Before you can plot data, you will need to generate data. The code samples in this notebook assume that you have run the model described by the input file found in:\n", "\n", "rayleigh/input_examples/benchmark_diagnostics_input\n", "\n", "This input file instructs *Rayleigh* to run the Christensen et al. (2001) hydrodynamic (case 0) benchmark. Running this model with the prescribed outputs will generate approximately 70 MB of data. \n", "\n", "To run this model:\n", "1. Create a directory for your simulation (e.g., **mkdir my_test_run**)\n", "2. Copy the input file: **cp rayleigh/input_examples/benchmark_diagnostics_input my_test_run/main_input** \n", "3. Copy or soft-link the *rayleigh* executable: **cp Rayleigh/bin/rayleigh.opt my_test_run/.**\n", "4. Run the code: **mpiexec -np N ./rayleigh -nprow n -npcol m** (choose values of {N,n,m} such that n x m = N)\n", "\n", "The code will run for 40,000 timesteps, or four viscous diffusion times. While it runs, *Rayleigh* will perform an in-situ analysis of the accuracy benchmark. Reports are written once every 1,000 time steps and are stored in the *Benchmark_Reports* subdirectory. Examine file 00030000 and ensure that you see similar results to those below. Your exact numbers may differ slightly, but all quantities should be under 1% difference. \n", "\n", "\n", "\n", " | Observable | Measured | Suggested | % Difference | Std. Dev.|\n", " |------------------|----------------|-------------|--------------|----------|\n", "| Kinetic Energy | 58.347827 | 58.348000 | -0.000297 | 0.000000 |\n", "| Temperature | 0.427424 | 0.428120 | -0.162460 | 0.000101 |\n", "| Vphi | -10.119483 | -10.157100 | -0.370356 | 0.013835 |\n", "| Drift Frequency | 0.183016 | 0.182400 | 0.337630 | 0.007295 |\n", "\n", "\n", "If necessary, copy the data to the system on which you intend to conduct your analysis. Before you can plot, you will need to configure your Python environment. \n", "\n", "\n", "\n", "II. Configuring Your Python Environment\n", "=============\n", "Rayleigh comes packaged with a Python library (*rayleigh_diagnostics.py*) that provides data structures and methods associated with each type of diagnostic output in Rayleigh. This library relies on Numpy and is compatible with Python 3.x or 2.x (The *print* function is imported from the *__future__* module). \n", "\n", "If you wish to follow along with the plotting examples described in this document, you will need to have the Numpy and Matplotlib Python packages installed. The following versions of these packages were used when creating these examples:\n", "* Matplotlib v2.0.2 \n", "* Numpy v1.13.1 \n", "\n", "Unless you are experienced at installing and managing Python packages, I recommend setting up a virtual environment for Python using [Conda](https://conda.io/docs/). You may also install the required packages manually, but the advantage of this approach is that you maintain an entirely separate version of Python and related packages for this project. Below are directions for setting up a Python/Conda environment with Intel-optimized Python packages on a Linux system (Mac and Windows work similarly). \n", "\n", "\n", "Conda Installation on Linux Systems\n", "-------------------------------\n", "\n", "\n", "**Step 1: ** Download the appropriate Miniconda installation script from [https://conda.io/miniconda.html](https://conda.io/miniconda.html) (choose Python 3.x) \n", "\n", "**Step 2: ** Make the shell script executable via: **chmod +x Miniconda3-latest-Linux-x86_64.sh** (or similar script name)\n", "\n", "**Step 3: ** Run the installation script: **./Miniconda3-latest-Linux-x86_64.sh** \n", "\n", "*NOTE:* The default installation directory is your home directory. This is also where Python packages for your Conda environments will be installed. Avoid installing to a disk with limited space (user home directories on HPC systems are often limited to a few GB).\n", "\n", "*NOTE:* Unless you have a specific reason not to do so, answer \"yes\" to the question concerning prepending to PATH.\n", "\n", "**Step 5: ** Update your Conda: **conda update conda**\n", "\n", "**Step 6: ** Add the Intel Conda channel: **conda config --add channels intel**\n", "\n", "**Step 7: ** Create a virtual environment for Intel's Conda distribution: **conda create -n idp intelpython3_full python=3**\n", "\n", "*NOTE:* In this case, *idp* will be your virtual environment name. You are free to pick an alternative when running conda create.\n", "\n", "*NOTE:* A number of Python packages will be downloaded, including Numpy and Matplotlib. The process may appear to hang at the last step. Be patient.\n", "\n", "**Step 8: ** Activate your virtual environment: **source activate idp**\n", "\n", "\n", "**Step 9: ** Verify your installation. Type **python** and then type the following commands at the prompt: \n", "1. import numpy\n", "2. import matplotlib\n", "\n", "If those commands worked without error, you may close Python ( type **exit()** ). You can revert to your native environment by typing **source deactivate** (or just close the terminal). Whenever you wish to access your newly-installed Python, type **source activate idp** first, before running python. \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Preparing to Plot\n", "---------------------\n", "All examples in this document rely on the rayleigh_diagnostics module. This module is located in Rayleigh/post_processing, along with several standalone scripts copies from the individual sections of this document. For example, the script **plot_G_Avgs.py** contains the code from section IV below. All python files you wish to use will need to reside in either your run directory (recommended) or a directory within your PYTHONPATH.\n", "\n", "We suggest copying all python files to your my_test_run directory:\n", "1. cp Rayleigh/post_processing/*.py my_test_run/.\n", "2. cp Rayleigh/post_processing/*.ipynb my_test_run/.\n", "\n", "The Jupyter Notebook\n", "--------------\n", "This document resides in three places:\n", "1. Rayleigh/doc/Diagnostic_Plotting.pdf\n", "2. Rayleigh/doc/Diagnostic_Plotting.html\n", "3. Rayleigh/post_processing/Diagnostic_Plotting.ipynb\n", "\n", "The third file is a [Jupyter](http://jupyter.org/) notebook file. This source code was used to generate the html and pdf documents. The notebook is designed to be run from within a Rayleigh simulation directory. If you wish to follow along interactively, copy the Jupyter notebook file from Rayleigh/post_processing/ into your Rayleigh simulation directory (step 2 from *Preparing to Plot*). You can run the file in Jupyter via:\n", "1. source activate idp\n", "2. jupyter notebook (from within your my_test_run directory)\n", "3. select Diagnostic_Plotting.ipynb in the file menu that presents itself.\n", "\n", "When finished:\n", "1. To close the notebook, type **ctrl+c** and enter \"yes\" when prompted to shut down the notebook server.\n", "2. type **source deactivate**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "III. Overview of Diagnostics in Rayleigh\n", "=======================\n", "\n", "*Rayleigh's* diagnostics package facilitates the in-situ analysis of a simulation using a variety of sampling methods. Each sampling method may be applied to a unique set of sampled quantities. Sampling methods are hereafter referred to as *output types* and sampled quantities as *output variables*.\n", "\n", "Files of each output type are stored in a similarly-named subdirectory within the *Rayleigh* simulation directory. Output files are numbered by the time step of the final data record stored in the file. Output behavior for each simulation is controlled through the *main_input* file. For each output type, the user specifies the output variables, cadence, records-per-file, and other properties by modifying the appropriate variables in the **output_namelist** section of *main_input*.\n", "\n", "\n", "Basic Output Control\n", "----------------------------------\n", "\n", "Each output type in *Rayleigh* has at least three namelist variables that govern its behavior:\n", "\n", "**{OutputType}_values**: comma-separated list of menu codes corresponding to the desired output variables\n", "\n", "**{OutputType}_frequency**: integer value that determines how often this type of output is performed\n", "\n", "**{OutputType}_nrec**: integer value that determines how many records are stored in each output file.\n", "\n", "All possible output variables and their associated menu codes are described in **rayleigh/doc/rayleigh_output_variables.pdf** You may find it useful to have that document open while following along with examples in this notebook.\n", "\n", "\n", "As an example of how these variables work, suppose that we want to occasionally output equatorial cuts (output type) of temperature, kinetic energy density, and radial velocity (output variables). At the same time, we might wish to dump full-volume averages (output type) of kinetic and magnetic energy (output variables) with a higher cadence. In that case, something similar to the following would appear in main_input:\n", "\n", "globalavg_values = 401, 1101 \n", "globalavg_frequency = 50 \n", "globalavg_nrec = 100\n", "\n", "equatorial_values = 1, 401, 501 \n", "equatorial_frequency = 2500 \n", "equatorial_nrec = 2\n", "\n", "This tells *Rayleigh* to output full-volume-averages of kinetic energy density (value code 401) and magnetic energy density (value code 1101) once every 50 time steps, with 100 records per file. Files are named based on the time step number of their final record. As a result, information from time steps 50, 100, 150, ..., 4950, 5000 will be stored in the file named *G_Avgs/00005000*. Time steps 5050 through 10,000 will stored in *G_Avgs/00010000*, and so on. \n", "\n", "For the equatorial cuts, *Rayleigh* will output radial velocity (code 1), the kinetic energy density (code 401) and temperature (code 501) in the equatorial plane once every 2,500 time steps, storing two time steps per file. Data from time steps 2,500 and 5,000 will be stored in *Equatorial_Slices/00005000*. Data from time steps 7,500 and 10,000 will be stored in *Equatorial_Slices/00010000* , and so on.\n", "\n", "*This general organizational scheme for output was adapted from that developed by Thomas Clune for the ASH code.*\n", "\n", "Positional Output Control\n", "-----------------------------\n", "\n", "Many of *Rayleigh's* output types allow the user to specify a set of gridpoints at which to sample the simulation. A user can, for example, output spherical surfaces sampled at arbitrary radii, or a meridional plane sampled at a specific longitude. This behavior is controlled through additional namelist variables; we refer to these variables as positional specifiers. In the sections that follow, positional specifiers associated with a given output type, if any, will be defined.\n", "\n", "Positional specifiers are either *indicial* or *normalized*. In the *main_input* file, indicial specifiers can be assigned a comma-separated list of grid indices on which to perform the output. For example, \n", "\n", "shellslice_levels = 1, 32, 64, 128\n", "\n", "instructs *Rayleigh* to output shell slices at { radius[1], radius[32], radius[64], radius[128]}. Note that radius[1] is the outer boundary.\n", "\n", "While useful in some situations, specifying indices can lead to confusion if a simulations resolution needs to be changed at some point during a model's evolution. For example if the radial grid initially had 128 points, index 128 would correspond to the lower boundary. If the resolution were to double, index 128 would correspond to mid-shell.\n", "\n", "For this reason, all positional specifiers may also be written in normalized form. Instead of integers, the normalized specifier is assigned a comma separated list of real values in the range [0,1]. The value of zero corresponds to the lowest-value grid coordinate (e.g., the inner radial boundary or theta=0 pole). The value 1 corresponds to the maximal coordinate (e.g., the outer radial boundary or theta=pi pole). A value of 0.5 corresponds to mid-domain. Normalized coordinates are indicated by adding *_nrm* to the indicial specifier's name. For example,\n", "\n", "shellslice_levels_nrm= 0, 0.5, 0.95\n", "\n", "instructs *Rayleigh* to output shell slices at the lower boundary, mid-shell, and slightly below the upper boundary. *Rayleigh* does not interpolate, but instead picks the grid coordinate closest to each specified normalized coordinate. \n", "\n", "We recommend using normalized coordinates to avoid inconsistencies between restarts. They also overcome difficulties associated with the non-uniform nature of the radial and theta grids wherein grid points cluster near the boundaries.\n", "\n", "**Positional Ranges**\n", "Ranges of coordinates can be specified using shorthand, if desired. The inclusive coordinate range [X,Y] is indicated by a positive/negative number pair appearing in the indicial or normalized coordinate list. Multiple ranges can be specified within a list. For example,\n", "\n", "shellslice_levels = 1,10,-15, 16, 20,-25, 128\n", "\n", "would instruct *Rayleigh* to output shell slices at radial indices = { 1, 10, 11, 12, 13, 14, 15, 16, 20, 21, 22, 23, 24, 25, 128}\n", "\n", "Similarly,\n", "\n", "shellslice_levels_nrm = 0,-0.5, 1.0\n", "\n", "instructs *Rayleigh* to output shells at all radii in the lower half of the domain, and at the outer boundary. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "IV. Global Averages\n", "------------\n", "\n", "**Summary:** Full-volume averages of requested output variables over the full, spherical shell\n", "\n", "**Subdirectory:** G_Avgs\n", "\n", "**main_input prefix:** globalavg\n", "\n", "**Python Class:** G_Avgs\n", "\n", "**Additional Namelist Variables:** \n", "None\n", "\n", "*Before proceeding, ensure that you have copied Rayleigh/post_processing/rayleigh_diagnostics.py to your simulation directory. This Python module is required for reading Rayleigh output into Python.*\n", "\n", "Examining the *main_input* file, we see that the following output values have been denoted for the Global Averages (see *rayleigh_output_variables.pdf* for the mathematical formulae):\n", "\n", "\n", "| Menu Code | Description |\n", "|-----------|-------------|\n", "| 401 | Full Kinetic Energy Density (KE) |\n", "| 402 | KE (radial motion) |\n", "| 403 | KE (theta motion) |\n", "| 404 | KE (phi motion) |\n", "| 405 | Mean Kinetic Energy Density (MKE) |\n", "| 406 | MKE (radial motion) |\n", "| 407 | MKE (theta motion) |\n", "| 408 | MKE (phi motion) |\n", "| 409 | Fluctuating Kinetic Energy Density (FKE) |\n", "| 410 | FKE (radial motion) |\n", "| 411 | FKE (theta motion) |\n", "| 412 | FKE (phi motion) |\n", "\n", "In the example that follows, we will plot the time-evolution of these different contributions to the kinetic energy budget. We begin with the following preamble:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "from rayleigh_diagnostics import G_Avgs, build_file_list\n", "import matplotlib.pyplot as plt\n", "import numpy\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The preamble for each plotting example will look similar to that above. We import the numpy and matplotlib.pyplot modules, aliasing the latter to *plt*. We also import two items from *rayleigh_diagnostics*: a helper function *build_file_list* and the *GlobalAverage* class. \n", "\n", "The *G_Avgs* class is the Python class that corresponds to the full-volume averages stored in the *G_Avgs* subdirectory of each Rayleigh run.\n", "\n", "We will use the build_file_list function in many of the examples that follow. It's useful when processing a time series of data, as opposed to a single snapshot. This function accepts three parameters: a beginning time step, an ending time step, and a subdirectory (path). It returns a list of all files found in that directory that lie within the inclusive range [beginning time step, ending time step]. The file names are prepended with the subdirectory name, as shown below." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Build a list of all files ranging from iteration 0 million to 1 million\n", "files = build_file_list(0,1000000,path='G_Avgs')\n", "print(files)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can create an instance of the G_Avgs class by initializing it with a filename. The optional keyword parameter *path* is used to specify the directory. If *path* is not specified, its value will default to the subdirectory name associated with the datastructure (*G_Avgs* in this instance). \n", "\n", "Each class was programmed with a **docstring** describing the class attributes. Once you created an instance of a rayleigh_diagnostics class, you can view its attributes using the help function as shown below." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = G_Avgs(filename=files[0],path='') # Here, files[0]='G_Avgs/00010000'\n", "#a= G_Avgs(filename='00010000') would yield an equivalent result\n", "help(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Examining the docstring, we see a few important attributes that are common to the other outputs discussed in this document:\n", "1. niter -- the number of time steps in the file\n", "2. nq -- the number of output variables stored in the file\n", "3. qv -- the menu codes for those variables\n", "4. vals -- the actual data\n", "5. time -- the simulation time corresponding to each output dump\n", "\n", "The first step in plotting a time series is to collate the data." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Loop over all files and concatenate their data into a single array\n", "nfiles = len(files)\n", "for i,f in enumerate(files):\n", " a = G_Avgs(filename=f,path='')\n", " if (i == 0):\n", " nq = a.nq\n", " niter = a.niter\n", " gavgs = numpy.zeros((niter*nfiles,nq),dtype='float64')\n", " iters = numpy.zeros(niter*nfiles,dtype='int32')\n", " time = numpy.zeros(niter*nfiles,dtype='float64')\n", " i0 = i*niter\n", " i1 = (i+1)*niter\n", " gavgs[i0:i1,:] = a.vals\n", " time[i0:i1] = a.time\n", " iters[i0:i1] = a.iters\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The Lookup Table (LUT)\n", "------------------\n", "\n", "The next step in the process is to identify where within the *gavgs* array our deisired output variables reside. Every Rayleigh file object possesses a lookup table (lut). The lookup table is a python list used to identify the index within the vals array where a particular menu code resides. For instance, the menu code for the theta component of the velocity is 2. The location of v_theta in the vals array is then stored in lut[2]. \n", "\n", "Note that you should never assume that output variables are stored in any particular order. Moreover, the lookup table is unique to each file and is likely to change during a run if you modify the output variables in between restarts. When running the benchmark, we kept a consistent set of outputs throughout the entirety of the run. This means that the lookup table did not change between outputs and that we can safely use the final file's lookup table (or any other file's table) to reference our data.\n", "\n", "Plotting Kinetic Energy\n", "---------------------------\n", "Let's examine the different contributions to the kinetic energy density in our models. Before we can plot, we should use the lookup table to identify the location of each quantity we are interested in plotting." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#The indices associated with our various outputs are stored in a lookup table\n", "#as part of the GlobalAverage data structure. We define several variables to\n", "#hold those indices here:\n", "\n", "lut = a.lut\n", "ke = lut[401] # Kinetic Energy (KE)\n", "rke = lut[402] # KE associated with radial motion\n", "tke = lut[403] # KE associated with theta motion\n", "pke = lut[404] # KE associated with azimuthal motion\n", "\n", "#We also grab some energies associated with the mean (m=0) motions\n", "mke = lut[405]\n", "mrke = lut[406] # KE associated with mean radial motion\n", "mtke = lut[407] # KE associated with mean theta motion\n", "mpke = lut[408] # KE associated with mean azimuthal motion\n", "\n", "#We also output energies associated with the fluctuating/nonaxisymmetric\n", "#motions (e.g., v- v_{m=0})\n", "fke = lut[409]\n", "frke = lut[410] # KE associated with mean radial motion\n", "ftke = lut[411] #KE associated with mean theta motion\n", "fpke = lut[412] # KE associated with mean azimuthal motion\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To begin with, let's plot the total, mean, and fluctuating kinetic energy density during the initial transient phase, and then during the equilibrated phase." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sizetuple=(10,3)\n", "fig, ax = plt.subplots(ncols=2, figsize=sizetuple)\n", "ax[0].plot(time, gavgs[:,ke], label='KE')\n", "ax[0].plot(time, gavgs[:,mke],label='MKE')\n", "ax[0].plot(time, gavgs[:,fke], label='FKE')\n", "ax[0].legend(loc='center right', shadow=True)\n", "ax[0].set_xlim([0,0.2])\n", "ax[0].set_title('Equilibration Phase')\n", "ax[0].set_xlabel('Time')\n", "ax[0].set_ylabel('Energy')\n", "\n", "ax[1].plot(time, gavgs[:,ke], label='KE')\n", "ax[1].plot(time, gavgs[:,mke], label = 'MKE')\n", "ax[1].plot(time,gavgs[:,fke],label='FKE')\n", "ax[1].legend(loc='center right', shadow=True)\n", "ax[1].set_title('Entire Time-Trace')\n", "ax[1].set_xlabel('Time')\n", "ax[1].set_ylabel('Energy')\n", "\n", "saveplot = False # Plots appear in the notebook and are not written to disk (set to True to save to disk)\n", "savefile = 'energy_trace.pdf' #Change .pdf to .png if pdf conversion gives issues\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also look at the energy associated with each velocity component.\n", "Note that we log scale in the last plot. There is very little mean radial or theta kinetic energy; it is mostly phi energy." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sizetuple=(5,10)\n", "xlims=[0,0.2]\n", "fig, ax = plt.subplots(ncols=1, nrows=3, figsize=sizetuple)\n", "ax[0].plot(time, gavgs[:,ke], label='KE')\n", "ax[0].plot(time, gavgs[:,rke],label='RKE')\n", "ax[0].plot(time, gavgs[:,tke], label='TKE')\n", "ax[0].plot(time, gavgs[:,pke], label='PKE')\n", "ax[0].legend(loc='center right', shadow=True)\n", "ax[0].set_xlim(xlims)\n", "ax[0].set_title('Total KE Breakdown')\n", "ax[0].set_xlabel('Time')\n", "ax[0].set_ylabel('Energy')\n", "\n", "ax[1].plot(time, gavgs[:,fke], label='FKE')\n", "ax[1].plot(time, gavgs[:,frke], label='FRKE')\n", "ax[1].plot(time, gavgs[:,ftke], label='FTKE')\n", "ax[1].plot(time, gavgs[:,fpke], label='FPKE')\n", "ax[1].legend(loc='center right', shadow=True)\n", "ax[1].set_xlim(xlims)\n", "ax[1].set_title('Fluctuating KE Breakdown')\n", "ax[1].set_xlabel('Time')\n", "ax[1].set_ylabel('Energy')\n", "\n", "ax[2].plot(time, gavgs[:,mke], label='MKE')\n", "ax[2].plot(time, gavgs[:,mrke], label='MRKE')\n", "ax[2].plot(time, gavgs[:,mtke], label='MTKE')\n", "ax[2].plot(time, gavgs[:,mpke], label='MPKE')\n", "ax[2].legend(loc='lower right', shadow=True)\n", "ax[2].set_xlim(xlims)\n", "ax[2].set_title('Mean KE Breakdown')\n", "ax[2].set_xlabel('Time')\n", "ax[2].set_ylabel('Energy')\n", "ax[2].set_yscale('log')\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "V. Shell Averages\n", "==========\n", "\n", "**Summary:** Spherical averages of requested output variables. Each output variable is stored as a 1-D function of radius.\n", "\n", "**Subdirectory:** Shell_Avgs\n", "\n", "**main_input prefix:** shellavg\n", "\n", "**Python Class:** Shell_Avgs\n", "\n", "**Additional Namelist Variables:** \n", "None\n", "\n", "The Shell-Averaged outputs are useful for examining how quantities vary as a function of radius. They are particularly useful for examining the distribution of energy as a function of radius, or the heat flux balance established by the system.\n", "\n", "Examining the *main_input* file, we see that the following output values have been denoted for the Shell Averages (see *rayleigh_output_variables.pdf* for mathematical formulae):\n", "\n", "\n", "| Menu Code | Description |\n", "|------------|-------------|\n", "| 1 | Radial Velocity |\n", "| 2 | Theta Velocity |\n", "| 3 | Phi Velocity |\n", "| 501 | Temperature Perturbation |\n", "| 1438 | Radial Convective Heat Flux|\n", "| 1468 |Radial Conductive Heat Flux |\n", "\n", "\n", "In the example that follows, we will plot the spherically-averaged velocity field as a function of radius, the mean temperature profile, and the radial heat flux. We begin with a preamble similar to that used for the Global Averages. Using the help function, we see that the Shell_Avgs data structure is similar to that of the G_Avgs. There are three important differences:\n", "* There is a radius attribute (necessary if we want to plot anything vs. radius)\n", "* The dimensionality of the values array has changed; radial index forms the first dimension.\n", "* The second dimension of the values array has a length of 4. In addition to the spherical mean, the 1st, 2nd and 3rd moments are stored in indices 0,1,2, and 3 respectively." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from rayleigh_diagnostics import Shell_Avgs, build_file_list\n", "import matplotlib.pyplot as plt\n", "import numpy\n", "\n", "# Build a list of all files ranging from iteration 0 million to 1 million\n", "files = build_file_list(0,1000000,path='Shell_Avgs')\n", "a = Shell_Avgs(filename=files[0], path='')\n", "help(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "***\n", "\n", "While it can be useful to look at instaneous snapshots of Shell Averages, it's often useful to examine these outputs in a time-averaged sense. Let's average of all 200 snapshots in the last file that was output. We could average over data from multiple files, but since the benchmark run achieves a nearly steady state, a single file will do in this case." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nfiles = len(files)\n", "\n", "nr = a.nr\n", "nq = a.nq\n", "nmom = 4\n", "niter = a.niter\n", "radius = a.radius\n", "savg=numpy.zeros((nr,nmom,nq),dtype='float64')\n", "for i in range(niter):\n", " savg[:,:,:] += a.vals[:,:,:,i]\n", "savg = savg*(1.0/niter)\n", "\n", "lut = a.lut\n", "vr = lut[1] # Radial Velocity\n", "vtheta = lut[2] # Theta Velocity\n", "vphi = lut[3] # Phi Velocity\n", "thermal = lut[501] # Temperature\n", "\n", "\n", "eflux = lut[1440] # Convective Heat Flux (radial)\n", "cflux = lut[1470] # Conductive Heat Flux (radial)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Velocity vs. Radius\n", "---------------------\n", "Next, we plot the mean velocity field, and its first moment, as a function of radius. Notice that the radial and theta velocity components have a zero spherical mean. Since we are running an incompressible model, this is a good sign!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sizetuple = (7,7)\n", "fig, ax = plt.subplots(nrows=2, ncols =1, figsize=sizetuple)\n", "\n", "ax[0].plot(radius,savg[:,0,vr],label=r'$v_r$')\n", "ax[0].plot(radius,savg[:,0,vtheta], label=r'$v_\\theta$')\n", "ax[0].plot(radius,savg[:,0,vphi], label=r'$v_\\phi$')\n", "ax[0].legend(shadow=True,loc='lower right')\n", "ax[0].set_xlabel('Radius')\n", "ax[0].set_ylabel('Velocity')\n", "ax[0].set_title('Spherically-Averaged Velocity Components')\n", "\n", "ax[1].plot(radius,savg[:,1,vr],label=r'$v_r$')\n", "ax[1].plot(radius,savg[:,1,vtheta], label=r'$v_\\theta$')\n", "ax[1].plot(radius,savg[:,1,vphi], label=r'$v_\\phi$')\n", "ax[1].legend(shadow=True,loc='upper left')\n", "ax[1].set_xlabel('Radius')\n", "ax[1].set_ylabel('Velocity')\n", "ax[1].set_title('Velocity Components: First Spherical Moment')\n", "\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Radial Temperature Profile\n", "------------------------------\n", "We might also look at temperature ..." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", "\n", "ax.plot(radius,savg[:,0,thermal],label='Temperature (mean)')\n", "ax.plot(radius,savg[:,1,thermal]*10, label='Temperature (standard dev.)')\n", "ax.legend(shadow=True,loc='upper right')\n", "ax.set_xlabel('Radius')\n", "ax.set_ylabel('Temperature')\n", "ax.set_title('Radial Temperature Profile')\n", "\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Heat Flux Contributions\n", "--------------------------\n", "We can also examine the balance between convective and conductive heat flux. In this case, before plotting these quantities as a function of radius, we normalize them by the surface area of the sphere to form a luminosity." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fpr=4.0*numpy.pi*radius*radius\n", "elum = savg[:,0,eflux]*fpr\n", "clum = savg[:,0,cflux]*fpr\n", "tlum = elum+clum\n", "fig, ax = plt.subplots()\n", "ax.plot(radius,elum,label='Convection')\n", "ax.plot(radius,clum, label='Conduction')\n", "ax.plot(radius,tlum, label='Total')\n", "ax.set_title('Flux Balance')\n", "ax.set_ylabel(r'Energy Flux ($\\times 4\\pi r^2$)')\n", "ax.set_xlabel('Radius')\n", "ax.legend(shadow=True)\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "VI. Azimuthal Averages\n", "=============\n", "\n", "\n", "**Summary:** Azimuthal averages of requested output variables. Each output variable is stored as a 2-D function of radius and latitude.\n", "\n", "**Subdirectory:** AZ_Avgs\n", "\n", "**main_input prefix:** azavg\n", "\n", "**Python Class:** AZ_Avgs\n", "\n", "**Additional Namelist Variables:** \n", "None\n", "\n", "Azimuthally-Averaged outputs are particularly useful for examining a system's mean flows (i.e., differential rotation and meridional circulation). \n", "\n", "Examining the *main_input* file, we see that the following output values have been denoted for the Azimuthal Averages (see *rayleigh_output_variables.pdf* for mathematical formulae):\n", "\n", "\n", "| Menu Code | Description |\n", "|------------|-------------|\n", "| 1 | Radial Velocity |\n", "| 2 | Theta Velocity |\n", "| 3 | Phi Velocity |\n", "| 201 | Radial Mass Flux |\n", "| 202 | Theta Mass Flux |\n", "| 501 | Temperature Perturbation |\n", "\n", "\n", "\n", "In the example that follows, we demonstrate how to plot azimuthal averages, including how to generate streamlines of mass flux. Note that since the benchmark is Boussinesq, our velocity and mass flux fields are identical. This is not the case when running an anelastic simulation.\n", "\n", "We begin with the usual preamble and also import two helper routines used for displaying azimuthal averages.\n", "\n", "Examining the data structure, we see that the vals array is dimensioned to account for latitudinal variation, and that we have new attributes costheta and sintheta used for referencing locations in the theta direction." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from rayleigh_diagnostics import AZ_Avgs, build_file_list, plot_azav, streamfunction\n", "import matplotlib.pyplot as plt\n", "import pylab\n", "import numpy\n", "#from azavg_util import *\n", "files = build_file_list(30000,40000,path='AZ_Avgs')\n", "az = AZ_Avgs(files[0],path='')\n", "help(az)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "Before creating our plots, let's time-average over the last two files that were output (thus sampling the equilibrated phase)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "\n", "\n", "nfiles = len(files)\n", "tcount=0\n", "for i in range(nfiles):\n", " az=AZ_Avgs(files[i],path='')\n", "\n", " if (i == 0):\n", " nr = az.nr\n", " ntheta = az.ntheta\n", " nq = az.nq\n", " azavg=numpy.zeros((ntheta,nr,nq),dtype='float64')\n", "\n", " for j in range(az.niter):\n", " azavg[:,:,:] += az.vals[:,:,:,j]\n", " tcount+=1\n", "azavg = azavg*(1.0/tcount) # Time steps were uniform for this run, so a simple average will suffice\n", "\n", "lut = az.lut\n", "vr = azavg[:,:,lut[1]]\n", "vtheta = azavg[:,:,lut[2]]\n", "vphi = azavg[:,:,lut[3]]\n", "rhovr = azavg[:,:,lut[201]]\n", "rhovtheta = azavg[:,:,lut[202]]\n", "temperature = azavg[:,:,lut[501]]\n", "radius = az.radius\n", "costheta = az.costheta\n", "sintheta = az.sintheta" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Before we render, we need to do some quick post-processing:\n", "1. Remove the spherical mean temperature from the azimuthal average.\n", "2. Convert v_phi into omega\n", "3. Compute the magnitude of the mass flux vector\n", "4. Compute stream function associated with the mass flux field" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Subtrace the ell=0 component from temperature at each radius\n", "for i in range(nr):\n", " temperature[:,i]=temperature[:,i] - numpy.mean(temperature[:,i])\n", "\n", "#Convert v_phi to an Angular velocity\n", "omega=numpy.zeros((ntheta,nr))\n", "for i in range(nr):\n", " omega[:,i]=vphi[:,i]/(radius[i]*sintheta[:])\n", "\n", "#Generate a streamfunction from rhov_r and rhov_theta\n", "psi = streamfunction(rhovr,rhovtheta,radius,costheta,order=0)\n", "#contours of mass flux are overplotted on the streamfunction PSI\n", "rhovm = numpy.sqrt(rhovr**2+rhovtheta**2)*numpy.sign(psi) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, we render the azimuthal averages. \n", "**NOTE:** If you want to save any of these figures, you can mimic the saveplot logic at the bottom of this example." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# We do a single row of 3 images \n", "# Spacing is default spacing set up by subplot\n", "figdpi=300\n", "sizetuple=(5.5*3,3*3)\n", "\n", "\n", "tsize = 20 # title font size\n", "cbfsize = 10 # colorbar font size\n", "fig, ax = plt.subplots(ncols=3,figsize=sizetuple,dpi=figdpi)\n", "plt.rcParams.update({'font.size': 14})\n", "\n", "#temperature\n", "#ax1 = f1.add_subplot(1,3,1)\n", "units = '(nondimensional)'\n", "plot_azav(fig,ax[0],temperature,radius,costheta,sintheta,mycmap='RdYlBu_r',boundsfactor = 2, \n", " boundstype='rms', units=units, fontsize = cbfsize)\n", "ax[0].set_title('Temperature',fontsize=tsize)\n", "\n", "#Differential Rotation\n", "#ax1 = f1.add_subplot(1,3,2)\n", "units = '(nondimensional)'\n", "plot_azav(fig,ax[1],omega,radius,costheta,sintheta,mycmap='RdYlBu_r',boundsfactor = 1.5, \n", " boundstype='rms', units=units, fontsize = cbfsize)\n", "ax[1].set_title(r'$\\omega$',fontsize=tsize)\n", "\n", "#Mass Flux\n", "#ax1 = f1.add_subplot(1,3,3)\n", "units = '(nondimensional)'\n", "plot_azav(fig,ax[2],psi,radius,costheta,sintheta,mycmap='RdYlBu_r',boundsfactor = 1.5, \n", " boundstype='rms', units=units, fontsize = cbfsize, underlay = rhovm)\n", "ax[2].set_title('Mass Flux',fontsize = tsize)\n", "\n", "saveplot=False\n", "if (saveplot):\n", " p.savefig(savefile) \n", "else:\n", " plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "VII. Simulation Slices \n", "============\n", "\n", "VII.1 Equatorial Slices\n", "--------------------------\n", "\n", "**Summary:** 2-D profiles of selected output variables in the equatorial plane. \n", "\n", "**Subdirectory:** Equatorial_Slices\n", "\n", "**main_input prefix:** equatorial\n", "\n", "**Python Class:** Equatorial_Slices\n", "\n", "**Additional Namelist Variables:** \n", "None\n", "\n", "The equatorial-slice output type allows us to examine how the fluid properties vary in longitude and radius.\n", "\n", "Examining the *main_input* file, we see that the following output values have been denoted for the Equatorial Slices (see *rayleigh_output_variables.pdf* for mathematical formulae):\n", "\n", "\n", "| Menu Code | Description |\n", "|------------|-------------|\n", "| 1 | Radial Velocity |\n", "| 2 | Theta Velocity |\n", "| 3 | Phi Velocity |\n", "\n", "\n", "\n", "\n", "In the example that follows, we demonstrate how to create a 2-D plot of radial velocity in the equatorial plane (at a single time step).\n", "\n", "We begin with the usual preamble. Examining the data structure, we see that the *vals* array is dimensioned to account for longitudinal variation, and that we have the new coordinate attribute *phi*." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from rayleigh_diagnostics import Equatorial_Slices\n", "import numpy\n", "import matplotlib.pyplot as plt\n", "from matplotlib import ticker, font_manager\n", "istring = '00040000'\n", "es = Equatorial_Slices(istring)\n", "tindex =1 # Grab second time index from this file\n", "help(es)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "################################\n", "# Equatorial Slice \n", "#Set up the grid\n", "\n", "remove_mean = True # Remove the m=0 mean\n", "nr = es.nr\n", "nphi = es.nphi\n", "r = es.radius/numpy.max(es.radius)\n", "phi = numpy.zeros(nphi+1,dtype='float64')\n", "phi[0:nphi] = es.phi\n", "phi[nphi] = numpy.pi*2 # For display purposes, it is best to have a redunant data point at 0,2pi\n", "\n", "#We need to generate a cartesian grid of x-y coordinates (both X & Y are 2-D)\n", "radius_matrix, phi_matrix = numpy.meshgrid(r,phi)\n", "X = radius_matrix * numpy.cos(phi_matrix)\n", "Y = radius_matrix * numpy.sin(phi_matrix)\n", "\n", "qindex = es.lut[1] # radial velocity\n", "field = numpy.zeros((nphi+1,nr),dtype='float64')\n", "field[0:nphi,:] =es.vals[:,:,qindex,tindex]\n", "field[nphi,:] = field[0,:] #replicate phi=0 values at phi=2pi\n", "\n", "#remove the mean if desired (usually a good idea, but not always)\n", "if (remove_mean):\n", " for i in range(nr):\n", " the_mean = numpy.mean(field[:,i])\n", " field[:,i] = field[:,i]-the_mean\n", "\n", "#Plot\n", "sizetuple=(8,5)\n", "fig, ax = plt.subplots(figsize=(8,8))\n", "tsize = 20 # title font size\n", "cbfsize = 10 # colorbar font size\n", "img = ax.pcolormesh(X,Y,field,cmap='jet')\n", "ax.axis('equal') # Ensure that x & y axis ranges have a 1:1 aspect ratio\n", "ax.axis('off') # Do not plot x & y axes\n", "\n", "# Plot bounding circles\n", "ax.plot(r[nr-1]*numpy.cos(phi), r[nr-1]*numpy.sin(phi), color='black') # Inner circle\n", "ax.plot(r[0]*numpy.cos(phi), r[0]*numpy.sin(phi), color='black') # Outer circle\n", "\n", "ax.set_title(r'$v_r$', fontsize=20)\n", "\n", "#colorbar ...\n", "cbar = plt.colorbar(img,orientation='horizontal', shrink=0.5, aspect = 15, ax=ax)\n", "cbar.set_label('nondimensional')\n", " \n", "tick_locator = ticker.MaxNLocator(nbins=5)\n", "cbar.locator = tick_locator\n", "cbar.update_ticks()\n", "cbar.ax.tick_params(labelsize=cbfsize) #font size for the ticks\n", "\n", "t = cbar.ax.xaxis.label\n", "t.set_fontsize(cbfsize) # font size for the axis title\n", "\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "VII.2 Meridional Slices\n", "--------------------------\n", "\n", "**Summary:** 2-D profiles of selected output variables sampled in meridional planes. \n", "\n", "**Subdirectory:** Meridional_Slices\n", "\n", "**main_input prefix:** meridional\n", "\n", "**Python Class:** Meridional_Slices\n", "\n", "**Additional Namelist Variables:** \n", "\n", "* meridional_indices (indicial) : indices along longitudinal grid at which to output meridional planes.\n", "\n", "* meridional_indices_nrm (normalized) : normalized longitudinal grid coordinates at which to output\n", "\n", "\n", "The meridional-slice output type allows us to examine how the fluid properties vary in latitude and radius.\n", "\n", "Examining the *main_input* file, we see that the following output values have been denoted for the Meridional Slices (see *rayleigh_output_variables.pdf* for mathematical formulae):\n", "\n", "\n", "| Menu Code | Description |\n", "|------------|-------------|\n", "| 1 | Radial Velocity |\n", "| 2 | Theta Velocity |\n", "| 3 | Phi Velocity |\n", "\n", "\n", "\n", "\n", "In the example that follows, we demonstrate how to create a 2-D plot of radial velocity in a meridional plane. The procedure is similar to that used to plot an azimuthal average.\n", "\n", "\n", "We begin with the usual preamble and import the *plot_azav* helper function. Examining the data structure, we see that it is similar to the AZ_Avgs data structure. The *vals* array possesses an extra dimension relative to its AZ_Avgs counterpart to account for the multiple longitudes that may be output, we see attributes *phi* and *phi_indices* have been added to reference the longitudinal grid. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#####################################\n", "# Meridional Slice\n", "from rayleigh_diagnostics import Meridional_Slices, plot_azav\n", "import numpy\n", "import matplotlib.pyplot as plt\n", "from matplotlib import ticker, font_manager\n", "# Read the data\n", "\n", "istring = '00040000'\n", "ms = Meridional_Slices(istring)\n", "tindex =1 # All example quantities were output with same cadence. Grab second time-index from all.\n", "help(ms)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "radius = ms.radius\n", "costheta = ms.costheta\n", "sintheta = ms.sintheta\n", "phi_index = 0 # We only output one Meridional Slice\n", "vr_ms = ms.vals[phi_index,:,:,ms.lut[1],tindex]\n", "units = 'nondimensional'\n", "\n", "# Plot\n", "sizetuple=(8,5)\n", "fig, ax = plt.subplots(figsize=(8,8))\n", "tsize = 20 # title font size\n", "cbfsize = 10 # colorbar font size\n", "ax.axis('equal') # Ensure that x & y axis ranges have a 1:1 aspect ratio\n", "ax.axis('off') # Do not plot x & y axes\n", "plot_azav(fig,ax,vr_ms,radius,costheta,sintheta,mycmap='RdYlBu_r',boundsfactor = 4.5, \n", " boundstype='rms', units=units, fontsize = cbfsize)\n", "ax.set_title('Radial Velocity',fontsize=tsize)\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "VII.3 Shell Slices\n", "--------------------------\n", "\n", "**Summary:** 2-D, spherical profiles of selected output variables sampled in at discrete radii. \n", "\n", "**Subdirectory:** Shell_Slices\n", "\n", "**main_input prefix:** shellslice\n", "\n", "**Python Class:** Shell_Slices\n", "\n", "**Additional Namelist Variables:** \n", "\n", "* shellslice_levels (indicial) : indices along radial grid at which to output spherical surfaces.\n", "\n", "* shellslice_levels_nrm (normalized) : normalized radial grid coordinates at which to output spherical surfaces.\n", "\n", "\n", "The shell-slice output type allows us to examine how the fluid properties vary on spherical surfaces.\n", "\n", "Examining the *main_input* file, we see that the following output values have been denoted for the Shell Slices (see *rayleigh_output_variables.pdf* for mathematical formulae):\n", "\n", "\n", "| Menu Code | Description |\n", "|------------|-------------|\n", "| 1 | Radial Velocity |\n", "| 2 | Theta Velocity |\n", "| 3 | Phi Velocity |\n", "\n", "\n", "\n", "\n", "In the example that follows, we demonstrate how to create a 2-D plot of the radial velocity on a Cartesian, lat-lon grid.\n", "\n", "Plotting on a lat-lon grid is straightforward and illustrated below. The shell-slice data structure is also displayed via the help() function in the example below and contains information needed to define the spherical grid for plotting purposes." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#####################################\n", "# Shell Slice\n", "from rayleigh_diagnostics import Shell_Slices\n", "import numpy\n", "import matplotlib.pyplot as plt\n", "from matplotlib import ticker, font_manager\n", "# Read the data\n", "\n", "istring = '00040000'\n", "ss = Shell_Slices(istring)\n", "help(ss)\n", "ntheta = ss.ntheta\n", "nphi = ss.nphi\n", "costheta = ss.costheta\n", "theta = numpy.arccos(costheta)\n", "\n", "#help(ss)\n", "tindex =1 # All example quantities were output with same cadence. Grab second time-index from all.\n", "rindex = 0 # only output one radius\n", "sizetuple=(8,8)\n", "\n", "vr = ss.vals[:,:,rindex,ss.lut[1],tindex]\n", "fig, ax = plt.subplots(figsize=sizetuple)\n", "\n", "\n", "img = plt.imshow(numpy.transpose(vr), extent=[0,360,-90,90])\n", "ax.set_xlabel( 'Longitude')\n", "ax.set_ylabel( 'Latitude')\n", "ax.set_title( 'Radial Velocity')\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By running the cell below, we can plot different output quantities on a spherical surface.\n", "In the example shown here, we plot all three velocity components ($u_r$, $u_{\\theta}$ and $u_{\\phi}$)\n", "projected onto a spherical surface. For demonstration purposes, we illustrate each velocity component using different colormaps, at different latitudinal centers of vantage point etc. (for more details see comments within cell below as well as the Jupyter notebook titled \"plot_shells.ipynb\").\n", "\n", "Note that in order to successfully run the cell below, you also need to have the orthographic projection code \"projection.py\" within the same directory/folder as this notebook." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy\n", "import matplotlib.pyplot as plt\n", "from matplotlib import gridspec\n", "from rayleigh_diagnostics import Shell_Slices\n", "from projection import plot_ortho\n", "\n", "# This plots various data from a single shell_slice file.\n", "# 3 diferent plots in 1 row and 3 columns are created.\n", "# It's easy to hack this to work with multiple files\n", "\n", "s1=Shell_Slices('00040000')\n", "data = numpy.zeros((s1.nphi,s1.ntheta),dtype='float64')\n", "costheta = s1.costheta\n", "nrows=2\n", "ncols=2\n", "pltin = 9 # Size of each subimage in inches (will be square)\n", "\n", "\n", "# number of rows and columns\n", "nrow=1\n", "ncol=3\n", "\n", "#We use gridspec to set up a grid. We actually have nrow*2 rows, with every other\n", "#row being a 'spacer' row that's 10% the height of the main rows.\n", "#This was the simplest way I could come up with the have the color bars appear nicely.\n", "fig = plt.figure(constrained_layout=False, figsize=(pltin*ncol,pltin*nrow*1.1))\n", "spec = gridspec.GridSpec(ncols=ncol, nrows=nrow*2, figure=fig, height_ratios=[1,.1]*nrow, width_ratios=[1]*ncol)\n", "\n", "\n", "\n", "plt.rcParams.update({'font.size': 16})\n", "#quantities codes to plot -- here all three velocity components\n", "qi = [1,2, 3]\n", "nm = [r'u$_r$', r'u$_\\theta$', r'u$_\\phi$']\n", "\n", "qinds = [qi, qi] # Quantity codes to plot\n", "names = [nm, nm] # Names for labeling\n", "\n", "lv = [[1]*ncol , [2]*ncol] # Shell levels to plot (top row is level 1, bottom row is level 2)\n", "\n", "\n", "style1=['-','--',':']\n", "style2=['-', '-', '-']\n", "styles = [style1, style2] # Line style of grid lines\n", "\n", "gwidth1=[0.5 , 1 , 1.5] \n", "gwidth2=[1,1,1]\n", "gwidths = [gwidth1, gwidth2] # width of grid lines for each image (Default: True)\n", "\n", "hwidths1=[2.5,2.5,2.5] # Width of the horizon line or each image (Default: 2)\n", "hwidths2=[2,2,2]\n", "hwidths=[hwidths1,hwidths2]\n", "\n", "cmaps1 = [\"RdYlBu_r\", \"seismic\", 'PiYG'] # A color table for each image (Default: RdYlBu_r)\n", "cmaps2 = [\"RdYlBu_r\"]*4\n", "cmaps = [cmaps1, cmaps1]\n", "\n", "pgrids1 = [True, True, True] \n", "pgrids2 = [True, True, True]\n", "pgrids = [pgrids1, pgrids2] # Plot grids, or not for each image (Default: True)\n", "\n", "latcens1 = [60, 45, 15]\n", "latcens = [latcens1, latcens1] # Latitudinal center of vantage point (Default: 45 N)\n", "\n", "loncens1 = [0,0,0]\n", "loncens2 = [30,30,30] # Longitudinal center of vantage point (Default: 0)\n", "loncens = [loncens1,loncens2]\n", "\n", "##########################################################\n", "# If the grid is plotted, the number of latitude lines\n", "# for the grid can be controlled via the nlats keyword.\n", "# Default: 9\n", "# Note that if nlats is even, the equator will not be drawn\n", "nlats1 = [3,5,7]\n", "nlats2 = [4,6,8]\n", "nlats = [nlats1, nlats1]\n", "\n", "##############################################################################\n", "# Similarly, the nlons keyword can be used to control longitude lines\n", "# More precisely, it controls the number of MERIDIANS (great circles) drawn\n", "# Default: 8\n", "nlons1 = [4,8,12]\n", "nlons2 = [4,12,16]\n", "nlons = [nlons1,nlons1]\n", "\n", "#Longitude grid-lines can be drawn in one of two ways:\n", "# 1) Completely to the pole (polar_style = 'polar')\n", "# 2) Truncated at the last line of latitue drawn (polar_style = 'truncated')\n", "# Default: \"truncated\"\n", "pstyle1 = ['truncated', 'polar', 'truncated']\n", "pstyle = [pstyle1, pstyle1]\n", "\n", "\n", "##############################################################\n", "# We can also control the way in which the image is saturated\n", "# via the scale_type keyword. There are three possibilities:\n", "# 1) scale_type=['rms', a], where a is of type 'float'\n", "# In this instance, the image bounds are -a*rms(data), +a*rms(data)\n", "# 2) scale_type = ['abs', a]\n", "# In this instance, the image bounds are -a*abs(data), +a*abs(data)\n", "# 3) scale_type= ['force', [a,b]]\n", "# In this instance, the image bounds are a,b\n", "# 4) scale_type = [None,None]\n", "# In this instance, the image bounds are min(image), max(image)\n", "# Default: [None,None]\n", "# Note that rms and abs are taken over projected image values, not input data\n", "# (you only see half the data in the image)\n", "\n", "scale_type1 = [['rms',2.0 ], [None,None], ['abs', 0.5]]\n", "scale_type2 = [['force', [-1500,1500]], ['force',[-10000,10000]], ['rms',2.5]]\n", "scale_types = [scale_type1, scale_type1]\n", "\n", "# Number of pixels across each projected, interpolated image\n", "# 768 is the default and seems to do a reasonable job\n", "nyzi = 768\n", "\n", "\n", "\n", "for j in range(ncol):\n", " for i in range(nrow):\n", " \n", " data[:,:] = s1.vals[:,:,lv[i][j],s1.lut[qinds[i][j]],0] \n", "\n", " row_ind = 2*i # skip over space allowed for color bars\n", " col_ind = j\n", "\n", " print(\"ROW/COL: \", row_ind, col_ind)\n", " ax = fig.add_subplot(spec[row_ind,col_ind])\n", " cspec = spec[row_ind+1,col_ind]\n", " caxis=None\n", "\n", " plot_ortho(data,s1.costheta,fig,ax,caxis, hwidth=hwidths[i][j], gridstyle=styles[i][j], \n", " gridwidth=gwidths[i][j], nyz=nyzi, colormap=cmaps[i][j], \n", " plot_grid=pgrids[i][j], latcen=latcens[i][j], loncen= loncens[i][j],\n", " pole_style=pstyle[i][j], nlats = nlats[i][j],scale_type=scale_types[i][j])\n", " ptitle=names[i][j]+\" (r_index = \"+str(lv[i][j])+\")\"\n", " ax.set_title(ptitle)\n", "\n", "\n", "# You can save the plot as a figure\n", "#plt.savefig('flows.pdf')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "VIII. Spherical Harmonic Spectra\n", "===================\n", "\n", "**Summary:** Spherical Harmonic Spectra sampled at discrete radii. \n", "\n", "**Subdirectory:** Shell_Spectra\n", "\n", "**main_input prefix:** shellspectra\n", "\n", "**Python Classes:** \n", "\n", "* Shell_Spectra : Complete data structure associated with Shell_Spectra outputs.\n", "* PowerSpectrum : Reduced data structure -- contains power spectrum of velocity and/or magnetic fields only.\n", "\n", "**Additional Namelist Variables:** \n", "\n", "* shellspectra_levels (indicial) : indices along radial grid at which to output spectra.\n", "\n", "* shellspectra_levels_nrm (normalized) : normalized radial grid coordinates at which to output spectra.\n", "\n", "\n", "The shell-spectra output type allows us to examine the spherical harmonic decomposition of output variables at discrete radii.\n", "\n", "Examining the *main_input* file, we see that the following output values have been denoted for the Shell Spectra (see *rayleigh_output_variables.pdf* for mathematical formulae):\n", "\n", "\n", "| Menu Code | Description |\n", "|------------|-------------|\n", "| 1 | Radial Velocity |\n", "| 2 | Theta Velocity |\n", "| 3 | Phi Velocity |\n", "\n", "\n", "\n", "Spherical harmonic spectra can be read into Python using either the **Shell_Spectra** or **PowerSpectrum** classes. \n", "\n", "The **Shell_Spectra** class provides the full complex spectra, as a function of degree ell and azimuthal order m, for each specified output variable. It possesses an attribute named *lpower* that contains the associated power for each variable, along with its m=0 contributions separated and removed.\n", "\n", "The **Power_Spectrum** class can be used to read a Shell_Spectra file and quickly generate a velocity or magnetic-field power spectrum. For this class to work correctly, your file must contain all three components of either the velocity or magnetic field. Other variables are ignored (use Shell_Spectrum's lpower for those).\n", "\n", "We illustrate how to use these two classes below. As usual, we call the help() function to display the docstrings that describe the different data structures embodied by each class." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "from matplotlib import ticker\n", "import numpy\n", "from rayleigh_diagnostics import Shell_Spectra, Power_Spectrum\n", "istring = '00040000'\n", "\n", "\n", "tind = 0\n", "rind = 0\n", "#help(ss)\n", "\n", "vpower = Power_Spectrum(istring)\n", "help(vpower)\n", "power = vpower.power\n", "\n", "fig, ax = plt.subplots(nrows=3, figsize=(6,6))\n", "ax[0].plot(power[:,rind,tind,0])\n", "ax[0].set_xlabel(r'Degree $\\ell$')\n", "ax[0].set_title('Velocity Power (total)')\n", "\n", "\n", "ax[1].plot(power[:,rind,tind,1])\n", "ax[1].set_xlabel(r'Degree $\\ell$')\n", "ax[1].set_title('Velocity Power (m=0)')\n", "\n", "ax[2].plot(power[:,rind,tind,2])\n", "ax[2].set_xlabel(r'Degree $\\ell$')\n", "ax[2].set_title('Velocity Power ( total - {m=0} )')\n", "\n", "plt.tight_layout()\n", "plt.show()\n", "\n", "fig, ax = plt.subplots()\n", "ss = Shell_Spectra(istring)\n", "help(ss)\n", "mmax = ss.mmax\n", "lmax = ss.lmax\n", "power_spectrum = numpy.zeros((lmax+1,mmax+1),dtype='float64')\n", "\n", "for i in range(1,4): # i takes on values 1,2,3\n", " qind=ss.lut[i]\n", " complex_spectrum = ss.vals[:,:,rind,qind,tind]\n", " power_spectrum = power_spectrum+numpy.real(complex_spectrum)**2 + numpy.imag(complex_spectrum)**2\n", "\n", "power_spectrum = numpy.transpose(power_spectrum)\n", "\n", "tiny = 1e-6\n", "img=ax.imshow(numpy.log10(power_spectrum+tiny), origin='lower')\n", "ax.set_ylabel('Azimuthal Wavenumber m')\n", "ax.set_xlabel(r'Degree $\\ell$')\n", "ax.set_title('Velocity Power Spectrum')\n", "\n", "#colorbar ...\n", "cbar = plt.colorbar(img) # ,shrink=0.5, aspect = 15)\n", "cbar.set_label('Log Power')\n", " \n", "tick_locator = ticker.MaxNLocator(nbins=5)\n", "cbar.locator = tick_locator\n", "cbar.update_ticks()\n", "cbar.ax.tick_params() #font size for the ticks\n", "\n", "\n", "plt.show()\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "IX. Point Probes\n", "============\n", "\n", "**Summary:** Point-wise sampling of desired output variables.\n", "\n", "**Subdirectory:** Point_Probes\n", "\n", "**main_input prefix:** point_probe\n", "\n", "**Python Class:** Point_Probes \n", "\n", "\n", "**Additional Namelist Variables:** \n", "\n", "* point_probe_r : radial indices for point-probe output\n", "\n", "* point_probe_theta : theta indices for point-probe output\n", "\n", "* point_probe_phi : phi indices for point-probe output\n", "\n", "* point_probe_r_nrm : normalized radial coordinates for point-probe output\n", "\n", "* point_probe_theta_nrm : normalized theta coordinates for point-probe output\n", "\n", "* point_probe_phi_nrm : normalized phi coordinates for point-probe output\n", "\n", "* point_probe_cache_size : number of time-samples to save before accessing the disk \n", "\n", "\n", "Point-probes allow us to sample a simulation at an arbitrary set of points. This output type serves two purposes:\n", "1. It provides an analog to laboratory measurements where slicing and averaging are difficult, but taking high-time-cadence using (for example) thermistors is common-practice.\n", "2. It provides an alternative method of slicing a model ( for when equatorial, meridional, or shell slices do yield the desired result).\n", "\n", "IX.1 Specifying Point-Probe Locations\n", "---------\n", "\n", "Point-probe locations are indicated by specifying a grid. The user does not supply a set of ordered coordinates (r,theta,phi). Instead, the user specifies nodes on the grid using the namelist variables described above. Examples follow.\n", "\n", "**Example 1: 4-point Coarse Grid **\n", "\n", "point_probe_r_nrm = 0.25, 0.5 \n", "point_probe_theta_nrm = 0.5 \n", "point_probe_phi_nrm = 0.2, 0.8\n", "\n", "This example would produce point probes at the four coordinates { (0.25, 0.5, 0.2), (0.25, 0.5, 0.8), (0.5, 0.5, 0.2), (0.5,0.5,0.8) } (r,theta,phi; normalized coordinates).\n", "\n", "**Example 2: \"Ring\" in Phi **\n", "\n", "point_probe_r_nrm = 0.5 \n", "point_probe_theta_nrm = 0.5 \n", "point_probe_phi_nrm = 0.0, -1.0\n", "\n", "This example describes a ring in longitude, sampled at mid-shell, in the equatorial plane. We have made use of the positional range feature here by indicating normalized phi coordinates of 0.0, -1.0. Rayleigh intreprets this as an instruction to sample all phi coordinates.\n", "\n", "** Example 3: 2-D Surface in (r,phi) **\n", "\n", "point_probe_r_nrm = 0, -1.0 \n", "point_probe_theta_nrm = 0.25 \n", "point_probe_phi_nrm = 0, -1.0\n", "\n", "This example uses the positional range feature along with normalized coordinates to generate a 2-D slice in r-phi at theta = 45 degrees (theta_nrm = 0.25). Using the syntax 0,-1.0 instructs *Rayleigh* to grab all r and phi coordinates.\n", "\n", "** Example 4: 3-D Meridional \"Wedges\" **\n", "\n", "point_probe_r_nrm = 0.0, -1.0 \n", "point_probe_theta_nrm = 0.0, -1.0 \n", "point_probe_phi_nrm = 0.20, -0.30, 0.7, -0.8\n", "\n", "This example generates two 3-D wedges described by all r,theta points and all longitudes in the ranges [72 deg, 108 deg] and [252 deg, 288 deg].\n", "\n", "IX.2 Point-Probe Caching\n", "-----------------------------\n", "\n", "When performing sparse spatial sampling using point-probes, it may be desireable to output with a high-time cadence. As this may cause disk-access patterns characterized by frequent, small writes, the point-probes are programmed with a caching feature. This feature is activated by specifing the **point_probe_cache_size** variable in the output namelist.\n", "\n", "This variable determines how many time-samples are saved in memory before a write is performed. Its default value is 1, which means that the disk is accessed with a frequency of **point_probe_frequency**. If the cache size is set to 10 (say), then samples are still peformed at **point_probe_frequency** but they are only written to disk after 10 have been collected in memory. \n", "\n", "**NOTE:** Be sure that **point_probe_cache_size** divides evenly into **point_probe_nrec**.\n", "\n", "\n", "IX.3 Example: Force-Balance with Point Probes\n", "-------------------------------------------------------\n", "\n", "Our example input file specifies a coarse, six-point grid. Examining the *main_input* file, we see that all variables necessary to examine the force balance in each direction have been specified. (see *rayleigh_output_variables.pdf* for mathematical formulae):\n", "\n", "\n", "| Menu Code | Description |\n", "|------------|-------------|\n", "| 1 | Radial Velocity |\n", "| 2 | Theta Velocity |\n", "| 3 | Phi Velocity |\n", "| 1201 | Radial Advection (v dot grad v) |\n", "| 1202 | Theta Advection |\n", "| 1203 | Phi Advection |\n", "| 1216 | Buoyancy Force (ell=0 component subtracted) |\n", "| 1219 | Radial Coriolis Force |\n", "| 1220 | Theta Coriolis Force |\n", "| 1221 | Phi Coriolis Force |\n", "| 1228 | Radial Viscous Force |\n", "| 1229 | Theta Viscous Force |\n", "| 1230 | Phi Viscous Force|\n", "\n", "\n", "**Note that the pressure force appears to be missing.** This is not an oversight. The diagnostic nature of the Pressure equation in incompressible/anelastic models, coupled with the second-order Crank-Nicolson time-stepping scheme, means that the pressure field can exhibit an even/odd sawtoothing in time. The *effective* pressure force (as implemented through the Crank-Nicolson scheme) is always a weighted average over two time steps **and is always well-resolved in time**. \n", "\n", "When sampling at regular intervals as we have here, if we directly sample the pressure force, we will sample either the high or low end of the sawtooth envelope, and the force balance will be off by a large factor. The easiest fix is to output the velocity field and compute its time derivative. This, in tandem with the sum of all other forces, can be used to calculate the effective pressure as a post-processing step. The (undesireable) alternative is to output once every time step and compute the effective pressure using the Crank-Nicolson weighting. \n", "\n", "We demonstrate how to compute the effective pressure force via post-processing in the example below." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from rayleigh_diagnostics import Point_Probes, build_file_list\n", "import numpy\n", "from matplotlib import pyplot as plt\n", "\n", "#Decide which direction you want to look at (set direction = {radial,theta, or phi})\n", "#This is used to determine the correct quantity codes below\n", "radial = 0\n", "theta = 1\n", "phi = 2\n", "direction=radial\n", "# Build a list of all files ranging from iteration 0 million to 1 million\n", "files = build_file_list(0,1000000,path='Point_Probes')\n", "nfiles = len(files)-1\n", "\n", "\n", "for i in range(nfiles):\n", " pp = Point_Probes(files[i],path='')\n", " if (i == 0):\n", " nphi = pp.nphi\n", " ntheta = pp.ntheta\n", " nr = pp.nr\n", " nq = pp.nq\n", " niter = pp.niter\n", " vals=numpy.zeros( (nphi,ntheta,nr,nq,niter*nfiles),dtype='float64')\n", " time=numpy.zeros(niter*nfiles,dtype='float64')\n", " vals[:,:,:,:, i*niter:(i+1)*niter] = pp.vals\n", " time[i*niter:(i+1)*niter]=pp.time\n", "istring='00040000' # iteration to examine\n", "help(pp)\n", "##################################################\n", "# We choose the coordinate indices **within**\n", "# the Point-Probe array that we want to examine\n", "# These indices start at zero and run to n_i-1\n", "# where n_i is the number of points sampled in \n", "# the ith direction\n", "\n", "# Use help(pp) after loading the Point-Probe file\n", "# to see the Point-Probe class structure\n", "\n", "pind = 0 # phi-index to examine\n", "rind = 0 # r-index to examine\n", "tind = 0 # theta-index to examine\n", "\n", "\n", "pp = Point_Probes(istring)\n", "lut = pp.lut\n", "\n", "nt = pp.niter\n", "\n", "\n", "#######################################################################\n", "# Grab velocity from the point probe data\n", "u = vals[pind,0,rind,pp.lut[1+direction],:]\n", "dt=time[1]-time[0]\n", "\n", "\n", "###########################################################################\n", "# Use numpy to compute time-derivative of u\n", "# (necessary to compute a smooth effective pressure without outputing every timestep)\n", "\n", "#Depending on Numpy version, gradient function takes either time (array) or dt (scalar)\n", "try:\n", " dudt = numpy.gradient(u,time)\n", "except:\n", " dt = time[1]-time[0] # Assumed to be constant...\n", " dudt = numpy.gradient(u,dt) \n", "\n", "\n", "\n", "################################################################\n", "# Forces (modulo pressure)\n", "# Note the minus sign for advection. Advective terms are output as u dot grad u, not -u dot grad u\n", "advec = -vals[ pind, tind, rind, lut[1201 + direction], :] \n", "cor = vals[ pind, tind, rind, lut[1219 + direction], :]\n", "visc = vals[ pind, tind, rind, lut[1228 + direction], :]\n", "forces = visc+cor+advec\n", "if (direction == radial):\n", " buoy = vals[ pind, tind, rind, lut[1216], :]\n", " forces = forces+buoy\n", "\n", "\n", "############################################3\n", "# Construct effective pressure force\n", "pres = dudt-forces\n", "forces = forces+pres\n", "############################################################\n", "# Set up the plot\n", "yfsize='xx-large' # size of y-axis label\n", "\n", "ustrings = [r'u_r', r'u_\\theta', r'u_\\phi']\n", "ustring=ustrings[direction]\n", "dstring = r'$\\frac{\\partial '+ustring+'}{\\partial t}$'\n", "fstrings = [r'$\\Sigma\\,F_r$' , r'$\\Sigma\\,F_\\theta$' , r'$\\Sigma\\,F_\\phi$' ]\n", "fstring = fstrings[direction]\n", "diff_string = dstring+' - '+fstring\n", "\n", "pstring = 'pressure'\n", "cstring = 'coriolis'\n", "vstring = 'viscous'\n", "bstring = 'buoyancy'\n", "fig, axes = plt.subplots(nrows=2, figsize=(7*2.54, 9.6))\n", "ax0 = axes[0]\n", "ax1 = axes[1]\n", "\n", "\n", "########################################\n", "# Upper: dur/dt and F_total\n", "#mpl.rc('xtick', labelsize=20) --- still trying to understand xtick label size etc.\n", "#mpl.rc('ytick', labelsize=20)\n", "\n", "ax0.plot(time,forces, label = fstring)\n", "ax0.plot(time,pres,label=pstring)\n", "ax0.plot(time,cor,label=cstring)\n", "ax0.plot(time,visc,label=vstring)\n", "if (direction == radial):\n", " ax0.plot(time,buoy,label=bstring)\n", "ax0.set_xlabel('Time', size=yfsize)\n", "\n", "ax0.set_ylabel('Acceleration', size=yfsize)\n", "ax0.set_title('Equilibration Phase',size=yfsize)\n", "ax0.set_xlim([0,0.1])\n", "leg0 = ax0.legend(loc='upper right', shadow=True, ncol = 1, fontsize=yfsize) \n", "\n", "##########################################\n", "# Lower: Numpy Gradient Approach\n", "ax1.plot(time,forces,label=fstring)\n", "ax1.plot(time,pres,label=pstring)\n", "ax1.plot(time,cor,label=cstring)\n", "ax1.plot(time,visc,label=vstring)\n", "if (direction == radial):\n", " ax1.plot(time,buoy,label=bstring)\n", "ax1.set_title('Late Evolution',size=yfsize)\n", "ax1.set_xlabel('Time',size=yfsize)\n", "ax1.set_ylabel('Acceleration', size =yfsize)\n", "ax1.set_xlim([0.2,4])\n", "leg1 = ax1.legend(loc='upper right', shadow=True, ncol = 1, fontsize=yfsize)\n", "\n", "\n", "plt.tight_layout()\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "X. Modal Outputs\n", "========\n", "\n", "\n", "**Summary:** Spherical Harmonic Spectral Coefficients sampled at discrete radii and degree ell. \n", "\n", "**Subdirectory:** SPH_Modes\n", "\n", "**main_input prefix:** sph_mode\n", "\n", "**Python Classes:** SPH_Modes\n", "\n", "\n", "\n", "**Additional Namelist Variables:** \n", "\n", "* sph_mode_levels (indicial) : indices along radial grid at which to output spectral coefficients.\n", "\n", "* sph_mode_levels_nrm (normalized) : normalized radial grid coordinates at which to output spectral coefficients.\n", "\n", "* sph_mode_ell : Comma-separated list of spherical harmonic degree ell to output.\n", "\n", "\n", "The Modal output type allows us to output a restricted set of complex spherical harmonic coefficients at discrete radii. For each specified ell-value, all associated azimuthal wavenumbers are output.\n", "\n", "This output can be useful for storing high-time-cadence spectral data for a few select modes. In the example below, we illustrate how to read in this output type, and we plot the temporal variation of the real and complex components of radial velocity for mode ell = 4, m = 4.\n", "\n", "\n", "Examining the *main_input* file, we see that the following output values have been denoted for the Shell Spectra (see *rayleigh_output_variables.pdf* for mathematical formulae):\n", "\n", "\n", "| Menu Code | Description |\n", "|------------|-------------|\n", "| 1 | Radial Velocity |\n", "| 2 | Theta Velocity |\n", "| 3 | Phi Velocity |\n", "\n", "We also see that ell=2,4,8 have been selected in the *main_input* file, leading to power at the following modes:\n", "\n", "|ell-value | m-values |\n", "|----------|---------------|\n", "| 2 | 0,1,2 |\n", "| 4 | 0,1,2,3,4 |\n", "| 8 | 0,1,2,3,4,5,6,7,8 |\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from rayleigh_diagnostics import SPH_Modes, build_file_list\n", "import matplotlib.pyplot as plt\n", "import numpy\n", "\n", "qind = 1 # Radial velocity\n", "rind = 0 # First radius stored in file\n", "\n", "\n", "files = build_file_list(0,1000000,path='SPH_Modes')\n", "nfiles = len(files)\n", "for i in range(nfiles):\n", " spm = SPH_Modes(files[i],path='')\n", " if (i == 0):\n", " nell = spm.nell\n", " nr = spm.nr\n", " nq = spm.nq\n", " niter = spm.niter\n", " lvals = spm.lvals\n", " max_ell = numpy.max(lvals)\n", " nt = niter*nfiles\n", " vr = spm.lut[qind]\n", " vals=numpy.zeros( (max_ell+1,nell,nr,nq,nt),dtype='complex64')\n", " time=numpy.zeros(nt,dtype='float64')\n", " vals[:,:,:,:, i*niter:(i+1)*niter] = spm.vals\n", " time[i*niter:(i+1)*niter]=spm.time\n", "help(spm)\n", "#####################################################3\n", "# Print some information regarding the bookkeeping\n", "print('...........')\n", "print(' Contents')\n", "print(' nr = ', nr)\n", "print(' nq = ', nq)\n", "print(' nt = ', nt)\n", "for i in range(nell):\n", " lstring=str(lvals[i])\n", " estring = 'Ell='+lstring+' Complex Amplitude : vals[0:'+lstring+','+str(i)+',0:nr-1,0:nq-1,0:nt-1]'\n", " print(estring)\n", "print(' First dimension is m-value.')\n", "print('...........')\n", "\n", "######################################\n", "# Create a plot of the ell=4, m=4 real and imaginary amplitudes\n", "radius = spm.radius[rind]\n", "lfour_mfour = vals[4,1,rind,vr,:]\n", "fig, ax = plt.subplots()\n", "ax.plot(time,numpy.real(lfour_mfour), label='real part')\n", "ax.plot(time,numpy.imag(lfour_mfour), label='complex part')\n", "ax.set_xlabel('Time')\n", "ax.set_ylabel('Amplitude')\n", "rstring = \"{0:4.2f}\".format(radius)\n", "ax.set_title(r'Radial Velocity ( $\\ell=4$ , m=4, radius='+rstring+' ) ')\n", "ax.legend(shadow=True)\n", "ax.set_xlim([0.5,4.0])\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.5" } }, "nbformat": 4, "nbformat_minor": 2 }