示例#1
0
void pcg32_srandom_r(pcg32_random_t* rng, uint64_t initial_state, uint64_t initseq)
{
    rng->state = 0U;
    rng->inc = (initseq << 1u) | 1u;
    pcg32_random_r(rng);
    rng->state += initial_state;
    pcg32_random_r(rng);
}
示例#2
0
uint32_t pcg32_boundedrand_r(pcg32_random_t* rng, uint32_t bound)
{
    // To avoid bias, we need to make the range of the RNG a multiple of
    // bound, which we do by dropping output less than a threshold.
    // A naive scheme to calculate the threshold would be to do
    //
    //     uint32_t threshold = 0x100000000ull % bound;
    //
    // but 64-bit div/mod is slower than 32-bit div/mod (especially on
    // 32-bit platforms).  In essence, we do
    //
    //     uint32_t threshold = (0x100000000ull-bound) % bound;
    //
    // because this version will calculate the same modulus, but the LHS
    // value is less than 2^32.

    uint32_t threshold = -bound % bound;

    // Uniformity guarantees that this loop will terminate.  In practice, it
    // should usually terminate quickly; on average (assuming all bounds are
    // equally likely), 82.25% of the time, we can expect it to require just
    // one iteration.  In the worst case, someone passes a bound of 2^31 + 1
    // (i.e., 2147483649), which invalidates almost 50% of the range.  In 
    // practice, bounds are typically small and only a tiny amount of the range
    // is eliminated.
    for (;;) {
        uint32_t r = pcg32_random_r(rng);
        if (r >= threshold)
            return r % bound;
    }
}
void mutate(gsl_matrix *chromosome, gsl_matrix *bounds, pcg32_random_t *rng)
{
    uint32_t rows = chromosome->size1,
             cols = chromosome->size2,
             row, 
             col;
    double r, min, max;

    // Select a random row and column
    row = (uint32_t)pcg32_boundedrand_r(rng, rows);
    col = (uint32_t)pcg32_boundedrand_r(rng, cols);

    // Set to a random value within the bounds
    min = gsl_matrix_get(bounds, col, 0);
    max = gsl_matrix_get(bounds, col, 1);
    r = (ldexp(pcg32_random_r(rng), -32) * (max - min)) + min;
    gsl_matrix_set(chromosome, row, col, r);

    if (DEBUG == DEBUG_MUTATE)
    {
        printf(YELLOW "MUTATED CHROMSOME\n" RESET);
        printf(YELLOW "ROW: %d, COL: %d, VAL: %10.6f\n" RESET, row, col, r);
        for (uint32_t i = 0; i < rows; ++i)
        {
            for (uint32_t j = 0; j < cols; ++j)
            {
                printf(YELLOW "%10.6f " RESET, gsl_matrix_get(chromosome, i, j));
            }
            printf("\n");
        }
    }
}
示例#4
0
void dostep(world *w){
    int nextbind = pcg32_boundedrand_r(&rng, w->nbonds); //ran_int(0, w->nbonds);
    int nextbond = w->bonds[nextbind];
    double test = ldexp(pcg32_random_r(&rng), -32);

    int ind0, ind1;
    bond2inds(w->N, nextbond, &ind0, &ind1);

    int ind = 0;
    int tx, ty;
    if (w->grid[ind0] == w->grid[ind1]){
        remove_bond(w, nextbond);
        return;
    }

    if (test < 1.0/(1+w->alpha)){
        ind = ind0 * (w->grid[ind0] == SS) + ind1 * (w->grid[ind1] == SS);
        ind2xy(w->N, ind, &tx, &ty);
        add_zombie(w, tx, ty);
    } else {
        ind = ind0 * (w->grid[ind0] == SZ) + ind1 * (w->grid[ind1] == SZ);
        ind2xy(w->N, ind, &tx, &ty);
        kill_site(w, tx, ty);
    }
}
示例#5
0
int rand_cdf_index(pcg32_random_t *rng, double *cdf, int N) {
    /* uniform random number between 0 and 1 */
    double r = ldexp(pcg32_random_r(rng), -32);
    for (int i = 0; i < N; i++){
      if (r < cdf[i]) {
        return i;
      }
    }
    return 0;
}
示例#6
0
int main() {

    Node* nodes = calloc(N, sizeof(Node));

    struct Heap heap;
    heap_init(&heap, nodes, N, D);

    pcg32_random_t rng1;
    pcg32_srandom_r(&rng1, time(NULL), (intptr_t)&rng1);

    for (int i = 0; i < N; i++) {
        Node* newnode = heap.nodes + i;
        newnode->id = i + 1;
        newnode->min_edge = 100 * (float) pcg32_random_r(&rng1) / UINT32_MAX;
    }

    heap_number(&heap);

    printf("unordered: \n");
    print_heap(&heap);

    min_heapify(&heap);

    printf("ordered: \n");
    print_heap(&heap);

    printf("min: %f\n\n", heap_find_min(&heap).min_edge);

    heap_deletemin(&heap);

    printf("deletemin: \n");
    print_heap(&heap);

    Node n = {.min_edge = 2.0, .id = heap.n + 1};

    heap_insert(&heap, n);

    printf("\ninsert: \n");
    print_heap(&heap);

    /*for (int i = 0; i < N; i++) {
        printf("min: %f\n\n", heap_find_min(&heap).min_edge);
        heap_deletemin(&heap);
        printHeap(&heap);
    }
*/
    free_heap(&heap);

}
示例#7
0
int get_random_value_rng(rng_t *rng, double *output)
{
    if(rng == NULL) {
        errno = EINVAL;
        return -1;
    }

    if(rng->distribution == RNG_UNIFORM) {
        uint32_t random_number = pcg32_random_r(rng->pcg_rng);
        double value = ldexp(random_number, -32);
        *output = value;
        return 0;
    }
    return -1;
}
示例#8
0
void presentencrypt(char *str, uint8_t *retstr)
{

    pcg32_random_t rng;
    pcg32_srandom_r(&rng, time(NULL) ^ (intptr_t)&printf, (intptr_t)&rounds);
    uint32_t rang = pcg32_random_r(&rng);
    memcpy(iv,&rang,sizeof(iv));

    uint8_t newMessage[200];
    //pad the message string and turn into bytearray
    padStr(str,newMessage);

    cbc_encrypt((uint8_t*)theKey,iv,newMessage,lenmsg);

    memcpy(retstr,newMessage,sizeof(newMessage));

    printf("sizeof(newMessage) %d\n", sizeof(newMessage));
}  
示例#9
0
文件: rng.c 项目: pyk/simple-nn
/* rng_get_random_value: Get the next random number from random number
 * generator rng and write the result to the output.
 *
 * It returns non-zero value if output is NULL
 * It returns zero if the operation success, the random number will be
 * written into output */
