Skip to content
Merged
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
18 changes: 4 additions & 14 deletions examples/ESRF_ORM_example/correct_orbit.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,15 @@

np.random.seed(1)
# mangle orbit
hcorr.strengths.set(
hcorr.strengths.get() + std_kick * np.random.normal(size=len(hcorr))
)
vcorr.strengths.set(
vcorr.strengths.get() + std_kick * np.random.normal(size=len(vcorr))
)
hcorr.strengths.set(hcorr.strengths.get() + std_kick * np.random.normal(size=len(hcorr)))
vcorr.strengths.set(vcorr.strengths.get() + std_kick * np.random.normal(size=len(vcorr)))

h0 = hcorr.strengths.get()
v0 = vcorr.strengths.get()

positions_bc = bpms.positions.get()
std_bc = np.std(positions_bc, axis=0)
print(
"R.m.s. orbit before correction "
f"H: {1e6 * std_bc[0]: .1f} µm, V: {1e6 * std_bc[1]: .1f} µm."
)
print(f"R.m.s. orbit before correction H: {1e6 * std_bc[0]: .1f} µm, V: {1e6 * std_bc[1]: .1f} µm.")
########################################################

ebs.orbit.set_virtual_weight(1000)
Expand All @@ -57,10 +50,7 @@
## inspect orbit correction
positions_ac = bpms.positions.get()
std_ac = np.std(positions_ac, axis=0)
print(
"R.m.s. orbit after correction H: "
f"{1e6 * std_ac[0]: .1f} µm, V: {1e6 * std_ac[1]: .1f} µm,"
)
print(f"R.m.s. orbit after correction H: {1e6 * std_ac[0]: .1f} µm, V: {1e6 * std_ac[1]: .1f} µm,")

fig = plt.figure()
ax1 = fig.add_subplot(311)
Expand Down
18 changes: 4 additions & 14 deletions examples/ESRF_ORM_example/correct_orbit_disp.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,12 @@
bpms = ebs.get_bpms("BPM")

# mangle orbit
hcorr.strengths.set(
hcorr.strengths.get() + std_kick * np.random.normal(size=len(hcorr))
)
vcorr.strengths.set(
vcorr.strengths.get() + std_kick * np.random.normal(size=len(vcorr))
)
hcorr.strengths.set(hcorr.strengths.get() + std_kick * np.random.normal(size=len(hcorr)))
vcorr.strengths.set(vcorr.strengths.get() + std_kick * np.random.normal(size=len(vcorr)))

positions_bc = bpms.positions.get()
std_bc = np.std(positions_bc, axis=0)
print(
"R.m.s. orbit before correction "
f"H: {1e6 * std_bc[0]: .1f} µm, V: {1e6 * std_bc[1]: .1f} µm."
)
print(f"R.m.s. orbit before correction H: {1e6 * std_bc[0]: .1f} µm, V: {1e6 * std_bc[1]: .1f} µm.")
########################################################

## Correct the orbit
Expand All @@ -58,10 +51,7 @@
## inspect orbit correction
positions_ac = bpms.positions.get()
std_ac = np.std(positions_ac, axis=0)
print(
"R.m.s. orbit after correction H: "
f"{1e6 * std_ac[0]: .1f} µm, V: {1e6 * std_ac[1]: .1f} µm,"
)
print(f"R.m.s. orbit after correction H: {1e6 * std_ac[0]: .1f} µm, V: {1e6 * std_ac[1]: .1f} µm,")

fig = plt.figure()
ax1 = fig.add_subplot(311)
Expand Down
4 changes: 1 addition & 3 deletions examples/ESRF_ORM_example/measure_dispersion.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
from pyaml.tuning_tools.dispersion import Dispersion

parent_folder = Path(__file__).parent
config_path = parent_folder.parent.parent.joinpath(
"tests", "config", "EBSOrbit.yaml"
).resolve()
config_path = parent_folder.parent.parent.joinpath("tests", "config", "EBSOrbit.yaml").resolve()
sr = Accelerator.load(config_path)
ebs = sr.design

Expand Down
8 changes: 2 additions & 6 deletions examples/ESRF_ORM_example/measure_reduced_ORM.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,10 @@
from pyaml.tuning_tools.orbit_response_matrix import OrbitResponseMatrix

# disable printing during ORM measurement to illustrate callback.
logger = logging.getLogger("pyaml.tuning_tools.orbit_response_matrix").setLevel(
logging.WARNING
)
logger = logging.getLogger("pyaml.tuning_tools.orbit_response_matrix").setLevel(logging.WARNING)

parent_folder = Path(__file__).parent
config_path = parent_folder.parent.parent.joinpath(
"tests", "config", "EBSOrbit.yaml"
).resolve()
config_path = parent_folder.parent.parent.joinpath("tests", "config", "EBSOrbit.yaml").resolve()
sr = Accelerator.load(config_path)
ebs = sr.design
orm = ebs.orm
Expand Down
12 changes: 3 additions & 9 deletions examples/ESRF_tune_example/esrf_tune_example_no_yaml.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,7 @@
names.append(cfg["name"])


simulator = Simulator(
SimulatorConfigModel(name="design", lattice="config/sr/lattices/ebs.mat")
)
simulator = Simulator(SimulatorConfigModel(name="design", lattice="config/sr/lattices/ebs.mat"))

quads = Magnet(MagnetArrayConfigModel(name="quadsForTune", elements=names))

Expand Down Expand Up @@ -142,12 +140,8 @@
# we directly connect to th CS
qxAtt, qyAtt = control.attach(
[
AttributeReadOnly(
AttributeReadOnlyConfig(attribute="sys/ringsimulator/ebs/Tune_h", unit="")
),
AttributeReadOnly(
AttributeReadOnlyConfig(attribute="sys/ringsimulator/ebs/Tune_v", unit="")
),
AttributeReadOnly(AttributeReadOnlyConfig(attribute="sys/ringsimulator/ebs/Tune_h", unit="")),
AttributeReadOnly(AttributeReadOnlyConfig(attribute="sys/ringsimulator/ebs/Tune_v", unit="")),
]
)

