Skip to content
Snippets Groups Projects
Commit aee891d4 authored by Tamas Gal's avatar Tamas Gal :speech_balloon:
Browse files

Initial commit

parents
No related branches found
No related tags found
No related merge requests found
*.so
MANIFEST
*.py[cod]
*.egg-info
.DS_Store
_build
_generate
build
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
: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).
**Note:** Beware that this package is in the development phase, so the API will
change until version ``1.0.0`` is released!
Installation
============
Run ``make`` to compile the Python modules::
make
Example
=======
Here is an example how to play around with muon PDFs using the ``jppy`` module::
In [1]: import jppy
In [2]: 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
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)
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
loading input from file /pbs/throng/km3net/src/Jpp/master/data/J4p.dat... OK
loading input from file /pbs/throng/km3net/src/Jpp/master/data/J5p.dat... OK
loading input from file /pbs/throng/km3net/src/Jpp/master/data/J6p.dat... OK
adding PDFs... OK
In [4]: 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.f
Out[6]: 0.0015357848280127355
In [7]: result.fp
Out[7]: -2.228096911939611e-05
In [8]: result.v
Out[8]: 0.02490276362751662
In [9]: result.V
Out[9]: 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)
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
.PHONY: clean
clean:
rm -rf $(BUILDDIR)/*
.PHONY: html
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
.PHONY: dirhtml
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
.PHONY: singlehtml
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
.PHONY: pickle
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
.PHONY: json
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
.PHONY: htmlhelp
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
.PHONY: qthelp
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/jppy.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/jppy.qhc"
.PHONY: applehelp
applehelp:
$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
@echo
@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
@echo "N.B. You won't be able to view it unless you put it in" \
"~/Library/Documentation/Help or install it in your application" \
"bundle."
.PHONY: devhelp
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/jppy"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/jppy"
@echo "# devhelp"
.PHONY: epub
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
.PHONY: latex
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
.PHONY: latexpdf
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: latexpdfja
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: text
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
.PHONY: man
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
.PHONY: texinfo
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
.PHONY: info
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
.PHONY: gettext
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
.PHONY: changes
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
.PHONY: linkcheck
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
.PHONY: doctest
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
.PHONY: coverage
coverage:
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
.PHONY: xml
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
.PHONY: pseudoxml
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
# -*- coding: utf-8 -*-
#
# jppy documentation build configuration file, created by
# sphinx-quickstart on Fri Feb 26 00:29:33 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.autosummary',
'sphinx.ext.napoleon',
]
autosummary_generate = True
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'jppy'
copyright = u'2020, Tamas Gal'
author = u'Tamas Gal'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'3.0.0'
# The full version, including alpha/beta/rc tags.
release = u'3.0.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'jppydoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'jppy.tex', u'jppy Documentation',
u'Tamas Gal', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'jppy', u'jppy Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'jppy', u'jppy Documentation',
author, 'jppy', 'Jpp Python Package',
'Science'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
jppy Documentation
============================
Contents:
.. toctree::
:maxdepth: 2
jppy
.. automodule:: jppy
[build-system]
requires = ["setuptools>=42", "wheel", "setuptools_scm[toml]>=3.4"]
setup.py 0 → 100644
import os
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
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
The purpose of this class is to postpone importing pybind11
until it is actually installed, so that the ``get_include()``
method can be invoked. """
def __init__(self, user=False):
self.user = user
def __str__(self):
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"
# As of Python 3.6, CCompiler has a `has_flag` method.
# cf http://bugs.python.org/issue26689
def has_flag(compiler, flagname):
"""Return a boolean indicating whether a flag name is supported on
the specified compiler.
"""
import tempfile
with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f:
f.write('int main (int argc, char **argv) { return 0; }')
try:
compiler.compile([f.name], extra_postargs=[flagname])
except setuptools.distutils.errors.CompileError:
return False
return True
def cpp_flag(compiler):
"""Return the -std=c++[11/14/17] compiler flag.
The newer version is prefered over c++11 (when it is available).
"""
flags = ['-std=c++17', '-std=c++14', '-std=c++11']
for flag in flags:
if has_flag(compiler, flag): return flag
raise RuntimeError('Unsupported compiler -- at least C++11 support '
'is needed!')
class BuildExt(build_ext):
"""A custom build extension for adding compiler-specific options."""
c_opts = {
'msvc': ['/EHsc'],
'unix': [],
}
l_opts = {
'msvc': [],
'unix': [],
}
if sys.platform == 'darwin':
darwin_opts = ['-stdlib=libc++', '-mmacosx-version-min=10.7']
c_opts['unix'] += darwin_opts
l_opts['unix'] += darwin_opts
def build_extensions(self):
ct = self.compiler.compiler_type
opts = self.c_opts.get(ct, [])
link_opts = self.l_opts.get(ct, [])
if ct == 'unix':
opts.append('-DVERSION_INFO="%s"' %
self.distribution.get_version())
opts.append(cpp_flag(self.compiler))
if has_flag(self.compiler, '-fvisibility=hidden'):
opts.append('-fvisibility=hidden')
elif ct == 'msvc':
opts.append('/DVERSION_INFO=\\"%s\\"' %
self.distribution.get_version())
for ext in self.extensions:
ext.extra_compile_args = opts
ext.extra_link_args = link_opts
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,
)
#include <pybind11/pybind11.h>
#include "JLang/JException.hh"
#include "JTools/JCollection.hh"
#include "JTools/JMap.hh"
#include "JTools/JGridMap.hh"
#include "JTools/JMapList.hh"
#include "JTools/JSpline.hh"
#include "JTools/JPolint.hh"
#include "JTools/JElement.hh"
#include "JTools/JResult.hh"
#include "JPhysics/JPDFTable.hh"
#include "JPhysics/JPDFTypes.hh"
#include "JMath/JZero.hh"
/**
* Auxiliary data structure for muon PDF.
*/
struct JMuonPDF_t {
typedef JPP::JSplineFunction1D<JPP::JSplineElement2S<double, double>,
JPP::JCollection,
JPP::JResultPDF<double> > JFunction1D_t;
typedef JPP::JMAPLIST<JPP::JPolint1FunctionalMap,
JPP::JPolint0FunctionalGridMap,
JPP::JPolint0FunctionalGridMap>::maplist JPDFMaplist_t;
typedef JPP::JPDFTable<JFunction1D_t, JPDFMaplist_t> JPDF_t;
typedef JFunction1D_t::result_type result_type;
/**
* Constructor.
*
* The PDF file descriptor should contain the wild card character JPHYSICS::WILD_CARD.\n
* The <tt>TTS</tt> corresponds to the additional time smearing applied to the PDFs.
*
* \param fileDescriptor PDF file descriptor
* \param TTS TTS [ns]
* \param numberOfPoints number of points for Gauss-Hermite integration of TTS
* \param epsilon precision for Gauss-Hermite integration of TTS
*/
JMuonPDF_t(const std::string& fileDescriptor,
const double TTS,
const int numberOfPoints = 25,
const double epsilon = 1.0e-10)
{
using namespace std;
using namespace JPP;
const JPDFType_t pdf_t[] = { DIRECT_LIGHT_FROM_MUON,
SCATTERED_LIGHT_FROM_MUON,
DIRECT_LIGHT_FROM_EMSHOWERS,
SCATTERED_LIGHT_FROM_EMSHOWERS,
DIRECT_LIGHT_FROM_DELTARAYS,
SCATTERED_LIGHT_FROM_DELTARAYS };
const int N = sizeof(pdf_t) / sizeof(pdf_t[0]);
JPDF_t pdf[N];
const JPDF_t::JSupervisor supervisor(new JPDF_t::JDefaultResult(zero));
for (int i = 0; i != N; ++i) {
const string file_name = getFilename(fileDescriptor, pdf_t[i]);
cout << "loading input from file " << file_name << "... " << flush;
pdf[i].load(file_name.c_str());
pdf[i].setExceptionHandler(supervisor);
cout << "OK" << endl;
}
// Add PDFs
cout << "adding PDFs... " << flush;
pdfA = pdf[1]; pdfA.add(pdf[0]);
pdfB = pdf[3]; pdfB.add(pdf[2]);
pdfC = pdf[5]; pdfC.add(pdf[4]);
cout << "OK" << endl;
if (TTS > 0.0) {
cout << "bluring PDFs... " << flush;
pdfA.blur(TTS, numberOfPoints, epsilon);
pdfB.blur(TTS, numberOfPoints, epsilon);
pdfC.blur(TTS, numberOfPoints, epsilon);
cout << "OK" << endl;
} else if (TTS < 0.0) {
THROW(JValueOutOfRange, "Illegal value of TTS [ns]: " << TTS);
}
}
/**
* Get PDF.
*
* The orientation of the PMT should be defined according this <a href="https://common.pages.km3net.de/jpp/JPDF.PDF">documentation</a>.\n
* In this, the zenith and azimuth angles are limited to \f[\left[0, \pi\right]\f].
*
* \param E muon energy at minimum distance of approach [GeV]
* \param R minimum distance of approach [m]
* \param theta PMT zenith angle [rad]
* \param phi PMT azimuth angle [rad]
* \param t1 arrival time relative to Cherenkov hypothesis [ns]
* \return hypothesis value
*/
result_type calculate(const double E,
const double R,
const double theta,
const double phi,
const double t1) const
{
using namespace JPP;
result_type h1 = (pdfA(R, theta, phi, t1) +
pdfB(R, theta, phi, t1) * E +
pdfC(R, theta, phi, t1) * getDeltaRaysFromMuon(E));
// safety measures
if (h1.f <= 0.0) {
h1.f = 0.0;
h1.fp = 0.0;
}
if (h1.v <= 0.0) {
h1.v = 0.0;
}
return h1;
}
JPDF_t pdfA; //!< PDF for minimum ionisong particle
JPDF_t pdfB; //!< PDF for average energy losses
JPDF_t pdfC; //!< PDF for delta-rays
};
/**
Python bindings.
*/
namespace py = pybind11;
PYBIND11_MODULE(pdf, m) {
m.doc() = "PDF utilities";
py::class_<JMuonPDF_t>(m, "JMuonPDF")
.def(py::init<const std::string &, double, int, double>(),
py::arg("file_descriptor"),
py::arg("TTS"),
py::arg("number_of_points") = 25,
py::arg("epsilon") = 1e-10)
.def("calculate", &JMuonPDF_t::calculate,
py::arg("E"),
py::arg("R"),
py::arg("theta"),
py::arg("phi"),
py::arg("t1")
),
py::class_<JTOOLS::JResultPDF<double>>(m, "JResultPDF")
.def(py::init<double, double, double, double>(),
py::arg("f"),
py::arg("fp"),
py::arg("v"),
py::arg("V"))
.def_readonly("f", &JTOOLS::JResultPDF<double>::f)
.def_readonly("fp", &JTOOLS::JResultPDF<double>::fp)
.def_readonly("v", &JTOOLS::JResultPDF<double>::v)
.def_readonly("V", &JTOOLS::JResultPDF<double>::V);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment