Class: ForChrisLib::ChiSquaredStdErr

Inherits:
Object
  • Object
show all
Defined in:
lib/chris_lib/for_chris_lib.rb

Overview

Evaluate a chi-squared goodness-of-fit test from summary statistics.

Instance Method Summary collapse

Constructor Details

#initialize(means, std_errs, mus, confidence_level: 0.95) ⇒ ChiSquaredStdErr

Returns a new instance of ChiSquaredStdErr.

Parameters:

  • means (Array<Numeric>)
  • std_errs (Array<Numeric>)

    standard errors of the means

  • mus (Array<Numeric>)

    hypothesised means

  • confidence_level (Float) (defaults to: 0.95)

Raises:



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/chris_lib/for_chris_lib.rb', line 30

def initialize(means, std_errs, mus, confidence_level: 0.95)
  [means, std_errs, mus].each do |collection|
    unless collection.respond_to?(:to_a)
      raise ArgumentError, 'means, std_errs, and mus must be enumerable'
    end
  end
  @means = means
  @std_errs = std_errs
  @mus = mus
  @confidence_level = confidence_level
  check_confidence_level
  raise ForChrisLibError, 'means, std_errs, and mus must be the same length' unless means.size == std_errs.size && means.size == mus.size
  raise ForChrisLibError, 'means cannot be empty' if means.empty?
  if std_errs.any? { |se| !se.is_a?(Numeric) }
    raise ForChrisLibError, 'std_errs must all be numeric'
  end
  if std_errs.any?(&:zero?)
    raise ForChrisLibError, 'std_errs must be non-zero to avoid division by zero'
  end
  @threshold = 1 - confidence_level
end

Instance Method Details

#callOpenStruct

Returns containing :pass?, :p, and :chi2.

Returns:

  • (OpenStruct)

    containing :pass?, :p, and :chi2



53
54
55
56
57
# File 'lib/chris_lib/for_chris_lib.rb', line 53

def call
  chi2 = means.zip(mus, std_errs).map { |m, mu, se| (m.to_f - mu)**2 / se**2 }.sum
  p_value = PChiSquared.new.call(means.size, chi2)
  OpenStruct.new(pass?: p_value > threshold, p: p_value, chi2: chi2)
end