Skip to content

Commit

Permalink
Merge pull request #5 from smartsammler/fix-python3
Browse files Browse the repository at this point in the history
Make kafe run with python3
  • Loading branch information
dsavoiu authored Mar 20, 2017
2 parents 1118891 + 3946534 commit f973b08
Show file tree
Hide file tree
Showing 16 changed files with 259 additions and 237 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
*.log
#.kafe
*.egg-info
*.cache
*.eggs

##########
# Images #
Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@ master
======
% [TODO] add unit test for input file parser

v1.3.0
======

% [FIX] make code Python 3 compatible.
Imports solved with try: Python2 variant; except ImportError: Python3 variant

v1.1.0
======

Expand All @@ -18,6 +24,7 @@ v1.1.0

v1.0.1
======

% [BUG] in fit.py (color name "darmagenta" -> "darkmagenta")
% [FIX] for matplotlib vers. 1.5.x : bbox parameters in plot.py
% [NOTE] set_color_cycle in fit.py is deprecated in matplotlib 1.5,
Expand Down
30 changes: 15 additions & 15 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# Install script for kafe using pip

function check_python_2 () {
function check_python_2_3 () {
echo "Checking Python version for executable '$1'..."
if ! [[ `which $1` ]]; then
echo "Python executable '$1' not found in PATH!"
Expand All @@ -13,15 +13,15 @@ function check_python_2 () {
echo "Python executable '$1' in Python 2: ok"
return 0
elif [[ PYTHON_VERSION -eq 3 ]]; then
echo "Python executable '$1' is Python 3: not supported"
return 1
echo "Python executable '$1' in Python 3: ok"
return 0
else
echo "Python executable '$1' not found in PATH!"
return 1
fi
}

function check_pip_python_2 () {
function check_pip_python_2_3 () {
echo "Checking Python version for pip executable '$1'..."
if ! [[ `which $1` ]]; then
echo "Pip executable '$1' not found in PATH!"
Expand All @@ -32,8 +32,8 @@ function check_pip_python_2 () {
echo "Pip executable '$1' uses Python 2: ok"
return 0
elif [[ PIP_PYTHON_VERSION -eq 3 ]]; then
echo "Pip executable '$1' uses Python 3: not supported"
return 1
echo "Pip executable '$1' uses Python 3: ok"
return 0
else
echo "Pip executable '$1' not found in PATH!"
return 1
Expand All @@ -43,26 +43,26 @@ function check_pip_python_2 () {
## -- main -- ##

# pip executables to try out
PIP_EXEC_LIST="pip pip2 pip2.7"
PIP_EXEC_LIST="pip pip2 pip2.7 pip3 pip3.1 pip3.2 pip3.3 pip3.4 pip3.5 pip3.6 pip3.7"
PY_EXEC="python"

check_python_2 $PY_EXEC
found_python_2=$?
check_python_2_3 $PY_EXEC
found_python_2_3=$?

if [[ found_python_2 -eq 0 ]]; then
if [[ found_python_2_3 -eq 0 ]]; then
for pip_exec in $PIP_EXEC_LIST; do
check_pip_python_2 $pip_exec
found_pip_python_2=$?
if [[ found_pip_python_2 -eq 0 ]]; then
check_pip_python_2_3 $pip_exec
found_pip_python_2_3=$?
if [[ found_pip_python_2_3 -eq 0 ]]; then
break
fi
done
if [[ found_pip_python_2 -ne 0 ]]; then
if [[ found_pip_python_2_3 -ne 0 ]]; then
echo "None of the executables '$PIP_EXEC_LIST' seem to be valid. Aborting."
exit 1
fi
else
echo "Python 2 executable not found on system. Aborting."
echo "Python 2 or Python 3 executable not found on system. Aborting."
exit 1
fi

Expand Down
26 changes: 13 additions & 13 deletions kafe/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,29 @@
Fitting with **kafe** in a nutshell goes like this:
1) create a `Dataset` object from your measurement data
>>> my_d = kafe.Dataset(data=[[0., 1., 2.], [1.23, 3.45, 5.62]])
2) add errors (uncertainties) to your `Dataset`
>>> my_d.add_error_source('y', 'simple', 0.5) # y errors, all +/- 0.5
3) import a model function from `kafe.function_library` (or define one
yourself)
>>> from kafe.function_library import linear_2par
4) create a `Fit` object from your `Dataset` and your model function
>>> my_f = kafe.Fit(my_d, linear_2par)
5) do the fit
>>> my_f.do_fit()
6) *(optional)* if you want to see a plot of the result, use the `Plot`
object
>>> my_p = kafe.Plot(my_f)
>>> my_p.plot_all()
>>> my_p.show()
Expand All @@ -50,7 +50,7 @@
"""

# Import config variables
import config
from . import config

# Import version info
from . import _version_info
Expand Down Expand Up @@ -88,7 +88,7 @@
import matplotlib
try:
matplotlib.use(config.G_MATPLOTLIB_BACKEND)
except ValueError, e:
except ValueError as e:
# matplotlib does not provide requested backend
_logger.error("matplotlib error: %s" % (e,))
_logger.warning("Failed to load requested backend '%s' for matplotlib. "
Expand Down
4 changes: 2 additions & 2 deletions kafe/_version_info.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
'''
.. module:: _version_info
:platform: Unix
:synopsis: Version 1.2.0 of kafe, release Jun. 2016
:synopsis: Version 1.3.0 of kafe, release Feb. 2017
.. moduleauthor:: Daniel Savoiu <danielsavoiu@gmail.com>
Guenter Quast <g.quast@kit.edu>
'''

major = 1
minor = 2
minor = 3
revision = 0

def _get_version_tuple():
Expand Down
17 changes: 10 additions & 7 deletions kafe/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@

import sys
import os
import ConfigParser
try:
import ConfigParser
except ImportError:
import configparser as ConfigParser
import kafe

# import main logger for kafe
Expand Down Expand Up @@ -80,7 +83,7 @@ def create_config_file(config_type, force=False):
"from '%s' to '%s'." \
% (kafe_default_config_file, _file))
else:
raise Exception("Cannot create config file at '%s': file exists" \
raise Exception("Cannot create config file at '%s': file exists"
% (_file,))


Expand All @@ -101,11 +104,11 @@ def create_config_file(config_type, force=False):

# Raise Error is no default config file found
if not os.path.exists(os.path.join(*kafe_configs['system'])):
raise IOError, "No default config file for kafe was " \
"found on the system but there should " \
"be one at '%s'. Please check your " \
"installation. " \
% (os.path.join(*kafe_configs['system']),)
raise IOError("No default config file for kafe was "
"found on the system but there should "
"be one at '%s'. Please check your "
"installation. "
% (os.path.join(*kafe_configs['system']),))

# Load all found config files into the ConfigParser
kafe_config_file = None
Expand Down
30 changes: 14 additions & 16 deletions kafe/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,11 @@
# DS 150610: add ErrorSource object
# ---------------------------------------------

from string import join, split

import numpy as np
from scipy.linalg import LinAlgError
import os

from numeric_tools import cov_to_cor, cor_to_cov, extract_statistical_errors, \
from .numeric_tools import cov_to_cor, cor_to_cov, extract_statistical_errors, \
zero_pad_lower_triangle, make_symmetric_lower

NUMBER_OF_AXES = 2
Expand Down Expand Up @@ -190,8 +188,8 @@ def get_matrix(self, size=None):
try:
iter(self.error_value)
except:
raise ValueError, ("Given error `%r' is not iterable."
% (self.error_value,))
raise ValueError("Given error `%r' is not iterable."
% (self.error_value,))
else:
# use value given
_val = np.asarray(self.error_value) # size is implicit
Expand All @@ -211,7 +209,7 @@ def get_matrix(self, size=None):
return _mat

else:
raise ValueError, "Unknown error type `%s'" % (self.error_type,)
raise ValueError("Unknown error type `%s'" % (self.error_type,))


class Dataset(object):
Expand Down Expand Up @@ -389,7 +387,7 @@ def set_data(self, data):
#data = data
pass

for axis in xrange(self.__n_axes): # go through the axes
for axis in range(self.__n_axes): # go through the axes
self.set_axis_data(axis, data[axis]) # load data for axis

def set_axis_data(self, axis, data):
Expand Down Expand Up @@ -616,7 +614,7 @@ def calc_cov_mats(self, axis='all'):
np.matrix(np.zeros((_size, _size)))]

if axis is 'all':
_axes_list = range(self.__n_axes)
_axes_list = list(range(self.__n_axes))
else:
_axes_list = [self.get_axis(axis)]

Expand Down Expand Up @@ -1072,7 +1070,7 @@ def get_formatted(self, format_string=".06e", delimiter='\t'):
output_list = []

# go through the axes
for axis in xrange(self.__n_axes):
for axis in range(self.__n_axes):
# define a helper list which we will fill out
helper_list = []

Expand Down Expand Up @@ -1123,7 +1121,7 @@ def get_formatted(self, format_string=".06e", delimiter='\t'):
# if there are also correlations (syst errors)
if self.__query_has_correlations[axis]:
# go through the columns of the correlation matrix
for col in xrange(idx):
for col in range(idx):
# append corr. coefficients to the helper list
helper_list[-1].append(
format(cor_mat[idx, col], format_string)
Expand All @@ -1136,7 +1134,7 @@ def get_formatted(self, format_string=".06e", delimiter='\t'):
tmp_string = ''
for row in output_list:
for entry in row:
tmp_string += join(entry, delimiter) + '\n'
tmp_string += delimiter.join(entry) + '\n'

return tmp_string

Expand Down Expand Up @@ -1237,7 +1235,7 @@ def read_from_file(self, input_file):
tmp_linenumber += 1 # update the line number

if '#' in line:
line = split(line, '#')[0] # ignore anything after
line = line.split('#')[0] # ignore anything after
# a comment sign (#)

if (not line) or (line.isspace()): # if empty line encountered
Expand Down Expand Up @@ -1293,7 +1291,7 @@ def read_from_file(self, input_file):
tmp_reading_data_block = True

# get the entries on the line as a list (whitespace-delimited)
tmp_fields = split(line)
tmp_fields = line.split()

# if there is only one entry,
# we know it's just the measurement data
Expand All @@ -1314,7 +1312,7 @@ def read_from_file(self, input_file):
if tmp_has_syst_errors:
# other fields are correlation coefficients
# (add 1.0 on main diagonal)
tmp_cormat.append(map(float, tmp_fields[2:]) + [1.0])
tmp_cormat.append(list(map(float, tmp_fields[2:]) + [1.0]))

# if there are not enough entries
# for a valid correlation matrix
Expand Down Expand Up @@ -1358,11 +1356,11 @@ def read_from_file(self, input_file):
self.set_cov_mat(tmp_axis, None) # unset cov mat

# Turn covariance matrices into ErrorSource objects
for axis in xrange(self.__n_axes):
for axis in range(self.__n_axes):
_mat = self.get_cov_mat(axis)

# remove existing error model (all error sources)
for err_src_id in xrange(len(self.err_src[axis])):
for err_src_id in range(len(self.err_src[axis])):
self.remove_error_source(axis, err_src_id, recompute_cov_mat=False)

if _mat is not None:
Expand Down
2 changes: 1 addition & 1 deletion kafe/dataset_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def build_dataset(xdata, ydata, cov_mats=None,
'yabscor': yabscor, 'yrelcor': yrelcor}

# go through the keyword arguments
for key, val in error_keywords.iteritems():
for key, val in error_keywords.items():

err_spec = key
err_val = val
Expand Down
Loading

0 comments on commit f973b08

Please sign in to comment.