Skip to content

[Fix] Remove mutables as default argument and fix smaller issues #249

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions pyerrors/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
r'''
r"""
# What is pyerrors?
`pyerrors` is a python package for error computation and propagation of Markov chain Monte Carlo data.
It is based on the gamma method [arXiv:hep-lat/0306017](https://arxiv.org/abs/hep-lat/0306017). Some of its features are:
Expand Down Expand Up @@ -476,7 +476,7 @@ def func(a, x):
A JSON schema that may be used to verify the correctness of a file with respect to the format definition is stored in ./examples/json_schema.json. The schema is a self-descriptive format definition and contains an exemplary file.

Julia I/O routines for the json.gz format, compatible with [ADerrors.jl](https://gitlab.ift.uam-csic.es/alberto/aderrors.jl), can be found [here](https://github.com/fjosw/ADjson.jl).
'''
"""
from .obs import *
from .correlators import *
from .fits import *
Expand Down
42 changes: 23 additions & 19 deletions pyerrors/correlators.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class Corr:

__slots__ = ["content", "N", "T", "tag", "prange"]

def __init__(self, data_input, padding=[0, 0], prange=None):
def __init__(self, data_input, padding=None, prange=None):
""" Initialize a Corr object.

Parameters
Expand All @@ -58,6 +58,8 @@ def __init__(self, data_input, padding=[0, 0], prange=None):
region identified for this correlator.
"""

if padding is None:
padding = [0, 0]
if isinstance(data_input, np.ndarray):
if data_input.ndim == 1:
data_input = list(data_input)
Expand Down Expand Up @@ -105,7 +107,7 @@ def __init__(self, data_input, padding=[0, 0], prange=None):
self.N = noNull[0].shape[0]
if self.N > 1 and noNull[0].shape[0] != noNull[0].shape[1]:
raise ValueError("Smearing matrices are not NxN.")
if (not all([item.shape == noNull[0].shape for item in noNull])):
if not all([item.shape == noNull[0].shape for item in noNull]):
raise ValueError("Items in data_input are not of identical shape." + str(noNull))
else:
raise TypeError("'data_input' contains item of wrong type.")
Expand Down Expand Up @@ -236,7 +238,7 @@ def symmetric(self):
newcontent.append(None)
else:
newcontent.append(0.5 * (self.content[t] + self.content[self.T - t]))
if (all([x is None for x in newcontent])):
if all([x is None for x in newcontent]):
raise ValueError("Corr could not be symmetrized: No redundant values")
return Corr(newcontent, prange=self.prange)

Expand Down Expand Up @@ -300,7 +302,7 @@ def matrix_symmetric(self):
return 0.5 * (Corr(transposed) + self)

def GEVP(self, t0, ts=None, sort="Eigenvalue", vector_obs=False, **kwargs):
r'''Solve the generalized eigenvalue problem on the correlator matrix and returns the corresponding eigenvectors.
r"""Solve the generalized eigenvalue problem on the correlator matrix and returns the corresponding eigenvectors.

The eigenvectors are sorted according to the descending eigenvalues, the zeroth eigenvector(s) correspond to the
largest eigenvalue(s). The eigenvector(s) for the individual states can be accessed via slicing
Expand Down Expand Up @@ -333,12 +335,12 @@ def GEVP(self, t0, ts=None, sort="Eigenvalue", vector_obs=False, **kwargs):
Method used to solve the GEVP.
- "eigh": Use scipy.linalg.eigh to solve the GEVP. (default for vector_obs=False)
- "cholesky": Use manually implemented solution via the Cholesky decomposition. Automatically chosen if vector_obs==True.
'''
"""

if self.N == 1:
raise ValueError("GEVP methods only works on correlator matrices and not single correlators.")
if ts is not None:
if (ts <= t0):
if ts <= t0:
raise ValueError("ts has to be larger than t0.")

if "sorted_list" in kwargs:
Expand Down Expand Up @@ -786,7 +788,7 @@ def root_function(x, d):
raise ValueError('Unknown variant.')

def fit(self, function, fitrange=None, silent=False, **kwargs):
r'''Fits function to the data
r"""Fits function to the data

Parameters
----------
Expand All @@ -799,7 +801,7 @@ def fit(self, function, fitrange=None, silent=False, **kwargs):
If not specified, self.prange or all timeslices are used.
silent : bool
Decides whether output is printed to the standard output.
'''
"""
if self.N != 1:
raise ValueError("Correlator must be projected before fitting")

