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

Add inheritance for bounding box operations #575

Merged
merged 10 commits into from
Jan 26, 2025
Merged

Conversation

MatthewMckee4
Copy link
Member

@MatthewMckee4 MatthewMckee4 commented Jan 26, 2025

Summary by Sourcery

Add support for mirroring, moving, and rotating instances using both database and layout coordinates. Update the flexgrid and layer_cat functions to use layout coordinates when performing bounding box operations. Add tests for instance operations and attributes, as well as update existing tests to accommodate these changes.

New Features:

  • Add methods to mirror, move and rotate instances using database coordinates.

Tests:

  • Add tests for instance operations using database and layout coordinates.
  • Update existing tests for transformations and bounding box operations.

Copy link
Contributor

sourcery-ai bot commented Jan 26, 2025

Reviewer's Guide by Sourcery

This pull request introduces inheritance for bounding box operations on instances, providing a more intuitive and consistent API for transformations. It also includes new tests to verify the correctness of the implementation.

Sequence diagram for flexgrid bounding box operations

sequenceDiagram
    participant F as Flexgrid
    participant I as Instance
    participant B as BoundingBox
    F->>I: Get bbox/dbbox
    I->>B: Create bounding box
    B-->>I: Return bounds
    I-->>F: Return bbox
    F->>I: Apply transformation
    Note over F,I: Transform instance position<br/>based on alignment and spacing
    F->>I: Get updated bbox
    I-->>F: Return new bounds
Loading

Class diagram for bounding box operations inheritance

classDiagram
    class Instance {
        +bbox()
        +dbbox()
        +trans
        +dcplx_trans
    }
    class BoundingBox {
        +left
        +right
        +top
        +bottom
        +center()
    }
    Instance --> BoundingBox : returns
    note for Instance "Handles both integer and floating-point transformations"
    note for BoundingBox "Represents geometric bounds"
Loading

File-Level Changes

Change Details Files
Added inheritance for bounding box operations on instances.
  • Added mirror_x, mirror_y, mirror, move, movex, movey, and rotate methods to the Instance class.
  • Added dmirror_x, dmirror_y, dmirror, dmove, dmovex, dmovey, and drotate methods to the Instance class.
  • Added imirror_x, imirror_y, imirror, imove, imovex, imovey, and irotate methods to the Instance class.
  • Added tests to verify the correctness of the new methods.
  • Added tests to verify the correctness of the instance attributes.
tests/test_instance.py
Updated flexgrid functions to use the new bounding box methods.
  • Updated flexgrid_dbu and flexgrid functions to use the new bbox and dbbox methods.
  • Removed unnecessary or None checks when getting values from dictionaries.
src/kfactory/grid.py
Updated tests to use the new bounding box methods.
  • Updated test_rotation and test_drotation to use the new rotate and drotate methods.
  • Updated test_connection_flags to use the new mirror method.
tests/test_transformations.py
Updated routing functions to use the new bounding box methods.
  • Updated layer_cat to use the new bbox method.
src/kfactory/routing/generic.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

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.

We've reviewed this pull request using the Sourcery rules engine. If you would also like our AI-powered code review then let us know.

