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

Merge branch 'add_JOscProb' into 'master'

Add JOscProb tools and interactive sliders for oscillation probabilities

See merge request !10
parents cd000714 7fb2825e
No related branches found
No related tags found
1 merge request!10Add JOscProb tools and interactive sliders for oscillation probabilities
Pipeline #32166 passed
Showing
with 3318 additions and 27 deletions
......@@ -17,7 +17,7 @@ stages:
.virtualenv_template: &virtualenv_definition |
./scripts/create_venv.sh
source venv/bin/activate
pip install .
python3 -m pip install .
.test_template: &test_definition |
source venv/bin/activate
......
%% 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
```
%% 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
```
#!/usr/bin/env bash
if [ ! -d "venv" ]; then
echo "Creating a fresh virtualenv..."
pip install -U pip setuptools wheel
python -m venv venv
python3 -m pip install -U pip setuptools wheel pybind11
python3 -m venv venv
else
echo "Virtualenv already created."
fi
......@@ -105,7 +105,7 @@ if __name__ == '__main__':
get_pybind_include(user=True),
get_jpp_include()
],
language='c++') for module in ['constants', 'geane', 'pdf', 'npe']
language='c++') for module in ['constants', 'geane', 'pdf', 'npe', 'oscprob', 'lang']
],
cmdclass = dict(
build_ext = BuildExt
......
......@@ -39,9 +39,7 @@ namespace JIO {
size = std::max(__size, 1024);
buffer = new char[size];
pos = 0;
ls = 0;
eof = true;
reset();
}
......@@ -119,8 +117,17 @@ namespace JIO {
return n;
}
protected:
/**
* Reset.
*/
void reset()
{
pos = 0;
ls = 0;
eof = true;
}
JLANG::JSinglePointer<JReader> in;
char* buffer; //!< internal buffer
......@@ -128,6 +135,12 @@ namespace JIO {
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&&);
};
......@@ -225,6 +238,12 @@ namespace JIO {
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&&);
};
}
......
......@@ -63,6 +63,27 @@ namespace JIO {
{
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
}
};
......
......@@ -147,21 +147,21 @@ namespace JIO {
}
JWriter& operator<<(const bool& value) { write((const char*) &value, sizeof(bool)); return *this; }
JWriter& operator<<(const char& value) { write((const char*) &value, sizeof(char)); return *this; }
JWriter& operator<<(const unsigned char& value) { write((const char*) &value, sizeof(unsigned char)); return *this; }
JWriter& operator<<(const short& value) { write((const char*) &value, sizeof(short)); return *this; }
JWriter& operator<<(const unsigned short& value) { write((const char*) &value, sizeof(unsigned short)); return *this; }
JWriter& operator<<(const int& value) { write((const char*) &value, sizeof(int)); return *this; }
JWriter& operator<<(const unsigned int& value) { write((const char*) &value, sizeof(unsigned int)); return *this; }
JWriter& operator<<(const long int& value) { write((const char*) &value, sizeof(long int)); return *this; }
JWriter& operator<<(const unsigned long int& value) { write((const char*) &value, sizeof(unsigned long int)); return *this; }
JWriter& operator<<(const long long int& value) { write((const char*) &value, sizeof(long long int)); return *this; }
JWriter& operator<<(const unsigned long long int& value) { write((const char*) &value, sizeof(unsigned long long int)); return *this; }
JWriter& operator<<(const float& value) { write((const char*) &value, sizeof(float)); return *this; }
JWriter& operator<<(const double& value) { write((const char*) &value, sizeof(double)); return *this; }
JWriter& operator<<(const long double& value) { write((const char*) &value, sizeof(long double)); return *this; }
JWriter& operator<<(const JLANG::JObjectID& value) { return (*this) << value.getID(); }
JWriter& operator<<(const bool value) { write((const char*) &value, sizeof(bool)); return *this; }
JWriter& operator<<(const char value) { write((const char*) &value, sizeof(char)); return *this; }
JWriter& operator<<(const unsigned char value) { write((const char*) &value, sizeof(unsigned char)); return *this; }
JWriter& operator<<(const short value) { write((const char*) &value, sizeof(short)); return *this; }
JWriter& operator<<(const unsigned short value) { write((const char*) &value, sizeof(unsigned short)); return *this; }
JWriter& operator<<(const int value) { write((const char*) &value, sizeof(int)); return *this; }
JWriter& operator<<(const unsigned int value) { write((const char*) &value, sizeof(unsigned int)); return *this; }
JWriter& operator<<(const long int value) { write((const char*) &value, sizeof(long int)); return *this; }
JWriter& operator<<(const unsigned long int value) { write((const char*) &value, sizeof(unsigned long int)); return *this; }
JWriter& operator<<(const long long int value) { write((const char*) &value, sizeof(long long int)); return *this; }
JWriter& operator<<(const unsigned long long int value) { write((const char*) &value, sizeof(unsigned long long int)); return *this; }
JWriter& operator<<(const float value) { write((const char*) &value, sizeof(float)); return *this; }
JWriter& operator<<(const double value) { write((const char*) &value, sizeof(double)); return *this; }
JWriter& operator<<(const long double value) { write((const char*) &value, sizeof(long double)); return *this; }
JWriter& operator<<(const JLANG::JObjectID& value) { return (*this) << value.getID(); }
/**
......
#ifndef __JLANG__JABSTRACTFILE__
#define __JLANG__JABSTRACTFILE__
#include <stdio.h>
#include "JLang/JComparable.hh"
/**
* \author mdejong
*/
namespace JLANG {}
namespace JPP { using namespace JLANG; }
namespace JLANG {
/**
* The JAbstractFile class encapsulates the c-style file descriptor.
*/
class JAbstractFile :
public JComparable<JAbstractFile>
{
public:
static const int FILE_CLOSED = -1;
/**
* Default constructor.
*/
JAbstractFile() :
fileDescriptor(FILE_CLOSED)
{}
/**
* Constructor.
*
* \param file file descriptor
*/
JAbstractFile(const int file) :
fileDescriptor(file)
{}
/**
* Constructor.
*
* \param stream file stream
*/
JAbstractFile(FILE* stream) :
fileDescriptor(fileno(stream))
{}
/**
* Less than operation.
*
* \param file JAbstractFile to be compared
* \return true if this file descriptor is less; else false
*/
bool less(const JAbstractFile& file) const
{
return getFileDescriptor() < file.getFileDescriptor();
}
/**
* Get file descriptor.
*
* \return file descriptor
*/
int getFileDescriptor() const
{
return fileDescriptor;
}
/**
* Get open status.
*/
bool is_open() const
{
return fileDescriptor != FILE_CLOSED;
}
protected:
int fileDescriptor;
};
}
#endif
#ifndef __JLANG__JABSTRACTIO__
#define __JLANG__JABSTRACTIO__
#include <istream>
#include <ostream>
/**
* \author mdejong
*/
namespace JLANG {}
namespace JPP { using namespace JLANG; }
namespace JLANG {
/**
* Interface for ASCII input using standard streams.
*/
class JStreamInput {
public:
/**
* Virtual destructor.
*/
virtual ~JStreamInput()
{}
/**
* Stream input.
*
* \param in input stream
* \return input stream
*/
virtual std::istream& read(std::istream& in) = 0;
/**
* Read object from input.
*
* \param in input stream
* \param object object
* \return input stream
*/
friend inline std::istream& operator>>(std::istream& in, JStreamInput& object)
{
return object.read(in);
}
};
/**
* Interface for ASCII output using standard streams.
*/
class JStreamOutput {
public:
/**
* Virtual destructor.
*/
virtual ~JStreamOutput()
{}
/**
* Stream output.
*
* \param out output stream
* \return output stream
*/
virtual std::ostream& write(std::ostream& out) const = 0;
/**
* Write object to output.
*
* \param out output stream
* \param object object
* \return output stream
*/
friend inline std::ostream& operator<<(std::ostream& out, const JStreamOutput& object)
{
return object.write(out);
}
};
/**
* Interface for ASCII output with prefix and postfix using standard streams.
*/
class JStreamSuffixOutput {
public:
/**
* Virtual destructor.
*/
virtual ~JStreamSuffixOutput()
{}
/**
* Stream output.
*
* \param out output stream
* \param prefix prefix
* \param postfix postfix
* \return output stream
*/
virtual std::ostream& write(std::ostream& out,
const char* prefix,
const char postfix) const = 0;
};
}
#endif
#ifndef __JLANG__JANYTYPE__
#define __JLANG__JANYTYPE__
/**
* \author mdejong
*/
namespace JLANG {}
namespace JPP { using namespace JLANG; }
namespace JLANG {
/**
* Auxiliary class for any type definition.
* This class can be used to test the validity of an expression through type conversion.
*/
struct JAnyType {
/**
* Type conversion operation.
*
* \param any_type any type
*/
template<class T>
JAnyType(const T& any_type)
{}
};
}
#endif
......@@ -13,16 +13,18 @@ namespace JLANG {
/**
* Generation of compiler error.
*/
template<bool>
template<bool, class T = void>
struct JAssert;
/**
* Implementation of valid assertion.
*/
template<>
struct JAssert<true>
template<class T>
struct JAssert<true, T>
{
static const bool value = true;
typedef T type;
};
}
......
#ifndef __JLANG__JCATEGORY
#define __JLANG__JCATEGORY
/**
* \author mdejong
*/
namespace JLANG {}
namespace JPP { using namespace JLANG; }
namespace JLANG {
/**
* Auxiliary class to define value, reference and pointer types for given data type and category.
*/
template<class T, bool is_constant>
struct JCategory;
/**
* Specialisation of JCategory for constant (i.e.\ non-modifiable) data type.
*/
template<class T>
struct JCategory<T, true> {
typedef const T value_type;
typedef const T& reference_type;
typedef const T* pointer_type;
};
/**
* Specialisation of JCategory for modifiable (i.e.\ non-constant) data type.
*/
template<class T>
struct JCategory<T, false> {
typedef T value_type;
typedef T& reference_type;
typedef T* pointer_type;
};
}
#endif
#ifndef __JLANG__JCOLORFACET__
#define __JLANG__JCOLORFACET__
#include <locale>
#include <ostream>
#include <string>
#include <vector>
#include <map>
#include "JLang/JType.hh"
#include "JLang/JTypeList.hh"
#include "JLang/JSinglePointer.hh"
#include "JLang/JException.hh"
/**
* \author mdejong
*/
namespace JLANG {}
namespace JPP { using namespace JLANG; }
namespace JLANG {
/**
* Enumeration of text colors.
*/
enum JColor_t {
RED, //!< red
GREEN, //!< green
BLUE, //!< blue
WHITE, //!< white
CYAN, //!< cyan
PURPLE, //!< purple
YELLOW, //!< yellow
RESET, //!< reset
BOLD //!< bold
};
/**
* Facet interface to specify text color.
* This class extends the std::locale::facet class.
*/
struct JColorFacet :
public std::locale::facet
{
static std::locale::id id;
/**
* Constructor.
*
* \param refs reference count
*/
JColorFacet(std::size_t refs = 0) :
std::locale::facet(refs)
{}
/**
* Print color.
*
* \param color code
* \return text
*/
virtual const char* c_str(const JColor_t color) const = 0;
/**
* Clone this facet.
*
* \return pointer to newly created facet
*/
virtual JColorFacet* clone() const = 0;
/**
* Check color.
*
* \param color code
* \return true if color; else false
*/
static inline bool is_color(const int color)
{
return !is_bold(color) && !is_reset(color);
}
/**
* Check bold.
*
* \param color code
* \return true if bold; else false
*/
static inline bool is_bold(const int color)
{
return color == BOLD;
}
/**
* Check reset.
*
* \param color code
* \return true if reset; else false
*/
static inline bool is_reset(const int color)
{
return color == RESET;
}
private:
JColorFacet(const JColorFacet&); // not defined
void operator=(const JColorFacet&); // not defined
};
/**
* Facet class to specify text color for ASCII.
*/
struct JColorFacetASCII :
public JColorFacet
{
/**
* Get name of facet.
*
* \return name
*/
static inline const char* getName()
{
return "ASCII";
}
/**
* Constructor.
*
* \param refs reference count
*/
JColorFacetASCII(std::size_t refs = 0) :
JColorFacet(refs)
{}
/**
* Print color.
*
* \param color code
* \return text
*/
virtual const char* c_str(const JColor_t color) const override
{
switch (color) {
case RED: return "\033[91m";
case GREEN: return "\033[92m";
case BLUE: return "\033[94m";
case WHITE: return "\033[97m";
case CYAN: return "\033[96m";
case PURPLE: return "\033[95m";
case YELLOW: return "\033[93m";
case BOLD: return "\033[1m";
case RESET: return "\033[0m";
default: return "";
}
}
/**
* Clone this facet.
*
* \return pointer to newly created facet
*/
virtual JColorFacetASCII* clone() const override
{
return new JColorFacetASCII();
}
};
/**
* Facet class to specify text color for ELcode.
*/
struct JColorFacetELcode :
public JColorFacet
{
/**
* Get name of facet.
*
* \return name
*/
static inline const char* getName()
{
return "ELcode";
}
/**
* Constructor.
*
* \param refs reference count
*/
JColorFacetELcode(std::size_t refs = 0) :
JColorFacet(refs)
{}
/**
* Print color.
*
* \param color code
* \return text
*/
virtual const char* c_str(const JColor_t color) const override
{
static std::string buffer;
history.push_back(color);
switch (color) {
case RED: return "[color=red]";
case GREEN: return "[color=green]";
case BLUE: return "[color=blue]";
case WHITE: return "[color=white]";
case CYAN: return "[color=cyan]";
case PURPLE: return "[color=purple]";
case YELLOW: return "[color=yellow]";
case BOLD: return "[bold]";
case RESET:
buffer.clear();
for (std::vector<int>::const_reverse_iterator i = history.rbegin(); i != history.rend(); ++i) {
if (is_color(*i))
buffer += "[/color]";
else if (is_bold (*i))
buffer += "[/bold]";
else
;
}
history.clear();
return buffer.c_str();
default: return "";
}
}
/**
* Clone this facet.
*
* \return pointer to newly created facet
*/
virtual JColorFacetELcode* clone() const override
{
return new JColorFacetELcode();
}
private:
mutable std::vector<int> history;
};
/**
* Typelist of color facets.
*/
typedef JTYPELIST<JColorFacetASCII, JColorFacetELcode>::typelist JColorFacetTypes_t;
/**
* Auxiliary map for color facets.
*/
struct JColorFacetMap_t :
public std::map<std::string, JSinglePointer<JColorFacet> >
{
typedef std::map<std::string, JSinglePointer<JColorFacet> > map_type;
typedef typename map_type::key_type key_type;
typedef typename map_type::mapped_type mapped_type;
typedef typename map_type::value_type value_type;
/**
* Default constructor.
*/
JColorFacetMap_t()
{
for_each(*this, JType<JColorFacetTypes_t>());
}
/**
* Get value for given key.
*
* Note that this method will throw an error if given key is absent.
*
* \param key key
* \return value
*/
const mapped_type& operator[](const key_type& key) const
{
const_iterator p = find(key);
if (p != this->end()) {
return p->second;
}
THROW(JNullPointerException, "Invalid key " << key);
}
/**
* Insert data type.
*
* \param type data type
*/
template<class T>
void operator()(const JType<T>& type)
{
insert(value_type(T::getName(), new T()));
}
};
/**
* Color facets.
*/
static const JColorFacetMap_t color_facets;
}
/**
* Print color.
*
* \param out output stream
* \param color color
* \return output stream
*/
inline std::ostream& operator<<(std::ostream& out, const JLANG::JColor_t color)
{
using namespace std;
using namespace JPP;
const locale& loc = out.getloc();
if (has_facet<JColorFacetASCII>(loc))
return out << use_facet<JColorFacetASCII> (loc).c_str(color);
else if (has_facet<JColorFacetELcode>(loc))
return out << use_facet<JColorFacetELcode>(loc).c_str(color);
else
return out << JColorFacetASCII().c_str(color);
}
#endif
#ifndef __JLANG__JCOMPARISONAVAILABLE__
#define __JLANG__JCOMPARISONAVAILABLE__
#include "JLang/JNullType.hh"
#include "JLang/JAnyType.hh"
#include "JLang/JVoid.hh"
#include "JLang/JTest.hh"
/**
* \author mdejong
*/
namespace JLANG {}
namespace JPP { using namespace JLANG; }
namespace JLANG {
/**
* Local namespace for fallback implementations for comparison operators.
*/
namespace JLOCAL {
/**
* Fallback implementations for comparison operators.
*/
inline JNullType operator==(JAnyType, JAnyType) { return JNullType(); }
inline JNullType operator!=(JAnyType, JAnyType) { return JNullType(); }
inline JNullType operator< (JAnyType, JAnyType) { return JNullType(); }
inline JNullType operator> (JAnyType, JAnyType) { return JNullType(); }
inline JNullType operator<=(JAnyType, JAnyType) { return JNullType(); }
inline JNullType operator>=(JAnyType, JAnyType) { return JNullType(); }
/**
* Test availability of comparison operators of non-composite data types.
*/
template<class T, class JType_t = void>
class JComparisonAvailable :
public JTest
{
using JTest::test;
static JTrue test(const bool&);
static T& getReference();
public:
static const bool has_eq = JTEST(test(getReference() == getReference())); //!< true if operator== available; else false
static const bool has_ne = JTEST(test(getReference() != getReference())); //!< true if operator!= available; else false
static const bool has_lt = JTEST(test(getReference() < getReference())); //!< true if operator< available; else false
static const bool has_gt = JTEST(test(getReference() > getReference())); //!< true if operator> available; else false
static const bool has_le = JTEST(test(getReference() <= getReference())); //!< true if operator<= available; else false
static const bool has_ge = JTEST(test(getReference() >= getReference())); //!< true if operator>= available; else false
};
/**
* Test availability of comparison operators of data types which have a type definitions for first_type and second_type.
* This applies to STL containers such as std::map.
* Note that STL provides for the comparison of the container based on comparisons of its elements.
*/
template<class T>
class JComparisonAvailable<T, typename JVoid<typename T::second_type>::type>
{
typedef typename T::first_type first_type;
typedef typename T::second_type second_type;
public:
static const bool has_eq = JComparisonAvailable<first_type>::has_eq && JComparisonAvailable<second_type>::has_eq;
static const bool has_ne = JComparisonAvailable<first_type>::has_ne && JComparisonAvailable<second_type>::has_ne;
static const bool has_lt = JComparisonAvailable<first_type>::has_lt && JComparisonAvailable<second_type>::has_lt;
static const bool has_gt = JComparisonAvailable<first_type>::has_gt && JComparisonAvailable<second_type>::has_gt;
static const bool has_le = JComparisonAvailable<first_type>::has_le && JComparisonAvailable<second_type>::has_le;
static const bool has_ge = JComparisonAvailable<first_type>::has_ge && JComparisonAvailable<second_type>::has_ge;
};
/**
* Test availability of comparison operators of data types which have a type definition for value_type.
* This applies to STL containers such as std::vector and std::set.
* Note that STL provides for the comparison of the container based on comparisons of its elements.
*/
template<class T>
class JComparisonAvailable<T, typename JVoid<typename T::value_type>::type> :
public JComparisonAvailable<typename T::value_type>
{};
/**
* Template base class for data structures without equality capability.
* This class implements the operators <tt> == != </tt>.
*/
template<class T>
class JNoequals {
private:
/**
* Equal operator.
*
* \param first first object
* \param second second object
* \return true if two objects are equal; else false
*/
friend JNullType operator==(const T& first, const T& second)
{
return JNullType();
}
/**
* Not equal operator.
*
* \param first first object
* \param second second object
* \return true if two objects are not equal; else false
*/
friend JNullType operator!=(const T& first, const T& second)
{
return JNullType();
}
};
}
using JLOCAL::JComparisonAvailable;
using JLOCAL::JNoequals;
}
#endif
#ifndef __JLANG__JEQUATION__
#define __JLANG__JEQUATION__
#include <string>
#include <locale>
#include <cstdio>
#include <sstream>
#include "JLang/JString.hh"
#include "JLang/JEquationFacet.hh"
#include "JLang/JValue.hh"
/**
* \author mdejong
*/
namespace JLANG {}
namespace JPP { using namespace JLANG; }
namespace JLANG {
/**
* General purpose equation class.
*
* An equation could have the following formats:
*
* <pre>
* \<skip line\> "comment" \<end of line\>
* \<skip line\> "comment" \<end of line\>
* \<key\> \<separator\> \<value\> \<end of line\>
* \<key\> \<separator\> \<left bracket\> \<value\> \<value> \<right bracket\> \<end of line\>
* \<key\>\<division\>\<key\> \<separator\> \<value\> \<end of line\>
* </pre>
* In this:
* - lines starting with one of the skip line characters are ignored;
* - <tt>key</tt> is the key of the equation;
* - <tt>value</tt> is the value of the equation; and
* - <tt>' '</tt> could be any of the specified white space characters.
*
* In case of a division of the key, the value of the equation will include
* the following key up to the end of line.
* The special characters are defined in the JEquationParameters class.
* The use of this class for I/O is handled via the JEquationFacet class.
*/
class JEquation {
public:
/**
* Auxiliary data structure for equation.
*/
template<class T>
struct equation_type {
/**
* Constructor.
*
* \param __key key
* \param __value value
*/
equation_type(const std::string __key,
const T& __value) :
key (__key),
value(__value)
{}
/**
* Write equation to output stream.
*
* \param out output stream
* \param equation equation
* \return output stream
*/
friend inline std::ostream& operator<<(std::ostream& out, const equation_type& equation)
{
using namespace std;
ostream::sentry sentry(out);
if (sentry) {
const locale& loc = out.getloc();
if (has_facet<JEquationFacet>(loc)) {
const JEquationFacet& facet = use_facet<JEquationFacet>(loc);
out << equation.key;
out << facet.getDefaultSeparator();
out << equation.value;
out << facet.getDefaultEndOfLine();
} else {
out << equation.key;
out << '=';
out << equation.value;
out << endl;
}
}
return out;
}
std::string key;
const T& value;
};
/**
* Auxiliary method to create equation type.
*
* \param key key
* \param value value
*/
template<class T>
static inline equation_type<T> make_equation(const std::string& key, const T& value)
{
return equation_type<T>(key, value);
}
/**
* Default constructor.
*/
JEquation() :
key (),
sep ('\0'),
value()
{}
/**
* Constructor.
*
* \param key key
* \param value value
*/
JEquation(const std::string& key, const std::string& value) :
key (key),
sep ('\0'),
value(value)
{}
/**
* Constructor.
*
* \param buffer input
* \param facet facet
*/
JEquation(const std::string& buffer, const JEquationFacet& facet)
{
setEquation(buffer, facet);
}
/**
* Get key.
*
* \return key
*/
const std::string& getKey() const
{
return key;
}
/**
* Get separator.
*
* \return separator
*/
const char getSeparator() const
{
return sep;
}
/**
* Get value.
*
* \return value
*/
const std::string& getValue() const
{
return value;
}
/**
* Read equation from input stream.
*
* \param in input stream
* \param equation equation
* \return input stream
*/
friend inline std::istream& operator>>(std::istream& in, JEquation& equation)
{
using namespace std;
istream::sentry sentry(in, false);
if (sentry) {
equation = JEquation();
const locale& loc = in.getloc();
if (has_facet<JEquationFacet>(loc)) {
const JEquationFacet& facet = use_facet<JEquationFacet>(loc);
ios_base::iostate state = in.rdstate();
for (int c; (c = in.peek()) != EOF && facet.isSkipLine((char) c); ) {
facet.ignore(in);
}
if (state == ios_base::goodbit) facet.get(in, istreambuf_iterator<char>(), in, state, equation.key);
if (state == ios_base::goodbit) facet.get(in, istreambuf_iterator<char>(), in, state, equation.sep);
if (state == ios_base::goodbit) facet.getline(in, equation.value);
// remove white spaces and brackets before evaluation
if (facet.isSeparator(equation.sep)) {
JString::const_iterator p = equation.value. begin();
JString::const_reverse_iterator q = equation.value.rbegin();
for ( ; ; ++p, ++q) {
for ( ; p != equation.value. end() && facet.isWhiteSpace(*p); ++p) {}
for ( ; q != equation.value.rend() && facet.isWhiteSpace(*q); ++q) {}
if (p == equation.value. end() || *p != facet.getLeftBracket() ||
q == equation.value.rend() || *q != facet.getRightBracket()) {
break;
}
}
if (p != equation.value.begin() || q != equation.value.rbegin()) {
equation.value = string(p, q.base());
}
}
if (state != ios_base::goodbit && state != ios_base::eofbit) {
in.setstate(state);
}
if (!(state & ios_base::eofbit)) {
if (!facet.isDivision (equation.sep) &&
!facet.isSeparator(equation.sep)) {
in.setstate(ios_base::badbit);
}
}
} else {
in.setstate(ios_base::failbit);
}
}
return in;
}
/**
* Write equation to output stream.
*
* \param out output stream
* \param equation equation
* \return output stream
*/
friend inline std::ostream& operator<<(std::ostream& out, const JEquation& equation)
{
using namespace std;
ostream::sentry sentry(out);
if (sentry) {
const locale& loc = out.getloc();
if (has_facet<JEquationFacet>(loc)) {
const JEquationFacet& facet = use_facet<JEquationFacet>(loc);
out << equation.key;
out << facet.getDefaultSeparator();
out << equation.value;
out << facet.getDefaultEndOfLine();
} else {
out << equation.key;
out << equation.sep;
out << equation.value;
out << endl;
}
}
return out;
}
/**
* Set equation.
*
* \param buffer input
* \param facet facet
* \return this equation
*/
JEquation& setEquation(const std::string& buffer, const JEquationFacet& facet)
{
using namespace std;
istringstream in(buffer);
in.imbue(locale(in.getloc(), facet.clone()));
in >> *this;
return *this;
}
/**
* Set this equation to its value.
*
* \param facet facet
* \return this equation
*/
JEquation& setEquation(const JEquationFacet& facet)
{
setEquation(getValue(), facet);
return *this;
}
/**
* Extract equation.
*
* \param buffer input
* \param facet facet
* \return equation
*/
static JEquation valueOf(const std::string& buffer, const JEquationFacet& facet)
{
return JEquation(buffer, facet);
}
/**
* Convert equation to string.
*
* \return string
*/
std::string toString() const
{
std::string buffer;
buffer += getKey();
buffer += getSeparator();
buffer += getValue();
return buffer;
}
protected:
JString key;
char sep;
JString value;
};
}
#endif
#ifndef __JLANG__JEQUATIONFACET__
#define __JLANG__JEQUATIONFACET__
#include <istream>
#include <ostream>
#include <locale>
#include <string>
#include <iterator>
#include <cstdio>
#include <limits>
#include "JLang/JStringFacet.hh"
#include "JLang/JEquationParameters.hh"
/**
* \author mdejong
*/
namespace JLANG {}
namespace JPP { using namespace JLANG; }
namespace JLANG {
/**
* Facet class to specify parsing of equations in currect locale (see class JLANG::JEquation).
* Tokens are defined as a piece of text delimited by various markers according the facet.
* The list of markers is defined by the JLANG::JEquationParameters data structure.
* This class extends the JLANG::JStringFacet and JLANG::JEquationParameters classes.
*/
class JEquationFacet:
public JStringFacet,
public JEquationParameters
{
public:
using JStringFacet::get;
using JStringFacet::put;
/**
* Default constructor.
*/
JEquationFacet() :
JStringFacet(),
JEquationParameters()
{}
/**
* Constructor.
*
* \param parameters equation parameters
*/
JEquationFacet(const JEquationParameters& parameters) :
JStringFacet(),
JEquationParameters(parameters)
{}
/**
* Clone this facet.
*
* \return pointer to newly created facet
*/
virtual JEquationFacet* clone() const override
{
return new JEquationFacet(static_cast<const JEquationParameters&>(*this));
}
/**
* Get character.
*
* \param __begin begin position of input stream
* \param __end end position of input stream
* \param format format
* \param result status after input operation
* \param buffer output character
* \return position of input stream
*/
istreambuf_iterator get(const istreambuf_iterator __begin,
const istreambuf_iterator __end,
const std::ios_base& format,
std::ios_base::iostate& result,
char& buffer) const
{
return do_get(__begin, __end, format, result, buffer);
}
/**
* Put character.
*
* \param out begin position of output stream
* \param format format
* \param c fill character
* \param buffer input character
* \return position of output stream buffer
*/
ostreambuf_iterator put(ostreambuf_iterator out,
const std::ios_base& format,
const char c,
const char buffer) const
{
return do_put(out, format, c, buffer);
}
/**
* Get combined prefix for output.
*
* \param prefix prefix
* \param name name
* \return prefix
*/
const std::string getPrefix(const std::string& prefix, const std::string& name) const
{
if (prefix.empty())
return name;
else
return prefix + getDefaultDivision() + name;
}
/**
* Pop white spaces.
*
* \param in input stream
* \return input stream
*/
std::istream& pop(std::istream& in) const
{
try {
for (int c; (c = in.peek()) != EOF && isWhiteSpace((char) c); ) { in.get(); }
}
catch(const std::exception& error) {};
return in;
}
protected:
/**
* Get string.
*
* \param __begin begin position of input stream
* \param __end end position of input stream
* \param format format
* \param result status after input operation
* \param buffer output string
* \return position of input stream
*/
virtual istreambuf_iterator do_get(const istreambuf_iterator __begin,
const istreambuf_iterator __end,
const std::ios_base& format,
std::ios_base::iostate& result,
std::string& buffer) const override
{
using namespace std;
result = (ios_base::iostate) 0; // reset I/O status
streamsize n = format.width(); // number of characters to read
if (n == 0) {
n = numeric_limits<streamsize>::max();
}
istreambuf_iterator i = __begin;
while (i != __end && isWhiteSpace(*i)) {
++i;
}
if (i == __end) {
result |= ios_base::failbit;
result |= ios_base::eofbit;
} else if (isSeparator(*i) ||
isEndOfLine(*i) ||
isDivision (*i)) {
result |= ios_base::failbit;
} else {
buffer.clear();
buffer.push_back(*i);
for (++i, --n; i != __end && n != 0 && (!isWhiteSpace(*i) &&
!isSeparator (*i) &&
!isEndOfLine (*i) &&
!isDivision (*i)); ++i, --n)
buffer.push_back(*i);
if (i == __end) {
result |= ios_base::eofbit;
}
}
return i;
}
/**
* Get character.
*
* \param __begin begin position of input stream
* \param __end end position of input stream
* \param format format
* \param result status after input operation
* \param buffer output character
* \return position of input stream
*/
virtual istreambuf_iterator do_get(const istreambuf_iterator __begin,
const istreambuf_iterator __end,
const std::ios_base& format,
std::ios_base::iostate& result,
char& buffer) const
{
using namespace std;
result = (ios_base::iostate) 0; // reset I/O status
istreambuf_iterator i = __begin;
while (i != __end && isWhiteSpace(*i)) {
++i;
}
if (i == __end) {
result |= ios_base::failbit;
result |= ios_base::eofbit;
} else if (!isDivision(*i) && !isSeparator(*i)) {
result |= ios_base::failbit;
} else {
buffer = *i++;
}
return i;
}
/**
* Put string.
*
* \param out begin position of output stream
* \param format format
* \param c fill character
* \param buffer input string
* \return current position of output stream
*/
virtual ostreambuf_iterator do_put(ostreambuf_iterator out,
const std::ios_base& format,
const char c,
const std::string& buffer) const override
{
using namespace std;
if (format.flags() & ios_base::right) {
for (streamsize i = buffer.size(); i < format.width(); ++i, ++out) {
*out = c;
}
}
for (string::const_iterator i = buffer.begin(); i != buffer.end(); ++i, ++out) {
*out = *i;
}
if (format.flags() & ios_base::left) {
for (streamsize i = buffer.size(); i < format.width(); ++i, ++out) {
*out = c;
}
}
return out;
}
/**
* Put character.
*
* \param out begin position of output stream
* \param format format
* \param c fill character
* \param buffer input character
* \return current position of output stream
*/
virtual ostreambuf_iterator do_put(ostreambuf_iterator out,
const std::ios_base& format,
const char c,
const char buffer) const
{
using namespace std;
if (format.flags() & ios_base::right) {
for (streamsize i = 1; i < format.width(); ++i, ++out) {
*out = c;
}
}
*out = buffer;
++out;
if (format.flags() & ios_base::left) {
for (streamsize i = 1; i < format.width(); ++i, ++out) {
*out = c;
}
}
return out;
}
/**
* \cond NEVER
* Ignore characters until next end of line.
*
* \param __begin begin position of input stream
* \param __end end position of input stream
* \return position of input stream
* \endcond
*/
/*
virtual istreambuf_iterator do_ignore(const istreambuf_iterator __begin,
const istreambuf_iterator __end) const
{
istreambuf_iterator i = __begin;
while (i != __end && !isEndOfLine(*i)) {
++i;
}
while (i != __end && isEndOfLine(*i)) {
++i; // skip end of line(s)
}
return i;
}
*/
/**
* Read string.
*
* \param __begin begin position of input stream
* \param __end end position of input stream
* \param result status after input operation
* \param buffer output string
* \return position of input stream
*/
virtual istreambuf_iterator do_getline(const istreambuf_iterator __begin,
const istreambuf_iterator __end,
std::ios_base::iostate& result,
std::string& buffer) const override
{
using namespace std;
result = (ios_base::iostate) 0; // reset I/O status
istreambuf_iterator i = __begin;
while (i != __end && isWhiteSpace(*i) && !isEndOfLine(*i)) {
++i;
}
if (i == __end) {
result |= ios_base::failbit;
result |= ios_base::eofbit;
} else if (isEndOfLine(*i)) {
buffer.clear();
} else {
buffer.clear();
for (int count = 0; i != __end && (count != 0 || !isEndOfLine(*i)); ++i) {
buffer.push_back(*i);
if (isLeftBracket (*i)) {
++count;
} else if (isRightBracket(*i)) {
--count;
}
}
while (i != __end && isEndOfLine(*i)) {
++i; // skip end of line(s)
}
}
return i;
}
private:
JEquationFacet(const JEquationFacet&); // not defined
void operator=(const JEquationFacet&); // not defined
};
/**
* Auxiliary class for end of line.
*/
struct JEndOfLine
{
/**
* Default constructor.
*/
JEndOfLine() :
index(0)
{}
/**
* Constructor.
*
* \param i index
* \return this JEndOfLine
*/
const JEndOfLine& operator()(const unsigned int i) const
{
index = i;
return *this;
}
/**
* Print end of line.
*
* \param out output stream
* \param eol end of line
* \return output stream
*/
friend inline std::ostream& operator<<(std::ostream& out, const JEndOfLine& eol)
{
using namespace std;
if (has_facet<JEquationFacet>(out.getloc()))
out << use_facet<JEquationFacet>(out.getloc()).getPreferredEndOfLine(eol.index);
else
out << '\n';
eol.index = 0;
return out;
}
private:
mutable unsigned int index;
};
/**
* Type definition of stream manipulator for equational I/O.
*/
typedef JLANG::JEquationFacet setequation;
/**
* Parse facet.
*
* \param in input stream
* \param facet facet
* \return input stream
*/
inline std::istream& operator>>(std::istream& in, const JLANG::JEquationFacet& facet)
{
using namespace std;
in.imbue(locale(in.getloc(), facet.clone()));
return in;
}
/**
* Parse facet.
*
* \param out output stream
* \param facet facet
* \return output stream
*/
inline std::ostream& operator<<(std::ostream& out, const JLANG::JEquationFacet& facet)
{
using namespace std;
out.imbue(locale(out.getloc(), facet.clone()));
return out;
}
/**
* Print white space.
*
* \param out output stream
* \return output stream
*/
inline std::ostream& white_space(std::ostream& out)
{
using namespace std;
using namespace JLANG;
if (has_facet<JEquationFacet>(out.getloc()))
out << use_facet<JEquationFacet>(out.getloc()).getDefaultWhiteSpace();
else
out << ' ';
return out;
}
/**
* Print division.
*
* \param out output stream
* \return output stream
*/
inline std::ostream& division(std::ostream& out)
{
using namespace std;
using namespace JLANG;
if (has_facet<JEquationFacet>(out.getloc()))
out << use_facet<JEquationFacet>(out.getloc()).getDefaultDivision();
else
out << '.';
return out;
}
/**
* Print separator.
*
* \param out output stream
* \return output stream
*/
inline std::ostream& separator(std::ostream& out)
{
using namespace std;
using namespace JLANG;
if (has_facet<JEquationFacet>(out.getloc()))
out << use_facet<JEquationFacet>(out.getloc()).getDefaultSeparator();
else
out << '=';
return out;
}
/**
* Print end of line.
*/
static const JLANG::JEndOfLine end_of_line;
/**
* Print left bracket.
*
* \param out output stream
* \return output stream
*/
inline std::ostream& left_bracket(std::ostream& out)
{
using namespace std;
using namespace JLANG;
if (has_facet<JEquationFacet>(out.getloc()))
out << use_facet<JEquationFacet>(out.getloc()).getLeftBracket();
else
out << '(';
return out;
}
/**
* Print right bracket.
*
* \param out output stream
* \return output stream
*/
inline std::ostream& right_bracket(std::ostream& out)
{
using namespace std;
using namespace JLANG;
if (has_facet<JEquationFacet>(out.getloc()))
out << use_facet<JEquationFacet>(out.getloc()).getRightBracket();
else
out << ')';
return out;
}
}
#endif
#ifndef __JLANG__JEQUATIONPARAMETERS__
#define __JLANG__JEQUATIONPARAMETERS__
#include <string>
/**
* \author mdejong
*/
namespace JLANG {}
namespace JPP { using namespace JLANG; }
namespace JLANG {
/**
* Simple data structure to support I/O of equations (see class JLANG::JEquation).
*/
class JEquationParameters {
public:
/**
* Default constructor.
*/
JEquationParameters()
{
this->sep = "=";
this->eol = "\n\r;";
this->div = "./";
this->skip = "#";
this->left = '(';
this->right = ')';
this->ws = " \t\n\v\f\r";
}
/**
* Constructor.
*
* \param sep separator characters
* \param eol end of line characters
* \param div division characters
* \param skip skip line characters
* \param left left bracket
* \param right right bracket
* \param ws white space characters
*/
JEquationParameters(const std::string& sep,
const std::string& eol,
const std::string& div,
const std::string& skip,
const char left = '(',
const char right = ')',
const std::string& ws = " \t\n\v\f\r")
{
this->sep = sep;
this->eol = eol;
this->div = div;
this->skip = skip;
this->left = left;
this->right = right;
this->ws = ws;
}
/**
* Get equation parameters.
*
* \return equation parameters
*/
const JEquationParameters& getEquationParameters() const
{
return *this;
}
/**
* Set equation parameters.
*
* \param buffer equation parameters
*/
void setEquationParameters(const JEquationParameters& buffer)
{
static_cast<JEquationParameters&>(*this) = buffer;
}
/**
* Get default separator character.
*
* \return separator between parameter and its value
*/
const char getDefaultSeparator() const
{
if (sep.empty())
return '=';
else
return sep[0];
}
/**
* Get separator characters.
*
* \return separator between parameter and its value
*/
const std::string& getSeparator() const
{
return sep;
}
/**
* Set separator character(s).
*
* \param sep separator between parameter and its value
*/
void setSeparator(const std::string& sep)
{
this->sep = sep;
}
/**
* Get default end of line character.
*
* \return end of line character
*/
const char getDefaultEndOfLine() const
{
if (eol.empty())
return '\n';
else
return eol[0];
}
/**
* Get preferred end of line character.
*
* \param index index
* \return end of line character
*/
const char getPreferredEndOfLine(const unsigned int index) const
{
if (eol.empty())
return '\n';
else if (index < eol.size())
return eol[index];
else
return eol[0];
}
/**
* Get end of line characters.
*
* \return end of line characters
*/
const std::string& getEndOfLine() const
{
return eol;
}
/**
* Set end of line characters.
*
* \param eol end of line character
*/
void setEndOfLine(const std::string& eol)
{
this->eol = eol;
}
/**
* Get default division character.
*
* \return division character
*/
const char getDefaultDivision() const
{
if (div.empty())
return '.';
else
return div[0];
}
/**
* Get division characters.
*
* \return division characters
*/
const std::string& getDivision() const
{
return div;
}
/**
* Set division characters.
*
* \param div division characters
*/
void setDivision(const std::string& div)
{
this->div = div;
}
/**
* Get default skip line character.
*
* \return skip line character
*/
const char getDefaultSkipLine() const
{
if (skip.empty())
return '#';
else
return skip[0];
}
/**
* Get skip line characters.
*
* \return skip line characters
*/
const std::string& getSkipLine() const
{
return skip;
}
/**
* Set skip line characters.
*
* \param skip skip line characters
*/
void setSkipLine(const std::string& skip)
{
this->skip = skip;
}
/**
* Set brackets.
*
* \param left left bracket
* \param right right bracket
*/
void setBrackets(const char left, const char right)
{
this->left = left;
this->right = right;
}
/**
* Get left bracket.
*
* \return left bracket
*/
char getLeftBracket() const
{
return left;
}
/**
* Get right bracket.
*
* \return right bracket
*/
char getRightBracket() const
{
return right;
}
/**
* Get default white space character.
*
* \return white space character
*/
const char getDefaultWhiteSpace() const
{
if (ws.empty())
return ' ';
else
return ws[0];
}
/**
* Get white space characters.
*
* \return white space characters
*/
const std::string& getWhiteSpace() const
{
return ws;
}
/**
* Set white space characters.
*
* \param ws white space characters
*/
void setWhiteSpace(const std::string& ws)
{
this->ws = ws;
}
/**
* Join equation parameters.
*
* \param value equation parameters
*/
JEquationParameters& join(const JEquationParameters& value)
{
using namespace std;
for (string::const_iterator i = value.sep.begin(); i != value.sep.end(); ++i) {
if (!isSeparator(*i)) {
sep += *i;
}
}
for (string::const_iterator i = value.eol.begin(); i != value.eol.end(); ++i) {
if (!isEndOfLine(*i)) {
eol += *i;
}
}
for (string::const_iterator i = value.div.begin(); i != value.div.end(); ++i) {
if (!isDivision(*i)) {
div += *i;
}
}
for (string::const_iterator i = value.skip.begin(); i != value.skip.end(); ++i) {
if (!isSkipLine(*i)) {
skip += *i;
}
}
for (string::const_iterator i = value.ws.begin(); i != value.ws.end(); ++i) {
if (!isWhiteSpace(*i)) {
ws += *i;
}
}
return *this;
}
/**
* Test for separator character.
*
* \param c character
* \result true if separator; else false
*/
inline bool isSeparator(const char c) const
{
return sep .find(c) != std::string::npos;
}
/**
* Test for end of line character.
*
* \param c character
* \result true if end of line; else false
*/
inline bool isEndOfLine (const char c) const { return eol .find(c) != std::string::npos; }
/**
* Test for division character.
*
* \param c character
* \result true if division; else false
*/
inline bool isDivision(const char c) const
{
return div .find(c) != std::string::npos;
}
/**
* Test for skip line character.
*
* \param c character
* \result true if skip line; else false
*/
inline bool isSkipLine(const char c) const
{
return skip.find(c) != std::string::npos;
}
/**
* Test for left bracket character.
*
* \param c character
* \result true if left bracket; else false
*/
inline bool isLeftBracket(const char c) const
{
return c == left;
}
/**
* Test for right bracket character.
*
* \param c character
* \result true if right bracket; else false
*/
inline bool isRightBracket(const char c) const
{
return c == right;
}
/**
* Test for white space character.
*
* \param c character
* \result true if white space; else false
*/
inline bool isWhiteSpace(const char c) const
{
return ws .find(c) != std::string::npos;
}
protected:
std::string sep;
std::string eol;
std::string div;
std::string skip;
char left;
char right;
std::string ws;
};
}
#endif
......@@ -354,6 +354,24 @@ namespace JLANG {
};
/**
* Exception for recovery of file.
*/
class JFileRecoveryException :
public JException
{
public:
/**
* Constructor.
*
* \param error error message
*/
JFileRecoveryException(const std::string& error) :
JException(error)
{}
};
/**
* Exception for reading of file.
*/
......@@ -660,6 +678,14 @@ namespace JLANG {
};
}
/**
* Make exception.
*
* \param JException_t exception
* \param A message
*/
#define MAKE_EXCEPTION(JException_t, A) JException_t(static_cast<std::ostringstream&>(JLANG::JException::getOstream() << __FILE__ << ':' << __LINE__ << std::endl << A).str())
/**
* Marco for throwing exception with std::ostream compatible message.
*
......@@ -667,7 +693,7 @@ namespace JLANG {
* \param A message
*/
#ifndef THROW
#define THROW(JException_t, A) do { throw JException_t(static_cast<std::ostringstream&>(JLANG::JException::getOstream() << __FILE__ << ':' << __LINE__ << std::endl << A).str()); } while(0)
#define THROW(JException_t, A) do { throw MAKE_EXCEPTION(JException_t, A); } while(0)
#endif
#endif
#ifndef __JLANG__JFILE__
#define __JLANG__JFILE__
#include <fcntl.h>
#include "JLang/JBinaryIO.hh"
#include "JLang/JAbstractFile.hh"
#include "JLang/JFileDescriptorMask.hh"
#include "JLang/JTimeval.hh"
#include <unistd.h>
/**
* \author mdejong
*/
namespace JLANG {}
namespace JPP { using namespace JLANG; }
namespace JLANG {
/**
* The JFile class extends the JAbstractFile class.
* This class implements the JBinaryInput and JBinaryOutput interfaces.
*/
class JFile :
public JAbstractFile,
public JBinaryInput,
public JBinaryOutput
{
public:
/**
* Default constructor.
*/
JFile() :
JAbstractFile(),
result(0)
{}
/**
* Constructor.
*
* \param file file descriptor
*/
JFile(const JAbstractFile& file) :
JAbstractFile(file),
result(1)
{}
/**
* Close file.
*/
void close()
{
if (fileDescriptor != FILE_CLOSED) {
::close(fileDescriptor);
fileDescriptor = FILE_CLOSED;
result = 0;
}
}
/**
* Read data from file.
*
* \param buffer buffer
* \param length number of bytes to read
* \return number of bytes read
*/
virtual int read(char* buffer, const int length)
{
return (result = ::read(fileDescriptor, buffer, length));
}
/**
* Write data to file.
*
* \param buffer buffer
* \param length number of bytes to write
* \return number of bytes written
*/
virtual int write(const char* buffer, const int length)
{
return (result = ::write(fileDescriptor, buffer, length));
}
/**
* Check availability of input.
* This method returns true if at least one byte can be read without blocking.
*
* \param timeout timeout
* \return true if ready to read; else false
*/
bool in_avail(JTimeval timeout = JTimeval::min()) const
{
return JFileDescriptorMask(*this).in_avail(timeout);
}
/**
* Check availability of output.
* This method returns true if at least one byte can be written without blocking.
*
* \param timeout timeout
* \return true if ready to write; else false
*/
bool out_avail(JTimeval timeout = JTimeval::min()) const
{
return JFileDescriptorMask(*this).out_avail(timeout);
}
/**
* Check status.
*
* \return true if last I/O operation successful; else false
*/
virtual bool good() const
{
return is_open() && !eof() && !bad();
}
/**
* Check status.
*
* \return true if last I/O operation caused logical error; else false
*/
virtual bool fail() const
{
return result == 0;
}
/**
* Check status.
*
* \return true if last I/O operation caused read/write error; else false
*/
virtual bool bad() const
{
return fail();
}
/**
* Check end of file.
*
* \return true if end of file; else false
*/
virtual bool eof() const
{
return result == EOF;
}
private:
int result;
};
}
#endif
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