task: variable length stream read, measurement value parse
authorametama <ametama@wafflesoft.org>
Sun, 1 Feb 2026 01:51:04 +0000 (02:51 +0100)
committerametama <ametama@wafflesoft.org>
Sun, 1 Feb 2026 01:51:04 +0000 (02:51 +0100)
src/main.c

index ecc6bb273958b31b519e53b55575d6064f2fe068..88066d0cd4e011b3b22107195cd5ea70fa9228fb 100644 (file)
@@ -28,6 +28,18 @@ char *readfile(FILE *f) {
     return str;
 }
 
+char *readstream(int fd) {
+    int s = 128;
+    char *buf = malloc(s * 2);
+    if (read(fd, buf, s) != s) return buf;
+    char *pos = buf + s;
+    while (read(fd, pos, s) == s) {
+        buf = realloc(buf, (s *= 2) * 2);
+        pos = buf + s;
+    }
+    return buf;
+}
+
 void spawn_ngspice(child_process *chp) {
     if (pipe(&chp->input_read) || pipe(&chp->output_read)) {
         printf("ngsolve: FATAL EXCEPTION\n    pipe creation unsuccessful.");
@@ -62,7 +74,18 @@ double fitness(double *x) {
         dprintf(chp.input_write, "$&%s ", task.mvars[d].symbol);
     dprintf(chp.input_write, "\" >&%d\nexec %d>&-\n.ENDC\n.END\n" /* Done writing (writes EOF to parent on chp.output_write). */, chp.output_write, chp.output_write);
     close(chp.input_write);  // Done writing (writes EOF to ngspice on chp.input_write).
-    // TODO: read measurements and build fitness from constraints and objectives.
+    // Measurements are retrieved here to calculate fitness.
+    // Calculating fitness using statements added to the input
+    // to ngspice has been considered but the input language
+    // appears to be too weak or buggy to do this sensibly.
+    double *mvars = malloc(sizeof(double) * task.mvarc);
+    char *mvar_output = readstream(chp.output_read);
+    char *pos = mvar_output;
+    for (int d = 0; d < task.mvarc; d++) mvars[d] = strtod(pos, &pos);
+    free(mvar_output);
+    // TODO: add constraints to task.
+    // TODO: calculate fitness.
+    free(mvars);
 }
 
 void optimize() {