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

Allow initialization of indexed sets via a function returning a dict #3363

Open
wants to merge 11 commits into
base: main
Choose a base branch
from

Conversation

mfripp
Copy link
Contributor

@mfripp mfripp commented Aug 25, 2024

Fixes # .

Summary/Motivation:

It is possible to construct Expression (and possibly Constraint) objects by passing a rule function that constructs a dictionary containing all the elements needed to initialize the Expression. Pyomo notices that this function only accepts one argument, marks it as constant==True and then later IndexedComponent._construct_from_rule_using_setitem calls the function, accepts the dict, and uses that to build the object. However, if you try something similar with indexed sets, it does not initialize correctly from the dictionary and doesn't give an error message. This pull request fixes the Set() definition to allow initialization via a function that produces a dictionary or dict-like object.

The examples below use this shared setup:

from pyomo.environ import ConcreteModel, Set
model = ConcreteModel()
model.A = Set(initialize=[1, 2])
model.B = Set(model.A, initialize={1: [2, 3], 2: [3, 4]})
model.B.pprint()
B : Size=2, Index=A, Ordered=Insertion
    Key : Dimen : Domain : Size : Members
      1 :     1 :    Any :    2 : {2, 3}
      2 :     1 :    Any :    2 : {3, 4}

Here is the current behavior. Pyomo unexpectedly uses the keys of the dict as the return value for any index in m.C:

model.C = Set(model.A, initialize=lambda m: {x: [x+1, x+2] for x in m.A})
model.C.pprint()
C : Size=2, Index=A, Ordered=Insertion
    Key : Dimen : Domain : Size : Members
      1 :     1 :    Any :    2 : {1, 2}
      2 :     1 :    Any :    2 : {1, 2}

Here is the new behavior after this change. Now m.C is the same as m.B, which is the behavior you would expect if the rule function returns the same dictionary as was used to initialize m.B.

model.C = Set(model.A, initialize=lambda m: {x: [x+1, x+2] for x in m.A})
model.C.pprint()
C : Size=2, Index=A, Ordered=Insertion
    Key : Dimen : Domain : Size : Members
      1 :     1 :    Any :    2 : {2, 3}
      2 :     1 :    Any :    2 : {3, 4}

The new initialization method allows more efficient and more readable code when initializing indexed sets. For example, my project often produces indexed sets from simple sets. The most readable approach to this is along these lines:

import pyomo.environ as pyo
model = ConcreteModel()

model.Nodes = pyo.Set(initialize=['A', 'B', 'C'])
model.Arcs = pyo.Set(initialize=[('A', 'B'), ('A', 'C'), ('C', 'B')])

def NodesOut_init(m, node):
    return [j for (i, j) in m.Arcs if i == node]
model.NodesOut = pyo.Set(model.Nodes, initialize=NodesOut_init)

The Pyomo documentation shows another approach with similar performance:

def NodesOut_init(m, node):
    for i, j in m.Arcs:
        if i == node:
            yield j
model.NodesOut = pyo.Set(model.Nodes, initialize=NodesOut_init)
model.NodesOut.pprint()

Both of the above become very slow if there are thousands of Nodes and millions of Arcs, since they scan all Arcs for every Node. The Pyomo documentation recommends this to improve performance:

model.NodesOut = pyo.Set(model.Nodes, within=model.Nodes)

def Populate_NodesOut(model):
    # loop over the arcs and record the end points
    for i, j in model.Arcs:
        model.NodesOut[i].add(j)

model.Populate_NodesOut = pyo.BuildAction(rule=Populate_NodesOut)

This requires users to understand BuildActions and to know that elements can be added to Sets after they are constructed, which is a different pattern from other components.

The new functionality in this pull request enables a simpler way to efficiently construct indexed sets:

def NodesOut_init(m):
    # Create a dict to show NodesOut list for every node
    d = {i: [] for i in m.Nodes}
    # loop over the arcs and record the end points
    for i, j in model.Arcs:
        d[i].append[j]
    return d

