Example #1
0
void lily_free_symtab(lily_symtab *symtab)
{
    /* Ties have to come first because deref functions rely on type and class
       information. */
    free_ties(symtab, symtab->literals);
    free_ties(symtab, symtab->function_ties);

    free_classes(symtab, symtab->old_class_chain);
    free_vars(symtab, symtab->old_function_chain);

    lily_package *package_iter = symtab->first_package;
    while (package_iter) {
        lily_module_entry *module_iter = package_iter->first_module;
        while (module_iter) {
            free_classes(symtab, module_iter->class_chain);
            free_vars(symtab, module_iter->var_chain);

            module_iter = module_iter->root_next;
        }
        package_iter = package_iter->root_next;
    }

    /* __main__ requires a special teardown because it doesn't allocate names
       for debug, and its code is a shallow copy of emitter's code block. */
    lily_function_val *main_function = symtab->main_function;
    lily_free(main_function);

    lily_free(symtab);
}
Example #2
0
void free_vars(struct vars *v)
{
	if (v == NULL) return;
	free_decl(v->decl);
	free_vars(v->v);
	free(v);
}
Example #3
0
void free_program(struct program *p)
{
	if (p == NULL) return;
	free_vars(p->v);
	free_instruction(p->i);
	free(p);
}
Example #4
0
LCP augment_lcp(const LCP & original,
                vec & x,
                vec & y,
                double scale){
  cout << "Scale: " << scale << endl;
  uint N = original.q.n_elem;
  x = ones<vec>(N);
  y = ones<vec>(N);
  y(find(1 == original.free_vars)).fill(0);
  
  vec r = y - (original.M * x + original.q); // Initial residual
  //[M r]
  //[0 s]
  sp_mat M = sp_mat(N+1,N+1);
  M(span(0,N-1),span(0,N-1)) = original.M;
  M(span(0,N-1),N) = r;
  M(N,N) = scale;

  vec q = vec(N+1);
  q.head(N) = original.q;
  q(N) = 0;

  x.resize(N+1);
  x(N) = 1;
  y.resize(N+1);
  y(N) = scale;

  // New variable is non-negative; all others same.
  bvec free_vars = bvec(N+1);
  free_vars.head(N) = original.free_vars;
  free_vars(N) = 0;
  
  return LCP(M,q,free_vars);
}
Example #5
0
static int count(const char *name)
{
    Rel *r = load(name);
    Vars *wvars = vars_new(0);

    long long sid = tx_enter("", rvars, wvars);
    load_vars();

    rel_eval(r, vars, &arg);

    Tuple *t;
    int i = 0;
    while ((t = tbuf_next(r->body)) != NULL) {
        tuple_free(t);
        i++;
    }

    rel_free(r);
    free_vars();

    tx_commit(sid);

    vars_free(wvars);

    return i;
}
Example #6
0
// Read part_struct data
void cgns_fill_parts(void)
{
  // Open cgns file and get cgns file index number fn
  char buf[FILE_NAME_SIZE];
  sprintf(buf, "%s/%s/%s", SIM_ROOT_DIR, OUTPUT_DIR, partFiles[partFileMap[tt]]);
  int fn;
  int ier = cg_open(buf, CG_MODE_READ, &fn);
  if (ier != 0 ) {
    printf("\nCGNS Error on file %s\n", buf);
    free_vars();
    cg_close(fn);
    cg_error_exit();
  }
  fflush(stdout);
  
  // Set base, zone, and solutions index numbers
  int bn = 1;
  int zn = 1;
  int sn = 1;

  // Read part coords
  double *x = malloc(nparts * sizeof(double));
  double *y = malloc(nparts * sizeof(double));
  double *z = malloc(nparts * sizeof(double));
  for (int p = 0; p < nparts; p++) {
    x[p] = 0;
    y[p] = 0;
    z[p] = 0;
  }

  cgsize_t range_min = 1;
  cgsize_t range_max = nparts;

  cg_coord_read(fn,bn,zn, "CoordinateX", RealDouble, &range_min, &range_max, x);
  cg_coord_read(fn,bn,zn, "CoordinateY", RealDouble, &range_min, &range_max, y);
  cg_coord_read(fn,bn,zn, "CoordinateZ", RealDouble, &range_min, &range_max, z);

  for (int p = 0; p < nparts; p++) {
    parts[p].x = x[p];
    parts[p].y = y[p];
    parts[p].z = z[p];
  }

  // Read part vel
  cg_field_read(fn,bn,zn,sn, "VelocityX", RealDouble, &range_min, &range_max, up);
  cg_field_read(fn,bn,zn,sn, "VelocityY", RealDouble, &range_min, &range_max, vp);
  cg_field_read(fn,bn,zn,sn, "VelocityZ", RealDouble, &range_min, &range_max, wp);

  // Calculate kinetic energy
  for (int p = 0; p < nparts; p++) {
    ke[p] = 0.5*(up[p]*up[p] + vp[p]*vp[p] + wp[p]*wp[p]);
    //ke[p] = 0.5*wp[p]*wp[p];
  }

  free(x);
  free(y);
  free(z);
  
  cg_close(fn);
}
Example #7
0
static void test_call()
{
    char *r[] = { "one_r1" };
    char *w[] = { };
    char *t[] = { "___param" };

    /* simulate a function call whih ignores the return value of a function
       see stmt_call for implementation details */
    Head *head = env_head(env, "one_r1");

    Rel *stmts[] = { rel_store("___param", rel_load(head, "one_r1")),
                     rel_store("___param", rel_load(head, "one_r1")) };

    Rel *fn = rel_call(r, 1, w, 0, t, 1,
                       stmts, 2,
                       NULL, 0,
                       NULL, "",
                       NULL);

    Vars *wvars = vars_new(0);
    long long sid = tx_enter("", rvars, wvars);
    vars_free(wvars);

    load_vars();

    rel_eval(fn, vars, &arg);
    rel_free(fn);
    rel_free(stmts[0]);
    rel_free(stmts[1]);
    free_vars();

    tx_commit(sid);
}
Example #8
0
/*
 * Create a new user session. This is done upon each successful login.
 */
void create_session(unsigned long long sid)
{
	char session_id[SID_LEN + 1];
	char restrict_ip[2] = "0\0";
	char pkbuf[256];
	char timestamp[21];
	char ssid[21];
	char tenant[TENANT_MAX + 1];
	char *username;
	int primary_key_size;
	MYSQL_RES *res;
	TCTDB *tdb;
	TCMAP *cols;
	GHashTable *db_row = NULL;

	username = make_mysql_safe_string(get_var(qvars, "username"));
	res = sql_query("SELECT uid, name, capabilities FROM passwd WHERE "
			"username = '******'", username);
	db_row = get_dbrow(res);

	get_tenant(env_vars.host, tenant);
	generate_hash(session_id, SHA256);

	if (strcmp(get_var(qvars, "restrict_ip"), "true") == 0) {
		d_fprintf(debug_log, "Restricting session to origin ip "
								"address\n");
		restrict_ip[0] = '1';
	}

	tdb = tctdbnew();
	tctdbopen(tdb, SESSION_DB, TDBOWRITER | TDBOCREAT);
	primary_key_size = sprintf(pkbuf, "%ld", (long)tctdbgenuid(tdb));
	snprintf(timestamp, sizeof(timestamp), "%ld", (long)time(NULL));
	snprintf(ssid, sizeof(ssid), "%llu", sid);
	cols = tcmapnew3("tenant", tenant,
			"sid", ssid,
			"uid", get_var(db_row, "uid"),
			"username", get_var(qvars, "username"),
			"name", get_var(db_row, "name"),
			"login_at", timestamp,
			"last_seen", timestamp,
			"origin_ip", env_vars.remote_addr,
			"client_id", env_vars.http_user_agent,
			"session_id", session_id,
			"csrf_token", "\0",
			"restrict_ip", restrict_ip,
			"capabilities", get_var(db_row, "capabilities"),
			NULL);
	tctdbput(tdb, pkbuf, primary_key_size, cols);
	tcmapdel(cols);
	tctdbclose(tdb);
	tctdbdel(tdb);

	fcgx_p("Set-Cookie: session_id=%s; path=/; httponly\r\n", session_id);

	mysql_free_result(res);
	free_vars(db_row);
	free(username);
}
Example #9
0
/*  lily_free_symtab_lits_and_vars

    This frees all literals and vars within the symtab. This is the first step
    to tearing down the symtab, with the second being to call lily_free_symtab.

    Symtab's teardown is in two steps so that the gc can have one final pass
    after the vars get a deref. This allows the gc to attempt cleanly destroying
    all values. It needs signature and class info, which is why that IS NOT
    touched here.

    Additionally, parts of symtab init may have failed, so NULL checks are
    important.

    symtab: The symtab to delete the vars and literals of. */
void lily_free_symtab_lits_and_vars(lily_symtab *symtab)
{
    lily_literal *lit, *lit_temp;

    lit = symtab->lit_start;

    while (lit != NULL) {
        lit_temp = lit->next;

        if (lit->sig->cls->is_refcounted)
            lily_deref_string_val(lit->value.string);

        lily_free(lit);

        lit = lit_temp;
    }

    /* This should be okay, because nothing will want to use the vars at this
       point. */
    if (symtab->classes != NULL) {
        int i;
        for (i = 0;i <= symtab->class_pos;i++) {
            lily_class *cls = symtab->classes[i];
            if (cls != NULL && cls->call_start != NULL)
                free_vars(cls->call_start);
        }
    }

    lily_function_val *main_function;

    if (symtab->var_start &&
        ((symtab->var_start->flags & VAL_IS_NIL) == 0))
        main_function = symtab->var_start->value.function;
    else
        main_function = NULL;

    if (symtab->var_start != NULL)
        free_vars(symtab->var_start);
    if (symtab->old_function_chain != NULL)
        free_vars(symtab->old_function_chain);

    if (main_function != NULL)
        free_lily_main(main_function);
}
Example #10
0
static int	build_cd_check_for_env(t_data *d)
{
	char	*home;
	char	*pwd;
	char	*oldpwd;

	home = ft_getenv("HOME", d->cenv);
	oldpwd = ft_getenv("OLDPWD", d->cenv);
	pwd = ft_getenv("PWD", d->cenv);
	if (oldpwd == NULL || pwd == NULL || home == NULL)
	{
		ft_putstr_fd("Cannot run `cd' without HOME or OLDPWD, PWD\n", 2);
		d->current->exedone = 1;
		free_vars(home, pwd, oldpwd);
		return (0);
	}
	free_vars(home, pwd, oldpwd);
	return (1);
}
Example #11
0
int dotest ()
{
    int v,p;
    double *d;
    time_t tbegin, tput, tget;
    alloc_vars();
    qhashtbl_t *tbl = qhashtbl(range);

    /* Put all data values with path/var into hashtable */
    printf("============== PUT DATA INTO HASHTABLE ============\n");
    time (&tbegin);
    for (p=0; p<npaths; p++) {
        for (v=0; v<nvars; v++) {
            tbl->put2(tbl, varpaths[p], varnames[v], &data[p*nvars+v]);
        }
    }
    time (&tput);
    tput = tput - tbegin;

    /* Get each element and check value */
    printf("============== GET DATA FROM HASHTABLE ============\n");
    time (&tbegin);
    for (p=npaths-1; p>=0; p--) {
        for (v=nvars-1; v>=0; v--) {
            d = tbl->get2(tbl, varpaths[p], varnames[v]);
            if (d == NULL) {
                printf ("ERROR: stored value for p=%d,v=%d not found in hash table\n",
                        p, v);
                return 1;
            } else if (*d != data[p*nvars+v]) {
                printf ("ERROR: for p=%d,v=%d, found value = %lf in hash table != "
                        "what was put in = %lf\n",
                        p, v, *d, data[p*nvars+v]);
                return 2;
            }

        }
    }
    time (&tget);
    tget = tget - tbegin;
    printf("Timing: put %d elements in %ld seconds, got them back in %ld seconds\n",
            npaths*nvars, (long)tput, (long)tget);

    /* Print hashtable */
    printf("============== PRINT HASHTABLE ============\n");
    tbl->debug(tbl,NULL,0);

    /* Free hashtable */
    tbl->free(tbl);

    free_vars();
    return 0;
}
Example #12
0
int main(void) 
{
  // Read input file
  main_read_input();

  // Read and sort output directory for finding files within our time limits
  init_part_files();
  init_flow_files();

  // Create output directory
  create_output_dir();

  // Get number of particles
  nparts = cgns_read_nparts();

  // Initialize domain and flow arrays
  domain_init(); 

  // Initialize partstruct and flow vars
  parts_init();
  flow_init();

  // Messy hack for taking advantage of CUDA_VISIBLE_DEVICES in SLURM
  dev_start = read_devices();

  // Allocate device memory
  cuda_dev_malloc();
  cuda_dom_push(); 
  //cuda_part_push();
  //cuda_part_pull();

  // Calculate tetrad stats
  for (tt = 0; tt < nFiles; tt++) {
    // Read in new data and push to device
    cgns_fill_flow();
    cuda_flow_push();

    // Calculate phase average
    cuda_phase_averaged_vel();
  }

  // write phaseAvereaged to file
  write_part_data();
   
  // Free and exit
  free_vars();
  cuda_dev_free();
  return EXIT_SUCCESS;
}
Example #13
0
static void free_classes(lily_symtab *symtab, lily_class *class_iter)
{
    while (class_iter) {
        lily_free(class_iter->name);

        if (class_iter->flags & CLS_IS_VARIANT) {
            lily_class *class_next = class_iter->next;
            lily_free(class_iter);
            class_iter = class_next;
            continue;
        }

        if (class_iter->properties != NULL)
            free_properties(symtab, class_iter);

        if (class_iter->call_chain != NULL)
            free_vars(symtab, class_iter->call_chain);

        lily_type *type_iter = class_iter->all_subtypes;
        lily_type *type_next;
        while (type_iter) {
            type_next = type_iter->next;
            lily_free(type_iter->subtypes);
            lily_free(type_iter);
            type_iter = type_next;
        }

        if (class_iter->flags & CLS_ENUM_IS_SCOPED) {
            /* Scoped enums pull their variants from the symtab's class chain so
               that parser won't find them. */
            int i;
            for (i = 0;i < class_iter->variant_size;i++) {
                lily_free(class_iter->variant_members[i]->name);
                lily_free(class_iter->variant_members[i]);
            }
        }

        lily_free(class_iter->variant_members);

        lily_class *class_next = class_iter->next;
        lily_free(class_iter);
        class_iter = class_next;
    }
}
Example #14
0
int main(int argc, char *argv[]){

	int c;
	Hmm *in_hmm;
	Hmm *out_hmm;
	Obs *in_obs;
	char *configfile = NULL;
	float log_lik;
	struct timeval timer;

	in_hmm = (Hmm *)malloc(sizeof(Hmm));
	out_hmm = (Hmm *)malloc(sizeof(Hmm));
	in_obs = (Obs *)malloc(sizeof(Obs));

	while ((c = getopt(argc, argv, "c:n:")) != -1) {
		switch(c) {
			case 'c':
				configfile = optarg;
				break;
			case '?':
				fprintf(stderr, "illegal options\n");
				exit(EXIT_FAILURE);

			default:
				abort();
		}
	}
	read_hmm_file(configfile, in_hmm, in_obs, 0);

	printf("\n");
	printf("HMM parameters read from file: \n");
	print_hmm(in_hmm);
	print_obs(in_obs);

	tic(&timer);
	log_lik = run_hmm_fo(in_hmm, in_obs);
	toc(&timer);
	printf("Log likelihood: %0.4f\n", log_lik);

	free_vars(in_hmm, in_obs);

	return 0;
}
Example #15
0
static void test_store()
{
    Rel *r = load("one_r1");

    Vars *wvars = vars_new(1);
    vars_add(wvars, "one_r1_cpy", 0, NULL);

    long long sid = tx_enter("", rvars, wvars);

    load_vars();
    rel_eval(r, vars, &arg);
    vol_write(wvars->vols[0], r->body, wvars->names[0], wvars->vers[0]);
    rel_free(r);
    free_vars();

    tx_commit(sid);

    vars_free(wvars);
    if (!equal(load("one_r1"), "one_r1_cpy"))
        fail();

    /* TODO: test reassignment in one statement logic */
}
Example #16
0
static int equal(Rel *left, const char *name)
{
    Rel *right = load(name);
    Vars *wvars = vars_new(0);

    long long sid = tx_enter("", rvars, wvars);
    load_vars();

    rel_eval(left, vars, &arg);
    rel_eval(right, vars, &arg);

    int res = rel_eq(left, right);

    rel_free(left);
    rel_free(right);
    free_vars();

    tx_commit(sid);

    vars_free(wvars);

    return res;
}
Example #17
0
int main(int argc, char *argv[]) 
{
  // Set directory structure
  directory_init(argc, argv);

  // Read input file
  main_read_input();

  // Read and sort output directory for finding files within our time limits
  init_part_files();

  // Get number of particles
  nparts = cgns_read_nparts();

  // Initialize domain and flow arrays
  #ifdef DEBUG
    show_domain();
  #endif

  // Create output directory
  create_output();

  // Loop over time
  //double inparts = 1./nparts;
  //double inFiles = 1./nFiles;
  for (int tt = 0; tt < nFiles; tt++) {
    int sum = cgns_fill_parts(tt);
    printf("t = %lf, sum = %d\n", partFileTime[tt], sum);

    // write to file
    write_mean(tt, sum);
  }

  // Free and exit
  free_vars();
  return EXIT_SUCCESS;
}
Example #18
0
static int equal_clone(const char *name)
{
    Rel *cp1 = load(name);
    Rel *cp2 = load(name);
    Vars *wvars = vars_new(0);

    long long sid = tx_enter("", rvars, wvars);
    load_vars();

    rel_eval(cp1, vars, &arg);
    rel_eval(cp2, vars, &arg);

    int res = rel_eq(cp1, cp2);

    rel_free(cp1);
    rel_free(cp2);
    free_vars();

    tx_commit(sid);

    vars_free(wvars);

    return res;
}
Example #19
0
static PyObject *
GMPy_MPZ_is_aprcl_prime(PyObject *self, PyObject *other)
{
  mpz_t N;
  s64_t T, U;
  int i, j, H, I, J, K, P, Q, W, X;
  int IV, InvX, LEVELnow, NP, PK, PL, PM, SW, VK, TestedQs, TestingQs;
  int QQ, T1, T3, U1, U3, V1, V3;
  int break_this = 0;
  MPZ_Object *tempx;

  if (!(tempx = GMPy_MPZ_From_Integer(other, NULL))) {
    TYPE_ERROR("is_aprcl_prime() requires 'mpz' argument");
    return NULL;
  }

  mpz_init(N);
  mpz_set(N, tempx->z);
  Py_DECREF(tempx);

  /* make sure the input is >= 2 and odd */
  if (mpz_cmp_ui(N, 2) < 0)
    Py_RETURN_FALSE;

  if (mpz_divisible_ui_p(N, 2)) {
    if (mpz_cmp_ui(N, 2) == 0)
      Py_RETURN_TRUE;
    else
      Py_RETURN_FALSE;
  }

  /* only three small exceptions for this implementation */
  /* with this set of P and Q primes */
  if (mpz_cmp_ui(N, 3) == 0)
    Py_RETURN_TRUE;
  if (mpz_cmp_ui(N, 7) == 0)
    Py_RETURN_TRUE;
  if (mpz_cmp_ui(N, 11) == 0)
    Py_RETURN_TRUE;

  /* If the input number is larger than 7000 decimal digits
     we will just return whether it is a BPSW (probable) prime */
  NumberLength = mpz_sizeinbase(N, 10);
  if (NumberLength > 7000) {
      VALUE_ERROR("value too large to test");
      return NULL;
  }

  allocate_vars();

  mpz_set(TestNbr, N);
  mpz_set_si(biS, 0);

  j = PK = PL = PM = 0;
  for (J = 0; J < PWmax; J++) {
    /* aiJX[J] = 0; */
    mpz_set_ui(aiJX[J], 0);
  }
  break_this = 0;
/* GetPrimes2Test : */
  for (i = 0; i < LEVELmax; i++) {
    /* biS[0] = 2; */
    mpz_set_ui(biS, 2);

    for (j = 0; j < aiNQ[i]; j++) {
      Q = aiQ[j];
      if (aiT[i]%(Q-1) != 0)
        continue;
      U = aiT[i] * Q;
      do {
        U /= Q;
        /* MultBigNbrByLong(biS, Q, biS, NumberLength); */
        mpz_mul_ui(biS, biS, Q);
      } while (U % Q == 0);

      // Exit loop if S^2 > N.
      if (CompareSquare(biS, TestNbr) > 0) {
        /* break GetPrimes2Test; */
        break_this = 1;
        break;
      }
    } /* End for j */

    if (break_this) break;
  } /* End for i */

  if (i == LEVELmax)
  { /* too big */
    free_vars();
    VALUE_ERROR("value too large to test");
    return NULL;
  }
  LEVELnow = i;
  TestingQs = j;
  T = aiT[LEVELnow];
  NP = aiNP[LEVELnow];

MainStart:
  for (;;)
  {
    for (i = 0; i < NP; i++)
    {
      P = aiP[i];
      if (T%P != 0) continue;

      SW = TestedQs = 0;
      /* Q = W = (int) BigNbrModLong(TestNbr, P * P); */
      Q = W = mpz_fdiv_ui(TestNbr, P * P);
      for (J = P - 2; J > 0; J--)
      {
        W = (W * Q) % (P * P);
      }
      if (P > 2 && W != 1)
      {
        SW = 1;
      }
      for (;;)
      {
        for (j = TestedQs; j <= TestingQs; j++)
        {
          Q = aiQ[j] - 1;
          /* G = aiG[j]; */
          K = 0;
          while (Q % P == 0)
          {
            K++;
            Q /= P;
          }
          Q = aiQ[j];
          if (K == 0)
          {
            continue;
          }

          PM = 1;
          for (I = 1; I < K; I++)
          {
            PM = PM * P;
          }
          PL = (P - 1) * PM;
          PK = P * PM;
          for (I = 0; I < PK; I++)
          {
            /* aiJ0[I] = aiJ1[I] = 0; */
            mpz_set_ui(aiJ0[I], 0);
            mpz_set_ui(aiJ1[I], 0);
          }
          if (P > 2)
          {
            JacobiSum(0, P, PL, Q);
          }
          else
          {
            if (K != 1)
            {
              JacobiSum(0, P, PL, Q);
              for (I = 0; I < PK; I++)
              {
                /* aiJW[I] = 0; */
                mpz_set_ui(aiJW[I], 0);
              }
              if (K != 2)
              {
                for (I = 0; I < PM; I++)
                {
                  /* aiJW[I] = aiJ0[I]; */
                  mpz_set(aiJW[I], aiJ0[I]);
                }
                JacobiSum(1, P, PL, Q);
                for (I = 0; I < PM; I++)
                {
                  /* aiJS[I] = aiJ0[I]; */
                  mpz_set(aiJS[I], aiJ0[I]);
                }
                JS_JW(PK, PL, PM, P);
                for (I = 0; I < PM; I++)
                {
                  /* aiJ1[I] = aiJS[I]; */
                  mpz_set(aiJ1[I], aiJS[I]);
                }
                JacobiSum(2, P, PL, Q);
                for (I = 0; I < PK; I++)
                {
                  /* aiJW[I] = 0; */
                  mpz_set_ui(aiJW[I], 0);
                }
                for (I = 0; I < PM; I++)
                {
                  /* aiJS[I] = aiJ0[I]; */
                  mpz_set(aiJS[I], aiJ0[I]);
                }
                JS_2(PK, PL, PM, P);
                for (I = 0; I < PM; I++)
                {
                  /* aiJ2[I] = aiJS[I]; */
                  mpz_set(aiJ2[I], aiJS[I]);
                }
              }
            }
          }
          /* aiJ00[0] = aiJ01[0] = 1; */
          mpz_set_ui(aiJ00[0], 1);
          mpz_set_ui(aiJ01[0], 1);
          for (I = 1; I < PK; I++)
          {
            /* aiJ00[I] = aiJ01[I] = 0; */
            mpz_set_ui(aiJ00[I], 0);
            mpz_set_ui(aiJ01[I], 0);
          }
          /* VK = (int) BigNbrModLong(TestNbr, PK); */
          VK = mpz_fdiv_ui(TestNbr, PK);
          for (I = 1; I < PK; I++)
          {
            if (I % P != 0)
            {
              U1 = 1;
              U3 = I;
              V1 = 0;
              V3 = PK;
              while (V3 != 0)
              {
                QQ = U3 / V3;
                T1 = U1 - V1 * QQ;
                T3 = U3 - V3 * QQ;
                U1 = V1;
                U3 = V3;
                V1 = T1;
                V3 = T3;
              }
              aiInv[I] = (U1 + PK) % PK;
            }
            else
            {
              aiInv[I] = 0;
            }
          }
          if (P != 2)
          {
            for (IV = 0; IV <= 1; IV++)
            {
              for (X = 1; X < PK; X++)
              {
                for (I = 0; I < PK; I++)
                {
                  /* aiJS[I] = aiJ0[I]; */
                  mpz_set(aiJS[I], aiJ0[I]);
                }
                if (X % P == 0)
                {
                  continue;
                }
                if (IV == 0)
                {
                  /* LongToBigNbr(X, biExp, NumberLength); */
                  mpz_set_ui(biExp, X);
                }
                else
                {
                  /* LongToBigNbr(VK * X / PK, biExp, NumberLength); */
                  mpz_set_ui(biExp, (VK * X) / PK);
                  if ((VK * X) / PK == 0)
                  {
                    continue;
                  }
                }
                JS_E(PK, PL, PM, P);
                for (I = 0; I < PK; I++)
                {
                  /* aiJW[I] = 0; */
                  mpz_set_ui(aiJW[I], 0);
                }
                InvX = aiInv[X];
                for (I = 0; I < PK; I++)
                {
                  J = (I * InvX) % PK;
                  /* AddBigNbrModN(aiJW[J], aiJS[I], aiJW[J], TestNbr, NumberLength); */
                  mpz_add(aiJW[J], aiJW[J], aiJS[I]);
                }
                NormalizeJW(PK, PL, PM, P);
                if (IV == 0)
                {
                  for (I = 0; I < PK; I++)
                  {
                    /* aiJS[I] = aiJ00[I]; */
                    mpz_set(aiJS[I], aiJ00[I]);
                  }
                }
                else
                {
                  for (I = 0; I < PK; I++)
                  {
                    /* aiJS[I] = aiJ01[I]; */
                    mpz_set(aiJS[I], aiJ01[I]);
                  }
                }
                JS_JW(PK, PL, PM, P);
                if (IV == 0)
                {
                  for (I = 0; I < PK; I++)
                  {
                    /* aiJ00[I] = aiJS[I]; */
                    mpz_set(aiJ00[I], aiJS[I]);
                  }
                }
                else
                {
                  for (I = 0; I < PK; I++)
                  {
                    /* aiJ01[I] = aiJS[I]; */
                    mpz_set(aiJ01[I], aiJS[I]);
                  }
                }
              } /* end for X */
            } /* end for IV */
          }
          else
          {
            if (K == 1)
            {
              /* MultBigNbrByLongModN(1, Q, aiJ00[0], TestNbr, NumberLength); */
              mpz_set_ui(aiJ00[0], Q);
              /* aiJ01[0] = 1; */
              mpz_set_ui(aiJ01[0], 1);
            }
            else
            {
              if (K == 2)
              {
                if (VK == 1)
                {
                  /* aiJ01[0] = 1; */
                  mpz_set_ui(aiJ01[0], 1);
                }
                /* aiJS[0] = aiJ0[0]; */
                /* aiJS[1] = aiJ0[1]; */
                mpz_set(aiJS[0], aiJ0[0]);
                mpz_set(aiJS[1], aiJ0[1]);
                JS_2(PK, PL, PM, P);
                if (VK == 3)
                {
                  /* aiJ01[0] = aiJS[0]; */
                  /* aiJ01[1] = aiJS[1]; */
                  mpz_set(aiJ01[0], aiJS[0]);
                  mpz_set(aiJ01[1], aiJS[1]);
                }
                /* MultBigNbrByLongModN(aiJS[0], Q, aiJ00[0], TestNbr, NumberLength); */
                mpz_mul_ui(aiJ00[0], aiJS[0], Q);
                /* MultBigNbrByLongModN(aiJS[1], Q, aiJ00[1], TestNbr, NumberLength); */
                mpz_mul_ui(aiJ00[1], aiJS[1], Q);
              }
              else
              {
                for (IV = 0; IV <= 1; IV++)
                {
                  for (X = 1; X < PK; X += 2)
                  {
                    for (I = 0; I <= PM; I++)
                    {
                      /* aiJS[I] = aiJ1[I]; */
                      mpz_set(aiJS[I], aiJ1[I]);
                    }
                    if (X % 8 == 5 || X % 8 == 7)
                    {
                      continue;
                    }
                    if (IV == 0)
                    {
                      /* LongToBigNbr(X, biExp, NumberLength); */
                      mpz_set_ui(biExp, X);
                    }
                    else
                    {
                      /* LongToBigNbr(VK * X / PK, biExp, NumberLength); */
                      mpz_set_ui(biExp, VK * X / PK);
                      if (VK * X / PK == 0)
                      {
                        continue;
                      }
                    }
                    JS_E(PK, PL, PM, P);
                    for (I = 0; I < PK; I++)
                    {
                      /* aiJW[I] = 0; */
                      mpz_set_ui(aiJW[I], 0);
                    }
                    InvX = aiInv[X];
                    for (I = 0; I < PK; I++)
                    {
                      J = I * InvX % PK;
                      /* AddBigNbrModN(aiJW[J], aiJS[I], aiJW[J], TestNbr, NumberLength); */
                      mpz_add(aiJW[J], aiJW[J], aiJS[I]);
                    }
                    NormalizeJW(PK, PL, PM, P);
                    if (IV == 0)
                    {
                      for (I = 0; I < PK; I++)
                      {
                        /* aiJS[I] = aiJ00[I]; */
                        mpz_set(aiJS[I], aiJ00[I]);
                      }
                    }
                    else
                    {
                      for (I = 0; I < PK; I++)
                      {
                        /* aiJS[I] = aiJ01[I]; */
                        mpz_set(aiJS[I], aiJ01[I]);
                      }
                    }
                    NormalizeJS(PK, PL, PM, P);
                    JS_JW(PK, PL, PM, P);
                    if (IV == 0)
                    {
                      for (I = 0; I < PK; I++)
                      {
                        /* aiJ00[I] = aiJS[I]; */
                        mpz_set(aiJ00[I], aiJS[I]);
                      }
                    }
                    else
                    {
                      for (I = 0; I < PK; I++)
                      {
                        /* aiJ01[I] = aiJS[I]; */
                        mpz_set(aiJ01[I], aiJS[I]);
                      }
                    }
                  } /* end for X */
                  if (IV == 0 || VK % 8 == 1 || VK % 8 == 3)
                  {
                    continue;
                  }
                  for (I = 0; I < PM; I++)
                  {
                    /* aiJW[I] = aiJ2[I]; */
                    /* aiJS[I] = aiJ01[I]; */
                    mpz_set(aiJW[I], aiJ2[I]);
                    mpz_set(aiJS[I], aiJ01[I]);
                  }
                  for (; I < PK; I++)
                  {
                    /* aiJW[I] = aiJS[I] = 0; */
                    mpz_set_ui(aiJW[I], 0);
                    mpz_set_ui(aiJS[I], 0);
                  }
                  JS_JW(PK, PL, PM, P);
                  for (I = 0; I < PM; I++)
                  {
                    /* aiJ01[I] = aiJS[I]; */
                    mpz_set(aiJ01[I], aiJS[I]);
                  }
                } /* end for IV */
              }
            }
          }
          for (I = 0; I < PL; I++)
          {
            /* aiJS[I] = aiJ00[I]; */
            mpz_set(aiJS[I], aiJ00[I]);
          }
          for (; I < PK; I++)
          {
            /* aiJS[I] = 0; */
            mpz_set_ui(aiJS[I], 0);
          }
          /* DivBigNbrByLong(TestNbr, PK, biExp, NumberLength); */
          mpz_fdiv_q_ui(biExp, TestNbr, PK);
          JS_E(PK, PL, PM, P);
          for (I = 0; I < PK; I++)
          {
            /* aiJW[I] = 0; */
            mpz_set_ui(aiJW[I], 0);
          }
          for (I = 0; I < PL; I++)
          {
            for (J = 0; J < PL; J++)
            {
              /* MontgomeryMult(aiJS[I], aiJ01[J], biTmp); */
              /* AddBigNbrModN(biTmp, aiJW[(I + J) % PK], aiJW[(I + J) % PK], TestNbr, NumberLength); */
              mpz_mul(biTmp, aiJS[I], aiJ01[J]);
              mpz_add(aiJW[(I + J) % PK], biTmp, aiJW[(I + J) % PK]);
            }
          }
          NormalizeJW(PK, PL, PM, P);
/* MatchingRoot : */
          do
          {
            H = -1;
            W = 0;
            for (I = 0; I < PL; I++)
            {
              if (mpz_cmp_ui(aiJW[I], 0) != 0)/* (!BigNbrIsZero(aiJW[I])) */
              {
                /* if (H == -1 && BigNbrAreEqual(aiJW[I], 1)) */
                if (H == -1 && (mpz_cmp_ui(aiJW[I], 1) == 0))
                {
                  H = I;
                }
                else
                {
                  H = -2;
                  /* AddBigNbrModN(aiJW[I], MontgomeryMultR1, biTmp, TestNbr, NumberLength); */
                  mpz_add_ui(biTmp, aiJW[I], 1);
                  mpz_mod(biTmp, biTmp, TestNbr);
                  if (mpz_cmp_ui(biTmp, 0) == 0) /* (BigNbrIsZero(biTmp)) */
                  {
                    W++;
                  }
                }
              }
            }
            if (H >= 0)
            {
              /* break MatchingRoot; */
              break;
            }
            if (W != P - 1)
            {
              /* Not prime */
              free_vars();
              Py_RETURN_FALSE;
            }
            for (I = 0; I < PM; I++)
            {
              /* AddBigNbrModN(aiJW[I], 1, biTmp, TestNbr, NumberLength); */
              mpz_add_ui(biTmp, aiJW[I], 1);
              mpz_mod(biTmp, biTmp, TestNbr);
              if (mpz_cmp_ui(biTmp, 0) == 0) /* (BigNbrIsZero(biTmp)) */
              {
                break;
              }
            }
            if (I == PM)
            {
              /* Not prime */
              free_vars();
              Py_RETURN_FALSE;
            }
            for (J = 1; J <= P - 2; J++)
            {
              /* AddBigNbrModN(aiJW[I + J * PM], 1, biTmp, TestNbr, NumberLength); */
              mpz_add_ui(biTmp, aiJW[I + J * PM], 1);
              mpz_mod(biTmp, biTmp, TestNbr);
              if (mpz_cmp_ui(biTmp, 0) != 0)/* (!BigNbrIsZero(biTmp)) */
              {
                /* Not prime */
                free_vars();
                Py_RETURN_FALSE;
              }
            }
            H = I + PL;
          }
          while (0);

          if (SW == 1 || H % P == 0)
          {
            continue;
          }
          if (P != 2)
          {
            SW = 1;
            continue;
          }
          if (K == 1)
          {
            if ((mpz_get_ui(TestNbr) & 3) == 1)
            {
              SW = 1;
            }
            continue;
          }

          // if (Q^((N-1)/2) mod N != N-1), N is not prime.

          /* MultBigNbrByLongModN(1, Q, biTmp, TestNbr, NumberLength); */
          mpz_set_ui(biTmp, Q);
          mpz_mod(biTmp, biTmp, TestNbr);

          mpz_sub_ui(biT, TestNbr, 1); /* biT = n-1 */
          mpz_divexact_ui(biT, biT, 2); /* biT = (n-1)/2 */
          mpz_powm(biR, biTmp, biT, TestNbr); /* biR = Q^((n-1)/2) mod n */
          mpz_add_ui(biTmp, biR, 1);
          mpz_mod(biTmp, biTmp, TestNbr);

          if (mpz_cmp_ui(biTmp, 0) != 0)/* (!BigNbrIsZero(biTmp)) */
          {
            /* Not prime */
            free_vars();
            Py_RETURN_FALSE;
          }
          SW = 1;
        } /* end for j */
        if (SW == 0)
        {
          TestedQs = TestingQs + 1;
          if (TestingQs < aiNQ[LEVELnow] - 1)
          {
            TestingQs++;
            Q = aiQ[TestingQs];
            U = T * Q;
            do
            {
              /* MultBigNbrByLong(biS, Q, biS, NumberLength); */
              mpz_mul_ui(biS, biS, Q);
              U /= Q;
            }
            while (U % Q == 0);

            continue; /* Retry */
          }
          LEVELnow++;
          if (LEVELnow == LEVELmax)
          {
            free_vars();
            // return mpz_bpsw_prp(N); /* Cannot tell */
            VALUE_ERROR("maximum levels reached");
            return NULL;
          }
          T = aiT[LEVELnow];
          NP = aiNP[LEVELnow];
          /* biS = 2; */
          mpz_set_ui(biS, 2);
          for (J = 0; J <= aiNQ[LEVELnow]; J++)
          {
            Q = aiQ[J];
            if (T%(Q-1) != 0) continue;
            U = T * Q;
            do
            {
              /* MultBigNbrByLong(biS, Q, biS, NumberLength); */
              mpz_mul_ui(biS, biS, Q);
              U /= Q;
            }
            while (U % Q == 0);
            if (CompareSquare(biS, TestNbr) > 0)
            {
              TestingQs = J;
              /* continue MainStart; */ /* Retry from the beginning */
              goto MainStart;
            }
          } /* end for J */
          free_vars();
          VALUE_ERROR("internal failure");
          return NULL;
        } /* end if */
        break;
      } /* end for (;;) */
    } /* end for i */

    // Final Test

    /* biR = 1 */
    mpz_set_ui(biR, 1);
    /* biN <- TestNbr mod biS */ /* Compute N mod S */
    mpz_fdiv_r(biN, TestNbr, biS);

    for (U = 1; U <= T; U++)
    {
      /* biR <- (biN * biR) mod biS */
      mpz_mul(biR, biN, biR);
      mpz_mod(biR, biR, biS);
      if (mpz_cmp_ui(biR, 1) == 0) /* biR == 1 */
      {
        /* Number is prime */
        free_vars();
        Py_RETURN_TRUE;
      }
      if (mpz_divisible_p(TestNbr, biR) && mpz_cmp(biR, TestNbr) < 0) /* biR < N and biR | TestNbr */
      {
        /* Number is composite */
        free_vars();
        Py_RETURN_FALSE;
      }
    } /* End for U */
    /* This should never be reached. */
    free_vars();
    SYSTEM_ERROR("Internal error: APR-CL error with final test.");
    return NULL;
  }
}
Example #20
0
PLCP augment_plcp(const PLCP & original,
                  vec & x,
                  vec & y,
                  vec & w,
                  double scale){
  
  uint N = original.P.n_rows;
  uint K = original.P.n_cols;
  assert(size(K,N) == size(original.U));

  
  sp_mat P = sp_mat(original.P);
  double I_norm = norm(speye(K,K) - P.t() * P);
  if(norm(I_norm) >= PRETTY_SMALL){
    cerr << "Error: P does not look orthogonal ("
	 << I_norm << ")..." << endl;
  }
  assert(I_norm < PRETTY_SMALL);
  
  sp_mat U = sp_mat(original.U);
  vec q = vec(original.q);
  assert(all(q(find(1 == original.free_vars)) <= 0));


  vec q_neg = min(zeros<vec>(N),q);
  vec q_pos = max(zeros<vec>(N),q);
  x = ones<vec>(N) - q_neg;
  y = ones<vec>(N) + q_pos;
  y(find(1 == original.free_vars)).fill(0);
  assert(norm(q_pos(find(1 == original.free_vars))) < ALMOST_ZERO);
  
  assert(N == x.n_elem);
  assert(N == y.n_elem);
  assert(all(x >= 0));
  assert(all(y >= 0));

  vec res = x - y + q;
  w = spsolve(P.t()*P + 1e-15*speye(K,K),P.t()*(x - y + q));

  vec w_res = P * w - res;
  if(norm(w_res) >= PRETTY_SMALL){
    cerr << "Error: Reduced vector w residual large ("
	 << w_res << ")..." << endl;
  }

  assert(norm(w_res) < PRETTY_SMALL);
  
  vec b = P.t()*x - U*x - w;
  assert(K == b.n_elem);
  
  P.resize(N+1,K+1);
  U.resize(K+1,N+1);
  q.resize(N+1);
  
  P(N,K) = 1.0;
  U(span(0,K-1),N) = b;
  U(K,N) = scale;
  q(N) = 0;

  x.resize(N+1);
  y.resize(N+1);
  w.resize(K+1);

  x(N) = 1;
  y(N) = scale;
  w(K) = 1.0 - scale;
  
  bvec free_vars = bvec(N+1);
  free_vars.head(N) = original.free_vars;
  free_vars(N) = 0;
  
  return PLCP(P,U,q,free_vars);
}
Example #21
0
static void free_stack_node(stack_node *node)
{
  free_vars(&node->locals);
  free_vars(&node->formals);
  free(node);
}
Example #22
0
cons_t eval(cons_t *c, var_t *local_vars){
	cons_t p;
	switch(c->type){
	case TYPE_OPERATE:{
		int (*func)(int x, int y) = c->v.func;
		int n;
		if(c->cdr == NULL){
			printf("operate error\n");
			return p;
		}
		n  = eval(c->cdr, local_vars).v.i;
		c = c->cdr->cdr;
		while(c != NULL){
			p = eval(c, local_vars);
			n = func(n, p.v.i);
			c = c->cdr;
		}
		p.type = TYPE_INT;
		p.v.i = n;
		return p;
	}

	case TYPE_COMPARE:{
		int (*func)(int x, int y) = c->v.func;
		if(c->cdr == NULL || c->cdr->cdr == NULL){
			printf("compare error\n");
			return p;
		}
		int n1 = eval(c->cdr, local_vars).v.i;
		int n2 = eval(c->cdr->cdr, local_vars).v.i;
		p.type = func(n1, n2);
		return p;
	}
		
	case TYPE_IF:
		p = eval(c->cdr, local_vars);
		if(p.type != TYPE_NIL){
			return eval(c->cdr->cdr, local_vars);
		}else{
			return eval(c->cdr->cdr->cdr, local_vars);
		}

	case TYPE_SETQ:
		c = c->cdr;
		if(c->type == TYPE_STR){
			p = eval(c->cdr, local_vars);
			if(p.type == TYPE_INT){
				const char *name = c->v.str;
				int value = p.v.i;
				global_vars = set_var_value(global_vars, name, value);
				return p;
			}else{
				printf("setq error 1");
			}
		}else{
				printf("setq error 2");
		}
		break;

	case TYPE_DEFUN:
		c = c->cdr;
		funcs = set_func(funcs, c->v.str, c->cdr->v.car, c->cdr->cdr->v.car);
		p.type = TYPE_DEFUN;
		return p;

	case TYPE_STR:{
		func_t *f = get_func(funcs, c->v.str);
		if(f != NULL){
			// function?
			cons_t *args = f->args;
			var_t *locals = NULL;
			c = c->cdr;
			while(args != NULL){
				if(c == NULL){
					printf("func argument error\n");
					return p;
				}
				cons_t p = eval(c, local_vars);
				locals = set_var_value(locals, args->v.str, p.v.i);

				args = args->cdr;
				c = c->cdr;
			}
			p = eval(f->car, locals);
			free_vars(locals);
		}else{
			var_t *v;
			// local variable?
			v = get_var_value(local_vars, c->v.str);
			if(v == NULL){
				// global variable?
				v = get_var_value(global_vars, c->v.str);
			}
			if(v == NULL){
				printf("var get error\n");
				return p;
			}
			p.type = TYPE_INT;
			p.v.i = v->value;
		}
		break;
	}

	case TYPE_INT:
		return *c;

	case TYPE_CAR:
		return eval(c->v.car, local_vars);
	
	default:
		printf("error type %d\n", c->type);
	}
	return p;
}
Example #23
0
int main(int argc, char *argv[]) 
{
  // Set directory structure
  directory_init(argc, argv);

  printf("Initializing...\n"); 
  fflush(stdout);
  // Read input file
  main_read_input();

  // Read and sort output directory for finding files within our time limits
  init_files();

  // Initialize domain and flow arrays
  domain_init(); 

  // Create output directory
  create_output();
  get_sigfigs();

  // Pull initial time step
  tt = 0;
  cgns_fill();

  // Find min and max and set up bins
  minmax(&min_vf, &max_vf, volume_fraction);
  minmax(&min_wp, &max_wp, part_w);
  minmax(&min_ke, &max_ke, part_ke);
  bin_init(min_vf, max_vf, &dBin_vf, &binStart_vf, &binEnd_vf);
  bin_init(min_wp, max_wp, &dBin_wp, &binStart_wp, &binEnd_wp);
  bin_init(min_ke, max_ke, &dBin_ke, &binStart_ke, &binEnd_ke);

  #ifdef DEBUG
    printf("  Bin Start (vf) = %lf\n", binStart_vf);
    printf("  Min (vf) = %lf\n", min_vf);
    printf("  dBin (vf) = %lf\n", dBin_vf);
    printf("  Max (vf) = %lf\n", max_vf);
    printf("  Bin End (vf) = %lf\n", binEnd_vf);
  #endif
    printf("  Bin Start (ke) = %lf\n", binStart_ke);
    printf("  Min (ke) = %lf\n", min_ke);
    printf("  dBin (ke) = %lf\n", dBin_ke);
    printf("  Max (ke) = %lf\n", max_ke);
    printf("  Bin End (ke) = %lf\n", binEnd_ke);

  // normalization for means
  double norm = 1./(dom.Gcc.s3 * nFiles);

  // Loop over time and bin
  printf("Looping...\n"); 
  fflush(stdout);
  int ind, ind_vf, ind_wp;

  for (tt = 0; tt < nFiles; tt++) {
    printf("  Timestep = %d of %d\n", tt+1, nFiles);
    fflush(stdout);
    // Fill data from cgns file
    cgns_fill();

    // Loop over space
    for (int cc = 0; cc < dom.Gcc.s3; cc++) {
      /* Volume Fraction */
      mean_vf += norm*volume_fraction[cc];
      // calculate index
      ind = (volume_fraction[cc] - binStart_vf)/dBin_vf;
      // if ind < 0, make it zero
      // if ind > nBins + 1, make it nBins +1
      ind = ind*(ind >= 0);         
      ind = ind*(ind <= (nBins + 1)) + (nBins + 1)*(ind > (nBins + 1));
      histogram_vf[ind]++;

      ind_vf = ind;

      /* Part Wp */
      mean_wp += norm*part_w[cc];
      ind = (part_w[cc] - binStart_wp)/dBin_wp;
      ind = ind*(ind >= 0);         
      ind = ind*(ind <= (nBins + 1)) + (nBins + 1)*(ind > (nBins + 1));
      histogram_wp[ind]++;

      ind_wp = ind;

      /* Bivariate */
      bihistogram_vf_wp[ind_wp + (nBins + 2)*ind_vf]++;

      /* Kinetic Energy */
      mean_ke += norm*part_ke[cc];
      ind = (part_ke[cc] - binStart_ke)/dBin_ke;
      ind = ind*(ind >= 0);         
      ind = ind*(ind <= (nBins + 1)) + (nBins + 1)*(ind > (nBins + 1));
      histogram_ke[ind]++;
    }

    // keep track of min max mean std for ALL files?
    // have bin padding as an input parameter?

  }
  // write to file
  write_field();

  // Free and exit
  printf("Done!\n");
  free_vars();
  return EXIT_SUCCESS;
}
void read_hmm_file(char *configfile, Hmm *hmm, Obs *obs, int transpose)
{
	FILE *fin, *bin;
	// Initialize line buffer
	char *linebuf = NULL;
	size_t buflen = 0;
	// Initialize parsing variables
	int c, k;
	float d;
	opterr = 0;
	// Initialize HMM parameters 
	int nStates = 0;            /* Number of possible states */
	int nSymbols = 0;           /* Number of possible symbols */
	int nSeq = 0;               /* Number of observation sequences */
	int length = 0;             /* Length of each observation sequence */
	// Initialize counter variables
	int i, j;

	// Open config file
	if (configfile == NULL) {
		fin = stdin;
	} else {
		fin = fopen(configfile, "r");
		if (fin == NULL) {
			HANDLE_ERROR("fopen");
		}
	}

	/* Parse the config file and extract HMM parameters */
	i = 0;
	while ((c = getline(&linebuf, &buflen, fin)) != -1) {

		/* Ignore blank and comment lines (start with '#') */
		if (c <= 1 || linebuf[0] == '#') {
			continue;
		}

		/* First section - read number of states */
		if (i == 0) {
			if (sscanf(linebuf, "%d", &nStates) != 1) {
				fprintf(stderr, "Config file format error: %d\n", i);
				free_vars(hmm, obs);
				exit(EXIT_FAILURE);
			}

			/* Allocate memory for Pi */
			hmm->nstates = nStates;
			hmm->pi = (float *) malloc(sizeof(float) * nStates);
			if (hmm->pi == NULL) {
				HANDLE_ERROR("malloc");
			}

			/* Allocate memory for A */
			hmm->a = (float *) malloc(sizeof(float) * nStates * nStates);
			if (hmm->a == NULL) {
				HANDLE_ERROR("malloc");
			}

			/* Second section - read number of possible symbols */
		} else if (i == 1) {
			if (sscanf(linebuf, "%d", &nSymbols) != 1) {
				fprintf(stderr, "Config file format error: %d\n", i);
				free_vars(hmm, obs);
				exit(EXIT_FAILURE);
			}

			/* Allocate memory for B */
			hmm->nsymbols = nSymbols;
			hmm->b = (float *) malloc(sizeof(float) * nStates * nSymbols);
			if (hmm->b == NULL) {
				HANDLE_ERROR("malloc");
			}

			/* Third section - read initial state probabilities (Pi) */
		} else if (i == 2) {

			/* Open memory stream and read in line */
			bin = fmemopen(linebuf, buflen, "r");
			if (bin == NULL) {
				HANDLE_ERROR("fmemopen");
			}

			/* Parse through memory stream and store probability values */
			for (j = 0; j < nStates; j++) {
				if (fscanf(bin, "%f", &d) != 1) {
					fprintf(stderr, "Config file format error: %d\n", i);
					free_vars(hmm, obs);
					exit(EXIT_FAILURE);
				}
				hmm->pi[j] = d;
			}
			fclose(bin);

			/* Fourth section - read in state transition probabilities (A) */
		} else if (i <= 2 + nStates) {

			/* Open memory stream and read in line */
			bin = fmemopen(linebuf, buflen, "r");
			if (bin == NULL) {
				HANDLE_ERROR("fmemopen");
			}

			/* Parse through memory stream and store probability values */
			for (j = 0; j < nStates; j++) {
				if (fscanf(bin, "%f", &d) != 1) {
					fprintf(stderr, "Config file format error: %d\n", i);
					free_vars(hmm, obs);
					exit(EXIT_FAILURE);
				}
				hmm->a[IDX((i - 3), j, nStates)] = d;
			}
			fclose(bin);

			/* Fifth section - read in output probabilities (B) */
		} else if ((i <= 2 + nStates * 2) && (transpose == 0)) {

			/* Open memory stream and read in line */
			bin = fmemopen(linebuf, buflen, "r");
			if (bin == NULL) {
				HANDLE_ERROR("fmemopen");
			}

			/* Parse through memory stream and store probability values */
			for (j = 0; j < nSymbols; j++) {
				if (fscanf(bin, "%f", &d) != 1) {
					fprintf(stderr, "Config file format error: %d\n", i);
					free_vars(hmm, obs);
					exit(EXIT_FAILURE);
				}
				hmm->b[j * nStates + (i - 3 - nStates)] = d;
			}
			fclose(bin);

			/* Fifth section (again) - read in output probabilities (B) if transposed */
		} else if ((i <= 2 + nStates + nSymbols) && (transpose)) {

			/* Open memory stream and read in line */
			bin = fmemopen(linebuf, buflen, "r");
			if (bin == NULL) {
				HANDLE_ERROR("fmemopen");
			}

			/* Parse through memory stream and store probability values */
			for (j = 0; j < nStates; j++) {
				if (fscanf(bin, "%f", &d) != 1) {
					fprintf(stderr, "Config file format error: %d\n", i);
					free_vars(hmm, obs);
					exit(EXIT_FAILURE);
				}
				hmm->b[(i - 3 - nStates) * nStates + j] = d;
			}
			fclose(bin);

			/* Sixth section - read in data size (seq, length) */
		} else if ((i == 3 + nStates * 2) && (transpose == 0)) {

			/* Read in data sequence and length values */
			if (sscanf(linebuf, "%d %d", &nSeq, &length) != 2) {
				fprintf(stderr, "Config file format error: %d\n", i);
				free_vars(hmm, obs);
				exit(EXIT_FAILURE);
			}
			obs->length = nSeq * length;

			/* Allocate memory for observation sequence */
			obs->data = (int *) malloc(sizeof(int) * nSeq * length);
			if (obs->data == NULL) {
				HANDLE_ERROR("malloc");
			}

			/* Sixth section (again) - read in data size if B is transposed */
		} else if ((i == 3 + nStates + nSymbols) && (transpose)) {

			/* Read in data sequence and length values */
			if (sscanf(linebuf, "%d %d", &nSeq, &length) != 2) {
				fprintf(stderr, "Config file format error: %d\n", i);
				free_vars(hmm, obs);
				exit(EXIT_FAILURE);
			}
			obs->length = nSeq * length;

			/* Allocate memory for observation sequence */
			obs->data = (int *) malloc(sizeof(int) * nSeq * length);
			if (obs->data == NULL) {
				HANDLE_ERROR("malloc");
			}

			/* Seventh section - read in observation sequence */
		} else if ((i <= 3 + nStates * 2 + nSeq) && (transpose == 0)) {

			/* Open memory stream and read in line */
			bin = fmemopen(linebuf, buflen, "r");
			if (bin == NULL) {
				HANDLE_ERROR("fmemopen");
			}

			/* Parse through observation sequence and store values (read down, then across) */
			for (j = 0; j < length; j++) {
				if (fscanf(bin, "%d", &k) != 1 || k < 0 || k >= nSymbols) {
					fprintf(stderr, "Config file format error: %d\n", i);
					free_vars(hmm, obs);
					exit(EXIT_FAILURE);
				}
				obs->data[j * nSeq + (i - 4 - nStates * 2)] = k;
			}
			fclose(bin);
		} else if ((i <= 3 + nStates + nSymbols + nSeq) && (transpose)) {

			/* Open memory stream and read in line */
			bin = fmemopen(linebuf, buflen, "r");
			if (bin == NULL) {
				HANDLE_ERROR("fmemopen");
			}

			/* Parse through observation sequence and store values (read down, then across) */
			for (j = 0; j < length; j++) {
				if (fscanf(bin, "%d", &k) != 1 || k < 0 || k >= nSymbols) {
					fprintf(stderr, "Config file format error: %d\n", i);
					free_vars(hmm, obs);
					exit(EXIT_FAILURE);
				}
				obs->data[j * nSeq + (i - 4 - (nStates + nSymbols))] = k;
			}
			fclose(bin);
		}

		/* Increment line counter */
		i++;

	}

	/* Close files and free memory */
	fclose(fin);
	if (linebuf) {
		free(linebuf);
	}

	/* Throw error if configuration file was not read properly */
	if (i < 4 + nStates * 2 + nSeq) {
		fprintf(stderr, "Configuration incomplete\n");
		free_vars(hmm, obs);
		exit(EXIT_FAILURE);
	}

}
Example #25
0
/*
 * Main application. This is where the requests come in and routed.
 */
