PyPSA / linopy

Linear optimization with N-D labeled arrays in Python
https://linopy.readthedocs.io
MIT License
153 stars 40 forks source link

Creating variable for each linear expression #300

Closed aurelije closed 1 week ago

aurelije commented 1 month ago

Hi linopyers, What is the recommended way to create variable for each linear expression? The context is that operation has been done on multidimensional variable resulting in LinearExpresssion object. I need to set soft constraint for that expression so I need variable per each linear expression to create constraint.

For me it was logical to do something like this:

soft_constraint_deviation_var = model.add_variables(
    0, 
    100, 
    coords=linear_expression.coords, 
    name='soft_constraint_deviation_var')

Variable gets created but if I try to print it I get KeyError: '_term'

The thing that worked (but it looks like too much of work) is:

soft_constraint_deviation_var = model.add_variables(
    linear_expression.assign(lower=0).data.lower, 
    linear_expression.assign(upper=100).data.upper, 
    name='soft_constraint_deviation_var')

Maybe in api that is made more for OR people and less for XArray people, we could have an method to generate soft constraint and/or deviation varaible.

FabianHofmann commented 1 month ago

good question! (EDIT HERE, previous answer was wrong) how does linear_expression.coords look like?

FabianHofmann commented 1 month ago

ah, you could take linear_exprssion.indexes instead of .coords

aurelije commented 1 month ago

It worked, just it is a bit misleading that for parameter named coords you need to send indexes as an argument

FabianHofmann commented 1 month ago

I know, it would be nice if that worked. but I would not know how to realize that. I am closing this issue, but if you don't mind you are could to document your use cases so that we can incorporate them into the documentation later.