Skip to content

Commit

Permalink
Handle old functions and update examples
Browse files Browse the repository at this point in the history
  • Loading branch information
nabobalis committed Jul 24, 2024
1 parent a9511eb commit 1025051
Show file tree
Hide file tree
Showing 41 changed files with 297 additions and 365 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -265,3 +265,4 @@ package.json
# Repo specific
examples/using_sunkit_magex_pfss/aia_map.fits
docs/sg_execution_times.rst
aia_map.fits
22 changes: 22 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
1.0.0 (2024-05-31)
==================

This is the first release and aims to keep the API the same from `pfsspy` to
`sunkit_magex`. The main difference is that you will need to replace the
import like so:

.. code-block:: python
# Before
import pfsspy
from pfsspy import tracing
# After
from sunkit_magex import pfss as pfsspy
from sunkit_magex.pfss import tracing
The main changes from the previous release of `pfsspy` are as follows:

* The ``GongSynopticMap`` class has moved into `sunpy`, note that the new
class in ``sunpy`` is slightly different in that it does not modify the
header.
1 change: 1 addition & 0 deletions changelog/63.breaking.1.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Made streamtracer a hard dependency of sunkit-magex.
6 changes: 6 additions & 0 deletions changelog/63.breaking.2.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Deprecated the following pfss utils:

- pfss.utils.fix_hmi_meta
- pfss.utils.load_adapt

These functions are no longer needed and will be removed.
1 change: 1 addition & 0 deletions changelog/63.breaking.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Increased the minimum required version of ``sunpy`` to v6.0.0.
34 changes: 34 additions & 0 deletions changelog/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
=========
Changelog
=========

.. note::

This README was adapted from the pytest changelog readme under the terms of the MIT licence.

This directory contains "news fragments" which are short files that contain a small **ReST**-formatted text that will be added to the next ``CHANGELOG``.

The ``CHANGELOG`` will be read by users, so this description should be aimed at SunPy users instead of describing internal changes which are only relevant to the developers.

Make sure to use full sentences with correct case and punctuation, for example::

Add support for Helioprojective coordinates in `sunpy.coordinates.frames`.

Please try to use Sphinx intersphinx using backticks.

Each file should be named like ``<PULL REQUEST>.<TYPE>[.<COUNTER>].rst``, where ``<PULL REQUEST>`` is a pull request number, ``COUNTER`` is an optional number if a PR needs multiple entries with the same type and ``<TYPE>`` is one of:

* ``breaking``: A change which requires users to change code and is not backwards compatible. (Not to be used for removal of deprecated features.)
* ``feature``: New user facing features and any new behavior.
* ``bugfix``: Fixes a reported bug.
* ``doc``: Documentation addition or improvement, like rewording an entire session or adding missing docs.
* ``deprecation``: Feature deprecation
* ``removal``: Feature removal.
* ``trivial``: A change which has no user facing effect or is tiny change.

So for example: ``123.feature.rst``, ``456.bugfix.rst``.

If you are unsure what pull request type to use, don't hesitate to ask in your PR.

Note that the ``towncrier`` tool will automatically reflow your text, so it will work best if you stick to a single paragraph, but multiple sentences and links are OK and encouraged.
You can install ``towncrier`` and then run ``towncrier --draft`` if you want to get a preview of how your change will look in the final release notes.
26 changes: 4 additions & 22 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,7 @@
Full Changelog
**************

1.0.0 (2024-05-31)
==================

This is the first release and aims to keep the API the same from `pfsspy` to
`sunkit_magex`. The main difference is that you will need to replace the
import like so:

.. code-block:: python
# Before
import pfsspy
from pfsspy import tracing
# After
from sunkit_magex import pfss as pfsspy
from sunkit_magex.pfss import tracing
The main changes from the previous release of `pfsspy` are as follows:

* The ``GongSynopticMap`` class has moved into `sunpy`, note that the new
class in ``sunpy`` is slightly different in that it does not modify the
header.
.. changelog::
:towncrier: ../
:towncrier-skip-if-empty:
:changelog_file: ../CHANGELOG.rst
1 change: 1 addition & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"sphinx_automodapi.automodapi",
"sphinx_automodapi.smart_resolver",
'sphinx_gallery.gen_gallery',
'sphinx_changelog',
]

