Ejemplo n.º 1
0
// Creates a new leaf by creating a node and then adapting it appropriately.
node * make_leaf( void ) {
    node * leaf = make_node();
    leaf->is_leaf = true;
    return leaf;
}
Ejemplo n.º 2
0
DFA *dfaImport(char* filename, char ***vars, int **orders)
{
  unsigned int i, numvars, bdd_nodes, ns, s;
  FILE *file;
  DFA *a;
  char ts[100];
  int ti;

  /* Read file */
  if ((file = fopen(filename, "r")) == 0) 
    return 0;

  fscanf(file,
	 "MONA DFA\n"
	 "number of variables: %u\n"
	 "variables: ", &numvars);
  if (vars) {
    *vars = (char **) mem_alloc(sizeof(char *) * (numvars + 1));
    (*vars)[numvars] = 0;
    for (i = 0; i < numvars; i++) {
      (*vars)[i] = (char *) mem_alloc(100);
      fscanf(file, " %s ", (*vars)[i]);
    }
  }
  else {
    for (i = 0; i < numvars; i++)
      fscanf(file, " %s ", ts);
  }
  fscanf(file,
	 "orders: ");
  if (orders) {
    *orders = (int *) mem_alloc(sizeof(int) * numvars);
    for (i = 0; i < numvars; i++)
      fscanf(file, " %d ", &((*orders)[i]));
  }
  else
    for (i = 0; i < numvars; i++)
      fscanf(file, " %d ", &ti);
  if (fscanf(file,
             "states: %u\n"
             "initial: %u\n"
             "bdd nodes: %u\n"
             "final:", 
             &ns, &s, &bdd_nodes) != 3) 
    return 0;
  a = dfaMake(ns);
  a->s = s;

  for (i = 0; i<a->ns; i++)
    fscanf(file, " %d", &a->f[i]);

  fscanf(file, "\nbehaviour:");
  for (i = 0; i < a->ns; i++)
    fscanf(file, " %u", &a->q[i]);

  fscanf(file, "\nbdd:\n");
  table = (BddNode *) mem_alloc(sizeof(BddNode)*bdd_nodes);
  
  for (i = 0; i < bdd_nodes; i++) {
    table[i].p = -1;
    fscanf(file, "%i %u %u\n", 
           &table[i].idx,
           &table[i].lo,
           &table[i].hi);
  }
  
  if (fgetc(file) != 'e' ||
      fgetc(file) != 'n' ||
      fgetc(file) != 'd') 
    return 0;
  fclose(file);

  /* fill bdd-manager */
  import_bddm = a->bddm;
  for (i = 0; i < a->ns; i++) 
    a->q[i] = make_node(a->q[i]);

  mem_free(table);
  return a;
}
Ejemplo n.º 3
0
/* Prepends a new key-value pair onto a list.

This is actually a synonym for make_node.
 */
Node *prepend(Hashable *key, Value *value, Node *rest)
{
    return make_node(key, value, rest);
}
Ejemplo n.º 4
0
tree
ubsan_create_data (const char *name, const location_t *ploc,
		   const struct ubsan_mismatch_data *mismatch, ...)
{
  va_list args;
  tree ret, t;
  tree fields[5];
  vec<tree, va_gc> *saved_args = NULL;
  size_t i = 0;
  location_t loc = UNKNOWN_LOCATION;

  /* Firstly, create a pointer to type descriptor type.  */
  tree td_type = ubsan_type_descriptor_type ();
  TYPE_READONLY (td_type) = 1;
  td_type = build_pointer_type (td_type);

  /* Create the structure type.  */
  ret = make_node (RECORD_TYPE);
  if (ploc != NULL)
    {
      loc = LOCATION_LOCUS (*ploc);
      fields[i] = build_decl (UNKNOWN_LOCATION, FIELD_DECL, NULL_TREE,
			      ubsan_source_location_type ());
      DECL_CONTEXT (fields[i]) = ret;
      i++;
    }

  va_start (args, mismatch);
  for (t = va_arg (args, tree); t != NULL_TREE;
       i++, t = va_arg (args, tree))
    {
      gcc_checking_assert (i < 3);
      /* Save the tree arguments for later use.  */
      vec_safe_push (saved_args, t);
      fields[i] = build_decl (UNKNOWN_LOCATION, FIELD_DECL, NULL_TREE,
			      td_type);
      DECL_CONTEXT (fields[i]) = ret;
      if (i)
	DECL_CHAIN (fields[i - 1]) = fields[i];
    }
  va_end (args);

  if (mismatch != NULL)
    {
      /* We have to add two more decls.  */
      fields[i] = build_decl (UNKNOWN_LOCATION, FIELD_DECL, NULL_TREE,
			      pointer_sized_int_node);
      DECL_CONTEXT (fields[i]) = ret;
      DECL_CHAIN (fields[i - 1]) = fields[i];
      i++;

      fields[i] = build_decl (UNKNOWN_LOCATION, FIELD_DECL, NULL_TREE,
			      unsigned_char_type_node);
      DECL_CONTEXT (fields[i]) = ret;
      DECL_CHAIN (fields[i - 1]) = fields[i];
      i++;
    }

  TYPE_FIELDS (ret) = fields[0];
  TYPE_NAME (ret) = get_identifier (name);
  layout_type (ret);

  /* Now, fill in the type.  */
  char tmp_name[32];
  static unsigned int ubsan_var_id_num;
  ASM_GENERATE_INTERNAL_LABEL (tmp_name, "Lubsan_data", ubsan_var_id_num++);
  tree var = build_decl (UNKNOWN_LOCATION, VAR_DECL, get_identifier (tmp_name),
			 ret);
  TREE_STATIC (var) = 1;
  TREE_PUBLIC (var) = 0;
  DECL_ARTIFICIAL (var) = 1;
  DECL_IGNORED_P (var) = 1;
  DECL_EXTERNAL (var) = 0;

  vec<constructor_elt, va_gc> *v;
  vec_alloc (v, i);
  tree ctor = build_constructor (ret, v);

  /* If desirable, set the __ubsan_source_location element.  */
  if (ploc != NULL)
    CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, ubsan_source_location (loc));

  size_t nelts = vec_safe_length (saved_args);
  for (i = 0; i < nelts; i++)
    {
      t = (*saved_args)[i];
      CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, t);
    }

  if (mismatch != NULL)
    {
      /* Append the pointer data.  */
      CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, mismatch->align);
      CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, mismatch->ckind);
    }

  TREE_CONSTANT (ctor) = 1;
  TREE_STATIC (ctor) = 1;
  DECL_INITIAL (var) = ctor;
  varpool_finalize_decl (var);

  return var;
}
Ejemplo n.º 5
0
/* Insert at the head of a linked list. */
node_t* insert_val(int val, node_t* cur_head) {
  node_t* new_node = make_node(val);
  new_node->next = cur_head;
  return new_node;
}
Ejemplo n.º 6
0
int main(void)
{
#if 0
	char prev_seq[] = "4213657";
	char in_seq[]   = "1234567";

	root = init(prev_seq, in_seq, 7);


	char prev_seq[] = "421356";
	char in_seq[]   = "123456";
	root = init(prev_seq, in_seq, 6);
#endif
#if 0	
	link a, b, c, d, e, f;

	a = make_node('4');
	b = make_node('2');
	c = make_node('5');
	d = make_node('1');
	e = make_node('3');
	f = make_node('6');
	
	a->l = b;
	a->r = c;
//	b->l = d;
//	b->r = e;
	f->l = d;
	c->r = f;
	d->l = e;
	root = a;
	
#endif
	
	link root = NULL;
	while(1)
	{
		char ch;
		ch = getchar();
		getchar();
		if(ch == 'q')
			break;
		root = insert(root, ch);

		printf("\\tree ");
		travels(root);
		printf("\n");
		fflush(stdout);
	}
	printf("........\n");
	while(1)
	{
		char ch = getchar();
		getchar();
		if(ch == '0')
			break;
		link p = search(root, ch);
		if(p != NULL)
			printf("%c is found\n", ch);
		else
			printf("not found\n");
	}
	int count = 0;
	count = depth(root);	
	printf("count = %d\n", count);
	int i = pingheng(root);
	printf("%d\n", i);

	return 0;
}
Ejemplo n.º 7
0
// Add a new element to the beginning of the list.
void push(Node **head, int val) {
    Node *nuNode = make_node(val, *head);
    *head = nuNode;
}
Ejemplo n.º 8
0
node *make_terminating_node(char d){
  return make_node(d,0);
}
Ejemplo n.º 9
0
node *insert_front(node *first_element, node new_element){
  return make_node(new_element.data, first_element);
}
Ejemplo n.º 10
0
static void
create_common (gfc_common_head *com, segment_info *head, bool saw_equiv)
{
  segment_info *s, *next_s;
  tree union_type;
  tree *field_link;
  tree field;
  tree field_init = NULL_TREE;
  record_layout_info rli;
  tree decl;
  bool is_init = false;
  bool is_saved = false;

  /* Declare the variables inside the common block.
     If the current common block contains any equivalence object, then
     make a UNION_TYPE node, otherwise RECORD_TYPE. This will let the
     alias analyzer work well when there is no address overlapping for
     common variables in the current common block.  */
  if (saw_equiv)
    union_type = make_node (UNION_TYPE);
  else
    union_type = make_node (RECORD_TYPE);

  rli = start_record_layout (union_type);
  field_link = &TYPE_FIELDS (union_type);

  /* Check for overlapping initializers and replace them with a single,
     artificial field that contains all the data.  */
  if (saw_equiv)
    field = get_init_field (head, union_type, &field_init, rli);
  else
    field = NULL_TREE;

  if (field != NULL_TREE)
    {
      is_init = true;
      *field_link = field;
      field_link = &DECL_CHAIN (field);
    }

  for (s = head; s; s = s->next)
    {
      build_field (s, union_type, rli);

      /* Link the field into the type.  */
      *field_link = s->field;
      field_link = &DECL_CHAIN (s->field);

      /* Has initial value.  */
      if (s->sym->value)
        is_init = true;

      /* Has SAVE attribute.  */
      if (s->sym->attr.save)
        is_saved = true;
    }

  finish_record_layout (rli, true);

  if (com)
    decl = build_common_decl (com, union_type, is_init);
  else
    decl = build_equiv_decl (union_type, is_init, is_saved);

  if (is_init)
    {
      tree ctor, tmp;
      vec<constructor_elt, va_gc> *v = NULL;

      if (field != NULL_TREE && field_init != NULL_TREE)
	CONSTRUCTOR_APPEND_ELT (v, field, field_init);
      else
	for (s = head; s; s = s->next)
	  {
	    if (s->sym->value)
	      {
		/* Add the initializer for this field.  */
		tmp = gfc_conv_initializer (s->sym->value, &s->sym->ts,
					    TREE_TYPE (s->field),
					    s->sym->attr.dimension,
					    s->sym->attr.pointer
					    || s->sym->attr.allocatable, false);

		CONSTRUCTOR_APPEND_ELT (v, s->field, tmp);
	      }
	  }

      gcc_assert (!v->is_empty ());
      ctor = build_constructor (union_type, v);
      TREE_CONSTANT (ctor) = 1;
      TREE_STATIC (ctor) = 1;
      DECL_INITIAL (decl) = ctor;

#ifdef ENABLE_CHECKING
      {
	tree field, value;
	unsigned HOST_WIDE_INT idx;
	FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), idx, field, value)
	  gcc_assert (TREE_CODE (field) == FIELD_DECL);
      }
#endif
    }

  /* Build component reference for each variable.  */
  for (s = head; s; s = next_s)
    {
      tree var_decl;

      var_decl = build_decl (s->sym->declared_at.lb->location,
			     VAR_DECL, DECL_NAME (s->field),
			     TREE_TYPE (s->field));
      TREE_STATIC (var_decl) = TREE_STATIC (decl);
      /* Mark the variable as used in order to avoid warnings about
	 unused variables.  */
      TREE_USED (var_decl) = 1;
      if (s->sym->attr.use_assoc)
	DECL_IGNORED_P (var_decl) = 1;
      if (s->sym->attr.target)
	TREE_ADDRESSABLE (var_decl) = 1;
      /* Fake variables are not visible from other translation units. */
      TREE_PUBLIC (var_decl) = 0;
      gfc_finish_decl_attrs (var_decl, &s->sym->attr);

      /* To preserve identifier names in COMMON, chain to procedure
         scope unless at top level in a module definition.  */
      if (com
          && s->sym->ns->proc_name
          && s->sym->ns->proc_name->attr.flavor == FL_MODULE)
	var_decl = pushdecl_top_level (var_decl);
      else
	gfc_add_decl_to_function (var_decl);

      SET_DECL_VALUE_EXPR (var_decl,
			   fold_build3_loc (input_location, COMPONENT_REF,
					    TREE_TYPE (s->field),
					    decl, s->field, NULL_TREE));
      DECL_HAS_VALUE_EXPR_P (var_decl) = 1;
      GFC_DECL_COMMON_OR_EQUIV (var_decl) = 1;

      if (s->sym->attr.assign)
	{
	  gfc_allocate_lang_decl (var_decl);
	  GFC_DECL_ASSIGN (var_decl) = 1;
	  GFC_DECL_STRING_LEN (var_decl) = GFC_DECL_STRING_LEN (s->field);
	  GFC_DECL_ASSIGN_ADDR (var_decl) = GFC_DECL_ASSIGN_ADDR (s->field);
	}

      s->sym->backend_decl = var_decl;

      next_s = s->next;
      free (s);
    }
}
Ejemplo n.º 11
0
SEXP glm_sampleworep(SEXP Y, SEXP X, SEXP Roffset, SEXP Rweights,
		     SEXP Rprobinit, SEXP Rmodeldim,
		     SEXP modelprior, SEXP betaprior,SEXP Rbestmodel,  SEXP plocal,
		     SEXP family, SEXP Rcontrol,
		     SEXP Rupdate, SEXP Rlaplace, SEXP Rparents) {
	int nProtected = 0;

	int nModels=LENGTH(Rmodeldim);

	//  Rprintf("Allocating Space for %d Models\n", nModels) ;


	SEXP ANS = PROTECT(allocVector(VECSXP, 14)); ++nProtected;
	SEXP ANS_names = PROTECT(allocVector(STRSXP, 14)); ++nProtected;
	SEXP Rprobs = PROTECT(duplicate(Rprobinit)); ++nProtected;
	SEXP R2 = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
	SEXP shrinkage = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
	SEXP modelspace = PROTECT(allocVector(VECSXP, nModels)); ++nProtected;
	SEXP modeldim =  PROTECT(duplicate(Rmodeldim)); ++nProtected;
	SEXP beta = PROTECT(allocVector(VECSXP, nModels)); ++nProtected;
	SEXP se = PROTECT(allocVector(VECSXP, nModels)); ++nProtected;
	SEXP deviance = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
	SEXP modelprobs = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
	SEXP priorprobs = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
	SEXP logmarg = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
	SEXP sampleprobs = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
	SEXP Q = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
	SEXP Rintercept = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;

	double *probs,logmargy, shrinkage_m;
	int i;

	glmstptr *glmfamily;
	glmfamily = make_glmfamily_structure(family);

	betapriorptr *betapriorfamily;
	betapriorfamily = make_betaprior_structure(betaprior, family);


	//get dimsensions of all variables
	int p = INTEGER(getAttrib(X,R_DimSymbol))[1];
	int k = LENGTH(modelprobs);

	int update = INTEGER(Rupdate)[0];
	double eps = DBL_EPSILON;
	double problocal = REAL(plocal)[0];

	struct Var *vars = (struct Var *) R_alloc(p, sizeof(struct Var)); // Info about the model variables.
	probs =  REAL(Rprobs);
	int n = sortvars(vars, probs, p);

	int *model = ivecalloc(p);
	/* fill in the sure things */
	for (i = n; i < p; i++)  {
		model[vars[i].index] = (int) vars[i].prob;
	}

	GetRNGstate();

	NODEPTR tree, branch;
	tree = make_node(vars[0].prob);
	//	Rprintf("For m=0, Initialize Tree with initial Model\n");

	int m = 0;
	int *bestmodel = INTEGER(Rbestmodel);
	for (i = n; i < p; i++)  {
		model[vars[i].index] = bestmodel[vars[i].index];
		INTEGER(modeldim)[m]  +=  bestmodel[vars[i].index];
	}

	double *pigamma = vecalloc(p);
	branch = tree;
	CreateTree_with_pigamma(branch, vars, bestmodel, model, n, m, modeldim,pigamma, Rparents);

	branch=tree;
	Substract_visited_probability_mass(branch, vars, model, n, m, pigamma,eps);

	int pmodel = INTEGER(modeldim)[m];
	SEXP Rmodel_m =	PROTECT(allocVector(INTSXP,pmodel));
	GetModel_m(Rmodel_m, model, p);
	//evaluate logmargy and shrinkage
	SEXP glm_fit = PROTECT(glm_FitModel(X, Y, Rmodel_m, Roffset, Rweights,
					    glmfamily, Rcontrol, Rlaplace,
					    betapriorfamily));
	double prior_m  = compute_prior_probs(model,pmodel,p, modelprior);
	logmargy = REAL(getListElement(getListElement(glm_fit, "lpy"),"lpY"))[0];
	shrinkage_m = REAL(getListElement(getListElement(glm_fit, "lpy"),
					"shrinkage"))[0];

	SetModel2(logmargy, shrinkage_m, prior_m, sampleprobs, logmarg, shrinkage, priorprobs, m);
	SetModel1(glm_fit, Rmodel_m, beta, se, modelspace, deviance, R2, Q,Rintercept, m);

	UNPROTECT(2);

	int *modelwork= ivecalloc(p);

	// sample models
	for (m = 1;  m < k  && pigamma[0] < 1.0; m++) {
	  INTEGER(modeldim)[m] = 0.0;
		for (i = n; i < p; i++)  {
			INTEGER(modeldim)[m]  +=  model[vars[i].index];
		}

		branch = tree;
		GetNextModel_swop(branch, vars, model, n, m, pigamma, problocal,
                      modeldim, bestmodel,Rparents);

		/* Now subtract off the visited probability mass. */
		branch=tree;
		Substract_visited_probability_mass(branch, vars, model, n, m, pigamma,eps);

		/* Now get model specific calculations */
		pmodel = INTEGER(modeldim)[m];
		PROTECT(Rmodel_m = allocVector(INTSXP,pmodel));
		memset(INTEGER(Rmodel_m), 0, pmodel * sizeof(int));
		GetModel_m(Rmodel_m, model, p);

		glm_fit = PROTECT(glm_FitModel(X, Y, Rmodel_m, Roffset, Rweights,
					       glmfamily, Rcontrol, Rlaplace,
					       betapriorfamily));
		prior_m = compute_prior_probs(model,pmodel,p, modelprior);
		logmargy = REAL(getListElement(getListElement(glm_fit, "lpy"),"lpY"))[0];
		shrinkage_m = REAL(getListElement(getListElement(glm_fit, "lpy"),
					"shrinkage"))[0];

		SetModel2(logmargy, shrinkage_m, prior_m, sampleprobs, logmarg, shrinkage, priorprobs, m);
		SetModel1(glm_fit, Rmodel_m, beta, se, modelspace, deviance, R2,Q,Rintercept, m);
		UNPROTECT(2);

		REAL(sampleprobs)[m] = pigamma[0];

		//update best model

		//update marginal inclusion probs
		if (m > 1) {
			double mod;
			double rem = modf((double) m/(double) update, &mod);
			if (rem  == 0.0) {
				int mcurrent = m;
				compute_modelprobs(modelprobs, logmarg, priorprobs,mcurrent);
				compute_margprobs(modelspace, modeldim, modelprobs, probs, mcurrent, p);
				if (update_probs(probs, vars, mcurrent, k, p) == 1) {
				  //					Rprintf("Updating Model Tree %d \n", m);
					update_tree(modelspace, tree, modeldim, vars, k,p,n,mcurrent, modelwork);
				}
			}
		}
	}

	if (m < k) {
	  // resize if constraints have reduced the number of models
	  k = m;
	  SETLENGTH(modelspace, m);
	  SETLENGTH(logmarg, m);
	  SETLENGTH(modelprobs, m);
	  SETLENGTH(priorprobs, m);
	  SETLENGTH(sampleprobs, m);
	  SETLENGTH(beta, m);
	  SETLENGTH(se, m);
	  SETLENGTH(deviance, m);
	  SETLENGTH(Q, m);
	  SETLENGTH(Rintercept, m);
	  SETLENGTH(shrinkage, m);
	  SETLENGTH(modeldim, m);
	  SETLENGTH(R2, m);
	}

	compute_modelprobs(modelprobs, logmarg, priorprobs,k);
	compute_margprobs(modelspace, modeldim, modelprobs, probs, k, p);

	SET_VECTOR_ELT(ANS, 0, Rprobs);
	SET_STRING_ELT(ANS_names, 0, mkChar("probne0"));

	SET_VECTOR_ELT(ANS, 1, modelspace);
	SET_STRING_ELT(ANS_names, 1, mkChar("which"));

	SET_VECTOR_ELT(ANS, 2, logmarg);
	SET_STRING_ELT(ANS_names, 2, mkChar("logmarg"));

	SET_VECTOR_ELT(ANS, 3, modelprobs);
	SET_STRING_ELT(ANS_names, 3, mkChar("postprobs"));

	SET_VECTOR_ELT(ANS, 4, priorprobs);
	SET_STRING_ELT(ANS_names, 4, mkChar("priorprobs"));

	SET_VECTOR_ELT(ANS, 5,sampleprobs);
	SET_STRING_ELT(ANS_names, 5, mkChar("sampleprobs"));

	SET_VECTOR_ELT(ANS, 6, deviance);
	SET_STRING_ELT(ANS_names, 6, mkChar("deviance"));

	SET_VECTOR_ELT(ANS, 7, beta);
	SET_STRING_ELT(ANS_names, 7, mkChar("mle"));

	SET_VECTOR_ELT(ANS, 8, se);
	SET_STRING_ELT(ANS_names, 8, mkChar("mle.se"));

	SET_VECTOR_ELT(ANS, 9, shrinkage);
	SET_STRING_ELT(ANS_names, 9, mkChar("shrinkage"));

	SET_VECTOR_ELT(ANS, 10, modeldim);
	SET_STRING_ELT(ANS_names, 10, mkChar("size"));

	SET_VECTOR_ELT(ANS, 11, R2);
	SET_STRING_ELT(ANS_names, 11, mkChar("R2"));

	SET_VECTOR_ELT(ANS, 12, Q);
	SET_STRING_ELT(ANS_names, 12, mkChar("Q"));

	SET_VECTOR_ELT(ANS, 13, Rintercept);
	SET_STRING_ELT(ANS_names, 13, mkChar("intercept"));

	setAttrib(ANS, R_NamesSymbol, ANS_names);
	PutRNGstate();

	UNPROTECT(nProtected);
	return(ANS);
}
Ejemplo n.º 12
0
struct node * add_node_r(struct node * here,int new_entry,int * work_needed)
{
  
  if(here==NULL)
    {
      *work_needed = 1;
      return make_node(new_entry);
    }
  
  if(new_entry<here->entry)
    {
      here->left = add_node_r(here->left,new_entry,work_needed);
      if(*work_needed)
	{
	  switch(here->balance)
	    {
	    case -1:
	      here->balance=0;
	      *work_needed=0;
	      return here;
	    case 0:
	      here->balance=1;
	      //*work_needed=1 already, doesn't need to be set.
	      return here;
	    case 1:
	      if(here->left->balance==1)
		here=rotate_ll(here);
	      else
		here=rotate_lr(here);
	      *work_needed=0;
	      return here;
	    }
	}
    }
  else
    {
      here->right =add_node_r(here->right,new_entry,work_needed);
      if(*work_needed)
	{
	  switch(here->balance)
	    {
	    case 1:
	      here->balance=0;
	      *work_needed=0;
	      return here;
	    case 0:
	      here->balance=-1;
	      return here;
	    case -1: 
	      if(here->right->balance==-1)
		here=rotate_rr(here);
	      else 
		here=rotate_rl(here);
	      *work_needed=0;
	      return here;
	    }
	}
    }
  