if port.base.trans:
self.shapes(port.layer).insert(poly.transformed(port.trans))
self.shapes(port.layer).insert(
kdb.Text(port.name if port.name else "", port.trans)
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Replace if-expression with or (or-if-exp-identity)

Suggested change
kdb.Text(port.name if port.name else "", port.trans)
kdb.Text(port.name or "", port.trans)


ExplanationHere we find ourselves setting a value if it evaluates to True, and otherwise
using a default.

The 'After' case is a bit easier to read and avoids the duplication of
input_currency.

It works because the left-hand side is evaluated first. If it evaluates to
true then currency will be set to this and the right-hand side will not be
evaluated. If it evaluates to false the right-hand side will be evaluated and
currency will be set to DEFAULT_CURRENCY.

else:
self.shapes(port.layer).insert(poly, port.dcplx_trans)
self.shapes(port.layer).insert(
kdb.Text(port.name if port.name else "", port.trans)
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Replace if-expression with or (or-if-exp-identity)

Suggested change
kdb.Text(port.name if port.name else "", port.trans)
kdb.Text(port.name or "", port.trans)


ExplanationHere we find ourselves setting a value if it evaluates to True, and otherwise
using a default.

The 'After' case is a bit easier to read and avoids the duplication of
input_currency.

It works because the left-hand side is evaluated first. If it evaluates to
true then currency will be set to this and the right-hand side will not be
evaluated. If it evaluates to false the right-hand side will be evaluated and
currency will be set to DEFAULT_CURRENCY.

Comment on lines 5084 to 5095
if isinstance(cross_section, SymmetricalCrossSection):
if cross_section.enclosure != self.kcl.get_enclosure(
cross_section.enclosure
):
return self.get_cross_section(
CrossSectionSpec(
sections=cross_section.enclosure.model_dump()["sections"],
main_layer=cross_section.main_layer,
name=cross_section.name,
width=cross_section.width,
)
)
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Merge nested if conditions (merge-nested-ifs)

Suggested change
if isinstance(cross_section, SymmetricalCrossSection):
if cross_section.enclosure != self.kcl.get_enclosure(
cross_section.enclosure
):
return self.get_cross_section(
CrossSectionSpec(
sections=cross_section.enclosure.model_dump()["sections"],
main_layer=cross_section.main_layer,
name=cross_section.name,
width=cross_section.width,
)
)
if isinstance(cross_section, SymmetricalCrossSection) and cross_section.enclosure != self.kcl.get_enclosure(
cross_section.enclosure
):
return self.get_cross_section(
CrossSectionSpec(
sections=cross_section.enclosure.model_dump()["sections"],
main_layer=cross_section.main_layer,
name=cross_section.name,
width=cross_section.width,
)
)


ExplanationToo much nesting can make code difficult to understand, and this is especially
true in Python, where there are no brackets to help out with the delineation of
different nesting levels.

Reading deeply nested code is confusing, since you have to keep track of which
conditions relate to which levels. We therefore strive to reduce nesting where
possible, and the situation where two if conditions can be combined using
and is an easy win.

_infos = infos() if infos else LayerInfos()
super().__init__(
name=name,
layer_enclosures=LayerEnclosureModel(dict()),
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Replace dict() with {} (dict-literal)

Suggested change
layer_enclosures=LayerEnclosureModel(dict()),
layer_enclosures=LayerEnclosureModel({}),


ExplanationThe most concise and Pythonic way to create a dictionary is to use the {}
notation.

This fits in with the way we create dictionaries with items, saving a bit of
mental energy that might be taken up with thinking about two different ways of
creating dicts.

x = {"first": "thing"}

Doing things this way has the added advantage of being a nice little performance
improvement.

Here are the timings before and after the change:

$ python3 -m timeit "x = dict()"
5000000 loops, best of 5: 69.8 nsec per loop
$ python3 -m timeit "x = {}"
20000000 loops, best of 5: 29.4 nsec per loop

Similar reasoning and performance results hold for replacing list() with [].

Comment on lines +5543 to +5545
if name is None:
if main_layer is not None and main_layer.name != "":
name = main_layer.name
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Merge nested if conditions (merge-nested-ifs)

Suggested change
if name is None:
if main_layer is not None and main_layer.name != "":
name = main_layer.name
if name is None and (main_layer is not None and main_layer.name != ""):
name = main_layer.name


ExplanationToo much nesting can make code difficult to understand, and this is especially
true in Python, where there are no brackets to help out with the delineation of
different nesting levels.

Reading deeply nested code is confusing, since you have to keep track of which
conditions relate to which levels. We therefore strive to reduce nesting where
possible, and the situation where two if conditions can be combined using
and is an easy win.

options.cell_conflict_resolution
!= kdb.LoadLayoutOptions.CellConflictResolution.RenameCell
):
self.kcl.set_meta_data()
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): We've found these issues:

Comment on lines +3605 to +3614
if isinstance(inst, Instance):
return Instance(self.kcl, self._base_kcell.kdb_cell.insert(inst.instance))
else:
if not property_id:
return Instance(self.kcl, self._base_kcell.kdb_cell.insert(inst))
else:
assert isinstance(inst, kdb.CellInstArray | kdb.DCellInstArray)
return Instance(
self.kcl, self._base_kcell.kdb_cell.insert(inst, property_id)
)
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): We've found these issues:

)
if self.locked:
raise LockedError(self)
if trans:
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): We've found these issues:

"""
self.clear_meta_info()
if not self.is_library_cell():
for i, port in enumerate(self.ports):
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): We've found these issues:

)
data["library"].register(data["name"])
return data
def get_meta_data(
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): We've found these issues:


Explanation
The quality score for this function is below the quality threshold of 25%.
This score is a combination of the method length, cognitive complexity and working memory.

How can you solve this?

It might be worth refactoring this function to make it shorter and more readable.

  • Reduce the function length by extracting pieces of functionality out into
    their own functions. This is the most important thing you can do - ideally a
    function should be less than 10 lines.
  • Reduce nesting, perhaps by introducing guard clauses to return early.
  • Ensure that variables are tightly scoped, so that code using related concepts
    sits together within the function rather than being scattered.

@github-actions github-actions bot added enhancement New feature or request routing labels Jan 26, 2025
Copy link

codecov bot commented Jan 26, 2025

Codecov Report

Attention: Patch coverage is 30.95238% with 29 lines in your changes missing coverage. Please review.

Project coverage is 59.21%. Comparing base (fd754cd) to head (f404584).
Report is 12 commits behind head on main.

Files with missing lines Patch % Lines
src/kfactory/grid.py 25.64% 29 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #575      +/-   ##
==========================================
+ Coverage   57.76%   59.21%   +1.45%     
==========================================
  Files          49       49              
  Lines        9529     9163     -366     
  Branches     1764     1739      -25     
==========================================
- Hits         5504     5426      -78     
+ Misses       3486     3203     -283     
+ Partials      539      534       -5     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@sebastian-goeldi sebastian-goeldi merged commit 368315b into main Jan 26, 2025
15 of 16 checks passed
@sebastian-goeldi sebastian-goeldi deleted the proto-instance branch January 26, 2025 19:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request routing
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants