Dear community,
I realized I did not send this to Morphmet, but just to Prof. Rohlf.
I forward this this to the community.
Cheers
Paolo Piras

Il dom 18 ott 2026, 21:13 Paolo Piras <[email protected]> ha scritto:

> Dear Prof. Rohlf,
>
> Thank you for your message.
>
> Just for the sake of pedagogy, I realized that I had provided a GRF
> function but not one specifically designed for Ordinary Resistant Fit
> between just two shapes. With myorfit2() (attached), I was able to
> reproduce the results shown in the upper part of Fig. 1 in Siegel, A. F., &
> Benson, R. H. (1982), “A Robust Comparison of Biological Shapes,”
> *Biometrics*, 38(2), 341–350, the original reference for Resistant Fit. Of
> course, the appropriate comparison is with Full OPA, since Resistant Fit
> estimates the tau scale coefficient. I also tested its performance on
> both 2D and 3D configurations with 400 landmarks. The execution time is
> acceptable, without the need for complex coding solutions, given that the
> problem involves only two shapes.
>
> Here too, I took advantage of AI assistance to further optimize the code.
>
> All the best,
>
> Paolo
>
> #### Siegel and Benson (1982) Fig. 1 top part fully reproducible experiment
> library(shapes)
> library(Morpho)
> x <- matrix(c(
>   100, 160,
>   20, 123,
>   20,  43,
>   100,   3,
>   180,  43,
>   180, 123
> ), ncol = 2, byrow = TRUE)
> y <- matrix(c(
>   100, 160,
>   20, 123,
>   20,  43,
>   100,   3,
>   277,  40,
>   272, 124
> ), ncol = 2, byrow = TRUE)
> links<-list(c(1, 2), c(2, 3), c(3, 4), c(4, 5), c(5, 6), c(1, 6))
> orf <- myorfit2(x, y)
> opa <- Morpho::rotonto(x, y,scale=T)$yrot
> opanoscaling<-Morpho::rotonto(x, y,scale=F)$yrot
> sqrt(rowSums((x - orf)^2))
> sqrt(rowSums((x - opa)^2))
> par(mfrow=c(2,2),oma=c(1,1,3,1))
> plot(rbind(x,y),asp=1)
> lineplot(x,links)
> lineplot(y,links)
> title("Original shapes")
> plot(rbind(x,orf),asp=1)
> lineplot(x,links)
> lineplot(orf,links)
> title("Ordinary Resistant Fit")
> plot(rbind(x,opa),asp=1)
> lineplot(x,links)
> lineplot(opa,links)
> title("Ordinary Full Proc. Align.")
> plot(rbind(x,opanoscaling),asp=1)
> lineplot(x,links)
> lineplot(opanoscaling,links)
> title("OPA no scaling")
> title("Irregular shape is superimposed onto octagon",outer=T)
>
> ### speed
> x2<-matrix(rnorm(400 * 3), ncol=3)
> y2<-matrix(rnorm(400 * 3), ncol=3)
> system.time(myorfit2(x2,y2))
> system.time(myorfit2(x2[,1:2],y2[,1:2]))
>
>
>
>
>
>
>
> Il giorno dom 18 ott 2026 alle ore 09:25 F.James Rohlf <
> [email protected]> ha scritto:
>
>> Should be useful tool. If some subset of landmarks did not vary much in
>> shape it would be embarrassing if an investigator did not notice that
>> fact.  A tool like this should probably be used more often - even if not
>> often part of the formal analysis reported in a publication.  I have not
>> tried it yet because I am pretty busy with another project but it would be
>> interesting to check a few complex datasets.
>>
>> Jim
>>
>> ......................................................
>>
>> *F. James Rohlf*
>>
>> *Distinguished Professor, Emeritus*
>>
>> *Anthropology and Ecology & Evolution*
>>
>> *Stony Brook University*
>>
>> Office: 631.632.8580 <(631)%20632-8580>
>>
>> [email protected]
>>
>> [image: Stony Brook University logo] <http://www.stonybrook.edu/>
>>
>>
>> ------ Original Message ------
>> From "Paolo Piras" <[email protected]>
>> To
>> Cc "Morphmet" <[email protected]>
>> Date 10/16/2026 8:54:39 AM
>> Subject [MORPHMET2] Generalized Resistant fit fast implementation in R
>>
>> EXTERNAL EMAIL - This email was sent by a person from outside your
>> organization. Exercise caution when clicking links, opening attachments or
>> taking further action, before validating its authenticity.
>> Dear Morphometrics community,
>>
>> I have been working on accelerating resistant fitting in R and would
>> like to share a preliminary benchmark comparing my implementation,
>> myrfit2() (attached), with the R package RPS: Resistant Procrustes
>> Superimposition (Pacheco G, Torcida S, Ferraggine V, Lotto F (2018).
>> RPS: Resistant Procrustes Superimposition. DOI:
>> 10.32614/CRAN.package.RPS. R package version 1.0.1.).
>> Although resistant fitting is rarely used in practical applications
>> (for a **good** number of statistical and differential-geometry
>> reasons that I will not list here), it remains a classic pedagogical
>> example of the different approaches available in modern shape
>> analysis. Making it feasible to apply to large datasets could
>> therefore be a useful option.
>> I developed myrfit2() by moving computationally intensive operations
>> into C++ using Rcpp. The implementation is self-contained in a single
>> R source file: the C++ kernels are compiled automatically at the first
>> function call and cached for reuse within the same R session. This
>> avoids the need for a separately compiled package and prevents
>> compilation overhead from recurring on subsequent calls.
>> The code requires the Rcpp package and, if not already available, the
>> appropriate build tools (Rtools on Windows). To use it, simply copy
>> and paste the code into the R console.
>>
>> Preliminary benchmark
>> All benchmarks were run on a PC with 13th Gen Intel(R) Core(TM)
>> i9-13900HX, 63,7 GB of RAM, running Microsoft Windows 11 Pro, using R
>> version 4.5.2 (2025-10-31 ucrt).
>> On my system, using the same input array, with dimensions [1:20, 1:3,
>> 1:10], I obtained the following elapsed times:
>> RPS (robgit_RPS): 12.39 seconds
>> myrfit2(): 0.06 seconds
>> This corresponds to an approximately 207-fold speed-up, or about 99.5%
>> less elapsed time, for this particular test.
>> In a separate test involving an array dim = c(400, 3, 400) it tooks 65
>> sec.
>> RPS freezes on this dataset.
>> These results are preliminary and depend on the hardware and dataset.
>> More extensive benchmarking, with repeated runs and matched
>> algorithmic settings, would be needed to establish how the speed-up
>> scales with dataset size and to ensure that the compared procedures
>> perform equivalent computational tasks.
>>
>> A typical use:
>>
>> arru <- array(rnorm(20 * 3 * 10), dim = c(20, 3, 10))
>> system.time(provarps<-RPS::robgit_RPS(arru[1:20,1:3,1:10]))
>> system.time(provamyrfit2<-myrfit2(arru[1:20,1:3,1:10]))
>> range(provarps-provamyrfit2)
>>
>>
>> Role of AI assistance
>> I **of course** used ChatGPT as an assistant during development,
>> particularly for translating computational bottlenecks into C++ and
>> integrating Rcpp. The process turned out to be considerably more
>> laborious than expected from my initial prompt. Nevertheless, given my
>> limited Rcpp programming skills, I doubt I could have achieved this
>> result without AI assistance.
>> I would welcome feedback from the community on the implementation
>> strategy, potential further optimizations, and appropriate
>> benchmarking practices.
>>
>> Best regards
>> Paolo Piras
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Morphmet" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to [email protected].
>> To view this discussion visit
>> https://protect.checkpoint.com/v2/r01/___https://groups.google.com/d/msgid/morphmet2/CAAdPgfPOuwec-B0DzuP*2Bg-VF*3DkjcJr-652y01ecKUzcPpWX52Q*40mail.gmail.com___.YzJ1OnN0b255YnJvb2s6YzpnOmQwMjlkMTdkN2Y3MzlmZGE1ODI3NzgzZGFlMzQ2ZGIyOjc6MDlhMDo0YmFmNmIyZDE4Njg0YjgyNDNlYTRmNzMzOGYwMmE2NzVhYWE2OGI2YmYwNTI3ODc3ZTc5NWUwMjYzOGE1MzkyOnA6VDpG
>> .
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"Morphmet" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion visit 
https://groups.google.com/d/msgid/morphmet2/CAAdPgfOw_g6Uw050%2BG44LbsOihdLXb4D5g8BSKbQU8P7%3DyG2kg%40mail.gmail.com.
myorfit2<-function(x, y, return_params = FALSE, tol = 1e-10) {
    
    # ----------------------------------------------------------
    # Controlli iniziali
    # ----------------------------------------------------------
    X <- as.matrix(x)
    Y <- as.matrix(y)
    
    storage.mode(X) <- "double"
    storage.mode(Y) <- "double"
    
    if (!identical(dim(X), dim(Y)))
        stop("x e y devono avere le stesse dimensioni.")
    
    if (!(ncol(X) %in% c(2L, 3L)))
        stop("Sono supportate configurazioni 2D e 3D.")
    
    if (nrow(X) < 3L)
        stop("Servono almeno tre landmark.")
    
    if (any(!is.finite(X)) || any(!is.finite(Y)))
        stop("Le coordinate devono essere finite.")
    
    # ----------------------------------------------------------
    # Funzioni ausiliarie locali
    # ----------------------------------------------------------
    
    # Prodotto vettoriale 3D
    cross3 <- function(a, b) {
        c(
            a[2] * b[3] - a[3] * b[2],
            a[3] * b[1] - a[1] * b[3],
            a[1] * b[2] - a[2] * b[1]
        )
    }
    
    # Mediana ripetuta
    repeated_median <- function(A) {
        A <- as.matrix(A)
        r <- apply(A, 1L, median, na.rm = TRUE)
        r <- r[is.finite(r)]
        
        if (!length(r))
            stop("Mediana ripetuta non definita.")
        
        median(r)
    }
    
    # Scala resistente: y mobile, x fisso
    robust_scale <- function(y, x) {
        n <- nrow(y)
        Q <- matrix(NA_real_, n, n)
        
        for (i in seq_len(n - 1L)) {
            for (j in (i + 1L):n) {
                dy <- sqrt(sum((y[j, ] - y[i, ])^2))
                dx <- sqrt(sum((x[j, ] - x[i, ])^2))
                
                if (is.finite(dx) && is.finite(dy) && dy > tol) {
                    Q[i, j] <- dx / dy
                    Q[j, i] <- dx / dy
                }
            }
        }
        
        q <- repeated_median(Q)
        
        if (!is.finite(q) || q <= 0)
            stop("Scala resistente non valida.")
        
        q
    }
    
    # Mediana circolare
    circular_median <- function(a) {
        a <- a[is.finite(a)]
        
        if (!length(a))
            return(NA_real_)
        
        center <- atan2(median(sin(a)), median(cos(a)))
        delta <- atan2(sin(a - center), cos(a - center))
        
        center + median(delta)
    }
    
    # Rotazione resistente 2D
    rotation_2d <- function(y, x) {
        n <- nrow(y)
        H <- matrix(NA_real_, n, n)
        
        for (i in seq_len(n - 1L)) {
            for (j in (i + 1L):n) {
                a <- y[j, ] - y[i, ]
                b <- x[j, ] - x[i, ]
                
                if (sqrt(sum(a^2)) <= tol ||
                    sqrt(sum(b^2)) <= tol)
                    next
                
                theta <- atan2(
                    a[1] * b[2] - a[2] * b[1],
                    sum(a * b)
                )
                
                H[i, j] <- theta
                H[j, i] <- theta
            }
        }
        
        h <- vapply(seq_len(n), function(i) {
            circular_median(H[i, ])
        }, numeric(1))
        
        theta <- circular_median(h)
        
        if (!is.finite(theta))
            stop("Rotazione 2D non stimabile.")
        
        matrix(c(
            cos(theta), sin(theta),
            -sin(theta), cos(theta)
        ), nrow = 2L)
    }
    
    # Conversione matrice 3D -> asse e angolo
    rotation_to_axis_angle <- function(R) {
        cs <- (sum(diag(R)) - 1) / 2
        theta <- acos(max(-1, min(1, cs)))
        
        if (theta < tol)
            return(list(axis = c(1, 0, 0), angle = 0))
        
        if (abs(pi - theta) < 1e-6) {
            ee <- eigen(R)
            k <- which.min(Mod(ee$values - 1))
            axis <- Re(ee$vectors[, k])
            axis <- axis / sqrt(sum(axis^2))
            
            return(list(axis = axis, angle = theta))
        }
        
        axis <- c(
            R[3, 2] - R[2, 3],
            R[1, 3] - R[3, 1],
            R[2, 1] - R[1, 2]
        ) / (2 * sin(theta))
        
        axis <- axis / sqrt(sum(axis^2))
        
        list(axis = axis, angle = theta)
    }
    
    # Conversione asse-angolo -> matrice di rotazione 3D
    axis_angle_to_rotation <- function(axis, angle) {
        axis <- axis / sqrt(sum(axis^2))
        
        a <- axis[1]
        b <- axis[2]
        c <- axis[3]
        
        K <- matrix(c(
            0, -c,  b,
            c,  0, -a,
            -b,  a,  0
        ), nrow = 3L, byrow = TRUE)
        
        cos(angle) * diag(3) +
            (1 - cos(angle)) * tcrossprod(axis) +
            sin(angle) * K
    }
    
    # Base ortonormale 3D
    basis3 <- function(a, b) {
        unit <- function(v) {
            nv <- sqrt(sum(v^2))
            
            if (!is.finite(nv) || nv <= tol)
                return(NULL)
            
            v / nv
        }
        
        u <- unit(b - a)
        v <- unit(b)
        
        if (is.null(u) || is.null(v))
            return(NULL)
        
        w <- unit(cross3(u, v))
        
        if (is.null(w))
            return(NULL)
        
        z <- unit(cross3(w, u))
        
        if (is.null(z))
            return(NULL)
        
        rbind(u, z, w)
    }
    
    # Rotazione resistente 3D
    rotation_3d <- function(y, x) {
        n <- nrow(y)
        
        axes <- array(NA_real_, c(n, n, 3L))
        angles <- matrix(NA_real_, n, n)
        
        for (i in seq_len(n - 1L)) {
            for (j in (i + 1L):n) {
                A <- basis3(y[i, ], y[j, ])
                B <- basis3(x[i, ], x[j, ])
                
                if (is.null(A) || is.null(B))
                    next
                
                Rij <- t(A) %*% B
                aa <- rotation_to_axis_angle(t(Rij))
                
                if (!all(is.finite(aa$axis)) ||
                    !is.finite(aa$angle))
                    next
                
                axes[i, j, ] <- aa$axis
                axes[j, i, ] <- aa$axis
                angles[i, j] <- aa$angle
                angles[j, i] <- aa$angle
            }
        }
        
        axis_rows <- matrix(NA_real_, n, 3L)
        angle_rows <- rep(NA_real_, n)
        
        for (i in seq_len(n)) {
            valid <- which(is.finite(angles[i, ]))
            
            if (!length(valid))
                next
            
            A <- matrix(
                axes[i, valid, , drop = FALSE],
                ncol = 3L
            )
            
            av <- vapply(seq_len(3L), function(k) {
                median(A[, k], na.rm = TRUE)
            }, numeric(1))
            
            nv <- sqrt(sum(av^2))
            
            if (is.finite(nv) && nv > tol) {
                axis_rows[i, ] <- av / nv
                angle_rows[i] <- median(angles[i, valid], na.rm = TRUE)
            }
        }
        
        valid <- which(
            is.finite(angle_rows) &
                apply(axis_rows, 1L, function(a) all(is.finite(a)))
        )
        
        if (!length(valid))
            stop("Rotazione 3D non stimabile.")
        
        axis <- vapply(seq_len(3L), function(k) {
            median(axis_rows[valid, k], na.rm = TRUE)
        }, numeric(1))
        
        nv <- sqrt(sum(axis^2))
        
        if (!is.finite(nv) || nv <= tol)
            stop("Asse di rotazione degenerato.")
        
        axis <- axis / nv
        angle <- median(angle_rows[valid], na.rm = TRUE)
        
        t(axis_angle_to_rotation(axis, angle))
    }
    
    # ----------------------------------------------------------
    # ORF: x fisso, y mobile
    # ----------------------------------------------------------
    
    q <- robust_scale(Y, X)
    
    R <- if (ncol(X) == 2L) {
        rotation_2d(Y, X)
    } else {
        rotation_3d(Y, X)
    }
    
    YR <- q * (Y %*% R)
    
    tr <- apply(X - YR, 2L, median)
    
    fitted <- sweep(YR, 2L, tr, "+")
    
    if (return_params) {
        return(list(
            yrot = fitted,
            scale = q,
            rotation = R,
            translation = tr
        ))
    }
    
    fitted
}

Reply via email to