int rng_get_random_value(rng_t rng, double *output)
{
    if(output == NULL) {
        errno = EINVAL;
        return -1;
    }

    if(rng.distribution == RNG_UNIFORM) {
        uint32_t random_number = pcg32_random_r(rng.pcg_rng);
        double value = ldexp(random_number, -32);
        *output = value;
        return 0;
    }

    /* TODO(pyk): implement NORMAL or GAUSSIAN distribution */

    return -1;
}
int select_parent(int size, double probability[size], pcg32_random_t *rng)
{
    int idx = 0;
    double r = pcg32_random_r(rng) / (double)UINT32_MAX;

    for (int i = 0; i < size; ++i)
    {
        if (i == 0)
        {
            if (r < probability[i])
            {
                idx = i;
                break;
            }
        }
        else if (r >= probability[i-1] && r < probability[i])
        {
            idx = i;
            break;
        }
    }
    return idx;
}
示例#11
0
uint32_t pcg32_random()
{
    return pcg32_random_r(&pcg32_global);
}
示例#12
0
uint32_t Math::rand() {
	return pcg32_random_r(&default_pcg);
}
示例#13
0
// TODO: we should eventually expose pcg.inc too
uint32_t Math::rand_from_seed(uint64_t *seed) {
	pcg32_random_t pcg = { *seed, PCG_DEFAULT_INC_64 };
	uint32_t r = pcg32_random_r(&pcg);
	*seed = pcg.state;
	return r;
}
示例#14
0
文件: myssl.c 项目: captdeaf/pennmush
/** Initialize the SSL context.
 * \return pointer to SSL context object.
 */
