# Buggy code
def measure_homodyne(self, phi, mode, select=None, **kwargs):
    """
    Performs a homodyne measurement on a mode.
    """
    m_omega_over_hbar = 1 / self._hbar

    # Make sure the state is mixed for reduced density matrix
    if self._pure:
        state = ops.mix(self._state, self._num_modes)
    else:
        state = self._state

    if select is not None:
        meas_result = select
        if isinstance(meas_result, numbers.Number):
            homodyne_sample = float(meas_result)
        else:
            raise TypeError("Selected measurement result must be of numeric type.")
    else:
        # Compute reduced density matrix
        unmeasured = [i for i in range(self._num_modes) if not i == mode]
        reduced = ops.partial_trace(state, self._num_modes, unmeasured)

        # Rotate to measurement basis
        reduced = self.apply_gate_BLAS(
            ops.phase(-phi, self._trunc), [0], state=reduced, pure=False, n=1
        )

        # Create pdf. Same as tf implementation, but using
        # the recursive relation H_0(x) = 1, H_1(x) = 2x, H_{n+1}(x) = 2xH_n(x) - 2nH_{n-1}(x)
        q_mag = kwargs.get("max", 10)
        num_bins = kwargs.get("num_bins", 100000)

        q_tensor, Hvals = ops.hermiteVals(
            q_mag, num_bins, m_omega_over_hbar, self._trunc
        )
        H_matrix = np.zeros((self._trunc, self._trunc, num_bins))
        for n, m in product(range(self._trunc), repeat=2):
            H_matrix[n][m] = (
                1 / sqrt(2**n * bang(n) * 2**m * bang(m)) * Hvals[n] * Hvals[m]
            )
        H_terms = np.expand_dims(reduced, -1) * np.expand_dims(H_matrix, 0)
        rho_dist = (
            np.sum(H_terms, axis=(1, 2))
            * (m_omega_over_hbar / pi) ** 0.5
            * np.exp(-m_omega_over_hbar * q_tensor**2)
            * (q_tensor[1] - q_tensor[0])
        )  # Delta_q for normalization (only works if the bins are equally spaced)

        # Sample from rho_dist. This is a bit different from tensorflow due to how
        # numpy treats multinomial sampling. In particular, numpy returns a
        # histogram of the samples whereas tensorflow gives the list of samples.
        # Numpy also does not use the log probabilities
        probs = rho_dist.flatten().real
        probs /= np.sum(probs)
        sample_hist = np.random.multinomial(1, probs)
        sample_idx = list(sample_hist).index(1)
        homodyne_sample = q_tensor[sample_idx]

    # Project remaining modes into the conditional state
    inf_squeezed_vac = np.array(
        [
            (-0.5) ** (n // 2) * sqrt(bang(n)) / bang(n // 2)
            if n % 2 == 0
            else 0.0 + 0.0j
            for n in range(self._trunc)
        ],
        dtype=ops.def_type,
    )
    alpha = homodyne_sample * sqrt(m_omega_over_hbar / 2)

    composed = np.dot(ops.phase(phi, self._trunc), ops.displacement(alpha, self._trunc))
    eigenstate = self.apply_gate_BLAS(
        composed, [0], state=inf_squeezed_vac, pure=True, n=1
    )

    vac_state = np.array(
        [1.0 + 0.0j if i == 0 else 0.0 + 0.0j for i in range(self._trunc)],
        dtype=ops.def_type,
    )
    projector = np.outer(vac_state, eigenstate.conj())

    self._state = self.apply_gate_BLAS(projector, [mode])

    # Normalize
    self._state = self._state / self.norm()

    return homodyne_sample


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-27-d8f9402683f5> in <module>
2
3 for x in pbar(flag):
----> 4     dummy = xaxb()
5
6     x_vals[i]=dummy[0]

<ipython-input-22-64fa305c29f6> in xaxb()
12         MeasureX | q[1]
13
---> 14     result = eng.run(prog)
15
16     x, y = result.samples

~/opt/anaconda3/lib/python3.7/site-packages/strawberryfields/engine.py in run(self, program, args, compile_options, run_options)
479         eng_run_options = {key: temp_run_options[key] for key in temp_run_options.keys() &amp; eng_run_keys}
480
--> 481         result = super()._run(program, args=args, compile_options=compile_options, **eng_run_options)
482
483         modes = temp_run_options["modes"]

~/opt/anaconda3/lib/python3.7/site-packages/strawberryfields/engine.py in _run(self, program, args, compile_options, **kwargs)
347             p.lock()
348
--> 349             self._run_program(p, **kwargs)
350             self.run_progs.append(p)
351             # store the latest measurement results

~/opt/anaconda3/lib/python3.7/site-packages/strawberryfields/engine.py in _run_program(self, prog, **kwargs)
421             try:
422                 # try to apply it to the backend
--> 423                 cmd.op.apply(cmd.reg, self.backend, **kwargs)  # NOTE we could also handle storing measured vals here
424                 applied.append(cmd)
425             except NotApplicableError:

~/opt/anaconda3/lib/python3.7/site-packages/strawberryfields/ops.py in apply(self, reg, backend, **kwargs)
285                 Only applies to Measurements.
286         """
--> 287         values = super().apply(reg, backend, **kwargs)
288         # convert the returned values into an iterable with the measured modes indexed along
289         # the first axis and shots along second axis (if larger than 1), so that we can assign

~/opt/anaconda3/lib/python3.7/site-packages/strawberryfields/ops.py in apply(self, reg, backend, **kwargs)
217         temp = [rr.ind for rr in reg]
218         # call the child class specialized _apply method
--> 219         return self._apply(temp, backend, **kwargs)
220
221

~/opt/anaconda3/lib/python3.7/site-packages/strawberryfields/ops.py in _apply(self, reg, backend, shots, **kwargs)
806             select = select / s
807
--> 808         return s * backend.measure_homodyne(p[0], *reg, shots=shots, select=select, **kwargs)
809
810     def __str__(self):

~/opt/anaconda3/lib/python3.7/site-packages/strawberryfields/backends/fockbackend/backend.py in measure_homodyne(self, phi, mode, shots, select, **kwargs)
187             raise NotImplementedError("fock backend currently does not support "
188                                       "shots != 1 for homodyne measurement")
--> 189         return self.circuit.measure_homodyne(phi, self._remap_modes(mode), select=select, **kwargs)
190
191     def loss(self, T, mode):

~/opt/anaconda3/lib/python3.7/site-packages/strawberryfields/backends/fockbackend/circuit.py in measure_homodyne(self, phi, mode, select, **kwargs)
498             probs = rho_dist.flatten().real
499             probs /= np.sum(probs)
--> 500             sample_hist = np.random.multinomial(1, probs)
501             sample_idx = list(sample_hist).index(1)
502             homodyne_sample = q_tensor[sample_idx]

mtrand.pyx in numpy.random.mtrand.RandomState.multinomial()

_common.pyx in numpy.random._common.check_array_constraint()

ValueError: pvals < 0, pvals > 1 or pvals contains NaNs

# Fixed code
def measure_homodyne(self, phi, mode, select=None, **kwargs):
    """
    Performs a homodyne measurement on a mode.
    """
    m_omega_over_hbar = 1 / self._hbar

    # Make sure the state is mixed for reduced density matrix
    if self._pure:
        state = ops.mix(self._state, self._num_modes)
    else:
        state = self._state

    if select is not None:
        meas_result = select
        if isinstance(meas_result, numbers.Number):
            homodyne_sample = float(meas_result)
        else:
            raise TypeError("Selected measurement result must be of numeric type.")
    else:
        # Compute reduced density matrix
        unmeasured = [i for i in range(self._num_modes) if not i == mode]
        reduced = ops.partial_trace(state, self._num_modes, unmeasured)

        # Rotate to measurement basis
        reduced = self.apply_gate_BLAS(
            ops.phase(-phi, self._trunc), [0], state=reduced, pure=False, n=1
        )

        # Create pdf. Same as tf implementation, but using
        # the recursive relation H_0(x) = 1, H_1(x) = 2x, H_{n+1}(x) = 2xH_n(x) - 2nH_{n-1}(x)
        q_mag = kwargs.get("max", 10)
        num_bins = kwargs.get("num_bins", 100000)

        q_tensor, Hvals = ops.hermiteVals(
            q_mag, num_bins, m_omega_over_hbar, self._trunc
        )
        H_matrix = np.zeros((self._trunc, self._trunc, num_bins))
        for n, m in product(range(self._trunc), repeat=2):
            H_matrix[n][m] = (
                1 / sqrt(2**n * bang(n) * 2**m * bang(m)) * Hvals[n] * Hvals[m]
            )
        H_terms = np.expand_dims(reduced, -1) * np.expand_dims(H_matrix, 0)
        rho_dist = (
            np.sum(H_terms, axis=(1, 2))
            * (m_omega_over_hbar / pi) ** 0.5
            * np.exp(-m_omega_over_hbar * q_tensor**2)
            * (q_tensor[1] - q_tensor[0])
        )  # Delta_q for normalization (only works if the bins are equally spaced)

        # Sample from rho_dist. This is a bit different from tensorflow due to how
        # numpy treats multinomial sampling. In particular, numpy returns a
        # histogram of the samples whereas tensorflow gives the list of samples.
        # Numpy also does not use the log probabilities
        probs = rho_dist.flatten().real
        probs /= np.sum(probs)

        # Due to floating point precision error, values in the calculated probability distribution
        # may have a very small negative value of -epsilon. The following sets
        # these small negative values to 0.
        probs[np.abs(probs) < 1e-10] = 0

        sample_hist = np.random.multinomial(1, probs)
        sample_idx = list(sample_hist).index(1)
        homodyne_sample = q_tensor[sample_idx]

    # Project remaining modes into the conditional state
    inf_squeezed_vac = np.array(
        [
            (-0.5) ** (n // 2) * sqrt(bang(n)) / bang(n // 2)
            if n % 2 == 0
            else 0.0 + 0.0j
            for n in range(self._trunc)
        ],
        dtype=ops.def_type,
    )
    alpha = homodyne_sample * sqrt(m_omega_over_hbar / 2)

    composed = np.dot(ops.phase(phi, self._trunc), ops.displacement(alpha, self._trunc))
    eigenstate = self.apply_gate_BLAS(
        composed, [0], state=inf_squeezed_vac, pure=True, n=1
    )

    vac_state = np.array(
        [1.0 + 0.0j if i == 0 else 0.0 + 0.0j for i in range(self._trunc)],
        dtype=ops.def_type,
    )
    projector = np.outer(vac_state, eigenstate.conj())

    self._state = self.apply_gate_BLAS(projector, [mode])

    # Normalize
    self._state = self._state / self.norm()

    return homodyne_sample