0

I have a dataframe df and need to compute a column “res” by satisfying the conditions below -

  1. elements of "res" have to be within the limit 0.5≤res≤4.5
  2. sum (df.res*df.A)==1
  3. orders of "res" have to be var1>var2>var3>……>var14 or df.order

I have tried to solve the problem as bellow. However when I run this program, it never ends!! I really appreciate if someone let me know what are the mistakes I have made here?

import pandas as pd
import numpy as np
import constraint
#---------------------------------------------
df=pd.DataFrame(
    {
        'variable':[
            'var0', 'var1', 'var2', 'var3', 'var4', 'var5', 'var6', 'var7', 'var8', 'var9', 'var10', 'var11', 'var12', 'var13'
        ],
        'order':[
            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
        ],'A':[0.0027600582074272947, 0.004143907916774134, 0.014206504854458709, 0.06336190092978324, 0.009248500532763536,
 0.020789254657924628, 0.0032889203664890534, 0.06596802605794902, 0.0726805811046797, 0.03376844484647921, 0.1382882042107672,
 0.06811217628830124, 0.24303017352264142, 0.2603533465035616],
        'B':[0.38435300797459954, 0.058529034193262046, 0.09093583649489624, 0.2439925002243425, 0.03044378829669108, 0.018764118492057124,
 0.0018789589897301514, 0.023775922953316174, 0.021750211297236473, 0.010065630547679687, 0.029266905237710934, 0.012391441458362717,
 0.042770981682731406, 0.03108166215738403]  
    }        
        )
#==========================================================
problem = constraint.Problem()
var_range=np.linspace(lo,up,5)
problem.addVariables(df.variable, var_range)

def cc_constraint(x0,x1, x2, x3, x4,x5,x6,x7,x8,x9,x10,x11,x12,x13):
    xx=[x0,x1, x2, x3, x4,x5,x6,x7,x8,x9,x10,x11,x12,x13]
    cc=np.array(xx)*np.array(df.A)
    if sum(cc)==1:
        return True
def order_constraint(x0,x1, x2, x3, x4,x5,x6,x7,x8,x9,x10,x11,x12,x13):
    if x0>x1>x2> x3> x4>x5>x6>x7>x8>x9>x10>x11>x12>x13:
        return True
problem.addConstraint(cc_constraint, list(df.variable))
problem.addConstraint(order_constraint, list(df.variable))

solutions = problem.getSolutions()

Jainul
  • 1
  • 2
  • Try with smaller data and it probably will end. Then it's a scalability problem which you need to analyze further: e.g. if the formulation is efficient in regards to propagation or if constraint-programming is the right approach at all. At first glance, the propagation looks super weak and it's not surprise that this won't scale. But given the rather unreadable description and code it's not much fun to work with it. – sascha Nov 19 '20 at 14:06
  • Thanks @sascha for your comment. Is there a way to propagate vectors? – Jainul Nov 29 '20 at 22:32

0 Answers0