toqito icon indicating copy to clipboard operation
toqito copied to clipboard

Feature: Add ability to perturb a vector by some factor

Open vprusso opened this issue 2 years ago • 4 comments

For various purposes, it is often useful to perturb a vector by some random amount scaled by some factor.

The following function takes in a list of vectors and some factor eps in which each vector in the list is randomly perturbed:

import numpy as np


def perturb_vectors(vectors: list[np.ndarray], eps: float = 0.1) -> list[np.ndarray]:
    """Perturb the vectors by adding a small random number to each element.

    :param vectors: List of vectors to perturb.
    :param eps: Amount by which to perturb vectors.
    :return: Resulting list of perturbed vectors by a factor of epsilon.
    """
    perturbed_vectors: list[np.ndarray] = []
    for i, v in enumerate(vectors):
        perturbed_vectors.append(v + np.random.randn(v.shape[0]) * eps)

        # Normalize the vectors after perturbing them.
        perturbed_vectors[i] = perturbed_vectors[i] / np.linalg.norm(perturbed_vectors[i])
    return np.array(perturbed_vectors)

The function can probably be written in a more concise manner and also requires documentation and tests.

vprusso avatar Nov 18 '23 13:11 vprusso

Hi! What do you mean by concise here, because it is not very complex to understand right now. One thing we could do is remove the loop by creating a random vector for the noise which matches the given vector's dimensions, and then add the noise to the vector. Just an idea, but I am not sure if this will improve the performance by a great margin. Let me know if this is something you want to implement. I will be happy to do it. Thank you

Shivansh20128 avatar Oct 12 '24 14:10 Shivansh20128

What do you mean by concise here, because it is not very complex to understand right now.

True! It seems to be about as concise as anything, so brevity is probably not anything that needs to be explicitly improved upon!

Indeed, I think you're correct that about the only thing we really need to do would be to write a proper docstring and tests for this and it should be in relatively good shape! I'll assign it to you for now, but feel free to let me know if that doesn't work as I know you have a lot on your plate!

vprusso avatar Oct 14 '24 18:10 vprusso

@vprusso Thank you for the assignment. Since this will be a new addition, can I add a new submodule to state_ops as this is an operation that will work on state vectors? Otherwise, let me know where I should make this addition. Thank you

Shivansh20128 avatar Oct 15 '24 05:10 Shivansh20128

I think matrix_ops/ might be the better spot for this as this operates on any set of vectors (and not necessarily a set of quantum states), but aside from that, yes, I think you have the right idea!

vprusso avatar Oct 15 '24 11:10 vprusso