pyerrors.misc

  1import pickle
  2import numpy as np
  3from .obs import Obs
  4
  5
  6def dump_object(obj, name, **kwargs):
  7    """Dump object into pickle file.
  8
  9    Parameters
 10    ----------
 11    obj : object
 12        object to be saved in the pickle file
 13    name : str
 14        name of the file
 15    path : str
 16        specifies a custom path for the file (default '.')
 17
 18    Returns
 19    -------
 20    None
 21    """
 22    if 'path' in kwargs:
 23        file_name = kwargs.get('path') + '/' + name + '.p'
 24    else:
 25        file_name = name + '.p'
 26    with open(file_name, 'wb') as fb:
 27        pickle.dump(obj, fb)
 28
 29
 30def load_object(path):
 31    """Load object from pickle file.
 32
 33    Parameters
 34    ----------
 35    path : str
 36        path to the file
 37
 38    Returns
 39    -------
 40    object : Obs
 41        Loaded Object
 42    """
 43    with open(path, 'rb') as file:
 44        return pickle.load(file)
 45
 46
 47def pseudo_Obs(value, dvalue, name, samples=1000):
 48    """Generate an Obs object with given value, dvalue and name for test purposes
 49
 50    Parameters
 51    ----------
 52    value : float
 53        central value of the Obs to be generated.
 54    dvalue : float
 55        error of the Obs to be generated.
 56    name : str
 57        name of the ensemble for which the Obs is to be generated.
 58    samples: int
 59        number of samples for the Obs (default 1000).
 60
 61    Returns
 62    -------
 63    res : Obs
 64        Generated Observable
 65    """
 66    if dvalue <= 0.0:
 67        return Obs([np.zeros(samples) + value], [name])
 68    else:
 69        for _ in range(100):
 70            deltas = [np.random.normal(0.0, dvalue * np.sqrt(samples), samples)]
 71            deltas -= np.mean(deltas)
 72            deltas *= dvalue / np.sqrt((np.var(deltas) / samples)) / np.sqrt(1 + 3 / samples)
 73            deltas += value
 74            res = Obs(deltas, [name])
 75            res.gamma_method(S=2, tau_exp=0)
 76            if abs(res.dvalue - dvalue) < 1e-10 * dvalue:
 77                break
 78
 79        res._value = float(value)
 80
 81        return res
 82
 83
 84def gen_correlated_data(means, cov, name, tau=0.5, samples=1000):
 85    """ Generate observables with given covariance and autocorrelation times.
 86
 87    Parameters
 88    ----------
 89    means : list
 90        list containing the mean value of each observable.
 91    cov : numpy.ndarray
 92        covariance matrix for the data to be generated.
 93    name : str
 94        ensemble name for the data to be geneated.
 95    tau : float or list
 96        can either be a real number or a list with an entry for
 97        every dataset.
 98    samples : int
 99        number of samples to be generated for each observable.
100
101    Returns
102    -------
103    corr_obs : list[Obs]
104        Generated observable list
105    """
106
107    assert len(means) == cov.shape[-1]
108    tau = np.asarray(tau)
109    if np.min(tau) < 0.5:
110        raise Exception('All integrated autocorrelations have to be >= 0.5.')
111
112    a = (2 * tau - 1) / (2 * tau + 1)
113    rand = np.random.multivariate_normal(np.zeros_like(means), cov * samples, samples)
114
115    # Normalize samples such that sample variance matches input
116    norm = np.array([np.var(o, ddof=1) / samples for o in rand.T])
117    rand = rand @ np.diag(np.sqrt(np.diag(cov))) @ np.diag(1 / np.sqrt(norm))
118
119    data = [rand[0]]
120    for i in range(1, samples):
121        data.append(np.sqrt(1 - a ** 2) * rand[i] + a * data[-1])
122    corr_data = np.array(data) - np.mean(data, axis=0) + means
123    return [Obs([dat], [name]) for dat in corr_data.T]
124
125
126def _assert_equal_properties(ol, otype=Obs):
127    otype = type(ol[0])
128    for o in ol[1:]:
129        if not isinstance(o, otype):
130            raise Exception("Wrong data type in list.")
131        for attr in ["reweighted", "e_content", "idl"]:
132            if hasattr(ol[0], attr):
133                if not getattr(ol[0], attr) == getattr(o, attr):
134                    raise Exception(f"All Obs in list have to have the same state '{attr}'.")
def dump_object(obj, name, **kwargs):
 7def dump_object(obj, name, **kwargs):
 8    """Dump object into pickle file.
 9
10    Parameters
11    ----------
12    obj : object
13        object to be saved in the pickle file
14    name : str
15        name of the file
16    path : str
17        specifies a custom path for the file (default '.')
18
19    Returns
20    -------
21    None
22    """
23    if 'path' in kwargs:
24        file_name = kwargs.get('path') + '/' + name + '.p'
25    else:
26        file_name = name + '.p'
27    with open(file_name, 'wb') as fb:
28        pickle.dump(obj, fb)