SSL_CTX *
ssl_init(char *private_key_file, char *ca_file, char *ca_dir,
         int req_client_cert)
{
  const SSL_METHOD
    *meth; /* If this const gives you a warning, you're
              using an old version of OpenSSL. Walker, this means you! */
  /* uint8_t context[128]; */
  unsigned int reps = 1;
  pcg32_random_t rand_state;
  uint64_t seeds[2];
  bool seeded = false;

  if (!bio_err) {
    if (!SSL_library_init())
      return NULL;
    SSL_load_error_strings();
    /* Error write context */
    bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
  }

  lock_file(stderr);
  fputs("Seeding OpenSSL random number pool.\n", stderr);
  unlock_file(stderr);
  while (!RAND_status()) {
    /* At this point, a system with /dev/urandom or a EGD file in the usual
       places will have enough entropy. Otherwise, be lazy and use random
       numbers until it's satisfied. */
    uint32_t gibberish[8];
    int n;

    if (!seeded) {
      generate_seed(seeds);
      pcg32_srandom_r(&rand_state, seeds[0], seeds[1]);
      seeded = 1;
    }

    for (n = 0; n < 8; n++)
      gibberish[n] = pcg32_random_r(&rand_state);

    RAND_seed(gibberish, sizeof gibberish);

    reps += 1;
  }

  lock_file(stderr);
  fprintf(stderr, "Seeded after %u %s.\n", reps, reps > 1 ? "cycles" : "cycle");
  unlock_file(stderr);

  /* Set up SIGPIPE handler here? */

  /* Create context */
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
  meth = TLS_server_method();
#else
  meth = SSLv23_server_method();
#endif
  ctx = SSL_CTX_new(meth);
  SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);

  /* Load keys/certs */
  if (private_key_file && *private_key_file) {
    if (!SSL_CTX_use_certificate_chain_file(ctx, private_key_file)) {
      ssl_errordump("Unable to load server certificate - only anonymous "
                    "ciphers supported.");
    }
    if (!SSL_CTX_use_PrivateKey_file(ctx, private_key_file, SSL_FILETYPE_PEM)) {
      ssl_errordump(
        "Unable to load private key - only anonymous ciphers supported.");
    }
  }

  /* Load trusted CAs */
  if ((ca_file && *ca_file) || (ca_dir && *ca_dir)) {
    if (!SSL_CTX_load_verify_locations(ctx,
                                       (ca_file && *ca_file) ? ca_file : NULL,
                                       (ca_dir && *ca_dir) ? ca_dir : NULL)) {
      ssl_errordump("Unable to load CA certificates");
    }
    {
      STACK_OF(X509_NAME) *certs = NULL;
      if (ca_file && *ca_file)
        certs = SSL_load_client_CA_file(ca_file);
      if (certs)
        SSL_CTX_set_client_CA_list(ctx, certs);

      if (req_client_cert)
        SSL_CTX_set_verify(ctx,
                           SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
                           client_verify_callback);
      else
        SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, client_verify_callback);
#if (OPENSSL_VERSION_NUMBER < 0x0090600fL)
      SSL_CTX_set_verify_depth(ctx, 1);
#endif
    }
  }

  SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE | SSL_OP_ALL);
  SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
                          SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);

  /* Set up DH key */
  {
    DH *dh;
    dh = get_dh2048();
    SSL_CTX_set_tmp_dh(ctx, dh);
    DH_free(dh);
  }

#ifdef NID_X9_62_prime256v1
  /* Set up ECDH key */
  {
    EC_KEY *ecdh = NULL;
    ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
    SSL_CTX_set_tmp_ecdh(ctx, ecdh);
    EC_KEY_free(ecdh);
  }
