From cef5510afc70c79b88825877178465e162ad6762 Mon Sep 17 00:00:00 2001
From: Carl Philipp Klemm <philipp@uvos.xyz>
Date: Fri, 3 May 2024 15:11:46 +0200
Subject: [PATCH] kiss_median: fix issue where the median was incorrect when
 the input data is not sorted or if it has length 1

---
 kissinference.c |  9 ++++++---
 test.cpp        | 24 ++++++++++++++++++++++++
 2 files changed, 30 insertions(+), 3 deletions(-)

diff --git a/kissinference.c b/kissinference.c
index 86317c7..a3efda6 100644
--- a/kissinference.c
+++ b/kissinference.c
@@ -508,15 +508,18 @@ static int kiss_cmp_float(const void *x, const void *y)
 	float *a = (float*)x;
 	float *b = (float*)y;
 
-	if(a < b)
-		return -1;
-	if(b < a)
+	if(*a < *b)
 		return 1;
+	if(*b < *a)
+		return -1;
 	return 0;
 }
 
 float kiss_median(float *data, size_t input_length)
 {
+	if(input_length == 1)
+		return data[0];
+
 	float *data_cpy = malloc(input_length*sizeof(*data));
 	memcpy(data_cpy, data, input_length*sizeof(*data));
 	qsort(data_cpy, input_length, sizeof(*data_cpy), kiss_cmp_float);
diff --git a/test.cpp b/test.cpp
index e48f9f2..6dc9f22 100644
--- a/test.cpp
+++ b/test.cpp
@@ -281,12 +281,30 @@ static bool testMedian()
 	if(!eis::fvalueEq(median, medianRef))
 	{
 		ret = false;
+		std::cout<<"Grads\n";
+		for(float val : grads)
+			std::cout<<val<<'\n';
 		std::cout<<median<<" is not "<<medianRef<<'\n';
 	}
 
 	return ret;
 }
 
+bool testTranslate()
+{
+	const char *model = "r-rc(r-w)";
+	char *cdc = kiss_eis_to_cdc(model);
+	char *relaxis = kiss_eis_to_relaxis(model);
+	std::cout<<"Eis: "<<model<<'\n';
+	std::cout<<"CDC: "<<cdc<<'\n';
+	std::cout<<"RelaxIS: "<<relaxis<<'\n';
+
+	free(cdc);
+	free(relaxis);
+
+	return true;
+}
+
 int main(int argc, char** argv)
 {
 	if(argc < 2)
@@ -339,4 +357,10 @@ int main(int argc, char** argv)
 		std::cerr<<"kiss_filter_spectra not working\n";
 		return 7;
 	}
+
+	if(!testTranslate())
+	{
+		std::cerr<<"kiss_eis_to_cdc or kiss_eis_to_relaxis not working\n";
+		return 8;
+	}
 }
-- 
GitLab