Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • km3py/jppy
  • hwarnhofer/jppy_hannes
2 results
Show changes
Commits on Source (107)
Showing with 1705 additions and 97 deletions
*.so
MANIFEST
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*.egg-info
.DS_Store
*.pyxbldc
# C extensions
*.so
# Distribution / packaging
build/
venv/
dist/
_build
_generate
build
pip-wheel-metadata
*.egg-info
*.egg
# Version info
src/jppy/version.py
# Temporary folders and meta-data
tmp/
# Data folders
pdfs/
variables:
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
# Pip's cache doesn't store the python packages
# https://pip.pypa.io/en/stable/reference/pip_install/#caching
#
# If you want to also cache the installed packages, you have to install
# them in a virtualenv and cache it as well.
stages:
- init
- build
- test
- doc
- release
.virtualenv_template: &virtualenv_definition |
./scripts/create_venv.sh
source venv/bin/activate
python3 -m pip install .
.test_template: &test_definition |
source venv/bin/activate
pip install -U pytest
pytest
.junit_template: &junit_definition
artifacts:
reports:
junit: "reports/junit*.xml"
download-pdfs:
image: docker.km3net.de/base/ci-helper:1
stage: init
script:
- ./scripts/get_pdfs.sh
artifacts:
paths:
- pdfs
cache:
paths:
- pdfs
key: "init-$CI_COMMIT_REF_SLUG"
build-jpp-master-py36:
image: docker.km3net.de/base/python:3.6
stage: build
script:
- *virtualenv_definition
cache:
paths:
- venv
key: "py36-$CI_COMMIT_REF_SLUG"
artifacts:
paths:
- venv
build-jpp-master-py37:
image: docker.km3net.de/base/python:3.7
stage: build
script:
- *virtualenv_definition
cache:
paths:
- venv
key: "py37-$CI_COMMIT_REF_SLUG"
artifacts:
paths:
- venv
build-jpp-master-py38:
image: docker.km3net.de/base/python:3.8
stage: build
script:
- *virtualenv_definition
cache:
paths:
- venv
key: "py38-$CI_COMMIT_REF_SLUG"
artifacts:
paths:
- venv
test-jpp-master-py36:
image: docker.km3net.de/base/python:3.6
stage: test
script:
- *test_definition
dependencies:
- build-jpp-master-py36
- download-pdfs
cache: {}
test-jpp-master-py37:
image: docker.km3net.de/base/python:3.7
stage: test
script:
- *test_definition
dependencies:
- build-jpp-master-py37
- download-pdfs
cache: {}
test-jpp-master-py38:
image: docker.km3net.de/base/python:3.8
stage: test
script:
- *test_definition
dependencies:
- build-jpp-master-py38
- download-pdfs
cache: {}
pages:
image: docker.km3net.de/base/python:3.8
stage: doc
script:
- pip install -U sphinx
- cd docs && make clean && make html && cd ..
- mv docs/_build/html public/
- cp -R examples public/
artifacts:
paths:
- public
cache: {}
only:
- tags
- master
pypi:
image: docker.km3net.de/base/python:3.8
stage: release
cache: {}
script:
- pip install -U twine setuptools setuptools_scm
- pip install .
- python setup.py sdist
- twine upload dist/*
only:
- tags
Unreleased changes
------------------
Version 3
---------
3.5.0 / 2022-11-07
~~~~~~~~~~~~~~~~~~
* ``JOscProb`` tools and lots of related functionalities has been added
3.4.1 / 2022-10-17
~~~~~~~~~~~~~~~~~~
* Fixed installation issue on macOS
3.4.0 / 2021-03-31
~~~~~~~~~~~~~~~~~~
* Added access to ``JPDF`` to (``jppy.pdf.JSinglePDF``) which can be used
to access single, or a subset of PDF files
3.3.0 / 2020-03-31
~~~~~~~~~~~~~~~~~~
* Add the ``jppy.npe`` module which provides access to NPE tables in Jpp.
The two new classes are ``JMuonNPE`` and ``JShowerNPE``.
3.2.2 / 2020-03-06
~~~~~~~~~~~~~~~~~~
* Binary wheel release on PyPI for macOS 10.15 and Linux
3.2.1 / 2020-03-05
~~~~~~~~~~~~~~~~~~
* c++17 support removed in favour of macOS compatibility
3.2 / 2020-03-02
~~~~~~~~~~~~~~~~
* shower PDF functionality added (``jppy.pdf.JShowerPDF``)
3.1 / 2020-02-28
~~~~~~~~~~~~~~~~
* removed ROOT dependency. ``jppy`` now only depends on a few Jpp headers
3.0 / 2020-02-27
~~~~~~~~~~~~~~~~
* **Major overhaul!** Dropped all the DAQ readout functionality in favour
of `km3io https://git.km3net.de/km3py/km3io`_
* Introduced the ``jppy.pdf`` module which has a wrapper class ``JMuonPDF``
to access Jpp PDF methods
Version 2
---------
2.1 / 2019-10-06
~~~~~~~~~~~~~~~
* Automatic discovery of libraries for ROOT 5 and 6
2.0 / 2018-12-20
~~~~~~~~~~~~~~~
* Support for Jpp 9+
Version 1
---------
1.6 / 2017-12-04
~~~~~~~~~~~~~~~
* depend on latest jpp trunk (method renaming grrrrr) (find in THRONG)
* fix build script (was broken in 1.5.1, apparently)
1.5.1 / 2017-11-21
~~~~~~~~~~~~~~~~~
* minor bugfixes. jfitreader now works (and has a km3pipe pump)
* DON'T USE
1.5.0 / 2017-11-21
~~~~~~~~~~~~~~~~~
* Add preliminary jfit reader
1.4.0 / 2017-10-19
~~~~~~~~~~~~~~~~~
* Adds timeslice and summary pump (preliminary)
The MIT License (MIT)
Copyright (c) 2020 Tamas Gal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
......@@ -4,44 +4,98 @@ The jppy Python package
.. image:: https://git.km3net.de/km3py/jppy/badges/master/pipeline.svg
:target: https://git.km3net.de/km3py/jppy/pipelines
.. image:: https://git.km3net.de/km3py/jppy/badges/master/coverage.svg
:target: https://km3py.pages.km3net.de/jppy/coverage
.. image:: https://examples.pages.km3net.de/km3badges/docs-latest-brightgreen.svg
.. image:: https://git.km3net.de/examples/km3badges/-/raw/master/docs-latest-brightgreen.svg
:target: https://km3py.pages.km3net.de/jppy
This software provides access to the PDF functionalities in Jpp. It depends on
some Jpp headers (no Jpp compilation needed) and on the ROOT ``TMath`` (a
compiled ROOT installation is needed).
This software provides Python access to functionalities in Jpp, like accessing
PDF and NPE functions.
**Note:** Beware that this package is in the development phase, so the API will
change until version ``1.0.0`` is released!
It currently depends on a few Jpp headers (no Jpp compilation needed), which are
bundled with the package. However, if you want to use another (newer) Jpp version,
make sure the ``$JPP_DIR`` is pointing to the Jpp directory.
Installation
============
Run ``make`` to compile the Python modules::
If you work on the Lyon CC, you can load the ``jpp/master`` module which
contains the latest release of ``jppy``::
module load jpp/master
Before installing manually, make sure the ``$JPP_DIR`` environment variable
is pointing to the Jpp directory otherwise it will use some older Jpp headers
for compilation. Please note that only the headers of Jpp are needed,
it is not necessary to compile the whole Jpp framework!
For the sake of completeness, here is how to do it::
git clone --recursive git@git.km3net.de:common/jpp.git
export JPP_DIR=$(pwd)/jpp
You also need the ``pybind11`` headers and on some Linux also the
``python-dev`` package::
brew install pybind11 # macOS
sudo pacman -S pybind11 # Arch based Linux
sudo apt-get install pybind11 python3-dev # Debian based Linux (e.g. Ubuntu)
The package can then be installed via ``pip``::
pip install jppy
or directly from the Git repository to get the latest stable from the
``master`` branch::
pip install git+https://git.km3net.de/km3py/jppy
make
or from a local clone::
Example
=======
git clone https://git.km3net.de/km3py/jppy
pip install jppy/
Here is an example how to play around with muon PDFs using the ``jppy`` module::
Example - Using PDFs
====================
.. image:: examples/muon_pdf.gif
:width: 400
:alt: Interactive Jupyter notebook with muon PDFs
The latest PDF data files can be downloaded from `the KM3NeT SFTP Server <http://sftp.km3net.de/data/latest/>`_.
In CC Lyon, these files are stored in ``$JPP_DIR/data``.
Here is an example how to play around with muon PDFs using the ``jppy`` module
in Lyon. Notice that ``jppy`` is already installed in the ``jpp/master``
module::
░ tgal@cca010:~
░ 13:22:51 > module load jpp/master
░ tgal@cca010:~
░ 13:22:54 > module list
Currently Loaded Modulefiles:
1) xrootd/4.8.1 5) tools/tig/2.4.1
2) km3net_env/1.1 6) tools/the_silver_searcher/2.2.0
3) python/3.7.5 7) root/6.18.04
4) tools/neovim/0.5.0 8) jpp/master
░ tgal@cca010:~
░ 13:22:56 > ipython
Python 3.7.5 (default, Nov 1 2019, 21:18:20)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.9.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import jppy
In [2]: jppy.pdf.JMuonPDF?
In [2]: jppy.version
Out[2]: '3.0.0a6'
In [3]: jppy.pdf.JMuonPDF?
Docstring: <no docstring>
Init docstring: __init__(self: jppy.pdf.JMuonPDF, file_descriptor: str, TTS: float, number_of_points: int = 25, epsilon: float = 1e-10) -> None
File: ~/dev/pybind/jppy.pdf.cpython-37m-x86_64-linux-gnu.so
File: /pbs/throng/km3net/software/python/3.7.5/lib/python3.7/site-packages/jppy/pdf.cpython-37m-x86_64-linux-gnu.so
Type: pybind11_type
Subclasses:
In [3]:
Do you really want to exit ([y]/n)? n
In [3]: muon_pdf = jppy.pdf.JMuonPDF("/pbs/throng/km3net/src/Jpp/master/data/J%p.dat", 0)
In [4]: muon_pdf = jppy.pdf.JMuonPDF("/pbs/throng/km3net/src/Jpp/master/data/J%p
...: .dat", 0)
loading input from file /pbs/throng/km3net/src/Jpp/master/data/J1p.dat... OK
loading input from file /pbs/throng/km3net/src/Jpp/master/data/J2p.dat... OK
loading input from file /pbs/throng/km3net/src/Jpp/master/data/J3p.dat... OK
......@@ -50,23 +104,30 @@ Here is an example how to play around with muon PDFs using the ``jppy`` module::
loading input from file /pbs/throng/km3net/src/Jpp/master/data/J6p.dat... OK
adding PDFs... OK
In [4]: muon_pdf.calculate?
In [5]: muon_pdf.calculate?
Docstring: calculate(self: jppy.pdf.JMuonPDF, E: float, R: float, theta: float, phi: float, t1: float) -> JTOOLS::JResultPDF<double>
Type: method
In [5]: result = muon_pdf.calculate(10, 5, 0, 0, 23)
In [6]: result = muon_pdf.calculate(10, 5, 0, 0, 23)
In [7]: result?
Type: JResultPDF
String form: <jppy.pdf.JResultPDF object at 0x7f735b5ca770>
File: /pbs/throng/km3net/software/python/3.7.5/lib/python3.7/site-packages/jppy/pdf.cpython-37m-x86_64-linux-gnu.so
Docstring: <no docstring>
Init docstring: __init__(self: jppy.pdf.JResultPDF, f: float, fp: float, v: float, V: float) -> None
In [6]: result.f
Out[6]: 0.0015357848280127355
In [8]: result.f
Out[8]: 0.0015357848280127355
In [7]: result.fp
Out[7]: -2.228096911939611e-05
In [9]: result.fp
Out[9]: -2.228096911939611e-05
In [8]: result.v
Out[8]: 0.02490276362751662
In [10]: result.v
Out[10]: 0.02490276362751662
In [9]: result.V
Out[9]: 0.1164929687159807
In [11]: result.V
Out[11]: 0.1164929687159807
In [10]: %timeit muon_pdf.calculate(10, 5, 0, 0, 23)
2.13 µs ± 242 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [12]: %timeit muon_pdf.calculate(10, 5, 0, 0, 23)
2.47 µs ± 293 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
......@@ -61,9 +61,9 @@ author = u'Tamas Gal'
# built documents.
#
# The short X.Y version.
version = u'3.0.0'
version = "3"
# The full version, including alpha/beta/rc tags.
release = u'3.0.0'
release = "3"
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
......
jppy Documentation
============================
.. include:: ../README.rst
Contents:
......
This diff is collapsed.
examples/cherenkov_muon.png

48.1 KiB

#!/usr/bin/env python3
# coding=utf-8
# Filename: cherenkov_muon.py
# Author: Tamas Gal <tgal@km3net.de>
"""
Plot PDF of Cherenkov light from muon using Jpp interpolation tables.
Usage:
cherenkov_muon.py [options]
cherenkov_muon.py (-h | --help)
Options:
-f FILE_DESCRIPTOR Descriptor of the PDFs [default: $JPP_DIR/data/J%p.dat].
--energy=<GeV> Muon energy [default: 1e3].
--distance=<m> Distance of approach [default: 50].
--tts=<ns> PMT time smearing [default: 0.0].
--xmin=<ns> X-axis minimum [default: -20].
--xmax=<ns> X-axis maximum [default: 500].
--ymin=<P/t> Y-axis minimum [default: 1e-7].
--ymax=<P/t> Y-axis maximum [default: 1e-2].
--n-points=<n> Number of points to calculate [default: 1000].
-o OUTFILE Plot file [default: cherenkov_muon.png].
-h --help Show this screen.
"""
from docopt import docopt
docopt(__doc__)
import functools
import os
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import jppy
def main():
from docopt import docopt
args = docopt(__doc__)
directions = {
"north": (0, 0),
"east": (np.pi / 2, 0),
"south": (np.pi, 0),
"west": (np.pi / 2, np.pi)
}
muon_pdf = jppy.pdf.JMuonPDF(os.path.expandvars(args['-f']),
TTS=float(args['--tts']))
xs = np.linspace(float(args['--xmin']), float(args['--xmax']),
int(args['--n-points']))
fig, ax = plt.subplots()
for direction, (theta, phi) in directions.items():
pdf = lambda t: muon_pdf.calculate(E=float(args['--energy']),
R=float(args['--distance']),
theta=theta,
phi=phi,
t1=t).f
ax.plot(xs, list(map(pdf, xs)), label=direction)
ax.set_yscale("log")
plt.title(
"PDF of Cherenkov light from muon with E = {} GeV and R = {} m".format(
args['--energy'], args['--distance']))
plt.ylim([float(args['--ymin']), float(args['--ymax'])])
plt.ylabel(r"$\frac{dP}{dt}$ / (npe/ns)")
plt.xlabel(r"$\Delta$t / ns")
plt.legend()
plt.grid(True)
plt.savefig(args['-o'])
print("The plot has been saved as {}".format(args['-o']))
if __name__ == '__main__':
main()
%% Cell type:markdown id:5030a86c tags:
# Interactive neutrino oscillation probabilities sliders
_Authors: Jurjan Bootsma, Bouke Jung, Maarten de Jong_
%% Cell type:markdown id:d45f6adf tags:
The following plots show the neutrino oscillation probabilities against the energy and cosine of the zenith angle. The user can choose which neutrino flavour goes in, which neutrino flavour goes out and if these are particles or anti-particles. Then the user can also use sliders to vary the fundamental oscillation parameters and see the shape of the probabilities change.
%% Cell type:code id:f90eeda5 tags:
``` python
import os
import ipywidgets as iw
import matplotlib.pyplot as plt
import numpy as np
import jppy
import matplotlib.colors as colors
print(f"jppy version: {jppy.version}")
```
%% Output
jppy version: 3.4.2.dev83+g6f357bb.d20221031
%% Cell type:code id:1cb7d5ea tags:
``` python
input_file = os.path.expandvars("$JPP_DATA/JOscProbTable.NO.dat")
interpolator = jppy.oscprob.JppyOscProbInterpolator(input_file)
```
%% Output
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-12-ad85b220ede2> in <module>
1 input_file = os.path.expandvars("$JPP_DATA/JOscProbTable.NO.dat")
2
----> 3 interpolator = jppy.oscprob.JppyOscProbInterpolator(input_file)
RuntimeError: /project/antares/jurjanbootsma/software/Jpp/software/JOscProb/JOscProbInterpolator.hh:148
JOscProbInterpolator::load(): Error reading file /project/antares/jurjanbootsma/software/Jpp/data//JOscProbTable.NO.dat
%% Cell type:code id:3490ab1b tags:
``` python
#Plot of oscillation probabilities against the energy
num=500
Es = np.logspace(0,2,num=num,base=10)
opts = dict(continuous_update=False)
@iw.interact
def show_pdf(flavour_in=iw.Dropdown(options=[("Electron",12),("Muon",14),("Tau",16)],
description="Flavour in",value=14),
flavour_out=iw.Dropdown(options=[("Electron",12),("Muon",14),("Tau",16)],
description="Flavour out",value=14),
CParity=iw.Dropdown(options=[("Particle",1),("Antiparticle",-1)],
description="C Parity"),
zenith_angle=iw.FloatSlider(min=-1,max=0,step=0.01,
description="$cosθ_{zenith}$",value=-0.5,**opts),
sinsqTh12=iw.FloatSlider(min=0.27,max=0.34,step=0.01,
description="$sin^2θ_{12}$",value=0.304,**opts),
dM21sq=iw.FloatSlider(min=6.93,max=7.95,step=0.01,
description="$\Delta m_{21}^2[10^{-5}]$",value=7.42,**opts),
sinsqTh13=iw.FloatSlider(min=0.021,max=0.024,step=0.001,
description="$sin^2θ_{13}$",value=0.02246,readout_format='.3f',**opts),
dM31sq=iw.FloatSlider(min=2.45,max=2.59,step=0.01,
description="$\Delta m_{31}^2[10^{-3}]$",value=2.51, **opts),
sinsqTh23=iw.FloatSlider(min=0.41,max=0.62,step=0.01,
description="$sin^2θ_{23}$",value=0.45,**opts),
deltaCP=iw.FloatSlider(min=0,max=2,step=0.01,
description="$\delta_{CP} / \pi$",value=1.28,**opts)):
#Convert mass differences to eV^2
dM21sq=dM21sq*10**-5
dM31sq=dM31sq*10**-3
zenith_angles = np.tile(zenith_angle, num)
#Set oscillation channel and parameters and perform interpolation
channel = jppy.oscprob.JOscChannel(flavour_in, flavour_out, CParity)
parameters = jppy.oscprob.JOscParameters(dM21sq, dM31sq, deltaCP, sinsqTh12, sinsqTh13, sinsqTh23)
probs = interpolator(parameters, channel, Es, zenith_angles)
#The plot
fig, ax = plt.subplots(figsize=(8,4))
ax.plot(Es, probs)
ax.set_xscale('log')
ax.set_ylim(0, 1.05)
plt.grid()
ax.set_xlabel('E [GeV]', fontsize=15)
ax.set_ylabel('Probability', fontsize=15)
```
%% Output
%% Cell type:markdown id:2922002a tags:
Varying zenith angles
%% Cell type:code id:053d7a58 tags:
``` python
#Plot of oscillation probabilities against the cosine of the zenith angle
num=1000
zenith_angles = np.linspace(-1,-0.05,num=num)
opts = dict(continuous_update=False)
@iw.interact
def show_pdf(flavour_in=iw.Dropdown(options=[("Electron",12),("Muon",14),("Tau",16)],
description="Flavour in",value=14),
flavour_out=iw.Dropdown(options=[("Electron",12),("Muon",14),("Tau",16)],
description="Flavour out",value=14),
CParity=iw.Dropdown(options=[("Particle",1),("Antiparticle",-1)],
description="C Parity"),
E=iw.FloatLogSlider(value=5,base=10,min=0,max=2,
description="Energy",step=0.1,**opts),
sinsqTh12=iw.FloatSlider(min=0.27,max=0.34,step=0.01,
description="$sin^2θ_{12}$",value=0.304,**opts),
dM21sq=iw.FloatSlider(min=6.93,max=7.95,step=0.01,
description="$\Delta m_{21}^2[10^{-5}]$",value=7.42,**opts),
sinsqTh13=iw.FloatSlider(min=0.021,max=0.024,step=0.001,
description="$sin^2θ_{13}$",value=0.02246,readout_format='.3f',**opts),
dM31sq=iw.FloatSlider(min=2.45,max=2.59,step=0.01,
description="$\Delta m_{31}^2[10^{-3}]$",value=2.51, **opts),
sinsqTh23=iw.FloatSlider(min=0.41,max=0.62,step=0.01,
description="$sin^2θ_{23}$",value=0.45,**opts),
deltaCP=iw.FloatSlider(min=0,max=2,step=0.01,
description="$\delta_{CP} / \pi$",value=1.28,**opts)):
#Converting units to eV^2
dM21sq=dM21sq*10**-5
dM31sq=dM31sq*10**-3
Es = np.tile(E, num)
#Set oscillation channel and parameters and perform interpolation
channel = jppy.oscprob.JOscChannel(flavour_in, flavour_out, CParity)
parameters = jppy.oscprob.JOscParameters(dM21sq, dM31sq, deltaCP, sinsqTh12, sinsqTh13, sinsqTh23)
probs = interpolator(parameters, channel, Es, zenith_angles)
fig, ax = plt.subplots(figsize=(8,4))
ax.plot(zenith_angles, probs)
ax.set_ylim(0, 1.05)
plt.grid()
ax.set_xlabel('Cosine of zenith angle', fontsize=15)
ax.set_ylabel('Probability', fontsize=15)
```
%% Output
%% Cell type:code id:a3e803f1 tags:
``` python
#2D density plot
num_E = 250
num_angle = 250
Es = np.logspace(0,2,num=num_E,base=10)
angles = np.linspace(-1,-0.05,num=num_angle)
Es_meshgrid, angles_meshgrid = np.meshgrid(Es, angles)
opts = dict(continuous_update=False)
@iw.interact
def show_pdf(flavour_in=iw.Dropdown(options=[("Electron",12),("Muon",14),("Tau",16)],
description="Flavour in",value=14),
flavour_out=iw.Dropdown(options=[("Electron",12),("Muon",14),("Tau",16)],
description="Flavour out",value=14),
CParity=iw.Dropdown(options=[("Particle",1),("Antiparticle",-1)],
description="C Parity"),
sinsqTh12=iw.FloatSlider(min=0.27,max=0.34,step=0.01,
description="$sin^2θ_{12}$",value=0.304,**opts),
dM21sq=iw.FloatSlider(min=6.93,max=7.96,step=0.01,
description="$\Delta m_{21}^2[10^{-5}]$",value=7.42,**opts),
sinsqTh13=iw.FloatSlider(min=0.021,max=0.024,step=0.001,
description="$sin^2θ_{13}$",value=0.02246,readout_format='.3f',**opts),
dM31sq=iw.FloatSlider(min=2.45,max=2.59,step=0.01,
description="$\Delta m_{31}^2[10^{-3}]$",value=2.51, **opts),
sinsqTh23=iw.FloatSlider(min=0.41,max=0.62,step=0.01,
description="$sin^2θ_{23}$",value=0.45,**opts),
deltaCP=iw.FloatSlider(min=0,max=2,step=0.01,
description="$\delta_{CP} / \pi$",value=1.28,**opts)):
#Converting units to eV^2
dM21sq=dM21sq*10**-5
dM31sq=dM31sq*10**-3
parameters = jppy.oscprob.JOscParameters(sinsqTh12=sinsqTh12,
dM21sq=dM21sq,
sinsqTh13=sinsqTh13,
dM31sq=dM31sq,
sinsqTh23=sinsqTh23,
deltaCP=deltaCP)
channel = jppy.oscprob.JOscChannel(flavour_in, flavour_out, CParity)
probs = interpolator(parameters, channel, Es_meshgrid.flatten(), angles_meshgrid.flatten())
probs_2D = np.reshape(probs, (num_angle,num_E))
fig, ax = plt.subplots(figsize=(8,6))
pos=ax.imshow(probs_2D, cmap='PuBu',vmin=0,vmax=1, origin = 'lower',
extent=(np.amin(Es), np.amax(Es), np.amin(angles), np.amax(angles)),aspect='auto')
plt.colorbar(pos,ax=ax)
ax.set_xlabel('E / GeV', fontsize=15)
ax.set_ylabel('Cosine of zenith angle', fontsize=15)
ticks = [1,50,100]
tick_labels = ["1","10","100"]
plt.xticks(ticks,labels=tick_labels)
plt.show()
```
%% Output
%% Cell type:code id:e3b721f1 tags:
``` python
baseline = interpolator.get_baseline_calculator()
```
%% Cell type:code id:2f5d67ce tags:
``` python
#2D density plot
num_L_E = 200
num_angle = 200
L_Es = np.linspace(500,10000,num=num_L_E)
angles = np.linspace(-1,-0.05,num=num_angle)
#angles=angles[::-1]
Ls = np.zeros(num_angle)
for i in range(0, num_angle):
L = baseline(angles[i])
Ls[i] = L
L_Es = L_Es[::-1]
L_E_meshgrid, L_meshgrid = np.meshgrid(L_Es, Ls)
L_E_meshgrid, angles_meshgrid = np.meshgrid(L_Es, angles)
Es_meshgrid = L_meshgrid/L_E_meshgrid
opts = dict(continuous_update=False)
@iw.interact
def show_pdf(flavour_in=iw.Dropdown(options=[("Electron",12),("Muon",14),("Tau",16)],
description="Flavour in",value=14),
flavour_out=iw.Dropdown(options=[("Electron",12),("Muon",14),("Tau",16)],
description="Flavour out",value=14),
CParity=iw.Dropdown(options=[("Particle",1),("Antiparticle",-1)],
description="C Parity"),
sinsqTh12=iw.FloatSlider(min=0.27,max=0.34,step=0.01,
description="$sin^2θ_{12}$",value=0.304,**opts),
dM21sq=iw.FloatSlider(min=6.93,max=7.96,step=0.01,
description="$\Delta m_{21}^2[10^{-5}]$",value=7.42,**opts),
sinsqTh13=iw.FloatSlider(min=0.021,max=0.024,step=0.001,
description="$sin^2θ_{13}$",value=0.02246,readout_format='.3f',**opts),
dM31sq=iw.FloatSlider(min=2.45,max=2.59,step=0.01,
description="$\Delta m_{31}^2[10^{-3}]$",value=2.51, **opts),
sinsqTh23=iw.FloatSlider(min=0.41,max=0.62,step=0.01,
description="$sin^2θ_{23}$",value=0.45,**opts),
deltaCP=iw.FloatSlider(min=0,max=2,step=0.01,
description="$\delta_{CP} / \pi$",value=1.28,**opts)):
#Converting units to eV^2
dM21sq=dM21sq*10**-5
dM31sq=dM31sq*10**-3
parameters = jppy.oscprob.JOscParameters(sinsqTh12=sinsqTh12,
dM21sq=dM21sq,
sinsqTh13=sinsqTh13,
dM31sq=dM31sq,
sinsqTh23=sinsqTh23,
deltaCP=deltaCP)
channel = jppy.oscprob.JOscChannel(flavour_in, flavour_out, CParity)
probs = interpolator(parameters, channel, Es_meshgrid.flatten(), angles_meshgrid.flatten())
probs_2D = np.reshape(probs, (num_angle,num_L_E))
probs_2D = probs_2D[:, ::-1]
fig, ax = plt.subplots(figsize=(8,6))
pos=ax.imshow(probs_2D, cmap='PuBu',vmin=0,vmax=1, origin = 'lower',
extent=(np.amin(L_Es), np.amax(L_Es), np.amin(angles), np.amax(angles)),aspect='auto')
plt.colorbar(pos,ax=ax)
ax.set_xlabel('L/E [km/GeV]', fontsize=15)
ax.set_ylabel('Cosine of zenith angle', fontsize=15)
plt.show()
```
%% Output
%% Cell type:code id:926a92f8 tags:
``` python
```
examples/muon_pdf.gif

2.04 MiB

%% Cell type:code id:df0497ff tags:
``` python
import os
import ipywidgets as iw
import matplotlib.pyplot as plt
import numpy as np
import jppy
print(f"jppy version: {jppy.version}")
```
%% Output
jppy version: 3.4.1.dev38+g19af23d.d20221023
%% Cell type:code id:66947fea tags:
``` python
#Reading the data
input_file = os.path.expandvars("${JPP_DATA}/JOscProbTable.NO.dat")
interpolator = jppy.oscprob.JppyOscProbInterpolator(input_file)
```
%% Output
loading oscillation probability table from file /home/yugen96/work/KM3NeT/software/Jpp/Jpp_dev/data//JOscProbTable.NO.dat... OK
%% Cell type:code id:9e442279 tags:
``` python
#Set the channel
flavour1 = jppy.oscprob.JFlavour_t(12)
flavour2 = jppy.oscprob.JFlavour_t(14)
CParity = jppy.oscprob.JChargeParity_t(1)
channel = jppy.oscprob.JOscChannel(flavour1, flavour2, CParity)
print(jppy.oscprob.JFlavour_t.ELECTRON)
print(channel.Cparity)
xs = np.logspace(1, 5, num=50, base=10)
```
%% Output
JFlavour_t.ELECTRON
JChargeParity_t.PARTICLE
%% Cell type:code id:c52117ec tags:
``` python
xs = np.linspace(10,1000,1000)
#xs = np.logspace(1, 3, num=50, base=10)
parameters = jppy.oscprob.JOscParameters(False)
parameters.set("sinsqTh12", 0.35,
"sinsqTh13", 0.025,
"sinsqTh23", 0.62)
probs = interpolator(parameters,channel,[10],[-1])
print(probs)
```
%% Output
[0.00916337]
%% Cell type:code id:8ed821ca tags:
``` python
xs = np.linspace(10,1000,1000)
opts = dict(continuous_update=False)
@iw.interact
def show_pdf(flavour_in=iw.Dropdown(options=[("Electron",12),("Muon",14),("Tau",16)], value=12),
flavour_out=iw.Dropdown(options=[("Electron",12),("Muon",14),("Tau",16)], value=14),
CParity=iw.Dropdown(options=[("Particle",1),("Antiparticle",-1)]),
sinsqTh12=iw.FloatSlider(min=0.2, max=0.35, step=0.01, value=0.304, **opts),
dM21sq=iw.FloatSlider(min=6.93e-5, max=7.96e-5, step=10e-7, value=7.42e-5,readout_format='.5f', **opts),
sinsqTh13=iw.FloatSlider(min=0.017, max=0.025, step=0.001, value=0.02246,readout_format='.3f', **opts),
dM31sq=iw.FloatSlider(min=0.00245,max=0.00269, step=0.00001, value=2.51e-3,readout_format='.4f', **opts),
sinsqTh23=iw.FloatSlider(min=0.38, max=0.62, step=0.01, value=0.45, **opts),
deltaCP=iw.FloatSlider(min=0, max=2, step=0.01, value=1.28, **opts)):
parameters = jppy.oscprob.JOscParameters(sinsqTh12=sinsqTh12,
dM21sq=dM21sq,
sinsqTh13=sinsqTh13,
dM31sq=dM31sq,
sinsqTh23=sinsqTh23,
deltaCP=deltaCP)
channel = jppy.oscprob.JOscChannel(jppy.oscprob.JFlavour_t(flavour_in),
jppy.oscprob.JFlavour_t(flavour_out),
jppy.oscprob.JChargeParity_t(CParity))
pdf = lambda E: interpolator(channel,[E],[1])
ys = list(map(pdf, xs))
y_above = np.max(ys)*1.25
fig, ax = plt.subplots(figsize=(8,4))
ax.plot(xs, ys)
ax.set_xscale('log')
ax.set_ylim(0, 0.065)
#ax.set_ylim(0, 1.1)
plt.grid()
ax.set_xlabel('E / GeV', fontsize=15)
ax.set_ylabel('Probability', fontsize=15)
```
%% Output
%% Cell type:markdown id:8da9161d tags:
Tests
%% Cell type:code id:eff09816 tags:
``` python
#Test if all the probilities add up to 1
xs = np.linspace(10,1000,1000)
opts = dict(continuous_update=False)
@iw.interact
def show_pdf(flavour_in=iw.Dropdown(options=[("Electron",12),("Muon",14),("Tau",16)], value=14),
CParity=iw.Dropdown(options=[("Particle",1),("Antiparticle",-1)]),
sinsqTh12=iw.FloatSlider(min=0.2, max=0.35, step=0.01, value=0.304, **opts),
dM21sq=iw.FloatSlider(min=6.93e-5, max=7.96e-5, step=10e-7, value=7.42e-5,readout_format='.1e', **opts),
sinsqTh13=iw.FloatSlider(min=0.017, max=0.025, step=0.001, value=0.02246,readout_format='.3f', **opts),
dM31sq=iw.FloatSlider(min=0.00245,max=0.00269, step=0.00001, value=2.51e-3,readout_format='.4f', **opts),
sinsqTh23=iw.FloatSlider(min=0.38, max=0.62, step=0.01, value=0.45, **opts),
deltaCP=iw.FloatSlider(min=0, max=2, step=0.01, value=1.28, **opts)):
parameters = jppy.oscprob.JOscParameters(sinsqTh12=sinsqTh12,
dM21sq=dM21sq,
sinsqTh13=sinsqTh13,
dM31sq=dM31sq,
sinsqTh23=sinsqTh23,
deltaCP=deltaCP)
interpolator = jppy.oscprob.JOscProbInterpolator8D(table, parameters)
channel = jppy.oscprob.JOscChannel(jppy.oscprob.JFlavour_t(flavour_in),
jppy.oscprob.JFlavour_t(12),
jppy.oscprob.JChargeParity_t(CParity))
pdf1 = lambda E: interpolator(channel,[E],[1])
ys1 = list(map(pdf1, xs))
interpolator = jppy.oscprob.JOscProbInterpolator8D(table, parameters)
channel = jppy.oscprob.JOscChannel(jppy.oscprob.JFlavour_t(flavour_in),
jppy.oscprob.JFlavour_t(14),
jppy.oscprob.JChargeParity_t(CParity))
pdf2 = lambda E: interpolator(channel,[E],[1])
ys2 = list(map(pdf2, xs))
channel = jppy.oscprob.JOscChannel(jppy.oscprob.JFlavour_t(flavour_in),
jppy.oscprob.JFlavour_t(16),
jppy.oscprob.JChargeParity_t(CParity))
pdf3 = lambda E: interpolator(channel,[E],[1])
ys3 = list(map(pdf3, xs))
ys_total = np.array(ys1)+np.array(ys2)+np.array(ys3)
fig, ax = plt.subplots(figsize=(8,4))
ax.plot(xs, ys_total)
ax.set_xscale('log')
#ax.set_yscale('log')
ax.set_ylim(0, 1.1)
#ax.set_ylim(0, y_above)
plt.grid()
ax.set_xlabel('E / GeV', fontsize=15)
ax.set_ylabel('Probability', fontsize=15)
```
%% Output
%% Cell type:code id:d8a39610 tags:
``` python
#Met goede y-as
xs = np.linspace(10,1000,1000)
opts = dict(continuous_update=False)
@iw.interact
def choose_channel(flavour_in=iw.Dropdown(options=[("Electron",12),("Muon",14),("Tau",16)], value=12),
flavour_out=iw.Dropdown(options=[("Electron",12),("Muon",14),("Tau",16)], value=14),
CParity=iw.Dropdown(options=[("Particle",1),("Antiparticle",-1)])):
channel = jppy.oscprob.JOscChannel(jppy.oscprob.JFlavour_t(flavour_in),
jppy.oscprob.JFlavour_t(flavour_out),
jppy.oscprob.JChargeParity_t(CParity))
print(channel)
opts = dict(continuous_update=False)
@iw.interact
def show_pdf(sinsqTh12=iw.FloatSlider(min=0.2, max=0.35, step=0.01, value=0.304, **opts),
dM21sq=iw.FloatSlider(min=6.93e-5, max=7.96e-5, step=10e-7, value=7.42e-5,readout_format='.5f', **opts),
sinsqTh13=iw.FloatSlider(min=0.017, max=0.025, step=0.001, value=0.02246,readout_format='.3f', **opts),
dM31sq=iw.FloatSlider(min=0.00245,max=0.00269, step=0.00001, value=2.51e-3,readout_format='.4f', **opts),
sinsqTh23=iw.FloatSlider(min=0.38, max=0.62, step=0.01, value=0.45, **opts),
deltaCP=iw.FloatSlider(min=0, max=2, step=0.01, value=1.28, **opts)):
parameters = jppy.oscprob.JOscParameters(sinsqTh12=sinsqTh12,
dM21sq=dM21sq,
sinsqTh13=sinsqTh13,
dM31sq=dM31sq,
sinsqTh23=sinsqTh23,
deltaCP=deltaCP)
interpolator = jppy.oscprob.JOscProbInterpolator8D(table, parameters)
pdf = lambda E: interpolator.__call__(channel,E,1)
ys = list(map(pdf, xs))
y_above = np.max(ys)*1.25
fig, ax = plt.subplots(figsize=(8,4))
ax.plot(xs, ys)
ax.set_xscale('log')
#ax.set_yscale('log')
ax.set_ylim(0, 0.065)
#ax.set_ylim(0, y_above)
plt.grid()
ax.set_xlabel('E / GeV', fontsize=15)
ax.set_ylabel('Probability', fontsize=15)
```
%% Output
Cparity=1
in=12
out=14
%% Cell type:code id:110c92f3 tags:
``` python
xs=[1,2,3,4]
ys=[2,4,6,8]
def func(a,b):
return a+b
pdf = lambda a,b: func(a,b)
zs = list(map(pdf,xs,ys))
print(zs)
```
%% Output
[3, 6, 9, 12]
%% Cell type:code id:7b58ec32 tags:
``` python
```
[build-system]
requires = ["setuptools>=42", "wheel", "setuptools_scm[toml]>=3.4"]
requires = ["setuptools>=42", "wheel", "setuptools_scm[toml]>=3.4", "pybind11>=2.6"]
build-backend = "setuptools.build_meta"
[tool.setuptools_scm]
write_to = "src/jppy/version.py"
#!/usr/bin/env bash
if [ ! -d "venv" ]; then
echo "Creating a fresh virtualenv..."
python3 -m pip install -U pip setuptools wheel pybind11
python3 -m venv venv
else
echo "Virtualenv already created."
fi
#!/usr/bin/env bash
export URL="https://sftp.km3net.de/data/v17.0.0/"
if [ ! -d "pdfs" ]; then
echo "Retrieving PDFs..."
mkdir pdfs
cd pdfs
for i in {1..6}; do
wget "$URL/J${i}p.dat"
done
for i in {13..14}; do
wget "$URL/J${i}p.dat"
done
else
echo "PDFs already downloaded."
fi
[metadata]
name = jppy
description = "Jpp Python package"
long_description = file: README.rst
long_description_content_type = text/x-rst
url = https://git.km3net.de/km3py/jppy
author = Tamas Gal
author_email = tgal@km3net.de
maintainer = Tamas Gal
maintainer_email = tgal@km3net.de
license = MIT
license_files = LICENSE
classifiers =
Development Status :: 5 - Production/Stable
Intended Audience :: Developers
Intended Audience :: Science/Research
License :: OSI Approved :: BSD License
Operating System :: OS Independent
Programming Language :: C++
Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3 :: Only
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Programming Language :: Python :: 3.9
Programming Language :: Python :: 3.10
Topic :: Scientific/Engineering
keywords =
C++11
Python bindings
KM3NeT
muon
neutrino
shower
hadronic
electromagnetic
Photomultiplier tubes
probability density function
[options]
packages = find:
install_requires =
pybind11>=2.4
setuptools>=40.6.2
setuptools_scm
toml
python_requires = >=3.6
include_package_data = True
package_dir =
=src
[build_ext]
inplace=1
[options.packages.find]
where = src
[options.extras_require]
all =
ipykernel
dev =
ipykernel
pytest
pytest-cov
pytest-flake8
pytest-pylint
pytest-watch
sphinx-gallery>=0.1.12
sphinx-rtd-theme>=0.3
sphinx>=1.6.3
sphinxcontrib-napoleon>=0.6.1
sphinxcontrib-programoutput>=0.11
sphinxcontrib-websupport>=1.0.1
sphinx-autoapi
twine
wheel
[bdist_wheel]
universal = 1
[tool:pytest]
junit_family = xunit2
addopts = -vv -rs -Wd
testpaths =
tests
[check-manifest]
ignore =
src/version.py
#!/usr/bin/env python3
import os
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
......@@ -5,8 +6,6 @@ import sys
import setuptools
import subprocess as sp
__version__ = '3.0.0'
class get_pybind_include(object):
"""Helper class to determine the pybind11 include path
......@@ -21,44 +20,12 @@ class get_pybind_include(object):
import pybind11
return pybind11.get_include(self.user)
def get_root_flags(kind):
"""Retrieve the root flags for kind='inc' or kind'='lib'"""
return sp.Popen(["root-config", "--{}dir".format(kind)],
stdout=sp.PIPE).communicate()[0].strip().decode()
def get_jpp_include():
return os.path.join(os.getenv("JPP_DIR"), "software")
ext_modules = [
Extension(
'jppy.pdf',
['src/pdf.cc'],
include_dirs=[
get_pybind_include(),
get_pybind_include(user=True),
get_root_flags("inc"),
get_jpp_include()
],
library_dirs=[get_root_flags("lib")],
libraries=["MathCore"],
language='c++')
]
# Populating the __init__.py with submodule imports, so that one can import
# the package and use the submodules directly with the dot-sytax.
with open("jppy/__init__.py", "w") as fobj:
for module in ext_modules:
fobj.write("from . import {}\n".format(module.name.split('.')[1]))
try:
with open("README.rst") as fh:
long_description = fh.read()
except UnicodeDecodeError:
long_description = "jppy - Jpp Python Package"
jpp_dir = os.getenv("JPP_DIR")
if jpp_dir:
return os.path.join(jpp_dir, "software")
return "src/jpp"
# As of Python 3.6, CCompiler has a `has_flag` method.
......@@ -82,7 +49,7 @@ def cpp_flag(compiler):
The newer version is prefered over c++11 (when it is available).
"""
flags = ['-std=c++17', '-std=c++14', '-std=c++11']
flags = ['-std=c++14', '-std=c++11']
for flag in flags:
if has_flag(compiler, flag): return flag
......@@ -126,18 +93,23 @@ class BuildExt(build_ext):
build_ext.build_extensions(self)
setup(
name='jppy',
version=__version__,
author='Tamas Gal',
author_email='tgal@km3net.de',
url='https://git.km3net.de/km3py/jppy',
description='Jpp Python Package',
packages=["jppy"],
long_description=long_description,
ext_modules=ext_modules,
install_requires=['pybind11>=2.4'],
setup_requires=['pybind11>=2.4'],
cmdclass={'build_ext': BuildExt},
zip_safe=False,
)
if __name__ == '__main__':
setup_args = dict(
ext_modules = [
Extension(
'jppy.{}'.format(module),
['src/jppy/{}.cc'.format(module)],
include_dirs=[
get_pybind_include(),
get_pybind_include(user=True),
get_jpp_include()
],
language='c++') for module in ['constants', 'geane', 'pdf', 'npe', 'oscprob', 'lang']
],
cmdclass = dict(
build_ext = BuildExt
)
)
setup(**setup_args)
#ifndef __JIO__JBUFFEREDIO__
#define __JIO__JBUFFEREDIO__
#include <algorithm>
#include <cstring>
#include "JLang/JSinglePointer.hh"
#include "JIO/JSerialisable.hh"
/**
* \author mdejong
*/
namespace JIO {}
namespace JPP { using namespace JIO; }
namespace JIO {
/**
* Buffered binary input.
* This class implements the JReader interface.
*/
class JBufferedReader :
public JReader
{
public:
/**
* Constructor.
* Note that this object owns the reader pointed to.
*
* \param __in pointer to reader
* \param __size size of internal buffer
*/
JBufferedReader(JReader* __in, const int __size = 1048576) :
in(__in)
{
size = std::max(__size, 1024);
buffer = new char[size];
reset();
}
/**
* Destructor.
*/
~JBufferedReader()
{
delete [] buffer;
}
/**
* Status of reader.
*
* \return status of this reader
*/
virtual bool getStatus() const override
{
return in->getStatus() || !eof;
}
/**
* Clear status of reader.
*/
virtual void clear() override
{
in->clear();
}
/**
* Read byte array.
*
* \param zbuf pointer to byte array
* \param n number of bytes
* \return number of bytes
*/
virtual int read(char* zbuf, int n) override
{
for (int i = 0; i != n; ) {
int m = n - i;
if (m > ls - pos) {
memmove(buffer, buffer + pos, ls - pos);
ls -= pos;
pos = 0;
ls += in->read(buffer + ls, size - ls);
if (m > ls) {
if (ls == 0) {
eof = true;
return n - i;
}
m = ls;
}
}
memcpy(zbuf + i, buffer + pos, m);
i += m;
pos += m;
}
eof = false;
return n;
}
protected:
/**
* Reset.
*/
void reset()
{
pos = 0;
ls = 0;
eof = true;
}
JLANG::JSinglePointer<JReader> in;
char* buffer; //!< internal buffer
int size; //!< size of internal buffer
int pos; //!< pointer to begin of available data
int ls; //!< pointer to end of available data
bool eof; //!< end of file
private:
JBufferedReader(const JBufferedReader&);
JBufferedReader(JBufferedReader&&);
JBufferedReader& operator=(const JBufferedReader&);
JBufferedReader& operator=(JBufferedReader&&);
};
/**
* Buffered binary output.
* This class implements the JWriter interface.
*/
class JBufferedWriter :
public JWriter
{
public:
/**
* Constructor.
* Note that this object owns the writer pointed to.
*
* \param __out pointer to writer
* \param __size size of internal buffer
*/
JBufferedWriter(JWriter* __out, const int __size = 1048576) :
out(__out)
{
size = std::max(__size, 1024);
buffer = new char[size];
pos = 0;
}
/**
* Destructor.
*/
~JBufferedWriter()
{
flush();
delete [] buffer;
}
/**
* Status of writer.
*
* \return status of this writer
*/
virtual bool getStatus() const override
{
return (bool) *out;
}
/**
* Write byte array.
*
* \param zbuf pointer to byte array
* \param n number of bytes
* \return number of bytes
*/
virtual int write(const char* zbuf, int n) override
{
for (int i = 0; i != n; ) {
int m = n - i;
if (m > size - pos) {
flush();
if (m > size - pos) {
m = size - pos;
}
}
memcpy(buffer + pos, zbuf + i, m);
i += m;
pos += m;
}
return n;
}
/**
* Write internal data to output.
*/
void flush()
{
pos -= out->write(buffer, pos);
}
protected:
JLANG::JSinglePointer<JWriter> out;
char* buffer; //!< internal buffer
int size; //!< size of internal buffer
int pos; //!< pointer to end of buffered data
private:
JBufferedWriter(const JBufferedWriter&);
JBufferedWriter(JBufferedWriter&&);
JBufferedWriter& operator=(const JBufferedWriter&);
JBufferedWriter& operator=(JBufferedWriter&&);
};
}
#endif
#ifndef __JIO__JFILESTREAMIO__
#define __JIO__JFILESTREAMIO__
#include <fstream>
#include "JIO/JStreamIO.hh"
#include "JIO/JBufferedIO.hh"
/**
* \author mdejong
*/
namespace JIO {}
namespace JPP { using namespace JIO; }
namespace JIO {
/**
* Binary buffered file input.
*/
class JFileStreamReader :
public std::ifstream,
public JBufferedReader
{
public:
using JAbstractObjectStatus::operator bool;
using JAbstractObjectStatus::operator!;
using JReader::operator>>;
/**
* Default constructor.
*/
JFileStreamReader() :
std::ifstream(),
JBufferedReader(new JStreamReader(static_cast<std::ifstream&>(*this)))
{}
/**
* Constructor.
*
* \param file_name file name
* \param size size of internal buffer
*/
JFileStreamReader(const char* file_name,
const int size = 1048576) :
std::ifstream (),
JBufferedReader(new JStreamReader(static_cast<std::ifstream&>(*this)), size)
{
open(file_name);
}
/**
* Open file.
*
* \param file_name file name
*/
void open(const char* file_name)
{
static_cast<std::ifstream*>(this)->open(file_name, std::ios::binary);
}
/**
* Clear status of reader.
*/
virtual void clear() override
{
std::ifstream ::clear();
JBufferedReader::clear();
}
/**
* Rewind.
*/
void rewind()
{
seekg(0); // rewind file stream
reset(); // reset buffer
}
};
/**
* Binary buffered file output.
*/
class JFileStreamWriter :
public std::ofstream,
public JBufferedWriter
{
public:
using JAbstractObjectStatus::operator bool;
using JAbstractObjectStatus::operator!;
using JWriter::operator<<;
/**
* Default constructor.
*/
JFileStreamWriter() :
std::ofstream(),
JBufferedWriter(new JStreamWriter(static_cast<std::ofstream&>(*this)))
{}
/**
* Constructor.
*
* \param file_name file name
* \param size size of internal buffer
*/
JFileStreamWriter(const char* file_name,
const int size = 1048576) :
std::ofstream(),
JBufferedWriter(new JStreamWriter(static_cast<std::ofstream&>(*this)), size)
{
open(file_name);
}
/**
* Open file.
*
* \param file_name file name
*/
void open(const char* file_name)
{
static_cast<std::ofstream*>(this)->open(file_name, std::ios::binary);
}
/**
* Close file.
*/
void close()
{
static_cast<JBufferedWriter*>(this)->flush();
static_cast<std::ofstream*> (this)->close();
}
};
}
#endif