#endif

  /* Set the cipher list to the usual default list, except that
   * we'll allow anonymous diffie-hellman, too.
   */
  SSL_CTX_set_cipher_list(ctx, "ALL:ECDH:ADH:!LOW:!MEDIUM:@STRENGTH");

  /* Set up session cache if we can */
  /*
     strncpy((char *) context, MUDNAME, 128);
     SSL_CTX_set_session_id_context(ctx, context, strlen(context));
   */

  return ctx;
}
示例#15
0
int main(int argc, char** argv)
{
    // Read command-line options

    int rounds = 5;
    bool nondeterministic_seed = false;
    int round, i;

    ++argv;
    --argc;
    if (argc > 0 && strcmp(argv[0], "-r") == 0) {
        nondeterministic_seed = true;
        ++argv;
        --argc;
    }
    if (argc > 0) {
        rounds = atoi(argv[0]);
    }

    // In this version of the code, we'll use a local rng, rather than the
    // global one.

    pcg32_random_t rng;

    // You should *always* seed the RNG.  The usual time to do it is the
    // point in time when you create RNG (typically at the beginning of the
    // program).
    //
    // pcg32_srandom_r takes two 64-bit constants (the initial state, and the
    // rng sequence selector; rngs with different sequence selectors will
    // *never* have random sequences that coincide, at all) - the code below
    // shows three possible ways to do so.

    if (nondeterministic_seed) {
        // Seed with external entropy -- the time and some program addresses
        // (which will actually be somewhat random on most modern systems).
        // A better solution, entropy_getbytes, using /dev/random, is provided
        // in the full library.
        
        pcg32_srandom_r(&rng, time(NULL) ^ (intptr_t)&printf, 
			      (intptr_t)&rounds);
    } else {
        // Seed with a fixed constant

        pcg32_srandom_r(&rng, 42u, 54u);
    }

    printf("pcg32_random_r:\n"
           "      -  result:      32-bit unsigned int (uint32_t)\n"
           "      -  period:      2^64   (* 2^63 streams)\n"
           "      -  state type:  pcg32_random_t (%zu bytes)\n"
           "      -  output func: XSH-RR\n"
           "\n",
           sizeof(pcg32_random_t));

    for (round = 1; round <= rounds; ++round) {
        printf("Round %d:\n", round);
        /* Make some 32-bit numbers */
        printf("  32bit:");
        for (i = 0; i < 6; ++i)
            printf(" 0x%08x", pcg32_random_r(&rng));
        printf("\n");

        /* Toss some coins */
        printf("  Coins: ");
        for (i = 0; i < 65; ++i)
            printf("%c", pcg32_boundedrand_r(&rng, 2) ? 'H' : 'T');
        printf("\n");

        /* Roll some dice */
        printf("  Rolls:");
        for (i = 0; i < 33; ++i) {
            printf(" %d", (int)pcg32_boundedrand_r(&rng, 6) + 1);
        }
        printf("\n");

        /* Deal some cards */
        enum { SUITS = 4, NUMBERS = 13, CARDS = 52 };
        char cards[CARDS];

        for (i = 0; i < CARDS; ++i)
            cards[i] = i;

        for (i = CARDS; i > 1; --i) {
            int chosen = pcg32_boundedrand_r(&rng, i);
            char card = cards[chosen];
            cards[chosen] = cards[i - 1];
            cards[i - 1] = card;
        }

        printf("  Cards:");
        static const char number[] = {'A', '2', '3', '4', '5', '6', '7',
                                      '8', '9', 'T', 'J', 'Q', 'K'};
        static const char suit[] = {'h', 'c', 'd', 's'};
        for (i = 0; i < CARDS; ++i) {
            printf(" %c%c", number[cards[i] / SUITS], suit[cards[i] % SUITS]);
            if ((i + 1) % 22 == 0)
                printf("\n\t");
        }
        printf("\n");

        printf("\n");
    }

    return 0;
}
示例#16
0
/**
 * The E-means algorithm, uses a genetic algorithm to optimize the parameters 
 * for the K-means implemetation of clustering based Lloyds clustering algorithm.
 *
 * @return        Status code, 0 for SUCCESS, 1 for ERROR
 */
