Skip to content
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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ dependencies = [
"urllib3",
"requests",
"xmltodict",
"ophyd-async",
]

[project.optional-dependencies]
Expand Down
10 changes: 10 additions & 0 deletions src/daq_config_server/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
DisplayConfig,
DisplayConfigData,
)
from .converters.insertion_device_lookup_table import (
EnergyCoverage,
EnergyCoverageEntry,
InsertionDeviceLookupTable,
Pol,
)
from .converters.lookup_tables import (
BeamlinePitchLookupTable,
BeamlineRollLookupTable,
Expand All @@ -15,6 +21,10 @@
"ConfigModel",
"DisplayConfig",
"DisplayConfigData",
"EnergyCoverage",
"EnergyCoverageEntry",
"InsertionDeviceLookupTable",
"Pol",
"GenericLookupTable",
"DetectorXYLookupTable",
"BeamlinePitchLookupTable",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from ._converters import (
parse_i09_2_gap_id_lut,
parse_i09_2_phase_id_lut,
parse_i10_gap_idd_lut,
parse_i10_gap_idu_lut,
parse_i10_phase_idd_lut,
parse_i10_phase_idu_lut,
parse_i21_gap_id_lut,
parse_i21_phase_id_lut,
)
from ._models import (
EnergyCoverage,
EnergyCoverageEntry,
InsertionDeviceLookupTable,
Pol,
)

__all__ = [
"parse_i09_2_gap_id_lut",
"parse_i09_2_phase_id_lut",
"parse_i10_gap_idd_lut",
"parse_i10_gap_idu_lut",
"parse_i10_phase_idd_lut",
"parse_i10_phase_idu_lut",
"parse_i21_gap_id_lut",
"parse_i21_phase_id_lut",
"EnergyCoverage",
"EnergyCoverageEntry",
"InsertionDeviceLookupTable",
"Pol",
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import csv
import io
from collections.abc import Generator
from typing import Any

import numpy as np

from ._models import (
EnergyCoverage,
EnergyCoverageEntry,
InsertionDeviceLookupTable,
InsertionDeviceLookupTableColumnConfig,
Pol,
Source,
)


def read_file_and_skip(file: str, skip_line_start_with: str = "#") -> Generator[str]:
"""Yield non-comment lines from the CSV content string."""
for line in io.StringIO(file):
if line.startswith(skip_line_start_with):
continue
else:
yield line


def convert_csv_to_lookup(
file_contents: str,
lut_config: InsertionDeviceLookupTableColumnConfig,
skip_line_start_with: str = "#",
) -> InsertionDeviceLookupTable:
"""
Convert CSV content into the Apple2 lookup-table dictionary.

Parameters:
-----------
file_contents:
The CSV file contents as string.
lut_config:
The configuration that how to process the file_contents into a LookupTable.
skip_line_start_with
Lines beginning with this prefix are skipped (default "#").

Returns:
-----------
LookupTable
"""
temp_mode_entries: dict[Pol, list[EnergyCoverageEntry]] = {}

def process_row(row: dict[str, Any]) -> None:
"""Process a single row from the CSV file and update the temporary entry
list."""
raw_mode_value = str(row[lut_config.mode]).lower()
mode_value = Pol(
lut_config.mode_name_convert.get(raw_mode_value, raw_mode_value)
)

coefficients = np.poly1d([float(row[coef]) for coef in lut_config.poly_deg])

energy_entry = EnergyCoverageEntry(
min_energy=float(row[lut_config.min_energy]),
max_energy=float(row[lut_config.max_energy]),
poly=coefficients,
)

if mode_value not in temp_mode_entries:
temp_mode_entries[mode_value] = []

temp_mode_entries[mode_value].append(energy_entry)

reader = csv.DictReader(read_file_and_skip(file_contents, skip_line_start_with))

for row in reader:
source = lut_config.source
# If there are multiple source only convert requested.
if source is None or row[source.column] == source.value:
process_row(row=row)
# Check if our LookupTable is empty after processing, raise error if it is.
if not temp_mode_entries:
raise RuntimeError(
"LookupTable content is empty, failed to convert the file contents to "
"a LookupTable!"
)

final_lut_root: dict[Pol, EnergyCoverage] = {}
for pol, entries in temp_mode_entries.items():
final_lut_root[pol] = EnergyCoverage.model_validate({"energy_entries": entries})

return InsertionDeviceLookupTable(root=final_lut_root)


"""Implementations for each beamline"""


def parse_i10_gap_idd_lut(contents: str) -> InsertionDeviceLookupTable:
source = Source(column="Source", value="idd")
lut_config = InsertionDeviceLookupTableColumnConfig(source=source)
return convert_csv_to_lookup(contents, lut_config)


def parse_i10_gap_idu_lut(contents: str) -> InsertionDeviceLookupTable:
source = Source(column="Source", value="idu")
lut_config = InsertionDeviceLookupTableColumnConfig(source=source)
return convert_csv_to_lookup(contents, lut_config)

Comment on lines +95 to +105
Copy link
Collaborator

@Relm-Arrowny Relm-Arrowny Mar 6, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently, the daq-config-server only accepts a file path, making it impossible to distinguish between these two configurations since they share the same filename.

We probably have two potential solutions for this:

  • Add an additional parameter: Modify the server to accept a secondary argument alongside the file path. This would resolve the naming conflict and allow us to handle beamline-specific logic via parameter settings rather than separate models.

  • Use unique configuration files: Maintain separate, uniquely named files for different LUT settings. This is alternative that avoids the need for server modifications and removes the dependency on custom models.

This probably effect the restructure #165 .

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a 3rd option we can also split the data file into two but it will spin ever more models

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Splitting your ID config files is the simplest solution. This means we can also remove the Source Field for LookupTableColumnConfig. I mentioned this awhile back as only I10 uses this column where it is simpler to split like i09

Copy link
Collaborator

@Relm-Arrowny Relm-Arrowny Mar 6, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Option 3 only resolves the filename conflict, we would still need to instantiate multiple models in the code for every ID configuration.

Option 2 is an improvement because it encapsulates all parameters within a beamline_lut_config file, allowing for easy modification without requiring a new model for each beamline.

However, I think the additional parameter is the best way forward. It would allow us to eliminate the FILE_TO_CONVERTER_MAP entirely, Relying on only a few unified models. This would also prevent the need to maintain an ever-growing list of individual configuration files/models.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This I do agree slightly agree with as additional parameters would give us the flexibility and eliminate the growing converter functions. However, then I don't think it's worth the effort.

So at the moment, we do this

class ConfigServerEnergyMotorLookup:
         ...
         file_contents = self.config_client.get_file_contents(
            self.path, reset_cached_result=True
        )
        return convert_csv_to_lookup(file_contents, lut_config=self.lut_config)

Currently, we can do this:

my_model = self.config_client.get_file_contents(self.path, desired_return_type=MyModel)

And you want to do able to do this

my_model = self.config_client.get_file_contents(self.path, desired_return_type=MyModel, **kwargs)

At this point, is it really worth the effort for it take custom parameters when we can do this on our side anyway?
We should just update our model to do this instead

class ConfigServerEnergyMotorLookup:
         ...
         file_contents = self.config_client.get_file_contents(
            self.path, reset_cached_result=True
        )
        return MyModel.from_content(file_contents, lut_config=self.lut_config)

The simplest solution is if the model can take a single argument of file contents, then it can support the desired_return_type feature. If it can't, then the model should live in daq-config-server but when loaded, the file contents should be returned as string and additional args should be given client side. However, the loader function lives on the model.

I guess that does make it slightly confusing though, so maybe supporting additional kwargs your model needs for loading is a much better way as then it is driven by configuration you provide to the client function rather than endlessly creating static functions for loading a simple model.


def parse_i10_phase_idd_lut(contents: str) -> InsertionDeviceLookupTable:
source = Source(column="Source", value="idd")
lut_config = InsertionDeviceLookupTableColumnConfig(source=source)
return convert_csv_to_lookup(contents, lut_config)


def parse_i10_phase_idu_lut(contents: str) -> InsertionDeviceLookupTable:
source = Source(column="Source", value="idu")
lut_config = InsertionDeviceLookupTableColumnConfig(source=source)
return convert_csv_to_lookup(contents, lut_config)


def parse_i09_2_gap_id_lut(contents: str) -> InsertionDeviceLookupTable:
lut_config = InsertionDeviceLookupTableColumnConfig(
poly_deg=[
"9th-order",
"8th-order",
"7th-order",
"6th-order",
"5th-order",
"4th-order",
"3rd-order",
"2nd-order",
"1st-order",
"0th-order",
]
)
return convert_csv_to_lookup(contents, lut_config)


def parse_i09_2_phase_id_lut(contents: str) -> InsertionDeviceLookupTable:
lut_config = InsertionDeviceLookupTableColumnConfig(poly_deg=["0th-order"])
return convert_csv_to_lookup(contents, lut_config)


def parse_i21_gap_id_lut(contents: str) -> InsertionDeviceLookupTable:
lut_config = InsertionDeviceLookupTableColumnConfig(grating="Grating")
return convert_csv_to_lookup(contents, lut_config)


def parse_i21_phase_id_lut(contents: str) -> InsertionDeviceLookupTable:
lut_config = InsertionDeviceLookupTableColumnConfig(
grating="Grating", poly_deg=["b"]
)
return convert_csv_to_lookup(contents, lut_config)
Loading
Loading