  return here;

}
SkipSet* make_skipset() {
	SkipSet* ss = (SkipSet *)malloc(sizeof(SkipSet));
	ss->header = make_node(MAX_LEVEL, -1000000000);
	ss->level = 0;
	return ss;
}
Ejemplo n.º 14
0
// Inserts a new key and pointer to a node into a node, causing the node's size to exceed
// the order, and causing the node to split into two.
node * insert_into_node_after_splitting(node * root, node * old_node, int left_index,
        int key, node * right) {
 
    int i, j, split, k_prime;
    node * new_node, * child;
    int * temp_keys;
    node ** temp_pointers;
 
    /* First create a temporary set of keys and pointers
     * to hold everything in order, including
     * the new key and pointer, inserted in their
     * correct places.
     * Then create a new node and copy half of the
     * keys and pointers to the old node and
     * the other half to the new.
     */
 
    temp_pointers = malloc( (order + 1) * sizeof(node *) );
    if (temp_pointers == NULL) {
        perror("Temporary pointers array for splitting nodes.");
        exit(EXIT_FAILURE);
    }
    temp_keys = malloc( order * sizeof(int) );
    if (temp_keys == NULL) {
        perror("Temporary keys array for splitting nodes.");
        exit(EXIT_FAILURE);
    }
 
    for (i = 0, j = 0; i < old_node->num_keys + 1; i++, j++) {
        if (j == left_index + 1) j++;
        temp_pointers[j] = old_node->pointers[i];
    }
 
    for (i = 0, j = 0; i < old_node->num_keys; i++, j++) {
        if (j == left_index) j++;
        temp_keys[j] = old_node->keys[i];
    }
 
    temp_pointers[left_index + 1] = right;
    temp_keys[left_index] = key;
 
    /* Create the new node and copy
     * half the keys and pointers to the
     * old and half to the new.
     */
    split = cut(order);
    new_node = make_node();
    old_node->num_keys = 0;
    for (i = 0; i < split - 1; i++) {
        old_node->pointers[i] = temp_pointers[i];
        old_node->keys[i] = temp_keys[i];
        old_node->num_keys++;
    }
    old_node->pointers[i] = temp_pointers[i];
    k_prime = temp_keys[split - 1];
    for (++i, j = 0; i < order; i++, j++) {
        new_node->pointers[j] = temp_pointers[i];
        new_node->keys[j] = temp_keys[i];
        new_node->num_keys++;
    }
    new_node->pointers[j] = temp_pointers[i];
    free(temp_pointers);
    free(temp_keys);
    new_node->parent = old_node->parent;
    for (i = 0; i <= new_node->num_keys; i++) {
        child = new_node->pointers[i];
        child->parent = new_node;
    }
 
    /* Insert a new key into the parent of the two
     * nodes resulting from the split, with
     * the old node to the left and the new to the right.
     */
 
    return insert_into_parent(root, old_node, k_prime, new_node);
}
Ejemplo n.º 15
0
trie make_trie() {
  return make_node('\0', 26);
}
Ejemplo n.º 16
0
SEXP amcmc(SEXP Y, SEXP X,  SEXP Rweights, SEXP Rprobinit, SEXP Rmodeldim, SEXP incint, SEXP Ralpha,SEXP method, SEXP modelprior, SEXP Rupdate, SEXP Rbestmodel, SEXP plocal, SEXP BURNIN_Iterations, SEXP MCMC_Iterations, SEXP LAMBDA, SEXP DELTA)
{
  SEXP   Rse_m, Rcoef_m, Rmodel_m; 

  SEXP   RXwork = PROTECT(duplicate(X)), RYwork = PROTECT(duplicate(Y));

  int nProtected = 2, nUnique=0, newmodel=0;
  int nModels=LENGTH(Rmodeldim);
  
  //  Rprintf("Allocating Space for %d Models\n", nModels) ;
  SEXP ANS = PROTECT(allocVector(VECSXP, 15)); ++nProtected;
  SEXP ANS_names = PROTECT(allocVector(STRSXP, 15)); ++nProtected;
  SEXP Rprobs = PROTECT(duplicate(Rprobinit)); ++nProtected;
  SEXP MCMCprobs= PROTECT(duplicate(Rprobinit)); ++nProtected;
  SEXP R2 = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
  SEXP shrinkage = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
  SEXP modelspace = PROTECT(allocVector(VECSXP, nModels)); ++nProtected;
  SEXP modeldim =  PROTECT(duplicate(Rmodeldim)); ++nProtected;
  SEXP counts =  PROTECT(duplicate(Rmodeldim)); ++nProtected;
  SEXP beta = PROTECT(allocVector(VECSXP, nModels)); ++nProtected;
  SEXP se = PROTECT(allocVector(VECSXP, nModels)); ++nProtected;
  SEXP mse = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
  SEXP modelprobs = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
  SEXP priorprobs = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
  SEXP logmarg = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
  SEXP sampleprobs = PROTECT(allocVector(REALSXP, nModels)); ++nProtected;
  SEXP NumUnique = PROTECT(allocVector(INTSXP, 1)); ++nProtected;

  double *Xwork, *Ywork, *wts, *coefficients,*probs, shrinkage_m, *MCMC_probs,
    SSY, yty, mse_m, *se_m, MH=0.0, prior_m=1.0, *real_model, prob_i,
    R2_m, RSquareFull, alpha, prone, denom, logmargy, postold, postnew;
  int nobs, p, k, i, j, m, n, l, pmodel, pmodel_old, *xdims, *model_m, *bestmodel, *varin, *varout;
  int mcurrent,  update, n_sure;
  double  mod, rem, problocal, *pigamma, pigammaold, pigammanew, eps, *hyper_parameters;
  double *XtX, *XtY, *XtXwork, *XtYwork, *SSgam, *Cov, *priorCov, *marg_probs;
  double one=1.0, lambda,  delta, wt = 1.0; 
 
  int inc=1, print = 0;
  int *model, *modelold, bit, *modelwork, old_loc, new_loc;	
  struct Var *vars;	/* Info about the model variables. */
  NODEPTR tree, branch;

  /* get dimsensions of all variables */


  nobs = LENGTH(Y);
  xdims = INTEGER(getAttrib(X,R_DimSymbol));
  p = xdims[1];
  k = LENGTH(modelprobs);
  update = INTEGER(Rupdate)[0];
  lambda=REAL(LAMBDA)[0];
  delta = REAL(DELTA)[0];
  //  Rprintf("delta %f lambda %f", delta, lambda);
  eps = DBL_EPSILON;
  problocal = REAL(plocal)[0];
  //  Rprintf("Update %i and prob.switch %f\n", update, problocal);
  /* Extract prior on models  */
  hyper_parameters = REAL(getListElement(modelprior,"hyper.parameters"));

  /*  Rprintf("n %d p %d \n", nobs, p);  */

  Ywork = REAL(RYwork);
  Xwork = REAL(RXwork);
  wts = REAL(Rweights);
 
  PrecomputeData(Xwork, Ywork, wts, &XtXwork, &XtYwork, &XtX, &XtY, &yty, &SSY, p, nobs);

  alpha = REAL(Ralpha)[0];

  vars = (struct Var *) R_alloc(p, sizeof(struct Var));
  probs =  REAL(Rprobs);
  n = sortvars(vars, probs, p); 

  for (i =0; i <n; i++) REAL(MCMCprobs)[vars[i].index] = 0.0;
  MCMC_probs =  REAL(MCMCprobs);


  pigamma = vecalloc(p);
  real_model = vecalloc(n);
  marg_probs = vecalloc(n);
  modelold = ivecalloc(p);
  model = ivecalloc(p);
  modelwork= ivecalloc(p);
  varin= ivecalloc(p);
  varout= ivecalloc(p);


  /* create gamma gamma' matrix */
  SSgam  = (double *) R_alloc(n * n, sizeof(double));
  Cov  = (double *) R_alloc(n * n, sizeof(double));
  priorCov  = (double *) R_alloc(n * n, sizeof(double));
  for (j=0; j < n; j++) {
    for (i = 0; i < n; i++) {
      SSgam[j*n + i] = 0.0;
      Cov[j*n + i] = 0.0;
      priorCov[j*n + i] = 0.0;
      if (j == i)  priorCov[j*n + i] = lambda;
    }
    marg_probs[i] = 0.0;
  }


  /* Make space for the models and working variables. */ 

  /*  pivot = ivecalloc(p); 
  qraux = vecalloc(p);
  work =  vecalloc(2 * p);
  effects = vecalloc(nobs); 
  v =  vecalloc(p * p); 
  betaols = vecalloc(p);
  */

 

  /*  Rprintf("Fit Full Model\n"); */

  if (nobs <= p) {RSquareFull = 1.0;}
  else {
    PROTECT(Rcoef_m = NEW_NUMERIC(p));
    PROTECT(Rse_m = NEW_NUMERIC(p));
    coefficients = REAL(Rcoef_m);  
    se_m = REAL(Rse_m);
    memcpy(coefficients, XtY,  p*sizeof(double));
    memcpy(XtXwork, XtX, p*p*sizeof(double));
    memcpy(XtYwork, XtY,  p*sizeof(double));

    mse_m = yty; 
    cholreg(XtYwork, XtXwork, coefficients, se_m, &mse_m, p, nobs);  

  /*olsreg(Ywork, Xwork,  coefficients, se_m, &mse_m, &p, &nobs, pivot,qraux,work,residuals,effects,v, betaols); */
    RSquareFull =  1.0 - (mse_m * (double) ( nobs - p))/SSY;
    UNPROTECT(2);
  }


  /* fill in the sure things */
  for (i = n, n_sure = 0; i < p; i++)  {
      model[vars[i].index] = (int) vars[i].prob;
      if (model[vars[i].index] == 1) ++n_sure;
  }


  GetRNGstate();
  tree = make_node(-1.0);

  /*  Rprintf("For m=0, Initialize Tree with initial Model\n");  */

  m = 0;
  bestmodel = INTEGER(Rbestmodel);

  INTEGER(modeldim)[m] = n_sure;

  /* Rprintf("Create Tree\n"); */
   branch = tree;

   for (i = 0; i< n; i++) {
      bit =  bestmodel[vars[i].index];
      if (bit == 1) {
	if (i < n-1 && branch->one == NULL) 
	  branch->one = make_node(-1.0);
	if (i == n-1 && branch->one == NULL)
	  branch->one = make_node(0.0);
	branch = branch->one;
      }
      else {
	if (i < n-1 && branch->zero == NULL)
	  branch->zero = make_node(-1.0);
	if (i == n-1 && branch->zero == NULL)
	  branch->zero = make_node(0.0);
	branch = branch->zero;
      } 
      
      model[vars[i].index] = bit; 
      INTEGER(modeldim)[m]  += bit;
      branch->where = 0;
   }
  


    /*    Rprintf("Now get model specific calculations \n"); */
 
    pmodel = INTEGER(modeldim)[m];
    PROTECT(Rmodel_m = allocVector(INTSXP,pmodel));
    model_m = INTEGER(Rmodel_m);

      for (j = 0, l=0; j < p; j++) {  
	if (model[j] == 1) {
            model_m[l] = j;
           l +=1;}
      }

    SET_ELEMENT(modelspace, m, Rmodel_m);

    Rcoef_m = NEW_NUMERIC(pmodel); PROTECT(Rcoef_m);
    Rse_m = NEW_NUMERIC(pmodel);   PROTECT(Rse_m);
    coefficients = REAL(Rcoef_m);  
    se_m = REAL(Rse_m);

      for (j=0, l=0; j < pmodel; j++) {
        XtYwork[j] = XtY[model_m[j]];
        for  ( i = 0; i < pmodel; i++) {
	  XtXwork[j*pmodel + i] = XtX[model_m[j]*p + model_m[i]];
	}
      } 

      
    mse_m = yty; 
    memcpy(coefficients, XtYwork, sizeof(double)*pmodel); 
    cholreg(XtYwork, XtXwork, coefficients, se_m, &mse_m, pmodel, nobs);  

    R2_m = 1.0 - (mse_m * (double) ( nobs - pmodel))/SSY;

    SET_ELEMENT(beta, m, Rcoef_m);
    SET_ELEMENT(se, m, Rse_m);

    REAL(R2)[m] = R2_m;
    REAL(mse)[m] = mse_m;

    gexpectations(p, pmodel, nobs, R2_m, alpha, INTEGER(method)[0], RSquareFull, SSY, &logmargy, &shrinkage_m);
    REAL(sampleprobs)[m] = 1.0;
    REAL(logmarg)[m] = logmargy;
    REAL(shrinkage)[m] = shrinkage_m;
    prior_m = compute_prior_probs(model,pmodel,p, modelprior);
    REAL(priorprobs)[m] = prior_m;

    UNPROTECT(3);


    old_loc = 0;
    pmodel_old = pmodel;
    nUnique=1;
    INTEGER(counts)[0] = 0;
    postold =  REAL(logmarg)[m] + log(REAL(priorprobs)[m]);
    memcpy(modelold, model, sizeof(int)*p);
  /*   Rprintf("model %d max logmarg %lf\n", m, REAL(logmarg)[m]); */

    /*  Rprintf("Now Sample the Rest of the Models \n");  */
    
  
  m = 0;

  //  Need to fix in case the number of sampled models exceeds the space! 
  while (m < INTEGER(BURNIN_Iterations)[0]) {

    memcpy(model, modelold, sizeof(int)*p);
    pmodel =  n_sure;
    MH = 1.0;

    if (pmodel_old == n_sure || pmodel_old == n_sure + n){
	MH =  random_walk(model, vars,  n);
	MH =  1.0 - problocal;
    }
    else {
      if (unif_rand() < problocal) {
      // random
	MH =  random_switch(model, vars, n, pmodel_old, varin, varout );
      }
      else {
      // Randomw walk proposal flip bit//
	MH =  random_walk(model, vars,  n);
      }
    }
    
    branch = tree;
    newmodel= 0;

    for (i = 0; i< n; i++) {
      bit =  model[vars[i].index];
      
      if (bit == 1) {
	if (branch->one != NULL) branch = branch->one;
	else newmodel = 1;
	}
      else {
	if (branch->zero != NULL)  branch = branch->zero;
	else newmodel = 1.0;
      } 
      pmodel  += bit;
    }

    if (pmodel  == n_sure || pmodel == n + n_sure)  MH = 1.0/(1.0 - problocal);

    if (newmodel == 1) {
      new_loc = nUnique;
      PROTECT(Rmodel_m = allocVector(INTSXP,pmodel));
      model_m = INTEGER(Rmodel_m);
      for (j = 0, l=0; j < p; j++) {  
	if (model[j] == 1) {
	  model_m[l] = j;
	  l +=1;}
      }	

      Rcoef_m = NEW_NUMERIC(pmodel); PROTECT(Rcoef_m);
      Rse_m = NEW_NUMERIC(pmodel);   PROTECT(Rse_m);
      coefficients = REAL(Rcoef_m);  
      se_m = REAL(Rse_m);
      for (j=0, l=0; j < pmodel; j++) {
        XtYwork[j] = XtY[model_m[j]];
        for  ( i = 0; i < pmodel; i++) {
	  XtXwork[j*pmodel + i] = XtX[model_m[j]*p + model_m[i]];
	}	
      }	 

      mse_m = yty; 
      memcpy(coefficients, XtYwork, sizeof(double)*pmodel); 
      cholreg(XtYwork, XtXwork, coefficients, se_m, &mse_m, pmodel, nobs);  

      R2_m = 1.0 - (mse_m * (double) ( nobs - pmodel))/SSY;
      prior_m = compute_prior_probs(model,pmodel,p, modelprior);
      gexpectations(p, pmodel, nobs, R2_m, alpha, INTEGER(method)[0], RSquareFull, SSY, &logmargy, &shrinkage_m);
      postnew = logmargy + log(prior_m);
    }
    else {
      new_loc = branch->where;
      postnew =  REAL(logmarg)[new_loc] + log(REAL(priorprobs)[new_loc]);      
    } 

    MH *= exp(postnew - postold);
    //    Rprintf("MH new %lf old %lf\n", postnew, postold);
    if (unif_rand() < MH) {

      if (newmodel == 1)  {
	new_loc = nUnique;
	insert_model_tree(tree, vars, n, model, nUnique);

	INTEGER(modeldim)[nUnique] = pmodel;
	SET_ELEMENT(modelspace, nUnique, Rmodel_m);

	SET_ELEMENT(beta, nUnique, Rcoef_m);
	SET_ELEMENT(se, nUnique, Rse_m);

	REAL(R2)[nUnique] = R2_m;
	REAL(mse)[nUnique] = mse_m;
	REAL(sampleprobs)[nUnique] = 1.0;
	REAL(logmarg)[nUnique] = logmargy;
	REAL(shrinkage)[nUnique] = shrinkage_m;
	REAL(priorprobs)[nUnique] = prior_m;
	UNPROTECT(3);
	++nUnique; 
      }

      old_loc = new_loc;
      postold = postnew;
      pmodel_old = pmodel;
      memcpy(modelold, model, sizeof(int)*p);
    }
    else  {
      if (newmodel == 1) UNPROTECT(3);
    }

    INTEGER(counts)[old_loc] += 1;
    
    for (i = 0; i < n; i++) {
     real_model[i] = (double) modelold[vars[i].index];
     REAL(MCMCprobs)[vars[i].index] += (double) modelold[vars[i].index];
   }

   // Update SSgam = gamma gamma^T + SSgam 
   F77_NAME(dsyr)("U", &n,  &one, &real_model[0], &inc,  &SSgam[0], &n);
   m++;
  }
  
  //  Rprintf("\n%d Unique models sampled during burnin\n", nUnique);


// Compute marginal probabilities  
  mcurrent = nUnique;
  compute_modelprobs(modelprobs, logmarg, priorprobs,mcurrent);
  compute_margprobs(modelspace, modeldim, modelprobs, probs, mcurrent, p);        
  for (i = 0; i < n; i++) {
    marg_probs[i] = wt*(REAL(MCMCprobs)[vars[i].index]/ (double) m) + 
      (1.0 - wt)* probs[vars[i].index];
  }	
  //  print=1;
  update_Cov(Cov, priorCov, SSgam, marg_probs, n, m, print);
 
// Global-Proposal
// Initialize post old proposal
 pigammaold = 0.0;
 for (i = 0; i < n; i++) {
   if (modelold[vars[i].index] == 1 ){	
     real_model[i] = 1.0;
     pigammaold += log(cond_prob(real_model,i, n, marg_probs,Cov, delta));
   }
   else {
     real_model[i] = 0.0;
     pigammaold += log(1.0 - cond_prob(real_model,i, n, marg_probs,Cov, delta));
   }
 }
 
//  need to fix to make sure that nUnique is less than nModels 

 while (m < INTEGER(BURNIN_Iterations)[0] + INTEGER(MCMC_Iterations)[0]) {  
      // for (m = 0; m < k; m++) {
   memcpy(model, modelold, sizeof(int)*p);
   pmodel =  n_sure;
   MH = 1.0;
   pigammanew = 0.0;
   branch = tree;
   newmodel = 0;
   for (i = 0; i < n; i++) {
     prob_i = cond_prob(real_model,i, n, marg_probs,Cov,delta);
     bit =  withprob(prob_i);
     
     if (bit == 1) {
       pigammanew += log(prob_i);
       if (branch->one != NULL) branch = branch->one;
       else newmodel= 1;
     }
     else {
       pigammanew += log(1.0 - prob_i);
       if (branch->zero != NULL) branch = branch->zero;
       else newmodel= 1;
     } 
     model[vars[i].index] = bit; 
     real_model[i] = (double) bit;
     pmodel  += bit;
   }
   if (newmodel == 1) {
     new_loc = nUnique;
     PROTECT(Rmodel_m = allocVector(INTSXP,pmodel));
     model_m = INTEGER(Rmodel_m);
     for (j = 0, l=0; j < p; j++) {  
       if (model[j] == 1) {
	 model_m[l] = j;
	 l +=1;}
     }	

     Rcoef_m = NEW_NUMERIC(pmodel); PROTECT(Rcoef_m);
     Rse_m = NEW_NUMERIC(pmodel);   PROTECT(Rse_m);
     coefficients = REAL(Rcoef_m);  
     se_m = REAL(Rse_m);
     for (j=0, l=0; j < pmodel; j++) {
       XtYwork[j] = XtY[model_m[j]];
       for  ( i = 0; i < pmodel; i++) {
	 XtXwork[j*pmodel + i] = XtX[model_m[j]*p + model_m[i]];
       }		
      }	 

     mse_m = yty; 
     memcpy(coefficients, XtYwork, sizeof(double)*pmodel); 
     cholreg(XtYwork, XtXwork, coefficients, se_m, &mse_m, pmodel, nobs);  
     
     R2_m = 1.0 - (mse_m * (double) ( nobs - pmodel))/SSY;
     prior_m = compute_prior_probs(model,pmodel,p, modelprior);
     gexpectations(p, pmodel, nobs, R2_m, alpha, INTEGER(method)[0], RSquareFull, SSY, &logmargy, &shrinkage_m);
     postnew = logmargy + log(prior_m);
    }	
   else {
     new_loc = branch->where;
     postnew =  REAL(logmarg)[new_loc] + log(REAL(priorprobs)[new_loc]);      
   } 

   MH = exp(postnew - postold + pigammaold - pigammanew);
   // Rprintf("it %d MH %lf  new %lf old %lf propold %lf propnew %lf \n", m, MH, postnew, postold, pigammanew, pigammaold);
   if (unif_rand() < MH) {
     
     if (newmodel ==1)  {
       new_loc = nUnique;

       insert_model_tree(tree, vars, n, model, nUnique);

       INTEGER(modeldim)[nUnique] = pmodel;
       SET_ELEMENT(modelspace, nUnique, Rmodel_m);
       
       SET_ELEMENT(beta, nUnique, Rcoef_m);
       SET_ELEMENT(se, nUnique, Rse_m);
       
       REAL(R2)[nUnique] = R2_m;
       REAL(mse)[nUnique] = mse_m;
       
       REAL(logmarg)[nUnique] = logmargy;
       REAL(shrinkage)[nUnique] = shrinkage_m;
       REAL(priorprobs)[nUnique] = prior_m;
       UNPROTECT(3);
       ++nUnique; 
     }	

     old_loc = new_loc;
     pigammaold = pigammanew;
     REAL(sampleprobs)[old_loc] = pigammaold;
     postold = postnew;
     pmodel_old = pmodel;
     memcpy(modelold, model, sizeof(int)*p);
   }
   else  {
     if (newmodel == 1) UNPROTECT(3);
   }	
 
   INTEGER(counts)[old_loc] += 1;

   for (i = 0; i < n; i++) {
     real_model[i] = (double) modelold[vars[i].index];
     REAL(MCMCprobs)[vars[i].index] += (double) modelold[vars[i].index];
   }
   F77_NAME(dsyr)("U", &n,  &one, &real_model[0], &inc,  &SSgam[0], &n);
   m++;

   
   rem = modf((double) m/(double) update, &mod);
   if (rem  == 0.0) {
     mcurrent = nUnique;
     compute_modelprobs(modelprobs, logmarg, priorprobs,mcurrent);
     compute_margprobs(modelspace, modeldim, modelprobs, probs, mcurrent, p);        

     for (i = 0; i < n; i++) {
       marg_probs[i] = wt*(REAL(MCMCprobs)[vars[i].index]/ (double) m) + 
	 (1.0 - wt)*probs[vars[i].index];
     }
     update_Cov(Cov, priorCov, SSgam, marg_probs, n, m, print);
     // Initialize post old proposal
     pigammaold = 0.0;
     for (i = 0; i < n; i++) {
       if (modelold[vars[i].index] == 1 ){	
	 real_model[i] = 1.0;
	 pigammaold += log(cond_prob(real_model,i, n, marg_probs,Cov, delta));
       }
       else {
	 real_model[i] = 0.0;
	 pigammaold += log(1.0 - cond_prob(real_model,i, n, marg_probs,Cov, delta));
       }}
   }
 }

 mcurrent = nUnique;
 compute_modelprobs(modelprobs, logmarg, priorprobs,mcurrent);
 compute_margprobs(modelspace, modeldim, modelprobs, probs, mcurrent, p);        
 wt = 0.1;
 for (i = 0; i < n; i++) {
   marg_probs[i] = wt* (REAL(MCMCprobs)[vars[i].index]/ (double) m) + 
				    (1.0 - wt)*probs[vars[i].index];
   //  marg_probs[n-1-i] =  REAL(MCMCprobs)[vars[i].index]/ (double) m;
  REAL(MCMCprobs)[vars[i].index] /= (double) m;
  }

 update_Cov(Cov, priorCov, SSgam, marg_probs, n, m, print);

//  Now sample W/O Replacement 
// Rprintf("NumUnique Models Accepted %d \n", nUnique);
 INTEGER(NumUnique)[0] = nUnique;

 if (nUnique < k) {

    //    compute_modelprobs(modelprobs, logmarg, priorprobs,mcurrent);
    //    compute_margprobs(modelspace, modeldim, modelprobs, probs, mcurrent, p);        
    
   //   update_MCMC_probs(MCMC_probs, vars, n, p);
   //   Rprintf("Update Tree\n");

   update_cond_tree(modelspace, tree, modeldim, vars, p, n, nUnique, modelwork, real_model, marg_probs, Cov, eps);      
  
         
   //   Rprintf("\nNow sample the rest without replacement\n");
   
   for (m = nUnique; m < k; m++) {
     INTEGER(modeldim)[m]  = n_sure;
     
     branch = tree;
  
     for (i = 0; i< n; i++) {
       pigamma[i] = 1.0;

       if (branch->prob == -1.0) {
	 branch->prob = cond_prob(real_model,i, n, marg_probs,Cov, delta);
	 branch->update = m+mcurrent;
       }
       	 
       bit =  withprob(branch->prob);
       real_model[n-i-1] = (double) bit;
     
       if (bit == 1) {
	 for (j=0; j<=i; j++)  pigamma[j] *= branch->prob;
	 if (i < n-1 && branch->one == NULL) 
	 //	    branch->one = make_node(vars[i+1].prob);
	 branch->one = make_node(cond_prob(real_model,i+1, n, marg_probs,Cov , delta));
       if (i == n-1 && branch->one == NULL)
	 branch->one = make_node(0.0);
       branch = branch->one;
       }
     else {
       for (j=0; j<=i; j++)  pigamma[j] *= (1.0 - branch->prob);
       if (i < n-1 && branch->zero == NULL)
	 //	 branch->zero = make_node(vars[i+1].prob);
	 branch->zero = make_node(cond_prob(real_model,i+1, n, marg_probs,Cov, delta));
       if (i == n-1 && branch->zero == NULL)
	 branch->zero = make_node(0.0);
       branch = branch->zero;
     }
       model[vars[i].index] = bit; 
       INTEGER(modeldim)[m]  += bit;
     }

     REAL(sampleprobs)[m] = pigamma[0]; 

     pmodel = INTEGER(modeldim)[m];

    // Now subtract off the visited probability mass. 
     branch=tree;
     for (i = 0; i < n; i++) {
       bit = model[vars[i].index];
       prone = branch->prob;
       if (bit == 1) prone -= pigamma[i];
       denom = 1.0 - pigamma[i];
       if (denom <= 0.0) {
	 if (denom < 0.0) {
	   Rprintf("neg denominator %le %le %le !!!\n", pigamma, denom, prone);
	   if (branch->prob < 0.0 && branch->prob < 1.0)
	     Rprintf("non extreme %le\n", branch->prob);}
	 denom = 0.0;}
       else {
	 if  (prone <= 0)  prone = 0.0;
	 if  (prone > denom)  {
	   if (prone <= eps) prone = 0.0;
	   else prone = 1.0;
	  // Rprintf("prone > 1 %le %le %le %le !!!\n", pigamma, denom, prone, eps);
	 }
	 else prone = prone/denom;
       }
       if (prone > 1.0 || prone < 0.0) 
	 	 Rprintf("%d %d Probability > 1!!! %le %le  %le %le \n",
	 	 m, i, prone, branch->prob, denom, pigamma);
      //      if (bit == 1)  pigamma /= (branch->prob);
      //	      else  pigamma /= (1.0 - branch->prob); 
      //	      if (pigamma > 1.0) pigamma = 1.0; 
       branch->prob  = prone;
       if (bit == 1) branch = branch->one;
       else  branch = branch->zero;
      //      Rprintf("%d %d \n",  branch->done, n - i); 
      //      if (log((double) branch->done) < (n - i)*log(2.0)) {
      //	if (bit == 1) branch = branch->one;
      //	else  branch = branch->zero;
      //}
      //else {
      //	    branch->one = NULL;
      //	    branch->zero = NULL; 
      //	    break; } 
     }
    /* Now get model specific calculations */ 

    PROTECT(Rmodel_m = allocVector(INTSXP, pmodel));
    model_m = INTEGER(Rmodel_m);

    for (j = 0, l=0; j < p; j++) {  
      if (model[j] == 1) {
	model_m[l] = j;
	l +=1;}
      }	
 

      SET_ELEMENT(modelspace, m, Rmodel_m);
   
      for (j=0, l=0; j < pmodel; j++) {
	XtYwork[j] = XtY[model_m[j]];
        for  ( i = 0; i < pmodel; i++) {
	  XtXwork[j*pmodel + i] = XtX[model_m[j]*p + model_m[i]];
	}	
      } 

    
      PROTECT(Rcoef_m = allocVector(REALSXP,pmodel));
      PROTECT(Rse_m = allocVector(REALSXP,pmodel));
      coefficients = REAL(Rcoef_m);  
      se_m = REAL(Rse_m);
  
      mse_m = yty; 
      memcpy(coefficients, XtYwork, sizeof(double)*pmodel); 
      cholreg(XtYwork, XtXwork, coefficients, se_m, &mse_m, pmodel, nobs);  

  
    //    olsreg(Ywork, Xwork, coefficients, se_m, &mse_m, &pmodel, &nobs, pivot,qraux,work,residuals,effects,v,betaols);   
  
      R2_m = 1.0 - (mse_m * (double) ( nobs - pmodel))/SSY;

      SET_ELEMENT(beta, m, Rcoef_m);
      SET_ELEMENT(se, m, Rse_m);

      REAL(R2)[m] = R2_m;
      REAL(mse)[m] = mse_m;

   gexpectations(p, pmodel, nobs, R2_m, alpha, INTEGER(method)[0],  RSquareFull, SSY, &logmargy, &shrinkage_m);
   REAL(logmarg)[m] = logmargy;
   REAL(shrinkage)[m] = shrinkage_m;
   REAL(priorprobs)[m] = compute_prior_probs(model,pmodel,p, modelprior);
       
   UNPROTECT(3);  
   }	
 }


 // Rprintf("modelprobs\n");
 compute_modelprobs(modelprobs, logmarg, priorprobs,k);
 // Rprintf("marginal probs\n");
 compute_margprobs(modelspace, modeldim, modelprobs, probs, k, p);  
 
 // Rprintf("saving\n");
  SET_VECTOR_ELT(ANS, 0, Rprobs);
  SET_STRING_ELT(ANS_names, 0, mkChar("probne0"));

  SET_VECTOR_ELT(ANS, 1, modelspace);
  SET_STRING_ELT(ANS_names, 1, mkChar("which"));

  SET_VECTOR_ELT(ANS, 2, logmarg);
  SET_STRING_ELT(ANS_names, 2, mkChar("logmarg"));

  SET_VECTOR_ELT(ANS, 3, modelprobs);
  SET_STRING_ELT(ANS_names, 3, mkChar("postprobs"));

  SET_VECTOR_ELT(ANS, 4, priorprobs);
  SET_STRING_ELT(ANS_names, 4, mkChar("priorprobs"));

  SET_VECTOR_ELT(ANS, 5,sampleprobs);
  SET_STRING_ELT(ANS_names, 5, mkChar("sampleprobs"));

  SET_VECTOR_ELT(ANS, 6, mse);
  SET_STRING_ELT(ANS_names, 6, mkChar("mse"));

  SET_VECTOR_ELT(ANS, 7, beta);
  SET_STRING_ELT(ANS_names, 7, mkChar("mle"));

  SET_VECTOR_ELT(ANS, 8, se);
  SET_STRING_ELT(ANS_names, 8, mkChar("mle.se"));

  SET_VECTOR_ELT(ANS, 9, shrinkage);
  SET_STRING_ELT(ANS_names, 9, mkChar("shrinkage"));

  SET_VECTOR_ELT(ANS, 10, modeldim);
  SET_STRING_ELT(ANS_names, 10, mkChar("size"));
 
  SET_VECTOR_ELT(ANS, 11, R2);
  SET_STRING_ELT(ANS_names, 11, mkChar("R2"));

  SET_VECTOR_ELT(ANS, 12, counts);
  SET_STRING_ELT(ANS_names, 12, mkChar("freq"));

  SET_VECTOR_ELT(ANS, 13, MCMCprobs);
  SET_STRING_ELT(ANS_names, 13, mkChar("probs.MCMC"));

  SET_VECTOR_ELT(ANS, 14, NumUnique);
  SET_STRING_ELT(ANS_names, 14, mkChar("n.Unique"));

  setAttrib(ANS, R_NamesSymbol, ANS_names);
  UNPROTECT(nProtected);
  //  Rprintf("Return\n");
  PutRNGstate();

  return(ANS);  
}
Ejemplo n.º 17
0
void search_given(char *given, search *mysearch) {
	struct stat info;
	stack *temp_stk; /*a temp var to work with history stack */
	Node *temp_node; /* a temp var to work with hsitory stack node */
	char *full_path; /* temp string of full path */
	errno = 0;
	/*get the file info */
	if (stat(given, &info) == -1) {
		perror(given);
		if (mysearch->client_fd > 0)
			send_err_line(mysearch, "%s: %s", given, mystrerror(errno));
		return;
	}
	/* if it directory */
	if (S_ISDIR(info.st_mode)) {
		/* get the full path */
		full_path=scan_dir_name(given);
		if (full_path==NULL)
			return;
		/*
		 * if -d is set to 0, do not process directory
		 */
		if (mysearch->max_dir_depth == 0) {
			fprintf(stderr,
					"%s is detected to exceed the search limit %d\n", full_path,
					mysearch->max_dir_depth);
			if (mysearch->client_fd > 0)
				send_err_line(mysearch,
						"%s is detected to exceed the search limit %d",
						full_path, mysearch->max_dir_depth);
			free(full_path);
			return;
		} else {
			/*allocate space to a history stack*/
			if ((temp_stk = malloc(sizeof(stack))) == NULL) {
				perror("malloc():");
				free(full_path);
				return;
			}
			else {
				/* initialize the stack and push it on stacks*/
				temp_stk->mysearch = mysearch;
				stack_init(temp_stk);
				/* make a node */

				if ((temp_node = make_node(full_path, 1, temp_stk)) == NULL) {
					free(full_path);
					free(temp_stk);
					return;
				}
				/*push the root node to the stack and kick it off*/
				stack_push(temp_stk, temp_node, NULL);
				walk_to_next(temp_node);
			}
		}
		return;
	} else {
		search_file(given, mysearch, NULL);
	} /* search it as a file*/
	return;
}
Ejemplo n.º 18
0
Archivo: c-omp.c Proyecto: 0mp/freebsd
tree
c_finish_omp_for (location_t locus, tree decl, tree init, tree cond,
		  tree incr, tree body, tree pre_body)
{
  location_t elocus = locus;
  bool fail = false;

  if (EXPR_HAS_LOCATION (init))
    elocus = EXPR_LOCATION (init);

  /* Validate the iteration variable.  */
  if (!INTEGRAL_TYPE_P (TREE_TYPE (decl)))
    {
      error ("%Hinvalid type for iteration variable %qE", &elocus, decl);
      fail = true;
    }
  if (TYPE_UNSIGNED (TREE_TYPE (decl)))
    warning (0, "%Hiteration variable %qE is unsigned", &elocus, decl);

  /* In the case of "for (int i = 0...)", init will be a decl.  It should
     have a DECL_INITIAL that we can turn into an assignment.  */
  if (init == decl)
    {
      elocus = DECL_SOURCE_LOCATION (decl);

      init = DECL_INITIAL (decl);
      if (init == NULL)
	{
	  error ("%H%qE is not initialized", &elocus, decl);
	  init = integer_zero_node;
	  fail = true;
	}

      init = build_modify_expr (decl, NOP_EXPR, init);
      SET_EXPR_LOCATION (init, elocus);
    }
  gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
  gcc_assert (TREE_OPERAND (init, 0) == decl);
  
  if (cond == NULL_TREE)
    {
      error ("%Hmissing controlling predicate", &elocus);
      fail = true;
    }
  else
    {
      bool cond_ok = false;

      if (EXPR_HAS_LOCATION (cond))
	elocus = EXPR_LOCATION (cond);

      if (TREE_CODE (cond) == LT_EXPR
	  || TREE_CODE (cond) == LE_EXPR
	  || TREE_CODE (cond) == GT_EXPR
	  || TREE_CODE (cond) == GE_EXPR)
	{
	  tree op0 = TREE_OPERAND (cond, 0);
	  tree op1 = TREE_OPERAND (cond, 1);

	  /* 2.5.1.  The comparison in the condition is computed in the type
	     of DECL, otherwise the behavior is undefined.

	     For example:
	     long n; int i;
	     i < n;

	     according to ISO will be evaluated as:
	     (long)i < n;

	     We want to force:
	     i < (int)n;  */
	  if (TREE_CODE (op0) == NOP_EXPR
	      && decl == TREE_OPERAND (op0, 0))
	    {
	      TREE_OPERAND (cond, 0) = TREE_OPERAND (op0, 0);
	      TREE_OPERAND (cond, 1) = fold_build1 (NOP_EXPR, TREE_TYPE (decl),
						    TREE_OPERAND (cond, 1));
	    }
	  else if (TREE_CODE (op1) == NOP_EXPR
		   && decl == TREE_OPERAND (op1, 0))
	    {
	      TREE_OPERAND (cond, 1) = TREE_OPERAND (op1, 0);
	      TREE_OPERAND (cond, 0) = fold_build1 (NOP_EXPR, TREE_TYPE (decl),
						    TREE_OPERAND (cond, 0));
	    }

	  if (decl == TREE_OPERAND (cond, 0))
	    cond_ok = true;
	  else if (decl == TREE_OPERAND (cond, 1))
	    {
	      TREE_SET_CODE (cond, swap_tree_comparison (TREE_CODE (cond)));
	      TREE_OPERAND (cond, 1) = TREE_OPERAND (cond, 0);
	      TREE_OPERAND (cond, 0) = decl;
	      cond_ok = true;
	    }
	}

      if (!cond_ok)
	{
	  error ("%Hinvalid controlling predicate", &elocus);
	  fail = true;
	}
    }

  if (incr == NULL_TREE)
    {
      error ("%Hmissing increment expression", &elocus);
      fail = true;
    }
  else
    {
      bool incr_ok = false;

      if (EXPR_HAS_LOCATION (incr))
	elocus = EXPR_LOCATION (incr);

      /* Check all the valid increment expressions: v++, v--, ++v, --v,
	 v = v + incr, v = incr + v and v = v - incr.  */
      switch (TREE_CODE (incr))
	{
	case POSTINCREMENT_EXPR:
	case PREINCREMENT_EXPR:
	case POSTDECREMENT_EXPR:
	case PREDECREMENT_EXPR:
	  incr_ok = (TREE_OPERAND (incr, 0) == decl);
	  break;

	case MODIFY_EXPR:
	  if (TREE_OPERAND (incr, 0) != decl)
	    break;
	  if (TREE_OPERAND (incr, 1) == decl)
	    break;
	  if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
	      && (TREE_OPERAND (TREE_OPERAND (incr, 1), 0) == decl
		  || TREE_OPERAND (TREE_OPERAND (incr, 1), 1) == decl))
	    incr_ok = true;
	  else if (TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR
		   && TREE_OPERAND (TREE_OPERAND (incr, 1), 0) == decl)
	    incr_ok = true;
	  else
	    {
	      tree t = check_omp_for_incr_expr (TREE_OPERAND (incr, 1), decl);
	      if (t != error_mark_node)
		{
		  incr_ok = true;
		  t = build2 (PLUS_EXPR, TREE_TYPE (decl), decl, t);
		  incr = build2 (MODIFY_EXPR, void_type_node, decl, t);
		}
	    }
	  break;

	default:
	  break;
	}
      if (!incr_ok)
	{
	  error ("%Hinvalid increment expression", &elocus);
	  fail = true;
	}
    }

  if (fail)
    return NULL;
  else
    {
      tree t = make_node (OMP_FOR);

      TREE_TYPE (t) = void_type_node;
      OMP_FOR_INIT (t) = init;
      OMP_FOR_COND (t) = cond;
      OMP_FOR_INCR (t) = incr;
      OMP_FOR_BODY (t) = body;
      OMP_FOR_PRE_BODY (t) = pre_body;

      SET_EXPR_LOCATION (t, locus);
      return add_stmt (t);
    }
}
Ejemplo n.º 19
0
void manage_window(xcb_window_t win, rule_consequence_t *csq, int fd)
{
	monitor_t *m = mon;
	desktop_t *d = mon->desk;
	node_t *f = mon->desk->focus;

	parse_rule_consequence(fd, csq);

	if (!csq->manage) {
		free(csq->layer);
		free(csq->state);
		window_show(win);
		return;
	}

	if (csq->node_desc[0] != '\0') {
		coordinates_t ref = {m, d, f};
		coordinates_t trg = {NULL, NULL, NULL};
		if (node_from_desc(csq->node_desc, &ref, &trg)) {
			m = trg.monitor;
			d = trg.desktop;
			f = trg.node;
		}
	} else if (csq->desktop_desc[0] != '\0') {
		coordinates_t ref = {m, d, NULL};
		coordinates_t trg = {NULL, NULL, NULL};
		if (desktop_from_desc(csq->desktop_desc, &ref, &trg)) {
			m = trg.monitor;
			d = trg.desktop;
			f = trg.desktop->focus;
		}
	} else if (csq->monitor_desc[0] != '\0') {
		coordinates_t ref = {m, NULL, NULL};
		coordinates_t trg = {NULL, NULL, NULL};
		if (monitor_from_desc(csq->monitor_desc, &ref, &trg)) {
			m = trg.monitor;
			d = trg.monitor->desk;
			f = trg.monitor->desk->focus;
		}
	}

	if (csq->sticky) {
		m = mon;
		d = mon->desk;
		f = mon->desk->focus;
	}

	if (csq->split_dir[0] != '\0' && f != NULL) {
		direction_t dir;
		if (parse_direction(csq->split_dir, &dir)) {
			presel_dir(m, d, f, dir);
		}
	}

	if (csq->split_ratio != 0 && f != NULL) {
		presel_ratio(m, d, f, csq->split_ratio);
	}

	node_t *n = make_node(win);
	client_t *c = make_client();
	c->border_width = csq->border ? d->border_width : 0;
	n->client = c;
	initialize_client(n);
	update_floating_rectangle(n);

	if (c->floating_rectangle.x == 0 && c->floating_rectangle.y == 0) {
		csq->center = true;
	}

	c->min_width = csq->min_width;
	c->max_width = csq->max_width;
	c->min_height = csq->min_height;
	c->max_height = csq->max_height;

	monitor_t *mm = monitor_from_client(c);
	embrace_client(mm, c);
	adapt_geometry(&mm->rectangle, &m->rectangle, n);

	if (csq->center) {
		window_center(m, c);
	}

	snprintf(c->class_name, sizeof(c->class_name), "%s", csq->class_name);
	snprintf(c->instance_name, sizeof(c->instance_name), "%s", csq->instance_name);

	f = insert_node(m, d, n, f);
	clients_count++;

	put_status(SBSC_MASK_NODE_MANAGE, "node_manage %s %s 0x%X 0x%X\n", m->name, d->name, win, f!=NULL?f->id:0);

	if (f != NULL && f->client != NULL && csq->state != NULL && *(csq->state) == STATE_FLOATING) {
		c->last_layer = c->layer = f->client->layer;
	}

	if (csq->layer != NULL) {
		c->last_layer = c->layer = *(csq->layer);
	}

	if (csq->state != NULL) {
		set_state(m, d, n, *(csq->state));
		c->last_state = c->state;
	}

	set_locked(m, d, n, csq->locked);
	set_sticky(m, d, n, csq->sticky);
	set_private(m, d, n, csq->private);

	arrange(m, d);

	bool give_focus = (csq->focus && (d == mon->desk || csq->follow));

	if (give_focus) {
		focus_node(m, d, n);
	} else if (csq->focus) {
		activate_node(m, d, n);
	} else {
		stack(d, n, false);
	}

	uint32_t values[] = {CLIENT_EVENT_MASK | (focus_follows_pointer ? XCB_EVENT_MASK_ENTER_WINDOW : 0)};
	xcb_change_window_attributes(dpy, win, XCB_CW_EVENT_MASK, values);

	if (d == m->desk) {
		window_show(n->id);
	} else {
		window_hide(n->id);
	}

	/* the same function is already called in `focus_node` but has no effects on unmapped windows */
	if (give_focus) {
		xcb_set_input_focus(dpy, XCB_INPUT_FOCUS_POINTER_ROOT, win, XCB_CURRENT_TIME);
	}

	ewmh_set_wm_desktop(n, d);
	ewmh_update_client_list(false);
	free(csq->layer);
	free(csq->state);
}
Ejemplo n.º 20
0
/* FN is a constructor or destructor, and there are FUNCTION_DECLs
   cloned from it nearby.  Instead of cloning this body, leave it
   alone and create tiny one-call bodies for the cloned
   FUNCTION_DECLs.  These clones are sibcall candidates, and their
   resulting code will be very thunk-esque.  */
static void
thunk_body (tree clone, tree fn, tree clone_to_call)
{
  tree bind, block, call, fn_parm, fn_parm_typelist;
  int parmno, vtt_parmno;
  tree clone_parm, parmlist;

  for (vtt_parmno = -1, parmno = 0, fn_parm = DECL_ARGUMENTS (fn);
       fn_parm;
       ++parmno, fn_parm = TREE_CHAIN (fn_parm))
    {
      if (DECL_ARTIFICIAL (fn_parm) && DECL_NAME (fn_parm) == vtt_parm_identifier)
	{
	  vtt_parmno = parmno;	/* Compensate for removed in_charge parameter.  */
	  break;
	}
    }
  /* Currently, we are not supposed to have a vtt argument. */
  gcc_assert(vtt_parmno == -1);

  /* Walk parameter lists together, creating parameter list for call to original function.  */
  for (parmno = 0,
	 parmlist = NULL,
	 fn_parm = DECL_ARGUMENTS (fn),
	 fn_parm_typelist = TYPE_ARG_TYPES (TREE_TYPE (fn)),
	 clone_parm = DECL_ARGUMENTS (clone);
       fn_parm;
       ++parmno,
	 fn_parm = TREE_CHAIN (fn_parm))
    {
      if (parmno == vtt_parmno && ! DECL_HAS_VTT_PARM_P (clone))
	{
	  tree typed_null_pointer_node = copy_node (null_pointer_node);
	  gcc_assert (fn_parm_typelist);
	  /* Clobber actual parameter with formal parameter type.  */
	  TREE_TYPE (typed_null_pointer_node) = TREE_VALUE (fn_parm_typelist);
	  parmlist = tree_cons (NULL, typed_null_pointer_node, parmlist);
	}
      else if (parmno == 1 && DECL_HAS_IN_CHARGE_PARM_P (fn))
	{
	  /* Just skip it. */
	}
      /* Map other parameters to their equivalents in the cloned
	 function.  */
      else
	{
	  gcc_assert (clone_parm);
	  DECL_ABSTRACT_ORIGIN (clone_parm) = NULL;
	  parmlist = tree_cons (NULL, clone_parm, parmlist);
	  clone_parm = TREE_CHAIN (clone_parm);
	}
      if (fn_parm_typelist)
	fn_parm_typelist = TREE_CHAIN (fn_parm_typelist);
    }

    /* We built this list backwards; fix now.  */
    parmlist = nreverse (parmlist);

    TREE_USED (clone_to_call) = 1;
    call = build_cxx_call (clone_to_call, parmlist);

    for (parmlist = TREE_OPERAND (call, 1); parmlist; parmlist = TREE_CHAIN (parmlist))
      {
	fn_parm = TREE_VALUE (parmlist);
	/* Remove the EMPTY_CLASS_EXPR because it upsets estimate_num_insns().  */
	if (TREE_CODE (fn_parm) == COMPOUND_EXPR)
	  {
	    gcc_assert (TREE_CODE (TREE_OPERAND (fn_parm, 1)) == EMPTY_CLASS_EXPR);
	    TREE_VALUE (parmlist) = TREE_OPERAND (fn_parm, 0);
	  }
      }
    block = make_node (BLOCK);
    if (targetm.cxx.cdtor_returns_this ())
      {
	tree clone_result = DECL_RESULT (clone);
	tree modify = build2 (MODIFY_EXPR, TREE_TYPE (clone_result), clone_result, call);
	add_stmt (modify);
	BLOCK_VARS (block) = clone_result;
      }
    else
      {
	add_stmt (call);
      }
    bind = c_build_bind_expr (block, cur_stmt_list);
    DECL_SAVED_TREE (clone) = push_stmt_list ();
    add_stmt (bind);
}
Ejemplo n.º 21
0
int main(int argc, char **argv) {
    unsigned int j;
    unsigned int k;
    redisContext *c;
    redisReply *reply;
    const char *hostname = (argc > 3) ? argv[3] : "127.0.0.1";
    int port = (argc > 4) ? atoi(argv[4]) : 6379;

    struct timeval timeout = { 1, 500000 }; // 1.5 seconds
    c = redisConnectWithTimeout(hostname, port, timeout);
    if (c == NULL || c->err) {
        if (c) {
            printf("Connection error: %s\n", c->errstr);
            redisFree(c);
        } else {
            printf("Connection error: can't allocate redis context\n");
        }
        exit(1);
    }


    //SETTING UP LOOKUP TABLE:
    redisReply *actors_ids;
    actors_ids = redisCommand(c, "SELECT 2");

    redisReply *start_actor;
    redisReply *end_actor;

    //Get the starting actor
    char *start_act = argv[1];
    start_actor = redisCommand(c,"GET %s", start_act);
    char *start = start_actor->str;
    // printf("%s\n", start);
    // freeReplyObject(start_actor);

    //Get the ending actor
    char *end_act = argv[2];
    end_actor = redisCommand(c,"GET %s", end_act);
    char *end = end_actor->str;
    // printf("%s\n", end);
    // freeReplyObject(end_actor);


    /* 
        BREADTH FIRST SEARCH IMPLEMENTATION
    */

    //Switch back to DB0 for breadth-first search
    redisReply *switch_back;
    switch_back = redisCommand(c, "SELECT 0");

    //initialize LLs and hashtables
    Node *actors; //used in BFS as the Queue
    Node *path; //used later for building the path

    //visited hashtable
    hashtable_t *hashtable = ht_create( 65536 );

    //hashtable of parents to build path later
    hashtable_t *hashtable_parents = ht_create( 65536 );
    
    //initialize the start node for the actors Queue
    actors = make_node(start, NULL);
    char *name = start;
    
    //while the start and end are not equal
    while (strcmp(name, end) != 0) {
        name = peek(&actors);

        //check-- has name been visited?
        char *check = ht_get(hashtable, name);

        //if name is unvisited
        if(strcmp(check, "NULL")==0){

            //break out if you have reached
            //finishing condition
            if (strcmp(name, end) == 0) { 
                break; 
            }
            
            //continue BFS
            //set up the query for the list of actors
            //in the adjacency list (neighbors)
            char word_reply[100] = "";
            strcat(word_reply, "LRANGE ");
            strcat(word_reply, name);
            strcat(word_reply, " 0 -1");
            //store the query response
            reply = redisCommand(c,word_reply);
            if (reply->type == REDIS_REPLY_ARRAY) {
                for (k = 0; k < reply->elements; k++) {
                    //push each neighbor onto the queue (as you
                    //do in BFS)
                    push(&actors, reply->element[k]->str);
                    //check if each neighbor is in the hashtable
                    //of parents
                    char *check2 = ht_get(hashtable_parents, reply->element[k]->str);
                    if (strcmp(check2, "NULL") == 0) {
                        //if not, then put that neighbor and it's parent, name
                        //in the hashtable. It is keeping it traceable
                        //by the path later. 
                        ht_set(hashtable_parents, reply->element[k]->str, name);
                    }
                }
            }
            //once done, set name to visited
            //recall that name is just the current node
            //we are visiting.
            ht_set(hashtable, name, "visited");
        }
        //traversing graph by popping from actors
        //then the new current node, name, will be set to 
        //the beginning of actors again at the beginning of the
        //while loop.
        pop(&actors);
    }

    //Switch to DB2 for actor lookup
    redisReply *switch_actor_name;
    switch_actor_name = redisCommand(c, "SELECT 1");


    //GET FIRST ACTOR NAME
    redisReply *first_actor_name;
    first_actor_name = redisCommand(c,"GET %s", end);
    char *first_parent_name = first_actor_name->str;

    Node *final_path = make_node(first_parent_name, NULL);

    /* 
        BUILDING UP THE PATH FROM THE PARENT HASHTABLE
    */

    //Gets first parent to make linked list
    //To trace back and print the path
    //parent is an id in hashtable_parents
    char *parent = ht_get(hashtable_parents, end);

    //Use parent hashtable to build up path
    //all the way up to but not including the final parent
    while (strcmp(parent, start) != 0) {
        //Need to store in redis reply after looking
        //up the actual name from id stored in parent
        redisReply *actor_name;

        //Get the actor name
        actor_name = redisCommand(c,"GET %s", parent);
        char *parent_name = actor_name->str;

        //push parent name to build up final path
        push(&final_path, parent_name);
        //get new parent
        parent = ht_get(hashtable_parents, parent);
    }

    //Get the final parent, the last name that needs
    //to get pushed onto the path
    redisReply *actor_name;
    actor_name = redisCommand(c,"GET %s", parent);
    char *parent_name = actor_name->str;

    push(&final_path, parent_name);

    reverse(&final_path);
    print_list(final_path);
    
    /* Disconnects and frees the context */
    redisFree(c);

    return 0;
}
Ejemplo n.º 22
0
void
use_thunk (tree thunk_fndecl, bool emit_p)
{
    tree a, t, function, alias;
    tree virtual_offset;
    HOST_WIDE_INT fixed_offset, virtual_value;
    bool this_adjusting = DECL_THIS_THUNK_P (thunk_fndecl);

    /* We should have called finish_thunk to give it a name.  */
    gcc_assert (DECL_NAME (thunk_fndecl));

    /* We should never be using an alias, always refer to the
       aliased thunk.  */
    gcc_assert (!THUNK_ALIAS (thunk_fndecl));

    if (TREE_ASM_WRITTEN (thunk_fndecl))
        return;

    function = THUNK_TARGET (thunk_fndecl);
    if (DECL_RESULT (thunk_fndecl))
        /* We already turned this thunk into an ordinary function.
           There's no need to process this thunk again.  */
        return;

    if (DECL_THUNK_P (function))
        /* The target is itself a thunk, process it now.  */
        use_thunk (function, emit_p);

    /* Thunks are always addressable; they only appear in vtables.  */
    TREE_ADDRESSABLE (thunk_fndecl) = 1;

    /* Figure out what function is being thunked to.  It's referenced in
       this translation unit.  */
    TREE_ADDRESSABLE (function) = 1;
    mark_used (function);
    if (!emit_p)
        return;

    if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function))
        alias = make_alias_for_thunk (function);
    else
        alias = function;

    fixed_offset = THUNK_FIXED_OFFSET (thunk_fndecl);
    virtual_offset = THUNK_VIRTUAL_OFFSET (thunk_fndecl);

    if (virtual_offset)
    {
        if (!this_adjusting)
            virtual_offset = BINFO_VPTR_FIELD (virtual_offset);
        virtual_value = tree_low_cst (virtual_offset, /*pos=*/0);
        gcc_assert (virtual_value);
    }
    else
        virtual_value = 0;

    /* And, if we need to emit the thunk, it's used.  */
    mark_used (thunk_fndecl);
    /* This thunk is actually defined.  */
    DECL_EXTERNAL (thunk_fndecl) = 0;
    /* The linkage of the function may have changed.  FIXME in linkage
       rewrite.  */
    TREE_PUBLIC (thunk_fndecl) = TREE_PUBLIC (function);
    DECL_VISIBILITY (thunk_fndecl) = DECL_VISIBILITY (function);
    DECL_VISIBILITY_SPECIFIED (thunk_fndecl)
        = DECL_VISIBILITY_SPECIFIED (function);
    if (DECL_ONE_ONLY (function))
        make_decl_one_only (thunk_fndecl);

    if (flag_syntax_only)
    {
        TREE_ASM_WRITTEN (thunk_fndecl) = 1;
        return;
    }

    push_to_top_level ();

    if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function)
            && targetm.have_named_sections)
    {
        resolve_unique_section (function, 0, flag_function_sections);

        if (DECL_SECTION_NAME (function) != NULL && DECL_ONE_ONLY (function))
        {
            resolve_unique_section (thunk_fndecl, 0, flag_function_sections);

            /* Output the thunk into the same section as function.  */
            DECL_SECTION_NAME (thunk_fndecl) = DECL_SECTION_NAME (function);
        }
    }

    /* The back-end expects DECL_INITIAL to contain a BLOCK, so we
       create one.  */
    DECL_INITIAL (thunk_fndecl) = make_node (BLOCK);

    /* Set up cloned argument trees for the thunk.  */
    t = NULL_TREE;
    for (a = DECL_ARGUMENTS (function); a; a = TREE_CHAIN (a))
    {
        tree x = copy_node (a);
        TREE_CHAIN (x) = t;
        DECL_CONTEXT (x) = thunk_fndecl;
        SET_DECL_RTL (x, NULL_RTX);
        DECL_HAS_VALUE_EXPR_P (x) = 0;
        t = x;
    }
    a = nreverse (t);
    DECL_ARGUMENTS (thunk_fndecl) = a;
    BLOCK_VARS (DECL_INITIAL (thunk_fndecl)) = a;

    if (this_adjusting
            && targetm.asm_out.can_output_mi_thunk (thunk_fndecl, fixed_offset,
                    virtual_value, alias))
    {
        const char *fnname;
        current_function_decl = thunk_fndecl;
        DECL_RESULT (thunk_fndecl)
            = build_decl (RESULT_DECL, 0, integer_type_node);
        fnname = XSTR (XEXP (DECL_RTL (thunk_fndecl), 0), 0);
        init_function_start (thunk_fndecl);
        current_function_is_thunk = 1;
        assemble_start_function (thunk_fndecl, fnname);

        targetm.asm_out.output_mi_thunk (asm_out_file, thunk_fndecl,
                                         fixed_offset, virtual_value, alias);

        assemble_end_function (thunk_fndecl, fnname);
        init_insn_lengths ();
        current_function_decl = 0;
        cfun = 0;
        TREE_ASM_WRITTEN (thunk_fndecl) = 1;
    }
    else
    {
        /* If this is a covariant thunk, or we don't have the necessary
        code for efficient thunks, generate a thunk function that
         just makes a call to the real function.  Unfortunately, this
         doesn't work for varargs.  */

        if (varargs_function_p (function))
            error ("generic thunk code fails for method %q#D which uses %<...%>",
                   function);

        DECL_RESULT (thunk_fndecl) = NULL_TREE;

        start_preparsed_function (thunk_fndecl, NULL_TREE, SF_PRE_PARSED);
        /* We don't bother with a body block for thunks.  */

        /* There's no need to check accessibility inside the thunk body.  */
        push_deferring_access_checks (dk_no_check);

        t = a;
        if (this_adjusting)
            t = thunk_adjust (t, /*this_adjusting=*/1,
                              fixed_offset, virtual_offset);

        /* Build up the call to the real function.  */
        t = tree_cons (NULL_TREE, t, NULL_TREE);
        for (a = TREE_CHAIN (a); a; a = TREE_CHAIN (a))
            t = tree_cons (NULL_TREE, a, t);
        t = nreverse (t);
        t = build_call (alias, t);
        CALL_FROM_THUNK_P (t) = 1;

        if (VOID_TYPE_P (TREE_TYPE (t)))
            finish_expr_stmt (t);
        else
        {
            if (!this_adjusting)
            {
                tree cond = NULL_TREE;

                if (TREE_CODE (TREE_TYPE (t)) == POINTER_TYPE)
                {
                    /* If the return type is a pointer, we need to
                       protect against NULL.  We know there will be an
                       adjustment, because that's why we're emitting a
                       thunk.  */
                    t = save_expr (t);
                    cond = cp_convert (boolean_type_node, t);
                }

                t = thunk_adjust (t, /*this_adjusting=*/0,
                                  fixed_offset, virtual_offset);
                if (cond)
                    t = build3 (COND_EXPR, TREE_TYPE (t), cond, t,
                                cp_convert (TREE_TYPE (t), integer_zero_node));
            }
            if (IS_AGGR_TYPE (TREE_TYPE (t)))
                t = build_cplus_new (TREE_TYPE (t), t);
            finish_return_stmt (t);
        }

        /* Since we want to emit the thunk, we explicitly mark its name as
        referenced.  */
        mark_decl_referenced (thunk_fndecl);

        /* But we don't want debugging information about it.  */
        DECL_IGNORED_P (thunk_fndecl) = 1;

        /* Re-enable access control.  */
        pop_deferring_access_checks ();

        thunk_fndecl = finish_function (0);
        tree_lowering_passes (thunk_fndecl);
        expand_body (thunk_fndecl);
    }

    pop_from_top_level ();
}
Ejemplo n.º 23
0
tree
streamer_alloc_tree (struct lto_input_block *ib, struct data_in *data_in,
		     enum LTO_tags tag)
{
  enum tree_code code;
  tree result;
#ifdef LTO_STREAMER_DEBUG
  HOST_WIDE_INT orig_address_in_writer;
#endif