# Add any paths that contain templates here, relative to this directory.
Expand Down
4 changes: 2 additions & 2 deletions docs/installing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ Alternatively ``sunkit-magex`` can be installed from PyPI using:
pip install sunkit-magex
This will install sunkit_magex and all of its dependencies.
In addition to the core dependencies, there are optional dependencies (numba, streamtracer) that can improve code performance.
These can be installed with
In addition to the core dependencies, numba is an optional dependency that can improve code performance.
This can be installed with:

.. code:: shell
Expand Down
5 changes: 2 additions & 3 deletions docs/performance.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ To enable this simply `install numba`_ and use `sunkit_magex.pfss` as normal.
Streamline tracing
==================

`sunkit_magex.pfss` has two streamline tracers: a pure python `sunkit_magex.pfss.tracing.PythonTracer` and a complied tracer `sunkit_magex.pfss.tracing.FortranTracer`.
The compiled version is significantly faster, using the `streamtracer`_ package.
`sunkit_magex.pfss` uses a complied tracer `sunkit_magex.pfss.tracing.PerformanceTracer` using the `streamtracer`_ package.

.. _numba: https://numba.pydata.org
.. _install numba: http://numba.pydata.org/numba-doc/latest/user/installing.html
.. _streamtracer: https://github.com/sunpy/streamtracer
.. _streamtracer: https://docs.sunpy.org/projects/streamtracer/en/stable/
3 changes: 0 additions & 3 deletions examples/finding_data/README.rst

This file was deleted.

65 changes: 0 additions & 65 deletions examples/finding_data/adapt_map_sequence.py

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
r"""
Magnetic field grid
Magnetic Field Grid
===================
A plot of the grid corners which the magnetic field values are taken from
Expand Down
49 changes: 23 additions & 26 deletions examples/internals/tracer_performance.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""
Tracer performance
Tracer Performance
==================
Comparing the performance of Python and Rust tracers.
Comparing the performance of the Python and Compiled tracers.
"""
import timeit

Expand All @@ -19,72 +19,69 @@
###############################################################################
# Create a dipole map.

def dipole_Br(r, theta):
return 2 * np.sin(theta) / r**3


ntheta = 180
nphi = 360
nr = 50
rss = 2.5

phi = np.linspace(0, 2 * np.pi, nphi)
theta = np.linspace(-np.pi / 2, np.pi / 2, ntheta)
theta, phi = np.meshgrid(theta, phi)

def dipole_Br(r, theta):
return 2 * np.sin(theta) / r**3


br = dipole_Br(1, theta)
br = sunpy.map.Map(br.T, pfss.utils.carr_cea_wcs_header('2010-01-01', br.shape))
pfss_input = pfss.Input(br, nr, rss)
pfss_output = pfss.pfss(pfss_input)
print('Computed PFSS solution')

###############################################################################
# Trace some field lines.

seed0 = np.atleast_2d(np.array([1, 1, 0]))
tracers = [pfss.tracing.PythonTracer(),
pfss.tracing.FortranTracer()]
tracers = [
pfss.tracing.PythonTracer(),
pfss.tracing.PerformanceTracer(),
]
nseeds = 2**np.arange(14)
times = [[], []]
times = [[] for _ in tracers]

for nseed in nseeds:
print(nseed)
seeds = np.repeat(seed0, nseed, axis=0)
r, lat, lon = pfss.coords.cart2sph(seeds[:, 0], seeds[:, 1], seeds[:, 2])
r = r * astropy.constants.R_sun
lat = (lat - np.pi / 2) * u.rad
lon = lon * u.rad
seeds = astropy.coordinates.SkyCoord(lon, lat, r, frame=pfss_output.coordinate_frame)

for i, tracer in enumerate(tracers):
# Skip the Python tracer for large numbers of seeds.
# It is too slow.
if nseed > 64 and i == 0:
continue

t = timeit.timeit(lambda: tracer.trace(seeds, pfss_output), number=1)
times[i].append(t)

###############################################################################
# Plot the results.

fig, ax = plt.subplots()
ax.scatter(nseeds[1:len(times[0])], times[0][1:], label='python')
ax.scatter(nseeds[1:], times[1][1:], label='compiled')

pydt = (times[0][4] - times[0][3]) / (nseeds[4] - nseeds[3])
ax.plot([1, 1e5], [pydt, 1e5 * pydt])

fort0 = times[1][1]
fordt = (times[1][-1] - times[1][-2]) / (nseeds[-1] - nseeds[-2])
ax.plot(np.logspace(0, 5, 100), fort0 + fordt * np.logspace(0, 5, 100))
for i, tracer in enumerate(tracers):
if i == 0:
ax.scatter(nseeds[1:len(times[i])], times[i][1:], label=tracer.__class__.__name__)
pydt = (times[0][4] - times[0][3]) / (nseeds[4] - nseeds[3])
ax.plot([1, 1e5], [pydt, 1e5 * pydt])
else:
ax.scatter(nseeds[1:], times[i][1:], label=tracer.__class__.__name__)
t0 = times[i][1]
dt = (times[i][-1] - times[i][-2]) / (nseeds[-1] - nseeds[-2])
ax.plot(np.logspace(0, 5, 100), t0 + dt * np.logspace(0, 5, 100))

ax.set_xscale('log')
ax.set_yscale('log')

ax.set_xlabel('Number of seeds')
ax.set_ylabel('Seconds')

ax.axvline(180 * 360, color='k', linestyle='--', label='180x360 seed points')

ax.legend()

plt.show()
3 changes: 0 additions & 3 deletions examples/testing/helpers.py → examples/testing/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import sunkit_magex.pfss.utils

result_dir = (pathlib.Path(__file__) / '..' / 'results').resolve()

pi = np.pi * u.rad


Expand Down Expand Up @@ -83,8 +82,6 @@ def open_flux_numeric(l, m, zss, nrho):
return np.sum(np.abs(br)) * (4 * np.pi) / nphi / ns


######################
# Field line helpers #
@u.quantity_input
def fr(r: u.m, rss: u.m, l):
rho = r / rss
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@
"""
import matplotlib.pyplot as plt
import numpy as np
from _helpers import pffspy_output, phi_fline_coords, theta_fline_coords

import astropy.constants as const
import astropy.units as u
from astropy.coordinates import SkyCoord
from astropy.visualization import quantity_support

from examples.testing.helpers import pffspy_output, phi_fline_coords, theta_fline_coords
from sunkit_magex import pfss

quantity_support()
Expand Down Expand Up @@ -48,7 +48,7 @@
dthetas = []
print(f'Tracing {step_size}...')
# Trace
tracer = pfss.tracing.FortranTracer(step_size=step_size)
tracer = pfss.tracing.PerformanceTracer(step_size=step_size)
flines = tracer.trace(seeds, pfss_out)
# Set a mask of open field lines
mask = flines.connectivities.astype(bool).reshape(theta.shape)
Expand All @@ -73,7 +73,6 @@

fig, axs = plt.subplots(nrows=2, sharex=True, sharey=True)


def plot_map(field, ax, label, title):
kwargs = dict(cmap='RdBu', vmin=-0.5, vmax=0.5, shading='nearest', edgecolors='face')
im = ax.pcolormesh(phi.to_value(u.deg), np.sin(theta).value,
Expand All @@ -85,10 +84,10 @@ def plot_map(field, ax, label, title):


plot_map(dtheta.to_value(u.deg), axs[0],
r'$\theta_{sunkit_magex.pfss} - \theta_{analytic}$ (deg)',
r'$\theta_{pfss} - \theta_{analytic}$ (deg)',
'Error in latitude')
plot_map(dphi.to_value(u.deg), axs[1],
r'$\phi_{sunkit_magex.pfss} - \phi_{analytic}$ (deg)',
r'$\phi_{pfss} - \phi_{analytic}$ (deg)',
'Error in longitude')

ax = axs[1]
Expand Down
Loading

0 comments on commit 1025051

Please sign in to comment.