Ejemplo n.º 1
0
    def test_log1p(self) -> None:
        """Test domain for log1p.
        """
        expr = cp.log1p(self.a)
        self.a.value = 2
        self.assertAlmostEqual(expr.grad[self.a], 1.0 / 3)

        self.a.value = 3
        self.assertAlmostEqual(expr.grad[self.a], 1.0 / 4)

        self.a.value = -1
        self.assertAlmostEqual(expr.grad[self.a], None)

        expr = cp.log1p(self.x)
        self.x.value = [3, 4]
        val = np.zeros((2, 2)) + np.diag([1 / 4, 1 / 5])
        self.assertItemsAlmostEqual(expr.grad[self.x].toarray(), val)

        expr = cp.log1p(self.x)
        self.x.value = [-1e-9 - 1, 4]
        self.assertAlmostEqual(expr.grad[self.x], None)

        expr = cp.log1p(self.A)
        self.A.value = [[1, 2], [3, 4]]
        val = np.zeros((4, 4)) + np.diag([1 / 2, 1 / 3, 1 / 4, 1 / 5])
        self.assertItemsAlmostEqual(expr.grad[self.A].toarray(), val)
Ejemplo n.º 2
0
 def test_log1p(self):
     """Test the log1p atom.
     """
     expr = cp.log1p(1)
     self.assertEqual(expr.sign, s.NONNEG)
     self.assertEqual(expr.curvature, s.CONSTANT)
     self.assertEqual(expr.shape, tuple())
     expr = cp.log1p(-0.5)
     self.assertEqual(expr.sign, s.NONPOS)
Ejemplo n.º 3
0
def cvx_power_alloc_unequal_power(W, Pa, nt, nc, nac):
    #Pc = Pa*np.ones((nt,1))  ## per-antenna power constraint
    d = cvx.Variable(nc * nac)
    objective = cvx.Maximize(cvx.sum_entries(cvx.log1p(d) / np.log(2)))
    constraints = [cvx.sum_entries(W @ d) <= Pa, d >= 0, d <= 10**3.6]
    prob = cvx.Problem(objective, constraints)
    prob.solve(max_iters=50000)
    return np.asarray(np.abs(d.value)).flatten()
Ejemplo n.º 4
0
def cvx_power_alloc_unequal_power(W, Pa, nt, nc, nac): 
    Pc = Pa*np.ones((nt,1))
    d = cvx.Variable(nc*nac) 
    objective = cvx.Maximize(cvx.sum_entries(cvx.log1p(d)/np.log(2))) 
    constraints = [W @ d <= Pc, d >= 0] 
    prob = cvx.Problem(objective, constraints) 
    prob.solve(solver='SCS') 
    print('Problem status: {}'.format(prob.status))
    return np.asarray(np.abs(d.value)).flatten()
Ejemplo n.º 5
0
def cvx_power_alloc_equal_power(W, Pa, nt, nc, nac):
    #Pc = Pa*np.ones((nt, 1))  ## per-antenna power constraint
    Q = np.kron(np.eye(nc), np.ones((nac, 1)))
    d = cvx.Variable(nc)
    objective = cvx.Maximize(cvx.sum_entries(cvx.log1p(d) / np.log(2)))
    if nc > 1:
        constraints = [cvx.sum_entries(W @ Q @ d) <= Pa, d >= 0, d <= 10**3.6]
    if nc == 1:
        constraints = [cvx.sum_entries(W @ Q) * d <= Pa, d >= 0, d <= 10**3.6]
    prob = cvx.Problem(objective, constraints)
    prob.solve(max_iters=50000)
    return np.asarray(np.abs(d.value)).flatten(), prob.status
Ejemplo n.º 6
0
def cvx_power_alloc_equal_power(W, Pa, nt, nc, nac):
    Pc = Pa*np.ones((nt, 1))
    Q = np.kron(np.eye(nc), np.ones((nac, 1)))
    d = cvx.Variable(nc)
    objective = cvx.Maximize(cvx.sum_entries(cvx.log1p(d)/np.log(2))) 
    ## Constraining SNR to be between min required for MCS = 0 ( = 3.9 dB) and for MCS = 12 ( = 36 dB)
    constraints = [W @ Q @ d <= Pc, d >= 0, d <= 10**3.6]
    prob = cvx.Problem(objective, constraints)
    # prob.solve(solver='SCS') 
    prob.solve(max_iters=50000) 
    # print('Problem status: {}'.format(prob.status))
    return np.asarray(np.abs(d.value)).flatten(), prob.status  
Ejemplo n.º 7
0
    def apply(self, network_configuration, firedex_configuration,
              publishers_configuration, network_flows):
        bandwidth = network_configuration.bandwidth()
        rho_tolerance = firedex_configuration.rho_tolerance()
        publication_collection = publishers_configuration.publication_collection(
        )

        # variable
        n = network_flows.__len__()
        # ---

        # problem to solve
        alpha = [x.adjusted_utility_function() for x in network_flows]
        success_rate = cvxpy.Variable(n, name="success_rates")

        objective = cvxpy.Maximize(
            cvxpy.sum(cvxpy.multiply(alpha, cvxpy.log1p(success_rate))))
        # ---

        # constraint
        network_flows_load = []
        for network_flow in network_flows:
            subscriptions = network_flow.subscriptions()
            current_load = 0
            for subscription in subscriptions:
                topic = subscription.topic()
                current_load += publication_collection.publications_load_by_topic(
                    topic=topic)

            network_flows_load.append(current_load)

        a = network_flows_load * success_rate
        network_load = cvxpy.sum(
            cvxpy.multiply(network_flows_load, success_rate))
        constraints = [
            network_load <= bandwidth * (1 - rho_tolerance), success_rate >= 0,
            success_rate <= 1
        ]
        # ---

        # solution
        prob = cvxpy.Problem(objective, constraints)
        prob.solve()

        solution = success_rate.value
        solution = [round(x, 2) for x in solution]
        # ---

        for network_flow, success_rate in zip(network_flows, solution):
            drop_rate = 1 - success_rate
            network_flow.set_drop_rate(drop_rate=drop_rate)
Ejemplo n.º 8
0
def solve_log(hist, v, wmax):
    wrs = list(hist.keys())
    z = np.array([[w - 1.0, w * r - v] for w, r in wrs])
    c = np.array([hist[wr] for wr in wrs])
    c = c / np.sum(c)

    lam = cp.Variable(2)
    constraints = [
        lam.T @ np.array([w - 1.0, w * r - vv]) >= -0.5 for w in (0, wmax)
        for r in (0, 1) for vv in (0, 1)
    ]
    objective = c.T @ cp.log1p(z @ lam)
    p = cp.Problem(cp.Maximize(objective), constraints)
    p.solve()
    return lam.value
Ejemplo n.º 9
0
def optim_with_cvxpy2(rtns,levs,mns,mcovs,headers,labels,worst,log_tdiscount,row_weight,ob):

    barrier=worst+1
    merit=pd.DataFrame(index=headers,columns=labels)
    nrows,ncols=rtns.shape
    nlevs=len(levs)
    alloc=np.ones((nlevs,ncols),dtype='float64')
    prtns=np.zeros((nlevs,nrows),dtype='float64')
    
    xx=cp.Variable(ncols)
    for i in range(nlevs):
        lev=levs[i]
        levreturn=(rtns*lev)
        print("Risk Aversion: ",lev)
        
        if ob=='MV':           
            constraints =[sum(xx)==1, 0<=xx, xx<=1] #Long-only portfolios                   
            objective=cp.Minimize(-cp.sum(cp.multiply(mns,xx)) + lev*cp.quad_form(xx,mcovs)/2.0)
            prob=cp.Problem(objective,constraints)
            result=prob.solve(eps_abs=1e-7,eps_rel=1e-7)
            xxvalue=xx.value
            prtns[i]=np.dot(rtns,xxvalue)
            merit['M_objective'][headers[i]]= np.sum(mns*xxvalue) - levs[i]*np.dot(np.dot(xxvalue,mcovs),xxvalue.T)/2.0
            merit['W_objective'][headers[i]]= np.sum(np.multiply(row_weight,(np.log1p(np.dot(levreturn,xxvalue.T))+log_tdiscount)))   

        elif ob=='LLS':
            constraints =[sum(xx)==1, 0<=xx, xx<=1, -1.0+barrier <= levreturn @ xx ] #Long-only portfolios                              
            objective=cp.Maximize(cp.sum(cp.multiply(row_weight,cp.log1p(levreturn @ xx)+log_tdiscount)))
            prob=cp.Problem(objective,constraints)
            result=prob.solve(abstol=1e-7,reltol=1e-7,verbose=False)/nrows
            xxvalue=xx.value
            if xxvalue is None:                
                print('WARNING!!!! cvxpy problem appears not feasible.')
                raise
            prtns[i]=np.dot(rtns,xxvalue)
            merit['M_objective'][headers[i]]= sum(mns*xxvalue) - levs[i]*np.dot(np.dot(xxvalue,mcovs),xxvalue.T)/2.0
            merit['W_objective'][headers[i]]= np.sum(np.multiply(row_weight,(np.log1p(np.dot(levreturn,xxvalue.T))+log_tdiscount)))       
        alloc[i]=xxvalue 
        merit['norm2'][headers[i]] = np.dot(xxvalue,xxvalue)        
    
    return (prtns[::].T,alloc[::],pd.DataFrame.copy(merit,deep=True))
Ejemplo n.º 10
0
def __achieved_utility(network_flow):
    success_rate = 1 - network_flow.get_drop_rate()
    achieved_utility = float(network_flow.adjusted_utility_function()) * float(
        cvxpy.log1p(success_rate).value)
    return achieved_utility
Ejemplo n.º 11
0
 def test_log1p(self) -> None:
     """Test domain for log1p.
     """
     dom = cp.log1p(self.a).domain
     Problem(Minimize(self.a), dom).solve(solver=cp.SCS, eps=1e-6)
     self.assertAlmostEqual(self.a.value, -1)
Ejemplo n.º 12
0
    def get_costs(dataset, pi):

        if pi.size(
                -1
        ) == 1:  # In case all tours directly return to depot, prevent further problems
            assert (
                pi == 0).all(), "If all length 1 tours, they should be zero"
            # Return
            return torch.zeros(pi.size(0), dtype=torch.float,
                               device=pi.device), None

        # Check that tours are valid, i.e. contain 0 to n -1
        sorted_pi = pi.data.sort(1)[0]
        # Make sure each node visited once at most (except for depot)
        assert ((sorted_pi[:, 1:] == 0) |
                (sorted_pi[:, 1:] > sorted_pi[:, :-1])).all(), "Duplicates"

        chGain = dataset['chGain'].cpu().numpy()  #(batch_size, n_loc)
        minRateReq = dataset['minRateReq'].cpu().numpy(
        )  #(batch_size, n_users)
        sharedFlag = dataset['sharedFlag'].cpu().numpy()  #(batch_size, n_RBs)
        numerology = dataset['numerology'].cpu().numpy()  #(batch_size)
        availRBNum = dataset['availRBNum'].cpu().numpy()  #(batch_size)
        availPower = dataset['availPower'].cpu().numpy()  #(batch_size)

        batch_size, n_loc = chGain.shape
        _, n_users = minRateReq.shape
        _, n_RBs = sharedFlag.shape

        ids = torch.arange(pi.size(1), dtype=torch.int64)
        penaltyFactor = 1000.
        scaleFactor = 1000.

        penalizedAggregateThroughput = torch.zeros(batch_size,
                                                   dtype=torch.float,
                                                   device=pi.device)

        for i in range(pi.size(0)):

            selected = pi[i, :]
            ids_withoutDepot = ids[selected >= 1]

            selectedUsers = ((selected[ids_withoutDepot] - 1) //
                             n_RBs).cpu().numpy()  # -1 because of depot
            selectedRBs = ((selected[ids_withoutDepot] - 1) %
                           n_RBs).cpu().numpy()  # -1 because of depot

            U = n_users
            K = availRBNum[i]

            if K == 0:
                penalizedAggregateThroughput[i] = 0.
                continue

            alpha_val = np.zeros((U, K), dtype=int)
            alpha_val[selectedUsers, selectedRBs] = 1

            P = cp.Variable(shape=(U, K))
            Delta = cp.Variable(shape=U)
            g_val = chGain[i, :]
            gain = g_val[g_val != 0].reshape((U, K))

            b_embb = ML.PRB_BW[numerology[i]] / scaleFactor

            # This function will be used as the objective so must be DCP;
            # i.e. elementwise multiplication must occur inside kl_div,
            # not outside otherwise the solver does not know if it is DCP...
            R = cp.multiply((b_embb / np.log(2)),
                            cp.multiply(alpha_val,
                                        cp.log1p(cp.multiply(P, gain))))

            objective = cp.Minimize(
                -cp.sum(R) +
                cp.multiply(penaltyFactor, cp.sum(cp.power(Delta, 2))))
            constraints = [
                cp.sum(cp.multiply(alpha_val, P)) <= availPower[i],
                (Delta + cp.sum(R, axis=1)) >=
                (minRateReq[i, :] / scaleFactor), P >= 0.0, Delta >= 0.0
            ]

            prob = cp.Problem(objective, constraints)
            prob.solve(solver=cp.MOSEK)

            penalizedAggregateThroughput[i] = prob.value

        return (penalizedAggregateThroughput), None
Ejemplo n.º 13
0
along with CVXPY.  If not, see <http://www.gnu.org/licenses/>.
"""

import cvxpy as cvx
import numpy.random as r
import numpy as np
from cvxpy.reductions.dcp2cone.dcp2cone import Dcp2Cone

n = 5
x = cvx.Variable(n)
y = cvx.Variable()
A = r.rand(n, n)
b = r.rand(n, 1)

l = np.random.randn(5, 4)
c = [cvx.abs(A * x + b) <= 2, cvx.abs(y) + x[0] <= 1, cvx.log1p(x) >= 5]
c.append(cvx.log_sum_exp(l, axis=0) <= 10)
X = cvx.Variable((5, 5))
c.append(cvx.log_det(X) >= 10)
cvx.Minimize(x[0])
prob = cvx.Problem(cvx.Minimize(x[0] + x[1] + y), c)

d2c = Dcp2Cone()
d2c.accepts(prob)
new_prob = d2c.apply(prob)

print(prob)
print('\n\n')
print(new_prob)

prob.solve()
Ejemplo n.º 14
0
 def test_log1p(self):
     """Test domain for log1p.
     """
     dom = cp.log1p(self.a).domain
     Problem(Minimize(self.a), dom).solve()
     self.assertAlmostEqual(self.a.value, -1)