Esempio n. 1
0
MRB_API mrb_value
mrb_ary_new_from_values(mrb_state *mrb, mrb_int size, const mrb_value *vals)
{
  mrb_value ary;
  struct RArray *a;

  ary = mrb_ary_new_capa(mrb, size);
  a = mrb_ary_ptr(ary);
  array_copy(a->ptr, vals, size);
  a->len = size;

  return ary;
}
Esempio n. 2
0
int main()
{
    int A[5] = { 1, 2, 3, 4, 5 };
    int B[5];
    int i;

    array_copy(A, B, 5);
    for (i = 0; i < 5; i++) {
        printf("A[%d] = %d, B[%d] = %d\n", i, A[i], i, B[i]);
    }

    return 0;
}
Esempio n. 3
0
int json_array_insert_new(json_t *json, unsigned int index, json_t *value)
{
    json_array_t *array;
    json_t **old_table;

    if(!value)
        return -1;

    if(!json_is_array(json) || json == value) {
        json_decref(value);
        return -1;
    }
    array = json_to_array(json);

    if(index > array->entries) {
        json_decref(value);
        return -1;
    }

    old_table = json_array_grow(array, 1, 0);
    if(!old_table) {
        json_decref(value);
        return -1;
    }

    if(old_table != array->table) {
        array_copy(array->table, 0, old_table, 0, index);
        array_copy(array->table, index + 1, old_table, index,
                   array->entries - index);
        free(old_table);
    }
    else
        array_move(array, index + 1, index, array->entries - index);

    array->table[index] = value;
    array->entries++;

    return 0;
}
Esempio n. 4
0
mrb_value
mrb_ary_new4(mrb_state *mrb, int n, const mrb_value *elts)
{
  mrb_value ary;

  ary = mrb_ary_new_capa(mrb, n);
  if (n > 0 && elts) {
    array_copy(RARRAY_PTR(ary), elts, n);
    RARRAY_LEN(ary) = n;
  }

  return ary;
}
Esempio n. 5
0
array_t* array_duplicate_content(array_t* input, size_t value_size)
{
	array_t* output=array_copy(input);
	arrayelement_t* element=output->first;
	while(element)
	{
		void* data=element->data;
		element->data=MALLOC(value_size);
		memcpy(element->data,data,value_size);
		element=element->next;
	}
	return output;
}
Esempio n. 6
0
void ioglued()
{
	thread_setName(thread_getCurrentThread(), "ioglued");

	__ioglued_modulesToStop = array_create();
	spinlock_unlock(&__ioglued_lock);

	size_t size = sizeof(ioglued_modules) / sizeof(const char *);
	for(size_t i=0; i<size; i++)
	{
		const char *name = ioglued_modules[i];
		io_module_t *module = io_moduleWithName(name);

		if(!module)
			dbg("ioglued: Failed to publish \"%s\"\n", name);
	}

	while(1) 
	{
		spinlock_lock(&__ioglued_lock);
		if(array_count(__ioglued_modulesToStop) > 0)
		{
			array_t *copy = array_copy(__ioglued_modulesToStop);
			array_removeAllObjects(__ioglued_modulesToStop);

			spinlock_unlock(&__ioglued_lock);

			for(size_t i=0; i<array_count(copy); i++)
			{
				io_module_t *module = array_objectAtIndex(copy, i);

				spinlock_lock(&module->lock);
				if(!module->initialized)
				{
					__ioglued_addReferencelessModule(module);
					spinlock_unlock(&module->lock);
					continue;
				}
				
				spinlock_unlock(&module->lock);
				io_moduleStop(module);
			}

			array_destroy(copy);
		}
		else
			spinlock_unlock(&__ioglued_lock);

		sd_yield();
	}
}
Esempio n. 7
0
void Solver::createTables()
{
    if (mSameColors) {
        mCodes.size = ipow(mColors, mPegs);
    } else {
        mCodes.size = 1;
        for(int i = 0; i < mPegs; ++i)
            mCodes.size *= (mColors - i);
    }

    mMaxResponse = (mPegs + 1)*(mPegs + 2)/2;

    mCodes.index = new unsigned char* [mCodes.size];

    for(int i = 0; i < mCodes.size; ++i) {
        mCodes.index[i] = new unsigned char[mPegs];
    }

    if (mSameColors) {
        for (int i = 0; i < mPegs; i++)
            mCodes.index[0][i] = 0;
        for (int i = 1; i < mCodes.size; i++) {
            array_copy(mCodes.index[i-1], mCodes.index[i], mPegs);
            nextCodeSameColor(mCodes.index[i]);
        }
    } else {
        for (int i = 0; i < mPegs; i++)
            mCodes.index[0][i] = i;
        for (int i = 1; i < mCodes.size; i++) {
            array_copy(mCodes.index[i-1], mCodes.index[i], mPegs);
            nextCodeDifferentColor(mCodes.index[i]);
        }
    }

    for(int i = 0; i < mCodes.size; ++i)
        mPossibles.append(i);
}
Esempio n. 8
0
Array * page_rank(Table * inbound, unsigned int order, float alpha, float convergence, unsigned int max_times)
{
        register int t = 0, k, i;
        register float norm2 = 1.0, prod_scalar, x;
        unsigned int total_size = order;
        Array * vector = initial(total_size);
        Array * new_vector = initial(total_size);
        Array * tmp;



        x = 1.0 - alpha;

        while (t < max_times && norm2 >= convergence) {
                t++;
                norm2 = 0.0;
                prod_scalar = 0.0;

                for (k = 0; k < total_size; k++) {
                        if (is_sink(inbound, k))
                                prod_scalar += array_get(vector, k) * alpha;
                }
                prod_scalar += x;

                for (k = 0; k < total_size; k++) {
                        array_set(new_vector, k, prod_scalar);
                        if (!is_sink(inbound, k)) {
                                tmp = table_get(inbound, k);
                                for (i = 0; i < array_len(tmp); i++) {
                                        array_incr(new_vector, k,
                                                   array_get(vector,
                                                             (int)array_get(tmp, i)) *
                                                   alpha);
                                }
                        }
                        norm2 += (array_get(new_vector, k) - array_get(vector, k)) *
                                (array_get(new_vector, k) - array_get(vector, k));
                }

                t++;

                norm2 = sqrt((double)norm2) / total_size;

                array_copy(vector, new_vector);
        }

        array_delete(new_vector);
        return normalize(vector);
}
Esempio n. 9
0
struct anim* anim_new(struct array* sprite_frames) {
    struct anim* anim = STRUCT_NEW(anim);
    
    anim->interval = 1.0f/4.0f;
    anim->callback = NULL;
    anim->sprite_frames = array_copy(sprite_frames);
    anim->speed = 1.0f;
    
    // privates
    anim->__id = ++__anim_id;
    anim->__now = 0.0f;
    anim->__cur_frame = 0;
    anim->__total_frame = array_size(anim->sprite_frames);
    anim->__state = ANIM_STATE_PLAY;
    return anim;
}
Esempio n. 10
0
static void
ary_concat(mrb_state *mrb, struct RArray *a, struct RArray *a2)
{
  mrb_int len;

  if (ARY_LEN(a2) > ARY_MAX_SIZE - ARY_LEN(a)) {
    mrb_raise(mrb, E_ARGUMENT_ERROR, "array size too big");
  }
  len = ARY_LEN(a) + ARY_LEN(a2);

  ary_modify(mrb, a);
  if (ARY_CAPA(a) < len) {
    ary_expand_capa(mrb, a, len);
  }
  array_copy(ARY_PTR(a)+ARY_LEN(a), ARY_PTR(a2), ARY_LEN(a2));
  mrb_write_barrier(mrb, (struct RBasic*)a);
  ARY_SET_LEN(a, len);
}
Esempio n. 11
0
static void
ary_expand_capa(mrb_state *mrb, struct RArray *a, mrb_int len)
{
  mrb_int capa = ARY_CAPA(a);

  if (len > ARY_MAX_SIZE || len < 0) {
  size_error:
    mrb_raise(mrb, E_ARGUMENT_ERROR, "array size too big");
  }

  if (capa < ARY_DEFAULT_LEN) {
    capa = ARY_DEFAULT_LEN;
  }
  while (capa < len) {
    if (capa <= ARY_MAX_SIZE / 2) {
      capa *= 2;
    }
    else {
      capa = len;
    }
  }
  if (capa < len || capa > ARY_MAX_SIZE) {
    goto size_error;
  }

  if (ARY_EMBED_P(a)) {
    mrb_value *ptr = ARY_EMBED_PTR(a);
    mrb_int len = ARY_EMBED_LEN(a);
    mrb_value *expanded_ptr = (mrb_value *)mrb_malloc(mrb, sizeof(mrb_value)*capa);

    ARY_UNSET_EMBED_FLAG(a);
    array_copy(expanded_ptr, ptr, len);
    a->as.heap.len = len;
    a->as.heap.aux.capa = capa;
    a->as.heap.ptr = expanded_ptr;
  }
  else if (capa > a->as.heap.aux.capa) {
    mrb_value *expanded_ptr = (mrb_value *)mrb_realloc(mrb, a->as.heap.ptr, sizeof(mrb_value)*capa);

    a->as.heap.aux.capa = capa;
    a->as.heap.ptr = expanded_ptr;
  }
}
Esempio n. 12
0
void vm_call_src(struct context *context, struct variable *func)
{
    struct map *env = NULL;
    if (func->map) {
        struct variable *v = (struct variable*)variable_map_get(context, func, byte_array_from_string(RESERVED_ENV));
        if (v)
            env = v->map;
    }

    struct program_state *state = (struct program_state*)stack_peek(context->program_stack, 0);
    struct variable *s = (struct variable*)stack_peek(context->operand_stack, 0);
    state->args = array_copy(s->list);

    INDENT

    // call the function
    switch (func->type) {
        case VAR_FNC:
            run(context, func->str, env, false);
            break;
        case VAR_C: {
            struct variable *v = func->cfnc(context);
            if (!v)
                v = variable_new_src(context, 0);
            else if (v->type != VAR_SRC) { // convert to VAR_SRC variable
                stack_push(context->operand_stack, v);
                v = variable_new_src(context, 1);
            }
            stack_push(context->operand_stack, v); // push the result
        } break;
        case VAR_NIL:
            vm_exit_message(context, "can't find function");
            break;
        default:
            vm_exit_message(context, "not a function");
            break;
    }

    state->args = NULL;

    UNDENT
}
Esempio n. 13
0
LOCAL void harmonic_time(struct dipole_desc *dipole) {
    int half_envelope_length=(int)rint((M_PI*MAX_ENVELOPE_CYCLES)/dipole->time[1]);

    if (dipole->time[2]-- >0) return;
    if (dipole->time[3]== -1) {
        /*{{{  Envelope processed: Initiate new wait state*/
        dipole->time[0]=2*M_PI*((double)rand())/RAND_MAX;
        dipole->time[2]=(int)(half_envelope_length*((double)rand())/RAND_MAX);
        dipole->time[4]=(int)(half_envelope_length*((double)rand())/RAND_MAX)+1; /* Avoid zero envelope */
        dipole->time[3]=2*dipole->time[4];
        array_setto_null(&dipole->dip_moment);
        return;
        /*}}}  */
    }
    if (dipole->time[2]== -1) array_setreadwrite(&dipole->dip_moment);
    array_copy(&dipole->initial_moment, &dipole->dip_moment);
    array_scale(&dipole->dip_moment, sin(dipole->time[0])*(1.0-square((dipole->time[3]-dipole->time[4])/dipole->time[4])));
    dipole->time[0]+=dipole->time[1];	/* time[1] is the frequency */
    dipole->time[3]--;
}
Esempio n. 14
0
static inline struct variable *cfnc_insert(struct context *context) // todo: test
{
    struct variable *args = (struct variable*)stack_pop(context->operand_stack);
    struct variable *self = (struct variable*)array_get(args->list.ordered, 0);
    struct variable *insertion = (struct variable*)array_get(args->list.ordered, 1);
    struct variable *start = args->list.ordered->length > 2 ?
        (struct variable*)array_get(args->list.ordered, 2) : NULL;
    null_check(self);
    null_check(insertion);
    assert_message(!start || start->type == VAR_INT, "non-integer index");

    int32_t position = 0;
    switch (self->type) {
        case VAR_LST: {
            struct array *list = array_new_size(1);
            array_set(list, 0, insertion);
            insertion = variable_new_list(context, list);
            position = self->list.ordered->length;
            array_del(list);
        } break;
        case VAR_STR:
            assert_message(insertion->type == VAR_STR, "insertion doesn't match destination");
            position = self->str->length;
            break;
        default:
            exit_message("bad insertion destination");
            break;
    }

    struct variable *first = variable_part(context, variable_copy(context, self), 0, position);
    struct variable *second = variable_part(context, variable_copy(context, self), position, -1);
    struct variable *joined = variable_concatenate(context, 3, first, insertion, second);
    
    if (self->type == VAR_LST) {
        array_del(self->list.ordered);
        self->list.ordered = array_copy(joined->list.ordered);
    } else {
        byte_array_del(self->str);
        self->str = byte_array_copy(joined->str);
    } return joined;
}
Esempio n. 15
0
File: array.c Progetto: iij/mruby
static mrb_value
mrb_ary_push_m(mrb_state *mrb, mrb_value self)
{
  mrb_value *argv;
  mrb_int len, len2, alen;
  struct RArray *a;

  mrb_get_args(mrb, "*!", &argv, &alen);
  a = mrb_ary_ptr(self);
  ary_modify(mrb, a);
  len = ARY_LEN(a);
  len2 = len + alen;
  if (ARY_CAPA(a) < len2) {
    ary_expand_capa(mrb, a, len2);
  }
  array_copy(ARY_PTR(a)+len, argv, alen);
  ARY_SET_LEN(a, len2);
  mrb_write_barrier(mrb, (struct RBasic*)a);

  return self;
}
Esempio n. 16
0
int json_array_extend(json_t *json, json_t *other_json)
{
    json_array_t *array, *other;
    unsigned int i;

    if(!json_is_array(json) || !json_is_array(other_json))
        return -1;
    array = json_to_array(json);
    other = json_to_array(other_json);

    if(!json_array_grow(array, other->entries, 1))
        return -1;

    for(i = 0; i < other->entries; i++)
        json_incref(other->table[i]);

    array_copy(array->table, array->entries, other->table, 0, other->entries);

    array->entries += other->entries;
    return 0;
}
Esempio n. 17
0
File: array.c Progetto: iij/mruby
static void
ary_replace(mrb_state *mrb, struct RArray *a, struct RArray *b)
{
  mrb_int len = ARY_LEN(b);

  ary_modify_check(mrb, a);
  if (a == b) return;
  if (ARY_SHARED_P(a)) {
    mrb_ary_decref(mrb, a->as.heap.aux.shared);
    a->as.heap.aux.capa = 0;
    a->as.heap.len = 0;
    a->as.heap.ptr = NULL;
    ARY_UNSET_SHARED_FLAG(a);
  }
  if (ARY_SHARED_P(b)) {
  shared_b:
    if (ARY_EMBED_P(a)) {
      ARY_UNSET_EMBED_FLAG(a);
    }
    else {
      mrb_free(mrb, a->as.heap.ptr);
    }
    a->as.heap.ptr = b->as.heap.ptr;
    a->as.heap.len = len;
    a->as.heap.aux.shared = b->as.heap.aux.shared;
    a->as.heap.aux.shared->refcnt++;
    ARY_SET_SHARED_FLAG(a);
    mrb_write_barrier(mrb, (struct RBasic*)a);
    return;
  }
  if (!MRB_FROZEN_P(b) && len > ARY_REPLACE_SHARED_MIN) {
    ary_make_shared(mrb, b);
    goto shared_b;
  }
  if (ARY_CAPA(a) < len)
    ary_expand_capa(mrb, a, len);
  array_copy(ARY_PTR(a), ARY_PTR(b), len);
  mrb_write_barrier(mrb, (struct RBasic*)a);
  ARY_SET_LEN(a, len);
}
Esempio n. 18
0
File: tf.c Progetto: 15ramky/pyretic
struct list_res
rule_inv_apply (const struct tf *tf, const struct rule *r, const struct res *in,
		bool append)
{
  /* Given a rule `r` in a tf `tf`, apply the inverse of `r` on the input
     (headerspace,port) `in`. */
  struct list_res res = {0};

  // prune cases where rule outport doesn't include the current port
  if (r->out > 0 && r->out != in->port) return res;
  if (r->out < 0 && !port_match(in->port, r->out, tf)) return res;
  if (!r->out) return res;

  // set up inverse match and rewrite arrays
  array_t *inv_rw=0, *inv_mat=0;
  if (r->mask) { // rewrite rule
    inv_mat = rule_set_inv_mat (r, in->hs.len);
    inv_rw  = rule_set_inv_rw (r, in->hs.len);
  }
  else { // fwding and topology rules
    if (r->match) inv_mat = array_copy (DATA_ARR (r->match), in->hs.len);
  }

  struct hs hs;
  if (!r->match) hs_copy (&hs, &in->hs); // topology rule
  else { // fwding and rewrite rules
    if (!hs_isect_arr (&hs, &in->hs, inv_mat)) return res;
    if (r->mask) hs_rewrite (&hs, DATA_ARR (r->mask), inv_rw);
  }

  // there is a new hs result corresponding to each rule inport
  bool used_hs = port_append_res (&res, r, tf, in, r->in, append, &hs, true);

  if (inv_rw) array_free (inv_rw);
  if (inv_mat) array_free (inv_mat);
  if (!used_hs) hs_destroy (&hs);

  return res;
}
Esempio n. 19
0
File: array.c Progetto: iij/mruby
static mrb_value
mrb_ary_unshift_m(mrb_state *mrb, mrb_value self)
{
  struct RArray *a = mrb_ary_ptr(self);
  mrb_value *vals, *ptr;
  mrb_int alen, len;

  mrb_get_args(mrb, "*!", &vals, &alen);
  if (alen == 0) {
    ary_modify_check(mrb, a);
    return self;
  }
  len = ARY_LEN(a);
  if (alen > ARY_MAX_SIZE - len) {
    mrb_raise(mrb, E_ARGUMENT_ERROR, "array size too big");
  }
  if (ARY_SHARED_P(a)
      && a->as.heap.aux.shared->refcnt == 1 /* shared only referenced from this array */
      && a->as.heap.ptr - a->as.heap.aux.shared->ptr >= alen) /* there's room for unshifted item */ {
    ary_modify_check(mrb, a);
    a->as.heap.ptr -= alen;
    ptr = a->as.heap.ptr;
  }
  else {
    ary_modify(mrb, a);
    if (ARY_CAPA(a) < len + alen)
      ary_expand_capa(mrb, a, len + alen);
    ptr = ARY_PTR(a);
    value_move(ptr + alen, ptr, len);
  }
  array_copy(ptr, vals, alen);
  ARY_SET_LEN(a, len+alen);
  while (alen--) {
    mrb_field_write_barrier_value(mrb, (struct RBasic*)a, vals[alen]);
  }

  return self;
}
Esempio n. 20
0
/*	LOAD_PROGRAM
 *  Input: Three ints (A, B, C) representing registers
 *	Seq_T segment = (Seq_T)Seq_get(SEGMEMORY, 0);

 *     This function searches for the segment at the id
 *     found in register B. If the id is zero, the counter
 *     to the value found in register C. If the id is not
 *     the instruction code segment is freed and the
 *     segment at id is duplicated and placed in the 0th
 *     position in the segment_memory sequence.
 *
 *  Output: N/A
 */
void load_program(int A, int B, int C)
{
// 	fprintf(stderr, "in load prog\n");
	(void) A;
	uint32_t b = register_at(B); 
	uint32_t c = register_at(C);
	if (b == 0){
		uint32_t c = register_at(C);
		if (c == 0)
			assign_counter(-1);
		else
			assign_counter(c - 1);
		return;
	}
	Seg_array seg_array = SEG_MEMORY[b];
	Seg_array new_seg_array = array_copy(seg_array);
	Seg_array inst_seg_array = SEG_MEMORY[0];
	FREE(inst_seg_array);
	SEG_MEMORY[0] = new_seg_array;
	if (c == 0)
		assign_counter(-1);
	assign_counter(c - 1);
}
// Take Rational Function Optimization step
void MOLECULE::rfo_step(void) {
  int i, j;
  int dim = g_nintco();
  double tval, tval2;
  double *f_q = p_Opt_data->g_forces_pointer();
  double **H = p_Opt_data->g_H_pointer();
  double *dq = p_Opt_data->g_dq_pointer();
fprintf(outfile,"doing rfo_step\n"); fflush(outfile);

  // build (lower-triangle of) RFO matrix and diagonalize
  double **rfo_mat = init_matrix(dim+1, dim+1);
  for (i=0; i<dim; ++i)
    for (j=0; j<=i; ++j)
      rfo_mat[i][j] = H[i][j];

  for (i=0; i<dim; ++i)
    rfo_mat[dim][i] = - f_q[i];

  if (Opt_params.print_lvl >= 3) {
    fprintf(outfile,"RFO mat\n");
    print_matrix(outfile, rfo_mat, dim+1, dim+1);
  }

  double *lambda = init_array(dim+1);
  opt_symm_matrix_eig(rfo_mat, dim+1, lambda);
  if (Opt_params.print_lvl >= 2) {
    fprintf(outfile,"RFO eigenvalues/lambdas\n");
    print_matrix(outfile, &(lambda), 1, dim+1);
  }

  // Do intermediate normalization.  
  // RFO paper says to scale eigenvector to make the last element equal to 1.
  // During the course of an optimization some evects may appear that are bogus leads
  // - the root following can avoid them. 
  for (i=0; i<dim+1; ++i) {
    tval = rfo_mat[i][dim];
    if (fabs(tval) > Opt_params.rfo_normalization_min) {
      for (j=0;j<dim+1;++j)
        rfo_mat[i][j] /= rfo_mat[i][dim];
    }
  }
  if (Opt_params.print_lvl >= 3) {
    fprintf(outfile,"RFO eigenvectors (rows)\n");
    print_matrix(outfile, rfo_mat, dim+1, dim+1);
  }

  int rfo_root, f;
  double rfo_eval;
  double *rfo_u;      // unit vector in step direction
  double rfo_dqnorm;   // norm of step
  double rfo_g;         // gradient in step direction
  double rfo_h;         // hessian in step direction
  double DE_projected; // projected energy change by quadratic approximation

  // *** choose which RFO eigenvector to use
  // if not root following, then use rfo_root'th lowest eigenvalue; default is 0 (lowest)
  if ( (!Opt_params.rfo_follow_root) || (p_Opt_data->g_iteration() == 1)) {
    rfo_root = Opt_params.rfo_root;
    fprintf(outfile,"\tFollowing RFO solution %d.\n", rfo_root);
  }
  else { // do root following
    double * rfo_old_evect = p_Opt_data->g_rfo_eigenvector_pointer();
    tval = 0;
    for (i=0; i<dim; ++i) { // dot only within H block, excluding rows and columns approaching 0
      tval2 = array_dot(rfo_mat[i], rfo_old_evect,dim);
      if (tval2 > tval) {
        tval = tval2;
        rfo_root = i;
      }
    }
    fprintf(outfile,"RFO vector %d has maximal overlap with previous step\n", rfo_root+1);
  }
  p_Opt_data->set_rfo_eigenvector(rfo_mat[rfo_root]);

  // print out lowest energy evects
  if (Opt_params.print_lvl >= 2) {
    for (i=0; i<dim+1; ++i) {
      if ((lambda[i] < 0.0) || (i <rfo_root)) {
        fprintf(outfile,"RFO eigenvalue %d: %15.10lf (or 2*%-15.10lf)\n", i+1, lambda[i],lambda[i]/2);
        fprintf(outfile,"eigenvector:\n");
        print_matrix(outfile, &(rfo_mat[i]), 1, dim+1);
      }
    }
  }
  free_array(lambda);

  for (j=0; j<dim; ++j)
    dq[j] = rfo_mat[rfo_root][j]; // leave out last column

  // Zero steps for frozen fragment
  for (f=0; f<fragments.size(); ++f) {
    if (fragments[f]->is_frozen() || Opt_params.freeze_intrafragment) {
      fprintf(outfile,"\tZero'ing out displacements for frozen fragment %d\n", f+1);
      for (i=0; i<fragments[f]->g_nintco(); ++i)
        dq[ g_intco_offset(f) + i ] = 0.0;
    }
  }

  apply_intrafragment_step_limit(dq);
  //check_intrafragment_zero_angles(dq);

  // get norm |dq| and unit vector in the step direction
  rfo_dqnorm = sqrt( array_dot(dq, dq, dim) );
  rfo_u = init_array(dim);
  array_copy(rfo_mat[rfo_root], rfo_u, dim);
  array_normalize(rfo_u, dim);
  free_matrix(rfo_mat);

  // get gradient and hessian in step direction
  rfo_g = -1 * array_dot(f_q, rfo_u, dim);
  rfo_h = 0;
  for (i=0; i<dim; ++i)
    rfo_h += rfo_u[i] * array_dot(H[i], rfo_u, dim);

  DE_projected = DE_rfo_energy(rfo_dqnorm, rfo_g, rfo_h);
  fprintf(outfile,"\tProjected energy change by RFO approximation: %20.10lf\n", DE_projected);

  // do displacements for each fragment separately
  for (f=0; f<fragments.size(); ++f) {
    if (fragments[f]->is_frozen() || Opt_params.freeze_intrafragment) {
      fprintf(outfile,"\tDisplacements for frozen fragment %d skipped.\n", f+1);
      continue;
    }
    fragments[f]->displace(&(dq[g_intco_offset(f)]), true, g_intco_offset(f));
  }

  // do displacements for interfragment coordinates
  double *q_target;
  for (int I=0; I<interfragments.size(); ++I) {

    q_target = interfragments[I]->intco_values();
    for (i=0; i<interfragments[I]->g_nintco(); ++i)
      q_target[i] += dq[g_interfragment_intco_offset(I) + i];

    interfragments[I]->orient_fragment(q_target);

    free_array(q_target);
  }

#if defined(OPTKING_PACKAGE_QCHEM)
//  // fix rotation matrix for rotations in QCHEM EFP code
//  for (int I=0; I<efp_fragments.size(); ++I)
//    efp_fragments[I]->displace( I, &(dq[g_efp_fragment_intco_offset(I)]) );
#endif

  //symmetrize_geom(); // now symmetrize the geometry for next step

  // save values in step data
  p_Opt_data->save_step_info(DE_projected, rfo_u, rfo_dqnorm, rfo_g, rfo_h);

  free_array(rfo_u);
  fflush(outfile);

} // end take RFO step
Esempio n. 22
0
LOCAL void noise_time_exit(struct dipole_desc *dipole) {
    array_copy(&dipole->initial_moment, &dipole->dip_moment);
}
Esempio n. 23
0
LOCAL void harmonic_time_init(struct dipole_desc *dipole) {
    array_copy(&dipole->dip_moment, &dipole->initial_moment);
    dipole->time[2]=dipole->time[3]= -1;
}
int main(int argc, char** argv) {
	
	if(argc > 1)
		___PROBLEM_SIZE___ = atoi(argv[1]);
	
	// MPI code starts here...
	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &processor_count);
	MPI_Comm_rank(MPI_COMM_WORLD, &processor_id);
	MPI_Status mpi_stat;
	
	double** A = MatrixUtility::InitializeEmptyMatrix(___PROBLEM_SIZE___, ___PROBLEM_SIZE___);
	double** A_res = MatrixUtility::InitializeEmptyMatrix(___PROBLEM_SIZE___, ___PROBLEM_SIZE___);
	double* B = MatrixUtility::InitializeEmptyVector(___PROBLEM_SIZE___);
	double* A_row_k = MatrixUtility::InitializeEmptyVector(___PROBLEM_SIZE___);
	double* X = MatrixUtility::InitializeEmptyVector(___PROBLEM_SIZE___);
	
	for (int i = 0; i < ___PROBLEM_SIZE___; i++) {
		X[i] = i+1;
	}
	
	/*
	
	A[0][0] = 2;
	A[0][1] = -1;
	A[0][2] = 0;
	A[1][0] = -1;
	A[1][1] = 2;
	A[1][2] = -1;
	A[2][0] = 0;
	A[2][1] = -1;
	A[2][2] = 1;
	
	B[0] = 1;
	B[1] = 0;
	B[2] = 0;
	 */
	
	double residual = 0;
	
	do {
		
		int row_per_processor = ___PROBLEM_SIZE___ / processor_count;
		
		int row_range_min = processor_id * row_per_processor;
		int row_range_max = row_range_min + row_per_processor - 1;
		
		if (___IS_MASTER_PROCESSOR___) {
			row_range_max = ___PROBLEM_SIZE___ - 1;
			
			for (int i = 0; i < ___PROBLEM_SIZE___; i++) {
				B[i] = -F_xn(X, i);
				
				A[i][i] = F_xn_xn(X, i);
				
				
				if(i < ___PROBLEM_SIZE___ - 1)
				{
					A[i][i + 1] = F_xn_xn_plus_1(X, i);
				}
				
				if(i > 0)
				{
					A[i][i - 1] = F_xn_xn_minus_1(X, i);
				}
			}
			
			if (___PROBLEM_SIZE___ <= 30) {
				printf("\nB:\n");
				for (int i = 0; i < ___PROBLEM_SIZE___; i++) {
					std::cout << std::setw(12) << B[i];
				}
				
				printf("\nA:\n");
				MatrixUtility::PrintMatrix(A, ___PROBLEM_SIZE___, ___PROBLEM_SIZE___);
			}
		}
		
		/*------------GET LDLT FACTOR------------*/
		
		for (int k = 0; k < ___PROBLEM_SIZE___; k++) {
			MPI_Bcast(A[k], ___PROBLEM_SIZE___, MPI_DOUBLE, ___MASTER_PROCESSOR___, MPI_COMM_WORLD);
		}
		
		for (int k = 0; k < ___PROBLEM_SIZE___; k++) {
			if (k >= row_range_min && k <= row_range_max) {
				for (int j = k + 1; j < ___PROBLEM_SIZE___; j++) {
					A[k][j] /= A[k][k];
				}
				
				if (___IS_PARALLEL___) {
					for (int i = processor_id; i < processor_count; i++) {
						if (i != processor_id) {
							MPI_Send(A[k], ___PROBLEM_SIZE___, MPI_DOUBLE, i, ___TAG___, MPI_COMM_WORLD);
						}
					}
				}
			}
			
			if (___IS_PARALLEL___){
				if (k <= row_range_max ) {
					if (k < row_range_min) {
						MPI_Recv(A_row_k, ___PROBLEM_SIZE___, MPI_DOUBLE, MPI_ANY_SOURCE, ___TAG___, MPI_COMM_WORLD, &mpi_stat);
					}
					else
					{
						array_copy(A_row_k, A[k], ___PROBLEM_SIZE___);
					}
					
					if (___IS_MASTER_PROCESSOR___) {
						array_copy(A_res[k], A_row_k, ___PROBLEM_SIZE___);
					}
				}
			}
			
			MPI_Barrier(MPI_COMM_WORLD);
			
			for (int i = ( ( (k+1) > row_range_min) ? (k+1) : row_range_min); i<=row_range_max; i++){
				for(int j = k + 1; j < ___PROBLEM_SIZE___; j++){
					if(___IS_PARALLEL___)
						A[i][j] = A[i][j] - A[i][k] * A_row_k[j];
					else
						A[i][j] = A[i][j] - A[i][k] * A[k][j];
				}
			}
		}
		
		if (___IS_PARALLEL___ && ___PROBLEM_SIZE___ <= 30)
		{
			if (___IS_MASTER_PROCESSOR___)
			{
				printf("\nA_res:\n");
				MatrixUtility::PrintMatrix(A_res, ___PROBLEM_SIZE___, ___PROBLEM_SIZE___);
			}
		}
		else
		{
			if (___PROBLEM_SIZE___ <= 30) {
				printf("\nA_res:\n");
				MatrixUtility::PrintMatrix(A, ___PROBLEM_SIZE___, ___PROBLEM_SIZE___);
			}
			
		}
		
		/*------------GET LDLT FACTOR FINISHED------------*/
		
		/*------------BACKWARD SUBSTITUTION------------*/
		
		if (___IS_MASTER_PROCESSOR___)
		{
			double* D;
			double** L_trans;
			if (___IS_PARALLEL___)
			{
				D = MatrixUtility::ExtractDiagnoal(A_res, ___PROBLEM_SIZE___);
				L_trans = MatrixUtility::GetMatrixTranspose(A_res, ___PROBLEM_SIZE___, ___PROBLEM_SIZE___);
			}
			else
			{
				D = MatrixUtility::ExtractDiagnoal(A, ___PROBLEM_SIZE___);
				L_trans = MatrixUtility::GetMatrixTranspose(A, ___PROBLEM_SIZE___, ___PROBLEM_SIZE___);
			}
			
			double* Y = new double[___PROBLEM_SIZE___];
			double* Z = new double[___PROBLEM_SIZE___];
			double* X_delta = MatrixUtility::InitializeEmptyVector(___PROBLEM_SIZE___);
			
			LDLUtility::SolveXWithLD(L_trans, ___PROBLEM_SIZE___, D, B, Z, Y, X_delta);
			//MatrixUtility::PrintVector(X_delta, ___PROBLEM_SIZE___);
			
			for (int i = 0; i < ___PROBLEM_SIZE___; i++) {
				X[i] += X_delta[i];
			}
			
			if (___PROBLEM_SIZE___ <= 30) {
				printf("\nX_delta:\n");
				for (int i = 0; i < ___PROBLEM_SIZE___; i++) {
					std::cout << std::setw(12) << X_delta[i];
				}
				printf("\nX:\n");
				for (int i = 0; i < ___PROBLEM_SIZE___; i++) {
					std::cout << std::setw(12) << X[i];
				}
				
				std::cout << std::endl;
				std::cout << std::endl;
			}
			residual = MatrixUtility::ComputeResidual(X_delta, ___PROBLEM_SIZE___);
			
			printf("Residual: %f\n", residual);
			
			delete [] Y;
			delete [] Z;
			delete [] X_delta;
		}
		
		MPI_Bcast(&residual, 1, MPI_DOUBLE, ___MASTER_PROCESSOR___, MPI_COMM_WORLD);
		
	} while (residual > ___TOLERANCE___);
	
	/*
	
	if (___IS_MASTER_PROCESSOR___) {
		
		printf("\nB:\n");
		for (int i = 0; i < ___PROBLEM_SIZE___; i++) {
			std::cout << std::setw(12) << B[i];
		}
		
		printf("\nA:\n");
		MatrixUtility::PrintMatrix(A, ___PROBLEM_SIZE___, ___PROBLEM_SIZE___);
		
		printf("\nA_res:\n");
		MatrixUtility::PrintMatrix(A, ___PROBLEM_SIZE___, ___PROBLEM_SIZE___);
		
		printf("\nX:\n");
		for (int i = 0; i < ___PROBLEM_SIZE___; i++) {
			std::cout << std::setw(12) << X[i];
		}
		
		std::cout << std::endl;
	}
	 */
	
	//printf("done\n");
	
	/*------------BACKWARD SUBSTITUTION FINISHED------------*/
	
	MPI_Finalize();
	
	return 0;
}
TEST (array_copy, ZeroCount) {
	int src[5] = {0};
	int dst[5] = {1,2,3,4,5};
	EXPECT_EQ(false,array_copy(src,dst,sizeof(int),0));
}
Esempio n. 26
0
File: pi.c Progetto: abfeldman/lydia
tv_nf pi_tison_trie(const_tv_nf cf)
{
    unsigned int i, l, q, x, y, z;

    tv_nf result = truncate_copy_nf(cf);
    tv_literal_set_list input = get_literal_sets(cf);
    tv_literal_set_list output = get_literal_sets(result);
    tv_literal_set model;

    stack s, sx, sy;

    trie_node c, cx, cy;

    trie db = trie_new((trie_node_destroy_func_t)array_free,
                       (trie_node_clone_func_t)array_copy);
    for (i = 0; i < input->sz; i++) {
        array l = literal_set_to_sorted_int_list(input->arr[i]);
        if (trie_is_subsumed(db, l)) {
            array_free(l);
            continue;
        }
        trie_remove_subsumed(db, l);
        trie_add(db, l, array_copy(l));
        array_free(l);
    }
    trie_gc(db);
/* We have the literal_sets in the trie now. */

    if (db->root->edges == NULL) {
        trie_free(db);
        rfre_tv_nf(result);
        return rdup_tv_nf(cf);
    }

    for (l = 0; l < cf->variables->sz; l++) {
        sx = stack_new(NULL, NULL);
/* Outer walk. */
        stack_push(sx, db->root);
        while (NULL != (cx = stack_pop(sx))) {
            for (x = 0; x < cx->edges->sz; x++) {
                if (((trie_node)cx->kids->arr[x])->is_deleted) {
                    continue;
                }
                if (((trie_node)cx->kids->arr[x])->is_terminal) {
/* Inner walk. */
                    sy = stack_new(NULL, NULL);
                    for (q = 0; q < sx->sz; q++) {
                        stack_push(sy, sx->arr[q]);
                    }
                    stack_push(sy, cx);

/* Finish the c level. */
                    z = x + 1;
                    while (NULL != (cy = stack_pop(sy))) {
                        for (y = z; y < cy->edges->sz; y++) {
                            if (((trie_node)cy->kids->arr[y])->is_deleted) {
                                continue;
                            }
                            if (((trie_node)cy->kids->arr[y])->is_terminal) {
                                array r = resolve_int_list_literal(((trie_node)cx->kids->arr[x])->value, ((trie_node)cy->kids->arr[y])->value, l * 2);
                                if (NULL == r) {
                                    continue;
                                }
                                if (trie_is_subsumed(db, r)) {
                                    array_free(r);
                                    continue;
                                }
                                trie_remove_subsumed(db, r);
                                trie_add(db, r, array_copy(r));
                                array_free(r);
                            } 
                            if (((trie_node)cy->kids->arr[y])->edges != NULL) {
                                stack_push(sy, cy->kids->arr[y]);
                            }
                        }
                        z = 0;
                    }
                    stack_free(sy);
/* End of the inner walk. */
                }
                if (((trie_node)cx->kids->arr[x])->edges != NULL) {
                    stack_push(sx, cx->kids->arr[x]);
                }
            }
        }
/* End of the outer walk. */
        stack_free(sx);
        trie_gc(db);
    }

    assert(input->sz > 0);
    model = rdup_tv_literal_set(input->arr[0]);
    rfre_int_list(model->pos);
    rfre_int_list(model->neg);
    model->pos = int_listNIL;
    model->neg = int_listNIL;

/* Convert the trie back to a clausal form. */
    s = stack_new(NULL, NULL);
    stack_push(s, db->root);
    while (NULL != (c = stack_pop(s))) {
        for (i = 0; i < c->edges->sz; i++) {
            if (((trie_node)c->kids->arr[i])->is_terminal) {
                append_tv_literal_set_list(output, int_list_to_literal_set(((trie_node)c->kids->arr[i])->value, model));
            }
            if (((trie_node)c->kids->arr[i])->edges != NULL) {
                stack_push(s, c->kids->arr[i]);
            }
        }
    }
    stack_free(s);
    trie_free(db);

    fre_tv_literal_set(model);

    set_literal_sets(result, output);

    return result;
}
/*
*  ARRAY COPY UNIT TEST CASES
**/
TEST (array_copy, NullSrc) {
	int dst[5] = {0};
	EXPECT_EQ(false,array_copy(NULL,dst,sizeof(int),5));
}
Esempio n. 28
0
MRB_API mrb_value
mrb_ary_splice(mrb_state *mrb, mrb_value ary, mrb_int head, mrb_int len, mrb_value rpl)
{
  struct RArray *a = mrb_ary_ptr(ary);
  mrb_int alen = ARY_LEN(a);
  const mrb_value *argv;
  mrb_int argc;
  mrb_int tail;

  ary_modify(mrb, a);

  /* len check */
  if (len < 0) mrb_raisef(mrb, E_INDEX_ERROR, "negative length (%S)", mrb_fixnum_value(len));

  /* range check */
  if (head < 0) {
    head += alen;
    if (head < 0) {
      mrb_raise(mrb, E_INDEX_ERROR, "index is out of array");
    }
  }
  tail = head + len;
  if (alen < len || alen < tail) {
    len = alen - head;
  }

  /* size check */
  if (mrb_array_p(rpl)) {
    argc = RARRAY_LEN(rpl);
    argv = RARRAY_PTR(rpl);
    if (argv == ARY_PTR(a)) {
      struct RArray *r;

      if (argc > 32767) {
        mrb_raise(mrb, E_ARGUMENT_ERROR, "too big recursive splice");
      }
      r = ary_dup(mrb, a);
      argv = ARY_PTR(r);
    }
  }
  else {
    argc = 1;
    argv = &rpl;
  }
  if (head >= alen) {
    if (head > ARY_MAX_SIZE - argc) {
      mrb_raisef(mrb, E_INDEX_ERROR, "index %S too big", mrb_fixnum_value(head));
    }
    len = head + argc;
    if (len > ARY_CAPA(a)) {
      ary_expand_capa(mrb, a, head + argc);
    }
    ary_fill_with_nil(ARY_PTR(a) + alen, head - alen);
    if (argc > 0) {
      array_copy(ARY_PTR(a) + head, argv, argc);
    }
    ARY_SET_LEN(a, len);
  }
  else {
    mrb_int newlen;

    if (alen - len > ARY_MAX_SIZE - argc) {
      mrb_raisef(mrb, E_INDEX_ERROR, "index %S too big", mrb_fixnum_value(alen + argc - len));
    }
    newlen = alen + argc - len;
    if (newlen > ARY_CAPA(a)) {
      ary_expand_capa(mrb, a, newlen);
    }

    if (len != argc) {
      mrb_value *ptr = ARY_PTR(a);
      tail = head + len;
      value_move(ptr + head + argc, ptr + tail, alen - tail);
      ARY_SET_LEN(a, newlen);
    }
    if (argc > 0) {
      value_move(ARY_PTR(a) + head, argv, argc);
    }
  }
  mrb_write_barrier(mrb, (struct RBasic*)a);
  return ary;
}
Esempio n. 29
0
/** \brief Principal Components analysis.

	 \ingroup grplinalg

	 This implementation uses SVD to calculate the PCA.
	 Example:
	 \code
	 Array *X = get_data_from_somewhere();
	 Array *var, *X_pca;
	 matrix_pca( X, &var, FALSE ); // overwrite X
	 X_pca = matrix_pca( X, &var, TRUE ); // do not touch X
	 \endcode
	 \param X a 2D array observations x variables containing the data
	 \param var output: vector of eigenvalues of XX^T in decreasing order; if you
 	         pass NULL, it is ignored; 
	 \param alloc if true, new memory is allocated and returned. Else
	            X is overwritten.
	 \return pointer to the PCA'd matrix 
*/
Array* matrix_pca( Array *X, Array **var, bool alloc ){
  Array *out=NULL;
  int i,j;
  bool ismatrix;
  matrix_CHECK( ismatrix, X );
  if( !ismatrix ) return NULL;

  int N,K; /* N observations, K variables */
  N = X->size[0];
  K = X->size[1];

  Array *tmp = array_copy( X, TRUE );

  /* subtract mean from observations */
  Array *mean=matrix_mean( X, 0 ); 
  for( i=0; i<N; i++ ){ 
	 for( j=0; j<K; j++ ){
		array_INDEX2( tmp, double, i, j ) -=
		  array_INDEX1( mean, double, j );
	 }
  }

  array_scale( tmp, 1.0/sqrt((double) N-1 ) );

  gsl_matrix *A=matrix_to_gsl( tmp, TRUE ); /* copy */
  gsl_matrix *V=gsl_matrix_alloc( K, K );
  gsl_vector *S=gsl_vector_alloc( K );
  gsl_vector *workspace=gsl_vector_alloc( K );

  /* A->U, V->V, S->S */
  gsl_linalg_SV_decomp( A, V, S, workspace);
  gsl_matrix_transpose( V );

  if( var ){
	 (*var)=array_fromptr2( DOUBLE, 1, S->data, S->size );
	 S->owner=0; /* transfer ownership to array */
	 (*var)->free_data=1;
	 for( i=0; i<array_NUMEL( *var ); i++ ){ 
		array_INDEX1( *var, double, i ) = SQR( array_INDEX1( *var, double, i ) );
	 }
  }

  Array *Vp=array_fromptr2( DOUBLE, 2, V->data, V->size1, V->size2 );
  matrix_transpose( tmp, FALSE );
  out=matrix_mult( Vp, tmp ); /* PCA'd data */
  matrix_transpose( out, FALSE );

  if( out->size[0]!=X->size[0] || out->size[1]!=X->size[1] ){
	 errprintf("Input/Output dimension mismatch: (%i,%i) vs. (%i,%i)\n",
				  X->size[0], X->size[1], out->size[0], out->size[1] );
  }

  if( !alloc ){ /* write back out->X */
	 memcpy( X->data, out->data, out->nbytes );
	 array_free( out );
	 out = X;
  }

  /* clean up */
  gsl_matrix_free( A );
  gsl_matrix_free( V );
  gsl_vector_free( S );
  gsl_vector_free( workspace );
  array_free( mean );
  array_free( Vp );
  array_free( tmp );

  return out;
}
Esempio n. 30
0
	Result recursiveClosestPair(Point A_[], int _size)
	{

	Result r_;
	Result result;
	Result Left;
	Result Right;
	Result closest;
	int N;
	int ns_sequences={0};
	double xm; int i=0;int j=0; int k=0;int ns=0; double _dist;int u=0;int m=0; int h=0; int dim=0;


	int size_=0;

	Point *Left_coordinates={0};
	Point *Right_coordinates={0};
	Point *S_coordinates={0};

	r_.min_distance=(double)INT_MAX;
	result.min_distance=(double)INT_MAX;
	Left.min_distance=(double)INT_MAX;
	Right.min_distance=(double)INT_MAX;
	closest.min_distance=(double)INT_MAX;
	N= _size;
   // printf("N: %d\n",N);





	if(N<=3)
	{
		result= bruteForceClosestPair(A_,N,1);
		//counting++;
		//if(closest.min_distance==0)
			//printf ("counting : %d\n", counting);

		//print_array_with_size(A_[0],N);

		return result;
	}
	else
	{

				Right_coordinates= (Point *) malloc(sizeof(Point)* N);
				Left_coordinates= (Point *) malloc(sizeof(Point)* N);



		   if(N%2==0)
		   {
		   size_=N/2;
		   array_copy(Left_coordinates, A_,size_,0);
		    array_copy(Right_coordinates, A_,N,size_);
		   }
		   else
		   {
		   size_=(N/2)+1;
		   array_copy(Left_coordinates, A_,size_,0);
		   array_copy(Right_coordinates, A_,N,size_-1);

		   }

			//size_ = ceilf(N/2);


		   /*
         counting++;
		 if(counting==73731)
			 scanf("%d",&a);
	     printf("size_: %d  N= %d counting: %d\n",size_,N,counting);
			*/

		/*
		printf("xL:\n");
		print_array(Left_coordinates[0]);



		 printf("xR:\n");
		 print_array(Right_coordinates[0]);
		 */

		xm=A_[size_-1].coordinates[0];


           for(i=0;i<N;i++)
		     {
				 if(A_[i].coordinates[0]<=xm)
	           		{
	           			Left_coordinates[u]=A_[i];

	           			u++;

	           		}
		           	else
		           	{
		           		Right_coordinates[m]=A_[i];

		           		m++;

		           	}

	           	}



		/*
		printf("yL:\n");
		print_array(Left_coordinates[1]);



		 printf("yR:\n");
		 print_array(Right_coordinates[1]);

		 printf("zL:\n");
		print_array(Left_coordinates[2]);



		 printf("zR:\n");
		 print_array(Right_coordinates[2]);
		 */

		Left=recursiveClosestPair(Left_coordinates,size_);
		Right=recursiveClosestPair(Right_coordinates,size_);
		result= Right;


		if(Left.min_distance<Right.min_distance)
		{
			result= Left;
		}



				//free(S_coordinates[i]);
				free(Right_coordinates);
				free(Left_coordinates);




				S_coordinates= (Point *) malloc(sizeof(Point)* N);
				//Right_coordinates= (Point *) malloc(sizeof(Point)* N);
				//Left_coordinates= (Point *) malloc(sizeof(Point)* N);





		    for(i=0;i<N;i++)
		    {
		    	if(fabsf(xm-A_[i].coordinates[0])<result.min_distance)
			    {
			    	S_coordinates[j]=A_[i];

			    	j++;
		    	}

		    }
			ns_sequences=j;
			j=0;


		closest=result;



			for(i=0;i<ns_sequences-1;i++)
			{
				k=i+1;
				while(k<ns_sequences && fabsf(S_coordinates[k].coordinates[0]-S_coordinates[i].coordinates[0])<closest.min_distance)
				{

					//++;

					_dist=calculate_distance(S_coordinates[k],S_coordinates[i]);
					//if(_dist==0)
					//	printf("counting : %d\n",counting);

					if(_dist<closest.min_distance && _dist!=0 )
					{
						r_.min_distance=_dist;

						r_.p =S_coordinates[k];

						r_.q= S_coordinates[i];



						closest=r_;
					}

					k++;
				}
			}

	//counting++;
		//if(closest.min_distance==0)
			//printf ("counting : %d\n", counting);
		//free(Left_coordinates);
		//free(Right_coordinates);
		//free(S_coordinates);


				free(S_coordinates);
				//free(Right_coordinates);
				//free(Left_coordinates);



		return closest;
	}

	}