Coder Social home page Coder Social logo

The "No gradients provided for any variable" error occurs when optimizing the position of the antenna with Sionna RT about sionna HOT 5 CLOSED

JackYifan avatar JackYifan commented on September 20, 2024
The "No gradients provided for any variable" error occurs when optimizing the position of the antenna with Sionna RT

from sionna.

Comments (5)

SebastianCa avatar SebastianCa commented on September 20, 2024

Hi @JackYifan,

The Sionna ray tracer currently does not provide gradients with respect to the transmitter position. You can confirm this by printing the grads variable, which is None in your experiment. However, it works for the transmitter orientation; you can simply make the orientation variable trainable (and deactivate the trainable transmitter position).

For an alternative approach, the Instant Radio Map repository allows access to transmitter gradients. This requires registering the transmitter position as a trainable variable. You can find more details in the InstantRM Tutorial notebook.

I hope this helps!

I'll close this issue.

from sionna.

JackYifan avatar JackYifan commented on September 20, 2024

@SebastianCa I have learned the InstantRM Tutorial notebook but still don't know how to optimize the antenna position. It seems that InstantRM can only optimize the parameters in params, where the params = mi.traverse(scene) can you give me an example please? Thank you.

from sionna.

SebastianCa avatar SebastianCa commented on September 20, 2024

@JackYifan please understand that InstantRM is not part of Sionna and I can't provide support here. However, it might be a good start to look into the above mentioned tutorial and the Differentiable Geometry Tutorial.

from sionna.

JackYifan avatar JackYifan commented on September 20, 2024

@SebastianCa I found that the gradients with respect to the transmitter position can be calculated in the following code. But I don't understand how does this happened, these two code snippets are almost the same. Could you explain the reason why?

# Set some environment variables
import os
gpu_num = 0 # GPU to be used. Use "" to use the CPU
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Suppress some TF warnings
os.environ["CUDA_VISIBLE_DEVICES"] = f"{gpu_num}"

# Import Sionna
try:
    import sionna
except ImportError as e:
    # Install Sionna if package is not already installed
    os.system("pip install sionna")
    import sionna

# Configure GPU
import tensorflow as tf
gpus = tf.config.list_physical_devices('GPU')
if gpus:
    try:
        tf.config.experimental.set_memory_growth(gpus[0], True)
    except RuntimeError as e:
        print(e)

# Avoid warnings from TensorFlow
import warnings
tf.get_logger().setLevel('ERROR')
warnings.filterwarnings('ignore')

# Other imports
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.patches as patches

from sionna.rt import load_scene, PlanarArray, Transmitter, Receiver, Camera

# Fix the seed for reproducible results
tf.random.set_seed(1)
# Load the scene
scene = load_scene(sionna.rt.scene.etoile)

# Set the scattering coefficient of the radio material in the scene
# to a non-zero value to enable scattering
for mat in scene.radio_materials.values():
    mat.scattering_coefficient = 1./tf.sqrt(3.)

# Configure the transmit array
scene.tx_array = PlanarArray(num_rows=1, num_cols=16,
                             vertical_spacing=0.5,
                             horizontal_spacing=0.5,
                             pattern="dipole",
                             polarization="V",
                             polarization_model=2)

# Configure the receive array (use to compute the coverage map)
scene.rx_array = PlanarArray(num_rows=1, num_cols=1,
                             vertical_spacing=0.5,
                             horizontal_spacing=0.5,
                             pattern="iso",
                             polarization="V",
                             polarization_model=2)

# Create a transmitter and add it to the scene
tx = Transmitter("tx", position=tf.Variable([-232, 130, 25.0],trainable=True),
                 orientation=tf.Variable([0.0,0.0,0.0],trainable=False)) # Trainable orientation
scene.add(tx)

cm_cell_size = np.array([0.1,0.1]) # Each cell is 2mx2m
# Rectangle defining the target area
target_center = np.array([-2.5,-2.5,6]) # Center
target_size = np.array([5.,5.]) # Size
target_orientation = np.array([0.,0.,0.]) # Orientation: parallel to XY
# Configure an SGD optimizer
optimizer = tf.keras.optimizers.RMSprop(1e-3)

# Number of training steps
num_steps = 30
def train_step():
    """A single training step"""
    with tf.GradientTape() as tape:
        # Compute coverage of the target area
        target_cm = scene.coverage_map(cm_center=target_center,
                                       cm_orientation=target_orientation, 
                                       cm_size=target_size, # Target area 
                                       cm_cell_size=cm_cell_size,
                                       diffraction=True, scattering=True, # Enable diffraction and scattering in addition to reflection and LoS
                                       check_scene=False) # Don't check the scene prior to compute to speed things up
        # The loss function is a rate in bit
        # We fix an arbitrary scaling factor corresponding to the transmit to noise power ratio
        # The scaling has a direct impact the gradient magnitudes
        scaling = 1e6
        rate = tf.reduce_mean(tf.math.log(1. + target_cm.as_tensor()*scaling))/tf.math.log(2.)
        loss = -rate
        
    
    # Compute gradients and apply through the optimizer
    # print(tape.watched_variables())
    grads = tape.gradient(loss, tape.watched_variables())
    # print(grads)
    optimizer.apply_gradients(zip(grads, tape.watched_variables()))
    return rate

for step in range(num_steps):       
    rate = train_step()
    print(f"Training step {step} - Rate: {rate.numpy():.2E} bit - tx position: {scene.transmitters['tx'].position.numpy()}", end='\n')

from sionna.

SebastianCa avatar SebastianCa commented on September 20, 2024

It seems there is a lack of gradients resulting from diffraction. When you disable diffraction, the gradient becomes None again. This likely indicates incomplete gradients, so I would not recommend using this setup to optimize your transmitter position. As mentioned above, InstantRM does not have this conceptual limitation.

from sionna.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.