Skip to content

ENH: allow passing source-detector distances to beer_lambert_law()` #13862

Closed

Description

@kalomak

Describe the new feature or enhancement

beer_lambert_law() currently gets source-detector distances from raw.info["chs"]. Many public fNIRS datasets do not include optode locations in the raw data file, but their corresponding papers report a fixed separation such as 3 cm. Could beer_lambert_law() accept an optional sd_distances=None argument so these datasets can still be converted from fnirs_od to hbo/hbr?

I can implement this if it gets accepted.

Describe your proposed implementation

Add an optional sd_distances argument to mne/preprocessing/nirs/_beer_lambert_law.py:17.

Proposed signature:
def beer_lambert_law(raw, ppf=6.0, sd_distances=None):

Example usage:
beer_lambert_law(raw_od, sd_distances=0.03)
beer_lambert_law(raw_od, sd_distances=[0.03, 0.03, 0.03, 0.03]) # matches info['chs'] order

Describe possible alternatives

Additional context

No response

Activity

  1. larsoner commented on Apr 23, 2026

    @larsoner
    Member

    Many public fNIRS datasets do not include optode locations in the raw data file, but their corresponding papers report a fixed separation such as 3 cm.

    Hmm... do they at least include nominal positions, like for each source/detector pair where the midpoint is? Are those encoded properly in the files?

    If that's the case, I wonder if we could instead create a function that uses these midpoints and adds nominal source/detector locations based on those. Like mne.preprocessing.fnirs.add_source_detector_locations(raw.info, distance=0.03) (or something in mne-nirs) that sets info["chs"] locations properly. We would have to choose how to place those sources and detectors, (e.g., just put them on lines of latitude / XY planes in the head coord frame).

    The reason for doing this is that, instead of fixing a single function, something like this would allow many other functions (e.g., plot_alignment) to work properly as well. At least in the sense that they will put sourced and detectors on the plot...

  2. kalomak commented on Apr 24, 2026

    @kalomak
    ContributorAuthor

    Hmm... do they at least include nominal positions, like for each source/detector pair where the midpoint is? Are those encoded properly in the files?

    Usually not. They either have no locations or full sensor-detector locations most of the time.

    In the rare case that there is only midpoint locations, it is pretty easy to manually make a proper montage with a hacky scipy.optim script, e.g.:

    def _sensor_residuals(
        flat_positions,
        channel_names,
        channel_positions,
        sources,
        detectors,
        sensor_distance,
    ):
        sensor_names = [*sources, *detectors]
        sensor_positions = flat_positions.reshape(len(sensor_names), 3)
        sensor_map = dict(zip(sensor_names, sensor_positions))
        target_radius = np.linalg.norm(channel_positions, axis=1).mean()
        residuals = []
        for channel_name, channel_position in zip(channel_names, channel_positions):
            source_name, detector_name = _split_fnirs_pair(channel_name)
            source_pos = sensor_map[source_name]
            detector_pos = sensor_map[detector_name]
            midpoint = (source_pos + detector_pos) / 2.0
            residuals.extend(30.0 * (midpoint - channel_position))
            residuals.append(5.0 * np.linalg.norm(source_pos - detector_pos) - sensor_distance)
        for sensor_position in sensor_positions:
            residuals.append(2.0 * (np.linalg.norm(sensor_position) - target_radius))
        return np.asarray(residuals)
    
    
    def find_best_sensor_locations_for_channels(
        channel_names, channel_positions, sensor_distance=0.03
    ):
        """Infer source and detector positions from channel-center locations.
    
        Optimization targets:
        1. Channels ~= midpoint of source and detector.
        2. Source-detector distances ~= `sensor_distance`.
        3. Optode dist from origin ~= head radius.
        while the source-detector spacing is softly encouraged toward `sensor_distance`.
        """
        channel_positions = np.asarray(channel_positions, dtype=float)
        sources, detectors = _ordered_sensor_names(channel_names)
        initial_guess = _initial_sensor_guess(
            channel_names, channel_positions, sources, detectors, sensor_distance
        )
        result = least_squares(
            _sensor_residuals,
            initial_guess,
            args=(channel_names, channel_positions, sources, detectors, sensor_distance),
        )
        sensor_names = [*sources, *detectors]
        sensor_positions = result.x.reshape(len(sensor_names), 3)
        return dict(zip(sensor_names, sensor_positions))

    But in my opinion not worth it to add this functionality to mne as the use case is so rare. sd_distances=None would be very useful though.

  3. larsoner commented on Apr 24, 2026

    @larsoner
    Member

    Okay yeah if it's generally all-or-nothing then agreed adding a sd_distances=None makes sense.

    And I am inclined to think it should error if the user:

    1. provides sd_distances=<scalar> when it can be computed from the actual positions (to be safe, we can always relax this later), or
    2. provides sd_distances=None and there are no positions to calculate the distances from
  4. kalomak commented on Apr 28, 2026

    @kalomak
    ContributorAuthor

    Looking into this now, I think warning would be better in case 1 above. If locations are faulty we should allow override somehow.

    Case 2: This would also be a breaking change, currently warns and sets distances to 0 if dist calculation fails and proceeds with the calculation.
    @mne/preprocessing/nirs/_beer_lambert_law.py#L77-L85

        distances = _get_sd_distances(raw, sd_distances)
        bad = ~np.isfinite(distances[picks])
        bad |= distances[picks] <= 0
        if bad.any():
            warn(
                "Source-detector distances are zero or NaN, some resulting "
                "concentrations will be zero. Consider setting a montage "
                "with raw.set_montage."
            )
        distances[picks[bad]] = 0.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions