void launch_get_min_recur(void *args) {
    struct get_min_arg_struct *arg_struct = (struct get_min_arg_struct *)args;
    int *cur_path = MY_MALLOC(arg_struct->tot_depth * sizeof(int));
    CHECK_PTR(cur_path, "cur_path could not be allocated");
    
    for (int i = 0; i < arg_struct->tot_depth; i++)
        cur_path[i] = -1;
    
    arg_struct->single_exprs = MY_MALLOC(arg_struct->ncol * arg_struct->nrow);
    CHECK_PTR(arg_struct->single_exprs, "args.single_exprs could not be allocated");
    
    memcpy(arg_struct->single_exprs, arg_struct->exprs, arg_struct->ncol*arg_struct->nrow);

    bool *skip_single = MY_MALLOC(arg_struct->ncol * sizeof(bool));
    memset(skip_single, 0, arg_struct->ncol * sizeof(bool));
    
    if(g_trace >= 2)
        printf("Launching search for (%lf,%lf)\n", arg_struct->num_const, arg_struct->denom_const);
    
    get_min_recur(0, arg_struct->tot_depth, cur_path, arg_struct->exprs, arg_struct->single_exprs, arg_struct->nrow, arg_struct->ncol, arg_struct->w1p, arg_struct->w1m, arg_struct->w2p, arg_struct->w2m, arg_struct->num_const, arg_struct->denom_const, arg_struct->curmin, arg_struct->combi_min_idx, skip_single, arg_struct->active, arg_struct->active_len, arg_struct->mutex);
    
    if(g_trace >= 2)
        printf("Finished search for (%lf,%lf)\n", arg_struct->num_const, arg_struct->denom_const);
    
    MY_FREE(arg_struct->single_exprs);
    MY_FREE(skip_single);
    MY_FREE(cur_path);
}
bool is_idx_in_set(int *cur_path, int tot_depth, int min_idx, int *active, int active_len) {
    int *idxs = MY_MALLOC(tot_depth * sizeof(int));
    CHECK_PTR(idxs, "idxs could not be allocated");
    
    int i, j;
    
    
    for (i = 0; i < tot_depth && cur_path[i] >= 0; i++)
        idxs[i] = cur_path[i];
    idxs[i] = min_idx;
    for (j = i+1; j < tot_depth; j++)
        idxs[j] = -1;
    
    qsort(idxs, i+1, sizeof(int), intcmp);
    
    for(i = 0; i < active_len; i++) {
        for (j = 0; j < tot_depth; j++) {
            if(active[i*tot_depth + j] != idxs[j])
                break;
        }
        if(j >= tot_depth) {
            MY_FREE(idxs);
            return true;
        }
    }
    
    MY_FREE(idxs);
    return false;
}
Beispiel #3
0
static
void
destroy_worker_threads(comp_thread_ctxt_t *threads, uint n)
{
	uint i;

	for (i = 0; i < n; i++) {
		comp_thread_ctxt_t *thd = threads + i;

		pthread_mutex_lock(&thd->data_mutex);
		threads[i].cancelled = TRUE;
		pthread_cond_signal(&thd->data_cond);
		pthread_mutex_unlock(&thd->data_mutex);

		pthread_join(thd->id, NULL);

		pthread_cond_destroy(&thd->data_cond);
		pthread_mutex_destroy(&thd->data_mutex);
		pthread_cond_destroy(&thd->ctrl_cond);
		pthread_mutex_destroy(&thd->ctrl_mutex);

		MY_FREE(thd->to);
	}

	MY_FREE(threads);
}
static int readSuperGraph(p3d_flatSuperGraph* fsg, p3d_rob* robot, xmlNodePtr parent) {
  xmlNodePtr cur = parent, *edgeTab = NULL;
  int nbNodes = 0, nbEdges = 0;
  if (!readGraphInfos(fsg, cur)) {
    printf("Error in graph parse: Can not read the graph infos\n");
    return FALSE;
  }
  //reset the number of node and edges(we increment the graph->nnode at each node addition)
  nbNodes = fsg->nNodes;
  fsg->nNodes = 0;
  nbEdges = fsg->nEdges;
  fsg->nEdges = 0;

  edgeTab = MY_ALLOC(xmlNodePtr, nbNodes);
  for (int i = 0; i < nbNodes; i++) {
    edgeTab[i] = NULL;
  }

  cur = cur->xmlChildrenNode;
  for (;cur != NULL; cur = cur->next) {
    if (!xmlStrcmp(cur->name, xmlCharStrdup("node"))) {
      if (!readXmlNode(fsg, robot, cur, edgeTab)) {
        printf("Error in graph parse: Can not read the node\n");
        for (int i = 0; i < fsg->nNodes; i++) {
          if (edgeTab[i] != NULL) {
            MY_FREE(edgeTab[i], xmlNode, 1);
          }
        }
        return FALSE;
      }
    } else if (xmlStrcmp(cur->name, xmlCharStrdup("text"))) {
      printf("Warning in graph parse: Unknown tag %s\n", (char*)cur->name);
    }
  }
  if (nbNodes != fsg->nNodes) {//compare the nodes numbers
    printf("Error in graph parse: All nodes are not parsed\n");
    for (int i = 0; i < fsg->nNodes; i++) {
      if (edgeTab[i] != NULL) {
        MY_FREE(edgeTab[i], xmlNode, 1);
      }
    }
    return FALSE;
  }
  if (!processXmlEdges(fsg, edgeTab)) {
    printf("Error in graph parse: Can not process nodes Edges\n");
    for (int i = 0; i < fsg->nNodes; i++) {
      if (edgeTab[i] != NULL) {
        MY_FREE(edgeTab[i], xmlNode, 1);
      }
    }
    return FALSE;
  }
  for (int i = 0; i < fsg->nNodes; i++) {
    if (edgeTab[i] != NULL) {
      MY_FREE(edgeTab[i], xmlNode, 1);
    }
  }
  return TRUE;
}
Beispiel #5
0
int
xb_stream_read_done(xb_rstream_t *stream)
{
	MY_FREE(stream->buffer);
	MY_FREE(stream);

	return 0;
}
static void func_releaseDataPointer_multiobject(void *data_pointer) {
	struct MultiObjectDataset *data = data_pointer;
	for (int64_t pos = 0; pos < data->num_objects; ++pos)
		MY_FREE(data->object_array[pos]);
	MY_FREE(data->object_array);
	if (data->free_subdatasets_on_release) {
		for (int64_t i = 0; i < data->num_subdatasets; ++i) {
			mknn_dataset_release(data->subdatasets[i]);
		}
	}
	MY_FREE(data->subdatasets);
	MY_FREE(data);
}
static void validate_frequencies(int64_t *array, int64_t minValueIncluded,
		int64_t maxValueNotIncluded, int64_t numSamples) {
	int64_t interval_size = maxValueNotIncluded - minValueIncluded;
	int64_t *frequencies = MY_MALLOC(interval_size, int64_t);
	for (int64_t i = 0; i < numSamples; ++i) {
		frequencies[array[i] - minValueIncluded]++;
	}
	int64_t expectedFreq = my_math_round_int(
			numSamples / (double) interval_size);
	int64_t expectedFreqDelta = my_math_round_int(expectedFreq * 0.01);
	my_log_info("expected frequency=%"PRIi64" +/- %"PRIi64"\n", expectedFreq,
			expectedFreqDelta);
	int64_t cont_errors = 0;
	for (int64_t i = 0; i < interval_size; ++i) {
		int64_t freq = frequencies[i];
		bool is_ok = (MY_ABS_INT(expectedFreq - freq) <= expectedFreqDelta);
		if (interval_size <= 100) {
			double freq_pct = 100.0 * freq / (double) numSamples;
			my_log_info("%3"PRIi64" =%7"PRIi64" (%1.2lf%%)%s\n",
					i + minValueIncluded, freq, freq_pct, is_ok ? "" : " *");
		}
		if (!is_ok)
			cont_errors++;
	}
	if (cont_errors == 0)
		my_log_info("OK. All frequencies inside range [%"PRIi64",%"PRIi64"]\n",
				expectedFreq - expectedFreqDelta,
				expectedFreq + expectedFreqDelta);
	else
		my_log_info(
				"ERROR. %"PRIi64"/%"PRIi64" frequencies out of range [%"PRIi64",%"PRIi64"]\n",
				cont_errors, interval_size, expectedFreq - expectedFreqDelta,
				expectedFreq + expectedFreqDelta);
	MY_FREE(frequencies);
}
void my_random_testInt(int64_t minValueIncluded, int64_t maxValueNotIncluded,
		int64_t numSamples) {
	my_log_info("\nrandomTestInt\n");
	int64_t *array = MY_MALLOC(numSamples, int64_t);
	my_random_intList(minValueIncluded, maxValueNotIncluded, array, numSamples);
	double actualAvg = my_math_averageIntArray(numSamples, array);
	double expectedAvg = (maxValueNotIncluded - 1 + minValueIncluded) / 2.0;
	char *st = my_newString_double(actualAvg);
	my_log_info("%"PRIi64" random int numbers in [%"PRIi64",%"PRIi64"): %s\n",
			numSamples, minValueIncluded, maxValueNotIncluded, st);
	MY_FREE(st);
	validate_stats(actualAvg, expectedAvg);
	validate_frequencies(array, minValueIncluded, maxValueNotIncluded,
			numSamples);
	MY_FREE(array);
}
Beispiel #9
0
static
int
compress_close(ds_file_t *file)
{
	ds_compress_file_t	*comp_file;
	datasink_t		*dest_ds;
	ds_file_t		*dest_file;

	comp_file = (ds_compress_file_t *) file->ptr;
	dest_ds = comp_file->dest_ds;
	dest_file = comp_file->dest_file;

	/* Write the qpress file trailer */
	dest_ds->write(dest_file, "ENDSENDS", 8);

	/* Supposedly the number of written bytes should be written as a
	"recovery information" in the file trailer, but in reality qpress
	always writes 8 zeros here. Let's do the same */

	write_uint64_le(dest_ds, dest_file, 0);

	dest_ds->close(dest_file);

	MY_FREE(file);

	return 0;
}
/**
 * @brief Delete the node list (private attribute)
 */
void DfsDefaultGraph::deleteNodeList(void){
  p3d_list_node* listNode = NULL;
  for(; _listNode; _listNode = listNode){
    listNode = ((p3d_list_node*)_listNode)->next;
    MY_FREE(_listNode, p3d_list_node, 1);
  }
}
Beispiel #11
0
static
void
compress_deinit(ds_ctxt_t *ctxt)
{
	ds_compress_ctxt_t 	*comp_ctxt;
	ds_ctxt_t		*dest_ctxt;
	ds_ctxt_t		*pipe_ctxt;
	datasink_t		*dest_ds;
	datasink_t		*pipe_ds;

	comp_ctxt = (ds_compress_ctxt_t *) ctxt->ptr;;

	destroy_worker_threads(comp_ctxt->threads, comp_ctxt->nthreads);

	dest_ctxt = comp_ctxt->dest_ctxt;
	dest_ds = dest_ctxt->datasink;

	pipe_ctxt = dest_ctxt->pipe_ctxt;
	pipe_ds = pipe_ctxt->datasink;

	dest_ds->deinit(dest_ctxt);
	pipe_ds->deinit(pipe_ctxt);

	MY_FREE(ctxt);
}
static double priv_calcularValorIndicador(Distance* fd, char *nomIndicador,
		int64_t numSamples, int64_t multiplicadorFase) {
	struct State_Multimetric *es = fd->state_dist;
	double *sample = computeDistanceSample(es->colQuery, es->colReference, fd,
			numSamples * multiplicadorFase, "Q", "R");
	struct MyDataStats stats = my_math_computeStats(numSamples, sample);
	struct MyQuantiles quant = my_math_computeQuantiles(numSamples, sample);
	MY_FREE(sample);
	double indicador = 0;
	if (my_string_equals_ignorecase(nomIndicador, "RHO"))
	indicador = stats.rho;
	else if (my_string_equals_ignorecase(nomIndicador, "VAR"))
	indicador = stats.variance;
	else if (my_string_equals_ignorecase(nomIndicador, "A1"))
	indicador = quant.a1;
	else if (my_string_equals_ignorecase(nomIndicador, "A0.5"))
	indicador = quant.a0_5;
	else if (my_string_equals_ignorecase(nomIndicador, "A0.1"))
	indicador = quant.a0_1;
	else if (my_string_equals_ignorecase(nomIndicador, "A0.01"))
	indicador = quant.a0_01;
	else if (my_string_equals_ignorecase(nomIndicador, "A0.001"))
	indicador = quant.a0_001;
	else if (my_string_equals_ignorecase(nomIndicador, "A0.0001"))
	indicador = quant.a0_0001;
	else if (my_string_equals_ignorecase(nomIndicador, "A0.00001"))
	indicador = quant.a0_00001;
	else
	my_log_error("indicador %s desconocido\n", nomIndicador);
	return indicador;
}
void my_random_intList_noRepetitions(int64_t minValueIncluded,
		int64_t maxValueNotIncluded, int64_t *array, int64_t sample_size) {
	int64_t interval_size = maxValueNotIncluded - minValueIncluded;
	my_assert_greaterInt("random interval", interval_size, 0);
	if (sample_size > interval_size)
		my_log_error(
				"cannot select %"PRIi64" values between %"PRIi64" possible values\n",
				sample_size, interval_size);
	if (sample_size > interval_size / 100) {
		int64_t *ids = my_random_newPermutation(minValueIncluded,
				maxValueNotIncluded);
		memcpy(array, ids, sample_size * sizeof(int64_t));
		MY_FREE(ids);
	} else {
		MY_MUTEX_LOCK(rnd_mutex);
		internal_ensure_seed();
		for (int64_t i = 0; i < sample_size; ++i) {
			array[i] = minValueIncluded + internal_random_int(interval_size);
			for (int64_t j = 0; j < i; ++j) {
				if (array[i] == array[j]) {
					i--;
					break;
				}
			}
		}
		MY_MUTEX_UNLOCK(rnd_mutex);
	}
}
Beispiel #14
0
void p3d_destroy_traj_content(p3d_rob* robotPt, p3d_traj* traj){
  destroy_list_localpath(robotPt, traj->courbePt);
  if(traj->name != NULL) {
    free(traj->name);
  }
  if(traj->file != NULL) {
    free(traj->file);
  }
  MY_FREE(traj,p3d_traj,1);
}
Beispiel #15
0
void p3d_free_proj_point_table(p3d_project_point ** proj_table, int nstep) {
 int i,j;
 for(i=0;i<nstep+1;i++) {
    for (j =0; j<nstep+1; j++) {
      MY_FREE(proj_table[(nstep+1)*i+j], p3d_project_point, 1);
      proj_table[(nstep+1)*i+j] = NULL;
    }
 }
  MY_FREE(proj_table, p3d_project_point*,(nstep+1)*(nstep+1));
}
Beispiel #16
0
void bg_track_info_free(bg_track_info_t * info)
  {
  int i;

  if(info->audio_streams)
    {
    for(i = 0; i < info->num_audio_streams; i++)
      bg_audio_info_free(&info->audio_streams[i]);
    MY_FREE(info->audio_streams);
    }

  if(info->video_streams)
    {
    for(i = 0; i < info->num_video_streams; i++)
      bg_video_info_free(&info->video_streams[i]);
    MY_FREE(info->video_streams);
    }
  if(info->text_streams)
    {
    for(i = 0; i < info->num_text_streams; i++)
      bg_text_info_free(&info->text_streams[i]);
    MY_FREE(info->text_streams);
    }
  if(info->overlay_streams)
    {
    for(i = 0; i < info->num_overlay_streams; i++)
      bg_overlay_info_free(&info->overlay_streams[i]);
    MY_FREE(info->overlay_streams);
    }
  
  gavl_metadata_free(&info->metadata);

  if(info->chapter_list)
    gavl_chapter_list_destroy(info->chapter_list);
  
  MY_FREE(info->url);
  memset(info, 0, sizeof(*info));
  }
Beispiel #17
0
void resetFrameBuffer(int id,char *buffer,int length) 
{
    struct MyFrameBufferQueueData *cursor = frameBufferHead;

    while(cursor != NULL)
    {
        if(cursor->framebuffer->id == id)
        {
            char *framebuffer = cursor->framebuffer->buffer;
            cursor->framebuffer->buffer = buffer;
            cursor->framebuffer->length = length;
            MY_FREE(framebuffer); //may cause error.
            return;
        }
        cursor = cursor->next;
    }
}
static void priv_printIndicator(struct State_Multimetric *es,
		char *nomIndicador, char *st_fase, double valIndicador) {
	if (st_fase != NULL)
	my_log_info("[%s] ", st_fase);
	for (int64_t i = 0; i < es->numDistances; ++i) {
		char *norm = my_newString_double(es->normalization[i]);
		char *pond = my_newString_double(es->fraction[i]);
		if (i > 0)
		my_log_info(" + ");
		my_log_info("%s*%s*%s", es->distances[i]->name, norm, pond);
		MY_FREE_MULTI(norm, pond);
	}
	char *val = my_newString_double(valIndicador);
	if (nomIndicador != NULL)
	my_log_info(" => %s=%s", nomIndicador, val);
	my_log_info("\n");
	MY_FREE(val);
}
static void p3d_addNodeInGraph(void){
  configPt qcurrent = NULL;
  pp3d_rob robotPt;
  p3d_node* current_nodePt;
  p3d_graph* G = NULL;
  double dist;

  robotPt = (p3d_rob*) p3d_get_desc_curid(P3D_ROBOT);
  if(!XYZ_GRAPH) {
    G = p3d_create_graph();
  }else{ 
    G = XYZ_GRAPH;
  }
  qcurrent = p3d_get_robot_config(robotPt);
  current_nodePt = p3d_APInode_make_multisol(G,qcurrent,NULL);
  if(G->start_nodePt== NULL) {
    G->start_nodePt = current_nodePt;
    p3d_insert_node(G,G->start_nodePt);
    p3d_create_compco(G,G->start_nodePt);
    if(G->start_nodePt == NULL){
      PrintInfo(("Probleme with startnode \n"));
    }
  }else{
    if(p3d_APInode_linked(G,G->prev_nodePt,current_nodePt,&dist)) {
      p3d_insert_node(G,current_nodePt);
      p3d_create_edges(G,G->prev_nodePt,current_nodePt,dist);
      p3d_add_node_compco(current_nodePt,G->prev_nodePt->comp, TRUE);
      //current_localpathPt = p3d_local_planner(robotPt, G->prev_nodePt->q, current_nodePt->q);
    }else{
      PrintInfo(("edge would be in collision\n"));
      p3d_destroy_config(robotPt, current_nodePt->q);
      MY_FREE(current_nodePt, p3d_node, 1);
      current_nodePt = NULL;
    }
  }
  if(current_nodePt !=NULL) {
    G->prev_nodePt = current_nodePt;
  }
}
void get_min_recur(int cur_depth, int tot_depth, int *cur_path,
                   char *cur_exprs, char *single_exprs, int nrow, int ncol,
                   double *w1p, double *w1m, double *w2p, double *w2m,
                   double num_const, double denom_const,
                   double *curmin, int *combi_min_idx, bool *skip_single,
                   int *active, int active_len, pthread_mutex_t *mutex) {
        
    
    
    double *a = MY_MALLOC(ncol * sizeof(double));
    CHECK_PTR(a, "a could not be allocated");
    double *b = MY_MALLOC(ncol * sizeof(double));
    CHECK_PTR(b, "b could not be allocated");
    double *c = MY_MALLOC(ncol * sizeof(double));
    CHECK_PTR(c, "c could not be allocated");
    double *d = MY_MALLOC(ncol * sizeof(double));
    CHECK_PTR(d, "d could not be allocated");
    double *gamma = MY_MALLOC(ncol * sizeof(double));
    CHECK_PTR(gamma, "gamma could not be allocated");

    double minval = DBL_MAX;
    int min_idx = -1;

    for (int j = 0; j < ncol; j++) {
        if(skip_single[j])
            continue;

        tot_node_explored++;

        a[j] = 0;
        b[j] = 0;
        c[j] = 0;
        d[j] = 0;
        for (int i = 0; i < nrow; i++) {
            if(cur_exprs[i + j*nrow]) {
                a[j] += w1p[i];
                b[j] += w1m[i];
                c[j] += w2p[i];
                d[j] += w2m[i];
            }
        }
                    
        gamma[j] = (num_const + a[j] - b[j]) / (denom_const + c[j] - d[j]);
        
        if(gamma[j] > EPSILON && gamma[j] < minval && !is_idx_in_set(cur_path, tot_depth, j, active, active_len)) {
            minval = gamma[j];
            min_idx = j;
        }
    }
//    printf("#%.0f | Single skipped: %ld\nskip_single[17375] = %d\n", tot_explored, single_skipped, skip_single[17375]);
    
//    int min_idx = get_pos_min_idx(gamma, ncol, cur_path, tot_depth, active, active_len);
    
    if (min_idx >= 0 && gamma[min_idx] < *curmin) {
        bool is_duplicate = false;
        for(int i = 0; i < cur_depth; i++)
            if(cur_path[i] == min_idx) {
                is_duplicate = true;
                break;
            }
        
        pthread_mutex_lock(mutex);
        if(! is_duplicate && gamma[min_idx] < *curmin) { // Checking again here to avoid race conditions
            
            *curmin = gamma[min_idx];
            for (int i = 0; i < tot_depth; i++)
                combi_min_idx[i] = cur_path[i];
            combi_min_idx[cur_depth] = min_idx;
            
            if(g_trace >= 3) {
                printf("New min: %.3f ", *curmin);
                for (int i = 0; i < tot_depth; i++)
                    printf("[%d]", combi_min_idx[i]);
                printf("\n");
            }
            
        }
        pthread_mutex_unlock(mutex);
    }
    
    
    if(cur_depth+1 < tot_depth) {
        
        
        char *combi_exprs = MY_MALLOC(ncol*nrow);
        CHECK_PTR(combi_exprs, "combi_exprs could not be allocated");
        char *exprs_mask = MY_MALLOC(ncol*nrow);
        if(exprs_mask == NULL) {
            printf("exprs_mask could not be allocated: %d * %d = %d\ncurdepth: %d\n", ncol, nrow, ncol*nrow, cur_depth);
            exit(-1);
        }
        
        clock_t begin=clock();
        
        char null_block [nrow];
        bzero(null_block, nrow);
        
        char *x = MY_MALLOC(nrow);
        int *x_subset = MY_MALLOC(nrow * sizeof(int));
        int *ordered = MY_MALLOC(nrow * sizeof(int));
        int *ranking = MY_MALLOC(nrow * sizeof(int));

        
        for(int j = 0; j < ncol; j++) {
            if(skip_single[j]) {
                easy_pruned++;
                goto skip;
            }

#ifdef USE_HEURISTIC_1
            if((denom_const - d[j] >= 0
                && (((num_const - b[j]) / (denom_const + c[j]) >= *curmin) ||
                    ((num_const + a[j]) / (denom_const - d[j]) <= EPSILON)))
               || (denom_const + c[j] <= 0
                   && (((num_const + a[j]) / (denom_const - d[j]) >= *curmin) ||
                       ((num_const - b[j]) / (denom_const + c[j]) <= EPSILON)))) {
                       
                easy_pruned++;
                goto skip;
            }
#endif
            
            for(int i = 0; i < cur_depth; i++)
                if(cur_path[i] == j)
                    goto skip;

#ifdef USE_HEURISTIC_2

            if(denom_const - d[j] > 0 || denom_const + c[j] < 0) {
                
                bool pos_denom = (denom_const - d[j] > 0);
                double num, denom;
                
                int tot_subset = 0;
                                
                for (int i = 0; i < nrow; i++) {
                    
                    if(cur_exprs[i + j*nrow] > 0) {
                        
                        if(pos_denom) {
                            num = w1p[i] - w1m[i];
                            denom = w2p[i] - w2m[i];
                        }
                        else {
                            num = w1m[i] - w1p[i];
                            denom = w2m[i] - w2p[i];
                        }
                        
                        if((num < 0 && denom >= 0) || (num == 0 && denom > 0))
                            x[i] = 1;
                        else if((num > 0 && denom <= 0) || (num == 0 && denom < 0))
                            x[i] = 0;
                        else if(num == 0 && denom == 0)
                            x[i] = 0;
                        else {
                            x_subset[tot_subset++] = i;
                            
                            if(num < 0 && denom < 0) // both strictly negative -> equiv. to both positives, taking !x afterward
                                x[i] = -2;
                            else // both strictly positive
                                x[i] = -1;
                        }
                    }
                    else
                        x[i] = 0;
                }
                
                double optim_min = MAXFLOAT;
                
                if(tot_subset > 0)  {
                    
                    pthread_mutex_lock(mutex);
                    for (int i = 0; i < tot_subset; i++) {
                        int sub_i = x_subset[i];
                        if(pos_denom)
                            ordered[i] = tot_subset-1-i;
                        else
                            ordered[i] = i;
                        weight_ratios[i] = (w1m[sub_i] - w1p[sub_i])/(w2m[sub_i] - w2p[sub_i]);
                    }
                    qsort(ordered, tot_subset, sizeof(int), order_of_double_cmp);
                    pthread_mutex_unlock(mutex);

                    for (int i = 0; i < tot_subset; i++)
                        ranking[ordered[i]] = i;
                    
                    
                    
                    
                    double optim_min_n_found, optim_min_d_found;
//                    int save_k = 0;
                    
                    for (int i = -1; i <= tot_subset; i++) {
                        int sub_k = 0;
                        optim_min_n_found = num_const;
                        optim_min_d_found = denom_const;
                        
                        for (int k = 0; k < nrow; k++) {
                            if((x[k] > 0) || (x[k] == -1 && ranking[sub_k] <= i) || (x[k] == -2 && ranking[sub_k] > i)) {
                                optim_min_n_found += w1p[k] - w1m[k];
                                optim_min_d_found += w2p[k] - w2m[k];
                            }
                            
                            if(x[k] < 0)
                                sub_k++;
                        }
                        if(optim_min_n_found / optim_min_d_found < optim_min) {
                            optim_min = optim_min_n_found / optim_min_d_found;
//                            save_k = i;
                            if(optim_min < *curmin)
                                break;
                        }
                    }
                    
                }
                else {
                    double optim_min_n = num_const, optim_min_d = denom_const;
                    for (int i = 0; i < nrow; i++) {
                        if(x[i] > 0) {
                            optim_min_n += w1p[i] - w1m[i];
                            optim_min_d += w2p[i] - w2m[i];
                        }
                    }
                    optim_min = optim_min_n/optim_min_d;
                }

                
                if(optim_min >= *curmin) {
                    pruned++;
                    goto skip;
                }
                else
                    not_pruned++;
            }
#endif
            

            if(cur_depth > 0) { //doing breadth first for first level saves time
                for(int k = 0; k < ncol; k++)
                    memcpy(&exprs_mask[k*nrow], &cur_exprs[j*nrow], nrow);
                
                bool non_null = false;
                for (int i = 0; i < nrow*ncol / sizeof(uint64_t); i++) {
                    ((uint64_t *) combi_exprs)[i] = ((uint64_t *) single_exprs)[i] & ((uint64_t *) exprs_mask)[i];
                    non_null |= (((uint64_t *) combi_exprs)[i] != 0);
                }
                for (int i = nrow*ncol - (nrow*ncol % sizeof(uint64_t)); i < nrow*ncol; i++) {
                    combi_exprs[i] = single_exprs[i] & exprs_mask[i];
                    non_null |= (combi_exprs[i] != 0);
                }
                
                if (! non_null) {
                    easy_pruned++;
                    goto skip;
                }

                cur_path[cur_depth] = j;
                get_min_recur(cur_depth+1, tot_depth, cur_path, combi_exprs, single_exprs, nrow, ncol, w1p, w1m, w2p, w2m, num_const, denom_const, curmin, combi_min_idx, skip_single, active, active_len, mutex);
            }
            
            tot_non_leaf_explored++;

            continue;
            
            skip:
            if(cur_depth == 0)
                skip_single[j] = TRUE;
        }
        
        if (cur_depth == 0) {
            for (int j = 0; j < ncol; j++) {
                
                if(skip_single[j])
                    continue;
                
                for(int k = 0; k < ncol; k++)
                    memcpy(&exprs_mask[k*nrow], &cur_exprs[j*nrow], nrow);
                
                bool non_null = false;
                for (int i = 0; i < nrow*ncol / sizeof(uint64_t); i++) {
                    ((uint64_t *) combi_exprs)[i] = ((uint64_t *) single_exprs)[i] & ((uint64_t *) exprs_mask)[i];
                    non_null |= (((uint64_t *) combi_exprs)[i] != 0);
                }
                for (int i = nrow*ncol - (nrow*ncol % sizeof(uint64_t)); i < nrow*ncol; i++) {
                    combi_exprs[i] = single_exprs[i] & exprs_mask[i];
                    non_null |= (combi_exprs[i] != 0);
                }
                
                if (! non_null) {
                    easy_pruned++;
                    continue;
                }

                cur_path[cur_depth] = j;
                get_min_recur(cur_depth+1, tot_depth, cur_path, combi_exprs, single_exprs, nrow, ncol, w1p, w1m, w2p, w2m, num_const, denom_const, curmin, combi_min_idx, skip_single, active, active_len, mutex);

            }
        }
        
        
        cur_path[cur_depth] = -1;
        
        MY_FREE(ordered);
        MY_FREE(ranking);

        MY_FREE(x);
        MY_FREE(x_subset);

        MY_FREE(combi_exprs);
        MY_FREE(exprs_mask);
        
        clock_t end=clock();
        double diff = (end - begin)*1000/CLOCKS_PER_SEC;
        if(tot_non_leaf_explored > 0 && cur_depth < 1) {
            if(g_trace >= 2)
                printf("Explored %.0f non-terminal so far (total: %.2f s.).\n", tot_non_leaf_explored, diff/1000);
        }
    }
    
    MY_FREE(a);
    MY_FREE(b);
    MY_FREE(c);
    MY_FREE(d);
    MY_FREE(gamma);
    
    return;
}
Beispiel #21
0
/*! \brief Destroy a link with a joint.
 *
 *  \param jnt_linkPt: the link to destroy
 */
void p3d_rw_jnt_destroy_joint_link(p3d_read_jnt_link_data * jnt_linkPt)
{
  MY_FREE(jnt_linkPt, p3d_read_jnt_link_data, 1);
}
static void snaketable_index_release(void *state_index) {
	struct SnakeTable_Index *state = state_index;
	MY_FREE(state);
}
Beispiel #23
0
/* +-----------------------------------------------------------------------+ */
/* Subroutine */ void direct_direct_(fp fcn, doublereal *x, integer *n, doublereal *eps, doublereal epsabs, integer *maxf, integer *maxt, double starttime, double maxtime, int *force_stop, doublereal *minf, doublereal *l, 
	doublereal *u, integer *algmethod, integer *ierror, FILE *logfile, 
	doublereal *fglobal, doublereal *fglper, doublereal *volper, 
	doublereal *sigmaper, void *fcn_data)
{
    /* System generated locals */
    integer i__1, i__2;
    doublereal d__1;

    /* changed by SGJ to be dynamically allocated ... would be
       even better to use realloc, below, to grow these as needed */
    integer MAXFUNC = *maxf <= 0 ? 101000 : (*maxf + 1000 + *maxf / 2);
    integer MAXDEEP = *maxt <= 0 ? MAXFUNC/5: *maxt + 1000;
    const integer MAXDIV = 5000;

    /* Local variables */
    integer increase;
    doublereal *c__ = 0	/* was [90000][64] */, *f = 0	/* 
	    was [90000][2] */;
    integer i__, j, *s = 0	/* was [3000][2] */, t;
    doublereal *w = 0;
    doublereal divfactor;
    integer ifeasiblef, iepschange, actmaxdeep;
    integer actdeep_div__, iinfesiblef;
    integer pos1, newtosample;
    integer ifree, help;
    doublereal *oldl = 0, fmax;
    integer maxi;
    doublereal kmax, *oldu = 0;
    integer oops, *list2 = 0	/* was [64][2] */, cheat;
    doublereal delta;
    integer mdeep, *point = 0, start;
    integer *anchor = 0, *length = 0	/* was [90000][64] */, *arrayi = 0;
    doublereal *levels = 0, *thirds = 0;
    integer writed;
    doublereal epsfix;
    integer oldpos, minpos, maxpos, tstart, actdeep, ifreeold, oldmaxf;
    integer numfunc, version;
    integer jones;

    /* FIXME: change sizes dynamically? */
#define MY_ALLOC(p, t, n) p = (t *) malloc(sizeof(t) * (n)); \
                          if (!(p)) { *ierror = -100; goto cleanup; }

    /* Note that I've transposed c__, length, and f relative to the 
       original Fortran code.  e.g. length was length(maxfunc,n) 
       in Fortran [ or actually length(maxfunc, maxdims), but by
       using malloc I can just allocate n ], corresponding to
       length[n][maxfunc] in C, but I've changed the code to access
       it as length[maxfunc][n].  That is, the maxfunc direction
       is the discontiguous one.  This makes it easier to resize
       dynamically (by adding contiguous rows) using realloc, without
       having to move data around manually. */
    MY_ALLOC(c__, doublereal, MAXFUNC * (*n));
    MY_ALLOC(length, integer, MAXFUNC * (*n));
    MY_ALLOC(f, doublereal, MAXFUNC * 2);
    MY_ALLOC(point, integer, MAXFUNC);
    if (*maxf <= 0) *maxf = MAXFUNC - 1000;

    MY_ALLOC(s, integer, MAXDIV * 2);

    MY_ALLOC(anchor, integer, MAXDEEP + 2);
    MY_ALLOC(levels, doublereal, MAXDEEP + 1);
    MY_ALLOC(thirds, doublereal, MAXDEEP + 1);    
    if (*maxt <= 0) *maxt = MAXDEEP;

    MY_ALLOC(w, doublereal, (*n));
    MY_ALLOC(oldl, doublereal, (*n));
    MY_ALLOC(oldu, doublereal, (*n));
    MY_ALLOC(list2, integer, (*n) * 2);
    MY_ALLOC(arrayi, integer, (*n));

/* +-----------------------------------------------------------------------+ */
/* |    SUBROUTINE Direct                                                  | */
/* | On entry                                                              | */
/* |     fcn -- The argument containing the name of the user-supplied      | */
/* |            SUBROUTINE that returns values for the function to be      | */
/* |            minimized.                                                 | */
/* |       n -- The dimension of the problem.                              | */
/* |     eps -- Exceeding value. If eps > 0, we use the same epsilon for   | */
/* |            all iterations. If eps < 0, we use the update formula from | */
/* |            Jones:                                                     | */
/* |               eps = max(1.D-4*abs(minf),epsfix),                      | */
/* |            where epsfix = abs(eps), the absolute value of eps which is| */
/* |            passed to the function.                                    | */
/* |    maxf -- The maximum number of function evaluations.                | */
/* |    maxT -- The maximum number of iterations.                          | */
/* |            Direct stops when either the maximum number of iterations  | */
/* |            is reached or more than maxf function-evalutions were made.| */
/* |       l -- The lower bounds of the hyperbox.                          | */
/* |       u -- The upper bounds of the hyperbox.                          | */
/* |algmethod-- Choose the method, that is either use the original method  | */
/* |            as described by Jones et.al. (0) or use our modification(1)| */
/* | logfile -- File-Handle for the logfile. DIRECT expects this file to be| */
/* |            opened and closed by the user outside of DIRECT. We moved  | */
/* |            this to the outside so the user can add extra information  | */
/* |            to this file before and after the call to DIRECT.          | */
/* | fglobal -- Function value of the global optimum. If this value is not | */
/* |            known (that is, we solve a real problem, not a testproblem)| */
/* |            set this value to -1.D100 and fglper (see below) to 0.D0.  | */
/* |  fglper -- Terminate the optimization when the percent error          | */
/* |                100(f_min - fglobal)/max(1,abs(fglobal)) < fglper.     | */
/* |  volper -- Terminate the optimization when the volume of the          | */
/* |            hyperrectangle S with f(c(S)) = minf is less then volper   | */
/* |            percent of the volume of the original hyperrectangle.      | */
/* |sigmaper -- Terminate the optimization when the measure of the         | */
/* |            hyperrectangle S with f(c(S)) = minf is less then sigmaper.| */
/* |                                                                       | */
/* | User data that is passed through without being changed:               | */
/* |  fcn_data - opaque pointer to any user data                           | */
/* |                                                                       | */
/* | On return                                                             | */
/* |                                                                       | */
/* |       x -- The final point obtained in the optimization process.      | */
/* |            X should be a good approximation to the global minimum     | */
/* |            for the function within the hyper-box.                     | */
/* |                                                                       | */
/* |    minf -- The value of the function at x.                            | */
/* |  Ierror -- Error flag. If Ierror is lower 0, an error has occurred. The| */
/* |            values of Ierror mean                                      | */
/* |            Fatal errors :                                             | */
/* |             -1   u(i) <= l(i) for some i.                             | */
/* |             -2   maxf is too large.                                   | */
/* |             -3   Initialization in DIRpreprc failed.                  | */
/* |             -4   Error in DIRSamplepoints, that is there was an error | */
/* |                  in the creation of the sample points.                | */
/* |             -5   Error in DIRSamplef, that is an error occurred while  | */
/* |                  the function was sampled.                            | */
/* |             -6   Error in DIRDoubleInsert, that is an error occurred   | */
/* |                  DIRECT tried to add all hyperrectangles with the same| */
/* |                  size and function value at the center. Either        | */
/* |                  increase maxdiv or use our modification (Jones = 1). | */
/* |            Termination values :                                       | */
/* |              1   Number of function evaluations done is larger then   | */
/* |                  maxf.                                                | */
/* |              2   Number of iterations is equal to maxT.               | */
/* |              3   The best function value found is within fglper of    | */
/* |                  the (known) global optimum, that is                  | */
/* |                   100(minf - fglobal/max(1,|fglobal|))  < fglper.     | */
/* |                  Note that this termination signal only occurs when   | */
/* |                  the global optimal value is known, that is, a test   | */
/* |                  function is optimized.                               | */
/* |              4   The volume of the hyperrectangle with minf at its    | */
/* |                  center is less than volper percent of the volume of  | */
/* |                  the original hyperrectangle.                         | */
/* |              5   The measure of the hyperrectangle with minf at its   | */
/* |                  center is less than sigmaper.                        | */
/* |                                                                       | */
/* | SUBROUTINEs used :                                                    | */
/* |                                                                       | */
/* | DIRheader, DIRInitSpecific, DIRInitList, DIRpreprc, DIRInit, DIRChoose| */
/* | DIRDoubleInsert, DIRGet_I, DIRSamplepoints, DIRSamplef, DIRDivide     | */
/* | DIRInsertList, DIRreplaceInf, DIRWritehistbox, DIRsummary, Findareas  | */
/* |                                                                       | */
/* | Functions used :                                                      | */
/* |                                                                       | */
/* | DIRgetMaxdeep, DIRgetlevel                                            | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | Parameters                                                            | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | The maximum of function evaluations allowed.                          | */
/* | The maximum dept of the algorithm.                                    | */
/* | The maximum number of divisions allowed.                              | */
/* | The maximal dimension of the problem.                                 | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | Global Variables.                                                     | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | EXTERNAL Variables.                                                   | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | User Variables.                                                       | */
/* | These can be used to pass user defined data to the function to be     | */
/* | optimized.                                                            | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | Place to define, if needed, some application-specific variables.      | */
/* | Note: You should try to use the arrays defined above for this.        | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | End of application - specific variables !                             | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | Internal variables :                                                  | */
/* |       f -- values of functions.                                       | */
/* |divfactor-- Factor used for termination with known global minimum.     | */
/* |  anchor -- anchors of lists with deepness i, -1 is anchor for list of | */
/* |            NaN - values.                                              | */
/* |       S -- List of potentially optimal points.                        | */
/* |   point -- lists                                                      | */
/* |    ifree -- first free position                                        | */
/* |       c -- midpoints of arrays                                        | */
/* |  thirds -- Precalculated values of 1/3^i.                             | */
/* |  levels -- Length of intervals.                                       | */
/* |  length -- Length of intervall (index)                                | */
/* |       t -- actual iteration                                           | */
/* |       j -- loop-variable                                              | */
/* | actdeep -- the actual minimal interval-length index                   | */
/* |  Minpos -- position of the actual minimum                             | */
/* |    file -- The filehandle for a datafile.                             | */
/* |  maxpos -- The number of intervalls, which are truncated.             | */
/* |    help -- A help variable.                                           | */
/* | numfunc -- The actual number of function evaluations.                 | */
/* |   file2 -- The filehandle for an other datafile.                      | */
/* |  ArrayI -- Array with the indexes of the sides with maximum length.   | */
/* |    maxi -- Number of directions with maximal side length.             | */
/* |    oops -- Flag which shows if anything went wrong in the             | */
/* |            initialisation.                                            | */
/* |   cheat -- Obsolete. If equal 1, we don't allow Ktilde > kmax.        | */
/* |  writed -- If writed=1, store final division to plot with Matlab.     | */
/* |   List2 -- List of indicies of intervalls, which are to be truncated. | */
/* |       i -- Another loop-variable.                                     | */
/* |actmaxdeep-- The actual maximum (minimum) of possible Interval length. | */
/* |  oldpos -- The old index of the minimum. Used to print only, if there | */
/* |            is a new minimum found.                                    | */
/* |  tstart -- The start of the outer loop.                               | */
/* |   start -- The postion of the starting point in the inner loop.       | */
/* | Newtosample -- The total number of points to sample in the inner loop.| */
/* |       w -- Array used to divide the intervalls                        | */
/* |    kmax -- Obsolete. If cheat = 1, Ktilde was not allowed to be larger| */
/* |            than kmax. If Ktilde > kmax, we set ktilde = kmax.         | */
/* |   delta -- The distance to new points from center of old hyperrec.    | */
/* |    pos1 -- Help variable used as an index.                            | */
/* | version -- Store the version number of DIRECT.                        | */
/* | oldmaxf -- Store the original function budget.                        | */
/* |increase -- Flag used to keep track if function budget was increased   | */
/* |            because no feasible point was found.                       | */
/* | ifreeold -- Keep track which index was free before. Used with          | */
/* |            SUBROUTINE DIRReplaceInf.                                  | */
/* |actdeep_div-- Keep track of the current depths for divisions.          | */
/* |    oldl -- Array used to store the original bounds of the domain.     | */
/* |    oldu -- Array used to store the original bounds of the domain.     | */
/* |  epsfix -- If eps < 0, we use Jones update formula. epsfix stores the | */
/* |            absolute value of epsilon.                                 | */
/* |iepschange-- flag iepschange to store if epsilon stays fixed or is     | */
/* |             changed.                                                  | */
/* |DIRgetMaxdeep-- Function to calculate the level of a hyperrectangle.   | */
/* |DIRgetlevel-- Function to calculate the level and stage of a hyperrec. | */
/* |    fmax -- Keep track of the maximum value of the function found.     | */
/* |Ifeasiblef-- Keep track if a feasible point has  been found so far.    | */
/* |             Ifeasiblef = 0 means a feasible point has been found,     | */
/* |             Ifeasiblef = 1 no feasible point has been found.          | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | JG 09/25/00 Version counter.                                          | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | JG 09/24/00 Add another actdeep to keep track of the current depths   | */
/* |             for divisions.                                            | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* |JG 01/13/01 Added epsfix for epsilon update. If eps < 0, we use Jones  | */
/* |            update formula. epsfix stores the absolute value of epsilon| */
/* |            then. Also added flag iepschange to store if epsilon stays | */
/* |            fixed or is changed.                                       | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | JG 01/22/01 fmax is used to keep track of the maximum value found.    | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | JG 01/22/01 Ifeasiblef is used to keep track if a feasible point has  | */
/* |             been found so far. Ifeasiblef = 0 means a feasible point  | */
/* |             has been found, Ifeasiblef = 1 if not.                    | */
/* | JG 03/09/01 IInfeasible is used to keep track if an infeasible point  | */
/* |             has been found. IInfeasible > 0 means a infeasible point  | */
/* |             has been found, IInfeasible = 0 if not.                   | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* |                            Start of code.                             | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
    /* Parameter adjustments */
    --u;
    --l;
    --x;

    /* Function Body */
    writed = 0;
    jones = *algmethod;
/* +-----------------------------------------------------------------------+ */
/* | Save the upper and lower bounds.                                      | */
/* +-----------------------------------------------------------------------+ */
    i__1 = *n;
    for (i__ = 1; i__ <= i__1; ++i__) {
	oldu[i__ - 1] = u[i__];
	oldl[i__ - 1] = l[i__];
/* L150: */
    }
/* +-----------------------------------------------------------------------+ */
/* | Set version.                                                          | */
/* +-----------------------------------------------------------------------+ */
    version = 204;
/* +-----------------------------------------------------------------------+ */
/* | Set parameters.                                                       | */
/* |    If cheat > 0, we do not allow \tilde{K} to be larger than kmax, and| */
/* |    set \tilde{K} to set value if necessary. Not used anymore.         | */
/* +-----------------------------------------------------------------------+ */
    cheat = 0;
    kmax = 1e10;
    mdeep = MAXDEEP;
/* +-----------------------------------------------------------------------+ */
/* | Write the header of the logfile.                                      | */
/* +-----------------------------------------------------------------------+ */
    direct_dirheader_(logfile, &version, &x[1], n, eps, maxf, maxt, &l[1], &u[1], 
	    algmethod, &MAXFUNC, &MAXDEEP, fglobal, fglper, ierror, &epsfix, &
		      iepschange, volper, sigmaper);
/* +-----------------------------------------------------------------------+ */
/* | If an error has occurred while writing the header (we do some checking | */
/* | of variables there), return to the main program.                      | */
/* +-----------------------------------------------------------------------+ */
    if (*ierror < 0) {
	goto cleanup;
    }
/* +-----------------------------------------------------------------------+ */
/* | If the known global minimum is equal 0, we cannot divide by it.       | */
/* | Therefore we set it to 1. If not, we set the divisionfactor to the    | */
/* | absolute value of the global minimum.                                 | */
/* +-----------------------------------------------------------------------+ */
    if (*fglobal == 0.) {
	divfactor = 1.;
    } else {
	divfactor = fabs(*fglobal);
    }
/* +-----------------------------------------------------------------------+ */
/* | Save the budget given by the user. The variable maxf will be changed  | */
/* | if in the beginning no feasible points are found.                     | */
/* +-----------------------------------------------------------------------+ */
    oldmaxf = *maxf;
    increase = 0;
/* +-----------------------------------------------------------------------+ */
/* | Initialiase the lists.                                                | */
/* +-----------------------------------------------------------------------+ */
    direct_dirinitlist_(anchor, &ifree, point, f, &MAXFUNC, &MAXDEEP);
/* +-----------------------------------------------------------------------+ */
/* | Call the routine to initialise the mapping of x from the n-dimensional| */
/* | unit cube to the hypercube given by u and l. If an error occurred,     | */
/* | give out a error message and return to the main program with the error| */
/* | flag set.                                                             | */
/* | JG 07/16/01 Changed call to remove unused data.                       | */
/* +-----------------------------------------------------------------------+ */
    direct_dirpreprc_(&u[1], &l[1], n, &l[1], &u[1], &oops);
    if (oops > 0) {
	if (logfile)
	     fprintf(logfile,"WARNING: Initialization in DIRpreprc failed.\n");
	*ierror = -3;
	goto cleanup;
    }
    tstart = 2;
/* +-----------------------------------------------------------------------+ */
/* | Initialise the algorithm DIRECT.                                      | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | Added variable to keep track of the maximum value found.              | */
/* +-----------------------------------------------------------------------+ */
    direct_dirinit_(f, fcn, c__, length, &actdeep, point, anchor, &ifree,
	    logfile, arrayi, &maxi, list2, w, &x[1], &l[1], &u[1], 
	    minf, &minpos, thirds, levels, &MAXFUNC, &MAXDEEP, n, n, &
	    fmax, &ifeasiblef, &iinfesiblef, ierror, fcn_data, jones,
		    starttime, maxtime, force_stop);
/* +-----------------------------------------------------------------------+ */
/* | Added error checking.                                                 | */
/* +-----------------------------------------------------------------------+ */
    if (*ierror < 0) {
	if (*ierror == -4) {
	    if (logfile)
		 fprintf(logfile, "WARNING: Error occurred in routine DIRsamplepoints.\n");
	    goto cleanup;
	}
	if (*ierror == -5) {
	    if (logfile)
		 fprintf(logfile, "WARNING: Error occurred in routine DIRsamplef..\n");
	    goto cleanup;
	}
	if (*ierror == -102) goto L100;
    }
    else if (*ierror == DIRECT_MAXTIME_EXCEEDED) goto L100;
    numfunc = maxi + 1 + maxi;
    actmaxdeep = 1;
    oldpos = 0;
    tstart = 2;
/* +-----------------------------------------------------------------------+ */
/* | If no feasible point has been found, give out the iteration, the      | */
/* | number of function evaluations and a warning. Otherwise, give out     | */
/* | the iteration, the number of function evaluations done and minf.      | */
/* +-----------------------------------------------------------------------+ */
    if (ifeasiblef > 0) {
	 if (logfile)
	      fprintf(logfile, "No feasible point found in %d iterations "
		      "and %d function evaluations.\n", tstart-1, numfunc);
    } else {
	 if (logfile)
	      fprintf(logfile, "%d, %d, %g, %g\n", 
		      tstart-1, numfunc, *minf, fmax);
    }
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | Main loop!                                                            | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
    i__1 = *maxt;
    for (t = tstart; t <= i__1; ++t) {
/* +-----------------------------------------------------------------------+ */
/* | Choose the sample points. The indices of the sample points are stored | */
/* | in the list S.                                                        | */
/* +-----------------------------------------------------------------------+ */
	actdeep = actmaxdeep;
	direct_dirchoose_(anchor, s, &MAXDEEP, f, minf, *eps, epsabs, levels, &maxpos, length, 
		&MAXFUNC, &MAXDEEP, &MAXDIV, n, logfile, &cheat, &
		kmax, &ifeasiblef, jones);
/* +-----------------------------------------------------------------------+ */
/* | Add other hyperrectangles to S, which have the same level and the same| */
/* | function value at the center as the ones found above (that are stored | */
/* | in S). This is only done if we use the original DIRECT algorithm.     | */
/* | JG 07/16/01 Added Errorflag.                                          | */
/* +-----------------------------------------------------------------------+ */
	if (*algmethod == 0) {
	     direct_dirdoubleinsert_(anchor, s, &maxpos, point, f, &MAXDEEP, &MAXFUNC,
		     &MAXDIV, ierror);
	    if (*ierror == -6) {
		if (logfile)
		     fprintf(logfile,
"WARNING: Capacity of array S in DIRDoubleInsert reached. Increase maxdiv.\n"
"This means that there are a lot of hyperrectangles with the same function\n"
"value at the center. We suggest to use our modification instead (Jones = 1)\n"
			  );
		goto cleanup;
	    }
	}
	oldpos = minpos;
/* +-----------------------------------------------------------------------+ */
/* | Initialise the number of sample points in this outer loop.            | */
/* +-----------------------------------------------------------------------+ */
	newtosample = 0;
	i__2 = maxpos;
	for (j = 1; j <= i__2; ++j) {
	    actdeep = s[j + MAXDIV-1];
/* +-----------------------------------------------------------------------+ */
/* | If the actual index is a point to sample, do it.                      | */
/* +-----------------------------------------------------------------------+ */
	    if (s[j - 1] > 0) {
/* +-----------------------------------------------------------------------+ */
/* | JG 09/24/00 Calculate the value delta used for sampling points.       | */
/* +-----------------------------------------------------------------------+ */
		actdeep_div__ = direct_dirgetmaxdeep_(&s[j - 1], length, &MAXFUNC, 
			n);
		delta = thirds[actdeep_div__ + 1];
		actdeep = s[j + MAXDIV-1];
/* +-----------------------------------------------------------------------+ */
/* | If the current dept of division is only one under the maximal allowed | */
/* | dept, stop the computation.                                           | */
/* +-----------------------------------------------------------------------+ */
		if (actdeep + 1 >= mdeep) {
		    if (logfile)
			 fprintf(logfile, "WARNING: Maximum number of levels reached. Increase maxdeep.\n");
		    *ierror = -6;
		    goto L100;
		}
		actmaxdeep = MAX(actdeep,actmaxdeep);
		help = s[j - 1];
		if (! (anchor[actdeep + 1] == help)) {
		    pos1 = anchor[actdeep + 1];
		    while(! (point[pos1 - 1] == help)) {
			pos1 = point[pos1 - 1];
		    }
		    point[pos1 - 1] = point[help - 1];
		} else {
		    anchor[actdeep + 1] = point[help - 1];
		}
		if (actdeep < 0) {
		    actdeep = (integer) f[(help << 1) - 2];
		}
/* +-----------------------------------------------------------------------+ */
/* | Get the Directions in which to decrease the intervall-length.         | */
/* +-----------------------------------------------------------------------+ */
		direct_dirget_i__(length, &help, arrayi, &maxi, n, &MAXFUNC);
/* +-----------------------------------------------------------------------+ */
/* | Sample the function. To do this, we first calculate the points where  | */
/* | we need to sample the function. After checking for errors, we then do | */
/* | the actual evaluation of the function, again followed by checking for | */
/* | errors.                                                               | */
/* +-----------------------------------------------------------------------+ */
		direct_dirsamplepoints_(c__, arrayi, &delta, &help, &start, length, 
			logfile, f, &ifree, &maxi, point, &x[
			1], &l[1], minf, &minpos, &u[1], n, &MAXFUNC, &
			MAXDEEP, &oops);
		if (oops > 0) {
		    if (logfile)
			 fprintf(logfile, "WARNING: Error occurred in routine DIRsamplepoints.\n");
		    *ierror = -4;
		    goto cleanup;
		}
		newtosample += maxi;
/* +-----------------------------------------------------------------------+ */
/* | JG 01/22/01 Added variable to keep track of the maximum value found.  | */
/* +-----------------------------------------------------------------------+ */
		direct_dirsamplef_(c__, arrayi, &delta, &help, &start, length,
			    logfile, f, &ifree, &maxi, point, fcn, &x[
			1], &l[1], minf, &minpos, &u[1], n, &MAXFUNC, &
			MAXDEEP, &oops, &fmax, &ifeasiblef, &iinfesiblef, 
				   fcn_data, force_stop);
		if (force_stop && *force_stop) {
		     *ierror = -102;
		     goto L100;
		}
		if (nlopt_stop_time_(starttime, maxtime)) {
		     *ierror = DIRECT_MAXTIME_EXCEEDED;
		     goto L100;
		}
		if (oops > 0) {
		    if (logfile)
			 fprintf(logfile, "WARNING: Error occurred in routine DIRsamplef.\n");
		    *ierror = -5;
		    goto cleanup;
		}
/* +-----------------------------------------------------------------------+ */
/* | Divide the intervalls.                                                | */
/* +-----------------------------------------------------------------------+ */
		direct_dirdivide_(&start, &actdeep_div__, length, point, arrayi, &
			help, list2, w, &maxi, f, &MAXFUNC, &MAXDEEP, n);
/* +-----------------------------------------------------------------------+ */
/* | Insert the new intervalls into the list (sorted).                     | */
/* +-----------------------------------------------------------------------+ */
		direct_dirinsertlist_(&start, anchor, point, f, &maxi, length, &
			MAXFUNC, &MAXDEEP, n, &help, jones);
/* +-----------------------------------------------------------------------+ */
/* | Increase the number of function evaluations.                          | */
/* +-----------------------------------------------------------------------+ */
		numfunc = numfunc + maxi + maxi;
	    }
/* +-----------------------------------------------------------------------+ */
/* | End of main loop.                                                     | */
/* +-----------------------------------------------------------------------+ */
/* L20: */
	}
/* +-----------------------------------------------------------------------+ */
/* | If there is a new minimum, show the actual iteration, the number of   | */
/* | function evaluations, the minimum value of f (so far) and the position| */
/* | in the array.                                                         | */
/* +-----------------------------------------------------------------------+ */
	if (oldpos < minpos) {
	    if (logfile)
		 fprintf(logfile, "%d, %d, %g, %g\n",
			 t, numfunc, *minf, fmax);
	}
/* +-----------------------------------------------------------------------+ */
/* | If no feasible point has been found, give out the iteration, the      | */
/* | number of function evaluations and a warning.                         | */
/* +-----------------------------------------------------------------------+ */
	if (ifeasiblef > 0) {
	    if (logfile)
		 fprintf(logfile, "No feasible point found in %d iterations "
			 "and %d function evaluations\n", t, numfunc);
	}
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* |                       Termination Checks                              | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | JG 01/22/01 Calculate the index for the hyperrectangle at which       | */
/* |             minf is assumed. We then calculate the volume of this     | */
/* |             hyperrectangle and store it in delta. This delta can be   | */
/* |             used to stop DIRECT once the volume is below a certain    | */
/* |             percentage of the original volume. Since the original     | */
/* |             is 1 (scaled), we can stop once delta is below a certain  | */
/* |             percentage, given by volper.                              | */
/* +-----------------------------------------------------------------------+ */
	*ierror = jones;
	jones = 0;
	actdeep_div__ = direct_dirgetlevel_(&minpos, length, &MAXFUNC, n, jones);
	jones = *ierror;
/* +-----------------------------------------------------------------------+ */
/* | JG 07/16/01 Use precalculated values to calculate volume.             | */
/* +-----------------------------------------------------------------------+ */
	delta = thirds[actdeep_div__] * 100;
	if (delta <= *volper) {
	    *ierror = 4;
	    if (logfile)
		 fprintf(logfile, "DIRECT stopped: Volume of S_min is "
			 "%g%% < %g%% of the original volume.\n",
			 delta, *volper);
	    goto L100;
	}
/* +-----------------------------------------------------------------------+ */
/* | JG 01/23/01 Calculate the measure for the hyperrectangle at which     | */
/* |             minf is assumed. If this measure is smaller then sigmaper,| */
/* |             we stop DIRECT.                                           | */
/* +-----------------------------------------------------------------------+ */
	actdeep_div__ = direct_dirgetlevel_(&minpos, length, &MAXFUNC, n, jones);
	delta = levels[actdeep_div__];
	if (delta <= *sigmaper) {
	    *ierror = 5;
	    if (logfile)
		 fprintf(logfile, "DIRECT stopped: Measure of S_min "
			 "= %g < %g.\n", delta, *sigmaper);
	    goto L100;
	}
/* +-----------------------------------------------------------------------+ */
/* | If the best found function value is within fglper of the (known)      | */
/* | global minimum value, terminate. This only makes sense if this optimal| */
/* | value is known, that is, in test problems.                            | */
/* +-----------------------------------------------------------------------+ */
	if ((*minf - *fglobal) * 100 / divfactor <= *fglper) {
	    *ierror = 3;
	    if (logfile)
		 fprintf(logfile, "DIRECT stopped: minf within fglper of global minimum.\n");
	    goto L100;
	}
/* +-----------------------------------------------------------------------+ */
/* | Find out if there are infeasible points which are near feasible ones. | */
/* | If this is the case, replace the function value at the center of the  | */
/* | hyper rectangle by the lowest function value of a nearby function.    | */
/* | If no infeasible points exist (IInfesiblef = 0), skip this.           | */
/* +-----------------------------------------------------------------------+ */
	if (iinfesiblef > 0) {
	     direct_dirreplaceinf_(&ifree, &ifreeold, f, c__, thirds, length, anchor, 
		    point, &u[1], &l[1], &MAXFUNC, &MAXDEEP, n, n, 
		    logfile, &fmax, jones);
	}
	ifreeold = ifree;
/* +-----------------------------------------------------------------------+ */
/* | If iepschange = 1, we use the epsilon change formula from Jones.      | */
/* +-----------------------------------------------------------------------+ */
	if (iepschange == 1) {
/* Computing MAX */
	    d__1 = fabs(*minf) * 1e-4;
	    *eps = MAX(d__1,epsfix);
	}
/* +-----------------------------------------------------------------------+ */
/* | If no feasible point has been found yet, set the maximum number of    | */
/* | function evaluations to the number of evaluations already done plus   | */
/* | the budget given by the user.                                         | */
/* | If the budget has already be increased, increase it again. If a       | */
/* | feasible point has been found, remark that and reset flag. No further | */
/* | increase is needed.                                                   | */
/* +-----------------------------------------------------------------------+ */
	if (increase == 1) {
	    *maxf = numfunc + oldmaxf;
	    if (ifeasiblef == 0) {
		if (logfile)
		     fprintf(logfile, "DIRECT found a feasible point.  The "
			     "adjusted budget is now set to %d.\n", *maxf);
		increase = 0;
	    }
	}
/* +-----------------------------------------------------------------------+ */
/* | Check if the number of function evaluations done is larger than the   | */
/* | allocated budget. If this is the case, check if a feasible point was  | */
/* | found. If this is a case, terminate. If no feasible point was found,  | */
/* | increase the budget and set flag increase.                            | */
/* +-----------------------------------------------------------------------+ */
	if (numfunc > *maxf) {
	    if (ifeasiblef == 0) {
		*ierror = 1;
		if (logfile)
		     fprintf(logfile, "DIRECT stopped: numfunc >= maxf.\n");
		goto L100;
	    } else {
		increase = 1;
		if (logfile)
                     fprintf(logfile, 
"DIRECT could not find a feasible point after %d function evaluations.\n"
"DIRECT continues until a feasible point is found.\n", numfunc);
		*maxf = numfunc + oldmaxf;
	    }
	}
/* L10: */
    }
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | End of main loop.                                                     | */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* +-----------------------------------------------------------------------+ */
/* | The algorithm stopped after maxT iterations.                          | */
/* +-----------------------------------------------------------------------+ */
    *ierror = 2;
    if (logfile)
	 fprintf(logfile, "DIRECT stopped: maxT iterations.\n");

L100:
/* +-----------------------------------------------------------------------+ */
/* | Store the position of the minimum in x.                               | */
/* +-----------------------------------------------------------------------+ */
    i__1 = *n;
    for (i__ = 1; i__ <= i__1; ++i__) {
	x[i__] = c__[i__ + minpos * i__1 - i__1-1] * l[i__] + l[i__] * u[i__];
	u[i__] = oldu[i__ - 1];
	l[i__] = oldl[i__ - 1];
/* L50: */
    }
/* +-----------------------------------------------------------------------+ */
/* | Store the number of function evaluations in maxf.                     | */
/* +-----------------------------------------------------------------------+ */
    *maxf = numfunc;
/* +-----------------------------------------------------------------------+ */
/* | Give out a summary of the run.                                        | */
/* +-----------------------------------------------------------------------+ */
    direct_dirsummary_(logfile, &x[1], &l[1], &u[1], n, minf, fglobal, &numfunc, 
	    ierror);
/* +-----------------------------------------------------------------------+ */
/* | Format statements.                                                    | */
/* +-----------------------------------------------------------------------+ */

 cleanup:
#define MY_FREE(p) if (p) free(p)
    MY_FREE(c__);
    MY_FREE(f);
    MY_FREE(s);
    MY_FREE(w);
    MY_FREE(oldl);
    MY_FREE(oldu);
    MY_FREE(list2);
    MY_FREE(point);
    MY_FREE(anchor);
    MY_FREE(length);
    MY_FREE(arrayi);
    MY_FREE(levels);
    MY_FREE(thirds);
} /* direct_ */
char *solve_it(char *inputData)
{
   pynum_t *values;
   pynum_t *weights;


   /* Parse the first line */
   char *line = strtok(inputData, "\r\n");

   if (line == nullptr) {
      puts("ERROR: input file malformed");
      return nullptr;
   }

   char *pSpace;

   const int numItems = strtoul(line, &pSpace, 10);
   const pynum_t capacity = strtoul(pSpace, nullptr, 10);
   line = strtok(nullptr, "\r\n");

   values = (pynum_t *)MY_MALLOC(sizeof(pynum_t)*numItems);
   weights = (pynum_t *)MY_MALLOC(sizeof(pynum_t)*numItems);
   
   /* Parse the rest of the data */
   int itemNum = 0;
   while(line != nullptr) {
      values[itemNum] = strtoul(line, &pSpace, 10);
      weights[itemNum] = strtoul(pSpace, nullptr, 10);

      ++itemNum;
      line = strtok(nullptr, "\r\n");
   }
  
   pynum_t rows = capacity + 1;
   pynum_t cols = numItems + 1;

   puts("Initializing table...");

   pynum_t *table = (pynum_t *)MY_MALLOC(sizeof(pynum_t) * rows * cols);
      
   /* Zero out the first row and colum */
   for (pynum_t col = 0; col < cols; ++col) {
      TBL_VAL(0, col) = 0;
   }

   for (pynum_t row = 0; row < rows; ++row) {
      TBL_VAL(row, 0) = 0;
   }

   puts("Done initializing table...\n");

   /* Build the table */
   puts("Building Table...");
   for (pynum_t col = 1; col < cols; ++col) {
      for (pynum_t row = 1; row < rows; ++row) {
         TBL_VAL(row, col) = 
            weights[col-1] <= row ?
               max(TBL_VAL(row, col-1), values[col-1] + TBL_VAL(row - weights[col-1], col-1)) :
               TBL_VAL(row, col-1);
      }
   }
   puts("Done building table.\n");
   

   //puts("Table:");
   //for (pynum_t row = 0; row < rows; ++row) {
   //   fputs("|", stdout);
   //   for (pynum_t col = 0; col < cols-1; ++col) {
   //      printf("%llu, ", TBL_VAL(row, col));
   //   }
   //   printf("%llu", TBL_VAL(row, cols-1));
   //   fputs("|\n", stdout);
   //}
   
   puts("\nTracking backward...");
   pynum_t weightRem = capacity;
   itemNum = (int)(numItems-1);
   while (itemNum >= 0) {
      if (TBL_VAL(weightRem, itemNum) != TBL_VAL(weightRem, itemNum+1)) {
         values[itemNum] = 1;
         weightRem -= weights[itemNum];
      } else {
         values[itemNum] = 0;
      }

      // printf("\tAssigning item %llu = %llu\n", itemNum, values[itemNum]);
      --itemNum;
   }
   puts("Done tracking backward.\n");

   /* Build the solution string.  
      Remember that the 'taken' value for each item is stored in values.
      Estimate the string length based on a generous guess
   */

   char *retString = (char *)MY_MALLOC(sizeof(char) * (100 + 100*numItems));

   if (retString == nullptr) {
      puts("ERROR: Couldn't allocate return string.");
      return nullptr; 
   }

   puts("Writing solution string...");
   int written = sprintf(retString, "%llu 1\n", TBL_VAL(rows-1, cols-1));
   
   for (itemNum = 0; itemNum < numItems; ++itemNum) {
      written += sprintf((retString+written), "%llu ", values[itemNum]);
   }
   retString[written] = '\0';
   puts("Done writing solution string...\n");

   MY_FREE(weights);
   MY_FREE(values);
   MY_FREE(table);
   return retString;
}
Beispiel #25
0
int main (void)
{
// Sync with the monitor.
	mk_mon_sync();
	// Enable stack checking.
	start_stack_check();
	
	/* 2. Benchmarking stuff (to measure usage of communication memory) */
	{
	    bench_mark_fill_pattern_to_cmem();
	}
	/* End of Benchmarking stuff before starting decoding */
	
	/* 2. Only benchmark related shared variables, (also includes variables for receiving start and sending stop signal) */
	volatile unsigned int *mb2_end = (unsigned int*)(mb2_cmemout0_BASEADDR + mb2_cmemout0_SIZE - 2*sizeof(unsigned int));
	volatile unsigned int *mb2_start = (unsigned int*)(mb2_cmemin0_BASEADDR + mb2_cmemin0_SIZE - sizeof(unsigned int));	
	int num_of_dma = 0; 
	/* End of sync variables */
	
	mk_mon_debug_info(2);
	
	/* 3. Wait for start signal from MB1 */
	*mb2_start = 0;
	while(*((volatile int*)mb2_start) != 1);
	
	mk_mon_debug_info(2);
	
	/* 4. All code pertaining to jpeg decoder below this line */
	{
	
	   /* Call your application function here */   
	   //core2_function();
	   int *aa,*ch;
	   MY_MK_MALLOC(ch,int,1);
	   MY_MK_MALLOC(aa,int,1);
	   //*ch = (int*) mk_malloc(10);
	   
	   MY_FREE(ch);
	   MY_FREE(aa);
	
	}
	/* End of the jpeg decoder function -*"No code pertaining to decoder beyond this line apart from sending end of job flags to MB1 and benchmarking stuff "*- */
	
	
	/* 5. Signal MB1 that work is finished in MB2 */
	*mb2_end = 1; 
	DMA_SEND_BLOCKING((unsigned int*)(mb1_cmemin0_pt_REMOTEADDR + mb1_cmemin0_SIZE - 2*sizeof(unsigned int)), mb2_end, 1, (void *)(mb2_dma0_BASEADDR),DMA_flag); //core2 finish flag
    
	/* 11. Code to compute number of DMA channels used in MB1 */
	switch(DMA_flag)
	{
	   case(0X00) : num_of_dma = 0; break;
	   case(0X0F) : num_of_dma = 1; break;
	   case(0XF0) : num_of_dma = 1; break;
	   case(0XFF) : num_of_dma = 2; break;
	   default: num_of_dma = -1;
	}
	
	/* 6. Benchmarking display code starts here */ 
	mk_mon_error(0XB2, num_of_dma);  // Displays the total number of DMA send and receive calls performed in MB2
	mk_mon_error(0XB3, bench_mark_measure_cmem_usage()); // Displays the size of communication memory used by MB2
	mk_mon_error(0XB4, bench_dyna_mem_size); // Displays the size of dynamic memory used by MB2
	
	mk_mon_debug_tile_finished();
	return 0;
}
void get_min_itemset(int *_tot_depth, int *exprs_col_major, int *_nrow, int *_ncol, double *w1, double *w2, int *active, int *_active_len, double *_lambda, double *curmin, int *min_idxs, int *trace) {
    
    g_trace = *trace;
    
    int tot_depth = *_tot_depth,
    nrow = *_nrow,
    ncol = *_ncol,
    active_len = *_active_len;
    double lambda = *_lambda;
    
    // printf("testing input:\ntot_depth: %d\nnrow: %d\nncol: %d\nw1: %.10f\nw2: %.10f\nactive: ", tot_depth, nrow, ncol, w1[0], w2[0]);
    //     printf("##DEBUG: active set: ");
    //     for(int i=(active_len-1) * tot_depth; i < active_len * tot_depth; i++)
    //        printf("%d ", active[i]);
    //    printf("\n\n");
    // printf("\n");
    // printf("\nlambda: %.4f\ncurmin: %.4f\nexprs:\n", lambda, *curmin);
    // for(int i=0; i < 100; i++)
    //    printf("%d ", (int) exprs_row_major[i]);
    // printf("\n");
    
    double *w1p = MY_MALLOC(nrow * sizeof(double));
    CHECK_PTR(w1p, "w1p could not be allocated");
    double *w1m = MY_MALLOC(nrow * sizeof(double));
    CHECK_PTR(w1m, "w1m could not be allocated");
    double *w2p = MY_MALLOC(nrow * sizeof(double));
    CHECK_PTR(w2p, "w2p could not be allocated");
    double *w2m = MY_MALLOC(nrow * sizeof(double));
    CHECK_PTR(w2m, "w2m could not be allocated");
    char *exprs = MY_MALLOC(ncol * nrow); //column-major
    CHECK_PTR(exprs, "exprs could not be allocated");
    weight_ratios = MY_MALLOC(nrow * sizeof(double));
    
    for (int i = 0; i < nrow; i++) {
        w1p[i] = max(0., w1[i]);
        w1m[i] = max(0., -w1[i]);
        w2p[i] = max(0., w2[i]);
        w2m[i] = max(0., -w2[i]);
    }
    
    for (int i = 0; i < active_len*tot_depth; i++)
        active[i]--;
    
    for (int i = 0; i < tot_depth; i++)
        min_idxs[i] = -1;
    
    
    for (int j = 0; j < nrow; j++)
        for (int i = 0; i < ncol; i++)
            exprs[i*nrow+j] = exprs_col_major[i*nrow+j];
    // exprs[i*nrow+j] = exprs_row_major[j*ncol+i];
    
    if(*curmin == 0 || *curmin > lambda)
        *curmin = lambda;
    
    tot_node_explored = 0;
    tot_non_leaf_explored = 0;
    
    
    struct get_min_arg_struct args;
    args.tot_depth = tot_depth;
    args.exprs = exprs;
//    args.single_exprs = MY_MALLOC(ncol * nrow);
//    CHECK_PTR(args.single_exprs, "args.single_exprs could not be allocated");
//    
//    memcpy(args.single_exprs, exprs, ncol*nrow);
    args.nrow = nrow;
    args.ncol = ncol;
    args.w1p = w1p;
    args.w1m = w1m;
    args.w2p = w2p;
    args.w2m = w2m;
    args.num_const = lambda;
    args.denom_const = 1;
    args.curmin = curmin;
    args.combi_min_idx = min_idxs;
    args.active = active;
    args.active_len = active_len;
    
    pthread_mutex_t mutex;
    args.mutex = &mutex;
    
    pthread_mutex_init(args.mutex, NULL);
    
    pthread_t sub1, sub2;
    
    pthread_create(&sub1, NULL, (void *) launch_get_min_recur, &args);
    
    struct get_min_arg_struct args2 = args;
    args2.num_const = -lambda;
    args2.denom_const = -1;
    
    pthread_create(&sub2, NULL, (void *) launch_get_min_recur, &args2);
    
    pthread_join(sub1, NULL);
    pthread_join(sub2, NULL);
    
    pthread_mutex_destroy(args.mutex);
    
    for (int i = 0; i < args.tot_depth; i++) {
        min_idxs[i] = min_idxs[i]+1;  //IMPORTANT: must increment!
        // printf("[%d]", min_idxs[i]);
    }
    
    if(g_trace >= 2)
        printf("Total explored: %.0f non-terminal (%.0f total)\n Pruned: %ld + %ld(/%ld)\n\n", tot_non_leaf_explored, tot_node_explored, easy_pruned, pruned, pruned+not_pruned);
    
    
//    MY_FREE(args.single_exprs);
//    MY_FREE(args2.single_exprs);
    
    MY_FREE(w1p);
    MY_FREE(w1m);
    MY_FREE(w2p);
    MY_FREE(w2m);
    MY_FREE(exprs);
    MY_FREE(weight_ratios);
    // printf(" (lambda: %.4f)\n", lambda);
    
}
static
int
mode_encrypt(File filein, File fileout)
{
	size_t			bytesread;
	size_t			chunkbuflen;
	void			*chunkbuf = NULL;
	size_t			encryptbuflen = 0;
	size_t			encryptedlen = 0;
	void			*encryptbuf = NULL;
	ulonglong		ttlchunkswritten = 0;
	ulonglong		ttlbyteswritten = 0;
	xb_wcrypt_t		*xbcrypt_file = NULL;
	gcry_cipher_hd_t	cipher_handle;
	gcry_error_t		gcry_error;

	if (encrypt_algo != GCRY_CIPHER_NONE) {
		gcry_error = gcry_cipher_open(&cipher_handle,
					      encrypt_algo,
					      encrypt_mode, 0);
		if (gcry_error) {
			msg("%s:encrypt: unable to open libgcrypt cipher - "
			    "%s : %s\n", my_progname,
			    gcry_strsource(gcry_error),
			    gcry_strerror(gcry_error));
			return 1;
		}

		gcry_error = gcry_cipher_setkey(cipher_handle,
						opt_encrypt_key,
						encrypt_key_len);
		if (gcry_error) {
			msg("%s:encrypt: unable to set libgcrypt cipher key - "
			    "%s : %s\n", my_progname,
			    gcry_strsource(gcry_error),
			    gcry_strerror(gcry_error));
			goto err;
		}
	}

	posix_fadvise(filein, 0, 0, POSIX_FADV_SEQUENTIAL);

	xbcrypt_file = xb_crypt_write_open(&fileout,
					   my_xb_crypt_write_callback);
	if (xbcrypt_file == NULL) {
		msg("%s:encrypt: xb_crypt_write_open() failed.\n",
		    my_progname);
		goto err;
	}

	/* now read in data in chunk size, encryptand write out */
	chunkbuflen = opt_encrypt_chunk_size;
	chunkbuf = my_malloc(chunkbuflen, MYF(MY_FAE));
	while ((bytesread = my_read(filein, chunkbuf, chunkbuflen,
				    MYF(MY_WME))) > 0) {

		if (encrypt_algo != GCRY_CIPHER_NONE) {
			gcry_error = gcry_cipher_reset(cipher_handle);

			if (gcry_error) {
				msg("%s:encrypt: unable to reset cipher - "
				    "%s : %s\n", my_progname,
				    gcry_strsource(gcry_error),
				    gcry_strerror(gcry_error));
				goto err;
			}
			gcry_error = gcry_cipher_setiv(cipher_handle,
							encrypt_iv,
							encrypt_iv_len);

			if (gcry_error) {
				msg("%s:encrypt: unable to set cipher iv - "
				    "%s : %s\n", my_progname,
				    gcry_strsource(gcry_error),
				    gcry_strerror(gcry_error));
				continue;
			}

			if (encryptbuflen < bytesread) {
				if (encryptbuflen) {
					encryptbuf = my_realloc(encryptbuf,
								bytesread,
								MYF(MY_WME));
					encryptbuflen = bytesread;
				} else {
					encryptbuf = my_malloc(bytesread,
							       MYF(MY_WME));
					encryptbuflen = bytesread;
				}
			}

			gcry_error = gcry_cipher_encrypt(cipher_handle,
							 encryptbuf,
							 encryptbuflen,
							 chunkbuf,
							 bytesread);

			encryptedlen = bytesread;

			if (gcry_error) {
				msg("%s:encrypt: unable to encrypt chunk - "
				    "%s : %s\n", my_progname,
				    gcry_strsource(gcry_error),
				    gcry_strerror(gcry_error));
				gcry_cipher_close(cipher_handle);
				goto err;
			}
		} else {
			encryptedlen = bytesread;
			encryptbuf = chunkbuf;
		}

		if (xb_crypt_write_chunk(xbcrypt_file, encryptbuf, bytesread, encryptedlen)) {
			msg("%s:encrypt: abcrypt_write_chunk() failed.\n",
			    my_progname);
			goto err;
		}

		ttlchunkswritten++;
		ttlbyteswritten += encryptedlen;

		if (opt_verbose)
			msg("%s:encrypt: %llu chunks written, %llu bytes "
			    "written\n.", my_progname, ttlchunkswritten,
			    ttlbyteswritten);
	}

	MY_FREE(chunkbuf);

	if (encryptbuf && encryptbuflen)
		MY_FREE(encryptbuf);

	xb_crypt_write_close(xbcrypt_file);

	if (encrypt_algo != GCRY_CIPHER_NONE)
		gcry_cipher_close(cipher_handle);

	if (opt_verbose)
		msg("\n%s:encrypt: done\n", my_progname);

	return 0;
err:
	if (chunkbuf)
		MY_FREE(chunkbuf);

	if (encryptbuf && encryptbuflen)
		MY_FREE(encryptbuf);

	if (xbcrypt_file)
		xb_crypt_write_close(xbcrypt_file);

	if (encrypt_algo != GCRY_CIPHER_NONE)
		gcry_cipher_close(cipher_handle);

	return 1;
}
static void p3d_addLastNodeInGraph(void){
  configPt qcurrent;
  double dist;
  pp3d_rob robotPt;
  p3d_graph* G = NULL;
  p3d_node* current_nodePt;
  p3d_list_edge* list_edge;
  
  robotPt = (p3d_rob*) p3d_get_desc_curid(P3D_ROBOT);
  if(!XYZ_GRAPH) {
    G = p3d_create_graph();
  }else{
    G = XYZ_GRAPH;
  }

  if (G->start_nodePt != NULL) {
    qcurrent = p3d_get_robot_config(robotPt);
    current_nodePt = p3d_APInode_make_multisol(G,qcurrent,NULL);
    if(p3d_APInode_linked(G,G->prev_nodePt,current_nodePt,&dist)) {
      if (G->traj1Pt == NULL) {
        p3d_insert_node(G,current_nodePt);
        p3d_create_edges(G,G->prev_nodePt,current_nodePt,dist);
        p3d_add_node_compco(current_nodePt,G->prev_nodePt->comp, TRUE);
        G->search_start = G->start_nodePt;
        G->search_goal = current_nodePt;
        G->traj1Pt = p3d_graph_to_traj(robotPt);
        if (G->traj1Pt != NULL) {
          G->prev_nodePt = G->start_nodePt;
          G->last_nodePt = current_nodePt;
          //bloque le 1er path
          current_nodePt->edges->E->unvalid = TRUE;
          list_edge = current_nodePt->edges->E->Nf->edges;
          while (list_edge!= NULL) {
            if(list_edge->E->Nf == current_nodePt) {
              list_edge->E->unvalid = TRUE;
            }
            list_edge = list_edge->next;
          }
        }else{
          PrintInfo(("Path1 not found!\n"));
        }
      }else{
        if(p3d_APInode_linked(G,current_nodePt,G->last_nodePt,&dist)) {
          p3d_insert_node(G,current_nodePt);
          p3d_create_edges(G,G->prev_nodePt,current_nodePt,dist);
          p3d_add_node_compco(current_nodePt,G->prev_nodePt->comp, TRUE);
          p3d_create_edges(G,current_nodePt,G->last_nodePt,dist);
          G->search_start = G->start_nodePt;
          G->search_goal = G->last_nodePt;
          G->traj2Pt = p3d_graph_to_traj(robotPt);

          if (G->traj2Pt != NULL) {
            p3d_compute_proj_in_form(G);
          }else{
            PrintInfo(("Path not found!\n"));
          }
        }else{
          PrintInfo(("edge would be in collision\n"));
          p3d_destroy_config(robotPt, current_nodePt->q);
          MY_FREE(current_nodePt, p3d_node, 1);
          current_nodePt = NULL;
        }
      }
    }else{
      PrintInfo(("edge would be in collision\n"));
      p3d_destroy_config(robotPt, current_nodePt->q);
      MY_FREE(current_nodePt, p3d_node, 1);
      current_nodePt = NULL;
    }
  }
}
static
int
mode_decrypt(File filein, File fileout)
{
	xb_rcrypt_t		*xbcrypt_file = NULL;
	void			*chunkbuf = NULL;
	size_t			chunksize;
	size_t			originalsize;
	void			*decryptbuf = NULL;
	size_t			decryptbufsize = 0;
	ulonglong		ttlchunksread = 0;
	ulonglong		ttlbytesread = 0;
	xb_rcrypt_result_t	result;
	gcry_cipher_hd_t	cipher_handle;
	gcry_error_t		gcry_error;

	if (encrypt_algo != GCRY_CIPHER_NONE) {
		gcry_error = gcry_cipher_open(&cipher_handle,
					      encrypt_algo,
					      encrypt_mode, 0);
		if (gcry_error) {
			msg("%s:decrypt: unable to open libgcrypt"
			    " cipher - %s : %s\n", my_progname,
			    gcry_strsource(gcry_error),
			    gcry_strerror(gcry_error));
			return 1;
		}

		gcry_error = gcry_cipher_setkey(cipher_handle,
						opt_encrypt_key,
						encrypt_key_len);
		if (gcry_error) {
			msg("%s:decrypt: unable to set libgcrypt cipher"
			    "key - %s : %s\n", my_progname,
			    gcry_strsource(gcry_error),
			    gcry_strerror(gcry_error));
			goto err;
		}
	}

	/* Initialize the xb_crypt format reader */
	xbcrypt_file = xb_crypt_read_open(&filein, my_xb_crypt_read_callback);
	if (xbcrypt_file == NULL) {
		msg("%s:decrypt: xb_crypt_read_open() failed.\n", my_progname);
		goto err;
	}

	/* Walk the encrypted chunks, decrypting them and writing out */
	while ((result = xb_crypt_read_chunk(xbcrypt_file, &chunkbuf,
					     &originalsize, &chunksize))
		== XB_CRYPT_READ_CHUNK) {

		if (encrypt_algo != GCRY_CIPHER_NONE) {
			gcry_error = gcry_cipher_reset(cipher_handle);
			if (gcry_error) {
				msg("%s:decrypt: unable to reset libgcrypt"
				    " cipher - %s : %s\n", my_progname,
				    gcry_strsource(gcry_error),
				    gcry_strerror(gcry_error));
				goto err;
			}

			gcry_error = gcry_cipher_setiv(cipher_handle,
							encrypt_iv,
							encrypt_iv_len);
			if (gcry_error) {
				msg("%s:decrypt: unable to set cipher iv - "
				    "%s : %s\n", my_progname,
				    gcry_strsource(gcry_error),
				    gcry_strerror(gcry_error));
				continue;
			}

			if (decryptbufsize < originalsize) {
				if (decryptbufsize) {
					decryptbuf = my_realloc(decryptbuf,
								originalsize,
								MYF(MY_WME));
					decryptbufsize = originalsize;
				} else {
					decryptbuf = my_malloc(originalsize,
							       MYF(MY_WME));
					decryptbufsize = originalsize;
				}
			}

			/* Try to decrypt it */
			gcry_error = gcry_cipher_decrypt(cipher_handle,
							 decryptbuf,
							 originalsize,
							 chunkbuf,
							 chunksize);
			if (gcry_error) {
				msg("%s:decrypt: unable to decrypt chunk - "
				    "%s : %s\n", my_progname,
				    gcry_strsource(gcry_error),
				    gcry_strerror(gcry_error));
				gcry_cipher_close(cipher_handle);
					goto err;
			}

		} else {
			decryptbuf = chunkbuf;
		}

		/* Write it out */
		if (my_write(fileout, decryptbuf, originalsize,
			     MYF(MY_WME | MY_NABP))) {
			msg("%s:decrypt: unable to write output chunk.\n",
			    my_progname);
			goto err;
		}
		ttlchunksread++;
		ttlbytesread += chunksize;
		if (opt_verbose)
			msg("%s:decrypt: %llu chunks read, %llu bytes read\n.",
		    	    my_progname, ttlchunksread, ttlbytesread);
	}

	xb_crypt_read_close(xbcrypt_file);

	if (encrypt_algo != GCRY_CIPHER_NONE)
		gcry_cipher_close(cipher_handle);

	if (decryptbuf && decryptbufsize)
		MY_FREE(decryptbuf);

	if (opt_verbose)
		msg("\n%s:decrypt: done\n", my_progname);

	return 0;
err:
	if (xbcrypt_file)
		xb_crypt_read_close(xbcrypt_file);

	if (encrypt_algo != GCRY_CIPHER_NONE)
		gcry_cipher_close(cipher_handle);

	if (decryptbuf && decryptbufsize)
		MY_FREE(decryptbuf);

	return 1;
}