chiark / gitweb /
get rid of debugging for checking OUTER iteration; leave SIGINT handler and fix to...
[moebius2.git] / energy.c
index 78b8f31ff44be4942efb40cb91f61d21718217b2..c0090677b40f43c4cb09da43b36412741a06c63d 100644 (file)
--- a/energy.c
+++ b/energy.c
 #include "common.h"
 #include "minimise.h"
 #include "mgraph.h"
+#include "parallel.h"
 
-#include <gsl/gsl_errno.h>
-#include <gsl/gsl_multimin.h>
+double vertex_areas[N], vertex_mean_edge_lengths[N], edge_lengths[N][V6];
 
-#include <signal.h>
-#include <sys/time.h>
+static double best_energy= DBL_MAX;
 
-static const char *input_file, *output_file;
-static char *output_file_tmp;
+static void addcost(double *energy, double tweight, double tcost, int pr);
 
-static void compute_vertex_areas(const Vertices vertices, double areas[N]);
-static double best_energy= DBL_MAX;
+/*---------- main energy computation, weights, etc. ----------*/
+
+typedef double CostComputation(const Vertices vertices, int section);
+typedef void PreComputation(const Vertices vertices, int section);
+
+typedef struct {
+  double weight;
+  CostComputation *fn;
+} CostContribution;
+
+#define NPRECOMPS ((sizeof(precomps)/sizeof(precomps[0])))
+#define NCOSTS ((sizeof(costs)/sizeof(costs[0])))
+#define COST(weight, compute) { (weight),(compute) },
+
+static PreComputation *const precomps[]= {
+  compute_edge_lengths,
+  compute_vertex_areas
+};
+
+static const CostContribution costs[]= {
+
+#if XBITS==3
+#define STOP_EPSILON 1e-6
+    COST(  3e3,   line_bending_cost)
+    COST(  3e3,   edge_length_variation_cost)
+    COST( 0.4e3,  rim_proximity_cost)
+    COST(  1e6,   edge_angle_cost)
+                  #define EDGE_ANGLE_COST_CIRCCIRCRAT (0.5/1.7)
+//    COST(  1e1,   small_triangles_cost)
+    COST(  1e12,   noncircular_rim_cost)
+#endif
+
+#if XBITS==4
+#define STOP_EPSILON 1e-6
+    COST(  3e5,   line_bending_cost)
+    COST( 10e2,   edge_length_variation_cost)
+    COST( 9.0e1,  rim_proximity_cost) // 5e1 is too much
+                                     // 2.5e1 is too little
+    // 0.2e1 grows compared to previous ?
+    // 0.6e0 shrinks compared to previous ?
+
+    COST(  1e12,   edge_angle_cost)
+                  #define EDGE_ANGLE_COST_CIRCCIRCRAT (0.5/1.3)
+    COST(  1e18,   noncircular_rim_cost)
+#endif
+
+#if XBITS==5
+#define STOP_EPSILON 1e-6
+    COST(  3e5,   line_bending_cost)
+    COST( 10e2,   edge_length_variation_cost)
+    COST( 9.0e1,  rim_proximity_cost) // 5e1 is too much
+                                     // 2.5e1 is too little
+    // 0.2e1 grows compared to previous ?
+    // 0.6e0 shrinks compared to previous ?
+
+    COST(  1e12,   edge_angle_cost)
+                  #define EDGE_ANGLE_COST_CIRCCIRCRAT (0.5/1.3)
+    COST(  1e18,   noncircular_rim_cost)
+#endif
+
+};
+
+const double edge_angle_cost_circcircrat= EDGE_ANGLE_COST_CIRCCIRCRAT;
+
+void energy_init(void) {
+  stop_epsilon= STOP_EPSILON;
+}
 
-enum printing_instance { pr_cost, pr_size, pr__max };
+/*---------- energy computation machinery ----------*/
 
-static void addcost(double *energy, double tweight, double tcost, int pr);
-#define COST(weight, compute) addcost(&energy, (weight), (compute), printing)
-static int printing_check(enum printing_instance);
-static void printing_init(void);
+void compute_energy_separately(const struct Vertices *vs,
+                        int section, void *energies_v, void *totals_v) {
+  double *energies= energies_v;
+  int ci;
+  
+  for (ci=0; ci<NPRECOMPS; ci++) {
+    costs[ci].fn(vs->a, section);
+    inparallel_barrier();
+  }
+  for (ci=0; ci<NCOSTS; ci++)
+    energies[ci]= costs[ci].fn(vs->a, section);
+}
 
