int console_cmd_help(game_state *gs, int argc, char **argv) { // print list of commands vector sorted; iterator it; hashmap_pair *pair, **ppair; vector_create(&sorted, sizeof(hashmap_pair*)); hashmap_iter_begin(&con->cmds, &it); while((pair = iter_next(&it)) != NULL) { vector_append(&sorted, &pair); } vector_sort(&sorted, &sort_command_by_name); vector_iter_begin(&sorted, &it); while((ppair = iter_next(&it)) != NULL) { char *name = (*ppair)->key; command *cmd = (*ppair)->val; console_output_add(name); console_output_add(" - "); console_output_addline(cmd->doc); } vector_free(&sorted); return 0; }
END_TEST START_TEST (insert_element_in_the_beginning) { char *py = strdup("python"); char *rb = strdup("ruby"); char *lp = strdup("lisp"); int rc; vector *v = vector_new(sizeof(char *), free_string, 5); vector_append(v, &py); vector_append(v, &rb); rc = vector_insert(v, &lp, 0); fail_unless(rc == 0); fail_unless(vector_length(v) == 3); fail_unless(lp == *(char **)vector_get(v, 0)); fail_unless(py == *(char **)vector_get(v, 1)); fail_unless(rb == *(char **)vector_get(v, 2)); vector_free(v); }
int main() { srand(1234); const size_t n = 100000; val_t* xs = malloc_or_die(n * sizeof(val_t)); /* haystack */ memset(xs, 0, n * sizeof(val_t)); /* needle */ size_t i = rand() % n; xs[i] = 1000; vector_t* vec = vector_create(xs, n); free(xs); interval_t* out; size_t count = peakolate(vec, f, g, 1, 10000, -INFINITY, 0, false, &out); if (count == 0) { fprintf(stderr, "No high density intervals were found.\n"); return EXIT_FAILURE; } else if (count > 1) { fprintf(stderr, "More than one high density interval was found.\n"); return EXIT_FAILURE; } else if (out[0].start != i || out[0].end != i) { fprintf(stderr, "Incorrect needle found.\n"); return EXIT_FAILURE; } vector_free(vec); free(out); return EXIT_SUCCESS; }
void enkf_config_node_free(enkf_config_node_type * node) { /* Freeing the underlying node object. */ if (node->freef != NULL) node->freef(node->data); free(node->key); stringlist_free(node->obs_keys); if (node->enkf_infile_fmt != NULL) path_fmt_free( node->enkf_infile_fmt ); if (node->enkf_outfile_fmt != NULL) path_fmt_free( node->enkf_outfile_fmt ); if (node->init_file_fmt != NULL) path_fmt_free( node->init_file_fmt ); if (node->internalize != NULL) bool_vector_free( node->internalize ); if (node->min_std != NULL) enkf_node_free( node->min_std ); vector_free( node->container_nodes ); free(node); }
int main() { // declare and initialize a new vector Vector vector; vector_init(&vector); // fill it up with 150 arbitrary values // this should expand capacity up to 200 int i; for (i = 200; i > -50; i--) { vector_append(&vector, i); } // set a value at an arbitrary index // this will expand and zero-fill the vector to fit vector_set(&vector, 4452, 21312984); // print out an arbitrary value in the vector printf("Heres the value at 27: %d\n", vector_get(&vector, 27)); // we're all done playing with our vector, // so free its underlying data array vector_free(&vector); // so free its underlying data array }
END_TEST START_TEST (sort_should_sort_the_vector) { int num1 = 2, num2 = 4, num3 = 5, num4 = 12, num5 = 23; vector *v = vector_new(sizeof(int), NULL, 5); vector_append(v, &num4); vector_append(v, &num2); vector_append(v, &num1); vector_append(v, &num5); vector_append(v, &num3); vector_sort(v, compare_ints); fail_unless(*(int *)vector_get(v, 0) == num1); fail_unless(*(int *)vector_get(v, 1) == num2); fail_unless(*(int *)vector_get(v, 2) == num3); fail_unless(*(int *)vector_get(v, 3) == num4); fail_unless(*(int *)vector_get(v, 4) == num5); vector_free(v); }
END_TEST START_TEST (search_should_ignore_everything_before_start_parameter) { int num1 = 12, num2 = 22, num3 = 23, num4 = 30, num5 = 34; vector *v = vector_new(sizeof(int *), NULL, 5); vector_append(v, &num1); vector_append(v, &num2); vector_append(v, &num3); vector_append(v, &num4); vector_append(v, &num5); fail_unless(vector_search(v, &num1, compare_ints, 1, false) == VECT_SEARCH_NOT_FOUND); fail_unless(vector_search(v, &num2, compare_ints, 2, false) == VECT_SEARCH_NOT_FOUND); fail_unless(vector_search(v, &num5, compare_ints, 2, false) == 4); fail_unless(vector_search(v, &num1, compare_ints, 1, true) == VECT_SEARCH_NOT_FOUND); fail_unless(vector_search(v, &num2, compare_ints, 2, true) == VECT_SEARCH_NOT_FOUND); fail_unless(vector_search(v, &num5, compare_ints, 2, true) == 4); vector_free(v); }
END_TEST START_TEST (insert_elements_in_all_positions) { char *move1 = strdup("forward loop"); char *move2 = strdup("goiter"); char *move3 = strdup("flaka"); char *move4 = strdup("back loop"); vector *v = vector_new(sizeof(char *), free_string, 5); fail_if(vector_insert(v, &move1, 0) == -1); fail_if(vector_insert(v, &move4, 1) == -1); fail_if(vector_insert(v, &move2, 1) == -1); fail_if(vector_insert(v, &move3, 2) == -1); fail_unless(4 == vector_length(v)); fail_unless(move1 == *(char **)vector_get(v, 0)); fail_unless(move2 == *(char **)vector_get(v, 1)); fail_unless(move3 == *(char **)vector_get(v, 2)); fail_unless(move4 == *(char **)vector_get(v, 3)); vector_free(v); }
void cesk_diff_buffer_free(cesk_diff_buffer_t* mem) { if(NULL == mem) return; int i, sz; sz = vector_size(mem->buffer); for(i = mem->converted; i < sz; i ++) { _cesk_diff_node_t* node; node = (_cesk_diff_node_t*)vector_get(mem->buffer, i); if(NULL == node || NULL == node->value) continue; switch(node->type) { case CESK_DIFF_ALLOC: case CESK_DIFF_STORE: cesk_value_decref((cesk_value_t*)node->value); break; case CESK_DIFF_REG: cesk_set_free((cesk_set_t*)node->value); break; } } vector_free(mem->buffer); free(mem); }
static void thread_reap(VALUE thr) { Thread *th; vector_t *v; th = THREAD(thr); v = th->obj_stk; vector_foreach(v, thread_reap_check); st_free_table(th->env_tbl); vector_free(th->obj_stk); vector_free(th->env_stk); vector_free(th->self_stk); vector_free(th->tok_stk); vector_free(th->stack); #ifdef SYMBOL_CACHE vector_free(th->modified_syms); #endif }
pk_t* poly_asssub_linexpr_array_det(bool assign, ap_manager_t* man, bool destructive, pk_t* pa, ap_dim_t* tdim, ap_linexpr0_t** texpr, size_t size) { size_t i; ap_dim_t* tdim2; numint_t** tvec; size_t nbcols; matrix_t* mat; pk_t* po; pk_internal_t* pk = (pk_internal_t*)man->internal; po = destructive ? pa : poly_alloc(pa->intdim,pa->realdim); if (!assign) poly_dual(pa); /* Obtain the needed matrix */ poly_obtain_F_dual(man,pa,"of the argument",assign); if (pk->exn){ pk->exn = AP_EXC_NONE; man->result.flag_best = man->result.flag_exact = false; poly_set_top(pk,po); goto _poly_asssub_linexpr_array_det_exit; } /* Return empty if empty */ if (!pa->C && !pa->F){ man->result.flag_best = man->result.flag_exact = true; poly_set_bottom(pk,po); return po; } /* Convert linear expressions */ nbcols = pk->dec + pa->intdim + pa->realdim; tvec = (numint_t**)malloc(size*sizeof(numint_t*)); for (i=0; i<size; i++){ tvec[i] = vector_alloc(nbcols); itv_linexpr_set_ap_linexpr0(pk->itv, &pk->poly_itv_linexpr, texpr[i]); vector_set_itv_linexpr(pk, tvec[i], &pk->poly_itv_linexpr, pa->intdim+pa->realdim,1); } /* Copy tdim because of sorting */ tdim2 = (ap_dim_t*)malloc(size*sizeof(ap_dim_t)); memcpy(tdim2,tdim,size*sizeof(ap_dim_t)); pk_asssub_isort(tdim2,tvec,size); /* Perform the operation */ mat = assign ? matrix_assign_variables(pk, pa->F, tdim2, tvec, size) : matrix_substitute_variables(pk, pa->F, tdim2, tvec, size); /* Free allocated stuff */ for (i=0; i<size; i++){ vector_free(tvec[i],nbcols); } free(tvec); free(tdim2); /* Update polyhedra */ if (destructive){ poly_clear(po); } po->F = mat; po->status = 0; _poly_asssub_linexpr_array_det_exit: if (!assign){ poly_dual(pa); if (!destructive) poly_dual(po); } assert(poly_check(pk,po)); return po; }
/* Main program */ int main(int argc, char *argv[]){ char **infiles, **outfiles; int nfiles, nout; char *arg_string; Loop_Options *loop_options; char *pname; int i; ident_t ident; scalar_t scalar; /* Save time stamp and args */ arg_string = time_stamp(argc, argv); /* Get arguments */ pname = argv[0]; if (ParseArgv(&argc, argv, argTable, 0) || (argc < 2)) { (void) fprintf(stderr, "\nUsage: %s [options] [<in1.mnc> ...] <out.mnc>\n", pname); (void) fprintf(stderr, " %s -help\n\n", pname); exit(EXIT_FAILURE); } /* Get output file names */ nout = (Output_list == NULL ? 1 : Output_list_size); outfiles = malloc(nout * sizeof(*outfiles)); if (Output_list == NULL) { outfiles[0] = argv[argc-1]; } else { for (i=0; i < Output_list_size; i++) { outfiles[i] = Output_list[i].file; } } /* check for output files */ for (i=0; i < nout; i++){ if(access(outfiles[i], F_OK) == 0 && !clobber){ fprintf(stderr, "%s: %s exists, use -clobber to overwrite\n\n", argv[0], outfiles[i]); exit(EXIT_FAILURE); } } /* Get the list of input files either from the command line or from a file, or report an error if both are specified. Note that if -outfile is given then there is no output file name left on argv after option parsing. */ nfiles = argc - 2; if (Output_list != NULL) nfiles++; if (filelist == NULL) { infiles = &argv[1]; } else if (nfiles <= 0) { infiles = read_file_names(filelist, &nfiles); if (infiles == NULL) { (void) fprintf(stderr, "Error reading in file names from file \"%s\"\n", filelist); exit(EXIT_FAILURE); } } else { (void) fprintf(stderr, "Do not specify both -filelist and input file names\n"); exit(EXIT_FAILURE); } /* Make sure that we have something to process */ if (nfiles == 0) { (void) fprintf(stderr, "No input files specified\n"); exit(EXIT_FAILURE); } /* Get the expression from the file if needed */ if ((expression == NULL) && (expr_file == NULL)) { (void) fprintf(stderr, "An expression must be specified on the command line\n"); exit(EXIT_FAILURE); } else if (expression == NULL) { expression = read_expression_file(expr_file); } /* Parse expression argument */ if (debug) fprintf(stderr, "Feeding in expression %s\n", expression); lex_init(expression); if (debug) yydebug = 1; else yydebug = 0; yyparse(); lex_finalize(); /* Optimize the expression tree */ root = optimize(root); /* Setup the input vector from the input files */ A = new_vector(); for (i=0; i<nfiles; i++) { if (debug) fprintf(stderr,"Getting file[%d] %s\n", i, argv[i+1]); scalar = new_scalar(eval_width); vector_append(A, scalar); scalar_free(scalar); } /* Construct initial symbol table from the A vector. Since setting a symbol makes a copy, we have to get a handle to that copy. */ rootsym = sym_enter_scope(NULL); ident = new_ident("A"); sym_set_vector(eval_width, NULL, A, ident, rootsym); vector_free(A); A = sym_lookup_vector(ident, rootsym); if (A==NULL) { (void) fprintf(stderr, "Error initializing symbol table\n"); exit(EXIT_FAILURE); } vector_incr_ref(A); /* Add output symbols to the table */ if (Output_list == NULL) { Output_values = NULL; } else { Output_values = malloc(Output_list_size * sizeof(*Output_values)); for (i=0; i < Output_list_size; i++) { ident = ident_lookup(Output_list[i].symbol); scalar = new_scalar(eval_width); sym_set_scalar(eval_width, NULL, scalar, ident, rootsym); scalar_free(scalar); Output_values[i] = sym_lookup_scalar(ident, rootsym); } } /* Set default copy_all_header according to number of input files */ if (copy_all_header == DEFAULT_BOOL) copy_all_header = (nfiles == 1); if (value_for_illegal_operations == DEFAULT_DBL) { if (use_nan_for_illegal_values) value_for_illegal_operations = INVALID_DATA; else value_for_illegal_operations = 0.0; } /* Do math */ loop_options = create_loop_options(); set_loop_verbose(loop_options, verbose); set_loop_clobber(loop_options, clobber); #if MINC2 set_loop_v2format(loop_options, minc2_format); #endif /* MINC2 */ set_loop_datatype(loop_options, datatype, is_signed, valid_range[0], valid_range[1]); set_loop_copy_all_header(loop_options, copy_all_header); /* only set buffer size if specified */ if(max_buffer_size_in_kb != 0){ set_loop_buffer_size(loop_options, (long) 1024 * max_buffer_size_in_kb); } set_loop_check_dim_info(loop_options, check_dim_info); voxel_loop(nfiles, infiles, nout, outfiles, arg_string, loop_options, do_math, NULL); free_loop_options(loop_options); /* Clean up */ vector_free(A); sym_leave_scope(rootsym); if (expr_file != NULL) free(expression); free(outfiles); if (Output_list != NULL) free(Output_list); if (Output_values != NULL) free(Output_values); exit(EXIT_SUCCESS); }
void test_vector() { Vector *v = vector_new(1,2,3); CU_ASSERT(v->x == 1); CU_ASSERT(v->y == 2); CU_ASSERT(v->z == 3); Vector *vc = vector_copy(v); CU_ASSERT(vc->x == 1); CU_ASSERT(vc->y == 2); CU_ASSERT(vc->z == 3); Vector *u = vector_new(4,5,6); vector_add(v,u); CU_ASSERT(v->x == 5); CU_ASSERT(v->y == 7); CU_ASSERT(v->z == 9); vector_subtract(v,u); CU_ASSERT(v->x == 1); CU_ASSERT(v->y == 2); CU_ASSERT(v->z == 3); vector_multiply(v,2); CU_ASSERT(v->x == 2); CU_ASSERT(v->y == 4); CU_ASSERT(v->z == 6); Vector *w = vector_cross(v,u); CU_ASSERT(w->x == -6); CU_ASSERT(w->y == 12); CU_ASSERT(w->z == -6); vector_free(v); vector_free(u); vector_free(w); v = vector_new(3,4,0); u = vector_new(0,3,4); CU_ASSERT(v->x==u->y); CU_ASSERT(v->y==u->z); w = vector_cross(v,u); CU_ASSERT(w->x == 16); CU_ASSERT(w->y == -12); CU_ASSERT(w->z == 9); CU_ASSERT(within_tol(vector_magnitude(v),5)); CU_ASSERT(within_tol(vector_magnitude(u),5)); vector_free(v); vector_free(u); vector_free(w); v = vector_new(1,0,0); u = vector_new(0,0,1); double a = vector_angle(v,u)/D2R; CU_ASSERT(within_tol(a,90)); CU_ASSERT(within_tol(vector_angle(u,v),90.*D2R)); w = vector_cross(v,u); CU_ASSERT(within_tol(vector_magnitude(w),1)); CU_ASSERT(w->x==0); CU_ASSERT(w->y==-1); CU_ASSERT(w->z==0); }
void vector_free__( void * arg ) { vector_free( vector_safe_cast( arg )); }
void ecl_rft_file_free(ecl_rft_file_type * rft_vector) { vector_free(rft_vector->data); hash_free( rft_vector->well_index ); free(rft_vector->filename); free(rft_vector); }
boolformula_t *learn_core (void *info, uscalar_t num_vars, membership_t membership, membership_t comembership, equivalence_t equivalence, int mode) { equivalence_result_t *eq_result; conjunction *conjecture; vector *bases; bases = vector_new (0); conjecture = get_conjecture (bases); boolformula_t* b_conjecture = cdnfformula_to_boolformula (conjecture); vector_free (conjecture); eq_result = (*equivalence) (info, num_vars, boolformula_copy (b_conjecture)); if (eq_result->is_equal) { //fprintf(stderr,"Number of Variables Used : %d\n", (unsigned int)num_vars); free(eq_result); return b_conjecture; } else { boolformula_free(b_conjecture); } #ifdef DEBUG fprintf (stderr, "add first basis with "); bitvector_print (eq_result->counterexample); #endif assert (bitvector_length (eq_result->counterexample) == num_vars + 1); add_basis (bases, eq_result->counterexample); bitvector_free (eq_result->counterexample); free(eq_result); while (true) { vector *I; bitvector *v; uscalar_t j, length; conjecture = get_conjecture (bases); #ifdef DEBUG fprintf (stderr, "new conjecture = "); boolformula_print (conjecture); #endif boolformula_t* b_conjecture = cdnfformula_to_boolformula (conjecture); vector_free (conjecture); eq_result = (*equivalence) (info, num_vars, boolformula_copy (b_conjecture)); if (eq_result->is_equal) { //fprintf(stderr,"Number of Variables Used : %d\n", (unsigned int)num_vars); cleanup (bases); free (eq_result); return b_conjecture; } else { boolformula_free(b_conjecture); } /* H_i's are still in bases, only free the conjunction */ assert (bitvector_length (eq_result->counterexample) == num_vars + 1); v = eq_result->counterexample; I = get_indices_to_modify (bases, v); if (vector_length (I) == 0) { if(mode==CDNF_Plus3 && (*membership)(info,v)==true) { #ifdef DEBUG fprintf (stderr, "conflict detected on: "); bitvector_print (v); fprintf (stderr, "num of variables: %d \n",num_vars); #endif refine_bases(info, membership,comembership,bases,mode); num_vars++; } else { #ifdef DEBUG fprintf (stderr, "add basis: "); bitvector_print (v); #endif add_basis (bases, v); } bitvector_free (v); free(eq_result); vector_free (I); continue; } free(eq_result); #ifdef DEBUG fprintf (stderr, "fix m_dnf with "); bitvector_print (v); #endif length = vector_length (I); for (j = 0; j < length; j++) { uscalar_t i; basis *B; bitvector *a_i, *v_i, *xor; vector *T_i; disjunction *H_i; monomial *m; i = (uscalar_t) vector_get (I, j); B = (basis *) vector_get (bases, i); a_i = B->a; T_i = B->T; H_i = B->H; v_i = bitvector_copy (v); walk (info, membership, v_i, a_i); xor = bitvector_xor (v_i, a_i); /* when xor == 0, a conflict has occurred. */ /* assert (!bitvector_is_zeros (xor)); */ if (bitvector_is_zeros (xor)) { #ifdef DEBUG fprintf (stderr, "conflict with the basis "); bitvector_print (a_i); #endif bitvector_free (xor); bitvector_free (v_i); if(mode==CDNF_PlusPlus||mode==CDNF_Plus3) { /* increase the number of variables */ #ifdef DEBUG fprintf (stderr, "num of variables: %d \n",num_vars); #endif refine_bases (info, membership, comembership, bases,mode); num_vars++; } else { bitvector_free (v); vector_free (I); return NULL; } break; } #ifdef DEBUG fprintf (stderr, "add support "); bitvector_print (v_i); #endif /* store v_i in T_i */ /* note that the original CDNF algorithm stores xor in S_i */ vector_add (T_i, v_i); /* compute M_DNF (v_i + a_i) */ m = cdnfformula_monomial_M_DNF (xor); /* compute m (x ^ a_i) */ m = compute_m_of_x_xor_a (m, a_i); vector_add (H_i, m); bitvector_free (xor); } bitvector_free (v); vector_free (I); } }
static void check_print_and_free_new_random_vector_______sent_size_vector_array_____returned(void **state){ vector_t * vc =vector_random(); assert_int_equal(vector_print(vc),1); assert_int_equal(vector_free(vc),1); }
/*===========================================================================* * main * *===========================================================================*/ int main(int argc, char **argv) { /* This is the main routine of this service. The main loop consists of * three major activities: getting new work, processing the work, and * sending the reply. The loop never terminates, unless a panic occurs. */ message m_in; int result; sef_startup(); vector_init(&sem_list); Qvector_init(&waiting_list); stackInit(&sem_stack,5); /* Main loop - get work and do it, forever. */ while (TRUE) { /* Wait for incoming message, sets 'callnr' and 'who'. */ get_work(&m_in); //printf("SEM recieved message %d\n",callnr); if (is_notify(callnr)) { printf("SEM: warning, got illegal notify from: %d\n", m_in.m_source); result = EINVAL; goto send_reply; } int arg = m_in.m1_i1; switch(callnr) { case SEM_INIT: //printf("Sem_init called, semaphore size 3%d.\n",arg); result = sem_init(arg); break; case SEM_UP: //printf("Sem_up called on semaphore %d.\n",arg); result = sem_up(arg); break; case SEM_DOWN: //printf("Sem_down called on semaphore %d. source: %d\n",arg,who_e); result = sem_down(arg,m_in.m_source); break; case SEM_RELEASE: //printf("Sem_release called on semaphore %d.\n",arg); result = sem_release(arg); break; default: printf("SEMAPHORE: warning, got illegal request from %d\n", m_in.m_source); result = EINVAL; } send_reply: /* Finally send reply message, unless disabled. */ if (result != EDONTREPLY) { m_in.m_type = result; /* build reply message */ reply(who_e, &m_in); /* send it away */ } } Qvector_free(&waiting_list); vector_free(&sem_list); return(OK); /* shouldn't come here */ }
void refine_bases (void *info, membership_t membership, membership_t comembership, vector *bases, int mode) { uscalar_t i, length; length = vector_length (bases); #ifdef DEBUG fprintf (stderr, "refine bases, num of DNF = %d",length); #endif for (i = 0; i < length; i++) { basis *B; bitvector *a_i; vector *T_i; uscalar_t l, T_i_len, j; bool b; B = (basis *) vector_get (bases, i); /* * extends each unsatisfying assignment by FALSE */ a_i = B->a; l = bitvector_length (a_i); bitvector_resize (a_i, l + 1); bitvector_set (a_i, l, false); if(mode==CDNF_PlusPlus) b = (*comembership) (info, a_i) == true ? false : true; else b=false; bitvector_set (a_i, l, b); #ifdef DEBUG fprintf (stderr, "extends basis: "); bitvector_print (a_i); #endif #ifdef DEBUG fprintf (stderr, "extends support: "); #endif T_i = B->T; T_i_len = vector_length (T_i); /* except the last basis, all bases have at least one support */ assert (i == length - 1 || T_i_len > 0); for (j = 0; j < T_i_len; j++) { bitvector *v; bool c; /* * extends v to v+b if MEM (v+b) = YES * to v+!b if MEM (v+b) = NO */ v = (bitvector *)vector_get (T_i, j); assert (bitvector_length (v) == l); bitvector_resize (v, l + 1); bitvector_set (v, l, b); c = (*membership) (info, v) == true ? b : !b; if (c != b) bitvector_set (v, l, c); #ifdef DEBUG bitvector_print (v); #endif } /* clean up disjunction for the current basis */ cdnfformula_disjunction_free (B->H); B->H = NULL; /* remove the last basis if it has no support */ if (T_i_len == 0) { assert (i == length - 1); bitvector_free (a_i); vector_free (T_i); free (vector_get (bases, length - 1)); vector_resize (bases, length - 1); } } /* * reconstruct disjunctions for the bases */ rebuild_disjunctions (bases); }
histogram *jackwerth::compute_histogram(double lo, double hi, double increment) { volatile double lokappa = 0.0; volatile double hikappa = 1.0; int done = 0; // OK, first we need to calculate "J" the number of entries in the computed // volatilities array. (And, the matrix size as well) int J = 1+(int)(1+((hi - lo) / increment)); // I is the number of observed values, so that's simply _num_observed. double **baseA = matrix_allocate(J,J,0.0); double **A = matrix_allocate(J,J,0.0); double *X = vector_allocate(J,0.0); double *B = vector_allocate(J,0.0); double final_probs[J]; for (int j = 0; j < J; ++j) { int values[] = { 1,-4,6,-4,1}; for (int k = -2; k <= 2; ++k) { int actual_k = j + k; int offset = values[k+2]; if (actual_k < 0) actual_k = 0; if (actual_k >= J) actual_k = (J-1); baseA[j][actual_k] = offset; } } int iters = 128; while (!done) { double kappa = lokappa + (hikappa - lokappa) / 2.0; double prop = (kappa - lokappa) / (hikappa - lokappa); done = (prop == 0.0); // OK, Kappa is _Binesh's_ invention. Kappa relates to lambda like so: // kappa = lambda / (1+lambda). // so, lambda = kappa / (1-kappa) // Why? This way Kappa = 0 is effectively reducing lambda to 0. // Kappa = 1 tho, would be lambda at a "infinite" value. (In reality, we'd // likely start at kappa = 0.9 and work till we didn't have any negative values. double lambda = kappa / (1-kappa); for (int i = 0; i < J; ++i) { B[i] = 0.0; for (int j = 0; j < J; ++j) A[i][j] = baseA[i][j]; } // Now, we have to add all the I's. // we have to make sure that each option here is actually // exactly on our "grid" (or rather on our discretized line). double coeff = lambda * (J * 1.0) / (_num_observed * increment * increment * increment * increment); for (int i = 0; i < _num_observed; ++i) { int index = (int)(0.5+((_observed_strikes[i] - lo) / increment)); // Now, _observed_strikes[i] - (index * increment + lo) should be "close" to zero. double trust_but_verify = _observed_strikes[i] - (index * increment + lo); if (!(((-increment/100) < trust_but_verify) && (trust_but_verify < (increment/100)))) { fprintf(stderr,"%s: %d: _observed_strikes[%d] = %.7g\n",__FILE__,__LINE__,i,_observed_strikes[i]); fprintf(stderr,"%s: %d: lo = %.7g\n",__FILE__,__LINE__,lo); fprintf(stderr,"%s: %d: index = %d\n",__FILE__,__LINE__,index); fprintf(stderr,"%s: %d: increment = %.7g\n",__FILE__,__LINE__,increment); fprintf(stderr,"%s: %d: trust_but_verify = %.7g\n",__FILE__,__LINE__,trust_but_verify); } assert(((-increment/100) < trust_but_verify) && (trust_but_verify < (increment/100))); double Aii = A[index][index]; double Bi = B[index]; A[index][index] = Aii+coeff; B[index] = Bi+coeff*_observed_volatilities[i]; } // OK, now we have to solve for X. just_svd(A,J,B,X); /* Now, the probabilities, according to page 66 of Jackwerth are Exp[r T] D[D[BS[S,K,r,q,V[K],T],K],K] if I read that right. I don't _like_ his version, because it uses r as the percentaged based return rather than an Exp[r] type r (ditto for q, the dividend yield.) Hopefully, mine will return the same results. We'll see in a minute. (I'm also not so sure I understand _why_ the equation works. _If_ it works, I'll have to look into _why_.) My version (or rather, mathematica's version _does_ work. However, Jackwerth's A. also works, B. is provably _equal_ to the mathematica version (implement both, and subtracting mathematica from jackwerth yields 0 in mathematica) and C. is less prone to numeric errors. */ const double *volatility = X; // just a renaming of the variable, really. double probs[J]; probs[0] = 0.0; probs[(J-1)] = 0.0; double total = 0.0; for (int j = 1; j < (J-1); ++j) { double V_K = volatility[j]; double dVdK = (volatility[j+1] - volatility[j-1]) / (2*increment); double dV2dK2 = (volatility[j-1] - 2*volatility[j] + volatility[j+1]) / (increment*increment); double q = _q; double r = _r; double T = _t; double S = _S; double K = lo + increment * j; double d1j = (log(S/K) + (r - q + V_K*V_K / 2.0) * T) / (V_K * sqrt(T)); double d2j = d1j - V_K * sqrt(T); probs[j] = ( (pdf(d2j)*(1+2*K * sqrt(T)*d1j*dVdK)/(K*V_K*sqrt(T))) + (S * exp(T*(r-q))*sqrt(T)*pdf(d1j)*(dV2dK2 + d1j*d2j * dVdK*dVdK / V_K)) ); total += probs[j]; } int negative_probs = 0; for (int j = 0; j < J; ++j) { probs[j] = probs[j] / total; if (probs[j] < 0.0) negative_probs = 1; } if (!negative_probs) { for (int j = 0; j < J; ++j) final_probs[j] = probs[j]; } if (negative_probs) { done = 0; hikappa = kappa; } else lokappa = kappa; iters--; if (iters < 0) done = 1; } vector_free(B); B = NULL; vector_free(B); B = NULL; vector_free(X); X = NULL; matrix_free(baseA); baseA = NULL; matrix_free(A); A = NULL; /* * OK, final_probs should contain our list of final probabilities. * Build a histogram: * The histogram will contain J bins, so it has to contain J+1 fenceposts. * The fenceposts should be log(K/S) values. */ double fenceposts[J+1]; /* Binesh - 2008-10-10 - Ugh. for (int j = 0; j < J+1; ++j) yields a "cannot optimize possibly infinite loops" error. So, that's why there's a "volatile" in front of int. */ for (volatile int j = 0; j < J+1; ++j) { double K = lo + increment * j - increment/2.0; double S = _S; double l = log(K/S); fenceposts[j] = l; } histogram *retVal = new histogram(J,fenceposts); for (int j = 0; j < J; ++j) { double K = lo + increment * j - increment/2.0; double S = _S; double l = log(K/S); retVal->accumulate(l,final_probs[j]); } return(retVal); }
void test_serialize() { char hex0[] = "28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c1"; char hex1[] = "28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c2"; char hex2[] = "28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c3"; uint8_t* hash0 = malloc(32); uint8_t* hash1 = malloc(32); uint8_t* hash2 = malloc(32); memcpy(hash0, utils_hex_to_uint8(hex0), 32); memcpy(hash1, utils_hex_to_uint8(hex1), 32); memcpy(hash2, utils_hex_to_uint8(hex2), 32); vector* vec = vector_new(5, free); vector_add(vec, hash0); vector_add(vec, hash1); vector_add(vec, hash2); cstring* s = cstr_new_sz(200); ser_u256_vector(s, vec); vector_free(vec, true); vector* vec2 = vector_new(0, NULL); struct const_buffer buf = {s->str, s->len}; deser_u256_vector(&vec2, &buf); vector_free(vec2, true); cstr_free(s, true); cstring* s2 = cstr_new_sz(200); ser_u16(s2, 0xAAFF); ser_u32(s2, 0xDDBBAAFF); ser_u64(s2, 0x99FF99FFDDBBAAFF); ser_varlen(s2, 10); ser_varlen(s2, 1000); ser_varlen(s2, 100000000); ser_str(s2, "test", 4); cstring* s3 = cstr_new("foo"); ser_varstr(s2, s3); cstr_free(s3, true); // ser_varlen(s2, (uint64_t)0x9999999999999999); // uint64 varlen is not supported right now struct const_buffer buf2 = {s2->str, s2->len}; uint16_t num0; deser_u16(&num0, &buf2); assert(num0 == 43775); //0xAAFF uint32_t num1; deser_u32(&num1, &buf2); assert(num1 == 3720063743); //0xDDBBAAFF uint64_t num2; deser_u64(&num2, &buf2); assert(num2 == 0x99FF99FFDDBBAAFF); //0x99FF99FFDDBBAAFF uint32_t num3; deser_varlen(&num3, &buf2); assert(num3 == 10); deser_varlen(&num3, &buf2); assert(num3 == 1000); deser_varlen(&num3, &buf2); assert(num3 == 100000000); char strbuf[255]; deser_str(strbuf, &buf2, 255); assert(strncmp(strbuf, "test", 4) == 0); cstring* deser_test = cstr_new_sz(0); deser_varstr(&deser_test, &buf2); assert(strncmp(deser_test->str, "foo", 3) == 0); cstr_free(deser_test, true); cstr_free(s2, true); }
/* ============================================================================= * data_generate * -- Binary variables of random PDFs * -- If seed is <0, do not reseed * -- Returns random network * ============================================================================= */ net_t* data_generate (data_t* dataPtr, long seed, long maxNumParent, long percentParent) { random_t* randomPtr = dataPtr->randomPtr; if (seed >= 0) { random_seed(randomPtr, seed); } /* * Generate random Bayesian network */ long numVar = dataPtr->numVar; net_t* netPtr = net_alloc(numVar); assert(netPtr); net_generateRandomEdges(netPtr, maxNumParent, percentParent, randomPtr); /* * Create a threshold for each of the possible permutation of variable * value instances */ long** thresholdsTable = (long**)SEQ_MALLOC(numVar * sizeof(long*)); assert(thresholdsTable); long v; for (v = 0; v < numVar; v++) { list_t* parentIdListPtr = net_getParentIdListPtr(netPtr, v); long numThreshold = 1 << list_getSize(parentIdListPtr); long* thresholds = (long*)SEQ_MALLOC(numThreshold * sizeof(long)); assert(thresholds); long t; for (t = 0; t < numThreshold; t++) { long threshold = random_generate(randomPtr) % (DATA_PRECISION + 1); thresholds[t] = threshold; } thresholdsTable[v] = thresholds; } /* * Create variable dependency ordering for record generation */ long* order = (long*)SEQ_MALLOC(numVar * sizeof(long)); assert(order); long numOrder = 0; queue_t* workQueuePtr = queue_alloc(-1); assert(workQueuePtr); vector_t* dependencyVectorPtr = vector_alloc(1); assert(dependencyVectorPtr); bitmap_t* orderedBitmapPtr = bitmap_alloc(numVar); assert(orderedBitmapPtr); bitmap_clearAll(orderedBitmapPtr); bitmap_t* doneBitmapPtr = bitmap_alloc(numVar); assert(doneBitmapPtr); bitmap_clearAll(doneBitmapPtr); v = -1; while ((v = bitmap_findClear(doneBitmapPtr, (v + 1))) >= 0) { list_t* childIdListPtr = net_getChildIdListPtr(netPtr, v); long numChild = list_getSize(childIdListPtr); if (numChild == 0) { bool status; /* * Use breadth-first search to find net connected to this leaf */ queue_clear(workQueuePtr); status = queue_push(workQueuePtr, (void*)v); assert(status); while (!queue_isEmpty(workQueuePtr)) { long id = (long)queue_pop(workQueuePtr); status = bitmap_set(doneBitmapPtr, id); assert(status); status = vector_pushBack(dependencyVectorPtr, (void*)id); assert(status); list_t* parentIdListPtr = net_getParentIdListPtr(netPtr, id); list_iter_t it; list_iter_reset(&it, parentIdListPtr); while (list_iter_hasNext(&it, parentIdListPtr)) { long parentId = (long)list_iter_next(&it, parentIdListPtr); status = queue_push(workQueuePtr, (void*)parentId); assert(status); } } /* * Create ordering */ long i; long n = vector_getSize(dependencyVectorPtr); for (i = 0; i < n; i++) { long id = (long)vector_popBack(dependencyVectorPtr); if (!bitmap_isSet(orderedBitmapPtr, id)) { bitmap_set(orderedBitmapPtr, id); order[numOrder++] = id; } } } } assert(numOrder == numVar); /* * Create records */ char* record = dataPtr->records; long r; long numRecord = dataPtr->numRecord; for (r = 0; r < numRecord; r++) { long o; for (o = 0; o < numOrder; o++) { long v = order[o]; list_t* parentIdListPtr = net_getParentIdListPtr(netPtr, v); long index = 0; list_iter_t it; list_iter_reset(&it, parentIdListPtr); while (list_iter_hasNext(&it, parentIdListPtr)) { long parentId = (long)list_iter_next(&it, parentIdListPtr); long value = record[parentId]; assert(value != DATA_INIT); index = (index << 1) + value; } long rnd = random_generate(randomPtr) % DATA_PRECISION; long threshold = thresholdsTable[v][index]; record[v] = ((rnd < threshold) ? 1 : 0); } record += numVar; assert(record <= (dataPtr->records + numRecord * numVar)); } /* * Clean up */ bitmap_free(doneBitmapPtr); bitmap_free(orderedBitmapPtr); vector_free(dependencyVectorPtr); queue_free(workQueuePtr); SEQ_FREE(order); for (v = 0; v < numVar; v++) { SEQ_FREE(thresholdsTable[v]); } SEQ_FREE(thresholdsTable); return netPtr; }
static matrix_t* matrix_substitute_variables(pk_internal_t* pk, matrix_t* mat, ap_dim_t* tdim, numint_t** tvec, size_t size) { size_t i,j,eindex; matrix_t* nmat = matrix_alloc(mat->nbrows, mat->nbcolumns,false); numint_t den; /* Computing common denominator */ numint_init_set(den,tvec[0][0]); for (i=1; i<size; i++){ numint_mul(den,den,tvec[i][0]); } if (numint_cmp_int(den,1)!=0){ /* General case */ numint_t* vden = vector_alloc(size); for (i=0; i<size; i++){ numint_divexact(vden[i],den,tvec[i][0]); } /* For each row */ for (i=0; i<mat->nbrows; i++) { /* Column 0 */ numint_set(nmat->p[i][0],mat->p[i][0]); /* Other columns */ /* First, copy the row and sets to zero substituted variables */ eindex = 0; for (j=1; j<mat->nbcolumns; j++){ if (eindex < size && pk->dec + tdim[eindex] == j) eindex++; else numint_mul(nmat->p[i][j],mat->p[i][j],den); } /* Second, add things coming from substitution */ for (j=1; j<mat->nbcolumns; j++){ for (eindex=0; eindex<size; eindex++){ if (numint_sgn(mat->p[i][pk->dec + tdim[eindex]])) { numint_mul(pk->matrix_prod, mat->p[i][pk->dec + tdim[eindex]], tvec[eindex][j]); numint_mul(pk->matrix_prod,pk->matrix_prod,vden[eindex]); numint_add(nmat->p[i][j],nmat->p[i][j],pk->matrix_prod); } } } } vector_free(vden,size); } else { /* Special case: all denominators are 1 */ /* For each row */ for (i=0; i<mat->nbrows; i++) { /* Column 0 */ numint_set(nmat->p[i][0],mat->p[i][0]); /* Other columns */ /* First, copy the row and sets to zero substituted variables */ eindex = 0; for (j=1; j<mat->nbcolumns; j++){ if (eindex < size && pk->dec + tdim[eindex] == j) eindex++; else numint_set(nmat->p[i][j],mat->p[i][j]); } /* Second, add things coming from substitution */ for (j=1; j<mat->nbcolumns; j++){ for (eindex=0; eindex<size; eindex++){ if (numint_sgn(mat->p[i][pk->dec + tdim[eindex]])) { numint_mul(pk->matrix_prod, mat->p[i][pk->dec + tdim[eindex]], tvec[eindex][j]); numint_add(nmat->p[i][j],nmat->p[i][j],pk->matrix_prod); } } } } } numint_clear(den); for (i=0; i<mat->nbrows; i++){ matrix_normalize_row(pk,nmat,i); } return nmat; }
/* ---------------------------------------------------------------------- */ static matrix_t* matrix_assign_variables(pk_internal_t* pk, matrix_t* mat, ap_dim_t* tdim, numint_t** tvec, size_t size) { size_t i,j,eindex; matrix_t* nmat = _matrix_alloc_int(mat->nbrows, mat->nbcolumns,false); numint_t den; /* Computing common denominator */ numint_init_set(den,tvec[0][0]); for (i=1; i<size; i++){ numint_mul(den,den,tvec[i][0]); } if (numint_cmp_int(den,1)!=0){ /* General case */ numint_t* vden = vector_alloc(size); for (i=0; i<size; i++){ numint_divexact(vden[i],den,tvec[i][0]); } /* Column 0: copy */ for (i=0; i<mat->nbrows; i++){ numint_init_set(nmat->p[i][0],mat->p[i][0]); } /* Other columns */ eindex = 0; for (j=1; j<mat->nbcolumns; j++){ if (eindex < size && pk->dec + tdim[eindex] == j){ /* We are on an assigned column */ for (i=0; i<mat->nbrows; i++){ /* For each row */ vector_product(pk,pk->matrix_prod, mat->p[i], tvec[eindex],mat->nbcolumns); numint_mul(pk->matrix_prod,pk->matrix_prod,vden[eindex]); /* Put the result */ numint_init_set(nmat->p[i][j],pk->matrix_prod); } eindex++; } else { /* We are on a normal column */ for (i=0; i<mat->nbrows; i++){ /* For each row */ numint_init(nmat->p[i][j]); numint_mul(nmat->p[i][j],mat->p[i][j],den); } } } vector_free(vden,size); } else { /* Special case: all denominators are 1 */ /* Column 0: copy */ for (i=0; i<mat->nbrows; i++){ numint_init_set(nmat->p[i][0],mat->p[i][0]); } /* Other columns */ eindex = 0; for (j=1; j<mat->nbcolumns; j++){ if (eindex < size && pk->dec + tdim[eindex] == j){ /* We are on a assigned column */ for (i=0; i<mat->nbrows; i++){ /* For each row */ vector_product(pk,pk->matrix_prod, mat->p[i], tvec[eindex],mat->nbcolumns); numint_init_set(nmat->p[i][j],pk->matrix_prod); } eindex++; } else { /* We are on a normal column */ for (i=0; i<mat->nbrows; i++){ /* For each row */ numint_init_set(nmat->p[i][j],mat->p[i][j]); } } } } numint_clear(den); for (i=0; i<mat->nbrows; i++){ matrix_normalize_row(pk,nmat,i); } return nmat; }
void config_content_item_free( config_content_item_type * item ) { vector_free( item->nodes ); free(item); }
void obs_vector_free(obs_vector_type * obs_vector) { vector_free( obs_vector->nodes ); free(obs_vector->obs_key); free(obs_vector); }
/* Execute command by argument readline. */ int cmd_execute_command_strict (vector vline, struct vty *vty, struct cmd_element **cmd) { unsigned int i; unsigned int index; vector cmd_vector; enum match_type match = 0; struct cmd_element *cmd_element; struct cmd_element *matched_element; unsigned int matched_count, incomplete_count; int argc; const char *argv[CMD_ARGC_MAX]; int varflag; char * command; cmd_vector = vector_copy(cmd_node_vector(cmdvec, vty->node)); for(index = 0; index < vector_active(vline); index++) { if((command = vector_slot(vline, index))) { int ret; match = cmd_filter_by_string(vector_slot(vline, index), cmd_vector, index); if(match == vararg_match) break; ret = is_cmd_ambiguous (command, cmd_vector, index, match); if (ret == 1) { vector_free (cmd_vector); return CMD_ERR_AMBIGUOUS; } if (ret == 2) { vector_free (cmd_vector); return CMD_ERR_NO_MATCH; } } } /* Check matched count. */ matched_element = NULL; matched_count = 0; incomplete_count = 0; for (i = 0; i < vector_active (cmd_vector); i++) if (vector_slot (cmd_vector, i) != NULL) { cmd_element = vector_slot (cmd_vector, i); if (match == vararg_match || index >= cmd_element->cmdsize) { matched_element = cmd_element; matched_count++; } else incomplete_count++; } /* Finish of using cmd_vector. */ vector_free (cmd_vector); /* To execute command, matched_count must be 1. */ if (matched_count == 0) { if (incomplete_count) return CMD_ERR_INCOMPLETE; else return CMD_ERR_NO_MATCH; } if (matched_count > 1) return CMD_ERR_AMBIGUOUS; /* Argument treatment */ varflag = 0; argc = 0; for (i = 0; i < vector_active (vline); i++) { if (varflag) argv[argc++] = vector_slot (vline, i); else { vector descvec = vector_slot (matched_element->strvec, i); if (vector_active (descvec) == 1) { struct desc *desc = vector_slot (descvec, 0); if (CMD_VARARG (desc->cmd)) varflag = 1; if (varflag || CMD_VARIABLE (desc->cmd) || CMD_OPTION (desc->cmd)) argv[argc++] = vector_slot (vline, i); } else argv[argc++] = vector_slot (vline, i); } if (argc >= CMD_ARGC_MAX) return CMD_ERR_EXEED_ARGC_MAX; } /* For vtysh execution. */ if (cmd) *cmd = matched_element; if (matched_element->daemon) return CMD_SUCCESS_DAEMON; /* Now execute matched command */ return (*matched_element->func) (matched_element, vty, argc, argv); }
void module_data_block_vector_free( module_data_block_vector_type * module_data_block_vector ) { vector_free( module_data_block_vector->data_block_vector ); free( module_data_block_vector ); }
void hash_table_free(hash_table *t) { vector_free(&t->buckets); }
void container_free( container_type * container ) { vector_free( container->nodes ); free( container ); }