From 52fd84bb3656fac0450323fda36af23bc05a540e Mon Sep 17 00:00:00 2001 From: Marco Sertoli Date: Fri, 27 Oct 2023 15:32:32 +0100 Subject: [PATCH] Deleting all unused stuff in st40 branch --- indica/operators/__init__.py | 6 - indica/operators/centrifugal_asymmetry.py | 274 ---------- indica/operators/main_ion_density.py | 105 ---- indica/operators/mean_charge.py | 101 ---- snippets/plot_jet.py | 20 - snippets/read_KT7D.py | 120 ----- snippets/test_get_efit.py | 26 - snippets/wall_coords_jet.txt | 251 --------- tests/unit/fake_equilibrium.py | 251 --------- .../readers/test_abstract_reader_pytest.py | 507 ------------------ tests/unit/test_offset.py | 0 tests/unit/test_session.py | 66 --- 12 files changed, 1727 deletions(-) delete mode 100644 indica/operators/centrifugal_asymmetry.py delete mode 100644 indica/operators/main_ion_density.py delete mode 100644 indica/operators/mean_charge.py delete mode 100644 snippets/plot_jet.py delete mode 100644 snippets/read_KT7D.py delete mode 100644 snippets/test_get_efit.py delete mode 100644 snippets/wall_coords_jet.txt delete mode 100644 tests/unit/fake_equilibrium.py delete mode 100644 tests/unit/readers/test_abstract_reader_pytest.py delete mode 100644 tests/unit/test_offset.py diff --git a/indica/operators/__init__.py b/indica/operators/__init__.py index 4bd71ea9..2ff71550 100644 --- a/indica/operators/__init__.py +++ b/indica/operators/__init__.py @@ -2,9 +2,6 @@ from .abstractoperator import OperatorError from .atomic_data import FractionalAbundance from .atomic_data import PowerLoss -from .centrifugal_asymmetry import AsymmetryParameter -from .centrifugal_asymmetry import ToroidalRotation -from .mean_charge import MeanCharge from .zeff import CalcZeff __all__ = [ @@ -12,8 +9,5 @@ "OperatorError", "FractionalAbundance", "PowerLoss", - "ToroidalRotation", - "AsymmetryParameter", - "MeanCharge", "CalcZeff", ] diff --git a/indica/operators/centrifugal_asymmetry.py b/indica/operators/centrifugal_asymmetry.py deleted file mode 100644 index 68d423b0..00000000 --- a/indica/operators/centrifugal_asymmetry.py +++ /dev/null @@ -1,274 +0,0 @@ -from typing import Any -from typing import List -from typing import Tuple -from typing import Union - -from xarray.core.dataarray import DataArray - -from .abstractoperator import EllipsisType -from .abstractoperator import Operator -from .. import session -from ..datatypes import DataType -from ..datatypes import ELEMENTS -from ..utilities import input_check - - -class ToroidalRotation(Operator): - """Calculate the toroidal rotation from asymmetry parameter. - - Parameters - ---------- - - Returns - ------- - toroidal_rotation - xarray.DataArray containing toroidal rotation for a given impurity element - - Attributes - ---------- - ARGUMENT_TYPES: List[DataType] - Ordered list of the types of data expected for each argument of the - operator. - RESULT_TYPES: List[DataType] - Ordered list of the types of data returned by the operator. - """ - - ARGUMENT_TYPES: List[Union[DataType, EllipsisType]] = [] - - RESULT_TYPES: List[Union[DataType, EllipsisType]] = [ - ("toroidal_rotation", "plasma"), - ] - - def __init__(self, sess: session.Session = session.global_session): - super().__init__(sess=sess) - - def return_types(self, *args: DataType) -> Tuple[Any, ...]: - return super().return_types(*args) - - def __call__( # type: ignore - self, - asymmetry_parameters: DataArray, - ion_temperature: DataArray, - main_ion: str, - impurity: str, - Zeff: DataArray, - electron_temp: DataArray, - ): - """Calculates the toroidal rotation frequency from the asymmetry parameter. - - Parameters - ---------- - asymmetry_parameters - xarray.DataArray containing asymmetry parameters data. In units of m^-2. - ion_temperature - xarray.DataArray containing ion temperature data. In units of eV. - main_ion - Element symbol of main ion. - impurity - Element symbol of chosen impurity element. - Zeff - xarray.DataArray containing Z-effective data from diagnostics. - electron_temp - xarray.DataArray containing electron temperature data. In units of eV. - - Returns - ------- - toroidal_rotation - xarray.DataArray containing data for toroidal rotation frequencies - for the given impurity element - """ - input_check( - "asymmetry_parameters", - asymmetry_parameters, - DataArray, - ndim_to_check=3, - positive=False, - strictly_positive=False, - ) - - input_check( - "ion_temperature", - ion_temperature, - DataArray, - ndim_to_check=3, - strictly_positive=True, - ) - - input_check("main_ion", main_ion, str) - - try: - assert main_ion in list(ELEMENTS.keys()) - except AssertionError: - raise ValueError(f"main_ion must be one of {list(ELEMENTS.keys())}") - - input_check("impurity", impurity, str) - - try: - assert impurity in list(ELEMENTS.keys()) - except AssertionError: - raise ValueError(f"impurity must be one of {list(ELEMENTS.keys())}") - - input_check("Zeff", Zeff, DataArray, ndim_to_check=2, strictly_positive=False) - - input_check( - "electron_temp", - electron_temp, - DataArray, - ndim_to_check=2, - strictly_positive=True, - ) - - asymmetry_parameter = asymmetry_parameters.sel(elements=impurity) - - impurity_mass_int = ELEMENTS[impurity][1] - - unified_atomic_mass_unit = 931.4941e6 # in eV/c^2 - impurity_mass = float(impurity_mass_int) * unified_atomic_mass_unit - - mean_charge = ELEMENTS[impurity][0] - - main_ion_mass_int = ELEMENTS[main_ion][1] - - main_ion_mass = float(main_ion_mass_int) * unified_atomic_mass_unit - - ion_temperature = ion_temperature.sel(elements=impurity) - - # mypy on the github CI suggests that * is an Unsupported operand type - # between float and DataArray, don't know how to fix yet so for now ignored - toroidal_rotation = 2.0 * ion_temperature * asymmetry_parameter # type: ignore - toroidal_rotation /= impurity_mass * ( - 1.0 - - (mean_charge * main_ion_mass * Zeff * electron_temp) # type: ignore - / (impurity_mass * (ion_temperature + Zeff * electron_temp)) - ) - - toroidal_rotation = toroidal_rotation**0.5 - - c = 3.0e8 # speed of light in vacuum - toroidal_rotation *= c - - return toroidal_rotation - - -class AsymmetryParameter(Operator): - """Calculate the asymmetry parameter from toroidal rotation. - - Parameters - ---------- - - Returns - ------- - asymmetry_parameter - xarray.DataArray containing asymmetry_parameter for a given impurity element - - """ - - ARGUMENT_TYPES: List[Union[DataType, EllipsisType]] = [] - - def __init__(self, sess: session.Session = session.global_session): - super().__init__(sess=sess) - - def return_types(self, *args: DataType) -> Tuple[Any, ...]: - return super().return_types(*args) - - def __call__( # type: ignore - self, - toroidal_rotations: DataArray, - ion_temperature: DataArray, - main_ion: str, - impurity: str, - Zeff: DataArray, - electron_temp: DataArray, - ): - """Calculates the asymmetry parameter from the toroidal rotation frequency. - - Parameters - ---------- - toroidal_rotations - xarray.DataArray containing toroidal rotation frequencies data. - In units of ms^-1. - ion_temperature - xarray.DataArray containing ion temperature data. In units of eV. - main_ion - Element symbol of main ion. - impurity - Element symbol of chosen impurity element. - Zeff - xarray.DataArray containing Z-effective data from diagnostics. - electron_temp - xarray.DataArray containing electron temperature data. In units of eV. - - Returns - ------- - asymmetry_parameter - xarray.DataArray containing data for asymmetry parameters - for the given impurity element - """ - input_check( - "toroidal_rotations", - toroidal_rotations, - DataArray, - ndim_to_check=3, - strictly_positive=False, - ) - - input_check( - "ion_temperature", - ion_temperature, - DataArray, - ndim_to_check=3, - strictly_positive=True, - ) - - input_check("main_ion", main_ion, str) - - try: - assert main_ion in list(ELEMENTS.keys()) - except AssertionError: - raise ValueError(f"main_ion must be one of {list(ELEMENTS.keys())}") - - input_check("impurity", impurity, str) - - try: - assert impurity in list(ELEMENTS.keys()) - except AssertionError: - raise ValueError(f"impurity must be one of {list(ELEMENTS.keys())}") - - input_check("Zeff", Zeff, DataArray, ndim_to_check=2, strictly_positive=False) - - input_check( - "electron_temp", - electron_temp, - DataArray, - ndim_to_check=2, - strictly_positive=True, - ) - - toroidal_rotations = toroidal_rotations.sel(elements=impurity) - - impurity_mass_int = ELEMENTS[impurity][1] - - unified_atomic_mass_unit = 931.4941e6 # in eV/c^2 - impurity_mass = float(impurity_mass_int) * unified_atomic_mass_unit - - mean_charge = ELEMENTS[impurity][0] - - main_ion_mass_int = ELEMENTS[main_ion][1] - - main_ion_mass = float(main_ion_mass_int) * unified_atomic_mass_unit - - ion_temperature = ion_temperature.sel(elements=impurity) - - c = 3.0e8 # speed of light in m/s - toroidal_rotations /= c - - # mypy on the github CI suggests that * is in an Unsupported operand type - # between float and DataArray, don't know how to fix yet so for now ignored - asymmetry_parameter = ( - impurity_mass * (toroidal_rotations**2) / (2.0 * ion_temperature) - ) - asymmetry_parameter *= 1.0 - ( - mean_charge * main_ion_mass * Zeff * electron_temp # type: ignore - ) / (impurity_mass * (ion_temperature + Zeff * electron_temp)) - - return asymmetry_parameter diff --git a/indica/operators/main_ion_density.py b/indica/operators/main_ion_density.py deleted file mode 100644 index 2d27b5bc..00000000 --- a/indica/operators/main_ion_density.py +++ /dev/null @@ -1,105 +0,0 @@ -"""Operator calculating the main ion density given the densities of impurities. -""" - -from typing import List -from typing import Tuple -from typing import Union - -from xarray.core.dataarray import DataArray - -from indica.datatypes import DataType -from .abstractoperator import EllipsisType -from .abstractoperator import Operator -from .. import session -from ..utilities import input_check - - -class MainIonDensity(Operator): - """Calculates the main ion density from given impurity densities and mean charge. - - Attributes - ---------- - ARGUMENT_TYPES: List[DataType] - Ordered list of the types of data expected for each argument of the - operator. - RESULT_TYPES: List[DataType] - Ordered list of the types of data returned by the operator. - - Returns - ------- - main_ion_density - xarray.DataArray of the main ion density. - - Methods - ------- - __call__(impurity_densities, electron_density, mean_charge) - Calculates the main ion density from given impurity densities and mean charge. - """ - - ARGUMENT_TYPES: List[Union[DataType, EllipsisType]] = [] - - RESULT_TYPES: List[Union[DataType, EllipsisType]] = [ - ("main_ion", "number_density"), - ] - - def __init__(self, sess: session.Session = session.global_session): - super().__init__(sess=sess) - - def return_types(self, *args: DataType) -> Tuple[DataType, ...]: - return super().return_types(*args) - - def __call__( # type: ignore - self, - impurity_densities: DataArray, - electron_density: DataArray, - mean_charge: DataArray, - ): - """Calculates the main ion density from given impurity densities - and mean charge. - - Parameters - ---------- - impurity_densities - xarray.DataArray of impurity densities for all impurity elements - of interest. - electron_density - xarray.DataArray of electron density - mean_charge - xarray.DataArray of mean charge of all impurity elements of interest. - This can be provided manually - (with dimensions of ["element", "rho_poloidal", "t]), - or can be passed as the results of MeanCharge.__call__ - - Returns - ------- - main_ion_density - xarray.DataArray of the main ion density. - """ - # no ndim check since impurity densities can have coords: - # [elements, rho, t] or [elements, R, z, t] - input_check( - "impurity_densities", - impurity_densities, - DataArray, - strictly_positive=False, - ) - - input_check( - "electron_density", - electron_density, - DataArray, - strictly_positive=False, - ) - - input_check( - "mean_charge", - mean_charge, - DataArray, - strictly_positive=False, - ) - - main_ion_density = electron_density - (mean_charge * impurity_densities).sum( - "element" - ) - - return main_ion_density diff --git a/indica/operators/mean_charge.py b/indica/operators/mean_charge.py deleted file mode 100644 index 8cd02a1d..00000000 --- a/indica/operators/mean_charge.py +++ /dev/null @@ -1,101 +0,0 @@ -"""Operator calculating the mean charge from the fractional abundance of all -ionisation charges of a given element. -""" - -from typing import List -from typing import Tuple -from typing import Union - -import numpy as np -from xarray.core.common import zeros_like -from xarray.core.dataarray import DataArray - -from .abstractoperator import EllipsisType -from .abstractoperator import Operator -from .. import session -from ..datatypes import DataType -from ..datatypes import ELEMENTS -from ..utilities import input_check - - -class MeanCharge(Operator): - """Calculate mean charge for a given element from its fractional abundance. - - Parameters - ---------- - - Returns - ------- - mean_charge - numpy.ndarray of mean charge of the given element. - - """ - - ARGUMENT_TYPES: List[Union[DataType, EllipsisType]] = [] - - RESULT_TYPES: List[Union[DataType, EllipsisType]] = [ - ("mean_charge", "impurity_element"), - ] - - def __init__(self, sess: session.Session = session.global_session): - super().__init__(sess=sess) - - def return_types(self, *args: DataType) -> Tuple[DataType, ...]: - return super().return_types(*args) - - def __call__(self, FracAbundObj: DataArray, element: str): # type: ignore - """Function to calculate the mean charge. - - Parameters - ---------- - FracAbundObj - numpy.ndarray describing the fractional abundance of the given element. - The first axis must correspond to the ionisation charges of the element. - element - Symbol of the element for which the mean charge is desired. - - Returns - ------- - mean_charge - numpy.ndarray of mean charge of the given element. - """ - - input_check( - "FracAbundObj", - FracAbundObj, - DataArray, - ndim_to_check=3, - strictly_positive=False, - ) - input_check("element", element, str) - - try: - assert element in ELEMENTS.keys() - except AssertionError: - raise ValueError( - f"Please input a single valid element from list:\ - {list(ELEMENTS.keys())}" - ) - - element_atomic_number = ELEMENTS[element][0] - - ionisation_charges = np.arange(0, element_atomic_number + 1) # type: ignore - - try: - assert ionisation_charges.shape[0] == FracAbundObj.shape[0] - except AssertionError: - raise AssertionError( - f"Number of ionisation charges in the \ - FractionalAbundance object do not match the expected number for the \ - element provided, {element}" - ) - - mean_charge = zeros_like(FracAbundObj) - mean_charge = mean_charge.isel(ion_charges=0) - mean_charge.drop_vars("ion_charges") - - mean_charge = np.sum( - ionisation_charges[:, np.newaxis, np.newaxis] * FracAbundObj, axis=0 - ) - - return mean_charge diff --git a/snippets/plot_jet.py b/snippets/plot_jet.py deleted file mode 100644 index 53248f95..00000000 --- a/snippets/plot_jet.py +++ /dev/null @@ -1,20 +0,0 @@ -import matplotlib.pylab as plt -import numpy as np - - -def plot_jet_wall( - filewall="/home/msertoli/work/datapool/wall_coords_jet.txt", divertor=True -): - """ - Plot JET first wall poloidal cross-section - """ - data = np.genfromtxt(filewall) - - plt.figure() - plt.plot(data[:, 0], data[:, 1], color="black", linewidth=2.5) - if divertor: - plt.xlim(2.3, 3.0) - plt.ylim(-1.8, -1.3) - plt.gca().set_aspect("equal", adjustable="box") - plt.xlabel("R (m)") - plt.ylabel("z (m)") diff --git a/snippets/read_KT7D.py b/snippets/read_KT7D.py deleted file mode 100644 index 6b63bd55..00000000 --- a/snippets/read_KT7D.py +++ /dev/null @@ -1,120 +0,0 @@ -import getdat as gd -import numpy as np - - -def get_kt7c(pulse, skip=None, trim40=False, backgrd=True, foregrd=False): - - if skip is None: - skip = 5 - - # get data - nwds = 0 - data_node = "df/t7-spec:003" - data, tvec, nwds, title, units, ier = gd.getdat(data_node, pulse, nwds=nwds) - ndata = nwds - - # get time vector - nwds_tim = 0 - tvec_tim, nwds_tim, ier_tim = gd.gettim(data_node, pulse, nwds=nwds_tim) - - # get number of frames - nframe_node = "DF/T7-NFRAME npixel * nframe: - data = data[0 : npixel * nframe] - elif ndata < npixel * nframe: - nframe = ndata // npixel - data = data[0 : npixel * nframe] - - # calculate exposure time - treadout = tvec_tim[0:nframe] - exp_time = treadout * 0.0 - exp_time[1:] = treadout[1:] - treadout[0:-1] - exp_time[0] = exp_time[1] # bald-faced lie (unknown exp for first frame) - exp_time = exp_time.round(decimals=4) - time = treadout - (exp_time / 2.0) - - # reshape data array - shape = (nframe, npixel) - data = np.reshape(data, shape) - - # keep only used pixels - npixel = 1024 - pixel = np.arange(npixel) - data = data[:, 0:npixel] - - # Calculate background or foreground: - # - background: exclude first 5 frames & the 2 'move' frames just before 40s - # - foreground: average last 20 frames - # In both cases normalise to exp_time (can vary during the discharge) - bkd = np.zeros(npixel) - if backgrd and not foregrd: - ind_bkd = np.argwhere(time < 40.0)[5:-2].flatten() - bkd = [] - for i in ind_bkd: - bkd.append(data[i, :] / exp_time[i]) - bkd = np.array(bkd).mean(axis=0).flatten() - - fgd = np.zeros(npixel) - if foregrd: - ind_fgd = range(nframe - 20, nframe) - fgd = [] - for i in ind_fgd: - fgd.append(data[i, :] / exp_time[i]) - fgd = np.array(fgd).mean(axis=0).flatten() - - # Normalise to exposure time (can vary during the discharge) and - # subtract background/foreground - for i in range(len(time)): - data[i, :] = data[i, :] / exp_time[i] - bkd - fgd - - # Retain data only for time > 40 s - if trim40: - indx40 = np.argwhere(time > 40.0).flatten() - data = data[indx40, :] - time = time[indx40] - treadout = treadout[indx40] - exp_time = exp_time[indx40] - - # Moc-up wavelength calibration: pixel offset accounts for changes - # in detector position - if pulse >= 80685: - pix_offs = +149 - elif pulse >= 80724: - pix_offs = 0 - elif pulse >= 84931: - pix_offs = -24 - elif pulse >= 89473: - pix_offs = -2 - else: - pix_offs = 0 - - c = [0.0] * 3 - c[0] = 4.0351381 - c[1] = 0.0033944632 - c[2] = -3.4947697e-07 - - # wavelength (nm) - pix = pixel + pix_offs - wave = c[0] + c[1] * pix + c[2] * pix**2 - - out = { - "data": data, - "time": time, - "treadout": treadout, - "exptime": exp_time, - "pixel": pixel, - "wave": wave, - } - - return out diff --git a/snippets/test_get_efit.py b/snippets/test_get_efit.py deleted file mode 100644 index 1a304299..00000000 --- a/snippets/test_get_efit.py +++ /dev/null @@ -1,26 +0,0 @@ -import getpass - -from indica.readers import PPFReader - -reader = PPFReader(90279, 45.0, 50.0) -if reader.requires_authentication: - user = input("JET username: ") - password = getpass.getpass("JET password: ") - assert reader.authenticate(user, password) - -data = reader.get("jetppf", "efit", 0) -print("f value") -print("=======\n") -print(data["f"]) -print("\n\n") -print("psi") -print("===\n") -print(data["psi"]) -print("\n\n") -print("Rmag") -print("====\n") -print(data["rmag"]) -print("\n\n") -print("Rbnd") -print("====\n") -print(data["rbnd"]) diff --git a/snippets/wall_coords_jet.txt b/snippets/wall_coords_jet.txt deleted file mode 100644 index b5b65582..00000000 --- a/snippets/wall_coords_jet.txt +++ /dev/null @@ -1,251 +0,0 @@ -3.28315 -1.12439 -3.31192 -1.08316 -3.32836 -1.06314 -3.35244 -1.03867 -3.37323 -1.0172 -3.42329 -0.95992 -3.44728 -0.93229 -3.49433 -0.87186 -3.5168 -0.84284 -3.55911 -0.78155 -3.58053 -0.75015 -3.61927 -0.68679 -3.63903 -0.6539 -3.67364 -0.58769 -3.68796 -0.56088 -3.7223 -0.48496 -3.73497 -0.4576 -3.76821 -0.37137 -3.77584 -0.35239 -3.80258 -0.2692 -3.81082 -0.24458 -3.83331 -0.15797 -3.83964 -0.13481 -3.85652 -0.05075 -3.86207 -0.02427 -3.87519 0.06852 -3.87835 0.08885 -3.88567 0.17625 -3.88793 0.1963 -3.89046 0.29045 -3.89144 0.31339 -3.88863 0.40756 -3.8884 0.42674 -3.88031 0.51993 -3.87894 0.53958 -3.86556 0.63228 -3.86349 0.64971 -3.84449 0.74347 -3.84091 0.76273 -3.81715 0.85325 -3.81303 0.87053 -3.78365 0.96125 -3.77904 0.97699 -3.74408 1.06719 -3.73821 1.08341 -3.69868 1.17046 -3.69176 1.18659 -3.67489 1.2188 -3.66741 1.23638 -3.6373 1.33388 -3.64211 1.40768 -3.62136 1.42656 -3.62076 1.4271 -3.59407 1.45138 -3.59348 1.45192 -3.56679 1.4762 -3.5662 1.47674 -3.53951 1.50102 -3.53892 1.50156 -3.51223 1.52584 -3.51164 1.52638 -3.48495 1.55066 -3.48436 1.55119 -3.45767 1.57547 -3.45708 1.57601 -3.43039 1.60029 -3.4298 1.60083 -3.40311 1.62511 -3.40252 1.62565 -3.38176 1.64453 -3.33154 1.70412 -3.28182 1.73872 -3.18634 1.81753 -3.13665 1.85212 -3.00098 1.88341 -2.86885 1.93955 -2.85247 1.94527 -2.77562 1.96797 -2.75763 1.97196 -2.67896 1.98285 -2.65886 1.98403 -2.57787 1.9829 -2.56057 1.98112 -2.48011 1.96774 -2.46596 1.96418 -2.38844 1.93892 -2.37422 1.93306 -2.29805 1.89475 -2.28755 1.88838 -2.19539 1.82284 -2.18241 1.82372 -2.1657 1.79082 -2.16533 1.7901 -2.14899 1.75794 -2.14863 1.75722 -2.13229 1.72506 -2.13193 1.72434 -2.11558 1.69217 -2.11522 1.69146 -2.09888 1.65929 -2.09852 1.65858 -2.08218 1.62641 -2.08181 1.6257 -2.06816 1.59882 -2.06756 1.59819 -2.05467 1.5645 -2.05438 1.56375 -2.04148 1.53005 -2.0412 1.52931 -2.0283 1.49561 -2.02801 1.49486 -2.01512 1.46117 -2.01483 1.46042 -2.00193 1.42672 -2.00164 1.42597 -1.98875 1.39228 -1.98846 1.39153 -1.97556 1.35783 -1.97528 1.35709 -1.9613 1.32058 -1.92992 1.27302 -1.92697 1.26095 -1.92259 1.25401 -1.94246 1.23457 -1.92727 1.15832 -1.92496 1.13801 -1.91241 1.06067 -1.90969 1.03999 -1.89845 0.96207 -1.89568 0.94009 -1.88577 0.86238 -1.8830 0.84067 -1.87309 0.76296 -1.87038 0.74168 -1.86048 0.66408 -1.85836 0.64287 -1.84987 0.56549 -1.84816 0.54523 -1.84184 0.4671 -1.84095 0.44616 -1.83724 0.36833 -1.83704 0.34737 -1.83592 0.27002 -1.83642 0.2485 -1.83787 0.17099 -1.83907 0.14967 -1.84313 0.07136 -1.84502 0.05067 -1.85168 -0.02749 -1.85424 -0.04782 -1.86338 -0.12484 -1.86665 -0.14554 -1.87848 -0.22313 -1.88235 -0.24315 -1.89673 -0.32025 -1.90128 -0.34019 -1.91822 -0.41681 -1.92341 -0.43655 -1.94275 -0.51204 -1.94865 -0.53185 -1.97056 -0.60693 -1.95973 -0.62652 -1.96175 -0.65756 -2.00911 -0.78399 -2.02042 -0.8113 -2.02073 -0.81204 -2.03454 -0.84537 -2.03484 -0.84612 -2.04865 -0.87945 -2.04896 -0.88019 -2.06276 -0.91352 -2.06307 -0.91426 -2.07688 -0.9476 -2.07718 -0.94834 -2.09099 -0.98167 -2.0913 -0.98241 -2.10511 -1.01574 -2.10549 -1.01667 -2.1193 -1.0500 -2.1196 -1.05074 -2.13341 -1.08407 -2.13372 -1.08482 -2.14752 -1.11815 -2.14783 -1.11889 -2.16164 -1.15222 -2.16194 -1.15296 -2.17575 -1.1863 -2.17606 -1.18704 -2.18986 -1.22037 -2.19017 -1.22111 -2.20149 -1.24842 -2.14463 -1.27494 -2.29362 -1.31483 -2.29362 -1.33144 -2.29544 -1.33443 -2.35993 -1.33443 -2.39619 -1.37323 -2.40915 -1.4003 -2.41225 -1.42198 -2.41293 -1.43148 -2.41293 -1.46854 -2.41224 -1.47678 -2.40762 -1.50441 -2.39801 -1.51641 -2.41921 -1.59223 -2.42117 -1.61022 -2.4188 -1.64283 -2.41628 -1.6561 -2.40573 -1.68971 -2.31498 -1.7387 -2.35349 -1.7387 -2.37428 -1.73504 -2.42744 -1.71349 -2.44623 -1.70983 -2.52369 -1.70983 -2.52459 -1.69997 -2.55911 -1.65498 -2.55296 -1.63799 -2.57391 -1.6018 -2.63299 -1.61714 -2.63369 -1.61989 -2.6938 -1.6355 -2.69434 -1.63821 -2.75443 -1.65481 -2.75517 -1.65658 -2.81471 -1.67203 -2.81467 -1.70788 -2.80425 -1.71158 -2.85703 -1.71158 -2.87846 -1.71602 -2.93644 -1.74139 -2.95732 -1.74595 -2.98698 -1.74595 -2.89768 -1.68233 -2.88199 -1.62282 -2.88163 -1.5916 -2.90045 -1.51041 -2.89049 -1.49841 -2.88786 -1.48925 -2.88591 -1.47397 -2.88591 -1.43566 -2.88946 -1.41714 -2.90082 -1.39278 -2.91335 -1.37624 -2.96348 -1.33481 -3.00975 -1.33481 -3.06005 -1.29777 -3.19404 -1.21404 -3.20225 -1.20891 -3.30634 -1.20891 -3.28315 -1.12439 diff --git a/tests/unit/fake_equilibrium.py b/tests/unit/fake_equilibrium.py deleted file mode 100644 index 0ac6ea5d..00000000 --- a/tests/unit/fake_equilibrium.py +++ /dev/null @@ -1,251 +0,0 @@ -"""A subclass of :py:class:`indica.equilibrium.Equilibrium` which fakes -the implementation.""" - -from itertools import product -from unittest.mock import MagicMock - -from hypothesis.strategies import composite -from hypothesis.strategies import floats -from hypothesis.strategies import one_of -from hypothesis.strategies import sampled_from -import numpy as np -from xarray import DataArray - -from indica.equilibrium import Equilibrium - - -FLUX_TYPES = ["poloidal", "toroidal"] - - -@composite -def flux_types(draw): - return draw(sampled_from(FLUX_TYPES)) - - -class FakeEquilibrium(Equilibrium): - """A class which fakes the behaviour of an Equilibrium object. Flux - surface and magnetic fields are taken to vary in an elliptical profile - away from the magnetif axis. - - Fluxes have form $$r^2 = \\frac{(R-R_{mag})^2}{a^2} + - \\frac{(z-z_{mag})^2}{b^2},$$ where $r = \\rho^n(1 + \\alpha t)$ and $a$, $b$, - $n$ and $\\alpha$ are parameters specified by the user at instantiation. - - $B_{tot}$ varies according to a different equation: - $$B_{tot} = \\frac{(1 + \\alpha t) a}{1 + bR} + (z - z_{mag}).$$ - - Paramter values may be specified at instantiation using - keyword-arguments of the constructor. There are also default - values available for flux kinds ``poloidal``, ``toroidal``, and - the total magnetic field strength. - - Parameters - ---------- - Rmag : float - Major radius of the magnetic axis - zmag : float - Vertical position of the magnetic axis - kwargs : Dict[str, float] - Values for parameters describing the equilibrium profile. Keys take the - form ``_``. The ```` may be any - string which will be accpeted as a ``kind`` argument in methods such as - :py:meth:`flux_coords``, or ``Btot`` if the paremeter is describing the - profile of total magnetic field strength. The ```` may - be ``a``, ``b``, ``n``, or ``alpha``. - - """ - - DEFAULT_PARAMS = { - "poloidal_a": 0.5, - "poloidal_b": 1.0, - "poloidal_n": 1, - "poloidal_alpha": 0.01, - "toroidal_a": 0.7, - "toroidal_b": 1.4, - "toroidal_n": 1, - "toroidal_alpha": -0.00005, - "Btot_a": 1.0, - "Btot_b": 1.0, - "Btot_alpha": 0.001, - } - - def __init__( - self, - Rmag=3.0, - zmag=0.0, - default_t=DataArray([0.0, 5e3], dims="t"), - Bmax=1.0, - **kwargs - ): - ones = DataArray(np.ones_like(default_t), coords=[("t", default_t)]) - self.rmag = np.abs(Rmag) * ones - self.zmag = zmag * ones - self.parameters = kwargs - for k, v in self.DEFAULT_PARAMS.items(): - if k not in self.parameters: - self.parameters[k] = v - self.default_t = default_t - self.prov_id = MagicMock() - self.provenance = MagicMock() - self._session = MagicMock() - - def Btot(self, R, z, t=None): - if t is None: - t = self.default_t - zmag = self.zmag - else: - zmag = self.zmag.interp( - t=t, method="nearest", kwargs={"fill_value": "extrapolate"} - ) - return ( - (1 + self.parameters["Btot_alpha"] * t) - * self.parameters["Btot_a"] - / (1 + self.parameters["Btot_b"] * R) - + z - - zmag, - t, - ) - - def enclosed_volume(self, rho, t=None, kind="poloidal"): - if t is None: - t = self.default_t - rmag = self.rmag - else: - rmag = self.rmag.interp( - t=t, method="nearest", kwargs={"fill_value": "extrapolate"} - ) - a = self.parameters[kind + "_a"] - b = self.parameters[kind + "_b"] - n = self.parameters[kind + "_n"] - alpha = self.parameters[kind + "_alpha"] - vol = 2 * np.pi**2 * a * b * rho ** (2 * n) * (1 + alpha * t) ** 2 * rmag - - # blank area variable to return so that tests pass - area = 0 - return vol, t, area - - def invert_enclosed_volume(self, vol, t=None, kind="poloidal"): - if t is None: - t = self.default_t - rmag = self.rmag - else: - rmag = self.rmag.interp( - t=t, method="nearest", kwargs={"fill_value": "extrapolate"} - ) - a = self.parameters[kind + "_a"] - b = self.parameters[kind + "_b"] - n = self.parameters[kind + "_n"] - alpha = self.parameters[kind + "_alpha"] - rho = (vol / (2 * np.pi**2 * a * b * (1 + alpha * t) ** 2 * rmag)) ** ( - 0.5 / n - ) - return rho, t - - def R_hfs(self, rho, t=None, kind="poloidal"): - R, _, t = self.spatial_coords(rho, np.pi, t, kind) - return R, t - - def R_lfs(self, rho, t=None, kind="poloidal"): - R, _, t = self.spatial_coords(rho, 0.0, t, kind) - return R, t - - def minor_radius(self, rho, theta, t=None, kind="poloidal"): - if t is None: - t = self.default_t - r = rho ** self.parameters[kind + "_n"] * ( - 1 + self.parameters[kind + "_alpha"] * t - ) - return r, t - - def flux_coords(self, R, z, t=None, kind="poloidal"): - if t is None: - t = self.default_t - rmag = self.rmag - zmag = self.zmag - else: - rmag = self.rmag.interp( - t=t, method="nearest", kwargs={"fill_value": "extrapolate"} - ) - zmag = self.zmag.interp( - t=t, method="nearest", kwargs={"fill_value": "extrapolate"} - ) - rho = ( - ( - (R - rmag) ** 2 / self.parameters[kind + "_a"] ** 2 - + (z - zmag) ** 2 / self.parameters[kind + "_b"] ** 2 - ) - / (1 + self.parameters[kind + "_alpha"] * t) ** 2 - ) ** (1 / (2 * self.parameters[kind + "_n"])) - theta = np.arctan2((z - zmag), (R - rmag)) - return rho, theta, t - - def spatial_coords(self, rho, theta, t=None, kind="poloidal"): - if t is None: - t = self.default_t - rmag = self.rmag - zmag = self.zmag - else: - rmag = self.rmag.interp( - t=t, method="nearest", kwargs={"fill_value": "extrapolate"} - ) - zmag = self.zmag.interp( - t=t, method="nearest", kwargs={"fill_value": "extrapolate"} - ) - tan_theta = np.tan(theta) - dR = np.sign(np.cos(theta)) * np.sqrt( - ( - rho ** self.parameters[kind + "_n"] - * (1 + self.parameters[kind + "_alpha"] * t) - ) - ** 2 - / ( - 1 / self.parameters[kind + "_a"] ** 2 - + (tan_theta / self.parameters[kind + "_b"]) ** 2 - ) - ) - dz = tan_theta * dR - return rmag + dR, zmag + dz, t - - def convert_flux_coords( - self, rho, theta, t=None, from_kind="poloidal", to_kind="toroidal" - ): - R, z, t = self.spatial_coords(rho, theta, t, from_kind) - return self.flux_coords(R, z, t, to_kind) - - -@composite -def fake_equilibria( - draw, - Rmag, - zmag, - default_t=DataArray([0.0, 500.0], dims="t"), - flux_types=FLUX_TYPES, - **kwargs -): - """Generate instances of the FakeEquilibrium class, with the specified - flux types. Parameters will be drawn from the ``floats`` strategy, - unless explicitely specified as a keyword arguments. These - parameters should take the form ``_a``, - ``_b``, ``_n`` and ``_alpha``. In - addition to the flux types specified as an argument, you may - specify the parameter values for ``Btot``. - - """ - param_types = { - "a": floats(-0.9, 9.0).map(lambda x: x + 1.0), - "b": floats(-0.9, 9.0).map(lambda x: x + 1.0), - "n": one_of(sampled_from([1, 2, 0.5]), floats(0.2, 4.0)), - "alpha": floats(-0.02, 0.09).map(lambda x: x + 0.01), - } - param_values = kwargs - for flux, param in product(flux_types, param_types): - param_name = flux + "_" + param - if param_name not in param_values: - param_values[param_name] = draw(param_types[param]) - if "Btot_a" in flux_types and "Btot_a" not in param_values: - param_values["Btot_a"] = draw(floats(1e-3, 1e3)) - if "Btot_b" in flux_types and "Btot_b" not in param_values: - param_values["Btot_b"] = draw(floats(1e-5, 1e-2)) - if "Btot_alpha" in flux_types and "Btot_alpha" not in param_values: - param_values["Btot_alpha"] = draw(floats(-1e-3, 1e-3)) - return FakeEquilibrium(Rmag, zmag, default_t, **param_values) diff --git a/tests/unit/readers/test_abstract_reader_pytest.py b/tests/unit/readers/test_abstract_reader_pytest.py deleted file mode 100644 index cccd6aba..00000000 --- a/tests/unit/readers/test_abstract_reader_pytest.py +++ /dev/null @@ -1,507 +0,0 @@ -"""Test methods present on the base class DataReader.""" - -from copy import deepcopy -from numbers import Number -from typing import Any -from typing import Dict -from typing import List -from typing import Set -from typing import Tuple - -import numpy as np - -from indica import session -from indica.numpy_typing import RevisionLike -from indica.readers import DataReader -from indica.readers.available_quantities import AVAILABLE_QUANTITIES - - -# TODO these values should come from the machine dimensions variable of the reader - -TSTART = 0 -TEND = 10 - - -class Reader(DataReader): - """Class to read fake data""" - - MACHINE_DIMS = ((1.83, 3.9), (-1.75, 2.0)) - INSTRUMENT_METHODS = { - "thomson_scattering": "get_thomson_scattering", - "equilibrium": "get_equilibrium", - "cyclotron_emissions": "get_cyclotron_emissions", - "charge_exchange": "get_charge_exchange", - "spectrometer": "get_spectrometer", - "bremsstrahlung_spectroscopy": "get_bremsstrahlung_spectroscopy", - "radiation": "get_radiation", - "helike_spectroscopy": "get_helike_spectroscopy", - "interferometry": "get_interferometry", - "diode_filters": "get_diode_filters", - } - - def __init__( - self, - pulse: int, - tstart: float, - tend: float, - server: str = "", - default_error: float = 0.05, - max_freq: float = 1e6, - session: session.Session = session.global_session, - ): - self._reader_cache_id = "" - self.NAMESPACE: Tuple[str, str] = ("", server) - super().__init__( - tstart, - tend, - max_freq, - session, - pulse=pulse, - server=server, - default_error=default_error, - ) - self.pulse = pulse - - def _get_charge_exchange( - self, - uid: str, - instrument: str, - revision: RevisionLike, - quantities: Set[str], - ) -> Dict[str, Any]: - - Rmin, Rmax = self.MACHINE_DIMS[0][0], self.MACHINE_DIMS[0][1] - zmin, zmax = self.MACHINE_DIMS[1][0], self.MACHINE_DIMS[1][1] - - results: Dict[str, Any] = { - "length": np.random.randint(4, 20), - "machine_dims": self.MACHINE_DIMS, - } - dt = np.random.uniform(0.001, 1.0) - times = np.arange(TSTART, TEND, dt) - wavelength = np.arange(520, 530, 0.1) - nt = times.shape[0] - results["times"] = times - results["wavelength"] = wavelength - results["spectra"] = np.random.uniform( - 10, 10.0e3, (nt, results["length"], wavelength.size) - ) - results["fit"] = deepcopy(results["spectra"]) - results["texp"] = np.full_like(times, dt) - - results["location"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - results["direction"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - - results["element"] = "element" - results["revision"] = np.random.randint(0, 10) - results["x"] = np.random.uniform(Rmin, Rmax, (results["length"],)) - results["y"] = np.random.uniform(Rmin, Rmax, (results["length"],)) - results["z"] = np.random.uniform(zmin, zmax, (results["length"],)) - results["R"] = np.random.uniform(Rmin, Rmax, (results["length"],)) - results["ti"] = np.random.uniform(10, 10.0e3, (nt, results["length"])) - results["vtor"] = np.random.uniform(1.0e2, 1.0e6, (nt, results["length"])) - results["angf"] = np.random.uniform(1.0e2, 1.0e6, (nt, results["length"])) - results["conc"] = np.random.uniform(1.0e-6, 1.0e-1, (nt, results["length"])) - results["bad_channels"] = [] - - for quantity in quantities: - results[f"{quantity}_records"] = [ - f"{quantity}_R_path", - f"{quantity}_z_path", - f"{quantity}_element_path", - f"{quantity}_time_path", - f"{quantity}_ti_path", - f"{quantity}_angf_path", - f"{quantity}_conc_path", - ] - - return results - - def _get_spectrometer( - self, - uid: str, - instrument: str, - revision: RevisionLike, - quantities: Set[str], - ) -> Dict[str, Any]: - - results: Dict[str, Any] = { - "length": np.random.randint(4, 20), - "machine_dims": self.MACHINE_DIMS, - } - dt = np.random.uniform(0.001, 1.0) - times = np.arange(TSTART, TEND, dt) - wavelength = np.arange(520, 530, 0.1) - nt = times.shape[0] - results["times"] = times - results["wavelength"] = wavelength - results["spectra"] = np.random.uniform( - 10, 10.0e3, (nt, results["length"], wavelength.size) - ) - - results["location"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - results["direction"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - - results["revision"] = np.random.randint(0, 10) - - for quantity in quantities: - results[f"{quantity}_records"] = [ - f"{quantity}_time_path", - f"{quantity}_spectra_path", - ] - - return results - - def _get_thomson_scattering( - self, - uid: str, - instrument: str, - revision: RevisionLike, - quantities: Set[str], - ) -> Dict[str, Any]: - - Rmin, Rmax = self.MACHINE_DIMS[0][0], self.MACHINE_DIMS[0][1] - zmin, zmax = self.MACHINE_DIMS[1][0], self.MACHINE_DIMS[1][1] - - results: Dict[str, Any] = { - "length": np.random.randint(4, 20), - "machine_dims": self.MACHINE_DIMS, - } - - dt = np.random.uniform(0.001, 1.0) - times = np.arange(TSTART, TEND, dt) - nt = times.shape[0] - results["times"] = times - results["revision"] = np.random.randint(0, 10) - - results["x"] = np.random.uniform(Rmin, Rmax, (results["length"],)) - results["y"] = np.random.uniform(Rmin, Rmax, (results["length"],)) - results["z"] = np.random.uniform(zmin, zmax, (results["length"],)) - results["R"] = np.random.uniform(Rmin, Rmax, (results["length"],)) - results["chi2"] = np.random.uniform(0, 2.0, (nt, results["length"])) - results["te"] = np.random.uniform(10, 10.0e3, (nt, results["length"])) - results["ne"] = np.random.uniform(1.0e16, 1.0e21, (nt, results["length"])) - results["bad_channels"] = [] - - for quantity in quantities: - results[f"{quantity}_records"] = [ - f"{quantity}_Rz_path", - f"{quantity}_value_path", - f"{quantity}_error_path", - ] - - return results - - def _get_equilibrium( - self, - uid: str, - calculation: str, - revision: RevisionLike, - quantities: Set[str], - ) -> Dict[str, Any]: - - Rmin, Rmax = self.MACHINE_DIMS[0][0], self.MACHINE_DIMS[0][1] - zmin, zmax = self.MACHINE_DIMS[1][0], self.MACHINE_DIMS[1][1] - - results: Dict[str, Any] = {} - - dt = np.random.uniform(0.001, 1.0) - times = np.arange(TSTART, TEND, dt) - results["times"] = times - nt = times.shape[0] - nrho = np.random.randint(20, 40) - - results["element"] = "element" - - results["R"] = np.random.uniform(Rmin, Rmax, (nrho,)) - results["z"] = np.random.uniform(zmin, zmax, (nrho,)) - - results["rgeo"] = np.random.uniform(Rmin, Rmax, (nt,)) - results["rmag"] = np.random.uniform(Rmin, Rmax, (nt,)) - results["zmag"] = np.random.uniform(zmin, zmax, (nt,)) - results["ipla"] = np.random.uniform(1.0e4, 1.0e6, (nt,)) - results["wp"] = np.random.uniform(1.0e3, 1.0e5, (nt,)) - results["df"] = np.random.uniform(0, 1, (nt,)) - results["faxs"] = np.random.uniform(1.0e-6, 0.1, (nt,)) - results["fbnd"] = np.random.uniform(-1, 1, (nt,)) - - results["psin"] = np.random.uniform(0, 1, (nrho,)) - results["psi_r"] = np.random.uniform(Rmin, Rmax, (nrho,)) - results["psi_z"] = np.random.uniform(zmin, zmax, (nrho,)) - - results["f"] = np.random.uniform(1.0e-6, 0.1, (nt, nrho)) - results["ftor"] = np.random.uniform(1.0e-4, 1.0e-2, (nt, nrho)) - results["ajac"] = np.random.uniform(1.0e-3, 2.0, (nt, nrho)) - results["vjac"] = np.random.uniform(1.0e-3, 2.0, (nt, nrho)) - results["rmji"] = np.random.uniform(Rmin, Rmax, (nt, nrho)) - results["rmjo"] = np.random.uniform(Rmin, Rmax, (nt, nrho)) - results["rbnd"] = np.random.uniform(Rmin, Rmax, (nt, nrho)) - results["zbnd"] = np.random.uniform(zmin, zmax, (nt, nrho)) - results["psi"] = np.random.uniform(-1, 1, (nt, nrho, nrho)) - - results["revision"] = np.random.randint(0, 10) - - for quantity in quantities: - results[f"{quantity}_records"] = [f"{quantity}_records"] - results["psi_records"] = ["value_records", "R_records", "z_records"] - return results - - def _get_radiation( - self, - uid: str, - instrument: str, - revision: RevisionLike, - quantities: Set[str], - ) -> Dict[str, Any]: - - results: Dict[str, Any] = { - "length": np.random.randint(4, 20), - "machine_dims": self.MACHINE_DIMS, - } - - results["revision"] = np.random.randint(0, 10) - dt = np.random.uniform(0.001, 1.0) - times = np.arange(TSTART, TEND, dt) - results["times"] = times - nt = times.shape[0] - results["location"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - results["direction"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - - results["times"] = times - results["brightness"] = np.random.uniform(0, 1.0e6, (nt, results["length"])) - - results["brightness_records"] = ["brightness_records"] * results["length"] - - return results - - def _get_bremsstrahlung_spectroscopy( - self, - uid: str, - instrument: str, - revision: RevisionLike, - quantities: Set[str], - ) -> Dict[str, Any]: - - results: Dict[str, Any] = { - "length": np.random.randint(4, 20), - "machine_dims": self.MACHINE_DIMS, - } - results["revision"] = np.random.randint(0, 10) - dt = np.random.uniform(0.001, 1.0) - times = np.arange(TSTART, TEND, dt) - results["times"] = times - nt = times.shape[0] - - results["location"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - results["direction"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - - quantity = "zeff" - results[quantity] = np.random.uniform(0, 1.0e6, (nt, results["length"])) - - results[f"{quantity}_records"] = [ - f"{quantity}_path_records", - f"{quantity}_los_records", - ] - - return results - - def _get_helike_spectroscopy( - self, - uid: str, - instrument: str, - revision: RevisionLike, - quantities: Set[str], - ) -> Dict[str, Any]: - - nwavelength = np.random.randint(256, 1024) - wavelength_start, wavelength_end = 3.8, 4.0 - - results: Dict[str, Any] = { - "length": np.random.randint(4, 20), - "machine_dims": self.MACHINE_DIMS, - } - results["revision"] = np.random.randint(0, 10) - dt = np.random.uniform(0.001, 1.0) - times = np.arange(TSTART, TEND, dt) - results["times"] = times - nt = times.shape[0] - - results["location"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - results["direction"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - - results["wavelength"] = np.linspace( - wavelength_start, wavelength_end, nwavelength - ) - - for quantity in quantities: - if quantity == "spectra": - results[quantity] = np.random.uniform( - 0, 1.0e6, (nt, results["length"], nwavelength) - ) - else: - results[quantity] = np.random.uniform(0, 1.0e4, (nt, results["length"])) - - results[f"{quantity}_records"] = [ - f"{quantity}_path_records", - ] - - return results - - def _get_diode_filters( - self, - uid: str, - instrument: str, - revision: RevisionLike, - quantities: Set[str], - ) -> Dict[str, Any]: - - results: Dict[str, Any] = { - "length": np.random.randint(4, 20), - "machine_dims": self.MACHINE_DIMS, - } - - results["revision"] = np.random.randint(0, 10) - dt = np.random.uniform(0.001, 1.0) - times = np.arange(TSTART, TEND, dt) - results["times"] = times - nt = times.shape[0] - - results["location"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - results["direction"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - results["labels"] = np.array(["label"] * results["length"]) - - for quantity in quantities: - results[quantity] = np.random.uniform(0, 1.0e6, (nt, results["length"])) - - results[f"{quantity}_records"] = [ - f"{quantity}_path_records", - ] - results[f"{quantity}_error_records"] = [ - f"{quantity}_error_path_records", - ] - - return results - - def _get_interferometry( - self, - uid: str, - instrument: str, - revision: RevisionLike, - quantities: Set[str], - ) -> Dict[str, Any]: - - results: Dict[str, Any] = { - "length": np.random.randint(4, 20), - "machine_dims": self.MACHINE_DIMS, - } - - results["revision"] = np.random.randint(0, 10) - dt = np.random.uniform(0.001, 1.0) - times = np.arange(TSTART, TEND, dt) - results["times"] = times - nt = times.shape[0] - - results["location"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - results["direction"] = np.array([[1.0, 2.0, 3.0]] * results["length"]) - for quantity in quantities: - results[quantity] = np.random.uniform(0, 1.0e6, (nt, results["length"])) - - results[f"{quantity}_records"] = [ - f"{quantity}_path_records", - ] - results[f"{quantity}_error_records"] = [ - f"{quantity}_error_path_records", - ] - - return results - - def _get_bad_channels( - self, uid: str, instrument: str, quantity: str - ) -> List[Number]: - return [] - - def _set_times_item( - self, - results: Dict[str, Any], - times: np.ndarray, - ): - if "times" not in results: - times = times - - def close(self): - del self._client - - def requires_authentication(self): - return True - - -def _test_get_methods( - instrument="ts", - nsamples=1, -): - """ - Generalised test for all get methods of the abstractreader - """ - - for i in range(nsamples): - reader = Reader( - 1, - TSTART, - TEND, - ) - - quantities = set(AVAILABLE_QUANTITIES[reader.INSTRUMENT_METHODS[instrument]]) - - results = reader.get("", instrument, 0, quantities) - - # Check whether data is as expected - for q, actual, expected in [(q, results[q], results[q]) for q in quantities]: - assert np.all(actual.values == expected) - - -def test_get_thomson_scattering(): - _test_get_methods(instrument="thomson_scattering", nsamples=10) - - -def test_get_charge_exchange(): - _test_get_methods(instrument="charge_exchange", nsamples=10) - - -def test_get_spectrometer(): - _test_get_methods(instrument="spectrometer", nsamples=10) - - -def test_get_equilibrium(): - _test_get_methods(instrument="equilibrium", nsamples=10) - - -def test_get_radiation(): - _test_get_methods(instrument="radiation", nsamples=10) - - -def test_get_bremsstrahlung_spectroscopy(): - _test_get_methods( - instrument="bremsstrahlung_spectroscopy", - nsamples=10, - ) - - -def test_get_helike_spectroscopy(): - _test_get_methods( - instrument="helike_spectroscopy", - nsamples=10, - ) - - -def test_get_diode_filters(): - _test_get_methods( - instrument="diode_filters", - nsamples=10, - ) - - -def test_get_interferometry(): - _test_get_methods( - instrument="interferometry", - nsamples=10, - ) diff --git a/tests/unit/test_offset.py b/tests/unit/test_offset.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/unit/test_session.py b/tests/unit/test_session.py index 5a076fed..67b3f0ab 100644 --- a/tests/unit/test_session.py +++ b/tests/unit/test_session.py @@ -70,67 +70,6 @@ def test_session_context_manager(): assert session.global_session == new_session assert session.global_session == old_session - -# @given(emails()) -# def test_session_begin(email): -# old_global = session.global_session -# try: -# Session.begin(email) -# assert session.global_session != old_global -# assert session.global_session._user[0].identifier.localpart == email -# finally: -# session.global_session = old_global - - -# @given( -# emails(), lists(from_regex("[a-z0-9]+", fullmatch=True), unique=True, min_size=1) -# ) -# def test_push_pop_agents(email, agent_ids): -# assume(all(ident != email for ident in agent_ids)) -# session = Session(email) -# agents = [] -# original_agent = session._user[0] -# for ident in agent_ids: -# agents.append(session.prov.agent(ident)) -# session.push_agent(agents[-1]) -# assert session.agent is agents[-1] -# for agent in agents[::-1]: -# popped = session.pop_agent() -# assert popped is agent -# delegation = next( -# iter( -# filter( -# lambda x: x.get_attribute("prov:delegate") == {agent.identifier}, -# session.prov.get_records(prov.ProvDelegation), -# ) -# ) -# ) -# assert delegation.get_attribute("prov:responsible") == { -# session.agent.identifier -# } -# assert session.agent is original_agent - - -# @given(emails(), from_regex("[a-z0-9]+", fullmatch=True)) -# def test_new_agent_context(email, agent_id): -# assume(email != agent_id) -# session = Session(email) -# agent = session.prov.agent(agent_id) -# old_agent = session.agent -# with session.new_agent(agent): -# assert session.agent is agent -# delegation = next( -# iter( -# filter( -# lambda x: x.get_attribute("prov:delegate") == {agent.identifier}, -# session.prov.get_records(prov.ProvDelegation), -# ) -# ) -# ) -# assert delegation.get_attribute("prov:responsible") == {old_agent.identifier} -# assert session.agent is old_agent - - def test_dependency_provenance(): session = Session("rand.m.person@ukaea.uk") dependencies = list( @@ -158,8 +97,3 @@ def test_dependency_provenance(): commit = indica_records[0].get_attribute("git_commit") assert len(commit) == 1 assert "UNKNOWN" not in commit - - -# Test exporting/reloading data produces same result - -# Test export/reload properly interacts with data in __main__