bqth29 / simulated-bifurcation-algorithm

Python CPU/GPU implementation of the Simulated Bifurcation (SB) algorithm to solve quadratic optimization problems (QUBO, Ising, TSP, optimal asset allocations for a portfolio, etc.).
MIT License
103 stars 25 forks source link

ValueError: Matrix must be square. #45

Closed MarMarhoun closed 8 months ago

MarMarhoun commented 8 months ago

Screenshot from 2023-12-14 23-39-52 Screenshot from 2023-12-14 23-40-36

I used this code to perform an opt task and I read on the docs that the An Ising problem, given a null-diagonal square symmetrical matrix.

sb.set_env(time_step=.1, pressure_slope=.01, heat_coefficient=.06)
best_vector, best_value = sb.maximize(matrix, agents=100, device='cuda', 
                                      max_steps=10000, sampling_period=30, ballistic= True, 
                                      convergence_threshold=50, use_window=True, heated=True, `best_only=True)`

The following error appears:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
[<ipython-input-65-6fffbfba281a>](https://localhost:8080/#) in <cell line: 2>()
      1 sb.set_env(time_step=.1, pressure_slope=.01, heat_coefficient=.06)
----> 2 best_vector, best_value = sb.maximize(matrix, agents=100, device='cuda', 
      3                                       max_steps=10000, sampling_period=30, ballistic= True,
      4                                       convergence_threshold=50, use_window=True, heated=True, best_only=True)
      5 

6 frames
[/usr/local/lib/python3.10/dist-packages/simulated_bifurcation/simulated_bifurcation.py](https://localhost:8080/#) in maximize(matrix, vector, constant, domain, dtype, device, agents, max_steps, best_only, ballistic, heated, verbose, use_window, sampling_period, convergence_threshold, timeout, input_type)
    864         domain = input_type
    865 
--> 866     return optimize(
    867         matrix,
    868         vector,

[/usr/local/lib/python3.10/dist-packages/simulated_bifurcation/simulated_bifurcation.py](https://localhost:8080/#) in optimize(matrix, vector, constant, domain, dtype, device, agents, max_steps, best_only, ballistic, heated, minimize, verbose, use_window, sampling_period, convergence_threshold, timeout, input_type)
    315         domain = input_type
    316 
--> 317     model = build_model(
    318         matrix=matrix,
    319         vector=vector,

[/usr/local/lib/python3.10/dist-packages/simulated_bifurcation/simulated_bifurcation.py](https://localhost:8080/#) in build_model(matrix, vector, constant, domain, dtype, device, input_type)
   1043 
   1044     if domain == "spin":
-> 1045         return SpinQuadraticPolynomial(
   1046             matrix=matrix,
   1047             vector=vector,

[/usr/local/lib/python3.10/dist-packages/simulated_bifurcation/polynomial/spin_polynomial.py](https://localhost:8080/#) in __init__(self, matrix, vector, constant, dtype, device, silence_deprecation_warning)
    155             )
    156 
--> 157         super().__init__(
    158             matrix,
    159             vector,

[/usr/local/lib/python3.10/dist-packages/simulated_bifurcation/polynomial/base_multivariate_polynomial.py](https://localhost:8080/#) in __init__(self, matrix, vector, constant, accepted_values, dtype, device, silence_deprecation_warning)
     81             )
     82         self.__check_device(device)
---> 83         self.__init_matrix(matrix, dtype, device)
     84         self.__init_vector(vector, dtype, device)
     85         self.__init_constant(constant, dtype, device)

[/usr/local/lib/python3.10/dist-packages/simulated_bifurcation/polynomial/base_multivariate_polynomial.py](https://localhost:8080/#) in __init_matrix(self, matrix, dtype, device)
    189     ) -> None:
    190         tensor_matrix = self._cast_matrix_to_tensor(matrix, dtype, device)
--> 191         self.__check_square_matrix(tensor_matrix)
    192         self.__matrix = tensor_matrix
    193         self.__dimension = tensor_matrix.shape[0]

[/usr/local/lib/python3.10/dist-packages/simulated_bifurcation/polynomial/base_multivariate_polynomial.py](https://localhost:8080/#) in __check_square_matrix(matrix)
    252             raise ValueError(f"Matrix requires two dimension, got {matrix.ndim}.")
    253         if matrix.shape[0] != matrix.shape[1]:
--> 254             raise ValueError("Matrix must be square.")
    255 
    256     def __check_vector_shape(self, vector: torch.Tensor) -> None:

ValueError: Matrix must be square.
bqth29 commented 8 months ago

Hi @MarMarhoun and thanks for reaching out.

I run the code snippet you sent on my side and it appears that the data tensor you are trying to use as an input for the SB algorithm has a shape (252, 6).

For SB to work, the input matrix you provide must be square, i.e. it must have 2 dimensions and both must be the same. The problem you encountered comes from the difference between the two dimensions of the matrix.

Hope this could help.

All the best!

MarMarhoun commented 8 months ago

Greetings @bqth29, Yes, I know this issue is there any way I can solve this issue?

I tried the following code to run the simulated bifurcation algorithm. However, I received an issue during the implementation.

Here is the code:

    !pip install yfinance
    !pip install plotly
    !pip install tqdm
    !pip install numpy
    !pip install pandas
    !pip install simulated-bifurcation
    !pip install deap
    !pip install plotly_express
    import yfinance as yf
    import torch
    import random # linear algebra
    import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
    import yfinance as yf
    import matplotlib.pyplot as plt

    import json
    import numpy as np
    import simulated_bifurcation as sb

    def get_data(asset_name, period='1y', interval='1d'):
        data = yf.download(tickers=asset_name, period=period, interval=interval)
        return data

    def optimize_sb(matrix, **kwargs):
        sb.set_env(time_step=.1, pressure_slope=.01, heat_coefficient=.06)
        best_vector, best_value = sb.maximize(matrix, **kwargs)
        return best_vector, best_value
if __name__ == "__main__":
    asset_name = 'AAPL'
    data = get_data(asset_name)
    matrix = torch.tensor(data.to_numpy())

    agents = 100
    max_steps = 10000
    sampling_period = 30
    convergence_threshold = 50
    device = 'cuda' # To enable the GPU

    best_vector, best_value = optimize_sb(matrix, agents=agents, device=device,
                                      max_steps=max_steps, sampling_period=sampling_period, ballistic= True,
                                      convergence_threshold=convergence_threshold, use_window=True, heated=True, best_only=True)

Here is the issue:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-efec6dd548a5> in <cell line: 2>()
      1 sb.set_env(time_step=.1, pressure_slope=.01, heat_coefficient=.06)
----> 2 best_vector, best_value = sb.maximize(matrix, agents=100, device='cuda', 
      3                                       max_steps=10000, sampling_period=30, ballistic= True,
      4                                       convergence_threshold=50, use_window=True, heated=True, best_only=True)

6 frames
/usr/local/lib/python3.10/dist-packages/simulated_bifurcation/polynomial/base_multivariate_polynomial.py in __check_square_matrix(matrix)
    252             raise ValueError(f"Matrix requires two dimension, got {matrix.ndim}.")
    253         if matrix.shape[0] != matrix.shape[1]:
--> 254             raise ValueError("Matrix must be square.")
    255 
    256     def __check_vector_shape(self, vector: torch.Tensor) -> None:

ValueError: Matrix must be square.
bqth29 commented 8 months ago

Hi @MarMarhoun,

It appears that your input matrix does not suit the SB algorithm because it is not square. Could you explain us what your code is trying to achieve to see if we can apply some operations to said matrix to make it square and compatible with SB?

All the best!