Module: Gsplat::Backend::RubySphericalHarmonics

Defined in:
lib/gsplat/backend/ruby/spherical_harmonics.rb

Overview

Numo forward/backward implementation of real spherical harmonics.

Class Method Summary collapse

Class Method Details

.backward(degree, directions, coefficients, grad_output, masks: nil, grad_dirs: true, grad_coeffs: true) ⇒ Object

rubocop:disable Metrics/ParameterLists



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/gsplat/backend/ruby/spherical_harmonics.rb', line 25

def backward(degree, directions, coefficients, grad_output, masks: nil, grad_dirs: true, grad_coeffs: true)
  # rubocop:enable Metrics/ParameterLists
  directions, coefficients, masks, leading_shape = validate_inputs(degree, directions, coefficients, masks)
  count = directions.size / 3
  basis_count = coefficients.shape[-2]
  channel_count = coefficients.shape[-1]
  gradient = directions.class.cast(grad_output)
  expected = leading_shape + [channel_count]
  unless gradient.shape == expected
    raise ShapeError, "expected output gradient #{expected.inspect}, got #{gradient.shape.inspect}"
  end

  normalized = normalize_directions(directions).reshape(count, 3)
  bases, derivatives = Math::SphericalHarmonicBasis.evaluate(normalized, degree, basis_count)
  apply_masks!(bases, derivatives, masks)
  gradient = gradient.reshape(count, channel_count)
  coefficient_values = coefficients.reshape(count, basis_count, channel_count)
  coefficient_gradient = if grad_coeffs
                           bases.reshape(count, basis_count, 1) * gradient.reshape(count, 1, channel_count)
                         end
  if grad_dirs
    direction_gradient = direction_gradient(
      directions,
      coefficient_values,
      gradient,
      derivatives,
      leading_shape
    )
  end
  [
    direction_gradient,
    coefficient_gradient&.reshape(*(leading_shape + [basis_count, channel_count]))
  ]
end

.forward(degree, directions, coefficients, masks: nil) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/gsplat/backend/ruby/spherical_harmonics.rb', line 9

def forward(degree, directions, coefficients, masks: nil)
  directions, coefficients, masks, leading_shape = validate_inputs(degree, directions, coefficients, masks)
  count = directions.size / 3
  basis_count = coefficients.shape[-2]
  channel_count = coefficients.shape[-1]
  normalized = normalize_directions(directions).reshape(count, 3)
  bases, = Math::SphericalHarmonicBasis.evaluate(normalized, degree, basis_count)
  apply_masks!(bases, nil, masks)
  colors = (
    bases.reshape(count, basis_count, 1) *
    coefficients.reshape(count, basis_count, channel_count)
  ).sum(axis: 1)
  colors.reshape(*(leading_shape + [channel_count]))
end