tests/testthat/test-cmtf_fg.R

test_that("cmtf_fg works under normal circumstances", {
  set.seed(123)
  A = array(rnorm(108*2), c(108, 2))
  B = array(rnorm(100*2), c(100, 2))
  C = array(rnorm(10*2), c(10, 2))
  D = array(rnorm(100*2), c(100, 2))
  E = array(rnorm(10*2), c(10, 2))

  df1 = reinflateTensor(A, B, C)
  df2 = reinflateTensor(A, D, E)
  datasets = list(df1, df2)
  modes = list(c(1,2,3), c(1,4,5))
  Z = setupCMTFdata(datasets, modes)

  result = initializeCMTF(Z, 1, initialization="random")
  expect_no_error(cmtf_fg(fac_to_vect(result), Z))
})

test_that("f is the same compared to cmtf_fun", {
  set.seed(123)
  A = array(rnorm(108*2), c(108, 2))
  B = array(rnorm(100*2), c(100, 2))
  C = array(rnorm(10*2), c(10, 2))
  D = array(rnorm(100*2), c(100, 2))
  E = array(rnorm(10*2), c(10, 2))

  df1 = reinflateTensor(A, B, C)
  df2 = reinflateTensor(A, D, E)
  datasets = list(df1, df2)
  modes = list(c(1,2,3), c(1,4,5))
  Z = setupCMTFdata(datasets, modes)

  result = initializeCMTF(Z, 1, initialization="random")
  f = cmtf_fun(fac_to_vect(result), Z)
  fg_output = cmtf_fg(fac_to_vect(result),Z)
  expect_equal(fg_output$fn, f)
})

test_that("g is the same compared to cmtf_gradient", {
  set.seed(123)
  A = array(rnorm(108*2), c(108, 2))
  B = array(rnorm(100*2), c(100, 2))
  C = array(rnorm(10*2), c(10, 2))
  D = array(rnorm(100*2), c(100, 2))
  E = array(rnorm(10*2), c(10, 2))

  df1 = reinflateTensor(A, B, C)
  df2 = reinflateTensor(A, D, E)
  datasets = list(df1, df2)
  modes = list(c(1,2,3), c(1,4,5))
  Z = setupCMTFdata(datasets, modes)

  result = initializeCMTF(Z, 1, initialization="random")
  g = cmtf_gradient(fac_to_vect(result), Z)
  fg_output = cmtf_fg(fac_to_vect(result),Z)
  expect_equal(fg_output$gr, g)
})

Try the CMTFtoolbox package in your browser

Any scripts or data that you put into this service are public.

CMTFtoolbox documentation built on Aug. 23, 2025, 1:11 a.m.