Dump object into pickle file.

Parameters
  • obj (object): object to be saved in the pickle file
  • name (str): name of the file
  • path (str): specifies a custom path for the file (default '.')
Returns
  • None
def load_object(path):
31def load_object(path):
32    """Load object from pickle file.
33
34    Parameters
35    ----------
36    path : str
37        path to the file
38
39    Returns
40    -------
41    object : Obs
42        Loaded Object
43    """
44    with open(path, 'rb') as file:
45        return pickle.load(file)

Load object from pickle file.

Parameters
  • path (str): path to the file
Returns
  • object (Obs): Loaded Object
def pseudo_Obs(value, dvalue, name, samples=1000):
48def pseudo_Obs(value, dvalue, name, samples=1000):
49    """Generate an Obs object with given value, dvalue and name for test purposes
50
51    Parameters
52    ----------
53    value : float
54        central value of the Obs to be generated.
55    dvalue : float
56        error of the Obs to be generated.
57    name : str
58        name of the ensemble for which the Obs is to be generated.
59    samples: int
60        number of samples for the Obs (default 1000).
61
62    Returns
63    -------
64    res : Obs
65        Generated Observable
66    """
67    if dvalue <= 0.0:
68        return Obs([np.zeros(samples) + value], [name])
69    else:
70        for _ in range(100):
71            deltas = [np.random.normal(0.0, dvalue * np.sqrt(samples), samples)]
72            deltas -= np.mean(deltas)
73            deltas *= dvalue / np.sqrt((np.var(deltas) / samples)) / np.sqrt(1 + 3 / samples)
74            deltas += value
75            res = Obs(deltas, [name])
76            res.gamma_method(S=2, tau_exp=0)
77            if abs(res.dvalue - dvalue) < 1e-10 * dvalue:
78                break
79
80        res._value = float(value)
81
82        return res

Generate an Obs object with given value, dvalue and name for test purposes

Parameters
  • value (float): central value of the Obs to be generated.
  • dvalue (float): error of the Obs to be generated.
  • name (str): name of the ensemble for which the Obs is to be generated.
  • samples (int): number of samples for the Obs (default 1000).
Returns
  • res (Obs): Generated Observable
def gen_correlated_data(means, cov, name, tau=0.5, samples=1000):
 85def gen_correlated_data(means, cov, name, tau=0.5, samples=1000):
 86    """ Generate observables with given covariance and autocorrelation times.
 87
 88    Parameters
 89    ----------
 90    means : list
 91        list containing the mean value of each observable.
 92    cov : numpy.ndarray
 93        covariance matrix for the data to be generated.
 94    name : str
 95        ensemble name for the data to be geneated.
 96    tau : float or list
 97        can either be a real number or a list with an entry for
 98        every dataset.
 99    samples : int
100        number of samples to be generated for each observable.
101
102    Returns
103    -------
104    corr_obs : list[Obs]
105        Generated observable list
106    """
107
108    assert len(means) == cov.shape[-1]
109    tau = np.asarray(tau)
110    if np.min(tau) < 0.5:
111        raise Exception('All integrated autocorrelations have to be >= 0.5.')
112
113    a = (2 * tau - 1) / (2 * tau + 1)
114    rand = np.random.multivariate_normal(np.zeros_like(means), cov * samples, samples)
115
116    # Normalize samples such that sample variance matches input
117    norm = np.array([np.var(o, ddof=1) / samples for o in rand.T])
118    rand = rand @ np.diag(np.sqrt(np.diag(cov))) @ np.diag(1 / np.sqrt(norm))
119
120    data = [rand[0]]
121    for i in range(1, samples):
122        data.append(np.sqrt(1 - a ** 2) * rand[i] + a * data[-1])
123    corr_data = np.array(data) - np.mean(data, axis=0) + means
124    return [Obs([dat], [name]) for dat in corr_data.T]

Generate observables with given covariance and autocorrelation times.

Parameters
  • means (list): list containing the mean value of each observable.
  • cov (numpy.ndarray): covariance matrix for the data to be generated.
  • name (str): ensemble name for the data to be geneated.
  • tau (float or list): can either be a real number or a list with an entry for every dataset.
  • samples (int): number of samples to be generated for each observable.
Returns
  • corr_obs (list[Obs]): Generated observable list