Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

Simplify arc creation through connect_to method on port - #3921

Open
avdudchenko wants to merge 14 commits into
Pyomo:mainfrom
avdudchenko:add_conenct_to
Open

avdudchenko wants to merge 14 commits into
Pyomo:mainfrom
avdudchenko:add_conenct_to

Conversation

@avdudchenko

@avdudchenko avdudchenko commented Apr 23, 2026 •

Copy link
Copy Markdown

Fixes # .

  • This adds a connect_to method to port to simplify arc creation in models

Summary/Motivation:

Currently in many models we use Arcs to connect multiple units/blocks together. In most IDAES/WaterTAP flowsheets or models this becomes very tedious as user must create, name, and track arcs as well as manually propagate them.

  • User needs to manually remember which arc is which and manually propagate them between unit initialization steps
  • This makes model code difficult to read and complicates flowsheet creation process

For example below shows an example, but one key thing to remember is in real flowsheets. the location of arc names and definitions would be separated by a hundreds of lines of code between arc creation and actual propagation occurs (example here:
arc creation and arc propagation by which point user probably forgot what the actual arcs are for and where they are connected (especially new users or developers)

m.block_a.outlet_port= Port()
m.block_b.inlet_port= Port()
m.block_a.block_a_to_block_b_arc=Arc(source=m.block_a.outlet, destination=m.block_b.inlet)

Then to propagate
propagate_method(m.block_a.block_a_to_block_b_arc) # If arc is not clearly named, its impossible to figure out whats its for. 

The connect_to method is intended to simplify arc creation and management work flow where user can simply connect two ports with simple connect_to call. This is not intended to replace Arc method, but be a parallel approach to connecting ports.

New approach

m.block_a.outlet_port= Port()
m.block_b.inlet_port= Port()
arc = m.block_a.outlet.connect_to(m.block_b.inlet) # Clear what is connecting to where

# To propagate the user can simply then go via current PR
propagate_method(arc) # clearly which connections are being propagated. 

# In future we will have a utility method
propagate_method(get_arcs(m.block_a.outlet)) - get_arcs method will be a new tool created to find arcs attached to block, this will ensure that we can find arcs on cloned models. 

Example of this workflow can be seen here

The objective of this PR is start a discussion on this workflow and get feedback on issues that might need to be addressed before implementation.

Some known concerns:

  • automatic arc naming based on ports can lead to collisions - attempted to address this by getting full port name which should include port.
  • There is a circular import issue as Arc import Port method, to circumvent this, connect_to import Arc at call. This is not ideal but impossible to address with out major reorganization of Arc or Port methods. I also do not wish to create a new "Port" object so we do not have to rebuild upstream models to access this method.

Changes proposed in this PR:

  • add connect_to method to Port
  • add get_created_arcs method to Port

Legal Acknowledgement

By contributing to this software project, I have read the contribution guide and agree to the following terms and conditions for my contribution:

  1. I agree my contributions are submitted under the BSD license.
  2. I represent I am authorized to make the contributions and grant the license. If my employer has rights to intellectual property that includes these contributions, I represent that I have received permission to make contributions and grant the required license on behalf of that employer.

@avdudchenko avdudchenko changed the title Simply arc creation through connect_to method on port Simplfy arc creation through connect_to method on port Apr 23, 2026
@avdudchenko avdudchenko changed the title Simplfy arc creation through connect_to method on port Simplify arc creation through connect_to method on port Apr 23, 2026
@blnicho
blnicho requested review from blnicho and jsiirola April 28, 2026 18:45
@blnicho
blnicho marked this pull request as draft April 29, 2026 05:35
@jsiirola

Copy link
Copy Markdown
Member

At the dev call we discussed splitting this PR in half, keeping the connect_to API extension, but deferring the get_connections to a later PR. The concern was that the proposed implementation of get_connections was both fragile (e.g., cloning partial models could cause consistency errors as the outgoing connections might not get updated correctly) and introduced circular references in the model.

We tossed around an idea of exploring an alternate implementation of get_connections by creating a utility (class) that would take a model and interrogate all the Arcs to collect the full port/arc connectivity graph. That object could then support the get_connections() (and potentially other logic like stream tearing),

We are adopting a new review process where we convert PRs that are "waiting on the author" back to "draft" (to signal the PR state to both the author and the dev team). Please use the "Ready for review" button to signal the developers when it is time to get the PR back into the review queue.

@avdudchenko

Copy link
Copy Markdown
Author

removed the get_connections method, and updated the connect_to method to also accept a name in case user wants to name it manually, since we do not provide to access the arc, the function now returns the created arc.

@avdudchenko
avdudchenko marked this pull request as ready for review August 6, 2026 20:44
@blnicho

blnicho commented Sep 2, 2026

Copy link
Copy Markdown
Member

@avdudchenko could you run black on this PR to fix the style failure? You should also merge in the main branch to pick up a typos fix that was recently merged.

@mrmundt

mrmundt commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

@avdudchenko - Hello hello! Can you please run black and merge in the most recent changes to main?

@blnicho blnicho moved this from Todo to Review In Progress in November 2026 Release Nov 10, 2026
Comment thread pyomo/network/tests/test_port.py Resolved
@github-project-automation github-project-automation Bot moved this from Review In Progress to Reviewer Approved in November 2026 Release Nov 16, 2026

@jsiirola jsiirola left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Some comments on the implementation are below, but I have a more fundamental question as to the motivation for this functionality. Apart from some "semantic sugar", does this provide anything that we can't already do with indexed Arcs and/or add_component? Does that semantic sugar warrant the increased technical debt?

Comment thread pyomo/network/port.py Outdated
block = self.parent_block()
if block is None:
raise ValueError(
"Cannot connect Port '%s' to Port '%s' because neither port has a parent block. Please specify a block to construct the Arc on."

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This message does not quite match the code: the code only checks the source port (not the destination) and the user-specified block.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed it by referring to primary port explicitly.

Comment thread pyomo/network/port.py Outdated
arc_name = f"{current_port_name}_to_{dest_port_name}"

block.add_component(arc_name, Arc(source=self, destination=port))
# verify its created as add_component can fail silently

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I do not understand this comment. I don't see a code path where add_component fails without raising an exception.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

If the string name is not a valid python name - it will not fail (or at least it used to not fail (e.g. m.add_component('$invalid$,name", Var) will not raise an error. For example:

import pyomo.environ as pyo

m = pyo.ConcreteModel()
bad_names = ["my var", "1x", "a.b", "x[1]", "a-b", "class", ""]

for name in bad_names:
    try:
        m.add_component(name, pyo.Var(initialize=1.0))
        print(f"add_component({name!r:10}) -> accepted silently, isidentifier={name.isidentifier()}")
    except Exception as e:
        print(f"add_component({name!r:10}) -> raised {type(e).__name__}: {e}")

print("\nComponents on model:")
for c in m.component_objects(pyo.Var, descend_into=False):
    print(f"  name={c.name!r:12} local_name={c.local_name!r}")

print("\nConsequences:")
print("  getattr works only via string:", getattr(m, "my var").value)
for name in ["a.b", "x[1]"]:
    print(f"  find_component({name!r}) -> {m.find_component(name)!r}  (expected the Var named {name!r})")

Output:

add_component('my var'  ) -> accepted silently, isidentifier=False
add_component('1x'      ) -> accepted silently, isidentifier=False
add_component('a.b'     ) -> accepted silently, isidentifier=False
add_component('x[1]'    ) -> accepted silently, isidentifier=False
add_component('a-b'     ) -> accepted silently, isidentifier=False
add_component('class'   ) -> accepted silently, isidentifier=True
add_component(''        ) -> accepted silently, isidentifier=False
...
  find_component('a.b') -> None  (expected the Var named 'a.b')
  find_component('x[1]') -> None  (expected the Var named 'x[1]')

Comment thread pyomo/network/port.py Resolved
Comment thread pyomo/network/port.py Resolved
Comment thread pyomo/network/port.py Resolved
@avdudchenko

avdudchenko commented Dec 3, 2026 •

Copy link
Copy Markdown
Author

Some comments on the implementation are below, but I have a more fundamental question as to the motivation for this functionality. Apart from some "semantic sugar", does this provide anything that we can't already do with indexed Arcs and/or add_component? Does that semantic sugar warrant the increased technical debt?

This is really just meant to make it easier to build models and connect things by abstracting away manual arc creation and management. I think small amount of technical debt can be worth it for cleaner/easier to use API... although with age of AI coming maybe I am wrong...

If you think this does not belong in pyomo we can close the PR, but I would push to ward making friendlier/easier to use API especially if it does not add complex technical debt.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants