"""
Copyright, the CVXPY authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import numpy as np
import pytest
import scipy.sparse as sp

import cvxpy as cp
from cvxpy.reductions.solvers.defines import INSTALLED_SOLVERS


@pytest.mark.skipif('IPOPT' not in INSTALLED_SOLVERS, reason='IPOPT is not installed.')
class TestQuadFormDifferentFormats:

    def test_quad_form_dense_sparse_sparse(self):
        # Generate a random non-trivial quadratic program.
        m = 15
        n = 10
        p = 5
        np.random.seed(1)
        P = np.random.randn(n, n)
        P = P.T @ P
        q = np.random.randn(n)
        G = np.random.randn(m, n)
        h = G @ np.random.randn(n, 1)
        A = np.random.randn(p, n)
        b = np.random.randn(p, 1)
        x = cp.Variable((n, 1))

        constraints = [G @ x <= h,
                       A @ x == b]

        # dense problem
        x.value = None
        prob = cp.Problem(cp.Minimize((1/2)*cp.quad_form(x, P) + q.T @ x),
                        constraints)
        prob.solve(nlp=True, verbose=False)
        dense_val = x.value

        # CSR problem
        x.value = None
        P_csr = sp.csr_matrix(P)
        prob = cp.Problem(cp.Minimize((1/2)*cp.quad_form(x, P_csr) + q.T @ x),
                        constraints)
        prob.solve(nlp=True, verbose=False)
        csr_val = x.value

        # CSC problem
        x.value = None
        P_csc = sp.csc_matrix(P)
        prob = cp.Problem(cp.Minimize((1/2)*cp.quad_form(x, P_csc) + q.T @ x),
                        constraints)
        prob.solve(nlp=True, verbose=False)
        csc_val = x.value

        assert np.allclose(dense_val, csr_val)
        assert np.allclose(dense_val, csc_val)

    def test_quad_form_dense_sparse_sparse_different_x(self):
        # Generate a random non-trivial quadratic program.
        m = 15
        n = 10
        p = 5
        np.random.seed(1)
        P = np.random.randn(n, n)
        P = P.T @ P
        q = np.random.randn(n)
        G = np.random.randn(m, n)
        h = G @ np.random.randn(n)
        A = np.random.randn(p, n)
        b = np.random.randn(p)
        x = cp.Variable(n)

        constraints = [G @ x <= h,
                       A @ x == b]

        # dense problem
        x.value = None
        prob = cp.Problem(cp.Minimize((1/2)*cp.quad_form(x, P) + q.T @ x),
                        constraints)
        prob.solve(nlp=True, verbose=False)
        dense_val = x.value

        # CSR problem
        x.value = None
        P_csr = sp.csr_matrix(P)
        prob = cp.Problem(cp.Minimize((1/2)*cp.quad_form(x, P_csr) + q.T @ x),
                        constraints)
        prob.solve(nlp=True, verbose=False)
        csr_val = x.value

        # CSC problem
        x.value = None
        P_csc = sp.csc_matrix(P)
        prob = cp.Problem(cp.Minimize((1/2)*cp.quad_form(x, P_csc) + q.T @ x),
                        constraints)
        prob.solve(nlp=True, verbose=False)
        csc_val = x.value

        assert np.allclose(dense_val, csr_val)
        assert np.allclose(dense_val, csc_val)

    def test_parameterized_quad_form_errors_clearly(self):
        n = 4
        x = cp.Variable(n, bounds=[-1, 1])
        rng = np.random.default_rng(0)
        P_val = rng.random((n, n))
        P_val = P_val + P_val.T
        P = cp.Parameter((n, n), symmetric=True, value=P_val)
        prob = cp.Problem(cp.Minimize(cp.quad_form(x, P)))

        with pytest.raises(NotImplementedError, match="parameterized P"):
            prob.solve(nlp=True)
