Skip to content
ForCADDocumentation
Browse guide contents ↓

Fit a NURBS volume to a sample grid

Fit a quarter-ring volume from 108 positions on a structured grid. U follows the angle, V increases from the inner to the outer radius, and W increases through the thickness. The example generates known positions so you can check the fit at an interior point between measurement stations.

Use one row per measurement in both uvw and measured. With U varying fastest, the one-based row for sample is . For your own measurements, fill each measured(row,:) with the physical coordinates recorded at the corresponding parameter triple.

program fit_a_volume
    use forcad, only: rk, nurbs_volume
    implicit none
    type(nurbs_volume) :: sector
    integer, parameter :: n(3) = [9, 4, 3], ends(2) = [-1, -1]
    real(rk), parameter :: bounds(2) = [0._rk, 1._rk], probe(3) = [0.37_rk, 0.42_rk, 0.58_rk]
    real(rk) :: uvw(product(n),3), measured(product(n),3), point(3), distance
    integer :: i, j, k, row

    do k = 1, n(3)
        do j = 1, n(2)
            do i = 1, n(1)
                row = i + n(1)*((j-1) + n(2)*(k-1))
                uvw(row,:) = real([i-1, j-1, k-1],rk) / real(n-1,rk)
                measured(row,:) = position(uvw(row,:))
            end do
        end do
    end do

    call sector%set(degree=[2,1,1], Xth_dir1=bounds, Xth_dir2=bounds, Xth_dir3=bounds, &
                   continuity1=ends, continuity2=ends, continuity3=ends)
    if (.not. sector%err%ok) error stop "Could not define the spline space"
    call sector%lsq_fit_nurbs(Xt=uvw, Xdata=measured, ndata=n, maxit=100, tol=1.e-10_rk)
    if (.not. sector%err%ok) then
        call sector%err%print()
        error stop "Volume fitting failed"
    end if
    point = sector%cmp_Xg(probe)
    distance = norm2(point - position(probe))
    print '(a,3f9.4)', "Fitted point (mm):", point
    print '(a,f9.5)', "Error at probe (mm):", distance
    if (distance > 0.03_rk) error stop "Probe exceeds 0.03 mm tolerance"
contains
    pure function position(parameter) result(xyz)
        real(rk), intent(in) :: parameter(3)
        real(rk) :: xyz(3), angle, radius
        angle = acos(-1._rk)*parameter(1)/2._rk
        radius = 20._rk + 10._rk*parameter(2)
        xyz = [radius*cos(angle), radius*sin(angle), 15._rk*parameter(3)]
    end function
end program

The twelve controls and their positive weights are fitted to all 108 samples. At the unused parameter triple , the fitted point is approximately mm. Its distance from the known point is 0.01947 mm. This checks one location. With measured data, reserve independent points across the region where you need to meet a tolerance.

For a larger example that fits a torus volume and writes VTK files, run fpm run --example lsq_fit_nurbs_3d --profile release from the checkout. Bundled example source.