Expand Down
4 changes: 1 addition & 3 deletions examples/SOLEIL_examples/01-SOLEIL_II_tune_example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -725,9 +725,7 @@
"print(f\"Tune after correction {tune_monitor.tune.get()}\")\n",
"qcorrectors.strengths.set(old_strength_values)\n",
"sleep(3)\n",
"print(\n",
" f\"Tune setting the tune back to original value correction {tune_monitor.tune.get()}\"\n",
")"
"print(f\"Tune setting the tune back to original value correction {tune_monitor.tune.get()}\")"
]
}
],
Expand Down
4 changes: 1 addition & 3 deletions examples/SOLEIL_examples/02-chromaticity_measurement.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,7 @@
}
],
"source": [
"chromaticity_measurement = control_mode.get_chromaticity_monitor(\n",
" \"DEFAULT_CHROMATICITY_MEASUREMENT\"\n",
")\n",
"chromaticity_measurement = control_mode.get_chromaticity_monitor(\"DEFAULT_CHROMATICITY_MEASUREMENT\")\n",
"chromaticity_measurement"
]
},
Expand Down
6 changes: 1 addition & 5 deletions pyaml/arrays/cfm_magnet_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,7 @@ def __init__(
self.__rwhardwares = RWMagnetHardwares(arrayName, magnets)

if use_aggregator:
raise (
PyAMLException(
"Aggregator not implemented for CombinedFunctionMagnetArray"
)
)
raise (PyAMLException("Aggregator not implemented for CombinedFunctionMagnetArray"))

@property
def strengths(self) -> RWMagnetStrengths:
Expand Down
4 changes: 1 addition & 3 deletions pyaml/arrays/element_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,7 @@ def __ensure_compatible_operand(self, other: object) -> "ElementArray":
if len(self) > 0 and len(other) > 0:
if self.get_peer() is not None and other.get_peer() is not None:
if self.get_peer() != other.get_peer():
raise PyAMLException(
f"{self.__class__.__name__}: cannot operate on arrays attached to different peers"
)
raise PyAMLException(f"{self.__class__.__name__}: cannot operate on arrays attached to different peers")
return other

def __auto_array(self, elements: list[Element]):
Expand Down
8 changes: 2 additions & 6 deletions pyaml/common/element_holder.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,17 +123,13 @@ def fill_array(
except Exception as err:
raise PyAMLException(f"{constructor.__name__} {array_name} : {err} @index {len(a)}") from None
if m in a:
raise PyAMLException(
f"{constructor.__name__} {array_name} : duplicate name {name} @index {len(a)}"
) from None
raise PyAMLException(f"{constructor.__name__} {array_name} : duplicate name {name} @index {len(a)}") from None
a.append(m)
ARR[array_name] = constructor(array_name, a)

def __add(self, array, element: Element):
if element.get_name() in self.__ALL: # Ensure name unicity
raise PyAMLException(
f"Duplicate element {element.__class__.__name__} name {{element.get_name()}}"
) from None
raise PyAMLException(f"Duplicate element {element.__class__.__name__} name {{element.get_name()}}") from None
array[element.get_name()] = element
self.__ALL[element.get_name()] = element

Expand Down
9 changes: 2 additions & 7 deletions pyaml/configuration/csvcurve.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,11 @@ def __init__(self, cfg: ConfigModel):
try:
self._curve = np.genfromtxt(path, delimiter=",", dtype=float, loose=False)
except ValueError as e:
raise PyAMLException(
f"CSVCurve(file='{cfg.file}',dtype=float): {str(e)}"
) from None
raise PyAMLException(f"CSVCurve(file='{cfg.file}',dtype=float): {str(e)}") from None

_s = np.shape(self._curve)
if len(_s) != 2 or _s[1] != 2:
raise PyAMLException(
f"CSVCurve(file='{cfg.file}',dtype=float):"
f"wrong shape (2,2) expected but got {str(_s)}"
)
raise PyAMLException(f"CSVCurve(file='{cfg.file}',dtype=float):wrong shape (2,2) expected but got {str(_s)}")

def get_curve(self) -> np.array:
"""
Expand Down
4 changes: 1 addition & 3 deletions pyaml/configuration/csvmatrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ def __init__(self, cfg: ConfigModel):
try:
self._mat = np.genfromtxt(path, delimiter=",", dtype=float, loose=False)
except ValueError as e:
raise PyAMLException(
f"CSVMatrix(file='{cfg.file}',dtype=float): {str(e)}"
) from None
raise PyAMLException(f"CSVMatrix(file='{cfg.file}',dtype=float): {str(e)}") from None

def get_matrix(self) -> np.array:
"""
Expand Down
8 changes: 2 additions & 6 deletions pyaml/configuration/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,7 @@ def build_object(self, d: dict, ignore_external: bool = False):
obj = elem_cls(cfg)
self.register_element(obj)
except Exception as e:
raise PyAMLConfigException(
f"{str(e)} when creating '{module.__name__}.{class_str}' {location_str}"
) from e
raise PyAMLConfigException(f"{str(e)} when creating '{module.__name__}.{class_str}' {location_str}") from e

else:
# Delayed construction
Expand Down Expand Up @@ -200,9 +198,7 @@ def depth_first_build(self, d, ignore_external: bool):
# We are now on leaf (no nested object), we can construct
return self.build_object(d, ignore_external)

raise PyAMLConfigException(
"Unexpected element found. 'dict' or 'list' expected but got '{d.__class__.__name__}'"
)
raise PyAMLConfigException("Unexpected element found. 'dict' or 'list' expected but got '{d.__class__.__name__}'")

def register_element(self, elt):
if isinstance(elt, Element):
Expand Down
8 changes: 2 additions & 6 deletions pyaml/configuration/fileloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ class PyAMLConfigCyclingException(PyAMLException):
def __init__(self, error_filename: str, path_stack: list[Path]):
self.error_filename = error_filename
parent_file_stack = [parent_path.name for parent_path in path_stack]
super().__init__(
f"Circular file inclusion of {error_filename}. File list before reaching it: {parent_file_stack}"
)
super().__init__(f"Circular file inclusion of {error_filename}. File list before reaching it: {parent_file_stack}")

pass

Expand Down Expand Up @@ -115,9 +113,7 @@ def expand_dict(self, d: dict):
location = field_locations[key]
file, line, col = location
location_str = f" in {file} at line {line}, column {col}"
raise PyAMLException(
f"Circular file inclusion of {pyaml_ex.error_filename}{location_str}"
) from pyaml_ex
raise PyAMLException(f"Circular file inclusion of {pyaml_ex.error_filename}{location_str}") from pyaml_ex

# Recursively expand a list
def expand_list(self, l: list):
Expand Down
4 changes: 1 addition & 3 deletions pyaml/configuration/inline_curve.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ def __init__(self, cfg: ConfigModel):

_s = np.shape(self._curve)
if len(_s) != 2 or _s[1] != 2:
raise PyAMLException(
f"InlineCurve(mat='{cfg.mat}',dtype=float): wrong shape (2,2) expected but got {str(_s)}"
)
raise PyAMLException(f"InlineCurve(mat='{cfg.mat}',dtype=float): wrong shape (2,2) expected but got {str(_s)}")

def get_curve(self) -> np.array:
"""
Expand Down
21 changes: 5 additions & 16 deletions pyaml/configuration/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,7 @@ def root_fields(cls) -> tuple[str, ...]:

def __init__(self):
self._state: dict[str, Any] = {"type": self.DEFAULT_TYPE}
self._items_by_category: dict[str, dict[str, dict[str, Any]]] = {
category: {} for category in self.NAMED_CATEGORIES
}
self._items_by_category: dict[str, dict[str, dict[str, Any]]] = {category: {} for category in self.NAMED_CATEGORIES}
self._sources_by_category: dict[str, dict[str, str]] = {category: {} for category in self.NAMED_CATEGORIES}
self._field_sources: dict[str, str] = {}
self._build_root: SourceRoot = get_root_folder()
Expand Down Expand Up @@ -297,11 +295,7 @@ def categories(self) -> list[str]:

>>> manager.categories()
"""
return [
category
for category in self.NAMED_CATEGORIES
if self._state.get(category) and len(self._state[category]) > 0
]
return [category for category in self.NAMED_CATEGORIES if self._state.get(category) and len(self._state[category]) > 0]

def keys(self, category: str | None = None) -> list[str]:
r"""
Expand Down Expand Up @@ -450,9 +444,7 @@ def settings(self) -> dict[str, Any]:
extra_fields = [
field
for field in self._state.keys()
if field not in self.NAMED_CATEGORIES
and field not in ordered_fields
and field not in _INTERNAL_METADATA_KEYS
if field not in self.NAMED_CATEGORIES and field not in ordered_fields and field not in _INTERNAL_METADATA_KEYS
]
for field in ordered_fields + extra_fields:
settings[field] = copy.deepcopy(self._state[field])
Expand Down Expand Up @@ -553,8 +545,7 @@ def __getattr__(self, name):
return self.get(categories[0], name)
if len(categories) > 1:
raise AttributeError(
f"ConfigurationManager key '{name}' is ambiguous across categories {categories}. "
"Use get(category, name)."
f"ConfigurationManager key '{name}' is ambiguous across categories {categories}. Use get(category, name)."
)
raise AttributeError(f"'ConfigurationManager' object has no attribute '{name}'")

Expand Down Expand Up @@ -810,9 +801,7 @@ def _describe_entry_source(self, entry: dict[str, Any], fallback_source: str) ->
def _coerce_path(self, payload) -> str:
if isinstance(payload, (str, os.PathLike)):
return os.fspath(payload)
raise PyAMLConfigException(
f"Cannot infer configuration source from payload of type '{type(payload).__name__}'."
)
raise PyAMLConfigException(f"Cannot infer configuration source from payload of type '{type(payload).__name__}'.")

def _extend_unique(self, target: list[str], values) -> None:
for value in values:
Expand Down
5 changes: 1 addition & 4 deletions pyaml/control/readback_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,7 @@ def __repr__(self):
str
Human-readable representation.
"""
return (
f"Value({self.value}, quality='{self.quality}',"
+ f"timestamp='{self.timestamp}')"
)
return f"Value({self.value}, quality='{self.quality}'," + f"timestamp='{self.timestamp}')"

def __float__(self):
"""
Expand Down
8 changes: 2 additions & 6 deletions pyaml/lattice/attribute_linker.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,8 @@ def get_element_identifier(self, element: Element) -> LinkerIdentifier:
LinkerIdentifier
The identifier for linking the element
"""
return PyAtAttributeIdentifier(
self.linker_config_model.attribute_name, element.get_name()
)
return PyAtAttributeIdentifier(self.linker_config_model.attribute_name, element.get_name())

def _test_at_element(
self, identifier: PyAtAttributeIdentifier, element: at.Element
) -> bool:
def _test_at_element(self, identifier: PyAtAttributeIdentifier, element: at.Element) -> bool:
attr_value = getattr(element, identifier.attribute_name, None)
return attr_value == identifier.identifier
Loading
Loading