Skip to content

Enhancement: rewrite long if-elif statements into dicts of function #105

Description

@eriktoller

We should collect the fitting methods into a dict with callable functions.

        fit = None
        if method == "linearregression":
            logger.debug("Using linear regression method for fitting.")
            fit = linregressfit(
                obs_well, ref_well, offset, tmin, tmax, name, p, aggregation
            )
        elif method == "npolyfit":
            logger.debug("Using Nth degree polynomial fit method for fitting.")
            degree = kwargs.get("degree", 4)
            fit = npolyfit(
                obs_well, ref_well, offset, degree, tmin, tmax, name, p, aggregation
            )
        elif method == "chebyshev":
            logger.debug("Using Chebyshev polynomial fit method for fitting.")
            degree = kwargs.get("degree", 4)
            fit = chebyshevfit(
                obs_well, ref_well, offset, degree, tmin, tmax, name, p, aggregation
            )
        if fit is None:
            logger.error(f"Fitting method '{method}' is not implemented.")
            raise NotImplementedError(f"Fitting method '{method}' is not implemented.")

We can collect to a dictionary

# 1. Define the mapping
fitting_methods = {
    "linearregression": lambda **cols: linregressfit(**cols),
    "npolyfit": lambda **cols: npolyfit(degree=kwargs.get("degree", 4), **cols),
    "chebyshev": lambda **cols: chebyshevfit(degree=kwargs.get("degree", 4), **cols),
}

# 2. Logic to execute
if method not in fitting_methods:
    logger.error(f"Fitting method '{method}' is not implemented.")
    raise NotImplementedError(f"Fitting method '{method}' is not implemented.")

logger.debug(f"Using {method} method for fitting.")

# Prepare shared arguments
common_args = {
    "obs_well": obs_well,
    "ref_well": ref_well,
    "offset": offset,
    "tmin": tmin,
    "tmax": tmax,
    "name": name,
    "p": p,
    "aggregation": aggregation
}

# Execute the mapped function
fit = fitting_methods[method](**common_args)

This will make it easier to implement new features later on. There are probably quite a few places where we can change this.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Fields

No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions