Commit a30ea78e for tesseract

commit a30ea78e9cfc92c1e515339315caf975f2fb8947
Author: Stefan Weil <sw@weilnetz.de>
Date:   Tue Dec 1 17:05:10 2026 +0100

    Read prototypes of the style mixed

    WritePrototype() writes a prototype of the style mixed with the names
    of the distributions of its dimensions, but ReadPrototype() did not
    know that style. It reported an invalid prototype style, read the
    prototype as an elliptical one and took the line with the names for
    the variances.

    Since the bit-field for the style is unsigned, such a prototype is
    written with its name. Read it, too, with the values which
    MakeDimUniform() and MakeDimRandom() set for a dimension which is
    not normal. A prototype which ends before its distributions or its
    variances is rejected.

    The training tools only use elliptical prototypes, so this has no
    effect there.

    Export ReadPrototype() for the new unit tests.

    Assisted-by: Claude Fable 5.2 (Anthropic)
    Signed-off-by: Stefan Weil <sw@weilnetz.de>

diff --git a/src/classify/clusttool.cpp b/src/classify/clusttool.cpp
index 938c904c..2b97ab86 100644
--- a/src/classify/clusttool.cpp
+++ b/src/classify/clusttool.cpp
@@ -24,6 +24,8 @@
 #include <cmath>   // for M_PI, std::isnan
 #include <locale>  // for std::locale::classic
 #include <sstream> // for std::stringstream
+#include <string>  // for std::string
+#include <vector>  // for std::vector

 namespace tesseract {

@@ -67,6 +69,42 @@ static bool ReadNFloats(TFile *fp, uint16_t N, float Buffer[]) {
   return true;
 }

+/**
+ * This routine reads the names of N distributions (normal, uniform,
+ * random) from one line of the specified text file, as WritePrototype
+ * writes them for a prototype of the style mixed.
+ * @param fp open text file to read the names from
+ * @param N number of names to read
+ * @param Distrib vector to place the distributions into
+ * @return true if N valid names were read
+ */
+static bool ReadNDistributions(TFile *fp, uint16_t N, std::vector<DISTRIBUTION> &Distrib) {
+  const int kMaxLineSize = 1024;
+  char line[kMaxLineSize];
+  if (fp->FGets(line, kMaxLineSize) == nullptr) {
+    tprintf("Hit EOF in ReadNDistributions!\n");
+    return false;
+  }
+
+  std::stringstream stream(line);
+  Distrib.clear();
+  for (uint16_t i = 0; i < N; i++) {
+    std::string token;
+    stream >> token;
+    if (token == "normal") {
+      Distrib.push_back(DISTRIBUTION::normal);
+    } else if (token == "uniform") {
+      Distrib.push_back(DISTRIBUTION::uniform);
+    } else if (token == "random") {
+      Distrib.push_back(DISTRIBUTION::D_random);
+    } else {
+      tprintf("Read of %u distributions failed!\n", N);
+      return false;
+    }
+  }
+  return true;
+}
+
 /**
  * This routine writes a text representation of N floats from
  * an array to a file.  All of the floats are placed on one line.
@@ -203,6 +241,9 @@ PROTOTYPE *ReadPrototype(TFile *fp, uint16_t N) {
     case 'a':
       Proto->Style = PROTOSTYLE::automatic;
       break;
+    case 'm':
+      Proto->Style = PROTOSTYLE::mixed;
+      break;
     default:
       tprintf("Invalid prototype style specification:%s\n", shape_token);
       Proto->Style = PROTOSTYLE::elliptical;
@@ -237,6 +278,35 @@ PROTOTYPE *ReadPrototype(TFile *fp, uint16_t N) {
       Proto->LogMagnitude = log(static_cast<double>(Proto->TotalMagnitude));
       Proto->Distrib.clear();
       break;
+    case PROTOSTYLE::mixed:
+      // A mixed prototype is an elliptical one with a distribution for each
+      // dimension. For a dimension which is not normal, the variance is half
+      // of the range (see MakeDimUniform and MakeDimRandom in cluster.cpp).
+      if (!ReadNDistributions(fp, N, Proto->Distrib)) {
+        delete Proto;
+        return nullptr;
+      }
+      Proto->Variance.Elliptical = new float[N];
+      if (!ReadNFloats(fp, N, Proto->Variance.Elliptical)) {
+        delete[] Proto->Variance.Elliptical;
+        delete Proto;
+        return nullptr;
+      }
+      Proto->Magnitude.Elliptical = new float[N];
+      Proto->Weight.Elliptical = new float[N];
+      Proto->TotalMagnitude = 1.0;
+      for (i = 0; i < N; i++) {
+        if (Proto->Distrib[i] == DISTRIBUTION::normal) {
+          Proto->Magnitude.Elliptical[i] =
+              1.0f / sqrt(2.0f * M_PI * Proto->Variance.Elliptical[i]);
+        } else {
+          Proto->Magnitude.Elliptical[i] = 1.0f / (2.0f * Proto->Variance.Elliptical[i]);
+        }
+        Proto->Weight.Elliptical[i] = 1.0f / Proto->Variance.Elliptical[i];
+        Proto->TotalMagnitude *= Proto->Magnitude.Elliptical[i];
+      }
+      Proto->LogMagnitude = log(static_cast<double>(Proto->TotalMagnitude));
+      break;
     default:
       delete Proto;
       tprintf("Invalid prototype style\n");
diff --git a/src/classify/clusttool.h b/src/classify/clusttool.h
index c6b5edcc..1d7b79d6 100644
--- a/src/classify/clusttool.h
+++ b/src/classify/clusttool.h
@@ -31,6 +31,7 @@ uint16_t ReadSampleSize(tesseract::TFile *fp);
 TESS_API
 PARAM_DESC *ReadParamDesc(tesseract::TFile *fp, uint16_t N);

+TESS_API
 PROTOTYPE *ReadPrototype(tesseract::TFile *fp, uint16_t N);

 TESS_API
diff --git a/unittest/normproto_test.cc b/unittest/normproto_test.cc
index be94325f..ffc076bb 100644
--- a/unittest/normproto_test.cc
+++ b/unittest/normproto_test.cc
@@ -123,5 +123,58 @@ TEST(ParamDescTest, ToleratesHugeLimits) {
   }
 }

+// A prototype of the style mixed must be read by ReadPrototype. It used to be
+// read as an elliptical prototype, with the names of the distributions as
+// its variances. The text is what WritePrototype writes for such a prototype.
+TEST(PrototypeTest, ReadsMixedPrototype) {
+  const uint16_t kNumParams = 3;
+  const float kMean[kNumParams] = {0.25f, 0.5f, 0.75f};
+  const float kVariance[kNumParams] = {0.04f, 0.1f, 0.5f};
+  const std::vector<DISTRIBUTION> kDistrib = {DISTRIBUTION::normal, DISTRIBUTION::uniform,
+                                              DISTRIBUTION::D_random};
+  const std::string text =
+      "significant   mixed    12\n"
+      "\t  0.250000  0.500000  0.750000\n"
+      "\t    normal   uniform    random\n"
+      "\t  0.040000  0.100000  0.500000\n";
+
+  TFile fp;
+  ASSERT_TRUE(fp.Open(text.data(), text.size()));
+  PROTOTYPE *result = ReadPrototype(&fp, kNumParams);
+  ASSERT_NE(result, nullptr);
+  EXPECT_TRUE(result->Significant);
+  EXPECT_TRUE(result->Style == PROTOSTYLE::mixed);
+  EXPECT_EQ(result->NumSamples, 12u);
+  EXPECT_EQ(result->Distrib, kDistrib);
+  ASSERT_EQ(result->Mean.size(), kNumParams);
+  for (unsigned i = 0; i < kNumParams; ++i) {
+    EXPECT_FLOAT_EQ(result->Mean[i], kMean[i]);
+    EXPECT_FLOAT_EQ(result->Variance.Elliptical[i], kVariance[i]);
+  }
+  // Normal: 1 / sqrt(2 * pi * variance). Uniform and random: 1 / range.
+  EXPECT_NEAR(result->Magnitude.Elliptical[0], 1.9947114f, 1e-5);
+  EXPECT_FLOAT_EQ(result->Magnitude.Elliptical[1], 5.0f);
+  EXPECT_FLOAT_EQ(result->Magnitude.Elliptical[2], 1.0f);
+  delete[] result->Variance.Elliptical;
+  delete[] result->Magnitude.Elliptical;
+  delete[] result->Weight.Elliptical;
+  delete result;
+}
+
+// A prototype of the style mixed which ends before its distributions or
+// before its variances must be rejected.
+TEST(PrototypeTest, RejectsTruncatedMixedPrototype) {
+  const uint16_t kNumParams = 3;
+  const std::string head =
+      "significant   mixed    12\n"
+      "\t  0.250000  0.500000  0.750000\n";
+  for (const char *tail : {"", "\t    normal   uniform\n", "\t    normal   uniform    random\n"}) {
+    const std::string text = head + tail;
+    TFile fp;
+    ASSERT_TRUE(fp.Open(text.data(), text.size()));
+    EXPECT_EQ(ReadPrototype(&fp, kNumParams), nullptr) << tail;
+  }
+}
+
 } // namespace
 } // namespace tesseract