I am trying to run this code on Artiq:

import numpy as np
from numpy.random import rand
from artiq.experiment import *
class PolarizationOptimization(EnvExperiment):
    def build(self): # not connected to any hardware (random input and output)
        self.setattr_device("core")
        self.target_state = np.array([1, 0, 0])
    @kernel
    def read_inner(self):
        inner_product = np.random.uniform(low=0.0, high=1.0)  #generating random values from 0 and 1
        return inner_product
    @kernel
    def grad_func(self, params0, params1, learning_rate):
        inner_prev = self.read_inner(params0)
        inner_adv = self.read_inner(params1)
        delta_p = -(params1 - params0) * (abs(1 - inner_adv) - abs(1 - inner_prev)) * learning_rate
        if (inner_adv - inner_prev) < 0:
            params0 += delta_p
            return params0
        else:
            params1 += delta_p
            return params1
    @kernel
    def gradient_ascent(self, target_state = np.array([1,0,0]), max_iterations = 400, threshold = 0.01): 
        params0 = (np.random.rand(4)-0.5) * 4000

And I keep getting this error:

error: cannot coerce NoneType to a numeric type
        params0 = (np.random.rand(4)-0.5) * 4000

I am not able to understand the issue. I would be grateful if I could get some help with this.

2 months later

From my experience, in @kernel you should not use functions from numpy packages. Functions decorated by @kernel are executed in the FPGA chips in ARTIQ chassis, and they only support ARTIQ hardware operations and fundamental Python data types and calculations.
You may try to remove all numpy functions into rpc and try again.

Indeed, only a very limited subset of NumPy (mostly transcendental math functions) are supported on the core device at this stage.

The error occurs because the compiler treats np.random.rand as an RPC call, but since that NumPy function of course doesn't have an ARTIQ compiler return type annotation, it is treated as not returning anything. Hence the error: Can't subtract 0.5 from NoneType.

Since this appears to be a common trap to new users, it might be nice to have a better error message for this. You might want to open a feature request for this.