Expand Down Expand Up @@ -878,6 +880,8 @@ def show(self, x_range=None, comp=None, y_range=None, logscale=False, plateau=No
comp : Corr or list of Corr
Correlator or list of correlators which are plotted for comparison.
The tags of these correlators are used as labels if available.
y_range : list
list of two values, determining the range of the y-axis e.g. [0, 12].
logscale : bool
Sets y-axis to logscale.
plateau : Obs
Expand Down Expand Up @@ -1093,7 +1097,7 @@ def __eq__(self, y):

def __add__(self, y):
if isinstance(y, Corr):
if ((self.N != y.N) or (self.T != y.T)):
if (self.N != y.N) or (self.T != y.T):
raise ValueError("Addition of Corrs with different shape")
newcontent = []
for t in range(self.T):
Expand Down Expand Up @@ -1338,21 +1342,21 @@ def __rtruediv__(self, y):

@property
def real(self):
def return_real(obs_OR_cobs):
if isinstance(obs_OR_cobs.flatten()[0], CObs):
return np.vectorize(lambda x: x.real)(obs_OR_cobs)
def return_real(obs_or_cobs):
if isinstance(obs_or_cobs.flatten()[0], CObs):
return np.vectorize(lambda x: x.real)(obs_or_cobs)
else:
return obs_OR_cobs
return obs_or_cobs

return self._apply_func_to_corr(return_real)

@property
def imag(self):
def return_imag(obs_OR_cobs):
if isinstance(obs_OR_cobs.flatten()[0], CObs):
return np.vectorize(lambda x: x.imag)(obs_OR_cobs)
def return_imag(obs_or_cobs):
if isinstance(obs_or_cobs.flatten()[0], CObs):
return np.vectorize(lambda x: x.imag)(obs_or_cobs)
else:
return obs_OR_cobs * 0 # So it stays the right type
return obs_or_cobs * 0 # So it stays the right type

return self._apply_func_to_corr(return_imag)

Expand Down Expand Up @@ -1396,7 +1400,7 @@ def prune(self, Ntrunc, tproj=3, t0proj=2, basematrix=None):
if basematrix is None:
basematrix = self
if Ntrunc >= basematrix.N:
raise ValueError('Cannot truncate using Ntrunc <= %d' % (basematrix.N))
raise ValueError('Cannot truncate using Ntrunc <= %d' % basematrix.N)
if basematrix.N != self.N:
raise ValueError('basematrix and targetmatrix have to be of the same size.')

Expand Down Expand Up @@ -1495,7 +1499,7 @@ def eigv(x, **kwargs):
def matmul(*operands):
return np.linalg.multi_dot(operands)
N = Gt.shape[0]
output = [[] for j in range(N)]
output = [[] for _ in range(N)]
if chol_inv is None:
chol = cholesky(G0) # This will automatically report if the matrix is not pos-def
chol_inv = inv(chol)
Expand Down
8 changes: 4 additions & 4 deletions pyerrors/dirac.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ def epsilon_tensor(i, j, k):
elem : int
Element (i,j,k) of the epsilon tensor of rank 3
"""
test_set = set((i, j, k))
if not (test_set <= set((1, 2, 3)) or test_set <= set((0, 1, 2))):
test_set = {i, j, k}
if not (test_set <= {1, 2, 3} or test_set <= {0, 1, 2}):
raise ValueError("Unexpected input", i, j, k)

return (i - j) * (j - k) * (k - i) / 2
Expand All @@ -50,8 +50,8 @@ def epsilon_tensor_rank4(i, j, k, o):
elem : int
Element (i,j,k,o) of the epsilon tensor of rank 4
"""
test_set = set((i, j, k, o))
if not (test_set <= set((1, 2, 3, 4)) or test_set <= set((0, 1, 2, 3))):
test_set = {i, j, k, o}
if not (test_set <= {1, 2, 3, 4} or test_set <= {0, 1, 2, 3}):
raise ValueError("Unexpected input", i, j, k, o)

return (i - j) * (j - k) * (k - i) * (i - o) * (j - o) * (o - k) / 12
Expand Down
8 changes: 4 additions & 4 deletions pyerrors/fits.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def __repr__(self):


def least_squares(x, y, func, priors=None, silent=False, **kwargs):
r'''Performs a non-linear fit to y = func(x).
r"""Performs a non-linear fit to y = func(x).
```

Parameters
Expand Down Expand Up @@ -224,7 +224,7 @@ def func_b(a, x):
chisquare/d.o.f.: 0.5388013574561786 # random
fit parameters [1.11897846 0.96361162 0.92325319] # random

'''
"""
output = Fit_result()

if (isinstance(x, dict) and isinstance(y, dict) and isinstance(func, dict)):
Expand Down Expand Up @@ -504,7 +504,7 @@ def chisqfunc_compact(d):


def total_least_squares(x, y, func, silent=False, **kwargs):
r'''Performs a non-linear fit to y = func(x) and returns a list of Obs corresponding to the fit parameters.
r"""Performs a non-linear fit to y = func(x) and returns a list of Obs corresponding to the fit parameters.

Parameters
----------
Expand Down Expand Up @@ -553,7 +553,7 @@ def func(a, x):
-------
output : Fit_result
Parameters and information on the fitted result.
'''
"""

output = Fit_result()

Expand Down
4 changes: 2 additions & 2 deletions pyerrors/input/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
r'''
r"""
`pyerrors` includes an `input` submodule in which input routines and parsers for the output of various numerical programs are contained.

# Jackknife samples
For comparison with other analysis workflows `pyerrors` can also generate jackknife samples from an `Obs` object or import jackknife samples into an `Obs` object.
See `pyerrors.obs.Obs.export_jackknife` and `pyerrors.obs.import_jackknife` for details.
'''
"""
from . import bdio as bdio
from . import dobs as dobs
from . import hadrons as hadrons
Expand Down
20 changes: 14 additions & 6 deletions pyerrors/input/dobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def _dict_to_xmlstring_spaces(d, space=' '):
return o


def create_pobs_string(obsl, name, spec='', origin='', symbol=[], enstag=None):
def create_pobs_string(obsl, name, spec='', origin='', symbol=None, enstag=None):
"""Export a list of Obs or structures containing Obs to an xml string
according to the Zeuthen pobs format.

Expand Down Expand Up @@ -113,6 +113,8 @@ def create_pobs_string(obsl, name, spec='', origin='', symbol=[], enstag=None):
XML formatted string of the input data
"""

if symbol is None:
symbol = []
od = {}
ename = obsl[0].e_names[0]
names = list(obsl[0].deltas.keys())
Expand Down Expand Up @@ -176,7 +178,7 @@ def create_pobs_string(obsl, name, spec='', origin='', symbol=[], enstag=None):
return rs


def write_pobs(obsl, fname, name, spec='', origin='', symbol=[], enstag=None, gz=True):
def write_pobs(obsl, fname, name, spec='', origin='', symbol=None, enstag=None, gz=True):
"""Export a list of Obs or structures containing Obs to a .xml.gz file
according to the Zeuthen pobs format.

Expand Down Expand Up @@ -206,6 +208,8 @@ def write_pobs(obsl, fname, name, spec='', origin='', symbol=[], enstag=None, gz
-------
None
"""
if symbol is None:
symbol = []
pobsstring = create_pobs_string(obsl, name, spec, origin, symbol, enstag)

if not fname.endswith('.xml') and not fname.endswith('.gz'):
Expand Down Expand Up @@ -309,7 +313,7 @@ def read_pobs(fname, full_output=False, gz=True, separator_insertion=None):
full_output : bool
If True, a dict containing auxiliary information and the data is returned.
If False, only the data is returned as list.
separatior_insertion: str or int
separator_insertion: str or int
str: replace all occurences of "separator_insertion" within the replica names
by "|%s" % (separator_insertion) when constructing the names of the replica.
int: Insert the separator "|" at the position given by separator_insertion.
Expand Down Expand Up @@ -409,7 +413,7 @@ def import_dobs_string(content, full_output=False, separator_insertion=True):
full_output : bool
If True, a dict containing auxiliary information and the data is returned.
If False, only the data is returned as list.
separatior_insertion: str, int or bool
separator_insertion: str, int or bool
str: replace all occurences of "separator_insertion" within the replica names
by "|%s" % (separator_insertion) when constructing the names of the replica.
int: Insert the separator "|" at the position given by separator_insertion.
Expand Down Expand Up @@ -677,7 +681,7 @@ def _dobsdict_to_xmlstring_spaces(d, space=' '):
return o


def create_dobs_string(obsl, name, spec='dobs v1.0', origin='', symbol=[], who=None, enstags=None):
def create_dobs_string(obsl, name, spec='dobs v1.0', origin='', symbol=None, who=None, enstags=None):
"""Generate the string for the export of a list of Obs or structures containing Obs
to a .xml.gz file according to the Zeuthen dobs format.

Expand Down Expand Up @@ -708,6 +712,8 @@ def create_dobs_string(obsl, name, spec='dobs v1.0', origin='', symbol=[], who=N
xml_str : str
XML string generated from the data
"""
if symbol is None:
symbol = []
if enstags is None:
enstags = {}
od = {}
Expand Down Expand Up @@ -866,7 +872,7 @@ def create_dobs_string(obsl, name, spec='dobs v1.0', origin='', symbol=[], who=N
return rs


def write_dobs(obsl, fname, name, spec='dobs v1.0', origin='', symbol=[], who=None, enstags=None, gz=True):
def write_dobs(obsl, fname, name, spec='dobs v1.0', origin='', symbol=None, who=None, enstags=None, gz=True):
"""Export a list of Obs or structures containing Obs to a .xml.gz file
according to the Zeuthen dobs format.

Expand Down Expand Up @@ -900,6 +906,8 @@ def write_dobs(obsl, fname, name, spec='dobs v1.0', origin='', symbol=[], who=No
-------
None
"""
if symbol is None:
symbol = []
if enstags is None:
enstags = {}

Expand Down
12 changes: 8 additions & 4 deletions pyerrors/input/hadrons.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ def extract_t0_hd5(path, filestem, ens_id, obs='Clover energy density', fit_rang
return fit_t0(t2E_dict, fit_range, plot_fit=kwargs.get('plot_fit'))


def read_DistillationContraction_hd5(path, ens_id, diagrams=["direct"], idl=None):
def read_DistillationContraction_hd5(path, ens_id, diagrams=None, idl=None):
"""Read hadrons DistillationContraction hdf5 files in given directory structure

Parameters
Expand All @@ -265,6 +265,8 @@ def read_DistillationContraction_hd5(path, ens_id, diagrams=["direct"], idl=None
extracted DistillationContration data
"""

if diagrams is None:
diagrams = ["direct"]
res_dict = {}

directories, idx = _get_files(path, "data", idl)
Expand Down Expand Up @@ -486,7 +488,7 @@ def read_Bilinear_hd5(path, filestem, ens_id, idl=None):
return result_dict


def read_Fourquark_hd5(path, filestem, ens_id, idl=None, vertices=["VA", "AV"]):
def read_Fourquark_hd5(path, filestem, ens_id, idl=None, vertices=None):
"""Read hadrons FourquarkFullyConnected hdf5 file and output an array of CObs

Parameters
Expand All @@ -508,6 +510,8 @@ def read_Fourquark_hd5(path, filestem, ens_id, idl=None, vertices=["VA", "AV"]):
extracted fourquark matrizes
"""

if vertices is None:
vertices = ["VA", "AV"]
files, idx = _get_files(path, filestem, idl)

mom_in = None
Expand Down Expand Up @@ -596,7 +600,7 @@ def _get_lorentz_names(name):
assert len(name) == 2

if 'S' in name or 'P' in name:
if not set(name) <= set(['S', 'P']):
if not set(name) <= {'S', 'P'}:
raise Exception("'" + name + "' is not a Lorentz scalar")

g_names = {'S': 'Identity',
Expand All @@ -605,7 +609,7 @@ def _get_lorentz_names(name):
res.append((g_names[name[0]], g_names[name[1]]))

else:
if not set(name) <= set(['V', 'A']):
if not set(name) <= {'V', 'A'}:
raise Exception("'" + name + "' is not a Lorentz scalar")

for ind in lorentz_index:
Expand Down
6 changes: 4 additions & 2 deletions pyerrors/input/openQCD.py
Original file line number Diff line number Diff line change
Expand Up @@ -596,7 +596,9 @@ def _parse_array_openQCD2(d, n, size, wa, quadrupel=False):
return arr


def _find_files(path, prefix, postfix, ext, known_files=[]):
def _find_files(path, prefix, postfix, ext, known_files=None):
if known_files is None:
known_files = []
found = []
files = []

Expand Down Expand Up @@ -1268,7 +1270,7 @@ def read_ms5_xsf(path, prefix, qc, corr, sep="r", **kwargs):
idl_wanted = True
if 'idl' in kwargs:
idl_wanted = (cnfg in expected_idl[repnum])
left_idl = left_idl - set([cnfg])
left_idl = left_idl - {cnfg}
if idl_wanted:
cnfgs[repnum].append(cnfg)

Expand Down
Loading
Loading