;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;   Modular Simulator Controller System - Statistics Rules                ;;;
;;;                                                                         ;;;
;;;   Author:     Oliver Juwig (TheBigO)                                    ;;;
;;;   License:    (2026) Creative Commons - BY-NC-SA                        ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;-------------------------------------------------------------------------;;;
;;;                            Public Rules Section                         ;;;
;;;-------------------------------------------------------------------------;;;

dampingFactor(?distance, ?maxDistance, ?damping, ?factor) <= ?distance < ?maxDistance, ?temp = ?distance * ?damping, ?factor = 1 - ?temp, !
dampingFactor(?, ?, ?, 0)

average([], 0) <= !
average(?list, ?average) <= sum(?list, ?sum), length(?list, ?length), ?average = ?sum / ?length

maxDeviation(?list, ?deviation) <= average(?list, ?average), maxDeviation(?list, ?average, ?deviation)

maxDeviation([?x], ?x, 0)
maxDeviation([?h | ?t], ?average, ?deviation) <= maxDeviation(?t, ?average, ?tDeviation), ?d = ?average - ?h, abs(?d, ?absD),
												 ?absD > ?tDeviation, !, ?deviation = ?absD
maxDeviation([?h | ?t], ?average, ?deviation) <= maxDeviation(?t, ?average, ?deviation)

stdDeviation(?list, ?deviation) <= variance(?list, ?variance), sqrt(?variance, ?deviation)

variance([], 0) <= !
variance(?list, ?variance) <= average(?list, ?average), squaredDeviation(?list, ?average, ?squared),
							  length(?list, ?length), ?variance = ?squared / ?length

squaredDeviation([], ?, 0)
squaredDeviation([?h | ?t], ?avg, ?squared) <= ?delta = ?h - ?avg, ?hSquared = ?delta * ?delta,
											   squaredDeviation(?t, ?avg, ?tSquared), ?squared = ?hSquared + ?tSquared

linRegression(?xValues, ?yValues, ?a, ?b) <= average(?xValues, ?xAverage), average(?yValues, ?yAverage),
											 avgDeltaProductSums(?xValues, ?xAverage, ?yValues, ?yAverage, ?dividend, ?divisor),
											 ?b = ?dividend / ?divisor, ?temp = ?b * ?xAverage, ?a = ?yAverage - ?temp
										  
avgDeltaProductSums([], ?, [], ?, 0, 0)
avgDeltaProductSums([?h1 | ?t1], ?avg1, [?h2 | ?t2], ?avg2, ?sum1, ?sum2) <=
		?d1 = ?h1 - ?avg1, ?d2 = ?h2 - ?avg2, ?p1 = ?d1 * ?d2, ?p2 = ?d1 * ?d1,
		avgDeltaProductSums(?t1, ?avg1, ?t2, ?avg2, ?tSum1, ?tSum2), ?sum1 = ?p1 + ?tSum1, ?sum2 = ?p2 + ?tSum2