  result = NULL_TREE;

#ifdef LTO_STREAMER_DEBUG
  /* Read the word representing the memory address for the tree
     as it was written by the writer.  This is useful when
     debugging differences between the writer and reader.  */
  orig_address_in_writer = streamer_read_hwi (ib);
  gcc_assert ((intptr_t) orig_address_in_writer == orig_address_in_writer);
#endif

  code = lto_tag_to_tree_code (tag);

  /* We should never see an SSA_NAME tree.  Only the version numbers of
     SSA names are ever written out.  See input_ssa_names.  */
  gcc_assert (code != SSA_NAME);

  /* Instantiate a new tree using the header data.  */
  if (CODE_CONTAINS_STRUCT (code, TS_STRING))
    result = streamer_read_string_cst (data_in, ib);
  else if (CODE_CONTAINS_STRUCT (code, TS_IDENTIFIER))
    result = input_identifier (data_in, ib);
  else if (CODE_CONTAINS_STRUCT (code, TS_VEC))
    {
      HOST_WIDE_INT len = streamer_read_hwi (ib);
      result = make_tree_vec (len);
    }
  else if (CODE_CONTAINS_STRUCT (code, TS_VECTOR))
    {
      HOST_WIDE_INT len = streamer_read_hwi (ib);
      result = make_vector (len);
    }
  else if (CODE_CONTAINS_STRUCT (code, TS_BINFO))
    {
      unsigned HOST_WIDE_INT len = streamer_read_uhwi (ib);
      result = make_tree_binfo (len);
    }
  else if (CODE_CONTAINS_STRUCT (code, TS_INT_CST))
    {
      unsigned HOST_WIDE_INT len = streamer_read_uhwi (ib);
      unsigned HOST_WIDE_INT ext_len = streamer_read_uhwi (ib);
      result = make_int_cst (len, ext_len);
    }
  else if (code == CALL_EXPR)
    {
      unsigned HOST_WIDE_INT nargs = streamer_read_uhwi (ib);
      return build_vl_exp (CALL_EXPR, nargs + 3);
    }
  else if (code == OMP_CLAUSE)
    {
      enum omp_clause_code subcode
	= (enum omp_clause_code) streamer_read_uhwi (ib);
      return build_omp_clause (UNKNOWN_LOCATION, subcode);
    }
  else
    {
      /* For all other nodes, materialize the tree with a raw
	 make_node call.  */
      result = make_node (code);
    }

#ifdef LTO_STREAMER_DEBUG
  /* Store the original address of the tree as seen by the writer
     in RESULT's aux field.  This is useful when debugging streaming
     problems.  This way, a debugging session can be started on
     both writer and reader with a breakpoint using this address
     value in both.  */
  lto_orig_address_map (result, (intptr_t) orig_address_in_writer);
#endif

  return result;
}
Ejemplo n.º 24
0
static tree
gfc_trans_omp_do (gfc_code *code, stmtblock_t *pblock,
		  gfc_omp_clauses *do_clauses)
{
  gfc_se se;
  tree dovar, stmt, from, to, step, type, init, cond, incr;
  tree count = NULL_TREE, cycle_label, tmp, omp_clauses;
  stmtblock_t block;
  stmtblock_t body;
  int simple = 0;
  bool dovar_found = false;
  gfc_omp_clauses *clauses = code->ext.omp_clauses;

  code = code->block->next;
  gcc_assert (code->op == EXEC_DO);

  if (pblock == NULL)
    {
      gfc_start_block (&block);
      pblock = &block;
    }

  omp_clauses = gfc_trans_omp_clauses (pblock, do_clauses, code->loc);
  if (clauses)
    {
      gfc_namelist *n;
      for (n = clauses->lists[OMP_LIST_LASTPRIVATE]; n != NULL; n = n->next)
	if (code->ext.iterator->var->symtree->n.sym == n->sym)
	  break;
      if (n == NULL)
	for (n = clauses->lists[OMP_LIST_PRIVATE]; n != NULL; n = n->next)
	  if (code->ext.iterator->var->symtree->n.sym == n->sym)
	    break;
      if (n != NULL)
	dovar_found = true;
    }

  /* Evaluate all the expressions in the iterator.  */
  gfc_init_se (&se, NULL);
  gfc_conv_expr_lhs (&se, code->ext.iterator->var);
  gfc_add_block_to_block (pblock, &se.pre);
  dovar = se.expr;
  type = TREE_TYPE (dovar);
  gcc_assert (TREE_CODE (type) == INTEGER_TYPE);

  gfc_init_se (&se, NULL);
  gfc_conv_expr_val (&se, code->ext.iterator->start);
  gfc_add_block_to_block (pblock, &se.pre);
  from = gfc_evaluate_now (se.expr, pblock);

  gfc_init_se (&se, NULL);
  gfc_conv_expr_val (&se, code->ext.iterator->end);
  gfc_add_block_to_block (pblock, &se.pre);
  to = gfc_evaluate_now (se.expr, pblock);

  gfc_init_se (&se, NULL);
  gfc_conv_expr_val (&se, code->ext.iterator->step);
  gfc_add_block_to_block (pblock, &se.pre);
  step = gfc_evaluate_now (se.expr, pblock);

  /* Special case simple loops.  */
  if (integer_onep (step))
    simple = 1;
  else if (tree_int_cst_equal (step, integer_minus_one_node))
    simple = -1;

  /* Loop body.  */
  if (simple)
    {
      init = build2_v (MODIFY_EXPR, dovar, from);
      cond = build2 (simple > 0 ? LE_EXPR : GE_EXPR, boolean_type_node,
		     dovar, to);
      incr = fold_build2 (PLUS_EXPR, type, dovar, step);
      incr = fold_build2 (MODIFY_EXPR, type, dovar, incr);
      if (pblock != &block)
	{
	  pushlevel (0);
	  gfc_start_block (&block);
	}
      gfc_start_block (&body);
    }
  else
    {
      /* STEP is not 1 or -1.  Use:
	 for (count = 0; count < (to + step - from) / step; count++)
	   {
	     dovar = from + count * step;
	     body;
	   cycle_label:;
	   }  */
      tmp = fold_build2 (MINUS_EXPR, type, step, from);
      tmp = fold_build2 (PLUS_EXPR, type, to, tmp);
      tmp = fold_build2 (TRUNC_DIV_EXPR, type, tmp, step);
      tmp = gfc_evaluate_now (tmp, pblock);
      count = gfc_create_var (type, "count");
      init = build2_v (MODIFY_EXPR, count, build_int_cst (type, 0));
      cond = build2 (LT_EXPR, boolean_type_node, count, tmp);
      incr = fold_build2 (PLUS_EXPR, type, count, build_int_cst (type, 1));
      incr = fold_build2 (MODIFY_EXPR, type, count, incr);

      if (pblock != &block)
	{
	  pushlevel (0);
	  gfc_start_block (&block);
	}
      gfc_start_block (&body);

      /* Initialize DOVAR.  */
      tmp = fold_build2 (MULT_EXPR, type, count, step);
      tmp = build2 (PLUS_EXPR, type, from, tmp);
      gfc_add_modify_expr (&body, dovar, tmp);
    }

  if (!dovar_found)
    {
      tmp = build_omp_clause (OMP_CLAUSE_PRIVATE);
      OMP_CLAUSE_DECL (tmp) = dovar;
      omp_clauses = gfc_trans_add_clause (tmp, omp_clauses);
    }
  if (!simple)
    {
      tmp = build_omp_clause (OMP_CLAUSE_PRIVATE);
      OMP_CLAUSE_DECL (tmp) = count;
      omp_clauses = gfc_trans_add_clause (tmp, omp_clauses);
    }

  /* Cycle statement is implemented with a goto.  Exit statement must not be
     present for this loop.  */
  cycle_label = gfc_build_label_decl (NULL_TREE);

  /* Put these labels where they can be found later. We put the
     labels in a TREE_LIST node (because TREE_CHAIN is already
     used). cycle_label goes in TREE_PURPOSE (backend_decl), exit
     label in TREE_VALUE (backend_decl).  */

  code->block->backend_decl = tree_cons (cycle_label, NULL, NULL);

  /* Main loop body.  */
  tmp = gfc_trans_omp_code (code->block->next, true);
  gfc_add_expr_to_block (&body, tmp);

  /* Label for cycle statements (if needed).  */
  if (TREE_USED (cycle_label))
    {
      tmp = build1_v (LABEL_EXPR, cycle_label);
      gfc_add_expr_to_block (&body, tmp);
    }

  /* End of loop body.  */
  stmt = make_node (OMP_FOR);

  TREE_TYPE (stmt) = void_type_node;
  OMP_FOR_BODY (stmt) = gfc_finish_block (&body);
  OMP_FOR_CLAUSES (stmt) = omp_clauses;
  OMP_FOR_INIT (stmt) = init;
  OMP_FOR_COND (stmt) = cond;
  OMP_FOR_INCR (stmt) = incr;
  gfc_add_expr_to_block (&block, stmt);

  return gfc_finish_block (&block);
}
Ejemplo n.º 25
0
Archivo: c-omp.c Proyecto: ymgcmstk/gcc
tree
c_finish_omp_for (location_t locus, enum tree_code code, tree declv,
		  tree orig_declv, tree initv, tree condv, tree incrv,
		  tree body, tree pre_body)
{
  location_t elocus;
  bool fail = false;
  int i;

  if ((code == CILK_SIMD || code == CILK_FOR)
      && !c_check_cilk_loop (locus, TREE_VEC_ELT (declv, 0)))
    fail = true;

  gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (initv));
  gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (condv));
  gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (incrv));
  for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
    {
      tree decl = TREE_VEC_ELT (declv, i);
      tree init = TREE_VEC_ELT (initv, i);
      tree cond = TREE_VEC_ELT (condv, i);
      tree incr = TREE_VEC_ELT (incrv, i);

      elocus = locus;
      if (EXPR_HAS_LOCATION (init))
	elocus = EXPR_LOCATION (init);

      /* Validate the iteration variable.  */
      if (!INTEGRAL_TYPE_P (TREE_TYPE (decl))
	  && TREE_CODE (TREE_TYPE (decl)) != POINTER_TYPE)
	{
	  error_at (elocus, "invalid type for iteration variable %qE", decl);
	  fail = true;
	}

      /* In the case of "for (int i = 0...)", init will be a decl.  It should
	 have a DECL_INITIAL that we can turn into an assignment.  */
      if (init == decl)
	{
	  elocus = DECL_SOURCE_LOCATION (decl);

	  init = DECL_INITIAL (decl);
	  if (init == NULL)
	    {
	      error_at (elocus, "%qE is not initialized", decl);
	      init = integer_zero_node;
	      fail = true;
	    }
	  DECL_INITIAL (decl) = NULL_TREE;

	  init = build_modify_expr (elocus, decl, NULL_TREE, NOP_EXPR,
	      			    /* FIXME diagnostics: This should
				       be the location of the INIT.  */
	      			    elocus,
				    init,
				    NULL_TREE);
	}
      if (init != error_mark_node)
	{
	  gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
	  gcc_assert (TREE_OPERAND (init, 0) == decl);
	}

      if (cond == NULL_TREE)
	{
	  error_at (elocus, "missing controlling predicate");
	  fail = true;
	}
      else
	{
	  bool cond_ok = false;

	  if (EXPR_HAS_LOCATION (cond))
	    elocus = EXPR_LOCATION (cond);

	  if (TREE_CODE (cond) == LT_EXPR
	      || TREE_CODE (cond) == LE_EXPR
	      || TREE_CODE (cond) == GT_EXPR
	      || TREE_CODE (cond) == GE_EXPR
	      || TREE_CODE (cond) == NE_EXPR
	      || TREE_CODE (cond) == EQ_EXPR)
	    {
	      tree op0 = TREE_OPERAND (cond, 0);
	      tree op1 = TREE_OPERAND (cond, 1);

	      /* 2.5.1.  The comparison in the condition is computed in
		 the type of DECL, otherwise the behavior is undefined.

		 For example:
		 long n; int i;
		 i < n;

		 according to ISO will be evaluated as:
		 (long)i < n;

		 We want to force:
		 i < (int)n;  */
	      if (TREE_CODE (op0) == NOP_EXPR
		  && decl == TREE_OPERAND (op0, 0))
		{
		  TREE_OPERAND (cond, 0) = TREE_OPERAND (op0, 0);
		  TREE_OPERAND (cond, 1)
		    = fold_build1_loc (elocus, NOP_EXPR, TREE_TYPE (decl),
				   TREE_OPERAND (cond, 1));
		}
	      else if (TREE_CODE (op1) == NOP_EXPR
		       && decl == TREE_OPERAND (op1, 0))
		{
		  TREE_OPERAND (cond, 1) = TREE_OPERAND (op1, 0);
		  TREE_OPERAND (cond, 0)
		    = fold_build1_loc (elocus, NOP_EXPR, TREE_TYPE (decl),
				   TREE_OPERAND (cond, 0));
		}

	      if (decl == TREE_OPERAND (cond, 0))
		cond_ok = true;
	      else if (decl == TREE_OPERAND (cond, 1))
		{
		  TREE_SET_CODE (cond,
				 swap_tree_comparison (TREE_CODE (cond)));
		  TREE_OPERAND (cond, 1) = TREE_OPERAND (cond, 0);
		  TREE_OPERAND (cond, 0) = decl;
		  cond_ok = true;
		}

	      if (TREE_CODE (cond) == NE_EXPR
		  || TREE_CODE (cond) == EQ_EXPR)
		{
		  if (!INTEGRAL_TYPE_P (TREE_TYPE (decl)))
		    {
		      if (code != CILK_SIMD && code != CILK_FOR)
			cond_ok = false;
		    }
		  else if (operand_equal_p (TREE_OPERAND (cond, 1),
					    TYPE_MIN_VALUE (TREE_TYPE (decl)),
					    0))
		    TREE_SET_CODE (cond, TREE_CODE (cond) == NE_EXPR
					 ? GT_EXPR : LE_EXPR);
		  else if (operand_equal_p (TREE_OPERAND (cond, 1),
					    TYPE_MAX_VALUE (TREE_TYPE (decl)),
					    0))
		    TREE_SET_CODE (cond, TREE_CODE (cond) == NE_EXPR
					 ? LT_EXPR : GE_EXPR);
		  else if (code != CILK_SIMD && code != CILK_FOR)
		    cond_ok = false;
		}
	    }

	  if (!cond_ok)
	    {
	      error_at (elocus, "invalid controlling predicate");
	      fail = true;
	    }
	}

      if (incr == NULL_TREE)
	{
	  error_at (elocus, "missing increment expression");
	  fail = true;
	}
      else
	{
	  bool incr_ok = false;

	  if (EXPR_HAS_LOCATION (incr))
	    elocus = EXPR_LOCATION (incr);

	  /* Check all the valid increment expressions: v++, v--, ++v, --v,
	     v = v + incr, v = incr + v and v = v - incr.  */
	  switch (TREE_CODE (incr))
	    {
	    case POSTINCREMENT_EXPR:
	    case PREINCREMENT_EXPR:
	    case POSTDECREMENT_EXPR:
	    case PREDECREMENT_EXPR:
	      if (TREE_OPERAND (incr, 0) != decl)
		break;

	      incr_ok = true;
	      incr = c_omp_for_incr_canonicalize_ptr (elocus, decl, incr);
	      break;

	    case COMPOUND_EXPR:
	      if (TREE_CODE (TREE_OPERAND (incr, 0)) != SAVE_EXPR
		  || TREE_CODE (TREE_OPERAND (incr, 1)) != MODIFY_EXPR)
		break;
	      incr = TREE_OPERAND (incr, 1);
	      /* FALLTHRU */
	    case MODIFY_EXPR:
	      if (TREE_OPERAND (incr, 0) != decl)
		break;
	      if (TREE_OPERAND (incr, 1) == decl)
		break;
	      if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
		  && (TREE_OPERAND (TREE_OPERAND (incr, 1), 0) == decl
		      || TREE_OPERAND (TREE_OPERAND (incr, 1), 1) == decl))
		incr_ok = true;
	      else if ((TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR
			|| (TREE_CODE (TREE_OPERAND (incr, 1))
			    == POINTER_PLUS_EXPR))
		       && TREE_OPERAND (TREE_OPERAND (incr, 1), 0) == decl)
		incr_ok = true;
	      else
		{
		  tree t = check_omp_for_incr_expr (elocus,
						    TREE_OPERAND (incr, 1),
						    decl);
		  if (t != error_mark_node)
		    {
		      incr_ok = true;
		      t = build2 (PLUS_EXPR, TREE_TYPE (decl), decl, t);
		      incr = build2 (MODIFY_EXPR, void_type_node, decl, t);
		    }
		}
	      break;

	    default:
	      break;
	    }
	  if (!incr_ok)
	    {
	      error_at (elocus, "invalid increment expression");
	      fail = true;
	    }
	}

      TREE_VEC_ELT (initv, i) = init;
      TREE_VEC_ELT (incrv, i) = incr;
    }

  if (fail)
    return NULL;
  else
    {
      tree t = make_node (code);

      TREE_TYPE (t) = void_type_node;
      OMP_FOR_INIT (t) = initv;
      OMP_FOR_COND (t) = condv;
      OMP_FOR_INCR (t) = incrv;
      OMP_FOR_BODY (t) = body;
      OMP_FOR_PRE_BODY (t) = pre_body;
      if (code == OMP_FOR)
	OMP_FOR_ORIG_DECLS (t) = orig_declv;

      SET_EXPR_LOCATION (t, locus);
      return add_stmt (t);
    }
}
Ejemplo n.º 26
0
LOCAL 	void insert_cuts_and_bdry2d(
	INTERFACE	*intfc,	/* an orginal intfc	*/
	double		**pc)	/* given corners of the subdomain */
{
	COMPONENT	comp;
	CROSS		*cross;
	CURVE		**cc, *c[4];
	CURVE		**curves1, **curves2;
	POINT		*p;
	INTERFACE	*sav_intfc;
	NODE		*n, **nn, *bn[4];
	int		i;

	sav_intfc = current_interface();
	set_current_interface(intfc);
	comp = (intfc->modified) ? long_component(pc[0],intfc) :
			component(pc[0],intfc);

redo_curve_list:
	for (cc = intfc->curves; cc && *cc; cc++)
	{
	    if (is_bdry(*cc))
	    {
	    	(void) delete_curve(*cc);
	    	goto redo_curve_list;
	    }
	}
	for (nn = intfc->nodes; nn && *nn; nn++)
	{
	    if (is_bdry(*nn))
	    {
	    	int num_in, num_out;
	    	if (num_curves_at_node(*nn,&num_in,&num_out) == 0)
	    	    (void) delete_node(*nn);
	    	else
	    	    set_not_bdry(*nn);
	    }
	}
	bn[0] = make_node(Point(pc[0]));
	bn[1] = make_node(Point(pc[2]));
	bn[2] = make_node(Point(pc[3]));
	bn[3] = make_node(Point(pc[1]));
	for (i = 0; i < 4; i++)
	{
	    c[i] = make_curve(NO_COMP,NO_COMP,bn[i],bn[(i+1)%4]);
	    set_is_bdry(c[0]);
	}

	if (intersections(intfc,&cross,YES) == FUNCTION_FAILED)
	{
	    screen("ERROR in insert_cuts_and_bdry2d(), "
	           "intersections() failed\n");
	    clean_up(ERROR);
	}

	if (cross == NULL)
	{
	    for (i = 0; i < 4; i++)
	    {
	    	positive_component(c[i]) = comp;
	    	negative_component(c[i]) = exterior_component(intfc);
	    }
	    return;
	}
	for (; cross != NULL; cross = cross->next)
	{
	    p = cross->p;
	    if (insert_point_in_bond(p,cross->b1,cross->c1)!=FUNCTION_SUCCEEDED)
	    {
	        screen("ERROR in insert_cuts_and_bdry2d(), "
		       "insert_point_in_bond() failed\n");
	        clean_up(ERROR);
	    }
	    rcl_after_insert_point(cross,p,cross->b1);
	    curves1 = split_curve(p,cross->b1,cross->c1,
	    		          positive_component(cross->c1),
	    		          negative_component(cross->c1),
	    		          positive_component(cross->c1),
	    		          negative_component(cross->c1));
	    rcl_after_split(cross,p,cross->b1,cross->c1,curves1);
	    if (insert_point_in_bond(p,cross->b2,cross->c2)!=FUNCTION_SUCCEEDED)
	    {
	        screen("ERROR in insert_cuts_and_bdry2d(), "
		       "insert_point_in_bond() failed\n");
	        clean_up(ERROR);
	    }
	    rcl_after_insert_point(cross,p,cross->b2);
	    curves2 = split_curve(p,cross->b2,cross->c2,
	    		          positive_component(cross->c2),
	    		          negative_component(cross->c2),
	    		          positive_component(cross->c2),
	    		          negative_component(cross->c2));
	    rcl_after_split(cross,p,cross->b2,cross->c2,curves1);
	    n = curves2[0]->end;
	    change_node_of_curve(curves2[0],
				NEGATIVE_ORIENTATION,curves1[0]->end);
	    change_node_of_curve(curves2[1],
				POSITIVE_ORIENTATION,curves1[0]->end);
	    (void) delete_node(n);
	}

	set_current_interface(sav_intfc);
	return;
}		/*end insert_cuts_and_bdry2d*/
Ejemplo n.º 27
0
void
sdbout_symbol (tree decl, int local)
{
  tree type = TREE_TYPE (decl);
  tree context = NULL_TREE;
  rtx value;
  int regno = -1;
  const char *name;

  /* If we are called before sdbout_init is run, just save the symbol
     for later.  */
  if (!sdbout_initialized)
    {
      preinit_symbols = tree_cons (0, decl, preinit_symbols);
      return;
    }

  sdbout_one_type (type);

  switch (TREE_CODE (decl))
    {
    case CONST_DECL:
      /* Enum values are defined by defining the enum type.  */
      return;

    case FUNCTION_DECL:
      /* Don't mention a nested function under its parent.  */
      context = decl_function_context (decl);
      if (context == current_function_decl)
	return;
      /* Check DECL_INITIAL to distinguish declarations from definitions.
	 Don't output debug info here for declarations; they will have
	 a DECL_INITIAL value of 0.  */
      if (! DECL_INITIAL (decl))
	return;
      if (!MEM_P (DECL_RTL (decl))
	  || GET_CODE (XEXP (DECL_RTL (decl), 0)) != SYMBOL_REF)
	return;
      PUT_SDB_DEF (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)));
      PUT_SDB_VAL (XEXP (DECL_RTL (decl), 0));
      PUT_SDB_SCL (TREE_PUBLIC (decl) ? C_EXT : C_STAT);
      break;

    case TYPE_DECL:
      /* Done with tagged types.  */
      if (DECL_NAME (decl) == 0)
	return;
      if (DECL_IGNORED_P (decl))
	return;
      /* Don't output intrinsic types.  GAS chokes on SDB .def
	 statements that contain identifiers with embedded spaces
	 (eg "unsigned long").  */
      if (DECL_IS_BUILTIN (decl))
	return;

      /* Output typedef name.  */
      if (template_name_p (DECL_NAME (decl)))
	PUT_SDB_DEF (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)));
      else
	PUT_SDB_DEF (IDENTIFIER_POINTER (DECL_NAME (decl)));
      PUT_SDB_SCL (C_TPDEF);
      break;

    case PARM_DECL:
      /* Parm decls go in their own separate chains
	 and are output by sdbout_reg_parms and sdbout_parms.  */
      gcc_unreachable ();

    case VAR_DECL:
      /* Don't mention a variable that is external.
	 Let the file that defines it describe it.  */
      if (DECL_EXTERNAL (decl))
	return;

      /* Ignore __FUNCTION__, etc.  */
      if (DECL_IGNORED_P (decl))
	return;

      /* If there was an error in the declaration, don't dump core
	 if there is no RTL associated with the variable doesn't
	 exist.  */
      if (!DECL_RTL_SET_P (decl))
	return;

      SET_DECL_RTL (decl,
		    eliminate_regs (DECL_RTL (decl), 0, NULL_RTX));
#ifdef LEAF_REG_REMAP
      if (current_function_uses_only_leaf_regs)
	leaf_renumber_regs_insn (DECL_RTL (decl));
#endif
      value = DECL_RTL (decl);

      /* Don't mention a variable at all
	 if it was completely optimized into nothingness.

	 If DECL was from an inline function, then its rtl
	 is not identically the rtl that was used in this
	 particular compilation.  */
      if (REG_P (value))
	{
	  regno = REGNO (value);
	  if (regno >= FIRST_PSEUDO_REGISTER)
	    return;
	}
      else if (GET_CODE (value) == SUBREG)
	{
	  while (GET_CODE (value) == SUBREG)
	    value = SUBREG_REG (value);
	  if (REG_P (value))
	    {
	      if (REGNO (value) >= FIRST_PSEUDO_REGISTER)
		return;
	    }
	  regno = REGNO (alter_subreg (&value));
	  SET_DECL_RTL (decl, value);
	}
      /* Don't output anything if an auto variable
	 gets RTL that is static.
	 GAS version 2.2 can't handle such output.  */
      else if (MEM_P (value) && CONSTANT_P (XEXP (value, 0))
	       && ! TREE_STATIC (decl))
	return;

      /* Emit any structure, union, or enum type that has not been output.
	 This occurs for tag-less structs (et al) used to declare variables
	 within functions.  */
      if (TREE_CODE (type) == ENUMERAL_TYPE
	  || TREE_CODE (type) == RECORD_TYPE
	  || TREE_CODE (type) == UNION_TYPE
	  || TREE_CODE (type) == QUAL_UNION_TYPE)
	{
	  if (COMPLETE_TYPE_P (type)		/* not a forward reference */
	      && KNOWN_TYPE_TAG (type) == 0)	/* not yet declared */
	    sdbout_one_type (type);
	}

      /* Defer SDB information for top-level initialized variables! */
      if (! local
	  && MEM_P (value)
	  && DECL_INITIAL (decl))
	return;

      /* C++ in 2.3 makes nameless symbols.  That will be fixed later.
	 For now, avoid crashing.  */
      if (DECL_NAME (decl) == NULL_TREE)
	return;

      /* Record the name for, starting a symtab entry.  */
      if (local)
	name = IDENTIFIER_POINTER (DECL_NAME (decl));
      else
	name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));

      if (MEM_P (value)
	  && GET_CODE (XEXP (value, 0)) == SYMBOL_REF)
	{
	  PUT_SDB_DEF (name);
	  if (TREE_PUBLIC (decl))
	    {
	      PUT_SDB_VAL (XEXP (value, 0));
	      PUT_SDB_SCL (C_EXT);
	    }
	  else
	    {
	      PUT_SDB_VAL (XEXP (value, 0));
	      PUT_SDB_SCL (C_STAT);
	    }
	}
      else if (regno >= 0)
	{
	  PUT_SDB_DEF (name);
	  PUT_SDB_INT_VAL (DBX_REGISTER_NUMBER (regno));
	  PUT_SDB_SCL (C_REG);
	}
      else if (MEM_P (value)
	       && (MEM_P (XEXP (value, 0))
		   || (REG_P (XEXP (value, 0))
		       && REGNO (XEXP (value, 0)) != HARD_FRAME_POINTER_REGNUM
		       && REGNO (XEXP (value, 0)) != STACK_POINTER_REGNUM)))
	/* If the value is indirect by memory or by a register
	   that isn't the frame pointer
	   then it means the object is variable-sized and address through
	   that register or stack slot.  COFF has no way to represent this
	   so all we can do is output the variable as a pointer.  */
	{
	  PUT_SDB_DEF (name);
	  if (REG_P (XEXP (value, 0)))
	    {
	      PUT_SDB_INT_VAL (DBX_REGISTER_NUMBER (REGNO (XEXP (value, 0))));
	      PUT_SDB_SCL (C_REG);
	    }
	  else
	    {
	      /* DECL_RTL looks like (MEM (MEM (PLUS (REG...)
		 (CONST_INT...)))).
		 We want the value of that CONST_INT.  */
	      /* Encore compiler hates a newline in a macro arg, it seems.  */
	      PUT_SDB_INT_VAL (DEBUGGER_AUTO_OFFSET
			       (XEXP (XEXP (value, 0), 0)));
	      PUT_SDB_SCL (C_AUTO);
	    }

	  /* Effectively do build_pointer_type, but don't cache this type,
	     since it might be temporary whereas the type it points to
	     might have been saved for inlining.  */
	  /* Don't use REFERENCE_TYPE because dbx can't handle that.  */
	  type = make_node (POINTER_TYPE);
	  TREE_TYPE (type) = TREE_TYPE (decl);
	}
      else if (MEM_P (value)
	       && ((GET_CODE (XEXP (value, 0)) == PLUS
		    && REG_P (XEXP (XEXP (value, 0), 0))
		    && GET_CODE (XEXP (XEXP (value, 0), 1)) == CONST_INT)
		   /* This is for variables which are at offset zero from
		      the frame pointer.  This happens on the Alpha.
		      Non-frame pointer registers are excluded above.  */
		   || (REG_P (XEXP (value, 0)))))
	{
	  /* DECL_RTL looks like (MEM (PLUS (REG...) (CONST_INT...)))
	     or (MEM (REG...)).  We want the value of that CONST_INT
	     or zero.  */
	  PUT_SDB_DEF (name);
	  PUT_SDB_INT_VAL (DEBUGGER_AUTO_OFFSET (XEXP (value, 0)));
	  PUT_SDB_SCL (C_AUTO);
	}
      else
	{
	  /* It is something we don't know how to represent for SDB.  */
	  return;
	}
      break;

    default:
      break;
    }
  PUT_SDB_TYPE (plain_type (type));
  PUT_SDB_ENDEF;
}
Ejemplo n.º 28
0
DFA *dfaImport(char* filename, char ***vars, int **orders)
{
  int i, numvars, bdd_nodes, ns, s;
  FILE *file;
  DFA *a;
  char ts[100];
  int ti;

  fprintf(stderr, "IN dfaImport\n");
  fflush(stderr);
  
  /* Read file */
  if ((file = fopen(filename, "r")) == 0) 
    return NULL;

  /*
   * BD: we should check the return value of every call to fscanf.
   */
  if (fscanf(file,
	     "MONA DFA\n"
	     "number of variables: %u\n"
	     "variables: ", &numvars) != 1) {
    return NULL;
  }

  /*
   * BD: allocate vars and order arrays here if needed.
   * Also initialize a and table to NULL in case we need to clean up.
   */
  a = NULL;
  table = NULL;
  if (vars) {
    *vars = (char **) mem_alloc(sizeof(char *) * (numvars + 1));
    // BD: initialize all to NULL so that we can release memory
    // in case of a read or format error.
    //    (*vars)[numvars] = 0;
    for (i=0; i<= numvars; i++) {
      (*vars)[i] = NULL;
    }
  }
  if (orders) {
    *orders = (int *) mem_alloc(sizeof(int) * numvars);
  }


  if (vars) {
    for (i = 0; i < numvars; i++) {
      (*vars)[i] = (char *) mem_alloc(100);
      if (fscanf(file, " %s ", (*vars)[i]) != 1) {
	goto cleanup;
      }
    }
  }
  else {
    for (i = 0; i < numvars; i++) {
      if (fscanf(file, " %s ", ts) != 1) {
	goto cleanup;
      }
    }
  }
  if (fscanf(file, "orders: ") != 0) {
    goto cleanup;
  }
  if (orders) {
    for (i = 0; i < numvars; i++)
      if (fscanf(file, " %d ", &((*orders)[i])) != 1) {
	goto cleanup;
      }
  }
  else {
    for (i = 0; i < numvars; i++) {
      if (fscanf(file, " %d ", &ti) != 1) {
	goto cleanup;
      }
    }
  }

  if (fscanf(file,
             "states: %u\n"
             "initial: %u\n"
             "bdd nodes: %u\n"
             "final:", 
             &ns, &s, &bdd_nodes) != 3) {
    goto cleanup;
  }

  a = dfaMake(ns);
  a->s = s;

  for (i = 0; i<a->ns; i++) {
    if (fscanf(file, " %d", &a->f[i]) != 1) {
      goto cleanup;
    }
  }

  if (fscanf(file, "\nbehaviour:") != 0) {
    goto cleanup;
  }
  for (i = 0; i < a->ns; i++) {
    if (fscanf(file, " %u", &a->q[i]) != 1) {
      goto cleanup;
    }
  }

  if (fscanf(file, "\nbdd:\n") != 0) {
    goto cleanup;
  }
  table = (BddNode *) mem_alloc(sizeof(BddNode)*bdd_nodes);
  
  for (i = 0; i < bdd_nodes; i++) {
    table[i].p = -1;
    if (fscanf(file, "%i %u %u\n", 
	       &table[i].idx,
	       &table[i].lo,
	       &table[i].hi) != 3) {
      goto cleanup;
    }
  }
  
  if (fgetc(file) != 'e' || fgetc(file) != 'n' || fgetc(file) != 'd') {
    goto cleanup;
  }

  fclose(file);

  /* fill bdd-manager */
  import_bddm = a->bddm;
  for (i = 0; i < a->ns; i++) 
    a->q[i] = make_node(a->q[i]);

  mem_free(table);
  return a;

 cleanup:
  fclose(file);
  if (table != NULL) {
    mem_free(table);
  }
  if (a != NULL) {
    dfaFree(a);
  }
  if (orders) {
    mem_free(*orders);
  }
  if (vars) {
    i = 0;
    while ((*vars)[i] != NULL) {
      mem_free((*vars)[i]);
      i ++;
    }
    mem_free(*vars);
  }

  return NULL;
}
Ejemplo n.º 29
0
int main(int argc, char **argv) {
    //Set up connection
    unsigned int j;
    unsigned int k;
    redisContext *c;
    redisReply *reply;
    const char *hostname = (argc > 3) ? argv[3] : "127.0.0.1";
    int port = (argc > 4) ? atoi(argv[4]) : 6379;

    struct timeval timeout = { 1, 500000 }; // 1.5 seconds
    c = redisConnectWithTimeout(hostname, port, timeout);
    if (c == NULL || c->err) {
        if (c) {
            printf("Connection error: %s\n", c->errstr);
            redisFree(c);
        } else {
            printf("Connection error: can't allocate redis context\n");
        }
        exit(1);
    }

    redisReply *all_keys;
    all_keys = redisCommand(c, "KEYS *");
    
    //For bidirectional, need to use 2 queues, 
    //1 for BFS from the start, and 1 for BFS
    //from the end
    Node *start_queue;
    Node *end_queue;

    //Create hashtables for the visited
    hashtable_t *hashtable_start = ht_create( 65536 );
    //hashtable_t *hashtable_end = ht_create( 65536 );

    //Create hashtable to store hashtable parents
    hashtable_t *hashtable_parents = ht_create( 65536 );
    hashtable_t *hashtable_parents_end = ht_create( 65536 );

    //Path will be found between these two
    char *start = "0000138";
    char *end = "0000197";
    
    //initialize the queues
    start_queue = make_node(start, NULL);
    end_queue = make_node(end, NULL);

    char *start_name = start;
    char *end_name = end;

    //LL for paths
    Node *path_to_meet_s;
    Node *path_to_meet_e;
    path_to_meet_s = make_node(start, NULL);
    path_to_meet_e = make_node(end, NULL);

    //Where do they meet
    char *met1 = start_name;
    char *met2 = end_name;
     
    //while start and end are not NULL
    //while (strcmp(start_name, end_name) != 4389605843690) {
    while ((strcmp(start_name, "NULL") != 0) && (strcmp(end_name, "NULL") != 0)) {

        //kick off the BFS with the start and the end
        start_name = peek(&start_queue);
        end_name = peek(&end_queue);
        //printf("start %s, end %s\n", start_name, end_name);

        //push to their BFS queues
        push(&path_to_meet_s, start_name);
        push(&path_to_meet_e, end_name);
        
        //Check if they exist in the visited hashtable, which is named
        //hashtable_start
        char *check_start = ht_get(hashtable_start, start_name);
        char *check_end = ht_get(hashtable_start, end_name);
        //char *check_end = ht_get(hashtable_end, end_name);
        
        //Same BFS
        if(strcmp(check_start, "NULL")==0){ 
            if (strcmp(end_name, start_name) == 0) {
                met1 = start_name;
                met2 = end_name;
                break;
            } 
            char word_reply1[100] = "";
            strcat(word_reply1, "LRANGE ");
            strcat(word_reply1, start_name);
            strcat(word_reply1, " 0 -1");
            reply = redisCommand(c,word_reply1);
            if (reply->type == REDIS_REPLY_ARRAY) {
                for (k = 0; k < reply->elements; k++) {
                    push(&start_queue, reply->element[k]->str);
                    char *check2_st = ht_get(hashtable_parents, reply->element[k]->str);
                    if (strcmp(check2_st, "NULL") == 0) {
                        ht_set(hashtable_parents, reply->element[k]->str, start_name);
                    }
                }
            }
            
            ht_set(hashtable_start, start_name, "visited");
        }
        
        //Same BFS
        if(strcmp(check_end, "NULL")==0){   
            if (strcmp(end_name, start_name) == 0) {
                met1 = start_name;
                met2 = end_name;
                break;
            } 
            char word_reply2[100] = "";
            strcat(word_reply2, "LRANGE ");
            strcat(word_reply2, end_name);
            strcat(word_reply2, " 0 -1");
            reply = redisCommand(c,word_reply2);
            if (reply->type == REDIS_REPLY_ARRAY) {
                for (k = 0; k < reply->elements; k++) {
                    push(&end_queue, reply->element[k]->str);
                    char *check2_en = ht_get(hashtable_parents_end, reply->element[k]->str);
                    if (strcmp(check2_en, "NULL") == 0) {
                        ht_set(hashtable_parents_end, reply->element[k]->str, end_name);
                    }
                }
            }
            ht_set(hashtable_start, end_name, "visited");
            //ht_set(hashtable_end, end_name, "visited");
        }
        
        //if you haven't reached the same actor from the start and the end
        //keep BFS traversing the front and end until you do
        if (strcmp(start_name, end_name) != 0) {
            pop(&start_queue);
            pop(&end_queue);
        } 
        //Otherwise, you have met, and you should break out of the while
        //loop to build the path
        else { 
            printf("met %s %s", start_name, end_name);
            break; 
        }
        pop(&path_to_meet_s);
        pop(&path_to_meet_e);
    }


    //After the while loop, you have paths to meet
    char *start_parent = peek(&path_to_meet_s);
    char *end_parent = peek(&path_to_meet_e);
    printf("%s ", "success\n");
    /*print_list(path_to_meet_s);
    printf("\n");
    print_list(path_to_meet_e);*/

    reverse(&path_to_meet_s);
    pop(&path_to_meet_s);
    reverse(&path_to_meet_e);
    
    char *parent_st = ht_get(hashtable_parents, start_parent);
    char *parent_en = ht_get(hashtable_parents_end, end_parent);
    while (strcmp(parent_st, start) != 0) {
        push(&path_to_meet_s, parent_st);
        parent_st = ht_get(hashtable_parents, parent_st);
    }
    while (strcmp(parent_en, end) != 0) {
        push(&path_to_meet_e, parent_en);
        parent_en = ht_get(hashtable_parents_end, parent_en);
    }
    push(&path_to_meet_s, parent_st);
    reverse(&path_to_meet_s);
    push(&path_to_meet_e, parent_en);

    //This is the final path
    //print_list(path_to_meet_s);
    print_list(path_to_meet_e);
        
    /* Disconnects and frees the context */
    redisFree(c);

    return 0;
}
Ejemplo n.º 30
0
void list_t_insert_front(int v, list_t *list) {
  list->first = make_node(v, list->first);
}