[Swift-commit] r6117 - SwiftApps/SciColSim

wilde at ci.uchicago.edu wilde at ci.uchicago.edu
Tue Jan 1 18:14:04 CST 2013


Author: wilde
Date: 2013-01-01 18:14:03 -0600 (Tue, 01 Jan 2013)
New Revision: 6117

Added:
   SwiftApps/SciColSim/optimizer-dispatch.cpp
Modified:
   SwiftApps/SciColSim/optimizer.cpp
Log:
Remove Grand Central Dispatch code from main optimizer version, and reformat code. Save version with GCD as optimizer-dispatch.cpp.

Added: SwiftApps/SciColSim/optimizer-dispatch.cpp
===================================================================
--- SwiftApps/SciColSim/optimizer-dispatch.cpp	                        (rev 0)
+++ SwiftApps/SciColSim/optimizer-dispatch.cpp	2013-01-02 00:14:03 UTC (rev 6117)
@@ -0,0 +1,1755 @@
+//
+//  main.cpp
+//  optimizer
+//
+//  Created by Andrey Rzhetsky on 4/11/11.
+//  Copyright 2011 University of Chicago. All rights reserved.
+//
+
+// Select OpenMP or Grand Central Dispatch for multithreading:
+
+#define MAXNworkers 24
+int Nworkers=MAXNworkers;
+
+#define NUniverse 24
+
+// Add operation code to enable existing code to be used at lower level from Swift scripts:
+
+char operation = 'n'; // n: normal; m: do one multi_loss (with n_reruns).
+                      // Not used: a: analyze and generate next annealing parameter set. g: tbd
+
+unsigned initSeed = 0;
+
+#include <fstream>
+#include <iostream>
+#include <stdio.h>
+#include <time.h>
+#include <ctime>
+#include <algorithm>
+#include <string>
+
+#include <stdio.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#include <sys/types.h>
+
+#ifdef P_DISPATCH
+#include <dispatch/dispatch.h>
+#endif
+
+#include <fstream>
+
+
+#include <stdlib.h>
+#include <boost/numeric/ublas/io.hpp>
+#include <boost/graph/graph_traits.hpp>
+#include <boost/graph/dijkstra_shortest_paths.hpp>
+#include <boost/graph/loop_erased_random_walk.hpp>
+#include <boost/graph/random.hpp>
+#include <boost/property_map/property_map.hpp>
+#include <boost/graph/graph_concepts.hpp>
+#include <boost/graph/properties.hpp>
+
+#include <boost/graph/graph_traits.hpp>
+#include <boost/graph/adjacency_list.hpp>
+#include <boost/graph/adjacency_matrix.hpp>
+
+#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error
+#define BOOST_MATH_DISCRETE_QUANTILE_POLICY real
+#include <boost/graph/random.hpp>
+#include <boost/random/geometric_distribution.hpp>
+#include <boost/random/uniform_01.hpp>
+#include <boost/random.hpp>
+#include <boost/random/linear_congruential.hpp>
+#include <boost/random/uniform_int.hpp>
+#include <boost/random/uniform_real.hpp>
+#include <boost/random/variate_generator.hpp>
+#include <boost/generator_iterator.hpp>
+#include <boost/lexical_cast.hpp>
+
+#define INT_INFINITY 2147483647
+
+#define FIX_VARIABLES 1
+
+using namespace boost;
+using namespace std;
+using namespace boost::numeric::ublas;
+
+static int max_dist=0;
+
+typedef boost::adjacency_matrix<boost::directedS> Graph;
+typedef std::pair<int,int> Edge;
+typedef boost::graph_traits<Graph> GraphTraits;
+typedef boost::numeric::ublas::triangular_matrix<double, boost::numeric::ublas::strict_upper> prob;
+typedef boost::numeric::ublas::triangular_matrix<double, boost::numeric::ublas::strict_upper> pathlength;
+typedef boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;
+
+namespace std {
+	using ::time;
+}
+
+static int var_fixed[5] = {1, 0, 1, 1, 0};
+
+typedef boost::minstd_rand base_generator_type;
+typedef adjacency_list < listS, vecS, directedS,
+no_property, property < edge_weight_t, int > > graph_t;
+typedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor;
+typedef graph_traits < graph_t >::edge_descriptor edge_descriptor;
+
+double max_loss = -1.0; // intialized to "unset"; set by first Universe constructor to run.
+
+//================================================
+string strDouble(double number)
+{
+    stringstream ss;//create a stringstream
+    ss << number;//add number to the stream
+    return ss.str();//return a string with the contents of the stream
+}
+
+//================================================
+
+double gaussian(double sigma)
+{
+    double GaussNum = 0.0;
+    int NumInSum = 10;
+    for(int i = 0; i < NumInSum; i++)
+    {
+        GaussNum += ((double)rand()/(double)RAND_MAX - 0.5);
+    }
+    GaussNum = GaussNum*sqrt((double)12/(double)NumInSum);
+
+
+    return GaussNum;
+
+}
+
+
+
+//=================================================
+double diffclock(clock_t clock1,clock_t clock2)
+{
+	double diffticks=clock1-clock2;
+	double diffms=(diffticks)/CLOCKS_PER_SEC;
+	return diffms;
+}
+
+//================================================
+//================================================================
+double get_new_x(double x, double dx){
+
+    double new_x;
+    // boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);
+    double r = rand()/(double)(pow(2.,31)-1.);
+
+    if (r > 0.5){
+        new_x = x + rand()*dx/(double)(pow(2.,31)-1.);
+    } else {
+        new_x = x - rand()*dx/(double)(pow(2.,31)-1.);
+    }
+
+    return new_x;
+
+}
+
+
+//===============================================
+string string_wrap(string ins, int mode){
+
+    std::ostringstream s;
+
+    switch(mode){
+        case 0:
+            s << "\033[1;29m" << ins << "\033[0m";
+            break;
+        case 1:
+            s << "\033[1;34m" << ins << "\033[0m";
+            break;
+        case 2:
+            s << "\033[1;44m" << ins << "\033[0m";
+            break;
+        case 3:
+            s << "\033[1;35m" << ins << "\033[0m";
+            break;
+        case 4:
+            s << "\033[1;33;44m" << ins << "\033[0m";
+            break;
+        case 5:
+            s << "\033[1;47;34m" << ins << "\033[0m";
+            break;
+        case 6:
+            s << "\033[1;1;31m" << ins << "\033[0m";
+            break;
+        case 7:
+            s << "\033[1;1;33m" << ins << "\033[0m";
+            break;
+        case 8:
+            s << "\033[1;1;43;34m" << ins << "\033[0m";
+            break;
+        case 9:
+            s << "\033[1;1;37m" << ins << "\033[0m";
+            break;
+        case 10:
+            s << "\033[1;30;47m" << ins << "\033[0m";
+            break;
+        default:
+            s << ins;
+    }
+
+    return s.str();
+}
+
+
+//===============================================
+string wrap_double(double val, int mode){
+
+    std::ostringstream s;
+    s << string_wrap(strDouble(val),mode);
+
+    return s.str();
+}
+
+
+
+//===============================================
+const
+string i2string(int i){
+
+    std::ostringstream s;
+    s << "worker"
+    << lexical_cast<std::string>(i);
+
+    return s.str();
+
+}
+
+//===============================================
+char* i2char(int i){
+
+    std::ostringstream s;
+    s << "worker"
+    << lexical_cast<std::string>(i);
+
+    char* a=new char[s.str().size()+1];
+    memcpy(a,s.str().c_str(), s.str().size());
+
+    return a;
+}
+
+//================================================
+class Universe {
+
+private:
+
+	double alpha_i;
+	double alpha_m;
+	double beta;
+	double gamma;
+	double delta;
+
+    double TargetNovelty;
+    double CumulativeRelativeLoss;
+    double CRLsquare;
+    string id;
+
+
+	int N_nodes;
+	int M_edges;
+
+	int N_epochs;
+	int N_steps;
+	int N_repeats;
+
+	int current_epoch;
+	double current_loss;
+  int current_repeat;
+  double current_novelty;
+
+	int mode_identify_failed;
+    int verbose_level; // 0 is silent, higher is more
+
+	double k_max;
+
+	graph_t Full_g;
+
+	double **Prob;
+	double **Tried;
+	double **Dist;
+	double **Final;
+    double **EdgeIndex;
+	double *Rank;
+
+    base_generator_type generator;
+    boost::uniform_real<> uni_dist;
+    boost::geometric_distribution<double> geo;
+
+public:
+
+
+
+	//======  Constructor ======
+	Universe(const std::string FileToOpen, int Epochs, int Steps, int Repeats, int identify_failed, double target, const std::string idd)
+	{
+		//typedef array_type2::index index2;
+
+
+		std::ifstream inFile;
+        //string line;
+
+        //-------------------------------
+
+        base_generator_type gene(42u);
+        generator = gene;
+//        generator.seed(static_cast<unsigned int>(std::time(0)));
+
+
+    if ( initSeed != 0.0 ) {
+        generator.seed(static_cast<unsigned int>(initSeed));
+      }
+    else {
+        timeval t;
+        gettimeofday(&t, NULL);
+        generator.seed(static_cast<unsigned int>(t.tv_usec));
+      }
+
+
+
+
+
+        boost::uniform_real<> uni_d(0,1);
+        uni_dist = uni_d;
+
+        //--------------------------------
+
+		int i, k;
+        int x, y;
+		Edge* edge_array_mine;
+		int num_arcs_mine, num_nodes_mine;
+		int* weights_mine;
+
+        TargetNovelty = target;
+        CumulativeRelativeLoss = 0.;
+        CRLsquare = 0.;
+
+
+		N_epochs  = Epochs;
+		N_steps   = Steps;
+		N_repeats = Repeats;
+
+		current_epoch = 0;
+		current_loss = 0.;
+		current_repeat = 0;
+
+        id = idd;
+
+        verbose_level = 1;
+
+		mode_identify_failed = identify_failed;
+
+
+		//-------------------------------
+		// The first pass though file with the graph
+		inFile.open(FileToOpen.c_str());
+		if (inFile.fail()) {
+			cout << "Unable to open file";
+			exit(1); // terminate with error
+		}else {
+
+            if (verbose_level > 2){
+                std::cout <<  " Opened <" << FileToOpen << ">"<<std::endl;
+            }
+        }
+
+		i=0;
+        std::string line;
+		//while (! inFile.eof() && ! inFile.fail()) {
+        while (1==1) {
+
+            inFile >> x;
+            inFile >> y;
+
+            if (verbose_level > 2){
+                std::cout << " x: " << x;
+                std::cout << " y: " << y << std::endl;
+            }
+
+			if (i==0){
+				N_nodes=x;
+				M_edges=y;
+                break;
+			}
+			i++;
+
+
+		}
+		inFile.close();
+
+        if (verbose_level == 2){
+            std::cout << N_nodes <<  " nodes, " << M_edges << " edges"<<std::endl;
+        }
+
+		// k_max is the longest distance possible
+
+        //k_max = M_edges;
+		k_max = 70;
+
+		//------------------------------------
+		// Get memory allocated for all class members
+
+		Prob = allocate_2Dmatrix(N_nodes, N_nodes);
+		Tried = allocate_2Dmatrix(N_nodes, N_nodes);
+		Dist = allocate_2Dmatrix(N_nodes, N_nodes);
+		Final = allocate_2Dmatrix(N_nodes, N_nodes);
+        EdgeIndex = allocate_2Dmatrix(N_nodes, N_nodes);
+		Rank = allocate_1Dmatrix(N_nodes);
+
+        //The second pass through file with the graph
+
+		for(int i = 0; i < N_nodes; ++i) {
+			Rank[i]=0.;
+			for(int j = 0; j < N_nodes; ++j) {
+				Final[i][j] = 0.;
+				Prob[i][j]=0.;
+				Dist[i][j]=-1.;
+				Tried[i][j]=0.;
+                EdgeIndex[i][j]=-1;
+			}
+		}
+
+
+		// Fill in the final graph -- and we are ready to go!
+
+	    inFile.open(FileToOpen.c_str());
+		if (!inFile) {
+            std::cout << "Unable to open file";
+			exit(1); // terminate with error
+		}
+		else {
+
+            if (verbose_level > 2){
+                std::cout <<  " Opened <" << FileToOpen << ">"<<std::endl;
+            }
+        }
+
+		i=0;
+		while (inFile >> x && inFile >>y) {
+			if (i > 0) {
+				Final[x][y]=1.;
+				Final[y][x]=1.;
+
+
+                if (verbose_level == 2){
+                    std::cout << ".";
+                }
+			}
+			i++;
+
+		}
+        if (verbose_level == 2){
+            std::cout << std::endl;
+        }
+		inFile.close();
+
+        k=0;
+        for (int i=0; i<N_nodes-1; i++){
+            for (int j=i+1;j<N_nodes; j++){
+                if(Final[i][j] > 0.){
+                    EdgeIndex[i][j]=k;
+                    k++;
+                }
+            }
+        }
+
+
+
+		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+		// create graph -- hopefully, we can keep it, just modifying edge weights
+
+
+		edge_array_mine = new Edge[2*M_edges];
+		num_arcs_mine = 2*M_edges;
+		num_nodes_mine = N_nodes;
+		weights_mine = new int[2*M_edges];
+		for (int i=0; i<2*M_edges; i++){ weights_mine[i]=1;}
+
+		k=0;
+		for(int i=0; i<N_nodes-1; i++){
+			for( int j=i+1; j<N_nodes; j++){
+				if (Final[i][j]>0.){
+					edge_array_mine[2*k]  =Edge(i,j);
+					edge_array_mine[2*k+1]=Edge(j,i);
+					k++;
+				}
+			}
+		}
+		graph_t g(edge_array_mine, edge_array_mine + num_arcs_mine, weights_mine, num_nodes_mine);
+
+		Full_g = g;
+		delete edge_array_mine;
+		delete weights_mine;
+
+		//===========================================================================
+		std::vector<edge_descriptor> p(num_edges(Full_g));
+		std::vector<int> d(num_edges(Full_g));
+		edge_descriptor s;
+		boost::graph_traits<graph_t>::vertex_descriptor u, v;
+
+		for (int i=0; i<N_nodes-1; i++){
+			for (int j=i+1; j<N_nodes; j++){
+				if (Final[i][j] > 0.){
+					u = vertex(i, Full_g);
+					v = vertex(j, Full_g);
+					remove_edge(u,v,Full_g);
+					remove_edge(v,u,Full_g);
+
+				}
+			}
+		}
+		if(max_loss <= 0.0) set_max_loss(N_nodes, M_edges, TargetNovelty);
+    }
+
+
+	//=====================================================================
+	int sample_failed_number(double pfail){
+
+		//boost::geometric_distribution<double> geo(pfail);
+		//boost::variate_generator<base_generator_type&, geometric_distribution<double> > geom(generator, geo);
+
+		double r, u, g;
+
+        r=0.;
+		for(int i=0; i<N_steps; i++){
+
+            u=(double)rand();
+            u = 1.-u /(double)(pow(2.,31)-1.);
+            g=(int)(ceil(log(u) / log(pfail)));
+
+			//r += geom();
+
+            r+=g;
+		}
+
+        if (verbose_level>=3){
+            std::cout << id << " failed " << r << std::endl;
+		}
+	return (int) round(r);  // FIXME: Andrey: please verify that round() is correct.
+
+	}
+
+    //=============================================
+    double get_target(void){
+        return TargetNovelty;
+    }
+
+    //=============================================
+    void set_target(double target){
+        TargetNovelty=target;
+    }
+
+	//=============================================
+	int sample(){
+
+        //boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);
+        // double r = uni(), Summa = 0.;
+
+
+
+        double r = rand(), Summa = 0.;
+        r /= (double)(pow(2.,31)-1.);
+		int result = 0;
+		int finished = 0;
+
+        if (verbose_level==4){
+            std::cout << id << " sampled " << r << std::endl;
+        }
+
+		for(int i=0; i<N_nodes-1 && finished==0; i++){
+			for( int j=i+1; j<N_nodes && finished==0; j++){
+
+				Summa += Prob[i][j];
+
+				if (Summa > r){
+
+					Tried[i][j]+=1.;
+
+					if (Final[i][j] > 0.){
+						result = 1;
+					}
+					finished = 1;
+				}
+			}
+		}
+
+		return result;
+
+	}
+
+	//===============================
+	void update_current_graph(void){
+
+		std::vector<edge_descriptor> p(num_edges(Full_g));
+		std::vector<int> d(num_edges(Full_g));
+		edge_descriptor s;
+		boost::graph_traits<graph_t>::vertex_descriptor u, v;
+
+		//property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, Full_g);
+		for (int i=0; i<N_nodes-1; i++){
+			for (int j=i+1; j<N_nodes; j++){
+				if (Final[i][j] > 0. && Tried[i][j]>0){
+					//s = edge(i, j, Full_g);
+					boost::graph_traits<graph_t>::edge_descriptor e1,e2;
+					bool found1, found2;
+					u = vertex(i, Full_g);
+					v = vertex(j, Full_g);
+					tie(e1, found1) = edge(u, v, Full_g);
+					tie(e2, found2) = edge(v, u, Full_g);
+					if (!found1 && !found2){
+						add_edge(u,v,1,Full_g);
+					    add_edge(v,u,1,Full_g);
+					}
+
+				}
+			}
+
+		}
+	}
+
+	//===============================
+	void update_distances(void){
+		// put shortest paths to the *Dist[][]
+		std::vector<vertex_descriptor> p(num_vertices(Full_g));
+		std::vector<int> d(num_vertices(Full_g));
+		vertex_descriptor s;
+
+
+		// put shortest paths to the *Dist[][]
+		for (int j=0; j<num_vertices(Full_g); j++){
+
+			if(Rank[j] > 0.){
+				s = vertex(j, Full_g);
+				dijkstra_shortest_paths(Full_g, s, predecessor_map(&p[0]).distance_map(&d[0]));
+
+				//std::cout <<" Vertex "<< j << std::endl;
+				graph_traits < graph_t >::vertex_iterator vi, vend;
+
+				for (boost::tie(vi, vend) = vertices(Full_g); vi != vend; ++vi) {
+
+					if (p[*vi]!=*vi){
+						Dist[*vi][j]=d[*vi];
+						Dist[j][*vi]=d[*vi];
+
+						if ( (int)round(Dist[*vi][j]>max_dist)) {
+						  // FIXME: Andrey: please verify that (int) cast is correct. Do we need to round()?
+						  // also, the indent on this iff statement was way off -
+						  // perhaps due to space v. tab?
+						  max_dist=(int)round(Dist[*vi][j]);
+						}
+
+
+					} else {
+						Dist[*vi][j]=-1.;
+						Dist[j][*vi]=-1.;
+					}
+				}
+			}
+
+		}
+
+
+	}
+
+	//======================================================
+	void update_ranks(void){
+
+		for(int i=0; i<N_nodes; i++){
+			Rank[i]=0.;
+		}
+
+		for(int i=0; i<N_nodes-1; i++){
+			for( int j=i+1; j<N_nodes; j++){
+				if (Tried[i][j]>0. && Final[i][j] >0.){
+					Rank[i]++;
+					Rank[j]++;
+				}
+			}
+		}
+
+	}
+
+	//====================================================================
+	void set_world(double a_i, double a_m, double b, double g, double d){
+
+		alpha_i=a_i;
+		alpha_m=a_m;
+		gamma=g;
+		beta=b;
+		delta=d;
+
+	}
+
+	//====================================================================
+	void reset_world(){
+
+        //====================================================
+		std::vector<edge_descriptor> p(num_edges(Full_g));
+		std::vector<int> d(num_edges(Full_g));
+		edge_descriptor s;
+		boost::graph_traits<graph_t>::vertex_descriptor u, v;
+		cout << "reset_world: start id=" << id << endl;
+
+		for (int i=0; i<N_nodes-1; i++){
+			for (int j=i+1; j<N_nodes; j++){
+				if (Final[i][j] > 0. && Tried[i][j] > 0){
+					u = vertex(i, Full_g);
+					v = vertex(j, Full_g);
+					remove_edge(u,v,Full_g);
+					remove_edge(v,u,Full_g);
+
+				}
+			}
+		}
+
+        //==================================================
+
+		current_loss=0;
+		current_epoch=0;
+		current_repeat++;
+        current_novelty=0;
+
+		for(int i = 0; i < N_nodes; ++i) {
+			Rank[i]=0.;
+			for(int j = 0; j < N_nodes; ++j) {
+				Prob[i][j]=0.;
+				Dist[i][j]=-1.;
+				Tried[i][j]=0.;
+			}
+		}
+		cout << "reset_world: end id=" << id << endl;
+	}
+
+
+    //==============================================
+    void show_parameters(void){
+
+        std::cout << "Parameters: "
+        << alpha_i << " "
+        << alpha_m << " | "
+        << beta << " "
+        << gamma << " | "
+        << delta << std::endl;
+
+    }
+
+
+
+    //===============================================
+    string file_name(){
+
+        std::ostringstream s;
+        s << "world_"
+        << lexical_cast<std::string>(alpha_i) << "_"
+        << lexical_cast<std::string>(alpha_m) << "_"
+        << lexical_cast<std::string>(beta) << "_"
+        << lexical_cast<std::string>(gamma) << "_"
+        << lexical_cast<std::string>(delta) << "_"
+        << lexical_cast<std::string>(N_epochs) << "_"
+        << lexical_cast<std::string>(N_steps) << "_"
+        << lexical_cast<std::string>(N_repeats) << ".txt";
+
+        return s.str();
+
+    }
+
+
+
+
+    //=================================================
+    void set_verbose(int verbose){
+
+        verbose_level = verbose;
+    }
+
+
+    //=============================================================
+    void update_probabilities(void){
+
+
+        //=========================
+		// Compute sampling probabilities
+		// first pass: \xi_i,j
+		for(int i=0; i<N_nodes-1; i++){
+			for( int j=i+1; j<N_nodes; j++){
+
+				double bg = 0.;
+
+				Prob[i][j] = alpha_i*log(min(Rank[i]+1.,Rank[j]+1.)) +
+                alpha_m*log(max(Rank[i]+1.,Rank[j]+1.));
+
+                if (Dist[i][j] > 0.){
+
+                    double k = Dist[i][j];
+                    if (k >= k_max){
+                        k = k_max-1;
+                    }
+
+                    bg = beta * log(k/k_max) + gamma * log(1. - k/k_max);
+
+                } else {
+                    bg = delta;
+                }
+
+				Prob[i][j] = exp(Prob[i][j] + bg);
+			}
+		}
+
+
+		// second pass: sum
+		double Summa = 0.;
+
+		for(int i=0; i<N_nodes-1; i++){
+			for( int j=i+1; j<N_nodes; j++){
+				Summa += Prob[i][j];
+			}
+		}
+
+		// third pass: normalize
+		for(int i=0; i<N_nodes-1; i++){
+			for( int j=i+1; j<N_nodes; j++){
+				Prob[i][j] /= Summa;
+			}
+		}
+
+    }
+
+	// Now we are ready for simulations
+	//==============================================
+	void update_world(){
+
+		int failed = 0;
+
+		// Given current universe compute shortest paths
+		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+		update_current_graph();
+		update_ranks();
+		update_distances();
+		update_probabilities();
+
+		//===============================
+		// sampling
+		int result;
+		double cost=0., novel=0.;
+		int publishable = 0;
+
+
+		//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+		if (mode_identify_failed == 1){
+
+			while(publishable < N_steps){
+
+		    	result = sample();
+			    publishable += result;
+			    failed += (1-result);
+
+			}
+
+			for(int i=0; i<N_nodes-1; i++){
+				for( int j=i+1; j<N_nodes; j++){
+
+					cost+=Tried[i][j];
+
+					if (Tried[i][j]>0. && Final[i][j]>0.){
+						novel+=1.;
+					}
+				}
+			}
+
+		}
+		//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+		else {
+
+			double pfail=0.;
+			int n_failed;
+			//, n_check = 0;
+
+			for(int i=0; i<N_nodes-1; i++){
+				for( int j=i+1; j<N_nodes; j++){
+					if (Final[i][j] == 0.){
+						pfail += Prob[i][j];
+						Prob[i][j] = 0.;
+					}
+
+				}
+			}
+
+			for(int i=0; i<N_nodes-1; i++){
+				for( int j=i+1; j<N_nodes; j++){
+					Prob[i][j] /= (1.-pfail);
+				}
+				//std::cout << std::endl;
+			}
+
+			n_failed = sample_failed_number(pfail);
+			while(publishable < N_steps){
+
+		    	result = sample();
+			    publishable += result;
+			}
+
+
+			current_loss += (n_failed + N_steps);
+			cost = current_loss;
+
+			for(int i=0; i<N_nodes-1; i++){
+				for( int j=i+1; j<N_nodes; j++){
+
+					if (Tried[i][j]>0. && Final[i][j]>0.){
+						novel+=1.;
+					}
+				}
+			}
+		}
+
+        current_novelty = novel;
+
+
+		//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+		if (verbose_level == 2){
+            std::cout << (current_repeat+1) << "  epoch=" << (current_epoch+1)
+
+		    << "  cost=" << cost
+		    << " novel=" << novel
+		    << " rel_loss=" << cost/novel
+		    << std::endl;
+        }
+
+		current_epoch++;
+	}
+
+
+	//======  Destructor ======
+	~Universe(){
+
+		delete_2Dmatrix(Final, N_nodes);
+		delete_2Dmatrix(Dist, N_nodes);
+		delete_2Dmatrix(Tried, N_nodes);
+		delete_2Dmatrix(Prob, N_nodes);
+        delete_2Dmatrix(EdgeIndex, N_nodes);
+		delete_1Dmatrix(Rank);
+	}
+
+    //================================================
+    // Allocate memory
+    double** allocate_2Dmatrix(int N, int M)
+    {
+        double **pointer;
+
+        if (verbose_level == 2){
+            std::cout<< "["<<N<<"|"<<M<<"]"<<std::endl;
+        }
+        pointer = new double*[N];
+        for (int i = 0; i < N; ++i)
+            pointer[i] = new double[M];
+
+        return pointer;
+    }
+    //===================
+    double* allocate_1Dmatrix(int N)
+    {
+        double *pointer;
+
+        if(N > 0){
+
+            pointer = new double[N];
+
+        }else {
+
+            pointer = NULL;
+        }
+
+        return pointer;
+
+    }
+
+    //==============================================
+    // De-Allocate memory to prevent memory leak
+    void delete_2Dmatrix(double **pointer, int N){
+
+        if (pointer != NULL){
+
+            for (int i = 0; i < N; ++i){
+                delete [] pointer[i];
+            }
+            delete [] pointer;
+        }
+    }
+    //====================
+    void delete_1Dmatrix(double *pointer){
+
+        delete [] pointer;
+    }
+
+    //===========================================
+    double get_rel_loss(){
+
+        return CumulativeRelativeLoss ;
+    }
+
+    //===========================================
+    double get_rel_loss_err(){
+
+        return CRLsquare ;
+    }
+
+
+
+    //==================================================================================
+    void evolve_to_target_and_save(int istart, int iend, double* storage, int* counters){
+
+      //double ALOT=100000000000.;
+        double ALOT= 3.0 * max_loss; // Per Andrey, 2012.12.29
+
+        double ratio = 0.0;
+        int check = 0;
+
+        reset_world();
+
+        for (int k = istart; k < iend; k++){
+	  cout << "evolve_ttas: k=" << k << endl; 
+
+            for(int i=0; i< N_epochs &&  current_novelty < TargetNovelty; i++){
+
+                if(ratio < max_loss){
+                    update_world();
+                }
+                else{
+		  cout << "k=" << k << " i=" << i << " ratio=" << ratio << " max_loss=" << max_loss << endl;
+                    break;
+                }
+                ratio = current_loss/current_novelty;
+            }
+            if( ratio < max_loss )
+                storage[k]=current_loss/current_novelty;
+            else
+                storage[k]=ALOT;
+            counters[k]=1;
+            reset_world();
+        }
+    }
+
+    //==============================================
+    int get_reruns(void){
+        return N_repeats;
+    }
+
+    //==============================================
+    double get_parameter(int i){
+
+        switch(i){
+            case 0:
+                return alpha_i;
+            case 1:
+                return alpha_m;
+            case 2:
+                return beta;
+            case 3:
+                return gamma;
+            case 4:
+                return delta;
+            default:
+
+                std::cout << "Erroneous parameter id!!!!\n\n\n";
+                return 0.;
+        }
+    }
+
+
+    //==============================================
+    void evolve_to_target(){
+
+        reset_world();
+        if (beta < -1. || gamma < -1.){
+            CumulativeRelativeLoss = 100000000000.;
+            CRLsquare = 0.;
+            return;
+        }
+
+
+        for (int k=0; k< N_repeats; k++){
+
+
+            for(int i=0; i<N_epochs &&  current_novelty < TargetNovelty; i++){
+                update_world();
+            }
+
+            CumulativeRelativeLoss += current_loss/current_novelty;
+            CRLsquare += (current_loss/current_novelty)*(current_loss/current_novelty);
+            if(verbose_level==3){
+                std::cout <<  CumulativeRelativeLoss << " | " << CRLsquare << std::endl;
+            }
+
+            if(verbose_level==1){
+                std::cout <<  "." ;
+
+            }
+            else if(verbose_level==2){
+                std::cout <<  "**" << (k+1) <<  "**  curr loss " << current_loss << "; curr novelty " << current_novelty << std::endl;
+            }
+
+
+            reset_world();
+        }
+
+        CumulativeRelativeLoss /= double(N_repeats);
+        CRLsquare /= double(N_repeats);
+
+        if(verbose_level==1){
+            std::cout << std::endl;
+        }
+
+        if(verbose_level==2){
+            std::cout <<  CumulativeRelativeLoss << " || " << CRLsquare << std::endl;
+        }
+
+        CRLsquare = 2*sqrt((CRLsquare - CumulativeRelativeLoss*CumulativeRelativeLoss)/double(N_repeats));
+
+    }
+
+
+    //================================================================
+    int set_parameter(double value, int position){
+
+        if (position < 0 || position > 4) {return 0;}
+
+        else {
+
+            switch(position){
+                case 0:
+                    alpha_i=value;
+                    return 1;
+                case 1:
+                    alpha_m=value;
+                    return 1;
+                case 2:
+                    beta=value;
+                    return 1;
+                case 3:
+                    gamma=value;
+                    return 1;
+                case 4:
+                    delta=value;
+                    return 1;
+            }
+
+        }
+
+        return 0;
+    }
+
+//--------
+
+void set_max_loss(long long v, long long e, long long t) {
+
+  cout << "set_max_loss v=" << v << " e=" << e << " t=" << t << " max_loss=" << max_loss << endl;
+
+  // Based on formulas from random_analytical.pdf
+
+  double sum, ERLt, VarRLt;
+
+  // (9): E[RLt] = (1/t) * SUM(i=0 to T of: (V*(V-1) / (2 * (E-i))
+
+  sum = 0;
+  for(int i=0;i<t;i++) {
+    sum += ((double)(v*(v-1))) / ((double)(2*(e-i)));
+  }
+  ERLt = (1.0/(double) t) * sum;
+
+  // (12): Var[RLt] = 1 / (T**2) * SUM( i=0 to T of: ((V*(V-1))/2) - E + 1 ) / ((E-i)**2)
+
+  sum = 0;
+  for(int i=0;i<t;i++) {
+    sum +=  
+      ( (((double)(v*(v-1)))/ 2.0) - (double)e + (double)i )
+      /  
+      (double)((e-i)*(e-i))
+      ;
+    if ( (double)((e-i)*(e-i)) == 0.0 ) {
+      printf( "set_max_loss: while doing variance: zero denom: %d %d\n", e, i);
+      exit(1);
+    }
+  }
+  int tmp = t*t;
+  VarRLt = (1.0/(double)((t) * t)) * sum;
+  if (VarRLt < 0.0) {
+    printf( "set_max_loss: while doing variance: VarRLT %d < 0\n", VarRLt);
+    exit(1);
+  }
+
+  // (9) + 3sigma = E[RLt] + 3 * SQRT(Var)
+
+  max_loss = ERLt + (3.0 * sqrt(VarRLt));
+  printf("set_max_loss: %12d %12.3f %12.8e %12.3f\n", t, ERLt, VarRLt, max_loss);
+}
+
+}; // End of class Universe
+
+//============================================================
+
+#ifdef P_DISPATCH
+std::pair<double,double> multi_loss(dispatch_group_t group,
+                                    Universe* un[],
+                                    dispatch_queue_t* CustomQueues,
+                                    double* Results,
+                                    int*    Counters,
+                                    double* params){
+#else
+std::pair<double,double> multi_loss(Universe* un[],
+                                    double* Results,
+                                    int*    Counters,
+                                    double* params){
+
+#endif
+
+    int N = un[0]->get_reruns();
+    int step = (int)floor((double)N/(double)(Nworkers)); // FIXME: Andrey: please check change in cast grouping and use of floor
+    int istart=0;
+    int iend = istart+step;
+
+    double Loss=0., LossSquare=0.;
+
+    timeval startTime, endTime;
+    double elapsedTime;
+    gettimeofday(&startTime, NULL);
+
+    if ( N > NUniverse ) {
+      std::cerr << "Error: Number of reruns=" << N << " is greater than max NUniverse=" << NUniverse << "\n";
+      exit(1);
+    }
+
+    for(int i=0; i<N; i++){
+        for(int j=0; j<5; j++){
+            un[i]->set_parameter(params[j],j);
+        }
+    }
+
+#ifdef P_DISPATCH
+    for(int i=0; i<Nworkers; i++){
+
+        dispatch_group_async(group, CustomQueues[i], ^{
+
+            // un[i]->evolve_to_target_and_save(istart, iend, Results, Counters);
+            un[i]->evolve_to_target_and_save(i*step, min((i+1)*step,N), Results, Counters);
+        });
+
+        std::cout << "queued: i=" << i << " N=" << N << " istart=" << istart << " iend=" << iend << "\n";
+        // istart += step;
+        // iend = min(istart+step,N);
+
+    }
+    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
+    //dispatch_release(group);
+#else
+    int i;
+
+    // Execute rerun loop in parallel
+
+    #pragma omp parallel for private (i)
+    for(i=0; i<N; i++){
+        un[i]->evolve_to_target_and_save(i, i+1, Results, Counters);
+     }
+#endif
+
+/*
+    for (int i=0; i<N; i++){
+        Loss+=Results[i]/(double)N;
+        LossSquare+=Results[i]*Results[i]/(double)N;
+    }
+
+    double two_std = ((LossSquare - Loss*Loss)/(double)N);
+    double two_std_dev = 2.*sqrt(two_std);
+*/
+
+    double sumsqdel;
+    Loss = 0.0, sumsqdel = 0.0;
+    for (int i=0; i<N; i++) {
+      Loss+=Results[i];
+    }
+    Loss /= (double)N;
+    for (int i=0; i<N; i++) {
+      double delta = Results[i] - Loss;
+      sumsqdel += delta*delta;
+    }
+    double variance = sumsqdel / double(N);
+    double two_std = 2.0 * sqrt(variance);
+
+    cout << "multi_loss: Loss=" << Loss << " sumsqdel=" << sumsqdel << " variance=" << variance << " two_std=" << two_std << endl;
+    std::pair<double,double> Res;
+    Res.first=Loss;
+    Res.second=two_std;
+
+    gettimeofday(&endTime, NULL);
+    elapsedTime = (endTime.tv_sec - startTime.tv_sec) * 1000.0;      // sec to ms
+    elapsedTime += (endTime.tv_usec - startTime.tv_usec) / 1000.0;   // us to ms
+    elapsedTime /= 1000.;
+    cout << "multi_loss(N=" << N << ", target=" << un[0]->get_target() << ") elapsed time: " << elapsedTime << " seconds " << elapsedTime/60. << " minutes\n\n";
+
+    return Res;
+}
+//============================================================
+
+
+//============================================================
+#ifdef P_DISPATCH
+void multi_annealing( dispatch_group_t group,
+                     Universe* un[],
+                     dispatch_queue_t* CustomQueues,
+                     double T_start, double T_end,
+                     double Target_rejection,
+                     int Annealing_repeats,
+                     double starting_jump,
+                     double* Results,
+                     int*    Counters,
+                     double* params0,
+                     double annealing_cycles){
+#else
+void multi_annealing(Universe* un[],
+                     double T_start, double T_end,
+                     double Target_rejection,
+                     int Annealing_repeats,
+                     double starting_jump,
+                     double* Results,
+                     int*    Counters,
+                     double* params0,
+                     double annealing_cycles){
+#endif
+    //.................................
+    // re-implement annealing
+
+    double dx[5]={0.,0.,0.,0.,0};
+    double x[5]={0.,0.,0.,0.,0};
+    double rejection[5]={0., 0., 0., 0., 0.};
+    double curr_x, curr_err, x_tmp;
+    double temperature;
+    double ratio, r;
+    int cycle=10;
+    //boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);
+
+    // set up parameter for annealing
+
+    x[0]=params0[0];
+    x[1]=params0[1];
+    x[2]=params0[2];
+    x[3]=params0[3];
+    x[4]=params0[4];
+
+    for(int i=0;i<5;i++){
+        dx[i] = starting_jump;
+    }
+
+    // establish the current value
+    std::pair<double,double>Res;
+
+#ifdef P_DISPATCH
+    Res = multi_loss(group, un, CustomQueues, Results, Counters, x);
+#else
+    Res = multi_loss(       un,               Results, Counters, x);
+#endif
+    std::cout << "Returned from initial multi_loss:" << std::endl;
+    std::cout << Res.first << " +- " << Res.second << std::endl;
+
+    if ( operation == 'm' ) {
+      FILE *f;
+      int N = un[0]->get_reruns();
+
+      f = fopen("multi_loss.data","w");
+      for(int i=0; i<N; i++) {
+        fprintf(f,"%.20e\n",Results[i]);
+      }
+      fclose(f);
+      exit(0);
+    }
+
+    curr_x   = Res.first;
+    curr_err = Res.second;
+
+    // optimization cycle
+
+    for(int i=0; i<annealing_cycles; i++){
+
+        temperature = T_start*exp( i*(log(T_end)-log(T_start))/(double)annealing_cycles);
+        std::cout  << std::endl << "....T = " << wrap_double(temperature,3) << std::endl << std::endl;
+
+        if (i % cycle == 0 && i > 0){
+
+            for (int k=0; k<5; k++){
+                rejection[k]/=(double)cycle;
+
+                if (rejection[k] > 0){
+                    dx[k] = dx[k]/(rejection[k]/Target_rejection);
+                    rejection[k]=0.;
+                }
+                else{
+                    dx[k]*=2.;
+                }
+                std::cout  << dx[k] << " ";
+            }
+            std::cout  << std::endl;
+        }
+
+
+        for (int j=0; j<5; j++){
+
+            ///////////////////////////////
+            if (FIX_VARIABLES==0 || var_fixed[j]==0){
+
+
+
+                // get new value of x[j]
+                double x_hold=x[j];
+                x_tmp = get_new_x(x[j],dx[j]);
+                x[j]=x_tmp;
+
+                std::cout << wrap_double(x_tmp,10) << " " << wrap_double(j,9) << "\n\n";
+                //=======================================
+                //.............................................
+                for(int w=0; w<Nworkers; w++){
+                    un[w]->set_parameter(x_tmp, j);
+                }
+
+#ifdef P_DISPATCH
+                Res = multi_loss(group, un, CustomQueues, Results, Counters, x);
+#else
+                Res = multi_loss(       un,               Results, Counters, x);
+#endif
+                std::cout << Res.first << " +- " << Res.second << std::endl;
+
+                ratio = min(1.,exp(-(Res.first-curr_x)/temperature));
+                r = rand()/(double)(pow(2.,31)-1.);
+                std::cout << r << " vs " << ratio << std::endl;
+
+                double ALOT=100000000000.;
+
+                if (Res.first < ALOT)
+                {
+                    ofstream filestr;
+
+                    filestr.open ("best_opt_some.txt", ofstream::app);
+
+                    // >> i/o operations here <<
+                    filestr
+
+		    << "N, " << i << ", " << j << ", " << dx[j] << ", " << rejection[j] << ", |, " // FIXME: MW-DEBUGGING
+
+                    << un[0]->get_target() << ", "
+                    << Res.first
+                    << ", " << un[0]->get_parameter(0)
+                    << ", " << un[0]->get_parameter(1)
+                    << ", " << un[0]->get_parameter(2)
+                    << ", " << un[0]->get_parameter(3)
+                    << ", " << un[0]->get_parameter(4) << ", " << Res.second << ",\n";
+
+                    filestr.close();
+
+
+                    filestr.open ("max_dist.txt", ofstream::app);
+
+                    // >> i/o operations here <<
+                    filestr << max_dist << ",\n";
+
+                    filestr.close();
+
+                    FILE *bf;
+                    bf = fopen("bestdb.txt","a");
+                    fprintf(bf, "N %2d %2d %10.5f %5.2f | %5.2f %10.5f [ %5.2f %5.2f %10.5f %10.5f %10.5f ] %10.5f\n", i, j, dx[j], rejection[j],
+			    un[0]->get_target(),
+			    Res.first,
+			    un[0]->get_parameter(0),
+			    un[0]->get_parameter(1),
+			    un[0]->get_parameter(2),
+			    un[0]->get_parameter(3),
+			    un[0]->get_parameter(4),
+			    Res.second);
+                    fclose(bf);
+                }
+
+
+                if (r > ratio){
+
+                    std::cout << " "<< (i+1) << ","<< (j)
+                    <<" "<< (i+1) << " Did not accept "
+                    << x_tmp << "(" << j << ")" << std::endl;
+                    std::cout << un[0]->get_parameter(0)
+                    << " " << un[0]->get_parameter(1)
+                    << " " << un[0]->get_parameter(2)
+                    << " " << un[0]->get_parameter(3)
+                    << " " << un[0]->get_parameter(4) << " " << std::endl;
+
+                    x[j]=x_hold;
+                    for(int w=0; w<Nworkers; w++){
+                        un[w]->set_parameter(x[j], j);
+                    }
+
+
+                    //set_parameter(x[j], j);
+                    rejection[j]+=1.;
+                }
+
+                else {
+
+                    curr_x   = Res.first;
+                    curr_err = Res.second;
+                    x[j] = x_tmp;
+
+                    for(int w=0; w<Nworkers; w++){
+                        un[w]->set_parameter(x[j], j);
+                    }
+
+                    std::cout << (i+1) << string_wrap((string) " Rejection counts: ", 8)
+                    << wrap_double(rejection[0],2) << " "
+                    << wrap_double(rejection[1],7) << " "
+                    << wrap_double(rejection[2],5) << " "
+                    << wrap_double(rejection[3],9) << " "
+                    << wrap_double(rejection[4],6) << " "
+                    << std::endl << std::endl;
+
+                    std::cout << " "<< (i+1) <<","<< (j)
+                    <<" "
+                    << string_wrap((string) "***** Did accept! ", 3)
+                    << wrap_double(un[0]->get_parameter(0),2) << " "
+                    << wrap_double(un[0]->get_parameter(1),7) << " "
+                    << wrap_double(un[0]->get_parameter(2),5) << " "
+                    << wrap_double(un[0]->get_parameter(3),9) << " "
+                    << wrap_double(un[0]->get_parameter(4),6) << " "
+                    << std::endl << std::endl;
+
+
+
+                }
+                //........................................................
+
+            }
+        }
+
+    }
+
+}
+
+
+
+//================================================
+int
+main(int argc, char* argv[])
+{
+
+    double params0[6] = {0., 0., 0., 0., 0., 0.2}, target=50., range;
+    string par_names0[6] = {"alpha_i", "alpha_m", "beta", "gamma", "delta", "target"};
+    string par_names1[4] = {"n_epochs", "n_steps", "n_reruns", "range"};
+    string par_names2[5] = {"T_start", "T_end", "Annealing_steps","Target_rejection","Starting_jump"};
+    string par_names3[5] = {"FREEZE_alpha_i", "FREEZE_alpha_m", "FREEZE_beta", "FREEZE_gamma", "FREEZE_delta"};
+    string par_names4[3] = {"Operation", "Nworkers", "initSeed"};
+
+    int params1[4] = {300, 50, 1000, 10};
+    int params3[5] = { 0, 0, 0, 0, 0};
+
+    //          temperature_start,  temperature_end,  annealing_steps target_rejection  Starting_jump
+    double params2[5] = {1,             0.001,               100,              0.3,           1.5};
+
+    int verbose_level = 2;
+    const std::string one="one", two="two";
+    static Universe* un[NUniverse];
+#ifdef P_DISPATCH
+    static dispatch_queue_t CustomQueues[MAXNworkers];
+#endif
+    static double* Results;
+    static int*    Counters;
+
+    timeval t1, t2;
+    double elapsedTime;
+    // start timer
+    gettimeofday(&t1, NULL);
+
+
+    if (argc < 8) {
+        std::cout << "Usage: super_optimizer alpha_i alpha_m beta gamma delta target_innov [n_epochs n_steps n_reruns] [range] [verbose_level]\n";
+        std::cout << "         [T_start T_end Annealing_steps Target_rejection Starting_jump]\n";
+        std::cout << "         [FREEZE_alpha_i FREEZE_alpha_m FREEZE_beta FREEZE_gamma FREEZE_delta]\n";
+
+        system("pwd");
+
+
+        return(1);
+    }
+    else {
+        for (int nArg=0; nArg < argc; nArg++){
+            //std::cout << nArg << " " << argv[nArg] << std::endl;
+            if (nArg > 0 && nArg < 7){
+                params0[nArg-1]= atof(argv[nArg]);
+                std::cout << par_names0[nArg-1] << ": " << params0[nArg-1] <<  std::endl;
+            }
+            if (nArg > 6 && nArg < 11){
+                params1[nArg-7]= atoi(argv[nArg]);
+                std::cout << par_names1[nArg-7] << ": " << params1[nArg-7] <<  std::endl;
+            }
+            if (nArg == 11){
+                verbose_level = atoi(argv[nArg]);
+                std::cout << "verbose level: " << verbose_level <<  std::endl;
+            }
+            if (nArg > 11 && nArg < 17){
+                params2[nArg-12]= atof(argv[nArg]);
+                std::cout << par_names2[nArg-12] << ": " << params2[nArg-12] <<  std::endl;
+            }
+            if (nArg > 16 && nArg < 22){
+	        params3[nArg-17]= (int)round(atof(argv[nArg]));   // FIXME: Andrey: please verify that round() is correct.
+	        var_fixed[nArg-17]= (int)round(atof(argv[nArg])); // FIXME: ditto
+                std::cout << par_names3[nArg-17] << ": " << var_fixed[nArg-17] <<  std::endl;
+            }
+            if (nArg == 22 ){
+                operation = *argv[nArg];
+                std::cout << par_names4[0] << ": " << operation <<  std::endl;
+            }
+            if (nArg == 23 ){
+                Nworkers = atoi(argv[nArg]);
+                std::cout << par_names4[1] << ": " << Nworkers <<  std::endl;
+            }
+            if (nArg == 24 ){
+                initSeed = atoi(argv[nArg]);
+                std::cout << par_names4[2] << ": " << initSeed <<  std::endl;
+            }
+
+
+        }
+
+    }
+
+    for (int j=0; j<5; j++){
+
+        cout << j << " | " << var_fixed[j] << " (fixed) \n";
+    }
+
+    target=params0[5];
+    range = (double)params1[3];
+	int identify_failed = 0;
+	char* filename= (char *)"movie_graph.txt";
+ 	int n_ep=params1[0], n_st=params1[1], n_rep=params1[2];
+
+    //...............................
+
+    for(int i=0; i<NUniverse; i++){
+        un[i] = new Universe((char *)filename,n_ep,n_st,
+                             (int)n_rep,
+                             identify_failed, target, i2string(i));
+#ifdef P_DISPATCH
+        CustomQueues[i] = dispatch_queue_create(i2char(i), NULL);
+#endif
+    }
+
+    //...............................
+    if(n_rep > 0){
+
+        Results = new double[n_rep];
+        Counters = new int[n_rep];
+
+    }else {
+
+        Results =  NULL;
+        Counters = NULL;
+        std::cout << " Number of reruns should be positive! " <<  std::endl;
+        return 0;
+
+    }
+    //...............................
+    //srand(time(0));
+    //srandomdev();
+
+    if ( initSeed != 0.0 ) {
+      srand(initSeed);
+    }
+    else {
+        timeval t;
+        gettimeofday(&t, NULL);
+        srand(t.tv_usec);
+    }
+
+    {
+        double r=0;
+        for (int j=0; j<100; j++){
+
+
+
+            r = rand()/(double)(pow(2.,31)-1.);
+            std::cout << r << " ";
+        }
+        std::cout << "\n";
+    }
+  	//random initiation of starting parameters
+
+    if (range > 0.){
+
+        for (int i=0; i < 5; i++){
+
+            if (params0[i]==-100.){
+
+                double r1 = (rand()/(double)(pow(2.,31)-1.));
+                double r2 = (rand()/(double)(pow(2.,31)-1.));
+                double sign = 1.;
+
+                if(r1 > 0.5){
+                    sign=-1.;
+                }
+
+                params0[i] = sign*r2*range;
+
+                std::cout << par_names0[i] << ": " << params0[i] <<  std::endl;
+            }
+        }
+
+    }
+
+
+    double T_start=params2[0], T_end=params2[1], Target_rejection=params2[3], starting_jump=params2[4];
+    int Annealing_repeats = (int) params2[2];
+
+#ifdef P_DISPATCH
+    dispatch_group_t group = dispatch_group_create();
+
+    //.............................
+    multi_annealing(group, un, CustomQueues, T_start, T_end, Target_rejection, Annealing_repeats,
+                    starting_jump, Results, Counters, params0, Annealing_repeats);
+
+    //dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
+    dispatch_release(group);
+    //.............................
+#else
+    multi_annealing(       un,                T_start, T_end, Target_rejection, Annealing_repeats,
+                    starting_jump, Results, Counters, params0, Annealing_repeats);
+#endif
+
+
+    // stop timer
+    gettimeofday(&t2, NULL);
+
+    // compute and print the elapsed time in millisec
+    elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
+    elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms
+    elapsedTime /= 1000.;
+    cout << "\n*** optimizer completed, elapsed time=" << elapsedTime << " seconds " << elapsedTime/60. << " minutes)\n\n";
+
+    //.....................
+
+    for(int i=0; i<Nworkers; i++){
+        delete un[i];
+    }
+
+    //....................
+    if(n_rep > 0){
+
+        delete [] Results;
+        delete [] Counters;
+
+    }
+
+    return 0;
+
+
+
+}
+

Modified: SwiftApps/SciColSim/optimizer.cpp
===================================================================
--- SwiftApps/SciColSim/optimizer.cpp	2013-01-01 23:41:00 UTC (rev 6116)
+++ SwiftApps/SciColSim/optimizer.cpp	2013-01-02 00:14:03 UTC (rev 6117)
@@ -33,13 +33,8 @@
 #include <sys/time.h>
 #include <sys/types.h>
 
-#ifdef P_DISPATCH
-#include <dispatch/dispatch.h>
-#endif
-
 #include <fstream>
 
-
 #include <stdlib.h>
 #include <boost/numeric/ublas/io.hpp>
 #include <boost/graph/graph_traits.hpp>
@@ -85,14 +80,14 @@
 typedef boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;
 
 namespace std {
-	using ::time;
+  using ::time;
 }
 
 static int var_fixed[5] = {1, 0, 1, 1, 0};
 
 typedef boost::minstd_rand base_generator_type;
 typedef adjacency_list < listS, vecS, directedS,
-no_property, property < edge_weight_t, int > > graph_t;
+                         no_property, property < edge_weight_t, int > > graph_t;
 typedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor;
 typedef graph_traits < graph_t >::edge_descriptor edge_descriptor;
 
@@ -101,25 +96,25 @@
 //================================================
 string strDouble(double number)
 {
-    stringstream ss;//create a stringstream
-    ss << number;//add number to the stream
-    return ss.str();//return a string with the contents of the stream
+  stringstream ss;//create a stringstream
+  ss << number;//add number to the stream
+  return ss.str();//return a string with the contents of the stream
 }
 
 //================================================
 
 double gaussian(double sigma)
 {
-    double GaussNum = 0.0;
-    int NumInSum = 10;
-    for(int i = 0; i < NumInSum; i++)
-    {
-        GaussNum += ((double)rand()/(double)RAND_MAX - 0.5);
-    }
-    GaussNum = GaussNum*sqrt((double)12/(double)NumInSum);
+  double GaussNum = 0.0;
+  int NumInSum = 10;
+  for(int i = 0; i < NumInSum; i++)
+  {
+    GaussNum += ((double)rand()/(double)RAND_MAX - 0.5);
+  }
+  GaussNum = GaussNum*sqrt((double)12/(double)NumInSum);
 
 
-    return GaussNum;
+  return GaussNum;
 
 }
 
@@ -128,26 +123,26 @@
 //=================================================
 double diffclock(clock_t clock1,clock_t clock2)
 {
-	double diffticks=clock1-clock2;
-	double diffms=(diffticks)/CLOCKS_PER_SEC;
-	return diffms;
+  double diffticks=clock1-clock2;
+  double diffms=(diffticks)/CLOCKS_PER_SEC;
+  return diffms;
 }
 
 //================================================
 //================================================================
 double get_new_x(double x, double dx){
 
-    double new_x;
-    // boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);
-    double r = rand()/(double)(pow(2.,31)-1.);
+  double new_x;
+  // boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);
+  double r = rand()/(double)(pow(2.,31)-1.);
 
-    if (r > 0.5){
-        new_x = x + rand()*dx/(double)(pow(2.,31)-1.);
-    } else {
-        new_x = x - rand()*dx/(double)(pow(2.,31)-1.);
-    }
+  if (r > 0.5){
+    new_x = x + rand()*dx/(double)(pow(2.,31)-1.);
+  } else {
+    new_x = x - rand()*dx/(double)(pow(2.,31)-1.);
+  }
 
-    return new_x;
+  return new_x;
 
 }
 
@@ -155,57 +150,57 @@
 //===============================================
 string string_wrap(string ins, int mode){
 
-    std::ostringstream s;
+  std::ostringstream s;
 
-    switch(mode){
-        case 0:
-            s << "\033[1;29m" << ins << "\033[0m";
-            break;
-        case 1:
-            s << "\033[1;34m" << ins << "\033[0m";
-            break;
-        case 2:
-            s << "\033[1;44m" << ins << "\033[0m";
-            break;
-        case 3:
-            s << "\033[1;35m" << ins << "\033[0m";
-            break;
-        case 4:
-            s << "\033[1;33;44m" << ins << "\033[0m";
-            break;
-        case 5:
-            s << "\033[1;47;34m" << ins << "\033[0m";
-            break;
-        case 6:
-            s << "\033[1;1;31m" << ins << "\033[0m";
-            break;
-        case 7:
-            s << "\033[1;1;33m" << ins << "\033[0m";
-            break;
-        case 8:
-            s << "\033[1;1;43;34m" << ins << "\033[0m";
-            break;
-        case 9:
-            s << "\033[1;1;37m" << ins << "\033[0m";
-            break;
-        case 10:
-            s << "\033[1;30;47m" << ins << "\033[0m";
-            break;
-        default:
-            s << ins;
-    }
+  switch(mode){
+  case 0:
+    s << "\033[1;29m" << ins << "\033[0m";
+    break;
+  case 1:
+    s << "\033[1;34m" << ins << "\033[0m";
+    break;
+  case 2:
+    s << "\033[1;44m" << ins << "\033[0m";
+    break;
+  case 3:
+    s << "\033[1;35m" << ins << "\033[0m";
+    break;
+  case 4:
+    s << "\033[1;33;44m" << ins << "\033[0m";
+    break;
+  case 5:
+    s << "\033[1;47;34m" << ins << "\033[0m";
+    break;
+  case 6:
+    s << "\033[1;1;31m" << ins << "\033[0m";
+    break;
+  case 7:
+    s << "\033[1;1;33m" << ins << "\033[0m";
+    break;
+  case 8:
+    s << "\033[1;1;43;34m" << ins << "\033[0m";
+    break;
+  case 9:
+    s << "\033[1;1;37m" << ins << "\033[0m";
+    break;
+  case 10:
+    s << "\033[1;30;47m" << ins << "\033[0m";
+    break;
+  default:
+    s << ins;
+  }
 
-    return s.str();
+  return s.str();
 }
 
 
 //===============================================
 string wrap_double(double val, int mode){
 
-    std::ostringstream s;
-    s << string_wrap(strDouble(val),mode);
+  std::ostringstream s;
+  s << string_wrap(strDouble(val),mode);
 
-    return s.str();
+  return s.str();
 }
 
 
@@ -214,25 +209,25 @@
 const
 string i2string(int i){
 
-    std::ostringstream s;
-    s << "worker"
+  std::ostringstream s;
+  s << "worker"
     << lexical_cast<std::string>(i);
 
-    return s.str();
+  return s.str();
 
 }
 
 //===============================================
 char* i2char(int i){
 
-    std::ostringstream s;
-    s << "worker"
+  std::ostringstream s;
+  s << "worker"
     << lexical_cast<std::string>(i);
 
-    char* a=new char[s.str().size()+1];
-    memcpy(a,s.str().c_str(), s.str().size());
+  char* a=new char[s.str().size()+1];
+  memcpy(a,s.str().c_str(), s.str().size());
 
-    return a;
+  return a;
 }
 
 //================================================
@@ -240,72 +235,72 @@
 
 private:
 
-	double alpha_i;
-	double alpha_m;
-	double beta;
-	double gamma;
-	double delta;
+  double alpha_i;
+  double alpha_m;
+  double beta;
+  double gamma;
+  double delta;
 
-    double TargetNovelty;
-    double CumulativeRelativeLoss;
-    double CRLsquare;
-    string id;
+  double TargetNovelty;
+  double CumulativeRelativeLoss;
+  double CRLsquare;
+  string id;
 
 
-	int N_nodes;
-	int M_edges;
+  int N_nodes;
+  int M_edges;
 
-	int N_epochs;
-	int N_steps;
-	int N_repeats;
+  int N_epochs;
+  int N_steps;
+  int N_repeats;
 
-	int current_epoch;
-	double current_loss;
+  int current_epoch;
+  double current_loss;
   int current_repeat;
   double current_novelty;
 
-	int mode_identify_failed;
-    int verbose_level; // 0 is silent, higher is more
+  int mode_identify_failed;
+  int verbose_level; // 0 is silent, higher is more
 
-	double k_max;
+  double k_max;
 
-	graph_t Full_g;
+  graph_t Full_g;
 
-	double **Prob;
-	double **Tried;
-	double **Dist;
-	double **Final;
-    double **EdgeIndex;
-	double *Rank;
+  double **Prob;
+  double **Tried;
+  double **Dist;
+  double **Final;
+  double **EdgeIndex;
+  double *Rank;
 
-    base_generator_type generator;
-    boost::uniform_real<> uni_dist;
-    boost::geometric_distribution<double> geo;
+  base_generator_type generator;
+  boost::uniform_real<> uni_dist;
+  boost::geometric_distribution<double> geo;
 
 public:
 
 
 
-	//======  Constructor ======
-	Universe(const std::string FileToOpen, int Epochs, int Steps, int Repeats, int identify_failed, double target, const std::string idd)
-	{
-		//typedef array_type2::index index2;
+  //======  Constructor ======
+  Universe(const std::string FileToOpen, int Epochs, int Steps, int Repeats, int identify_failed, double target, const std::string idd)
+    {
+      //typedef array_type2::index index2;
 
 
-		std::ifstream inFile;
-        //string line;
+      std::ifstream inFile;
+      //string line;
 
-        //-------------------------------
+      //-------------------------------
 
-        base_generator_type gene(42u);
-        generator = gene;
+      base_generator_type gene(42u);
+      generator = gene;
 //        generator.seed(static_cast<unsigned int>(std::time(0)));
 
 
-    if ( initSeed != 0.0 ) {
+      if ( initSeed != 0.0 ) {
         generator.seed(static_cast<unsigned int>(initSeed));
       }
-    else {
+      else {
         timeval t;
         gettimeofday(&t, NULL);
         generator.seed(static_cast<unsigned int>(t.tv_usec));
@@ -315,1002 +310,962 @@
 
 
 
-        boost::uniform_real<> uni_d(0,1);
-        uni_dist = uni_d;
+      boost::uniform_real<> uni_d(0,1);
+      uni_dist = uni_d;
 
-        //--------------------------------
+      //--------------------------------
 
-		int i, k;
-        int x, y;
-		Edge* edge_array_mine;
-		int num_arcs_mine, num_nodes_mine;
-		int* weights_mine;
+      int i, k;
+      int x, y;
+      Edge* edge_array_mine;
+      int num_arcs_mine, num_nodes_mine;
+      int* weights_mine;
 
-        TargetNovelty = target;
-        CumulativeRelativeLoss = 0.;
-        CRLsquare = 0.;
+      TargetNovelty = target;
+      CumulativeRelativeLoss = 0.;
+      CRLsquare = 0.;
 
 
-		N_epochs  = Epochs;
-		N_steps   = Steps;
-		N_repeats = Repeats;
+      N_epochs  = Epochs;
+      N_steps   = Steps;
+      N_repeats = Repeats;
 
-		current_epoch = 0;
-		current_loss = 0.;
-		current_repeat = 0;
+      current_epoch = 0;
+      current_loss = 0.;
+      current_repeat = 0;
 
-        id = idd;
+      id = idd;
 
-        verbose_level = 1;
+      verbose_level = 1;
 
-		mode_identify_failed = identify_failed;
+      mode_identify_failed = identify_failed;
 
 
-		//-------------------------------
-		// The first pass though file with the graph
-		inFile.open(FileToOpen.c_str());
-		if (inFile.fail()) {
-			cout << "Unable to open file";
-			exit(1); // terminate with error
-		}else {
+      //-------------------------------
+      // The first pass though file with the graph
+      inFile.open(FileToOpen.c_str());
+      if (inFile.fail()) {
+        cout << "Unable to open file";
+        exit(1); // terminate with error
+      }else {
 
-            if (verbose_level > 2){
-                std::cout <<  " Opened <" << FileToOpen << ">"<<std::endl;
-            }
+        if (verbose_level > 2){
+          std::cout <<  " Opened <" << FileToOpen << ">"<<std::endl;
         }
+      }
 
-		i=0;
-        std::string line;
-		//while (! inFile.eof() && ! inFile.fail()) {
-        while (1==1) {
+      i=0;
+      std::string line;
+      //while (! inFile.eof() && ! inFile.fail()) {
+      while (1==1) {
 
-            inFile >> x;
-            inFile >> y;
+        inFile >> x;
+        inFile >> y;
 
-            if (verbose_level > 2){
-                std::cout << " x: " << x;
-                std::cout << " y: " << y << std::endl;
-            }
+        if (verbose_level > 2){
+          std::cout << " x: " << x;
+          std::cout << " y: " << y << std::endl;
+        }
 
-			if (i==0){
-				N_nodes=x;
-				M_edges=y;
-                break;
-			}
-			i++;
+        if (i==0){
+          N_nodes=x;
+          M_edges=y;
+          break;
+        }
+        i++;
 
 
-		}
-		inFile.close();
+      }
+      inFile.close();
 
-        if (verbose_level == 2){
-            std::cout << N_nodes <<  " nodes, " << M_edges << " edges"<<std::endl;
-        }
+      if (verbose_level == 2){
+        std::cout << N_nodes <<  " nodes, " << M_edges << " edges"<<std::endl;
+      }
 
-		// k_max is the longest distance possible
+      // k_max is the longest distance possible
 
-        //k_max = M_edges;
-		k_max = 70;
+      //k_max = M_edges;
+      k_max = 70;
 
-		//------------------------------------
-		// Get memory allocated for all class members
+      //------------------------------------
+      // Get memory allocated for all class members
 
-		Prob = allocate_2Dmatrix(N_nodes, N_nodes);
-		Tried = allocate_2Dmatrix(N_nodes, N_nodes);
-		Dist = allocate_2Dmatrix(N_nodes, N_nodes);
-		Final = allocate_2Dmatrix(N_nodes, N_nodes);
-        EdgeIndex = allocate_2Dmatrix(N_nodes, N_nodes);
-		Rank = allocate_1Dmatrix(N_nodes);
+      Prob = allocate_2Dmatrix(N_nodes, N_nodes);
+      Tried = allocate_2Dmatrix(N_nodes, N_nodes);
+      Dist = allocate_2Dmatrix(N_nodes, N_nodes);
+      Final = allocate_2Dmatrix(N_nodes, N_nodes);
+      EdgeIndex = allocate_2Dmatrix(N_nodes, N_nodes);
+      Rank = allocate_1Dmatrix(N_nodes);
 
-        //The second pass through file with the graph
+      //The second pass through file with the graph
 
-		for(int i = 0; i < N_nodes; ++i) {
-			Rank[i]=0.;
-			for(int j = 0; j < N_nodes; ++j) {
-				Final[i][j] = 0.;
-				Prob[i][j]=0.;
-				Dist[i][j]=-1.;
-				Tried[i][j]=0.;
-                EdgeIndex[i][j]=-1;
-			}
-		}
+      for(int i = 0; i < N_nodes; ++i) {
+        Rank[i]=0.;
+        for(int j = 0; j < N_nodes; ++j) {
+          Final[i][j] = 0.;
+          Prob[i][j]=0.;
+          Dist[i][j]=-1.;
+          Tried[i][j]=0.;
+          EdgeIndex[i][j]=-1;
+        }
+      }
 
 
-		// Fill in the final graph -- and we are ready to go!
+      // Fill in the final graph -- and we are ready to go!
 
-	    inFile.open(FileToOpen.c_str());
-		if (!inFile) {
-            std::cout << "Unable to open file";
-			exit(1); // terminate with error
-		}
-		else {
+      inFile.open(FileToOpen.c_str());
+      if (!inFile) {
+        std::cout << "Unable to open file";
+        exit(1); // terminate with error
+      }
+      else {
 
-            if (verbose_level > 2){
-                std::cout <<  " Opened <" << FileToOpen << ">"<<std::endl;
-            }
+        if (verbose_level > 2){
+          std::cout <<  " Opened <" << FileToOpen << ">"<<std::endl;
         }
+      }
 
-		i=0;
-		while (inFile >> x && inFile >>y) {
-			if (i > 0) {
-				Final[x][y]=1.;
-				Final[y][x]=1.;
+      i=0;
+      while (inFile >> x && inFile >>y) {
+        if (i > 0) {
+          Final[x][y]=1.;
+          Final[y][x]=1.;
 
 
-                if (verbose_level == 2){
-                    std::cout << ".";
-                }
-			}
-			i++;
-
-		}
-        if (verbose_level == 2){
-            std::cout << std::endl;
+          if (verbose_level == 2){
+            std::cout << ".";
+          }
         }
-		inFile.close();
+        i++;
 
-        k=0;
-        for (int i=0; i<N_nodes-1; i++){
-            for (int j=i+1;j<N_nodes; j++){
-                if(Final[i][j] > 0.){
-                    EdgeIndex[i][j]=k;
-                    k++;
-                }
-            }
+      }
+      if (verbose_level == 2){
+        std::cout << std::endl;
+      }
+      inFile.close();
+
+      k=0;
+      for (int i=0; i<N_nodes-1; i++){
+        for (int j=i+1;j<N_nodes; j++){
+          if(Final[i][j] > 0.){
+            EdgeIndex[i][j]=k;
+            k++;
+          }
         }
+      }
 
 
 
-		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-		// create graph -- hopefully, we can keep it, just modifying edge weights
+      //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+      // create graph -- hopefully, we can keep it, just modifying edge weights
 
 
-		edge_array_mine = new Edge[2*M_edges];
-		num_arcs_mine = 2*M_edges;
-		num_nodes_mine = N_nodes;
-		weights_mine = new int[2*M_edges];
-		for (int i=0; i<2*M_edges; i++){ weights_mine[i]=1;}
+      edge_array_mine = new Edge[2*M_edges];
+      num_arcs_mine = 2*M_edges;
+      num_nodes_mine = N_nodes;
+      weights_mine = new int[2*M_edges];
+      for (int i=0; i<2*M_edges; i++){ weights_mine[i]=1;}
 
-		k=0;
-		for(int i=0; i<N_nodes-1; i++){
-			for( int j=i+1; j<N_nodes; j++){
-				if (Final[i][j]>0.){
-					edge_array_mine[2*k]  =Edge(i,j);
-					edge_array_mine[2*k+1]=Edge(j,i);
-					k++;
-				}
-			}
-		}
-		graph_t g(edge_array_mine, edge_array_mine + num_arcs_mine, weights_mine, num_nodes_mine);
+      k=0;
+      for(int i=0; i<N_nodes-1; i++){
+        for( int j=i+1; j<N_nodes; j++){
+          if (Final[i][j]>0.){
+            edge_array_mine[2*k]  =Edge(i,j);
+            edge_array_mine[2*k+1]=Edge(j,i);
+            k++;
+          }
+        }
+      }
+      graph_t g(edge_array_mine, edge_array_mine + num_arcs_mine, weights_mine, num_nodes_mine);
 
-		Full_g = g;
-		delete edge_array_mine;
-		delete weights_mine;
+      Full_g = g;
+      delete edge_array_mine;
+      delete weights_mine;
 
-		//===========================================================================
-		std::vector<edge_descriptor> p(num_edges(Full_g));
-		std::vector<int> d(num_edges(Full_g));
-		edge_descriptor s;
-		boost::graph_traits<graph_t>::vertex_descriptor u, v;
+      //===========================================================================
+      std::vector<edge_descriptor> p(num_edges(Full_g));
+      std::vector<int> d(num_edges(Full_g));
+      edge_descriptor s;
+      boost::graph_traits<graph_t>::vertex_descriptor u, v;
 
-		for (int i=0; i<N_nodes-1; i++){
-			for (int j=i+1; j<N_nodes; j++){
-				if (Final[i][j] > 0.){
-					u = vertex(i, Full_g);
-					v = vertex(j, Full_g);
-					remove_edge(u,v,Full_g);
-					remove_edge(v,u,Full_g);
+      for (int i=0; i<N_nodes-1; i++){
+        for (int j=i+1; j<N_nodes; j++){
+          if (Final[i][j] > 0.){
+            u = vertex(i, Full_g);
+            v = vertex(j, Full_g);
+            remove_edge(u,v,Full_g);
+            remove_edge(v,u,Full_g);
 
-				}
-			}
-		}
-		if(max_loss <= 0.0) set_max_loss(N_nodes, M_edges, TargetNovelty);
+          }
+        }
+      }
+      if(max_loss <= 0.0) set_max_loss(N_nodes, M_edges, TargetNovelty);
     }
 
 
-	//=====================================================================
-	int sample_failed_number(double pfail){
+  //=====================================================================
+  int sample_failed_number(double pfail){
 
-		//boost::geometric_distribution<double> geo(pfail);
-		//boost::variate_generator<base_generator_type&, geometric_distribution<double> > geom(generator, geo);
+    //boost::geometric_distribution<double> geo(pfail);
+    //boost::variate_generator<base_generator_type&, geometric_distribution<double> > geom(generator, geo);
 
-		double r, u, g;
+    double r, u, g;
 
-        r=0.;
-		for(int i=0; i<N_steps; i++){
+    r=0.;
+    for(int i=0; i<N_steps; i++){
 
-            u=(double)rand();
-            u = 1.-u /(double)(pow(2.,31)-1.);
-            g=(int)(ceil(log(u) / log(pfail)));
+      u=(double)rand();
+      u = 1.-u /(double)(pow(2.,31)-1.);
+      g=(int)(ceil(log(u) / log(pfail)));
 
-			//r += geom();
+      //r += geom();
 
-            r+=g;
-		}
-
-        if (verbose_level>=3){
-            std::cout << id << " failed " << r << std::endl;
-		}
-	return (int) round(r);  // FIXME: Andrey: please verify that round() is correct.
-
-	}
-
-    //=============================================
-    double get_target(void){
-        return TargetNovelty;
+      r+=g;
     }
 
-    //=============================================
-    void set_target(double target){
-        TargetNovelty=target;
+    if (verbose_level>=3){
+      std::cout << id << " failed " << r << std::endl;
     }
+    return (int) round(r);  // FIXME: Andrey: please verify that round() is correct.
 
-	//=============================================
-	int sample(){
+  }
 
-        //boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);
-        // double r = uni(), Summa = 0.;
+  //=============================================
+  double get_target(void){
+    return TargetNovelty;
+  }
 
+  //=============================================
+  void set_target(double target){
+    TargetNovelty=target;
+  }
 
+  //=============================================
+  int sample(){
 
-        double r = rand(), Summa = 0.;
-        r /= (double)(pow(2.,31)-1.);
-		int result = 0;
-		int finished = 0;
+    //boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);
+    // double r = uni(), Summa = 0.;
 
-        if (verbose_level==4){
-            std::cout << id << " sampled " << r << std::endl;
-        }
 
-		for(int i=0; i<N_nodes-1 && finished==0; i++){
-			for( int j=i+1; j<N_nodes && finished==0; j++){
 
-				Summa += Prob[i][j];
+    double r = rand(), Summa = 0.;
+    r /= (double)(pow(2.,31)-1.);
+    int result = 0;
+    int finished = 0;
 
-				if (Summa > r){
+    if (verbose_level==4){
+      std::cout << id << " sampled " << r << std::endl;
+    }
 
-					Tried[i][j]+=1.;
+    for(int i=0; i<N_nodes-1 && finished==0; i++){
+      for( int j=i+1; j<N_nodes && finished==0; j++){
 
-					if (Final[i][j] > 0.){
-						result = 1;
-					}
-					finished = 1;
-				}
-			}
-		}
+        Summa += Prob[i][j];
 
-		return result;
+        if (Summa > r){
 
-	}
+          Tried[i][j]+=1.;
 
-	//===============================
-	void update_current_graph(void){
+          if (Final[i][j] > 0.){
+            result = 1;
+          }
+          finished = 1;
+        }
+      }
+    }
 
-		std::vector<edge_descriptor> p(num_edges(Full_g));
-		std::vector<int> d(num_edges(Full_g));
-		edge_descriptor s;
-		boost::graph_traits<graph_t>::vertex_descriptor u, v;
+    return result;
 
-		//property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, Full_g);
-		for (int i=0; i<N_nodes-1; i++){
-			for (int j=i+1; j<N_nodes; j++){
-				if (Final[i][j] > 0. && Tried[i][j]>0){
-					//s = edge(i, j, Full_g);
-					boost::graph_traits<graph_t>::edge_descriptor e1,e2;
-					bool found1, found2;
-					u = vertex(i, Full_g);
-					v = vertex(j, Full_g);
-					tie(e1, found1) = edge(u, v, Full_g);
-					tie(e2, found2) = edge(v, u, Full_g);
-					if (!found1 && !found2){
-						add_edge(u,v,1,Full_g);
-					    add_edge(v,u,1,Full_g);
-					}
+  }
 
-				}
-			}
+  //===============================
+  void update_current_graph(void){
 
-		}
-	}
+    std::vector<edge_descriptor> p(num_edges(Full_g));
+    std::vector<int> d(num_edges(Full_g));
+    edge_descriptor s;
+    boost::graph_traits<graph_t>::vertex_descriptor u, v;
 
-	//===============================
-	void update_distances(void){
-		// put shortest paths to the *Dist[][]
-		std::vector<vertex_descriptor> p(num_vertices(Full_g));
-		std::vector<int> d(num_vertices(Full_g));
-		vertex_descriptor s;
+    //property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, Full_g);
+    for (int i=0; i<N_nodes-1; i++){
+      for (int j=i+1; j<N_nodes; j++){
+        if (Final[i][j] > 0. && Tried[i][j]>0){
+          //s = edge(i, j, Full_g);
+          boost::graph_traits<graph_t>::edge_descriptor e1,e2;
+          bool found1, found2;
+          u = vertex(i, Full_g);
+          v = vertex(j, Full_g);
+          tie(e1, found1) = edge(u, v, Full_g);
+          tie(e2, found2) = edge(v, u, Full_g);
+          if (!found1 && !found2){
+            add_edge(u,v,1,Full_g);
+            add_edge(v,u,1,Full_g);
+          }
 
+        }
+      }
 
-		// put shortest paths to the *Dist[][]
-		for (int j=0; j<num_vertices(Full_g); j++){
+    }
+  }
 
-			if(Rank[j] > 0.){
-				s = vertex(j, Full_g);
-				dijkstra_shortest_paths(Full_g, s, predecessor_map(&p[0]).distance_map(&d[0]));
+  //===============================
+  void update_distances(void){
+    // put shortest paths to the *Dist[][]
+    std::vector<vertex_descriptor> p(num_vertices(Full_g));
+    std::vector<int> d(num_vertices(Full_g));
+    vertex_descriptor s;
 
-				//std::cout <<" Vertex "<< j << std::endl;
-				graph_traits < graph_t >::vertex_iterator vi, vend;
 
-				for (boost::tie(vi, vend) = vertices(Full_g); vi != vend; ++vi) {
+    // put shortest paths to the *Dist[][]
+    for (int j=0; j<num_vertices(Full_g); j++){
 
-					if (p[*vi]!=*vi){
-						Dist[*vi][j]=d[*vi];
-						Dist[j][*vi]=d[*vi];
+      if(Rank[j] > 0.){
+        s = vertex(j, Full_g);
+        dijkstra_shortest_paths(Full_g, s, predecessor_map(&p[0]).distance_map(&d[0]));
 
-						if ( (int)round(Dist[*vi][j]>max_dist)) {
-						  // FIXME: Andrey: please verify that (int) cast is correct. Do we need to round()?
-						  // also, the indent on this iff statement was way off -
-						  // perhaps due to space v. tab?
-						  max_dist=(int)round(Dist[*vi][j]);
-						}
+        //std::cout <<" Vertex "<< j << std::endl;
+        graph_traits < graph_t >::vertex_iterator vi, vend;
 
+        for (boost::tie(vi, vend) = vertices(Full_g); vi != vend; ++vi) {
 
-					} else {
-						Dist[*vi][j]=-1.;
-						Dist[j][*vi]=-1.;
-					}
-				}
-			}
+          if (p[*vi]!=*vi){
+            Dist[*vi][j]=d[*vi];
+            Dist[j][*vi]=d[*vi];
 
-		}
+            if ( (int)round(Dist[*vi][j]>max_dist)) {
+              // FIXME: Andrey: please verify that (int) cast is correct. Do we need to round()?
+              // also, the indent on this iff statement was way off -
+              // perhaps due to space v. tab?
+              max_dist=(int)round(Dist[*vi][j]);
+            }
 
 
-	}
+          } else {
+            Dist[*vi][j]=-1.;
+            Dist[j][*vi]=-1.;
+          }
+        }
+      }
 
-	//======================================================
-	void update_ranks(void){
+    }
 
-		for(int i=0; i<N_nodes; i++){
-			Rank[i]=0.;
-		}
 
-		for(int i=0; i<N_nodes-1; i++){
-			for( int j=i+1; j<N_nodes; j++){
-				if (Tried[i][j]>0. && Final[i][j] >0.){
-					Rank[i]++;
-					Rank[j]++;
-				}
-			}
-		}
+  }
 
-	}
+  //======================================================
+  void update_ranks(void){
 
-	//====================================================================
-	void set_world(double a_i, double a_m, double b, double g, double d){
+    for(int i=0; i<N_nodes; i++){
+      Rank[i]=0.;
+    }
 
-		alpha_i=a_i;
-		alpha_m=a_m;
-		gamma=g;
-		beta=b;
-		delta=d;
+    for(int i=0; i<N_nodes-1; i++){
+      for( int j=i+1; j<N_nodes; j++){
+        if (Tried[i][j]>0. && Final[i][j] >0.){
+          Rank[i]++;
+          Rank[j]++;
+        }
+      }
+    }
 
-	}
+  }
 
-	//====================================================================
-	void reset_world(){
+  //====================================================================
+  void set_world(double a_i, double a_m, double b, double g, double d){
 
-        //====================================================
-		std::vector<edge_descriptor> p(num_edges(Full_g));
-		std::vector<int> d(num_edges(Full_g));
-		edge_descriptor s;
-		boost::graph_traits<graph_t>::vertex_descriptor u, v;
-		cout << "reset_world: start id=" << id << endl;
+    alpha_i=a_i;
+    alpha_m=a_m;
+    gamma=g;
+    beta=b;
+    delta=d;
 
-		for (int i=0; i<N_nodes-1; i++){
-			for (int j=i+1; j<N_nodes; j++){
-				if (Final[i][j] > 0. && Tried[i][j] > 0){
-					u = vertex(i, Full_g);
-					v = vertex(j, Full_g);
-					remove_edge(u,v,Full_g);
-					remove_edge(v,u,Full_g);
+  }
 
-				}
-			}
-		}
+  //====================================================================
+  void reset_world(){
 
-        //==================================================
+    //====================================================
+    std::vector<edge_descriptor> p(num_edges(Full_g));
+    std::vector<int> d(num_edges(Full_g));
+    edge_descriptor s;
+    boost::graph_traits<graph_t>::vertex_descriptor u, v;
+    cout << "reset_world: start id=" << id << endl;
 
-		current_loss=0;
-		current_epoch=0;
-		current_repeat++;
-        current_novelty=0;
+    for (int i=0; i<N_nodes-1; i++){
+      for (int j=i+1; j<N_nodes; j++){
+        if (Final[i][j] > 0. && Tried[i][j] > 0){
+          u = vertex(i, Full_g);
+          v = vertex(j, Full_g);
+          remove_edge(u,v,Full_g);
+          remove_edge(v,u,Full_g);
 
-		for(int i = 0; i < N_nodes; ++i) {
-			Rank[i]=0.;
-			for(int j = 0; j < N_nodes; ++j) {
-				Prob[i][j]=0.;
-				Dist[i][j]=-1.;
-				Tried[i][j]=0.;
-			}
-		}
-		cout << "reset_world: end id=" << id << endl;
-	}
+        }
+      }
+    }
 
+    //==================================================
 
-    //==============================================
-    void show_parameters(void){
+    current_loss=0;
+    current_epoch=0;
+    current_repeat++;
+    current_novelty=0;
 
-        std::cout << "Parameters: "
-        << alpha_i << " "
-        << alpha_m << " | "
-        << beta << " "
-        << gamma << " | "
-        << delta << std::endl;
-
+    for(int i = 0; i < N_nodes; ++i) {
+      Rank[i]=0.;
+      for(int j = 0; j < N_nodes; ++j) {
+        Prob[i][j]=0.;
+        Dist[i][j]=-1.;
+        Tried[i][j]=0.;
+      }
     }
+    cout << "reset_world: end id=" << id << endl;
+  }
 
 
+  //==============================================
+  void show_parameters(void){
 
-    //===============================================
-    string file_name(){
+    std::cout << "Parameters: "
+              << alpha_i << " "
+              << alpha_m << " | "
+              << beta << " "
+              << gamma << " | "
+              << delta << std::endl;
 
-        std::ostringstream s;
-        s << "world_"
-        << lexical_cast<std::string>(alpha_i) << "_"
-        << lexical_cast<std::string>(alpha_m) << "_"
-        << lexical_cast<std::string>(beta) << "_"
-        << lexical_cast<std::string>(gamma) << "_"
-        << lexical_cast<std::string>(delta) << "_"
-        << lexical_cast<std::string>(N_epochs) << "_"
-        << lexical_cast<std::string>(N_steps) << "_"
-        << lexical_cast<std::string>(N_repeats) << ".txt";
+  }
 
-        return s.str();
 
-    }
 
+  //===============================================
+  string file_name(){
 
+    std::ostringstream s;
+    s << "world_"
+      << lexical_cast<std::string>(alpha_i) << "_"
+      << lexical_cast<std::string>(alpha_m) << "_"
+      << lexical_cast<std::string>(beta) << "_"
+      << lexical_cast<std::string>(gamma) << "_"
+      << lexical_cast<std::string>(delta) << "_"
+      << lexical_cast<std::string>(N_epochs) << "_"
+      << lexical_cast<std::string>(N_steps) << "_"
+      << lexical_cast<std::string>(N_repeats) << ".txt";
 
+    return s.str();
 
-    //=================================================
-    void set_verbose(int verbose){
+  }
 
-        verbose_level = verbose;
-    }
 
 
-    //=============================================================
-    void update_probabilities(void){
 
+  //=================================================
+  void set_verbose(int verbose){
 
-        //=========================
-		// Compute sampling probabilities
-		// first pass: \xi_i,j
-		for(int i=0; i<N_nodes-1; i++){
-			for( int j=i+1; j<N_nodes; j++){
+    verbose_level = verbose;
+  }
 
-				double bg = 0.;
 
-				Prob[i][j] = alpha_i*log(min(Rank[i]+1.,Rank[j]+1.)) +
-                alpha_m*log(max(Rank[i]+1.,Rank[j]+1.));
+  //=============================================================
+  void update_probabilities(void){
 
-                if (Dist[i][j] > 0.){
 
-                    double k = Dist[i][j];
-                    if (k >= k_max){
-                        k = k_max-1;
-                    }
+    //=========================
+    // Compute sampling probabilities
+    // first pass: \xi_i,j
+    for(int i=0; i<N_nodes-1; i++){
+      for( int j=i+1; j<N_nodes; j++){
 
-                    bg = beta * log(k/k_max) + gamma * log(1. - k/k_max);
+        double bg = 0.;
 
-                } else {
-                    bg = delta;
-                }
+        Prob[i][j] = alpha_i*log(min(Rank[i]+1.,Rank[j]+1.)) +
+          alpha_m*log(max(Rank[i]+1.,Rank[j]+1.));
 
-				Prob[i][j] = exp(Prob[i][j] + bg);
-			}
-		}
+        if (Dist[i][j] > 0.){
 
+          double k = Dist[i][j];
+          if (k >= k_max){
+            k = k_max-1;
+          }
 
-		// second pass: sum
-		double Summa = 0.;
+          bg = beta * log(k/k_max) + gamma * log(1. - k/k_max);
 
-		for(int i=0; i<N_nodes-1; i++){
-			for( int j=i+1; j<N_nodes; j++){
-				Summa += Prob[i][j];
-			}
-		}
+        } else {
+          bg = delta;
+        }
 
-		// third pass: normalize
-		for(int i=0; i<N_nodes-1; i++){
-			for( int j=i+1; j<N_nodes; j++){
-				Prob[i][j] /= Summa;
-			}
-		}
-
+        Prob[i][j] = exp(Prob[i][j] + bg);
+      }
     }
 
-	// Now we are ready for simulations
-	//==============================================
-	void update_world(){
 
-		int failed = 0;
+    // second pass: sum
+    double Summa = 0.;
 
-		// Given current universe compute shortest paths
-		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+    for(int i=0; i<N_nodes-1; i++){
+      for( int j=i+1; j<N_nodes; j++){
+        Summa += Prob[i][j];
+      }
+    }
 
-		update_current_graph();
-		update_ranks();
-		update_distances();
-		update_probabilities();
+    // third pass: normalize
+    for(int i=0; i<N_nodes-1; i++){
+      for( int j=i+1; j<N_nodes; j++){
+        Prob[i][j] /= Summa;
+      }
+    }
 
-		//===============================
-		// sampling
-		int result;
-		double cost=0., novel=0.;
-		int publishable = 0;
+  }
 
+  // Now we are ready for simulations
+  //==============================================
+  void update_world(){
 
-		//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-		if (mode_identify_failed == 1){
+    int failed = 0;
 
-			while(publishable < N_steps){
+    // Given current universe compute shortest paths
+    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
-		    	result = sample();
-			    publishable += result;
-			    failed += (1-result);
+    update_current_graph();
+    update_ranks();
+    update_distances();
+    update_probabilities();
 
-			}
+    //===============================
+    // sampling
+    int result;
+    double cost=0., novel=0.;
+    int publishable = 0;
 
-			for(int i=0; i<N_nodes-1; i++){
-				for( int j=i+1; j<N_nodes; j++){
 
-					cost+=Tried[i][j];
+    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+    if (mode_identify_failed == 1){
 
-					if (Tried[i][j]>0. && Final[i][j]>0.){
-						novel+=1.;
-					}
-				}
-			}
+      while(publishable < N_steps){
 
-		}
-		//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-		else {
+        result = sample();
+        publishable += result;
+        failed += (1-result);
 
-			double pfail=0.;
-			int n_failed;
-			//, n_check = 0;
+      }
 
-			for(int i=0; i<N_nodes-1; i++){
-				for( int j=i+1; j<N_nodes; j++){
-					if (Final[i][j] == 0.){
-						pfail += Prob[i][j];
-						Prob[i][j] = 0.;
-					}
+      for(int i=0; i<N_nodes-1; i++){
+        for( int j=i+1; j<N_nodes; j++){
 
-				}
-			}
+          cost+=Tried[i][j];
 
-			for(int i=0; i<N_nodes-1; i++){
-				for( int j=i+1; j<N_nodes; j++){
-					Prob[i][j] /= (1.-pfail);
-				}
-				//std::cout << std::endl;
-			}
+          if (Tried[i][j]>0. && Final[i][j]>0.){
+            novel+=1.;
+          }
+        }
+      }
 
-			n_failed = sample_failed_number(pfail);
-			while(publishable < N_steps){
+    }
+    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+    else {
 
-		    	result = sample();
-			    publishable += result;
-			}
+      double pfail=0.;
+      int n_failed;
+      //, n_check = 0;
 
+      for(int i=0; i<N_nodes-1; i++){
+        for( int j=i+1; j<N_nodes; j++){
+          if (Final[i][j] == 0.){
+            pfail += Prob[i][j];
+            Prob[i][j] = 0.;
+          }
 
-			current_loss += (n_failed + N_steps);
-			cost = current_loss;
+        }
+      }
 
-			for(int i=0; i<N_nodes-1; i++){
-				for( int j=i+1; j<N_nodes; j++){
+      for(int i=0; i<N_nodes-1; i++){
+        for( int j=i+1; j<N_nodes; j++){
+          Prob[i][j] /= (1.-pfail);
+        }
+        //std::cout << std::endl;
+      }
 
-					if (Tried[i][j]>0. && Final[i][j]>0.){
-						novel+=1.;
-					}
-				}
-			}
-		}
+      n_failed = sample_failed_number(pfail);
+      while(publishable < N_steps){
 
-        current_novelty = novel;
+        result = sample();
+        publishable += result;
+      }
 
 
-		//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-		if (verbose_level == 2){
-            std::cout << (current_repeat+1) << "  epoch=" << (current_epoch+1)
+      current_loss += (n_failed + N_steps);
+      cost = current_loss;
 
-		    << "  cost=" << cost
-		    << " novel=" << novel
-		    << " rel_loss=" << cost/novel
-		    << std::endl;
+      for(int i=0; i<N_nodes-1; i++){
+        for( int j=i+1; j<N_nodes; j++){
+
+          if (Tried[i][j]>0. && Final[i][j]>0.){
+            novel+=1.;
+          }
         }
+      }
+    }
 
-		current_epoch++;
-	}
+    current_novelty = novel;
 
 
-	//======  Destructor ======
-	~Universe(){
+    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+    if (verbose_level == 2){
+      std::cout << (current_repeat+1) << "  epoch=" << (current_epoch+1)
 
-		delete_2Dmatrix(Final, N_nodes);
-		delete_2Dmatrix(Dist, N_nodes);
-		delete_2Dmatrix(Tried, N_nodes);
-		delete_2Dmatrix(Prob, N_nodes);
-        delete_2Dmatrix(EdgeIndex, N_nodes);
-		delete_1Dmatrix(Rank);
-	}
+                << "  cost=" << cost
+                << " novel=" << novel
+                << " rel_loss=" << cost/novel
+                << std::endl;
+    }
 
-    //================================================
-    // Allocate memory
-    double** allocate_2Dmatrix(int N, int M)
+    current_epoch++;
+  }
+
+
+  //======  Destructor ======
+  ~Universe(){
+
+    delete_2Dmatrix(Final, N_nodes);
+    delete_2Dmatrix(Dist, N_nodes);
+    delete_2Dmatrix(Tried, N_nodes);
+    delete_2Dmatrix(Prob, N_nodes);
+    delete_2Dmatrix(EdgeIndex, N_nodes);
+    delete_1Dmatrix(Rank);
+  }
+
+  //================================================
+  // Allocate memory
+  double** allocate_2Dmatrix(int N, int M)
     {
-        double **pointer;
+      double **pointer;
 
-        if (verbose_level == 2){
-            std::cout<< "["<<N<<"|"<<M<<"]"<<std::endl;
-        }
-        pointer = new double*[N];
-        for (int i = 0; i < N; ++i)
-            pointer[i] = new double[M];
+      if (verbose_level == 2){
+        std::cout<< "["<<N<<"|"<<M<<"]"<<std::endl;
+      }
+      pointer = new double*[N];
+      for (int i = 0; i < N; ++i)
+        pointer[i] = new double[M];
 
-        return pointer;
+      return pointer;
     }
-    //===================
-    double* allocate_1Dmatrix(int N)
+  //===================
+  double* allocate_1Dmatrix(int N)
     {
-        double *pointer;
+      double *pointer;
 
-        if(N > 0){
+      if(N > 0){
 
-            pointer = new double[N];
+        pointer = new double[N];
 
-        }else {
+      }else {
 
-            pointer = NULL;
-        }
+        pointer = NULL;
+      }
 
-        return pointer;
+      return pointer;
 
     }
 
-    //==============================================
-    // De-Allocate memory to prevent memory leak
-    void delete_2Dmatrix(double **pointer, int N){
+  //==============================================
+  // De-Allocate memory to prevent memory leak
+  void delete_2Dmatrix(double **pointer, int N){
 
-        if (pointer != NULL){
+    if (pointer != NULL){
 
-            for (int i = 0; i < N; ++i){
-                delete [] pointer[i];
-            }
-            delete [] pointer;
-        }
+      for (int i = 0; i < N; ++i){
+        delete [] pointer[i];
+      }
+      delete [] pointer;
     }
-    //====================
-    void delete_1Dmatrix(double *pointer){
+  }
+  //====================
+  void delete_1Dmatrix(double *pointer){
 
-        delete [] pointer;
-    }
+    delete [] pointer;
+  }
 
-    //===========================================
-    double get_rel_loss(){
+  //===========================================
+  double get_rel_loss(){
 
-        return CumulativeRelativeLoss ;
-    }
+    return CumulativeRelativeLoss ;
+  }
 
-    //===========================================
-    double get_rel_loss_err(){
+  //===========================================
+  double get_rel_loss_err(){
 
-        return CRLsquare ;
-    }
+    return CRLsquare ;
+  }
 
 
 
-    //==================================================================================
-    void evolve_to_target_and_save(int istart, int iend, double* storage, int* counters){
+  //==================================================================================
+  void evolve_to_target_and_save(int istart, int iend, double* storage, int* counters){
 
-      //double ALOT=100000000000.;
-        double ALOT= 3.0 * max_loss; // Per Andrey, 2012.12.29
+    //double ALOT=100000000000.;
+    double ALOT= 3.0 * max_loss; // Per Andrey, 2012.12.29
 
-        double ratio = 0.0;
-        int check = 0;
+    double ratio = 0.0;
+    int check = 0;
 
-        reset_world();
+    reset_world();
 
-        for (int k = istart; k < iend; k++){
-	  cout << "evolve_ttas: k=" << k << endl; 
+    for (int k = istart; k < iend; k++){
+      cout << "evolve_ttas: k=" << k << endl;
 
-            for(int i=0; i< N_epochs &&  current_novelty < TargetNovelty; i++){
+      for(int i=0; i< N_epochs &&  current_novelty < TargetNovelty; i++){
 
-                if(ratio < max_loss){
-                    update_world();
-                }
-                else{
-		  cout << "k=" << k << " i=" << i << " ratio=" << ratio << " max_loss=" << max_loss << endl;
-                    break;
-                }
-                ratio = current_loss/current_novelty;
-            }
-            if( ratio < max_loss )
-                storage[k]=current_loss/current_novelty;
-            else
-                storage[k]=ALOT;
-            counters[k]=1;
-            reset_world();
+        if(ratio < max_loss){
+          update_world();
         }
+        else{
+          cout << "k=" << k << " i=" << i << " ratio=" << ratio << " max_loss=" << max_loss << endl;
+          break;
+        }
+        ratio = current_loss/current_novelty;
+      }
+      if( ratio < max_loss )
+        storage[k]=current_loss/current_novelty;
+      else
+        storage[k]=ALOT;
+      counters[k]=1;
+      reset_world();
     }
+  }
 
-    //==============================================
-    int get_reruns(void){
-        return N_repeats;
-    }
+  //==============================================
+  int get_reruns(void){
+    return N_repeats;
+  }
 
-    //==============================================
-    double get_parameter(int i){
+  //==============================================
+  double get_parameter(int i){
 
-        switch(i){
-            case 0:
-                return alpha_i;
-            case 1:
-                return alpha_m;
-            case 2:
-                return beta;
-            case 3:
-                return gamma;
-            case 4:
-                return delta;
-            default:
+    switch(i){
+    case 0:
+      return alpha_i;
+    case 1:
+      return alpha_m;
+    case 2:
+      return beta;
+    case 3:
+      return gamma;
+    case 4:
+      return delta;
+    default:
 
-                std::cout << "Erroneous parameter id!!!!\n\n\n";
-                return 0.;
-        }
+      std::cout << "Erroneous parameter id!!!!\n\n\n";
+      return 0.;
     }
+  }
 
 
-    //==============================================
-    void evolve_to_target(){
+  //==============================================
+  void evolve_to_target(){
 
-        reset_world();
-        if (beta < -1. || gamma < -1.){
-            CumulativeRelativeLoss = 100000000000.;
-            CRLsquare = 0.;
-            return;
-        }
+    reset_world();
+    if (beta < -1. || gamma < -1.){
+      CumulativeRelativeLoss = 100000000000.;
+      CRLsquare = 0.;
+      return;
+    }
 
 
-        for (int k=0; k< N_repeats; k++){
+    for (int k=0; k< N_repeats; k++){
 
 
-            for(int i=0; i<N_epochs &&  current_novelty < TargetNovelty; i++){
-                update_world();
-            }
+      for(int i=0; i<N_epochs &&  current_novelty < TargetNovelty; i++){
+        update_world();
+      }
 
-            CumulativeRelativeLoss += current_loss/current_novelty;
-            CRLsquare += (current_loss/current_novelty)*(current_loss/current_novelty);
-            if(verbose_level==3){
-                std::cout <<  CumulativeRelativeLoss << " | " << CRLsquare << std::endl;
-            }
+      CumulativeRelativeLoss += current_loss/current_novelty;
+      CRLsquare += (current_loss/current_novelty)*(current_loss/current_novelty);
+      if(verbose_level==3){
+        std::cout <<  CumulativeRelativeLoss << " | " << CRLsquare << std::endl;
+      }
 
-            if(verbose_level==1){
-                std::cout <<  "." ;
+      if(verbose_level==1){
+        std::cout <<  "." ;
 
-            }
-            else if(verbose_level==2){
-                std::cout <<  "**" << (k+1) <<  "**  curr loss " << current_loss << "; curr novelty " << current_novelty << std::endl;
-            }
+      }
+      else if(verbose_level==2){
+        std::cout <<  "**" << (k+1) <<  "**  curr loss " << current_loss << "; curr novelty " << current_novelty << std::endl;
+      }
 
 
-            reset_world();
-        }
+      reset_world();
+    }
 
-        CumulativeRelativeLoss /= double(N_repeats);
-        CRLsquare /= double(N_repeats);
+    CumulativeRelativeLoss /= double(N_repeats);
+    CRLsquare /= double(N_repeats);
 
-        if(verbose_level==1){
-            std::cout << std::endl;
-        }
+    if(verbose_level==1){
+      std::cout << std::endl;
+    }
 
-        if(verbose_level==2){
-            std::cout <<  CumulativeRelativeLoss << " || " << CRLsquare << std::endl;
-        }
-
-        CRLsquare = 2*sqrt((CRLsquare - CumulativeRelativeLoss*CumulativeRelativeLoss)/double(N_repeats));
-
+    if(verbose_level==2){
+      std::cout <<  CumulativeRelativeLoss << " || " << CRLsquare << std::endl;
     }
 
+    CRLsquare = 2*sqrt((CRLsquare - CumulativeRelativeLoss*CumulativeRelativeLoss)/double(N_repeats));
 
-    //================================================================
-    int set_parameter(double value, int position){
+  }
 
-        if (position < 0 || position > 4) {return 0;}
 
-        else {
+  //================================================================
+  int set_parameter(double value, int position){
 
-            switch(position){
-                case 0:
-                    alpha_i=value;
-                    return 1;
-                case 1:
-                    alpha_m=value;
-                    return 1;
-                case 2:
-                    beta=value;
-                    return 1;
-                case 3:
-                    gamma=value;
-                    return 1;
-                case 4:
-                    delta=value;
-                    return 1;
-            }
+    if (position < 0 || position > 4) {return 0;}
 
-        }
+    else {
 
-        return 0;
+      switch(position){
+      case 0:
+        alpha_i=value;
+        return 1;
+      case 1:
+        alpha_m=value;
+        return 1;
+      case 2:
+        beta=value;
+        return 1;
+      case 3:
+        gamma=value;
+        return 1;
+      case 4:
+        delta=value;
+        return 1;
+      }
+
     }
 
+    return 0;
+  }
+
 //--------
 
-void set_max_loss(long long v, long long e, long long t) {
+  void set_max_loss(long long v, long long e, long long t) {
 
-  cout << "set_max_loss v=" << v << " e=" << e << " t=" << t << " max_loss=" << max_loss << endl;
+    cout << "set_max_loss v=" << v << " e=" << e << " t=" << t << " max_loss=" << max_loss << endl;
 
-  // Based on formulas from random_analytical.pdf
+    // Based on formulas from random_analytical.pdf
 
-  double sum, ERLt, VarRLt;
+    double sum, ERLt, VarRLt;
 
-  // (9): E[RLt] = (1/t) * SUM(i=0 to T of: (V*(V-1) / (2 * (E-i))
+    // (9): E[RLt] = (1/t) * SUM(i=0 to T of: (V*(V-1) / (2 * (E-i))
 
-  sum = 0;
-  for(int i=0;i<t;i++) {
-    sum += ((double)(v*(v-1))) / ((double)(2*(e-i)));
-  }
-  ERLt = (1.0/(double) t) * sum;
+    sum = 0;
+    for(int i=0;i<t;i++) {
+      sum += ((double)(v*(v-1))) / ((double)(2*(e-i)));
+    }
+    ERLt = (1.0/(double) t) * sum;
 
-  // (12): Var[RLt] = 1 / (T**2) * SUM( i=0 to T of: ((V*(V-1))/2) - E + 1 ) / ((E-i)**2)
+    // (12): Var[RLt] = 1 / (T**2) * SUM( i=0 to T of: ((V*(V-1))/2) - E + 1 ) / ((E-i)**2)
 
-  sum = 0;
-  for(int i=0;i<t;i++) {
-    sum +=  
-      ( (((double)(v*(v-1)))/ 2.0) - (double)e + (double)i )
-      /  
-      (double)((e-i)*(e-i))
-      ;
-    if ( (double)((e-i)*(e-i)) == 0.0 ) {
-      printf( "set_max_loss: while doing variance: zero denom: %d %d\n", e, i);
+    sum = 0;
+    for(int i=0;i<t;i++) {
+      sum +=
+        ( (((double)(v*(v-1)))/ 2.0) - (double)e + (double)i )
+        /
+        (double)((e-i)*(e-i))
+        ;
+      if ( (double)((e-i)*(e-i)) == 0.0 ) {
+        printf( "set_max_loss: while doing variance: zero denom: %d %d\n", e, i);
+        exit(1);
+      }
+    }
+    int tmp = t*t;
+    VarRLt = (1.0/(double)((t) * t)) * sum;
+    if (VarRLt < 0.0) {
+      printf( "set_max_loss: while doing variance: VarRLT %d < 0\n", VarRLt);
       exit(1);
     }
-  }
-  int tmp = t*t;
-  VarRLt = (1.0/(double)((t) * t)) * sum;
-  if (VarRLt < 0.0) {
-    printf( "set_max_loss: while doing variance: VarRLT %d < 0\n", VarRLt);
-    exit(1);
-  }
 
-  // (9) + 3sigma = E[RLt] + 3 * SQRT(Var)
+    // (9) + 3sigma = E[RLt] + 3 * SQRT(Var)
 
-  max_loss = ERLt + (3.0 * sqrt(VarRLt));
-  printf("set_max_loss: %12d %12.3f %12.8e %12.3f\n", t, ERLt, VarRLt, max_loss);
-}
+    max_loss = ERLt + (3.0 * sqrt(VarRLt));
+    printf("set_max_loss: %12d %12.3f %12.8e %12.3f\n", t, ERLt, VarRLt, max_loss);
+  }
 
 }; // End of class Universe
 
 //============================================================
 
-#ifdef P_DISPATCH
-std::pair<double,double> multi_loss(dispatch_group_t group,
-                                    Universe* un[],
-                                    dispatch_queue_t* CustomQueues,
-                                    double* Results,
-                                    int*    Counters,
-                                    double* params){
-#else
 std::pair<double,double> multi_loss(Universe* un[],
                                     double* Results,
                                     int*    Counters,
                                     double* params){
 
-#endif
+  int N = un[0]->get_reruns();
+  int step = (int)floor((double)N/(double)(Nworkers)); // FIXME: Andrey: please check change in cast grouping and use of floor
+  int istart=0;
+  int iend = istart+step;
 
-    int N = un[0]->get_reruns();
-    int step = (int)floor((double)N/(double)(Nworkers)); // FIXME: Andrey: please check change in cast grouping and use of floor
-    int istart=0;
-    int iend = istart+step;
+  double Loss=0., LossSquare=0.;
 
-    double Loss=0., LossSquare=0.;
+  timeval startTime, endTime;
+  double elapsedTime;
+  gettimeofday(&startTime, NULL);
 
-    timeval startTime, endTime;
-    double elapsedTime;
-    gettimeofday(&startTime, NULL);
+  if ( N > NUniverse ) {
+    std::cerr << "Error: Number of reruns=" << N << " is greater than max NUniverse=" << NUniverse << "\n";
+    exit(1);
+  }
 
-    if ( N > NUniverse ) {
-      std::cerr << "Error: Number of reruns=" << N << " is greater than max NUniverse=" << NUniverse << "\n";
-      exit(1);
+  for(int i=0; i<N; i++){
+    for(int j=0; j<5; j++){
+      un[i]->set_parameter(params[j],j);
     }
+  }
 
-    for(int i=0; i<N; i++){
-        for(int j=0; j<5; j++){
-            un[i]->set_parameter(params[j],j);
-        }
-    }
+  int i;
 
-#ifdef P_DISPATCH
-    for(int i=0; i<Nworkers; i++){
+  // Execute rerun loop in parallel
 
-        dispatch_group_async(group, CustomQueues[i], ^{
+#pragma omp parallel for private (i)
+  for(i=0; i<N; i++){
+    un[i]->evolve_to_target_and_save(i, i+1, Results, Counters);
+  }
 
-            // un[i]->evolve_to_target_and_save(istart, iend, Results, Counters);
-            un[i]->evolve_to_target_and_save(i*step, min((i+1)*step,N), Results, Counters);
-        });
-
-        std::cout << "queued: i=" << i << " N=" << N << " istart=" << istart << " iend=" << iend << "\n";
-        // istart += step;
-        // iend = min(istart+step,N);
-
-    }
-    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
-    //dispatch_release(group);
-#else
-    int i;
-
-    // Execute rerun loop in parallel
-
-    #pragma omp parallel for private (i)
-    for(i=0; i<N; i++){
-        un[i]->evolve_to_target_and_save(i, i+1, Results, Counters);
-     }
-#endif
-
 /*
-    for (int i=0; i<N; i++){
-        Loss+=Results[i]/(double)N;
-        LossSquare+=Results[i]*Results[i]/(double)N;
-    }
+  for (int i=0; i<N; i++){
+  Loss+=Results[i]/(double)N;
+  LossSquare+=Results[i]*Results[i]/(double)N;
+  }
 
-    double two_std = ((LossSquare - Loss*Loss)/(double)N);
-    double two_std_dev = 2.*sqrt(two_std);
+  double two_std = ((LossSquare - Loss*Loss)/(double)N);
+  double two_std_dev = 2.*sqrt(two_std);
 */
 
-    double sumsqdel;
-    Loss = 0.0, sumsqdel = 0.0;
-    for (int i=0; i<N; i++) {
-      Loss+=Results[i];
-    }
-    Loss /= (double)N;
-    for (int i=0; i<N; i++) {
-      double delta = Results[i] - Loss;
-      sumsqdel += delta*delta;
-    }
-    double variance = sumsqdel / double(N);
-    double two_std = 2.0 * sqrt(variance);
+  double sumsqdel;
+  Loss = 0.0, sumsqdel = 0.0;
+  for (int i=0; i<N; i++) {
+    Loss+=Results[i];
+  }
+  Loss /= (double)N;
+  for (int i=0; i<N; i++) {
+    double delta = Results[i] - Loss;
+    sumsqdel += delta*delta;
+  }
+  double variance = sumsqdel / double(N);
+  double two_std = 2.0 * sqrt(variance);
 
-    cout << "multi_loss: Loss=" << Loss << " sumsqdel=" << sumsqdel << " variance=" << variance << " two_std=" << two_std << endl;
-    std::pair<double,double> Res;
-    Res.first=Loss;
-    Res.second=two_std;
+  cout << "multi_loss: Loss=" << Loss << " sumsqdel=" << sumsqdel << " variance=" << variance << " two_std=" << two_std << endl;
+  std::pair<double,double> Res;
+  Res.first=Loss;
+  Res.second=two_std;
 
-    gettimeofday(&endTime, NULL);
-    elapsedTime = (endTime.tv_sec - startTime.tv_sec) * 1000.0;      // sec to ms
-    elapsedTime += (endTime.tv_usec - startTime.tv_usec) / 1000.0;   // us to ms
-    elapsedTime /= 1000.;
-    cout << "multi_loss(N=" << N << ", target=" << un[0]->get_target() << ") elapsed time: " << elapsedTime << " seconds " << elapsedTime/60. << " minutes\n\n";
+  gettimeofday(&endTime, NULL);
+  elapsedTime = (endTime.tv_sec - startTime.tv_sec) * 1000.0;      // sec to ms
+  elapsedTime += (endTime.tv_usec - startTime.tv_usec) / 1000.0;   // us to ms
+  elapsedTime /= 1000.;
+  cout << "multi_loss(N=" << N << ", target=" << un[0]->get_target() << ") elapsed time: " << elapsedTime << " seconds " << elapsedTime/60. << " minutes\n\n";
 
-    return Res;
+  return Res;
 }
 //============================================================
 
 
 //============================================================
-#ifdef P_DISPATCH
-void multi_annealing( dispatch_group_t group,
-                     Universe* un[],
-                     dispatch_queue_t* CustomQueues,
-                     double T_start, double T_end,
-                     double Target_rejection,
-                     int Annealing_repeats,
-                     double starting_jump,
-                     double* Results,
-                     int*    Counters,
-                     double* params0,
-                     double annealing_cycles){
-#else
+
 void multi_annealing(Universe* un[],
                      double T_start, double T_end,
                      double Target_rejection,
@@ -1320,190 +1275,184 @@
                      int*    Counters,
                      double* params0,
                      double annealing_cycles){
-#endif
-    //.................................
-    // re-implement annealing
 
-    double dx[5]={0.,0.,0.,0.,0};
-    double x[5]={0.,0.,0.,0.,0};
-    double rejection[5]={0., 0., 0., 0., 0.};
-    double curr_x, curr_err, x_tmp;
-    double temperature;
-    double ratio, r;
-    int cycle=10;
-    //boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);
+  //.................................
+  // re-implement annealing
 
-    // set up parameter for annealing
+  double dx[5]={0.,0.,0.,0.,0};
+  double x[5]={0.,0.,0.,0.,0};
+  double rejection[5]={0., 0., 0., 0., 0.};
+  double curr_x, curr_err, x_tmp;
+  double temperature;
+  double ratio, r;
+  int cycle=10;
+  //boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);
 
-    x[0]=params0[0];
-    x[1]=params0[1];
-    x[2]=params0[2];
-    x[3]=params0[3];
-    x[4]=params0[4];
+  // set up parameter for annealing
 
-    for(int i=0;i<5;i++){
-        dx[i] = starting_jump;
-    }
+  x[0]=params0[0];
+  x[1]=params0[1];
+  x[2]=params0[2];
+  x[3]=params0[3];
+  x[4]=params0[4];
 
-    // establish the current value
-    std::pair<double,double>Res;
+  for(int i=0;i<5;i++){
+    dx[i] = starting_jump;
+  }
 
-#ifdef P_DISPATCH
-    Res = multi_loss(group, un, CustomQueues, Results, Counters, x);
-#else
-    Res = multi_loss(       un,               Results, Counters, x);
-#endif
-    std::cout << "Returned from initial multi_loss:" << std::endl;
-    std::cout << Res.first << " +- " << Res.second << std::endl;
+  // establish the current value
+  std::pair<double,double>Res;
 
-    if ( operation == 'm' ) {
-      FILE *f;
-      int N = un[0]->get_reruns();
+  Res = multi_loss(       un,               Results, Counters, x);
 
-      f = fopen("multi_loss.data","w");
-      for(int i=0; i<N; i++) {
-        fprintf(f,"%.20e\n",Results[i]);
-      }
-      fclose(f);
-      exit(0);
+  std::cout << "Returned from initial multi_loss:" << std::endl;
+  std::cout << Res.first << " +- " << Res.second << std::endl;
+
+  if ( operation == 'm' ) {
+    FILE *f;
+    int N = un[0]->get_reruns();
+
+    f = fopen("multi_loss.data","w");
+    for(int i=0; i<N; i++) {
+      fprintf(f,"%.20e\n",Results[i]);
     }
+    fclose(f);
+    exit(0);
+  }
 
-    curr_x   = Res.first;
-    curr_err = Res.second;
+  curr_x   = Res.first;
+  curr_err = Res.second;
 
-    // optimization cycle
+  // optimization cycle
 
-    for(int i=0; i<annealing_cycles; i++){
+  for(int i=0; i<annealing_cycles; i++){
 
-        temperature = T_start*exp( i*(log(T_end)-log(T_start))/(double)annealing_cycles);
-        std::cout  << std::endl << "....T = " << wrap_double(temperature,3) << std::endl << std::endl;
+    temperature = T_start*exp( i*(log(T_end)-log(T_start))/(double)annealing_cycles);
+    std::cout  << std::endl << "....T = " << wrap_double(temperature,3) << std::endl << std::endl;
 
-        if (i % cycle == 0 && i > 0){
+    if (i % cycle == 0 && i > 0){
 
-            for (int k=0; k<5; k++){
-                rejection[k]/=(double)cycle;
+      for (int k=0; k<5; k++){
+        rejection[k]/=(double)cycle;
 
-                if (rejection[k] > 0){
-                    dx[k] = dx[k]/(rejection[k]/Target_rejection);
-                    rejection[k]=0.;
-                }
-                else{
-                    dx[k]*=2.;
-                }
-                std::cout  << dx[k] << " ";
-            }
-            std::cout  << std::endl;
+        if (rejection[k] > 0){
+          dx[k] = dx[k]/(rejection[k]/Target_rejection);
+          rejection[k]=0.;
         }
+        else{
+          dx[k]*=2.;
+        }
+        std::cout  << dx[k] << " ";
+      }
+      std::cout  << std::endl;
+    }
 
 
-        for (int j=0; j<5; j++){
+    for (int j=0; j<5; j++){
 
-            ///////////////////////////////
-            if (FIX_VARIABLES==0 || var_fixed[j]==0){
+      ///////////////////////////////
+      if (FIX_VARIABLES==0 || var_fixed[j]==0){
 
 
 
-                // get new value of x[j]
-                double x_hold=x[j];
-                x_tmp = get_new_x(x[j],dx[j]);
-                x[j]=x_tmp;
+        // get new value of x[j]
+        double x_hold=x[j];
+        x_tmp = get_new_x(x[j],dx[j]);
+        x[j]=x_tmp;
 
-                std::cout << wrap_double(x_tmp,10) << " " << wrap_double(j,9) << "\n\n";
-                //=======================================
-                //.............................................
-                for(int w=0; w<Nworkers; w++){
-                    un[w]->set_parameter(x_tmp, j);
-                }
+        std::cout << wrap_double(x_tmp,10) << " " << wrap_double(j,9) << "\n\n";
+        //=======================================
+        //.............................................
+        for(int w=0; w<Nworkers; w++){
+          un[w]->set_parameter(x_tmp, j);
+        }
 
-#ifdef P_DISPATCH
-                Res = multi_loss(group, un, CustomQueues, Results, Counters, x);
-#else
-                Res = multi_loss(       un,               Results, Counters, x);
-#endif
-                std::cout << Res.first << " +- " << Res.second << std::endl;
+        Res = multi_loss(       un,               Results, Counters, x);
 
-                ratio = min(1.,exp(-(Res.first-curr_x)/temperature));
-                r = rand()/(double)(pow(2.,31)-1.);
-                std::cout << r << " vs " << ratio << std::endl;
+        std::cout << Res.first << " +- " << Res.second << std::endl;
 
-                double ALOT=100000000000.;
+        ratio = min(1.,exp(-(Res.first-curr_x)/temperature));
+        r = rand()/(double)(pow(2.,31)-1.);
+        std::cout << r << " vs " << ratio << std::endl;
 
-                if (Res.first < ALOT)
-                {
-                    ofstream filestr;
+        double ALOT=100000000000.;
 
-                    filestr.open ("best_opt_some.txt", ofstream::app);
+        if (Res.first < ALOT)
+        {
+          ofstream filestr;
 
-                    // >> i/o operations here <<
-                    filestr
+          filestr.open ("best_opt_some.txt", ofstream::app);
 
-		    << "N, " << i << ", " << j << ", " << dx[j] << ", " << rejection[j] << ", |, " // FIXME: MW-DEBUGGING
+          // >> i/o operations here <<
+          filestr
 
-                    << un[0]->get_target() << ", "
-                    << Res.first
-                    << ", " << un[0]->get_parameter(0)
-                    << ", " << un[0]->get_parameter(1)
-                    << ", " << un[0]->get_parameter(2)
-                    << ", " << un[0]->get_parameter(3)
-                    << ", " << un[0]->get_parameter(4) << ", " << Res.second << ",\n";
+            << "N, " << i << ", " << j << ", " << dx[j] << ", " << rejection[j] << ", |, " // FIXME: MW-DEBUGGING
 
-                    filestr.close();
+            << un[0]->get_target() << ", "
+            << Res.first
+            << ", " << un[0]->get_parameter(0)
+            << ", " << un[0]->get_parameter(1)
+            << ", " << un[0]->get_parameter(2)
+            << ", " << un[0]->get_parameter(3)
+            << ", " << un[0]->get_parameter(4) << ", " << Res.second << ",\n";
 
+          filestr.close();
 
-                    filestr.open ("max_dist.txt", ofstream::app);
 
-                    // >> i/o operations here <<
-                    filestr << max_dist << ",\n";
+          filestr.open ("max_dist.txt", ofstream::app);
 
-                    filestr.close();
+          // >> i/o operations here <<
+          filestr << max_dist << ",\n";
 
-                    FILE *bf;
-                    bf = fopen("bestdb.txt","a");
-                    fprintf(bf, "N %2d %2d %10.5f %5.2f | %5.2f %10.5f [ %5.2f %5.2f %10.5f %10.5f %10.5f ] %10.5f\n", i, j, dx[j], rejection[j],
-			    un[0]->get_target(),
-			    Res.first,
-			    un[0]->get_parameter(0),
-			    un[0]->get_parameter(1),
-			    un[0]->get_parameter(2),
-			    un[0]->get_parameter(3),
-			    un[0]->get_parameter(4),
-			    Res.second);
-                    fclose(bf);
-                }
+          filestr.close();
 
+          FILE *bf;
+          bf = fopen("bestdb.txt","a");
+          fprintf(bf, "N %2d %2d %10.5f %5.2f | %5.2f %10.5f [ %5.2f %5.2f %10.5f %10.5f %10.5f ] %10.5f\n", i, j, dx[j], rejection[j],
+                  un[0]->get_target(),
+                  Res.first,
+                  un[0]->get_parameter(0),
+                  un[0]->get_parameter(1),
+                  un[0]->get_parameter(2),
+                  un[0]->get_parameter(3),
+                  un[0]->get_parameter(4),
+                  Res.second);
+          fclose(bf);
+        }
 
-                if (r > ratio){
 
-                    std::cout << " "<< (i+1) << ","<< (j)
+        if (r > ratio){
+
+          std::cout << " "<< (i+1) << ","<< (j)
                     <<" "<< (i+1) << " Did not accept "
                     << x_tmp << "(" << j << ")" << std::endl;
-                    std::cout << un[0]->get_parameter(0)
+          std::cout << un[0]->get_parameter(0)
                     << " " << un[0]->get_parameter(1)
                     << " " << un[0]->get_parameter(2)
                     << " " << un[0]->get_parameter(3)
                     << " " << un[0]->get_parameter(4) << " " << std::endl;
 
-                    x[j]=x_hold;
-                    for(int w=0; w<Nworkers; w++){
-                        un[w]->set_parameter(x[j], j);
-                    }
+          x[j]=x_hold;
+          for(int w=0; w<Nworkers; w++){
+            un[w]->set_parameter(x[j], j);
+          }
 
 
-                    //set_parameter(x[j], j);
-                    rejection[j]+=1.;
-                }
+          //set_parameter(x[j], j);
+          rejection[j]+=1.;
+        }
 
-                else {
+        else {
 
-                    curr_x   = Res.first;
-                    curr_err = Res.second;
-                    x[j] = x_tmp;
+          curr_x   = Res.first;
+          curr_err = Res.second;
+          x[j] = x_tmp;
 
-                    for(int w=0; w<Nworkers; w++){
-                        un[w]->set_parameter(x[j], j);
-                    }
+          for(int w=0; w<Nworkers; w++){
+            un[w]->set_parameter(x[j], j);
+          }
 
-                    std::cout << (i+1) << string_wrap((string) " Rejection counts: ", 8)
+          std::cout << (i+1) << string_wrap((string) " Rejection counts: ", 8)
                     << wrap_double(rejection[0],2) << " "
                     << wrap_double(rejection[1],7) << " "
                     << wrap_double(rejection[2],5) << " "
@@ -1511,7 +1460,7 @@
                     << wrap_double(rejection[4],6) << " "
                     << std::endl << std::endl;
 
-                    std::cout << " "<< (i+1) <<","<< (j)
+          std::cout << " "<< (i+1) <<","<< (j)
                     <<" "
                     << string_wrap((string) "***** Did accept! ", 3)
                     << wrap_double(un[0]->get_parameter(0),2) << " "
@@ -1523,14 +1472,14 @@
 
 
 
-                }
-                //........................................................
-
-            }
         }
+        //........................................................
 
+      }
     }
 
+  }
+
 }
 
 
@@ -1540,216 +1489,197 @@
 main(int argc, char* argv[])
 {
 
-    double params0[6] = {0., 0., 0., 0., 0., 0.2}, target=50., range;
-    string par_names0[6] = {"alpha_i", "alpha_m", "beta", "gamma", "delta", "target"};
-    string par_names1[4] = {"n_epochs", "n_steps", "n_reruns", "range"};
-    string par_names2[5] = {"T_start", "T_end", "Annealing_steps","Target_rejection","Starting_jump"};
-    string par_names3[5] = {"FREEZE_alpha_i", "FREEZE_alpha_m", "FREEZE_beta", "FREEZE_gamma", "FREEZE_delta"};
-    string par_names4[3] = {"Operation", "Nworkers", "initSeed"};
+  double params0[6] = {0., 0., 0., 0., 0., 0.2}, target=50., range;
+  string par_names0[6] = {"alpha_i", "alpha_m", "beta", "gamma", "delta", "target"};
+  string par_names1[4] = {"n_epochs", "n_steps", "n_reruns", "range"};
+  string par_names2[5] = {"T_start", "T_end", "Annealing_steps","Target_rejection","Starting_jump"};
+  string par_names3[5] = {"FREEZE_alpha_i", "FREEZE_alpha_m", "FREEZE_beta", "FREEZE_gamma", "FREEZE_delta"};
+  string par_names4[3] = {"Operation", "Nworkers", "initSeed"};
 
-    int params1[4] = {300, 50, 1000, 10};
-    int params3[5] = { 0, 0, 0, 0, 0};
+  int params1[4] = {300, 50, 1000, 10};
+  int params3[5] = { 0, 0, 0, 0, 0};
 
-    //          temperature_start,  temperature_end,  annealing_steps target_rejection  Starting_jump
-    double params2[5] = {1,             0.001,               100,              0.3,           1.5};
+  //          temperature_start,  temperature_end,  annealing_steps target_rejection  Starting_jump
+  double params2[5] = {1,             0.001,               100,              0.3,           1.5};
 
-    int verbose_level = 2;
-    const std::string one="one", two="two";
-    static Universe* un[NUniverse];
-#ifdef P_DISPATCH
-    static dispatch_queue_t CustomQueues[MAXNworkers];
-#endif
-    static double* Results;
-    static int*    Counters;
+  int verbose_level = 2;
+  const std::string one="one", two="two";
+  static Universe* un[NUniverse];
+  static double* Results;
+  static int*    Counters;
 
-    timeval t1, t2;
-    double elapsedTime;
-    // start timer
-    gettimeofday(&t1, NULL);
+  timeval t1, t2;
+  double elapsedTime;
+  // start timer
+  gettimeofday(&t1, NULL);
 
 
-    if (argc < 8) {
-        std::cout << "Usage: super_optimizer alpha_i alpha_m beta gamma delta target_innov [n_epochs n_steps n_reruns] [range] [verbose_level]\n";
-        std::cout << "         [T_start T_end Annealing_steps Target_rejection Starting_jump]\n";
-        std::cout << "         [FREEZE_alpha_i FREEZE_alpha_m FREEZE_beta FREEZE_gamma FREEZE_delta]\n";
+  if (argc < 8) {
+    std::cout << "Usage: super_optimizer alpha_i alpha_m beta gamma delta target_innov [n_epochs n_steps n_reruns] [range] [verbose_level]\n";
+    std::cout << "         [T_start T_end Annealing_steps Target_rejection Starting_jump]\n";
+    std::cout << "         [FREEZE_alpha_i FREEZE_alpha_m FREEZE_beta FREEZE_gamma FREEZE_delta]\n";
 
-        system("pwd");
+    system("pwd");
 
 
-        return(1);
-    }
-    else {
-        for (int nArg=0; nArg < argc; nArg++){
-            //std::cout << nArg << " " << argv[nArg] << std::endl;
-            if (nArg > 0 && nArg < 7){
-                params0[nArg-1]= atof(argv[nArg]);
-                std::cout << par_names0[nArg-1] << ": " << params0[nArg-1] <<  std::endl;
-            }
-            if (nArg > 6 && nArg < 11){
-                params1[nArg-7]= atoi(argv[nArg]);
-                std::cout << par_names1[nArg-7] << ": " << params1[nArg-7] <<  std::endl;
-            }
-            if (nArg == 11){
-                verbose_level = atoi(argv[nArg]);
-                std::cout << "verbose level: " << verbose_level <<  std::endl;
-            }
-            if (nArg > 11 && nArg < 17){
-                params2[nArg-12]= atof(argv[nArg]);
-                std::cout << par_names2[nArg-12] << ": " << params2[nArg-12] <<  std::endl;
-            }
-            if (nArg > 16 && nArg < 22){
-	        params3[nArg-17]= (int)round(atof(argv[nArg]));   // FIXME: Andrey: please verify that round() is correct.
-	        var_fixed[nArg-17]= (int)round(atof(argv[nArg])); // FIXME: ditto
-                std::cout << par_names3[nArg-17] << ": " << var_fixed[nArg-17] <<  std::endl;
-            }
-            if (nArg == 22 ){
-                operation = *argv[nArg];
-                std::cout << par_names4[0] << ": " << operation <<  std::endl;
-            }
-            if (nArg == 23 ){
-                Nworkers = atoi(argv[nArg]);
-                std::cout << par_names4[1] << ": " << Nworkers <<  std::endl;
-            }
-            if (nArg == 24 ){
-                initSeed = atoi(argv[nArg]);
-                std::cout << par_names4[2] << ": " << initSeed <<  std::endl;
-            }
+    return(1);
+  }
+  else {
+    for (int nArg=0; nArg < argc; nArg++){
+      //std::cout << nArg << " " << argv[nArg] << std::endl;
+      if (nArg > 0 && nArg < 7){
+        params0[nArg-1]= atof(argv[nArg]);
+        std::cout << par_names0[nArg-1] << ": " << params0[nArg-1] <<  std::endl;
+      }
+      if (nArg > 6 && nArg < 11){
+        params1[nArg-7]= atoi(argv[nArg]);
+        std::cout << par_names1[nArg-7] << ": " << params1[nArg-7] <<  std::endl;
+      }
+      if (nArg == 11){
+        verbose_level = atoi(argv[nArg]);
+        std::cout << "verbose level: " << verbose_level <<  std::endl;
+      }
+      if (nArg > 11 && nArg < 17){
+        params2[nArg-12]= atof(argv[nArg]);
+        std::cout << par_names2[nArg-12] << ": " << params2[nArg-12] <<  std::endl;
+      }
+      if (nArg > 16 && nArg < 22){
+        params3[nArg-17]= (int)round(atof(argv[nArg]));   // FIXME: Andrey: please verify that round() is correct.
+        var_fixed[nArg-17]= (int)round(atof(argv[nArg])); // FIXME: ditto
+        std::cout << par_names3[nArg-17] << ": " << var_fixed[nArg-17] <<  std::endl;
+      }
+      if (nArg == 22 ){
+        operation = *argv[nArg];
+        std::cout << par_names4[0] << ": " << operation <<  std::endl;
+      }
+      if (nArg == 23 ){
+        Nworkers = atoi(argv[nArg]);
+        std::cout << par_names4[1] << ": " << Nworkers <<  std::endl;
+      }
+      if (nArg == 24 ){
+        initSeed = atoi(argv[nArg]);
+        std::cout << par_names4[2] << ": " << initSeed <<  std::endl;
+      }
 
 
-        }
-
     }
 
-    for (int j=0; j<5; j++){
+  }
 
-        cout << j << " | " << var_fixed[j] << " (fixed) \n";
-    }
+  for (int j=0; j<5; j++){
 
-    target=params0[5];
-    range = (double)params1[3];
-	int identify_failed = 0;
-	char* filename= (char *)"movie_graph.txt";
- 	int n_ep=params1[0], n_st=params1[1], n_rep=params1[2];
+    cout << j << " | " << var_fixed[j] << " (fixed) \n";
+  }
 
-    //...............................
+  target=params0[5];
+  range = (double)params1[3];
+  int identify_failed = 0;
+  char* filename= (char *)"movie_graph.txt";
+  int n_ep=params1[0], n_st=params1[1], n_rep=params1[2];
 
-    for(int i=0; i<NUniverse; i++){
-        un[i] = new Universe((char *)filename,n_ep,n_st,
-                             (int)n_rep,
-                             identify_failed, target, i2string(i));
-#ifdef P_DISPATCH
-        CustomQueues[i] = dispatch_queue_create(i2char(i), NULL);
-#endif
-    }
+  //...............................
 
-    //...............................
-    if(n_rep > 0){
+  for(int i=0; i<NUniverse; i++){
+    un[i] = new Universe((char *)filename,n_ep,n_st,
+                         (int)n_rep,
+                         identify_failed, target, i2string(i));
+  }
 
-        Results = new double[n_rep];
-        Counters = new int[n_rep];
+  //...............................
+  if(n_rep > 0){
 
-    }else {
+    Results = new double[n_rep];
+    Counters = new int[n_rep];
 
-        Results =  NULL;
-        Counters = NULL;
-        std::cout << " Number of reruns should be positive! " <<  std::endl;
-        return 0;
+  }else {
 
-    }
-    //...............................
-    //srand(time(0));
-    //srandomdev();
+    Results =  NULL;
+    Counters = NULL;
+    std::cout << " Number of reruns should be positive! " <<  std::endl;
+    return 0;
 
-    if ( initSeed != 0.0 ) {
-      srand(initSeed);
-    }
-    else {
-        timeval t;
-        gettimeofday(&t, NULL);
-        srand(t.tv_usec);
-    }
+  }
+  //...............................
+  //srand(time(0));
+  //srandomdev();
 
-    {
-        double r=0;
-        for (int j=0; j<100; j++){
+  if ( initSeed != 0.0 ) {
+    srand(initSeed);
+  }
+  else {
+    timeval t;
+    gettimeofday(&t, NULL);
+    srand(t.tv_usec);
+  }
 
+  {
+    double r=0;
+    for (int j=0; j<100; j++){
 
 
-            r = rand()/(double)(pow(2.,31)-1.);
-            std::cout << r << " ";
-        }
-        std::cout << "\n";
+
+      r = rand()/(double)(pow(2.,31)-1.);
+      std::cout << r << " ";
     }
-  	//random initiation of starting parameters
+    std::cout << "\n";
+  }
+  //random initiation of starting parameters
 
-    if (range > 0.){
+  if (range > 0.){
 
-        for (int i=0; i < 5; i++){
+    for (int i=0; i < 5; i++){
 
-            if (params0[i]==-100.){
+      if (params0[i]==-100.){
 
-                double r1 = (rand()/(double)(pow(2.,31)-1.));
-                double r2 = (rand()/(double)(pow(2.,31)-1.));
-                double sign = 1.;
+        double r1 = (rand()/(double)(pow(2.,31)-1.));
+        double r2 = (rand()/(double)(pow(2.,31)-1.));
+        double sign = 1.;
 
-                if(r1 > 0.5){
-                    sign=-1.;
-                }
-
-                params0[i] = sign*r2*range;
-
-                std::cout << par_names0[i] << ": " << params0[i] <<  std::endl;
-            }
+        if(r1 > 0.5){
+          sign=-1.;
         }
 
+        params0[i] = sign*r2*range;
+
+        std::cout << par_names0[i] << ": " << params0[i] <<  std::endl;
+      }
     }
 
+  }
 
-    double T_start=params2[0], T_end=params2[1], Target_rejection=params2[3], starting_jump=params2[4];
-    int Annealing_repeats = (int) params2[2];
 
-#ifdef P_DISPATCH
-    dispatch_group_t group = dispatch_group_create();
+  double T_start=params2[0], T_end=params2[1], Target_rejection=params2[3], starting_jump=params2[4];
+  int Annealing_repeats = (int) params2[2];
 
-    //.............................
-    multi_annealing(group, un, CustomQueues, T_start, T_end, Target_rejection, Annealing_repeats,
-                    starting_jump, Results, Counters, params0, Annealing_repeats);
+  multi_annealing(       un,                T_start, T_end, Target_rejection, Annealing_repeats,
+                         starting_jump, Results, Counters, params0, Annealing_repeats);
 
-    //dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
-    dispatch_release(group);
-    //.............................
-#else
-    multi_annealing(       un,                T_start, T_end, Target_rejection, Annealing_repeats,
-                    starting_jump, Results, Counters, params0, Annealing_repeats);
-#endif
+  // stop timer
+  gettimeofday(&t2, NULL);
 
+  // compute and print the elapsed time in millisec
+  elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
+  elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms
+  elapsedTime /= 1000.;
+  cout << "\n*** optimizer completed, elapsed time=" << elapsedTime << " seconds " << elapsedTime/60. << " minutes)\n\n";
 
-    // stop timer
-    gettimeofday(&t2, NULL);
+  //.....................
 
-    // compute and print the elapsed time in millisec
-    elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
-    elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms
-    elapsedTime /= 1000.;
-    cout << "\n*** optimizer completed, elapsed time=" << elapsedTime << " seconds " << elapsedTime/60. << " minutes)\n\n";
+  for(int i=0; i<Nworkers; i++){
+    delete un[i];
+  }
 
-    //.....................
+  //....................
+  if(n_rep > 0){
 
-    for(int i=0; i<Nworkers; i++){
-        delete un[i];
-    }
+    delete [] Results;
+    delete [] Counters;
 
-    //....................
-    if(n_rep > 0){
+  }
 
-        delete [] Results;
-        delete [] Counters;
+  return 0;
 
-    }
 
-    return 0;
 
-
-
 }
 




More information about the Swift-commit mailing list