model.NodesOut = pyo.Set(model.Nodes, initialize=NodesOut_init)

In the future, this could enable efficient construction of indexed sets via other methods that expect a component to be initialized from a function, e.g.,

@model.Set(model.Nodes)
def NodesOut(m):
    d = {i: [] for i in m.Nodes}
    for i, j in model.Arcs:
        d[i].append[j]
    return d

(Currently this last example doesn't work because the model.Set() decorator passes the function to Set() via rule instead of initialize.)

Changes proposed in this PR:

  • Revise Set.construct() to call the rule function once and then use its result to initialize the indexed set if self.is_indexed() and type(self._init_values._init) is ScalarCallInitializer.
    • The second condition only occurs when Set() is called with a rule that accepts a single argument (the block). In all cases where a set is indexed (the first condition) but the rule function doesn't accept indexes (the second condition), it makes sense to try initializing with the object returned by the function.
    • This could perhaps be broadened a bit by checking self._init_values.constant() and then checking whether self._init_values._init uses a function as its initializer. But there doesn't seem to be a clean way to do that, and in all these cases it looks like self._init_values._init is of type ScalarCallInitializer. The submitted test will catch if this changes.
  • Add pyomo.core.tests.unit.test_sets.TestSetErrors.test_setargs6 to verify that the code above produces the second behavior, not the first.
  • Update online documentation to include this new behavior.

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.

@mfripp
Copy link
Contributor Author

mfripp commented Aug 25, 2024

On my system, this is failing the style and unit tests, but that seems to be due to problems in the repository before I started. This pull request adds one more successful test and does not increase the number of failed tests.

@mrmundt
Copy link
Contributor

mrmundt commented Aug 25, 2024

@mfripp - Please install the latest version of black and run black -S -C on the offending file. Thanks!

@mfripp
Copy link
Contributor Author

mfripp commented Aug 25, 2024

Thanks @mrmundt , I've done that. Looks like I accidentally used black 22.10.0 from elsewhere on my system instead of the newer one (24.8.0) I had just installed. The newer one seems happier with the Pyomo codebase overall and reformatted a few lines in this pull request, which I've now resubmitted.

@mfripp
Copy link
Contributor Author

mfripp commented Aug 29, 2024

@mrmundt, it looks like this pull request passed all tests except "Jenkins CI / test (pull request)". When I click for details on that, I get a message that "pyomo-jenkins.sandia.gov took too long to respond". Is there some way I can run this test locally or something I can fix to get this unblocked?

@blnicho
Copy link
Member

blnicho commented Aug 29, 2024

@mfripp our Jenkins infrastructure is currently down so you can ignore the failure for now. We'll rerun the tests when we get Jenkins running again.

Copy link

codecov bot commented Aug 30, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 88.63%. Comparing base (f32f122) to head (ce4bf54).
Report is 5 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #3363   +/-   ##
=======================================
  Coverage   88.63%   88.63%           
=======================================
  Files         879      879           
  Lines      100221   100223    +2     
=======================================
+ Hits        88827    88829    +2     
  Misses      11394    11394           
Flag Coverage Δ
linux 86.27% <100.00%> (+<0.01%) ⬆️
osx 75.64% <100.00%> (+<0.01%) ⬆️
other 86.76% <100.00%> (+<0.01%) ⬆️
win 84.02% <100.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

@mfripp
Copy link
Contributor Author

mfripp commented Sep 1, 2024

The PR finished all the tests successfully after @jsiirola tagged it as AT:RETEST, but then I merged changes from Pyomo:main and it got stuck on Jenkins CI / inspection again.

@mrmundt
Copy link
Contributor

mrmundt commented Sep 10, 2024

@mfripp - We talked about this PR last week in our weekly dev call, and we are waiting on some feedback from one of our core devs who is on travel. Thanks for submitting it! We'll hopefully have some comments for you soon.

@mfripp
Copy link
Contributor Author

mfripp commented Oct 4, 2024

Thanks! Hope it’s able to go through.

@mrmundt mrmundt requested a review from jsiirola October 8, 2024 18:56
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