void handle_request(void)
{
	bool logged_in = false;
	char *request_uri;
	struct timespec stp;
	struct timespec etp;

	clock_gettime(CLOCK_REALTIME, &stp);

	qvars = NULL;
	avars = NULL;
	u_files = NULL;

	set_env_vars();
	set_vars();
	request_uri = strdupa(env_vars.request_uri);

	/* Initialise the database connection */
	conn = db_conn();
	if (!conn)
		goto out2;

	/*
	 * Some routes need to come before the login / session stuff as
	 * they can't be logged in and have no session.
	 */
	if (match_uri(request_uri, "//")) {
		/* function call goes here */
		goto out2;
	}

	if (match_uri(request_uri, "/login/")) {
		login();
		goto out2;
	}

	logged_in = is_logged_in();
	if (!logged_in) {
		printf("Location: /login/\r\n\r\n");
		goto out2;
	}

	/* Logged in, set-up the user_session structure */
	set_user_session();

	/* Add new url handlers after here */

	if (match_uri(request_uri, "/logout/")) {
		logout();
		goto out;
	}

	/* Default location */
	printf("Location: /login/\r\n\r\n");

out:
	free_user_session();

out2:
	free_vars(qvars);
	free_avars();
	free_u_files();
	clock_gettime(CLOCK_REALTIME, &etp);
	d_fprintf(access_log, "Got request from %s for %s (%s), %ums\n",
			env_vars.remote_addr, request_uri,
			env_vars.request_method,
			(unsigned int)((etp.tv_sec * 1000 +
					etp.tv_nsec / NS_MSEC) -
				(stp.tv_sec * 1000 + stp.tv_nsec / NS_MSEC)));
	free_env_vars();
	mysql_close(conn);
}
Example #26
0
void read_hmm_file(char *configfile, Hmm *hmm, Obs *obs, int transpose)
{
	FILE *fin, *bin;
	
	char *linebuf = NULL;
	size_t buflen = 0;

	int c, k;
	float d;
	opterr = 0;

	int nStates = 0;
	int nSymbols = 0;
	int nSeq = 0;
	int length = 0;

	int i, j;

	if (configfile == NULL) {
		fin = stdin;
	} else {
		fin = fopen(configfile, "r");
		if (fin == NULL) {
			HANDLE_ERROR("fopen");
		}
	}

	i = 0;
	while ((c = getline(&linebuf, &buflen, fin)) != -1) {
		// If you want to watch which line precessing, use next line.
		// printf("%d: %s", c, linebuf);
		if (c <= 1 || linebuf[0] == '#' || linebuf[0] == '\r' || linebuf[0] == '\n') {
			continue;
		}

		if (i == 0) {
			if (sscanf(linebuf, "%d", &nStates) != 1) {
				fprintf(stderr, "Config file format error: %d\n", i);
				free_vars(hmm, obs);
				exit(EXIT_FAILURE);
			}

			hmm->nstates = nStates;
			hmm->pi = (float *) malloc(sizeof(float) * nStates);
			if (hmm->pi == NULL) {
				HANDLE_ERROR("malloc");
			}

			hmm->a = (float *) malloc(sizeof(float) * nStates * nStates);
			if (hmm->a == NULL) {
				HANDLE_ERROR("malloc");
			}
		} else if (i == 1) {
			if (sscanf(linebuf, "%d", &nSymbols) != 1) {
				fprintf(stderr, "Config file format error: %d\n", i);
				free_vars(hmm, obs);
				exit(EXIT_FAILURE);
			}

			hmm->nsymbols = nSymbols;
			hmm->b = (float *) malloc(sizeof(float) * nStates * nSymbols);
			if (hmm->b == NULL) {
				HANDLE_ERROR("malloc");
			}
		} else if (i == 2) {
			bin = fmemopen(linebuf, buflen, "r");
			if (bin == NULL) {
				HANDLE_ERROR("fmemopen");
			}
			
			for (j = 0; j < nStates; j++) {
				if (fscanf(bin, "%f", &d) != 1) {
					fprintf(stderr, "Config file format error: %d\n", i);
					free_vars(hmm, obs);
					exit(EXIT_FAILURE);
				}
				hmm->pi[j] = d;
			}
			fclose(bin);
		} else if (i <= 2 + nStates) {
			bin = fmemopen(linebuf, buflen, "r");
			if(bin == NULL) {
				HANDLE_ERROR("fmemopen");
			}

			for (j = 0; j < nStates; j++) {
				if (fscanf(bin, "%f", &d) != 1) {
					fprintf(stderr, "Config file format error: %d\n", i);
					free_vars(hmm, obs);
					exit(EXIT_FAILURE);
				}
				hmm->a[IDX((i-3), j, nStates)] = d;
			}
			fclose(bin);
		} else if ((i <= 2 + nStates * 2) && (transpose == 0)) {
			bin = fmemopen(linebuf, buflen, "r");
			if (bin == NULL) {
				HANDLE_ERROR("fmemopen");
			}

			for (j = 0; j < nSymbols; j++) {
				if (fscanf(bin, "%f", &d) != 1) {
					fprintf(stderr, "Config file format error: %d\n", i);
					free_vars(hmm, obs);
					exit(EXIT_FAILURE);
				}
				hmm->b[j * nStates + (i - 3 - nStates)] = d;
			}
			fclose(bin);
		} else if ((i <= 2 + nStates + nSymbols) && (transpose)) { 
			bin = fmemopen(linebuf, buflen, "r");
			if (bin == NULL) {
				HANDLE_ERROR("fmemopen");
			}

			for (j = 0; j < nStates; j++) {
				if (fscanf(bin, "%f", &d) != 1) {
					fprintf(stderr, "Config file format error: %d\n", i);
					free_vars(hmm, obs);
					exit(EXIT_FAILURE);
				}
				hmm->b[(i - 3 - nStates) * nStates + j] = d;
			}	
			fclose(bin);
		} else if ((i == 3 + nStates * 2) && (transpose == 0)) {
			if (sscanf(linebuf, "%d %d", &nSeq, &length) != 2) {
				fprintf(stderr, "Config file format error: %d\n", i);
				free_vars(hmm, obs);
				exit(EXIT_FAILURE);
			}
			obs->length = nSeq * length;

			int memory_size = nSeq * length;
			obs->data = (int *) malloc(sizeof(int) * memory_size);
			if (obs->data == NULL) {
				HANDLE_ERROR("malloc");
			}
		} else if ((i == 3 + nStates + nSymbols) && (transpose)) {
			if (sscanf(linebuf, "%d %d", &nSeq, &length) != 2) {
				fprintf(stderr, "Config file format error: %d\n", i);
				free_vars(hmm, obs);
				exit(EXIT_FAILURE);
			}
			obs->length = nSeq * length;

			obs->data = (int *) malloc(sizeof(int) * nSeq * length);
			if (obs->data == NULL) {
				HANDLE_ERROR("malloc");
			}
		} else if ((i <= 3 + nStates * 2 + nSeq) && (transpose == 0)){
			bin = fmemopen(linebuf, buflen, "r");
			if (bin == NULL) {
				HANDLE_ERROR("fmemopen");
			}
			
			for (j = 0; j < length; j++) {
				if (fscanf(bin, "%d", &k) != 1 || k < 0 || k >= nSymbols) {
					fprintf(stderr, "Config file format error: %d\n", i);
					free_vars(hmm, obs);
					exit(EXIT_FAILURE);
				}
				obs->data[j * nSeq + (i - 4 - nStates * 2)] = k;
			}
			fclose(bin);
		} else if ((i <= 3 + nStates + nSymbols + nSeq) && (transpose)){
			bin = fmemopen(linebuf, buflen, "r");
			if (bin == NULL) {
				HANDLE_ERROR("fmemopen");
			}

			for (j = 0; j < length; j++) {
				if (fscanf(bin, "%d", &k) != 1 || k < 0 || k >= nSymbols) {
					fprintf(stderr, "Config file format error: %d\n", i);
					free_vars(hmm, obs);
					exit(EXIT_FAILURE);
				}
				obs->data[j * nSeq + (i - 4 - (nStates + nSymbols))] = k;
			}
			fclose(bin);
		}
	
		i++;
	}
	fclose(fin);
	if (linebuf) {
		free(linebuf);
	}

	if (i < 4 + nStates * 2 + nSeq) {
		fprintf(stderr, "Configuration incomplete\n");
		free_vars(hmm, obs);
		exit(EXIT_FAILURE);
	}
}
Example #27
0
int start_rendering()
{
	static int done = 0;
	static void * network_thread_data[2] = { NULL, NULL };
	static Uint32 last_frame_and_command_update = 0;

	SDL_Thread *network_thread;
	queue_t *message_queue;

#ifndef WINDOWS
	SDL_EventState(SDL_SYSWMEVENT,SDL_ENABLE);
#endif
	queue_initialise(&message_queue);
	network_thread_data[0] = message_queue;
	network_thread_data[1] = &done;
	network_thread = SDL_CreateThread(get_message_from_server, network_thread_data);

	/* Loop until done. */
	while( !done )
		{
			SDL_Event event;

			// handle SDL events
			in_main_event_loop = 1;
			while( SDL_PollEvent( &event ) )
				{
					done = HandleEvent(&event);
				}
			in_main_event_loop = 0;

			//advance the clock
			cur_time = SDL_GetTicks();

			//check for network data
			if(!queue_isempty(message_queue)) {
				message_t *message;

				while((message = queue_pop(message_queue)) != NULL)
				{
					process_message_from_server(message->data, message->length);
					free(message->data);
					free(message);
				}
			}
#ifdef	OLC
			olc_process();
#endif	//OLC
			my_tcp_flush(my_socket);    // make sure the tcp output buffer is set
			
			if (have_a_map && cur_time > last_frame_and_command_update + 60) {
				LOCK_ACTORS_LISTS();
				next_command();
				UNLOCK_ACTORS_LISTS();
				move_to_next_frame();
				last_frame_and_command_update = cur_time;
			}

			while (cur_time > next_second_time && real_game_second < 59)
			{
				real_game_second += 1;
				new_second();
				next_second_time += 1000;
			}

#ifdef NEW_SOUND
			weather_sound_control();
#endif	//NEW_SOUND

			if(!limit_fps || (cur_time-last_time && 1000/(cur_time-last_time) <= limit_fps))
			{
				weather_update();

                animate_actors();
				//draw everything
				draw_scene();
				last_time=cur_time;
			}
			else {
				SDL_Delay(1);//give up timeslice for anyone else
			}

#ifdef TIMER_CHECK
			//Check the timers to make sure that they are all still alive...
			check_timers();
#endif

			//cache handling
			if(cache_system)cache_system_maint();
			//see if we need to exit
			if(exit_now) {
				done = 1;
				break;
			}
		}
	if(!done) {
		done = 1;
	}
	LOG_INFO("Client closed");
	SDL_WaitThread(network_thread,&done);
	queue_destroy(message_queue);
	if(pm_log.ppl)free_pm_log();

	//save all local data
	save_local_data(NULL, 0);

#ifdef PAWN
	cleanup_pawn ();
#endif

#ifdef NEW_SOUND
	destroy_sound();		// Cleans up physical elements of the sound system and the streams thread
	clear_sound_data();		// Cleans up the config data
#endif // NEW_SOUND
	ec_destroy_all_effects();
	if (have_a_map)
	{
		destroy_map();
		free_buffers();
	}
	unload_questlog();
	save_item_lists();
	free_emotes();
	free_actor_defs();
	free_books();
	free_vars();
	cleanup_rules();
	save_exploration_map();
	cleanup_counters();
	cleanup_chan_names();
	cleanup_hud();
	SDL_RemoveTimer(draw_scene_timer);
	SDL_RemoveTimer(misc_timer);
	end_particles ();
	free_bbox_tree(main_bbox_tree);
	main_bbox_tree = NULL;
	free_astro_buffer();
	free_translations();
	free_skybox();
	/* Destroy our GL context, etc. */
	SDL_QuitSubSystem(SDL_INIT_AUDIO);
	SDL_QuitSubSystem(SDL_INIT_TIMER);
/*#ifdef WINDOWS
	// attempt to restart if requested
	if(restart_required > 0){
		LOG_INFO("Restarting %s", win_command_line);
		SDL_CreateThread(system, win_command_line);
	}
#endif  //WINDOWS
*/
#ifdef NEW_SOUND
	final_sound_exit();
#endif
#ifdef	CUSTOM_UPDATE
	stopp_custom_update();
#endif	/* CUSTOM_UPDATE */
	clear_zip_archives();

	destroy_tcp_out_mutex();

	if (use_frame_buffer) free_reflection_framebuffer();

	printf("doing SDL_Quit\n");
	fflush(stderr);
	SDL_Quit( );
	printf("done SDL_Quit\n");
	fflush(stderr);
	cleanup_mem();
	xmlCleanupParser();
	FreeXML();

	exit_logging();

	return(0);
}
Example #28
0
static char *
parse_block(tConf *block, char *cur, FILE *file, int *lnum)
{
    char *tok, *var, *var2;
    char line[LINE_MAX];
    tConf *b2 = NULL;
    sConf *item = NULL;
    sConf *sconftab = block->subtok;
    cVar  *vars[MAX_VALUES] = { 0 };
    int   vnum = 0, tlnum = 0, clear = 0, done = 0, skip = 0;

    if((sconftab) && (sconftab->flag == SCONFF_STRING))
    {
        /* this subtype only takes freeform variables
         * dont bother looking for tokens
         */
        int i = 0;
        while(!BadPtr(cur) || ((fgets(line, LINE_MAX, file) != NULL) &&
                               (*lnum)++ && (cur = line)))
        {
            cur = check_quote(cur);
            if(BadPtr(cur))
                continue;
            if(clear)
            {
                if(*cur != ';')
                {
                    confparse_error("Missing semicolon", *lnum);
                    free_vars(vars);
                    return NULL;
                }
                else
                    cur++;
                clear = 0;
                cur = check_quote(cur);
                if(BadPtr(cur))
                    continue;
            }
            if(done)
            {
                if(*cur != ';')
                {
                    confparse_error("Missing block end semicolon", *lnum);
                    free_vars(vars);
                    return NULL;
                }
                else
                    cur++;
                if(((*block->func) (vars, *lnum)) == -1)
                {
                    free_vars(vars);
                    return NULL;
                }
                if(BadPtr(cur))
                    *cur = '#';     /* we cant return a bad pointer because
                                     * that will pull us out of the conf read
                                     * so this will just get ignored
                                     * kludgy, but effective */
                free_vars(vars);
                return cur;
            }
            cur = check_quote(cur);
            if(BadPtr(cur))
                continue;
            if(*cur == '}')
            {
                done = 1;
                cur++;
                cur = check_quote(cur);
                if(BadPtr(cur))
                    continue;
                if(*cur != ';')
                {
                    confparse_error("Missing block end semicolon", *lnum);
                    free_vars(vars);
                    return NULL;
                }
                else
                    cur++;
                if(((*block->func) (vars, *lnum)) == -1)
                {
                    free_vars(vars);
                    return NULL;
                }
                if(BadPtr(cur))
                    *cur = '#';     /* we cant return a bad pointer because
                                     * that will pull us out of the conf read
                                     * so this will just get ignored
                                     * kludgy, but effective */
                free_vars(vars);
                return cur;
            }
            vars[vnum] = (cVar *) MyMalloc(sizeof(cVar));
            memset((char *) vars[vnum], '\0', sizeof(cVar));
            vars[vnum]->loaded = 1;
            vars[vnum]->type = NULL;
            tok = cur;
            if(*cur == '"')
            {
                i = 1;
                cur++;
            }
            var = cur;
            if(i == 1)
            {
                while(!BadPtr(cur) && (*cur != '"'))
                    cur++;
                if(BadPtr(cur))
                {
                    confparse_error("Cant find closequote", *lnum);
                    free_vars(vars);
                    return NULL;
                }
                *cur = '\0';
                cur++;
                while(!BadPtr(cur) && (*cur != ';'))
                    cur++;
            }
            else
            {
                while(!BadPtr(cur) && (*cur != ';'))
                {
                    if((*cur == ' '))
                    {
                        *cur = '\0';
                        if(vars[vnum]->loaded == 1)
                        {
                            DupString(vars[vnum]->value, var);
                            vars[vnum]->loaded = 2;
                        }
                    }
                    else if(vars[vnum]->loaded == 2)
                    {
                        confparse_error("Junk after value", *lnum);
                        free_vars(vars);
                        return NULL;
                    }
                    cur++;
                }
            }
            tlnum = *lnum;
            if(BadPtr(cur))
            {
                clear = 1;
                continue;
            }
            *cur = '\0';
            cur++;
            if(vars[vnum]->loaded == 1)
                DupString(vars[vnum]->value, var);
            vars[vnum]->loaded = 3;
            vnum++;
        }
        confparse_error("Unexpected EOF: Syntax Error", tlnum);
        free_vars(vars);
        return NULL;
    }

    while(!BadPtr(cur) || ((fgets(line, LINE_MAX, file) != NULL) && (*lnum)++
                           && (cur = line)))
    {
        cur = check_quote(cur);
        if(BadPtr(cur))
            continue;
        if(clear)
        {
            /* if we're looking for a closing semicolon, check for it first
             * if we cant find it, ignore it and hope for the best
             */
            if(*cur != ';')
            {
                confparse_error("Missing semicolon ", *lnum);
                free_vars(vars);
                return NULL;
            }
            else
                cur++;
            clear = 0;
            if(vars[vnum])
            {
                vars[vnum]->loaded = 3;
                vnum++;
            }
            item = NULL;
            cur = check_quote(cur);
            if(BadPtr(cur))
                continue;
        }
        if(done)
        {
            /* we've found the end of our block, now we're looking for the
             * closing semicolon.  if we cant find it, ignore it and
             * hope for the best
             */
            if(*cur != ';')
            {
                confparse_error("Missing block end semicolon", *lnum);
                free_vars(vars);
                return NULL;
            }
            else
                cur++;
            if(((*block->func) (vars, *lnum)) == -1)
            {
                free_vars(vars);
                return NULL;
            }
            if(BadPtr(cur))
                *cur = '#';     /* we cant return a bad pointer because
                                 * that will pull us out of the conf read
                                 * so this will just get ignored
                                 * kludgy, but effective */
            free_vars(vars);
            return cur;
        }
        if(b2 && b2->tok)
        {
            /* we've identified a nested block in a previous loop.
             * we didnt get an openquote yet, so look for that.
             * we must find this.  keep looking til we do.
             */
            if(*cur != '{')
            {
                confparse_error("Junk after nested block token", *lnum);
                free_vars(vars);
                return NULL;
            }
            cur++;
            cur = check_quote(cur);
            cur = parse_block(b2, cur, file, lnum);
            b2 = NULL;
            continue;
        }
        if(!item || !item->tok)
        {
            /* if we dont already have a specific token we're working on
             * find one here.
             */
            cur = check_quote(cur);
            if(BadPtr(cur))
                continue;
            tok = cur;
            tlnum = *lnum;
            if(*cur == '}')
            {
                /* if we've got a closebracket, then we've hit the end
                 * of our block.
                 */
                done = 1;
                cur++;
                cur = check_quote(cur);
                if(BadPtr(cur))
                    continue;
                if(*cur != ';')
                {
                    confparse_error("Missing block end semicolon", *lnum);
                    free_vars(vars);
                    return NULL;
                }
                else
                    cur++;
                if(((*block->func) (vars, *lnum)) == -1)
                {
                    free_vars(vars);
                    return NULL;
                }
                if(BadPtr(cur))
                    *cur = '#';     /* we cant return a bad pointer because
                                     * that will pull us out of the conf read
                                     * so this will just get ignored
                                     * kludgy, but effective */
                free_vars(vars);
                return cur;

            }
            /* our token ends where whitespace or a semicolon begins */
            while(!BadPtr(cur) && ((*cur != ' ') && (*cur != ';') &&
                                   (*cur != '\t') && (*cur != '\n')))
                cur++;
            if(BadPtr(cur))
            {
                confparse_error("Unterminated token", *lnum);
                free_vars(vars);
                return NULL;
            }
            else
            {
                if(*cur == ';')
                    skip = 1;
                *cur = '\0';
            }
            cur++;
            if(block->nest)
            {
                /* we allow nested stuff inside here, so check for it. */
                for(b2 = tconftab; b2->tok; b2++)
                    if(!mycmp(b2->tok, tok))
                        break;
                if(b2 && b2->tok)
                    if(!(block->nest & b2->flag))
                        b2 = NULL;
                if(b2 && b2->tok)
                {
                    /* recurse through the block we found */
                    tlnum = *lnum;
                    cur = check_quote(cur);
                    if(BadPtr(cur))
                        continue;
                    if(*cur != '{')
                    {
                        confparse_error("Junk after nested block name", *lnum);
                        free_vars(vars);
                        return NULL;
                    }
                    cur++;
                    cur = check_quote(cur);
                    cur = parse_block(b2, cur, file, lnum);
                    if(!cur)
                    {
                        free_vars(vars);
                        return NULL;
                    }
                    b2 = NULL;
                    continue;
                }
            }
            /* find our token */
            for(item = sconftab; item && item->tok; item++)
                if(!mycmp(item->tok, tok))
                    break;
            if(!item->tok)
            {
                confparse_error("Unknown token", *lnum);
                free_vars(vars);
                return NULL;
            }
            /* create our variable */
            vars[vnum] = (cVar *) MyMalloc(sizeof(cVar));
            memset((char *) vars[vnum], '\0', sizeof(cVar));
            vars[vnum]->type = item;
            vars[vnum]->loaded = 1;
        }
        if(item->var & VARTYPE_NONE)
        {
            /* we dont need to grab a variable for this type
             * just look for the closing semicolon, and move on */
            vars[vnum]->loaded = 2;
            if(!skip)
            {
                /* we've already gotten our semicolon back
                 * at the end of our token.  dont look for it. */
                cur = check_quote(cur);
                while(!BadPtr(cur) && (*cur != ';'))
                    cur++;
                if(BadPtr(cur))
                {
                    clear = 1;
                    continue;
                }
                cur++;
            }
            skip = 0;
            vars[vnum]->loaded = 3;
            vnum++;
            item = NULL;
            continue;
        }
        if(item->var & VARTYPE_STRING)
        {
            /* we're looking for a string here, so we require
             * quotes around the string...
             */
            cur = check_quote(cur);
            while(!BadPtr(cur) && (*cur != '"'))
                cur++;
            if(BadPtr(cur))
                continue;
            cur++;
            var = cur;
            while(!BadPtr(cur) && (*cur != '"'))
                cur++;
            if(BadPtr(cur))
            {
                confparse_error("Unterminated quote", *lnum);
                free_vars(vars);
                return NULL;
            }
            *cur = '\0';
            cur++;
            DupString(vars[vnum]->value, var);
            vars[vnum]->loaded = 2;
            while(!BadPtr(cur) && (*cur != ';'))
                cur++;
            if(BadPtr(cur))
            {
                clear = 1;
                continue;
            }
            cur++;
            vars[vnum]->loaded = 3;
            vnum++;
            item = NULL;
            continue;
        }
        if(item->var & VARTYPE_INT)
        {
            cur = check_quote(cur);
            var = cur;
            while(!BadPtr(cur) && ((*cur != ';') && (*cur != '\t') &&
                                   (*cur != '\n') && (*cur != ' ')))
                cur++;
            if(BadPtr(cur))
            {
                clear = 1;
                continue;
            }
            if(*cur != ';')
                clear = 1;
            *cur = '\0';
            cur++;
            var2 = var;
            while(*var)
            {
                if(IsDigit(*var))
                    var++;
                else
                {
                    confparse_error("Expecting integer value", *lnum);
                    free_vars(vars);
                    return NULL;
                }
            }
            if(!item)
                continue;
            var = var2;
            DupString(vars[vnum]->value, var);
            vars[vnum]->loaded = 3;
            vnum++;
            item = NULL;
            continue;
        }
        if(item->var & VARTYPE_NAME)
        {
            cur = check_quote(cur);
            if(!BadPtr(cur) && (*cur == '"'))
                cur++;
            var = cur;
            while(!BadPtr(cur) && (*cur != ';'))
            {
                if((*cur == ' ') || (*cur == '"') || (*cur == '\t'))
                {
                    *cur = '\0';
                    if(vars[vnum]->loaded == 1)
                    {
                        DupString(vars[vnum]->value, var);
                        vars[vnum]->loaded = 2;
                    }
                }
                cur++;
            }
            if(BadPtr(cur))
            {
                clear = 1;
                continue;
            }
            *cur = '\0';
            cur++;
            if(vars[vnum]->loaded == 1)
                DupString(vars[vnum]->value, var);
            vars[vnum]->loaded = 3;
            vnum++;
            item = NULL;
            continue;
        }
        confparse_error("Unexpected EOF:  Syntax Error", tlnum);
        free_vars(vars);
        return NULL;
    }
    confparse_error("Unexpected EOF:  Syntax Error", tlnum);
    free_vars(vars);
    return NULL;
}
Example #29
0
int main(int argc, char *argv[]) 
{
  // Set up batch submission
  #ifdef BATCH
    SIM_ROOT_DIR = (char*) malloc(CHAR_BUF_SIZE * sizeof(char));
    ROOT_DIR = (char*) malloc(CHAR_BUF_SIZE * sizeof(char));

    // arg[0] = program name
    // arg[1] = SIM_ROOT_DIR
    if (argc == 2) {
      sprintf(SIM_ROOT_DIR, "%s", argv[1]);
      sprintf(ROOT_DIR, "%s/f-rec-part-3D", SIM_ROOT_DIR);
    } else if (argc != 2) {
      printf("usage: %s SIM_ROOT_DIR\n", argv[0]);
      exit(EXIT_FAILURE);
    }
    printf("\n SIM_ROOT_DIR = %s\n", SIM_ROOT_DIR);
    printf(" ROOT_DIR = %s\n\n", ROOT_DIR);
  #else           // prevent compiler warning
    argc = argc;
    argv = argv;
  #endif

  // Read input file
  main_read_input();

  // Read and sort output directory for finding files within our time limits
  init_part_files();

  // Get number of particles
  nparts = cgns_read_nparts();

  // Initialize partstruct and flow vars
  parts_init();

  // Initialize domain and flow arrays
  domain_init(); 

  // Allocate arrays
  alloc_arrays();

  // Create output directory
  get_sigfigs();
  create_output();

  /* MAIN LOOP */
  double kl, km, kn;
  int ll, mm, nn, corder;
  // Loop over time
  for (tt = 0; tt < nFiles; tt++) {
    // Fill parts with new info
    cgns_fill_parts();

    // Loop over all coefficients l,m,n (x,y,z)
    for (ll = 0; ll <= orderL; ll++) {
      kl = 2.*PI*ll/dom.xl;
      for (mm = 0; mm <= orderM; mm++) {
        km = 2.*PI*mm/dom.yl;
        for (nn = 0; nn <= orderN; nn++) {
          kn = 2.*PI*nn/dom.zl;
          corder = nn + (orderN + 1)*mm + (orderN + 1)*(orderM + 1)*ll;

          // Calculate coefficients n_lmn
          // TODO: need diff for vfrac
          calc_coeffs(n_lmn, ones, parts, kl, km, kn, corder);
          //printf("n_lmn[%d] = %f + %fi\n", corder, creal(n_lmn[corder]), cimag(n_lmn[corder]));
          // does it make sense to not even store n_lmn?

          // evaluate series for n_lmn at x,y,z
          // TODO: need diff for vfrac
          // TODO: parallelize? probably not, is not TOO slow
          // TODO: is n_rec always real?
          eval_series(n_rec, n_lmn, kl, km, kn, corder);

        }
      }
    }
    // Normalize nq by n to find q
    // make sure to divide by volume...
    //normalize(nu_ces, n_ces);

//  // write to file -- TODO take specific nq_rec as input
    cgns_write_field();
  }
   
  // Free and exit
  free_vars();
  printf("... Done!\n");
  return EXIT_SUCCESS;
}