Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: ♻️ Cleanup code into seperate functions #1183

Merged
merged 2 commits into from
Feb 18, 2024
Merged

Conversation

Anselmoo
Copy link
Owner

Also add best_tol parameter to CIReport class

All PR-Submissions:


  • Have you followed the guidelines in our Contributing document?
  • Have you checked to ensure there aren't other open
    Pull Requests for the same
    update/change?

New ✨✨ Feature-Submissions:


  • Does your submission pass tests?
  • Have you lint your code locally prior to submission? Fixed:
  • This PR is for a new feature, not a bug fix.

Changes to ⚙️ Core-Features:


  • Have you added an explanation of what your changes do and why you'd like
    us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully run tests with your changes locally?

Also add `best_tol` parameter to CIReport class
@Anselmoo Anselmoo enabled auto-merge (squash) February 18, 2024 11:57
@github-actions github-actions bot added the python Pull requests that update Python code label Feb 18, 2024
Copy link

Quality Gate Passed Quality Gate passed

Issues
0 New issues

Measures
0 Security Hotspots
No data about Coverage
0.0% Duplication on New Code

See analysis details on SonarCloud

@github-actions github-actions bot added the testing Improve testing & coverage label Feb 18, 2024
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

PR Type: Refactoring

PR Summary: This pull request introduces a refactor of the CIReport class within the spectrafit project. The changes include the addition of a new parameter best_tol to allow for configurable tolerance in determining the 'BEST' label for confidence intervals. Additionally, the refactor breaks down the report generation process into smaller, more focused methods such as calculate_offset and create_report_row, enhancing the modularity and readability of the code.

Decision: Comment

📝 Type: 'Refactoring' - not supported yet.
  • Sourcery currently only approves 'Typo fix' PRs.
✅ Issue addressed: this change correctly addresses the issue or implements the desired feature.
No details provided.
✅ Small diff: the diff is small enough to approve with confidence.
No details provided.

General suggestions:

  • Ensure that the new best_tol parameter is clearly documented, especially its impact on determining the 'BEST' label for confidence intervals. This will help future maintainers and users understand its purpose and how to use it effectively.
  • Consider revising the condition in the create_report_row method to handle negative values of cval correctly by using abs(cval) < self.best_tol. This change will ensure that the method accurately identifies values close to zero as 'BEST', regardless of their sign.
spectrafit/report.py: The refactor introduces unnecessary complexity through additional methods and parameters; consider simplifying by integrating new features more directly into existing logic.

While the intention behind the refactor to introduce best_tol and modularize the code with additional methods like calculate_offset and create_report_row is appreciated for its aim to improve readability and maintainability, it inadvertently increases the overall complexity of the class. This is primarily due to the introduction of more parameters, conditionals, and loops, which elevates the cognitive load required to understand and navigate the code.

A more streamlined approach could achieve similar improvements in code clarity and functionality without significantly adding to its complexity. For instance, integrating best_tol directly within the existing logic, while retaining a more linear flow, could simplify understanding and maintaining the code. Below is a suggested revision that incorporates best_tol effectively, yet maintains a simpler structure by minimizing the introduction of new methods and conditionals:

class ConfidenceReport:
    def __init__(self, ci, with_offset=True, ndigits=5, best_tol=1.0e-2):
        self.ci = ci
        self.with_offset = with_offset
        self.ndigits = ndigits
        self.best_tol = best_tol
        self.df = pd.DataFrame()

    def convp(self, x, bound_type):
        return "BEST" if abs(x[0]) < self.best_tol else f"{x[0] * 100:.2f}% - {bound_type}"

    def __call__(self):
        report = {}
        for name, row in self.ci.items():
            offset = 0.0
            if self.with_offset:
                for cval, val in row:
                    if abs(cval) < self.best_tol:
                        offset = val
                        break  # Assuming we only need the first match
            for i, (cval, val) in enumerate(row):
                sval = val if cval < self.best_tol else val - offset
                bound_type = "LOWER" if i < len(row) / 2 else "UPPER"
                report.setdefault(self.convp((cval, val), bound_type), {})[name] = sval
        self.df = pd.DataFrame(report)
        self.tabulate(df=self.df)

    def tabulate(self, df):
        PrintingResults.print_tabulate_df(df=df, floatfmt=f".{self.ndigits}f")

This approach aims to balance the introduction of new functionality with maintaining the simplicity and readability of the code, ensuring it remains easy to navigate and modify in the future.

Thanks for using Sourcery. We offer it for free for open source projects and would be very grateful if you could help us grow. If you like it, would you consider sharing Sourcery on your favourite social media? ✨

Share Sourcery

Help me be more useful! Please click 👍 or 👎 on each comment to tell me if it was helpful.

str: The confidence interval as a string.
"""
return (
"BEST" if abs(x[0]) < self.best_tol else f"{x[0] * 100:.2f}% - {bound_type}"
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (llm): Using self.best_tol in the convp method to determine the 'BEST' label dynamically is a significant improvement. It makes the method more adaptable to different precision requirements. However, ensure that the documentation or comments clearly explain the impact of best_tol on the 'BEST' label determination to avoid any confusion for future maintainers or users.

offset (float): The offset for the row.
"""
for i, (cval, val) in enumerate(row):
sval = val if cval < self.best_tol else val - offset
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (llm): The condition cval < self.best_tol in the create_report_row method might not correctly handle cases where cval is negative. Consider using abs(cval) < self.best_tol to ensure that both positive and negative values of cval close to zero are treated as 'BEST'.

Copy link

codecov bot commented Feb 18, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Comparison is base (c8d0b27) 100.00% compared to head (bae4397) 100.00%.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #1183   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           44        44           
  Lines         4462      4467    +5     
=========================================
+ Hits          4462      4467    +5     
Files Coverage Δ
spectrafit/report.py 100.00% <100.00%> (ø)
spectrafit/test/test_report.py 100.00% <100.00%> (ø)

@Anselmoo Anselmoo merged commit 57456ec into main Feb 18, 2024
46 of 47 checks passed
@Anselmoo Anselmoo deleted the feature/refactor branch February 18, 2024 12:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
python Pull requests that update Python code testing Improve testing & coverage
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant