"""
Saving and loading results
==========================

**spm1d** 0.5 introduces results saving and loading in HDF5 format via
``spm1d.io.save`` and ``spm1d.io.load``. In version 0.4 saving was
possible only through custom pickling, but as of v0.5 saving and loading
are officially supported. Results may be saved before or after inference.
The saved files can be easily read in MATLAB, R and any other language
that supports HDF5.
"""

import os, tempfile
# sphinx_gallery_thumbnail_path = '_static/thumbs/saving.png'
import numpy as np
from matplotlib import pyplot as plt
import spm1d
import jikudata as jd

dataset = jd.PlantarArchAngle()     # 1D dataset:  two conditions, ten participants
y, A    = dataset.y, dataset.x
y0, y1  = y[A == 0], y[A == 1]
ti      = spm1d.stats.ttest_paired( y1, y0 ).inference( 0.05 )

fpath   = os.path.join( tempfile.mkdtemp(), 'result.h5' )   # a temporary file
spm1d.io.save( fpath, ti )                                   # save
ti1     = spm1d.io.load( fpath )                             # load
print( 'loaded result equals the original:', ti1 == ti )

# %%
#  |
#  |
#
#  The figure below simply emphasizes that the saved and
#  loaded results are identical.
plt.rc( 'font', family='sans-serif' )
plt.rc( 'font', **{'sans-serif': ['Helvetica Neue', 'Helvetica', 'Arial', 'Liberation Sans', 'DejaVu Sans']} )
fig = plt.figure( figsize=(8, 6) )
ax0 = fig.add_axes( [0.02, 0.50, 0.40, 0.40] )
ax1 = fig.add_axes( [0.58, 0.50, 0.40, 0.40] )
for ax, t in zip( (ax0, ax1), (ti, ti1) ):
    t.plot( ax=ax )
    ax.set_xticks( [] );  ax.set_yticks( [] )
    ax.set_ylabel( '' )
fig.text( 0.22, 0.97, 'result', ha='center', va='top', fontsize=22 )
fig.text( 0.78, 0.97, 'loaded result', ha='center', va='top', fontsize=22 )
fig.text( 0.50, 0.70, '→', ha='center', va='center', fontsize=40, family='DejaVu Sans' )   # DejaVu Sans:  bundled with matplotlib, and has the arrow glyph
fig.text( 0.50, 0.32, 'result.h5', ha='center', va='center', fontsize=26, family='monospace',
          bbox=dict( boxstyle='round,pad=0.6', facecolor='#e6f4f8', edgecolor='#0e6e84' ) )
fig.text( 0.50, 0.12, 'spm1d.io.save   →   spm1d.io.load', ha='center', va='center', fontsize=20, family='monospace' )

# %%
#  |
#  |
#
#  Results before inference can be saved and loaded in the same way:
fpath1 = os.path.join( os.path.dirname( fpath ), 'result_before_inference.h5' )
spm1d.io.save( fpath1, spm1d.stats.ttest_paired( y1, y0 ) )           # a result before inference
print( spm1d.io.load( fpath1 ) )