-/*---------- main energy computation and subroutines ----------*/
+void compute_energy_combine(const struct Vertices *vertices,
+                        int section, void *energies_v, void *totals_v) {
+  int ci;
+  double *energies= energies_v;
+  double *totals= totals_v;
 
-static double compute_energy(const Vertices vertices) {
-  double vertex_areas[N], energy;
-  int printing;
+  for (ci=0; ci<NCOSTS; ci++)
+    totals[ci] += energies[ci];
+}
 
-  compute_vertex_areas(vertices,vertex_areas);
-  energy= 0;
+double compute_energy(const struct Vertices *vs) {
+  static int bests_unprinted;
+
+  double totals[NCOSTS], energy;
+  int ci, printing;
+
+  printing= printing_check(pr_cost,0);
 
-  printing= printing_check(pr_cost);
+  if (printing) printf("%15lld c>e |", evaluations);
 
-  if (printing) printf("cost > energy |");
+  for (ci=0; ci<NCOSTS; ci++)
+    totals[ci]= 0;
 
-  COST(1e2, edgewise_vertex_displacement_cost(vertices));
-  COST(1e2, graph_layout_cost(vertices,vertex_areas));
-//  COST(1e4, noncircular_rim_cost(vertices));
+  inparallel(vs,
+            compute_energy_separately,
+            compute_energy_combine,
+            sizeof(totals) /* really, size of energies */,
+            totals);
+
+  energy= 0;
+  for (ci=0; ci<NCOSTS; ci++)
+    addcost(&energy, costs[ci].weight, totals[ci], printing);
 
   if (printing) printf("| total %# e |", energy);
 
@@ -48,12 +135,18 @@ static double compute_energy(const Vertices vertices) {
     FILE *best_f;
     int r;
 
-    if (printing) printf(" BEST");
+    if (printing) {
+      printf(" BEST");
+      if (bests_unprinted) printf(" [%4d]",bests_unprinted);
+      bests_unprinted= 0;
+    } else {
+      bests_unprinted++;
+    }
 
-    best_f= fopen(output_file_tmp,"wb");  if (!best_f) diee("fopen new out");
-    r= fwrite(vertices,sizeof(Vertices),1,best_f); if (r!=1) diee("fwrite");
+    best_f= fopen(best_file_tmp,"wb");  if (!best_f) diee("fopen new out");
+    r= fwrite(vs->a,sizeof(vs->a),1,best_f); if (r!=1) diee("fwrite");
     if (fclose(best_f)) diee("fclose new best");
-    if (rename(output_file_tmp,output_file)) diee("rename install new best");
+    if (rename(best_file_tmp,best_file)) diee("rename install new best");
 
     best_energy= energy;
   }
@@ -62,20 +155,31 @@ static double compute_energy(const Vertices vertices) {
     flushoutput();
   }
 
+  evaluations++;
   return energy;
 }
 
 static void addcost(double *energy, double tweight, double tcost, int pr) {
   double tenergy= tweight * tcost;
-  if (pr) printf(" %# e > %# e |", tcost, tenergy);
+  if (pr) printf(" %# e x %g > %# e* |", tcost, tweight, tenergy);
   *energy += tenergy;
 }
 
-static void compute_vertex_areas(const Vertices vertices, double areas[N]) {
-  int v0,v1,v2, e1,e2, k;
+/*---------- Precomputations ----------*/
 
-  FOR_VERTEX(v0) {
-    double total= 0.0;
+void compute_edge_lengths(const Vertices vertices, int section) {
+  int v1,e,v2;
+
+  FOR_EDGE(v1,e,v2, OUTER)
+    edge_lengths[v1][e]= hypotD(vertices[v1],vertices[v2]);
+}
+
+void compute_vertex_areas(const Vertices vertices, int section) {
+  int v0,v1,v2, e1,e2;
+//  int k;
+
+  FOR_VERTEX(v0, OUTER) {
+    double total= 0.0, edges_total=0;
     int count= 0;
 
     FOR_VEDGE(v0,e1,v1) {
@@ -83,259 +187,277 @@ static void compute_vertex_areas(const Vertices vertices, double areas[N]) {
       v2= EDGE_END2(v0,e2);
       if (v2<0) continue;
 
-      double e1v[D3], e2v[D3], av[D3];
-      K {
-       e1v[k]= vertices[v1][k] - vertices[v0][k];
-       e2v[k]= vertices[v2][k] - vertices[v0][k];
-      }
-      xprod(av, e1v, e2v);
-      total += magnD(av);
+      edges_total += edge_lengths[v0][e1];
+
+//      double e1v[D3], e2v[D3], av[D3];
+//      K {
+//     e1v[k]= vertices[v1][k] - vertices[v0][k];
+//     e2v[k]= vertices[v2][k] - vertices[v0][k];
+//      }
+//      xprod(av, e1v, e2v);
+//      total += magnD(av);
+
       count++;
     }
-    areas[v0]= total / count;
+    vertex_areas[v0]= total / count;
+    vertex_mean_edge_lengths[v0]= edges_total / count;
   }
 }
 
-/*---------- use of GSL ----------*/
+/*---------- Edgewise vertex displacement ----------*/
 
-  /* We want to do multidimensional minimisation.
+  /*
+   * Definition:
    *
-   * We don't think there are any local minima.  Or at least, if there
-   * are, the local minimum which will be found from the starting
-   * state is the one we want.
+   *    At each vertex Q, in each direction e:
    *
-   * We don't want to try to provide a derivative of the cost
-   * function.  That's too tedious (and anyway the polynomial
-   * approximation to our our cost function sometimes has high degree
-   * in the inputs which means the quadratic model implied by most of
-   * the gradient descent minimisers is not ideal).
+   *                                         e
+   *                           Q ----->----- R
+   *                     _,-'\__/
+   *                         _,-'       delta
+   *              P '
    *
-   * This eliminates most of the algorithms.  Nelder and Mead's
-   * simplex algorithm is still available and we will try that.
+   *                      r
+   *       cost    = delta          (we use r=3)
+   *           Q,e
    *
-   * In our application we are searching for the optimal locations of
-   * N actualvertices in D3 (3) dimensions - ie, we are searching for
-   * the optimal metapoint in an N*D3-dimensional space.
    *
-   * So eg with X=Y=100, the simplex will contain 300 metavertices
-   * each of which is an array of 300 doubles for the actualvertex
-   * coordinates.  Hopefully this won't be too slow ...
+   * Calculation:
+   *
+   *      Let vector A = PQ
+   *                 B = QR
+   *
+   *                          -1   A . B
+   *      delta =  tan     -------
+   *                     | A x B |
+   *
+   *      which is always in the range 0..pi because the denominator
+   *      is nonnegative.  We add epsilon to |AxB| to avoid division
+   *      by zero.
+   *
+   *                     r
+   *      cost    = delta
+   *          Q,e
    */
 
-static gsl_multimin_fminimizer *minimiser;
+double line_bending_cost(const Vertices vertices, int section) {
+  static const double axb_epsilon= 1e-6;
+  static const double exponent_r= 4;
 
-static const double stop_epsilon= 1e-6;
+  int pi,e,qi,ri, k;
+  double  a[D3], b[D3], axb[D3];
+  double total_cost= 0;
 
-static double minfunc_f(const gsl_vector *x, void *params) {
-  assert(x->size == DIM);
-  assert(x->stride == 1);
-  return compute_energy((const double(*)[D3])x->data);
-}
+  FOR_EDGE(qi,e,ri, OUTER) {
+    pi= EDGE_END2(qi,(e+3)%V6); if (pi<0) continue;
 
-int main(int argc, const char *const *argv) {
-  gsl_multimin_function multimin_function;
-  double size;
-  Vertices initial, step_size;
-  FILE *initial_f;
-  gsl_vector initial_gsl, step_size_gsl;
-  int r, v, k;
+//if (!(qi&XMASK)) fprintf(stderr,"%02x-%02x-%02x (%d)\n",pi,qi,ri,e);
 
-  if (argc!=3 || argv[1][0]=='-' || strncmp(argv[2],"-o",2))
-    { fputs("usage: minimise <input> -o<output\n",stderr); exit(8); }
+    K a[k]= -vertices[pi][k] + vertices[qi][k];
+    K b[k]= -vertices[qi][k] + vertices[ri][k];
 
-  input_file= argv[1];
-  output_file= argv[2]+2;
-  if (asprintf(&output_file_tmp,"%s.new",output_file) <= 0) diee("asprintf");
+    xprod(axb,a,b);
 
-  graph_layout_prepare();
-  printing_init();
-  
-  minimiser= gsl_multimin_fminimizer_alloc
-    (gsl_multimin_fminimizer_nmsimplex, DIM);
-  if (!minimiser) { perror("alloc minimiser"); exit(-1); }
+    double delta= atan2(magnD(axb) + axb_epsilon, dotprod(a,b));
+    double cost= pow(delta,exponent_r);
 
-  multimin_function.f= minfunc_f;
-  multimin_function.n= DIM;
-  multimin_function.params= 0;
+    total_cost += cost;
+  }
+  return total_cost;
+}
 
-  initial_f= fopen(input_file,"rb");  if (!initial_f) diee("fopen initial");
-  errno= 0; r= fread(initial,sizeof(initial),1,initial_f);
-  if (r!=1) diee("fread");
-  fclose(initial_f);
+/*---------- edge length variation ----------*/
 
-  initial_gsl.size= DIM;
-  initial_gsl.stride= 1;
-  initial_gsl.block= 0;
-  initial_gsl.owner= 0;
-  step_size_gsl= initial_gsl;
+  /*
+   * Definition:
+   *
+   *    See the diagram above.
+   *                                r
+   *       cost    = ( |PQ| - |QR| )
+   *           Q,e
+   */
 
-  initial_gsl.data= &initial[0][0];
-  step_size_gsl.data= &step_size[0][0];
+double edge_length_variation_cost(const Vertices vertices, int section) {
+  double diff, cost= 0, exponent_r= 2;
+  int q, e,r, eback;
 
-  FOR_VERTEX(v)
-    K step_size[v][k]= 0.03;
-//int vx,vy;
-//  FOR_RIM_VERTEX(vx,vy,v)
-//    step_size[v][3] *= 0.1;
+  FOR_EDGE(q,e,r, OUTER) {
+    eback= edge_reverse(q,e);
+    diff= edge_lengths[q][e] - edge_lengths[q][eback];
+    cost += pow(diff,exponent_r);
+  }
+  return cost;
+}
 
-  GA( gsl_multimin_fminimizer_set(minimiser, &multimin_function,
-                                 &initial_gsl, &step_size_gsl) );
+/*---------- rim proximity cost ----------*/
+
+static void find_nearest_oncircle(double oncircle[D3], const double p[D3]) {
+  /* By symmetry, nearest point on circle is the one with
+   * the same angle subtended at the z axis. */
+  oncircle[0]= p[0];
+  oncircle[1]= p[1];
+  oncircle[2]= 0;
+  double mult= 1.0/ magnD(oncircle);
+  oncircle[0] *= mult;
+  oncircle[1] *= mult;
+}
 
-  for (;;) {
-    GA( gsl_multimin_fminimizer_iterate(minimiser) );
+double rim_proximity_cost(const Vertices vertices, int section) {
+  double oncircle[3], cost=0;
+  int v;
 
-    size= gsl_multimin_fminimizer_size(minimiser);
-    r= gsl_multimin_test_size(size, stop_epsilon);
+  FOR_VERTEX(v, OUTER) {
+    int y= v >> YSHIFT;
+    int nominal_edge_distance= y <= Y/2 ? y : Y-1-y;
+    if (nominal_edge_distance==0) continue;
 
-    if (printing_check(pr_size))
-      printf("%*s size %# e, r=%d\n", 135,"", size, r);
-    flushoutput();
+    find_nearest_oncircle(oncircle, vertices[v]);
 
-    if (r==GSL_SUCCESS) break;
-    assert(r==GSL_CONTINUE);
+    cost +=
+      vertex_mean_edge_lengths[v] *
+      (nominal_edge_distance*nominal_edge_distance) /
+      (hypotD2(vertices[v], oncircle) + 1e-6);
   }
-  return 0;
+  return cost;
 }
 
-/*---------- Edgewise vertex displacement ----------*/
+/*---------- noncircular rim cost ----------*/
+
+double noncircular_rim_cost(const Vertices vertices, int section) {
+  int vy,vx,v;
+  double cost= 0.0;
+  double oncircle[3];
+
+  FOR_RIM_VERTEX(vy,vx,v, OUTER) {
+    find_nearest_oncircle(oncircle, vertices[v]);
+
+    double d2= hypotD2(vertices[v], oncircle);
+    cost += d2*d2;
+  }
+  return cost;
+}
+
+/*---------- overly sharp edge cost ----------*/
 
   /*
-   *
-   *
    *
    *                       Q `-_
-   *              / |    `-_
-   *             /  |       `-.
-   *            /   M - - - - - S
-   *           /  ' |      _,-'
-   *          /  '  |  _,-'
-   *         / '  , P '
-   *        / ',-'
-   *       /,-'
+   *              / |    `-_                          P'Q' ------ S'
+   *             /  |       `-.                             _,' `.       .
+   *            /   |           S                _,'     :      .
+   *           /    |      _,-'                _,'        :r    .r
+   *          /     |  _,-'               R' '           `.   .
+   *         /    , P '                               ` .   r     :  .
+   *        /  ,-'                                 `  .   : 
+   *       /,-'                                                 ` C'
    *      /'
    *            R
    *
-   *  Let delta =  180deg - angle RMS
    *
-   *  Let  l = |PQ|
-   *       d = |RS|
    *
-   *  Giving energy contribution:
-   *
-   *                                   3
-   *                            l delta
-   *    E             =  F   .  --------
-   *     vd, edge PQ      vd       d
-   *
-   *
-   *  (The dimensions of this are those of F_vd.)
+   *  Let delta =  angle between two triangles' normals
    *
-   *  We calculate delta as  atan2(|AxB|, A.B)
-   *  where A = PQ, B = QR
+   *  Giving energy contribution:
    *
-   *  In practice to avoid division by zero we'll add epsilon to d and
-   *  |AxB| and the huge energy ought then to be sufficient for the
-   *  model to avoid being close to R=S.
+   *                                   2
+   *    E             =  F   .  delta
+   *     vd, edge PQ      vd
    */
 
-double edgewise_vertex_displacement_cost(const Vertices vertices) {
-  static const double axb_epsilon= 1e-6;
+double edge_angle_cost(const Vertices vertices, int section) {
+  double pq1[D3], rp[D3], ps[D3], rp_2d[D3], ps_2d[D3], rs_2d[D3];
+  double a,b,c,s,r;
+  const double minradius_base= 0.2;
 
-  int pi,e,qi,ri, k; //,si
-  double  a[D3], b[D3], axb[D3]; //m[D3],
+  int pi,e,qi,ri,si, k;
+//  double our_epsilon=1e-6;
   double total_cost= 0;
 
-  FOR_EDGE(qi,e,ri) {
-    pi= EDGE_END2(qi,(e+3)%V6); if (pi<0) continue;
+  FOR_EDGE(pi,e,qi, OUTER) {
+//    if (!(RIM_VERTEX_P(pi) || RIM_VERTEX_P(qi))) continue;
 
-//    K m[k]= (vertices[pi][k] + vertices[qi][k]) * 0.5;
-    K a[k]= -vertices[pi][k] + vertices[qi][k];
-    K b[k]= -vertices[qi][k] + vertices[ri][k];
+    si= EDGE_END2(pi,(e+V6-1)%V6);  if (si<0) continue;
+    ri= EDGE_END2(pi,(e   +1)%V6);  if (ri<0) continue;
 
-    xprod(axb,a,b);
-    
-    double delta= atan2(magnD(axb) + axb_epsilon, dotprod(a,b));
-    double cost= pow(delta,3);
+    K {
+      pq1[k]= -vertices[pi][k] + vertices[qi][k];
+      rp[k]=  -vertices[ri][k] + vertices[pi][k];
+      ps[k]=  -vertices[pi][k] + vertices[si][k];
+    }
 
-    if (!e && !(qi & YMASK))
-      cost *= 10;
+    normalise(pq1,1,1e-6);
+    xprod(rp_2d, rp,pq1); /* projects RP into plane normal to PQ */
+    xprod(ps_2d, ps,pq1); /* likewise PS */
+    K rs_2d[k]= rp_2d[k] + ps_2d[k];
+    /* radius of circumcircle of R'P'S' from Wikipedia
+     * `Circumscribed circle' */
+    a= magnD(rp_2d);
+    b= magnD(ps_2d);
+    c= magnD(rs_2d);
+    s= 0.5*(a+b+c);
+    r= a*b*c / sqrt((a+b+c)*(a-b+c)*(b-c+a)*(c-a+b) + 1e-6);
+
+    double minradius= minradius_base + edge_angle_cost_circcircrat*(a+b);
+    double deficit= minradius - r;
+    if (deficit < 0) continue;
+    double cost= deficit*deficit;
 
     total_cost += cost;
   }
-  return total_cost;
-}
 
-/*---------- noncircular rim cost ----------*/
-
-double noncircular_rim_cost(const Vertices vertices) {
-  int vy,vx,v;
-  double cost= 0.0;
-
-  FOR_RIM_VERTEX(vy,vx,v) {
-    double oncircle[3];
-    /* By symmetry, nearest point on circle is the one with
-     * the same angle subtended at the z axis. */
-    oncircle[0]= vertices[v][0];
-    oncircle[1]= vertices[v][1];
-    oncircle[2]= 0;
-    double mult= 1.0/ magnD(oncircle);
-    oncircle[0] *= mult;
-    oncircle[1] *= mult;
-    double d2= hypotD2(vertices[v], oncircle);
-    cost += d2*d2;
-  }
-  return cost;
+  return total_cost;
 }
 
-/*---------- printing rate limit ----------*/
-
-static volatile unsigned print_todo;
-static sigset_t print_alarmset;
-
-static int printing_check(enum printing_instance which) {
-  static int skipped[pr__max];
-  
-  unsigned bits= 1u << which;
-  int sk;
-
-  if (!(print_todo & bits)) {
-    skipped[which]++;
-    return 0;;
-  }
-
-  sigprocmask(SIG_BLOCK,&print_alarmset,0);
-  print_todo &= ~bits;
-  sigprocmask(SIG_UNBLOCK,&print_alarmset,0);
+/*---------- small triangles cost ----------*/
 
-  sk= skipped[which];
-  if (sk) printf("[%4d] ",sk);
-  else printf("       ");
-  skipped[which]= 0;
+  /*
+   *
+   *                       Q `-_
+   *              / |    `-_
+   *             /  |       `-.
+   *            /   |           S
+   *           /    |      _,-'
+   *          /     |  _,-'
+   *         /    , P '
+   *        /  ,-'
+   *       /,-'
+   *      /'
+   *            R
+   *
+   *  Let delta =  angle between two triangles' normals
+   *
+   *  Giving energy contribution:
+   *
+   *                                   2
+   *    E             =  F   .  delta
+   *     vd, edge PQ      vd
+   */
 
-  return 1;
-}
+double small_triangles_cost(const Vertices vertices, int section) {
+  double pq[D3], ps[D3];
+  double x[D3];
+  int pi,e,qi,si, k;
+//  double our_epsilon=1e-6;
+  double total_cost= 0;
 
-static void alarmhandler(int ignored) {
-  print_todo= ~0u;
-}
+  FOR_EDGE(pi,e,qi, OUTER) {
+//    if (!(RIM_VERTEX_P(pi) || RIM_VERTEX_P(qi))) continue;
 
-static void printing_init(void) {
-  struct sigaction sa;
-  struct itimerval itv;
+    si= EDGE_END2(pi,(e+V6-1)%V6);  if (si<0) continue;
 
-  sigemptyset(&print_alarmset);
-  sigaddset(&print_alarmset,SIGALRM);
+    K {
+      pq[k]= vertices[qi][k] - vertices[pi][k];
+      ps[k]= vertices[si][k] - vertices[pi][k];
+    }
+    xprod(x, pq,ps);
 
-  sa.sa_handler= alarmhandler;
-  sa.sa_mask= print_alarmset;
-  sa.sa_flags= SA_RESTART;
-  if (sigaction(SIGALRM,&sa,0)) diee("sigaction ALRM");
-  
-  itv.it_interval.tv_sec= 0;
-  itv.it_interval.tv_usec= 200000;
-  itv.it_value= itv.it_interval;
+    double cost= 1/(magnD2(x) + 0.01);
 
-  if (setitimer(ITIMER_REAL,&itv,0)) diee("setitimer REAL");
+//double cost= pow(magnD(spqxpqr), 3);
+//assert(dot>=-1 && dot <=1);
+//double cost= 1-dot;
+    total_cost += cost;
+  }
 
-  raise(SIGALRM);
+  return total_cost;
 }