int emeans(void)
{
    gsl_matrix *data = NULL,
               *bounds = NULL,
               *parent1 = NULL,
               *parent2 = NULL,
               **population = NULL,
               **new_population = NULL,
               ***clusters = NULL;
    int status = SUCCESS;
    double fitness[size],
           probability[size];

    // Initialize the PRNG
    pcg32_random_t rng;
    int rounds = 5;
    pcg32_srandom_r(&rng, time(NULL) ^ (intptr_t)&printf, (intptr_t)&rounds);

    // Allocate memory and load the data
    data = gsl_matrix_alloc(data_rows, data_cols);
    bounds = gsl_matrix_alloc(data_cols, 2);
    parent1 = gsl_matrix_alloc(n_clusters, data_cols);
    parent2 = gsl_matrix_alloc(n_clusters, data_cols);
    population = (gsl_matrix **)calloc(size, sizeof(gsl_matrix **));
    new_population = (gsl_matrix **)calloc(size, sizeof(gsl_matrix **));
    clusters = (gsl_matrix ***)calloc(size, sizeof(gsl_matrix ***));

    for (int i = 0; i < (int)size; ++i)
    {
        clusters[i] = (gsl_matrix **)calloc(n_clusters, sizeof(gsl_matrix **));
        population[i] = gsl_matrix_alloc(n_clusters, data_cols);
        new_population[i] = gsl_matrix_alloc(n_clusters, data_cols);
    }
    if ((status = load_data(data_file, data)) != SUCCESS)
    {   
        fprintf(stderr, RED "Unable to load data!\n" RESET);
        status = ERROR;
        goto free;
    }

    // Calculate the bounds of the data
    calc_bounds(data, bounds);

    // Generate the initial population
    printf(CYAN "Generating initial population...\n" RESET);
    for (int i = 0; i < (int)size; ++i)
    {
        random_centroids(population[i], bounds, &rng);
    }

    // Perform the Genetic Algorithm
    for (int iter = 0; iter < max_iter; ++iter)
    {
        // Compute the fitness of each chromosome
        for (int i = 0; i < (int)size; ++i)
        {
            lloyd_defined(trials, population[i], data, n_clusters, clusters[i]);
            fitness[i] = dunn_index(population[i], n_clusters, clusters[i]);
            if (VERBOSE == 1)
                printf(CYAN "chromsome[%d], fitness: %10.6f\n" RESET, i, fitness[i]);
        }

        // Generate the probabilities for roulette wheel selection
        gen_probability(size, fitness, probability);

        // Save the results if there is a new best solution
        save_results(fitness_file, centroids_file, cluster_file, size, fitness, 
                     population, n_clusters, clusters);

        // Perform roulette wheel selection and GA operators
        if (VERBOSE == 1)
            printf(CYAN "Executing roulette wheel selection...\n" RESET);

        // Select parents from the population and perform genetic operators
        for (int i = 0; i < size; i += 2)
        {
            // Select parents
            for (int j = 0, idx = 0; j < 2; ++j)
            {
                idx = select_parent(size, probability, &rng);
                if (VERBOSE == 1)
                    printf(CYAN "Parent %d selected as chromsome %d from population\n" RESET, j, idx);

                if (j == 0)
                    gsl_matrix_memcpy(parent1, population[idx]);
                else
                    gsl_matrix_memcpy(parent2, population[idx]);
            }

            // Perform crossover and mutation with specified probabilities
            if (VERBOSE == 1)
                printf(CYAN "Performing crossover...\n" RESET);
            if (pcg32_random_r(&rng) / (double)UINT32_MAX <= c_rate)
            {
                crossover(parent1, parent2, &rng);
            }

            if (VERBOSE == 1)
                printf(CYAN "Performing background mutation...\n" RESET);
            for (int j = 0; j < 2; ++j)
            {
                if (pcg32_random_r(&rng) / (double)UINT32_MAX <= m_rate)
                {
                    if (j == 0)
                        mutate(parent1, bounds, &rng);
                    else
                        mutate(parent2, bounds, &rng);
                }
            }

            // Copy each parent to the new population
            if (VERBOSE == 1)
                printf(CYAN "Copying parents to new population...\n" RESET);
            gsl_matrix_memcpy(new_population[i], parent1);
            gsl_matrix_memcpy(new_population[i+1], parent2);
        }

        // Copy the new population to the next population
        if (VERBOSE == 1)
            printf(CYAN "Copying current population as new population\n" RESET);

        for (int i = 0; i < size; ++i)
        {
            gsl_matrix_memcpy(population[i], new_population[i]);
        }

        // Check if stop signal, terminate if present
        if (access("./stop", F_OK) != -1)
        {
            printf(YELLOW "Stop signal received, shutting down!\n" RESET);
            remove("./stop");
            break;
        }

    }
    printf(GREEN "Finished executing E-means, shutting down!\n" RESET);

free:
    for (int i = 0; i < (int)size; ++i)
    {
        for (int j = 0; j < n_clusters; ++j)
        {
            gsl_matrix_free(clusters[i][j]);
        }
        free(clusters[i]);
    }
    free(clusters);
    for (int i = 0; i < (int)size; ++i)
    {
        gsl_matrix_free(population[i]);
        gsl_matrix_free(new_population[i]);
    }
    free(population);
    free(new_population);
    gsl_matrix_free(data);
    gsl_matrix_free(bounds);
    return status;
}