Search is not available for this dataset
text
string
meta
dict
#include <stdio.h> #include <stdarg.h> #include <string.h> #include <math.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <gbpLib.h> #include <gbpRNG.h> #include <gbpMCMC.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_fit.h> #include <gsl/gsl_interp.h> void compute_MCMC(MCMC_info *MCMC) { char filename_output_dir[SID_MAX_FILENAME_LENGTH]; char filename_chain_dir[SID_MAX_FILENAME_LENGTH]; char filename_results_dir[SID_MAX_FILENAME_LENGTH]; char filename_plots_dir[SID_MAX_FILENAME_LENGTH]; char filename_run[SID_MAX_FILENAME_LENGTH]; char filename_chain[SID_MAX_FILENAME_LENGTH]; char filename_chain_config[SID_MAX_FILENAME_LENGTH]; char filename_chain_covariance[SID_MAX_FILENAME_LENGTH]; char filename_stats[SID_MAX_FILENAME_LENGTH]; char filename_coverage[SID_MAX_FILENAME_LENGTH]; char filename_histograms[SID_MAX_FILENAME_LENGTH]; char filename_results[SID_MAX_FILENAME_LENGTH]; char filename_stop[SID_MAX_FILENAME_LENGTH]; char column_txt[SID_MAX_FILENAME_LENGTH]; char problem_name_test[MCMC_NAME_SIZE]; char P_name_test[MCMC_NAME_SIZE]; char format_string[64]; char name_test[MCMC_NAME_SIZE]; char array_name_test[MCMC_NAME_SIZE]; int n_avg_test; int flag_autocor_on_test; int n_P_test; int n_DS_test; int n_arrays_test; int n_M_test; double P_init_test; double M_target_test; double dM_target_test; double array_test; double P_min_test; double P_max_test; double ln_Pr_min; double ln_Pr_max; double ln_Pr_avg; int i_tune; int i_P, j_P, k_P; int i_M, j_M; int ii_P, jj_P; int i_avg; int i_C; int i_DS, n_DS; int i_iteration, j_iteration; int flag_continue; char flag_success; int flag_stop = GBP_FALSE; int i_coverage; int j_coverage; int bin_x; int bin_y; int n_avg; int n_avg_burn; int n_avg_integrate; int n_P, n_C; int n_gals; double * x_P; double ** x_M; double * M_target; double * dM_target; double * P_min; double * P_max; double * P_new; double * P_last; double * P_init; double * P_chain; double * P_avg; double * dP_avg; double ** M_best; double ** M_min; double ** M_max; double ** M_new; double ** M_lo_68; double ** M_hi_68; double ** M_lo_95; double ** M_hi_95; size_t *** M_histogram; double ** M_last; double ** M_avg; double ** dM_avg; double * slopes; double * dP_sub; double * ln_Pr_chain; double * ln_Pr_proposals; double * drift; double ** auto_cor; double ** P_chain_stats; double ** P_prop_stats; size_t ** P_histogram; size_t ** coverage_true; size_t ** coverage_false; size_t ** coverage_keep; double * V_read; double L_x, L_y, L_z; int n_x, n_y, n_z; int n_C_x; FILE * fp_run; FILE * fp_chain; FILE * fp_chain_config; FILE * fp_chain_covariance; FILE * fp_stats; FILE * fp_coverage; FILE * fp_histograms; FILE * fp_results; FILE * fp_stop; int seed = 182743; int i_report; time_t time_start, time_stop; double time_diff; int i_iteration_start; int i_iteration_next_report; int n_accepted; int n_active; int n_iterations; int n_iterations_burn; int n_iterations_integrate; int n_iterations_phase; int n_thin; int n_thin_burn; int n_thin_integrate; int i_thin; int n_chains_test; int flag_autocor_on; int n_coverage; int coverage_size; int i_phase; int i_array; int * n_M; int flag_initialized; int flag_no_map_write; int flag_no_map_write_test; int n_used; double RN; double *** P_arrays; int * n_P_arrays; double constant; size_t * histogram_index; size_t * coverage_keep_index; size_t P_best_index; size_t M_best_index; double accumulator; size_t P_lo_68_index; size_t P_hi_68_index; size_t P_lo_95_index; size_t P_hi_95_index; size_t M_lo_68_index; size_t M_hi_68_index; size_t M_lo_95_index; size_t M_hi_95_index; double * P_lo_68; double * P_hi_68; double * P_lo_95; double * P_hi_95; double * P_contour_68; double * P_contour_95; double * P_best; int my_chain; int flag_init; int i_column; int dummy_t; int n_iterations_file_total; int n_iterations_file_burn; int flag_restart = GBP_FALSE; int flag_minimize_IO = GBP_FALSE; MCMC_DS_info *current_DS; MCMC_DS_info *next_DS; size_t i_iteration_buffer; size_t i_P_buffer; size_t i_M_buffer; SID_log("Performing MCMC...", SID_LOG_OPEN | SID_LOG_TIMER); SID_log("Initializing...", SID_LOG_OPEN); // Initialize the covariance matrix set_MCMC_covariance(MCMC, NULL); // First call with NULL must be after P_init is set! // Initialize arrays init_MCMC_arrays(MCMC); // Grab some stuff from the MCMC structure n_P = MCMC->n_P; n_DS = MCMC->n_DS; n_avg = MCMC->n_avg; n_thin = MCMC->n_thin; coverage_size = MCMC->coverage_size; flag_autocor_on = MCMC->flag_autocor_on; my_chain = MCMC->my_chain; n_iterations = MCMC->n_iterations; n_iterations_burn = MCMC->n_iterations_burn; n_iterations_integrate = n_iterations - n_iterations_burn; flag_no_map_write = SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_NO_MAP_WRITE); flag_minimize_IO = SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_MINIMIZE_IO); SID_log("temperature = %lf", SID_LOG_COMMENT, MCMC->temperature); SID_log("n_avg = %d", SID_LOG_COMMENT, n_avg); SID_log("n_thin = %d", SID_LOG_COMMENT, n_thin); SID_log("coverage_size = %d", SID_LOG_COMMENT, coverage_size); SID_log("n_iterations = %d", SID_LOG_COMMENT, n_iterations); SID_log("n_iterations_burn = %d", SID_LOG_COMMENT, n_iterations_burn); SID_log("n_iterations_integrate = %d", SID_LOG_COMMENT, n_iterations_integrate); // Initialize random number generator SID_log("random seed = %d", SID_LOG_COMMENT, MCMC->seed); if(MCMC->V != NULL) SID_log("Covariance matrix is initialized.", SID_LOG_COMMENT); else SID_log("Covariance matrix is NOT initialized.", SID_LOG_COMMENT); if(flag_autocor_on) SID_log("Auto-correlation is on.", SID_LOG_COMMENT); else SID_log("Auto-correlation is off.", SID_LOG_COMMENT); if(flag_minimize_IO) SID_log("Minimize I/O is on.", SID_LOG_COMMENT); else SID_log("Minimize I/O is off.", SID_LOG_COMMENT); // Initialize chain arrays n_M = MCMC->n_M; M_new = MCMC->M_new; M_last = MCMC->M_last; P_new = MCMC->P_new; P_last = MCMC->P_last; P_init = MCMC->P_init; P_chain = MCMC->P_chain; P_min = (double *)SID_malloc(sizeof(double) * n_P); P_max = (double *)SID_malloc(sizeof(double) * n_P); P_avg = (double *)SID_malloc(sizeof(double) * n_P); dP_avg = (double *)SID_malloc(sizeof(double) * n_P); ln_Pr_chain = (double *)SID_malloc(sizeof(double) * n_avg); ln_Pr_proposals = (double *)SID_malloc(sizeof(double) * n_avg); drift = (double *)SID_malloc(sizeof(double) * n_P); slopes = (double *)SID_malloc(sizeof(double) * n_P); dP_sub = (double *)SID_malloc(sizeof(double) * n_P); P_chain_stats = (double **)SID_malloc(sizeof(double *) * n_P); P_prop_stats = (double **)SID_malloc(sizeof(double *) * n_P); if(flag_autocor_on) auto_cor = (double **)SID_malloc(sizeof(double *) * n_P); else auto_cor = NULL; for(i_P = 0; i_P < n_P; i_P++) { drift[i_P] = 0.; slopes[i_P] = 0.; dP_sub[i_P] = 0.; P_chain_stats[i_P] = (double *)SID_malloc(sizeof(double) * n_avg); P_prop_stats[i_P] = (double *)SID_malloc(sizeof(double) * n_avg); if(flag_autocor_on) auto_cor[i_P] = (double *)SID_malloc(sizeof(double) * n_avg); } // Set directories sprintf(filename_output_dir, "%s/", MCMC->filename_output_dir); sprintf(filename_chain_dir, "%s/chains/", filename_output_dir); sprintf(filename_results_dir, "%s/results/", filename_output_dir); sprintf(filename_plots_dir, "%s/plots/", filename_output_dir); // Set filenames sprintf(filename_run, "%s/run.dat", filename_output_dir); sprintf(filename_chain, "%s/chain_trace_%06d.dat", filename_chain_dir, my_chain); sprintf(filename_chain_config, "%s/chain_config_%06d.dat", filename_chain_dir, my_chain); sprintf(filename_chain_covariance, "%s/chain_covariance_%06d.dat", filename_chain_dir, my_chain); sprintf(filename_stats, "%s/chain_stats_%06d.dat", filename_chain_dir, my_chain); sprintf(filename_coverage, "%s/coverage.dat", filename_results_dir); sprintf(filename_histograms, "%s/histograms.dat", filename_results_dir); sprintf(filename_stop, "%s/stop", filename_output_dir); SID_log("Done.", SID_LOG_CLOSE); // Perform integration SID_log("Initializing integration...", SID_LOG_OPEN); MCMC->flag_integrate_on = GBP_TRUE; // Make sure the needed directories exist mkdir(filename_output_dir, 02755); mkdir(filename_chain_dir, 02755); mkdir(filename_results_dir, 02755); mkdir(filename_plots_dir, 02755); // Read/Write Header file if(SID.I_am_Master) { // If run.dat already exists, this is a restart. Check that it is consistant with the current run. if((fp_run = fopen(filename_run, "rb")) != NULL) { flag_restart = GBP_TRUE; SID_log("Checking the consistancy of this run with the previous run...", SID_LOG_OPEN); SID_fread_verify(problem_name_test, sizeof(char), MCMC_NAME_SIZE, fp_run); if(strcmp(problem_name_test, MCMC->problem_name)) SID_exit_error("Problem names are inconsistant (i.e. {%s}!={%s}).", SID_ERROR_LOGIC, MCMC->problem_name, problem_name_test); SID_fread_verify(&n_chains_test, sizeof(int), 1, fp_run); MCMC->n_chains = GBP_MAX(MCMC->n_chains, n_chains_test); SID_fread_verify(&n_avg_test, sizeof(int), 1, fp_run); if(n_avg_test != n_avg) SID_exit_error("Integration averaging intervals are inconsistant (i.e. %d!=%d).", SID_ERROR_LOGIC, n_avg, n_avg_test); SID_fread_verify(&flag_autocor_on_test, sizeof(int), 1, fp_run); if(flag_autocor_on_test != flag_autocor_on) SID_exit_error("Autocorrelation flags are inconsistant (i.e. %d!=%d).", SID_ERROR_LOGIC, flag_autocor_on, flag_autocor_on_test); SID_fread_verify(&flag_no_map_write_test, sizeof(int), 1, fp_run); if(flag_no_map_write_test != flag_no_map_write) SID_exit_error("Map write flags are inconsistant (i.e. %d!=%d).", SID_ERROR_LOGIC, flag_no_map_write, flag_no_map_write_test); SID_fread_verify(&n_P_test, sizeof(int), 1, fp_run); if(n_P_test != n_P) SID_exit_error("The number of paramaters is inconsistant (i.e. %d!=%d).", SID_ERROR_LOGIC, n_P, n_P_test); MCMC->P_name_length = 0; for(i_P = 0; i_P < n_P; i_P++) { SID_fread_verify(P_name_test, sizeof(char), MCMC_NAME_SIZE, fp_run); if(strcmp(P_name_test, MCMC->P_names[i_P])) SID_exit_error("Parameter #%d's names are inconsistant (i.e. {%s}!={%s}).", SID_ERROR_LOGIC, i_P, MCMC->P_names[i_P], P_name_test); SID_fread_verify(&P_init_test, sizeof(double), 1, fp_run); // if(P_init_test!=MCMC->P_init[i_P]) // SID_exit_error("Parameter #%d's initial values are inconsistant (i.e. // %le!=%le).",SID_ERROR_LOGIC,i_P,MCMC->P_init[i_P],P_init_test); SID_fread_verify(&P_min_test, sizeof(double), 1, fp_run); if(P_min_test != MCMC->P_limit_min[i_P]) SID_exit_error("Parameter #%d's minimum values are inconsistant (i.e. %le!=%le).", SID_ERROR_LOGIC, i_P, MCMC->P_limit_min[i_P], P_min_test); SID_fread_verify(&P_max_test, sizeof(double), 1, fp_run); if(P_max_test != MCMC->P_limit_max[i_P]) SID_exit_error("Parameter #%d's maximum values are inconsistant (i.e. %le!=%le).", SID_ERROR_LOGIC, i_P, MCMC->P_limit_max[i_P], P_max_test); MCMC->P_name_length = GBP_MAX((size_t)(MCMC->P_name_length), strlen(MCMC->P_names[i_P])); } sprintf(MCMC->P_name_format, "%%-%ds", MCMC->P_name_length); SID_fread_verify(&n_arrays_test, sizeof(int), 1, fp_run); if(n_arrays_test != MCMC->n_arrays) SID_exit_error("Numbers of project arrays are inconsistant (i.e. %d!=%d).", SID_ERROR_LOGIC, MCMC->n_arrays, n_arrays_test); for(i_array = 0; i_array < MCMC->n_arrays; i_array++) { SID_fread_verify(&array_name_test, sizeof(char), MCMC_NAME_SIZE, fp_run); if(strcmp(array_name_test, MCMC->array_name[i_array])) SID_exit_error("Project array names are inconsisitant (i.e. {%s}!={%s}).", SID_ERROR_LOGIC, MCMC->array_name[i_array], array_name_test); for(i_P = 0; i_P < n_P; i_P++) { SID_fread_verify(&array_test, sizeof(double), 1, fp_run); if(array_test != MCMC->array[i_array][i_P]) SID_exit_error("Project array #%d element #%d is inconsistant (i.e. %le!=%le).", SID_ERROR_LOGIC, i_array, i_P, MCMC->array[i_array][i_P], array_test); } } SID_fread_verify(&n_DS_test, sizeof(int), 1, fp_run); if(n_DS_test != n_DS) SID_exit_error("The number of datasets is inconsistant (i.e. %d!=%d).", SID_ERROR_LOGIC, n_DS, n_DS_test); current_DS = MCMC->DS; i_DS = 0; while(current_DS != NULL) { next_DS = current_DS->next; SID_fread_verify(name_test, sizeof(char), MCMC_NAME_SIZE, fp_run); if(strcmp(name_test, current_DS->name)) SID_exit_error("Dataset #%d's names are inconsistant (i.e. {%s}!={%s}).", SID_ERROR_LOGIC, i_DS, current_DS->name, name_test); SID_fread_verify(&n_M_test, sizeof(int), 1, fp_run); if(n_M_test != n_M[i_DS]) SID_exit_error("The sizes of dataset #%d are inconsistant (i.e. %d!=%d).", SID_ERROR_LOGIC, i_DS, n_M_test, n_M[i_DS]); for(i_M = 0; i_M < current_DS->n_M; i_M++) { SID_fread_verify(&M_target_test, sizeof(double), 1, fp_run); if(M_target_test != current_DS->M_target[i_M]) SID_exit_error("Dataset #%d, element #%d is inconsistant (i.e. %le!=%le).", SID_ERROR_LOGIC, i_DS, i_M, current_DS->M_target[i_M], M_target_test); } for(i_M = 0; i_M < current_DS->n_M; i_M++) { SID_fread_verify(&dM_target_test, sizeof(double), 1, fp_run); if(dM_target_test != current_DS->dM_target[i_M]) SID_exit_error("Dataset #%d, uncertainty element #%d is inconsistant (i.e. %le!=%le).", SID_ERROR_LOGIC, i_DS, i_M, current_DS->M_target[i_M], M_target_test); } SID_fread_verify(&n_arrays_test, sizeof(int), 1, fp_run); if(n_arrays_test != current_DS->n_arrays) SID_exit_error("The number of arrays in dataset #%d is inconsistant (i.e. %d!=%d).", SID_ERROR_LOGIC, i_DS, n_arrays_test, current_DS->n_arrays); for(i_array = 0; i_array < current_DS->n_arrays; i_array++) { SID_fread_verify(array_name_test, sizeof(char), MCMC_NAME_SIZE, fp_run); if(strcmp(array_name_test, current_DS->array_name[i_array])) SID_exit_error("Array name #%d for dataset #%d is inconsisitant (i.e. {%s}!={%s}).", SID_ERROR_LOGIC, i_array, i_DS, current_DS->array_name[i_array], array_name_test); for(i_M = 0; i_M < current_DS->n_M; i_M++) { SID_fread_verify(&array_test, sizeof(double), 1, fp_run); if(array_test != current_DS->array[i_array][i_M]) SID_exit_error("Array #%d, element #%d for dataset #%d is inconsistant (i.e. %le!=%le).", SID_ERROR_LOGIC, i_array, i_M, i_DS, current_DS->array[i_array][i_M], array_test); } } current_DS = next_DS; i_DS++; } fclose(fp_run); SID_log("Done.", SID_LOG_CLOSE); } // ... else if run.dat does not exist, create it else { SID_log("Write header file...", SID_LOG_OPEN); if((fp_run = fopen(filename_run, "wb")) == NULL) SID_exit_error("Could not open file for writing {%s}.", SID_ERROR_IO_OPEN, filename_run); // Stuff relating to this MCMC project fwrite(MCMC->problem_name, sizeof(char), MCMC_NAME_SIZE, fp_run); fwrite(&(MCMC->n_chains), sizeof(int), 1, fp_run); fwrite(&n_avg, sizeof(int), 1, fp_run); fwrite(&flag_autocor_on, sizeof(int), 1, fp_run); fwrite(&flag_no_map_write, sizeof(int), 1, fp_run); fwrite(&n_P, sizeof(int), 1, fp_run); for(i_P = 0; i_P < n_P; i_P++) { fwrite(MCMC->P_names[i_P], sizeof(char), MCMC_NAME_SIZE, fp_run); fwrite(&(MCMC->P_init[i_P]), sizeof(double), 1, fp_run); fwrite(&(MCMC->P_limit_min[i_P]), sizeof(double), 1, fp_run); fwrite(&(MCMC->P_limit_max[i_P]), sizeof(double), 1, fp_run); } fwrite(&(MCMC->n_arrays), sizeof(int), 1, fp_run); for(i_array = 0; i_array < MCMC->n_arrays; i_array++) { fwrite(MCMC->array_name[i_array], sizeof(char), MCMC_NAME_SIZE, fp_run); fwrite(MCMC->array[i_array], sizeof(double), n_P, fp_run); } // Stuff relating to the constraining datasets fwrite(&n_DS, sizeof(int), 1, fp_run); current_DS = MCMC->DS; while(current_DS != NULL) { next_DS = current_DS->next; fwrite(current_DS->name, sizeof(char), MCMC_NAME_SIZE, fp_run); fwrite(&(current_DS->n_M), sizeof(int), 1, fp_run); fwrite(current_DS->M_target, sizeof(double), current_DS->n_M, fp_run); fwrite(current_DS->dM_target, sizeof(double), current_DS->n_M, fp_run); fwrite(&(current_DS->n_arrays), sizeof(int), 1, fp_run); for(i_array = 0; i_array < current_DS->n_arrays; i_array++) { fwrite(current_DS->array_name[i_array], sizeof(char), MCMC_NAME_SIZE, fp_run); fwrite(current_DS->array[i_array], sizeof(double), current_DS->n_M, fp_run); } current_DS = next_DS; } fclose(fp_run); SID_log("Done.", SID_LOG_CLOSE); } } SID_Bcast(&flag_restart, 1, SID_INT, SID_MASTER_RANK, MCMC->comm); SID_Bcast(&(MCMC->n_chains), 1, SID_INT, SID_MASTER_RANK, MCMC->comm); SID_Bcast(&(MCMC->P_name_length), 1, SID_INT, SID_MASTER_RANK, MCMC->comm); sprintf(MCMC->P_name_format, "%%-%ds", MCMC->P_name_length); // If this is NOT a restart, start from scratch ... n_iterations_file_total = 0; n_iterations_file_burn = 0; if(!flag_restart) { SID_log("Initializing state...", SID_LOG_OPEN); // Report the starting conditions if(my_chain == SID.My_rank) { SID_log("Initial parameters & priors:", SID_LOG_ALLRANKS | SID_LOG_OPEN); sprintf(format_string, "%s = %%13.6le (%%13.6le ->%%13.6le)", MCMC->P_name_format); for(i_P = 0; i_P < n_P; i_P++) SID_log(format_string, SID_LOG_ALLRANKS | SID_LOG_COMMENT, MCMC->P_names[i_P], P_last[i_P], MCMC->P_limit_min[i_P], MCMC->P_limit_max[i_P]); SID_log("", SID_LOG_ALLRANKS | SID_LOG_NOPRINT | SID_LOG_CLOSE); } // Perform autotuning (if requested) if(SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_AUTOTUNE)) autotune_MCMC(MCMC); MCMC->flag_init_chain = GBP_TRUE; // Set the initial state SID_log("Writing chain config file...", SID_LOG_OPEN); if((fp_chain = fopen(filename_chain, "wb")) == NULL) SID_exit_error("Could not open file for writing {%s}.", SID_ERROR_IO_OPEN, filename_chain); if((fp_stats = fopen(filename_stats, "wb")) == NULL) SID_exit_error("Could not open file for writing {%s}.", SID_ERROR_IO_OPEN, filename_stats); if((fp_chain_config = fopen(filename_chain_config, "wb")) == NULL) SID_exit_error("Could not open file for writing {%s}.", SID_ERROR_IO_OPEN, filename_chain_config); fwrite(&n_iterations_file_total, sizeof(int), 1, fp_chain_config); fwrite(&n_iterations_file_burn, sizeof(int), 1, fp_chain_config); fwrite(&(MCMC->temperature), sizeof(double), 1, fp_chain_config); fwrite(MCMC->V, sizeof(double), n_P * n_P, fp_chain_config); fclose(fp_chain_config); SID_log("Done.", SID_LOG_CLOSE); SID_log("Done.", SID_LOG_CLOSE); } // ... else read the state we left-off from ... else if(my_chain == SID.My_rank) { SID_log("Loading previous state...", SID_LOG_OPEN); MCMC->flag_init_chain = GBP_FALSE; // ... fetch the number of intervals that have already been computed ... n_iterations_file_total = 0; if((fp_chain_config = fopen(filename_chain_config, "rb")) != NULL) { SID_log("Reading the existant number of iterations...", SID_LOG_OPEN); V_read = (double *)SID_malloc(sizeof(double) * n_P * n_P); SID_fread_verify(&n_iterations_file_total, sizeof(int), 1, fp_chain_config); SID_fread_verify(&n_iterations_file_burn, sizeof(int), 1, fp_chain_config); SID_fread_verify(&(MCMC->temperature), sizeof(double), 1, fp_chain_config); SID_fread_verify(V_read, sizeof(double), n_P * n_P, fp_chain_config); set_MCMC_covariance(MCMC, V_read); SID_free(SID_FARG V_read); SID_log("# burn iterations = %d (%d requested)", SID_LOG_COMMENT, n_iterations_file_burn, n_iterations_burn); SID_log("# total iterations = %d (%d requested)", SID_LOG_COMMENT, n_iterations_file_total, n_iterations); SID_log("Temperature = %le", SID_LOG_COMMENT, MCMC->temperature); fclose(fp_chain_config); SID_log("Done.", SID_LOG_CLOSE); } // ... scan to the end of the chain and read the last-used parameter set if(n_iterations_file_total > 0) { SID_log("Reading the last-used parameter set...", SID_LOG_OPEN); fp_chain = fopen(filename_chain, "rb"); for(i_iteration = 0; i_iteration < n_iterations_file_total; i_iteration++) { for(i_avg = 0; i_avg < n_avg; i_avg++) { SID_fread_verify(&flag_success, sizeof(char), 1, fp_chain); if((i_iteration + i_avg) != 0) { MCMC->ln_likelihood_last = MCMC->ln_likelihood_new; memcpy(P_last, P_new, n_P * sizeof(double)); if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) memcpy(M_last[i_DS], M_new[i_DS], n_M[i_DS] * sizeof(double)); } } SID_fread_verify(&(MCMC->ln_likelihood_new), sizeof(double), 1, fp_chain); SID_fread_verify(P_new, sizeof(double), n_P, fp_chain); if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) SID_fread_verify(M_new[i_DS], sizeof(double), n_M[i_DS], fp_chain); } if((i_iteration + i_avg) == 0) { MCMC->ln_likelihood_chain = MCMC->ln_likelihood_new; MCMC->ln_likelihood_last = MCMC->ln_likelihood_new; } if(flag_success) { MCMC->ln_likelihood_chain = MCMC->ln_likelihood_new; memcpy(P_chain, P_new, n_P * sizeof(double)); } } } fclose(fp_chain); fp_chain = fopen(filename_chain, "ab"); SID_log("Done.", SID_LOG_CLOSE); // ... scan to the end of the chain stats and read the last-generated statistics (particularly the drift) SID_log("Reading the last-generated statistics...", SID_LOG_OPEN); fp_stats = fopen(filename_stats, "rb"); for(i_iteration = 0; i_iteration < n_iterations_file_total; i_iteration++) { SID_fread_verify(P_min, sizeof(double), n_P, fp_stats); // Read proposal stats SID_fread_verify(P_avg, sizeof(double), n_P, fp_stats); SID_fread_verify(P_max, sizeof(double), n_P, fp_stats); SID_fread_verify(dP_avg, sizeof(double), n_P, fp_stats); SID_fread_verify(dP_sub, sizeof(double), n_P, fp_stats); SID_fread_verify(&ln_Pr_min, sizeof(double), 1, fp_stats); SID_fread_verify(&ln_Pr_avg, sizeof(double), 1, fp_stats); SID_fread_verify(&ln_Pr_max, sizeof(double), 1, fp_stats); if(flag_autocor_on) SID_fread_verify(auto_cor, sizeof(double), n_avg - 1, fp_stats); SID_fread_verify(P_min, sizeof(double), n_P, fp_stats); // Read chain stats SID_fread_verify(P_avg, sizeof(double), n_P, fp_stats); SID_fread_verify(P_max, sizeof(double), n_P, fp_stats); SID_fread_verify(dP_avg, sizeof(double), n_P, fp_stats); SID_fread_verify(dP_sub, sizeof(double), n_P, fp_stats); SID_fread_verify(&ln_Pr_min, sizeof(double), 1, fp_stats); SID_fread_verify(&ln_Pr_avg, sizeof(double), 1, fp_stats); SID_fread_verify(&ln_Pr_max, sizeof(double), 1, fp_stats); if(flag_autocor_on) SID_fread_verify(auto_cor, sizeof(double), n_avg - 1, fp_stats); SID_fread_verify(slopes, sizeof(double), n_P, fp_stats); SID_fread_verify(drift, sizeof(double), n_P, fp_stats); } fclose(fp_stats); fp_stats = fopen(filename_stats, "ab"); SID_log("Done.", SID_LOG_CLOSE); } else { memcpy(P_last, P_init, n_P * sizeof(double)); MCMC->flag_init_chain = GBP_TRUE; fp_chain = fopen(filename_chain, "wb"); fp_stats = fopen(filename_stats, "wb"); } // Report the starting conditions if(my_chain == SID.My_rank) { SID_log("Resume from parameters:", SID_LOG_ALLRANKS | SID_LOG_OPEN); sprintf(format_string, "%s = %%13.6le", MCMC->P_name_format); for(i_P = 0; i_P < n_P; i_P++) SID_log(format_string, SID_LOG_ALLRANKS | SID_LOG_COMMENT, MCMC->P_names[i_P], P_last[i_P]); SID_log("", SID_LOG_ALLRANKS | SID_LOG_NOPRINT | SID_LOG_CLOSE); } SID_log("Done.", SID_LOG_CLOSE); } // End of restart stuff SID_Bcast(&n_iterations_file_total, 1, SID_INT, my_chain, MCMC->comm); SID_Bcast(&n_iterations_file_burn, 1, SID_INT, my_chain, MCMC->comm); SID_Bcast(&n_iterations, 1, SID_INT, my_chain, MCMC->comm); SID_Bcast(&(MCMC->flag_init_chain), 1, SID_INT, my_chain, MCMC->comm); SID_Bcast(&(MCMC->ln_likelihood_chain), 1, SID_DOUBLE, my_chain, MCMC->comm); SID_Bcast(&(MCMC->ln_likelihood_new), 1, SID_DOUBLE, my_chain, MCMC->comm); // Remove the existant iterations from the totals we need to perform still if(n_iterations_file_total < n_iterations_burn) { i_phase = 0; i_iteration = n_iterations_file_total; } else if(n_iterations_file_total < n_iterations) { i_phase = 1; i_iteration = n_iterations_file_total - n_iterations_burn; } else { i_phase = 2; // ... in other words, we're done; skip the integration. i_iteration = n_iterations; } i_iteration_start = i_iteration; // This is the end of the initialization SID_log("Done.", SID_LOG_CLOSE); // Create the chain in 2 phases: a burn-in phase and an integration phase SID_log("Performing integration...", SID_LOG_OPEN | SID_LOG_TIMER); i_iteration_buffer = 0; i_P_buffer = 0; i_M_buffer = 0; for(; i_phase < 2; i_phase++) { switch(i_phase) { case 0: SID_log("Performing burn-in phase...", SID_LOG_OPEN | SID_LOG_TIMER); n_iterations_phase = n_iterations_burn; break; case 1: SID_log("Performing integration phase...", SID_LOG_OPEN | SID_LOG_TIMER); n_iterations_phase = n_iterations - n_iterations_burn; break; } // Initialize progress reporting int n_report = 10; // This is the number of progress reports that will be creates. eg. 10 -> every 10% i_report = 0; if(n_iterations_phase > 20) i_iteration_next_report = i_iteration_start + (n_iterations_phase - i_iteration_start) / n_report; else i_iteration_next_report = 20; // Loop until this phase (burn or integrate) is done flag_continue = GBP_TRUE; while(flag_continue) { // Process one averaging interval at a time // Start timer time(&time_start); for(i_avg = 0, i_thin = 1; i_avg < n_avg; i_thin++) { // Generate new proposal and determine it's chi^2 flag_success = generate_MCMC_chain(MCMC); // If this rank is processing chain information ... if(my_chain == SID.My_rank) { // ... and this proposal is kept by the thining then ... if(i_thin == n_thin) { // ... reformat parameter arrays for statistics generation for(i_P = 0; i_P < n_P; i_P++) { P_chain_stats[i_P][i_avg % n_avg] = P_chain[i_P]; P_prop_stats[i_P][i_avg % n_avg] = P_new[i_P]; } ln_Pr_chain[i_avg % n_avg] = MCMC->ln_Pr_chain; ln_Pr_proposals[i_avg % n_avg] = MCMC->ln_Pr_new; // ... and write to the chain file switch(flag_minimize_IO) { case GBP_TRUE: MCMC->flag_success_buffer[i_iteration_buffer] = flag_success; MCMC->ln_likelihood_new_buffer[i_iteration_buffer] = MCMC->ln_likelihood_new; i_iteration_buffer++; memcpy(&(MCMC->P_new_buffer[i_P_buffer]), P_new, (size_t)n_P * sizeof(double)); i_P_buffer += n_P; if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) { memcpy(&(MCMC->M_new_buffer[i_M_buffer]), M_new[i_DS], (size_t)n_M[i_DS] * sizeof(double)); i_M_buffer += n_M[i_DS]; } } break; default: fwrite(&flag_success, sizeof(char), 1, fp_chain); fwrite(&(MCMC->ln_likelihood_new), sizeof(double), 1, fp_chain); fwrite(P_new, sizeof(double), n_P, fp_chain); if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) fwrite(M_new[i_DS], sizeof(double), n_M[i_DS], fp_chain); } break; } } } // Change counters at the end of a thining interval if(i_thin == n_thin) { i_thin = 0; i_avg++; } } // End of averaging interval loop if(i_phase == 0) n_iterations_file_burn++; n_iterations_file_total++; i_iteration++; // Stop timer time(&time_stop); time_diff = difftime(time_stop, time_start); // Generate statistics for the averaging interval we just completed if(my_chain == SID.My_rank) { // Write the statistics to the chain stats file compute_MCMC_chain_stats(P_prop_stats, n_P, n_avg, P_min, P_avg, P_max, dP_avg, auto_cor, slopes, dP_sub, ln_Pr_proposals, &ln_Pr_min, &ln_Pr_avg, &ln_Pr_max); fwrite(P_min, sizeof(double), n_P, fp_stats); fwrite(P_avg, sizeof(double), n_P, fp_stats); fwrite(P_max, sizeof(double), n_P, fp_stats); fwrite(dP_avg, sizeof(double), n_P, fp_stats); fwrite(dP_sub, sizeof(double), n_P, fp_stats); fwrite(&ln_Pr_min, sizeof(double), 1, fp_stats); fwrite(&ln_Pr_avg, sizeof(double), 1, fp_stats); fwrite(&ln_Pr_max, sizeof(double), 1, fp_stats); if(flag_autocor_on) fwrite(auto_cor, sizeof(double), n_avg - 1, fp_stats); compute_MCMC_chain_stats(P_chain_stats, n_P, n_avg, P_min, P_avg, P_max, dP_avg, auto_cor, slopes, dP_sub, ln_Pr_chain, &ln_Pr_min, &ln_Pr_avg, &ln_Pr_max); fwrite(P_min, sizeof(double), n_P, fp_stats); fwrite(P_avg, sizeof(double), n_P, fp_stats); fwrite(P_max, sizeof(double), n_P, fp_stats); fwrite(dP_avg, sizeof(double), n_P, fp_stats); fwrite(dP_sub, sizeof(double), n_P, fp_stats); fwrite(&ln_Pr_min, sizeof(double), 1, fp_stats); fwrite(&ln_Pr_avg, sizeof(double), 1, fp_stats); fwrite(&ln_Pr_max, sizeof(double), 1, fp_stats); if(flag_autocor_on) fwrite(auto_cor, sizeof(double), n_avg - 1, fp_stats); for(i_P = 0; i_P < n_P; i_P++) drift[i_P] += slopes[i_P]; fwrite(slopes, sizeof(double), n_P, fp_stats); fwrite(drift, sizeof(double), n_P, fp_stats); } // Report progress if(i_iteration == i_iteration_next_report) { i_report++; SID_log("%3d%% complete.", SID_LOG_COMMENT | SID_LOG_TIMER, (100 / n_report) * (i_report)); time_diff /= (double)(n_avg); if(time_diff > 0.1) SID_log("\tMean time for single model call: %.1f", SID_LOG_COMMENT, time_diff); i_iteration_next_report = GBP_MIN(n_iterations_phase, i_iteration_start + (n_iterations_phase - i_iteration_start) * (i_report + 1) / n_report); } // Check to see if a stop has been called to the run ... if(SID.I_am_Master) { if((fp_stop = fopen(filename_stop, "r")) != NULL) { fclose(fp_stop); // remove(filename_stop); flag_stop = GBP_TRUE; } } SID_Bcast(&flag_stop, 1, SID_INT, SID_MASTER_RANK, MCMC->comm); // ... if so, stop all ranks and cancel the subsequent analysis stage if(flag_stop) { flag_continue = GBP_FALSE; MCMC->flag_analysis_on = GBP_FALSE; i_phase = 3; SID_log("*** Stop file found. Terminating run. ***", SID_LOG_COMMENT); } // Check to see if this phase's iterations are complete if(i_iteration >= n_iterations_phase) flag_continue = GBP_FALSE; } // while flag_continue=GBP_TRUE // Report progress SID_log("Completed iterations in this phase: %d (%d requested)", SID_LOG_COMMENT, i_iteration, n_iterations_phase); // Report success rate SID_log("Proposal success: %5.3f%% (%lld of %lld)", SID_LOG_COMMENT, 1e2 * ((float)(MCMC->n_success) / (float)(MCMC->n_propositions)), MCMC->n_success, MCMC->n_propositions); i_iteration = 0; i_iteration_start = i_iteration; SID_log("Done.", SID_LOG_CLOSE); } if(my_chain == SID.My_rank) { fp_chain_config = fopen(filename_chain_config, "wb"); fwrite(&n_iterations_file_total, sizeof(int), 1, fp_chain_config); fwrite(&n_iterations_file_burn, sizeof(int), 1, fp_chain_config); fwrite(&(MCMC->temperature), sizeof(double), 1, fp_chain_config); fwrite(MCMC->V, sizeof(double), n_P * n_P, fp_chain_config); fclose(fp_chain_config); fclose(fp_chain); fclose(fp_stats); } SID_log("Done.", SID_LOG_CLOSE); // Perform analysis on chain(s) if(MCMC->flag_analysis_on) analyze_MCMC(MCMC); // Clean-up SID_log("Cleaning-up...", SID_LOG_OPEN); SID_free(SID_FARG P_min); SID_free(SID_FARG P_max); SID_free(SID_FARG P_avg); SID_free(SID_FARG dP_avg); SID_free(SID_FARG ln_Pr_chain); SID_free(SID_FARG ln_Pr_proposals); SID_free(SID_FARG drift); SID_free(SID_FARG slopes); SID_free(SID_FARG dP_sub); for(i_P = 0; i_P < n_P; i_P++) { SID_free(SID_FARG P_chain_stats[i_P]); SID_free(SID_FARG P_prop_stats[i_P]); if(flag_autocor_on) SID_free(SID_FARG auto_cor[i_P]); } SID_free(SID_FARG P_chain_stats); SID_free(SID_FARG P_prop_stats); if(flag_autocor_on) SID_free(SID_FARG auto_cor); SID_log("Done.", SID_LOG_CLOSE); SID_log("Done.", SID_LOG_CLOSE); }
{ "alphanum_fraction": 0.5463290658, "avg_line_length": 48.5594002307, "ext": "c", "hexsha": "2fa8edc54ad393305d784a970270ce2dcf1b3e19", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_path": "src/gbpMath/gbpMCMC/compute_MCMC.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_path": "src/gbpMath/gbpMCMC/compute_MCMC.c", "max_line_length": 138, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_path": "src/gbpMath/gbpMCMC/compute_MCMC.c", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "num_tokens": 9994, "size": 42101 }
/* main.h: contains all forward declarations and necessary includes */ #ifndef MAIN_H #define MAIN_H #define DEBUG false #include <cstdlib> #include <iostream> #include <string> #include <cmath> #include <list> #include <ctime> #include <unistd.h> #include <gsl/gsl_rng.h> using namespace std; extern gsl_rng *r; // global random number generator: class Agent; // a thinking human agent class Link; // a link between two agents bool validLink(Agent* agent1, Agent* agent2, list<Link> &relation); // returns false if the Agents are the same or already linked void removeLink(Agent* agent1, Agent* agent2, list<Link> &relation); // searches for and removes the link between two agents void printXML(int nr_of_agents, list<Link> &relation); // prints XML output void printDOT(list<Link> &relation); // prints GraphViz DOT output double connectivity(); // TODO: returns some statistic indicating the fat-tailness of the connectivity distribution double assortativity(list<Link> &relation); // returns the assortativity coefficient of the network double clustering(int nr_of_agents, Agent population[], list<Link> &relation); // returns the global clustering coefficient bool exists(Agent* target, list<Agent*> &agents); // returns true if the target is in the list of agents double avgpath(int nr_of_agents, Agent population[]); // returns the average path length #endif // MAIN_H
{ "alphanum_fraction": 0.7578796562, "avg_line_length": 25.3818181818, "ext": "h", "hexsha": "871d7d353b1451d5f2d0955ddf6b0d42695a2e37", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "e4428af14657d0b4e182c943e91dc19513700c1f", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "r2src/unet", "max_forks_repo_path": "main.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e4428af14657d0b4e182c943e91dc19513700c1f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC0-1.0" ], "max_issues_repo_name": "r2src/unet", "max_issues_repo_path": "main.h", "max_line_length": 92, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e4428af14657d0b4e182c943e91dc19513700c1f", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "r2src/unet", "max_stars_repo_path": "main.h", "max_stars_repo_stars_event_max_datetime": "2016-09-03T23:46:15.000Z", "max_stars_repo_stars_event_min_datetime": "2016-09-03T23:46:15.000Z", "num_tokens": 312, "size": 1396 }
/* * author: Achim Gaedke * created: January 2002 * file: pygsl/src/multiminmodule.c * $Id: multiminmodule.c,v 1.5 2004/03/08 08:42:16 schnizer Exp $ */ #include <setjmp.h> #include <pygsl/block_helpers.h> #include <pygsl/error_helpers.h> #include <pygsl/function_helpers.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multimin.h> #include "multiminmodule_doc.h" /* * I have two different types to minimize and I am too lazy to implement the same * twice. Therefore I use unions and add a flag to the minimizer for the type */ union pygsl_multimin_minimizer_type{ const gsl_multimin_fminimizer_type *f; const gsl_multimin_fdfminimizer_type *fdf; }; union pygsl_multimin_minimizer{ gsl_multimin_fminimizer *f; gsl_multimin_fdfminimizer *fdf; }; union pygsl_multimin_func{ gsl_multimin_function *f; gsl_multimin_function_fdf *fdf; }; struct pygsl_solver_types{ const char * f_minimizer; const char * fdf_minimizer; }; static struct pygsl_solver_types my_solvers = {"F-Minimizer", "Fdf-Minimizer"}; /* * type: * == 0 -> f * != 0 -> fdf */ typedef struct { PyObject_HEAD PyObject* py_f; PyObject* py_df; PyObject* py_fdf; PyObject* trailing_params; union pygsl_multimin_func func; union pygsl_multimin_minimizer min; size_t n; const char *mytype; int isset; /* Used as a flag if the jmp_buf is set */ jmp_buf buffer; } PyGSL_multimin; #define PyGSL_multimin_check(op) ((op)->ob_type == &PyGSL_multimin_pytype) #define PyGSL_multimin_isf(op) ((op)->mytype == my_solvers.f_minimizer) static void PyGSL_multimin_dealloc(PyGSL_multimin* self); static PyObject* PyGSL_multimin_getattr(PyGSL_multimin * obj, char *name); PyTypeObject PyGSL_multimin_pytype = { PyObject_HEAD_INIT(NULL) /* fix up the type slot in initcrng */ 0, /* ob_size */ "PyGSL_multimin", /* tp_name */ sizeof(PyGSL_multimin), /* tp_basicsize */ 0, /* tp_itemsize */ /* standard methods */ (destructor) PyGSL_multimin_dealloc, /* tp_dealloc ref-count==0 */ (printfunc) 0, /* tp_print "print x" */ (getattrfunc) PyGSL_multimin_getattr,/* tp_getattr "x.attr" */ (setattrfunc) 0, /* tp_setattr "x.attr=v" */ (cmpfunc) 0, /* tp_compare "x > y" */ (reprfunc) 0, /* tp_repr `x`, print x */ /* type categories */ 0, /* tp_as_number +,-,*,/,%,&,>>,pow...*/ 0, /* tp_as_sequence +,[i],[i:j],len, ...*/ 0, /* tp_as_mapping [key], len, ...*/ /* more methods */ (hashfunc) 0, /* tp_hash "dict[x]" */ (ternaryfunc) 0, /* tp_call "x()" */ (reprfunc) 0, /* tp_str "str(x)" */ (getattrofunc) 0, /* tp_getattro */ (setattrofunc) 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0L, /* tp_flags */ (char *) PyGSL_multimin_type_doc /* tp_doc */ }; /* Reference to this module */ PyObject *module = NULL; static const char filename[] = __FILE__; /* The Callbacks */ double PyGSL_multimin_function_f(const gsl_vector* x, void* params) { double result; int flag; int i; FUNC_MESS_BEGIN(); PyGSL_multimin *min_o; min_o = (PyGSL_multimin *) params; assert(PyGSL_multimin_check(min_o)); for(i = 0; i<x->size; i++){ DEBUG_MESS(2, "Got a x[%d] of %f", i, gsl_vector_get(x, i)); } flag = PyGSL_function_wrap_On_O(x, min_o->py_f, min_o->trailing_params, &result, NULL, x->size, __FUNCTION__); if (flag!= GSL_SUCCESS){ result = gsl_nan(); if(min_o->isset == 1) longjmp(min_o->buffer,flag); } DEBUG_MESS(2, "Got a result of %f", result); FUNC_MESS_END(); return result; } void PyGSL_multimin_function_df(const gsl_vector* x, void* params, gsl_vector *df) { int flag, i; PyGSL_multimin *min_o; min_o = (PyGSL_multimin *) params; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(min_o)); for(i = 0; i<x->size; i++){ DEBUG_MESS(2, "Got a x[%d] of %f", i, gsl_vector_get(x, i)); } flag = PyGSL_function_wrap_Op_On(x, df, min_o->py_df, min_o->trailing_params, x->size, x->size, __FUNCTION__); for(i = 0; i<df->size; i++){ DEBUG_MESS(2, "Got df x[%d] of %f", i, gsl_vector_get(df, i)); } if(flag!=GSL_SUCCESS){ if(min_o->isset == 1) longjmp(min_o->buffer,flag); } FUNC_MESS_END(); } void PyGSL_multimin_function_fdf(const gsl_vector* x, void* params, double *f, gsl_vector *df) { int flag, i; PyGSL_multimin *min_o; FUNC_MESS_BEGIN(); min_o = (PyGSL_multimin *) params; assert(PyGSL_multimin_check(min_o)); for(i = 0; i<x->size; i++){ DEBUG_MESS(2, "Got a x[%d] of %f", i, gsl_vector_get(x, i)); } flag = PyGSL_function_wrap_On_O(x, min_o->py_fdf, min_o->trailing_params, f, df, x->size, __FUNCTION__); DEBUG_MESS(2, "Got a result of %f", *f); for(i = 0; i<df->size; i++){ DEBUG_MESS(2, "Got df x[%d] of %f", i, gsl_vector_get(df, i)); } if (flag!= GSL_SUCCESS){ *f = gsl_nan(); if(min_o->isset == 1) longjmp(min_o->buffer,flag); } FUNC_MESS_END(); return; } static PyObject* PyGSL_multimin_set_f(PyGSL_multimin *self, PyObject *args, PyObject *kw) { PyObject* func = NULL, * params = NULL, * x = NULL, * steps = NULL; PyArrayObject * xa = NULL, * stepsa = NULL; int n=0, flag=GSL_EFAILED; int stride_recalc; gsl_vector_view gsl_x; gsl_vector_view gsl_steps; static const char *kwlist[] = {"f", "x0", "args", "steps", NULL}; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if (self->min.f == NULL) { gsl_error("Got a NULL Pointer of min.f", filename, __LINE__ - 3, GSL_EFAULT); return NULL; } assert(args); /* arguments PyFunction, Parameters, start Vector, step Vector */ if (0==PyArg_ParseTupleAndKeywords(args,kw,"OOOO", (char **) kwlist, &func,&x,&params,&steps)) return NULL; if(!PyCallable_Check(func)){ gsl_error("First argument must be callable", filename, __LINE__ - 3, GSL_EBADFUNC); return NULL; } n=self->n; xa = PyGSL_PyArray_PREPARE_gsl_vector_view(x, PyArray_DOUBLE, 0, n, 4, NULL); if (xa == NULL){ PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1); goto fail; } if(PyGSL_STRIDE_RECALC(xa->strides[0],sizeof(double), &stride_recalc) != GSL_SUCCESS) goto fail; gsl_x = gsl_vector_view_array_with_stride((double *)(xa->data), stride_recalc, xa->dimensions[0]); stepsa = PyGSL_PyArray_PREPARE_gsl_vector_view(steps, PyArray_DOUBLE, 0, n, 5, NULL); if (stepsa == NULL){ PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1); goto fail; } if(PyGSL_STRIDE_RECALC(stepsa->strides[0],sizeof(double), &stride_recalc) != GSL_SUCCESS) goto fail; gsl_steps = gsl_vector_view_array_with_stride((double *)(stepsa->data), stride_recalc, stepsa->dimensions[0]); if (self->func.f != NULL) { /* free the previous function and params */ Py_XDECREF(self->trailing_params); Py_XDECREF(self->py_f); } else { /* allocate function space */ self->func.f=calloc(1, sizeof(gsl_multimin_function)); if (self->func.f==NULL) { gsl_error("Could not allocate the object for the minimizer function", filename, __LINE__ - 3, GSL_ENOMEM); goto fail; } } /* add new function and parameters */ self->trailing_params=params; Py_INCREF(params); self->py_f=func; Py_INCREF(func); /* initialize the function struct */ self->func.f->n=n; self->func.f->f=PyGSL_multimin_function_f; self->func.f->params=(void*)self; if((flag = setjmp(self->buffer)) == 0){ self->isset = 1; flag = gsl_multimin_fminimizer_set(self->min.f,self->func.f, &gsl_x.vector, &gsl_steps.vector); if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){ goto fail; } } else { goto fail; } Py_DECREF(xa); Py_DECREF(stepsa); Py_INCREF(Py_None); self->isset = 0; FUNC_MESS_END(); return Py_None; fail: FUNC_MESS("Fail"); PyGSL_ERROR_FLAG(flag); self->isset = 0; Py_XDECREF(xa); Py_XDECREF(stepsa); return NULL; } static PyObject* PyGSL_multimin_set_fdf(PyGSL_multimin *self, PyObject *args, PyObject *kw) { PyObject * f = NULL, * df = NULL, * fdf = NULL, * params = NULL, * x = NULL; PyArrayObject * xa = NULL; int n=0, flag=GSL_EFAILED; int stride_recalc=-1; double step=0.01, tol=1e-4; gsl_vector_view gsl_x; static const char *kwlist[] = {"f", "df", "fdf", "x0", "args", "step", "tol", NULL}; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if (self->min.fdf == NULL) { gsl_error("Got a NULL Pointer of min.fdf", filename, __LINE__ - 3, GSL_EFAULT); return NULL; } /* arguments PyFunction, Parameters, start Vector, step Vector */ if (0==PyArg_ParseTupleAndKeywords(args, kw, "OOOO|Odd", (char **)kwlist, &f, &df, &fdf, &x, &params, &step, &tol)) return NULL; n=self->n; xa = PyGSL_PyArray_PREPARE_gsl_vector_view(x, PyArray_DOUBLE, 0, n, 4, NULL); if (xa == NULL){ PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1); goto fail; } if(params == NULL){ /* Reference counter increased later, when the parameters are set */ params = Py_None; } if(PyGSL_STRIDE_RECALC(xa->strides[0],sizeof(double), &stride_recalc) != GSL_SUCCESS) goto fail; gsl_x = gsl_vector_view_array_with_stride((double *)(xa->data), stride_recalc, xa->dimensions[0]); if (self->func.fdf != NULL) { /* free the previous function and params */ Py_XDECREF(self->trailing_params); Py_XDECREF(self->py_f); Py_XDECREF(self->py_df); Py_XDECREF(self->py_fdf); } else { /* allocate function space */ self->func.fdf=malloc(sizeof(gsl_multimin_function_fdf)); if (self->func.fdf==NULL) { gsl_error("Could not allocate the object for the minimizer function", filename, __LINE__ - 3, GSL_ENOMEM); goto fail; } } /* add new function and parameters */ self->trailing_params=params; Py_INCREF(params); self->py_f=f; Py_INCREF(f); self->py_df=df; Py_INCREF(df); self->py_fdf=fdf; Py_INCREF(fdf); /* initialize the function struct */ self->func.fdf->n=n; self->func.fdf->f =PyGSL_multimin_function_f; self->func.fdf->df =PyGSL_multimin_function_df; self->func.fdf->fdf=PyGSL_multimin_function_fdf; self->func.fdf->params=(void*)self; if((flag = setjmp(self->buffer)) == 0){ self->isset = 1; flag = gsl_multimin_fdfminimizer_set(self->min.fdf,self->func.fdf, &gsl_x.vector, step, tol); if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){ goto fail; } }else{ goto fail; } self->isset = 0; Py_DECREF(xa); Py_INCREF(Py_None); FUNC_MESS_END(); return Py_None; fail: PyGSL_ERROR_FLAG(flag); self->isset = 0; Py_XDECREF(xa); return NULL; } /* static PyObject* PyGSL_multimin_set(PyGSL_multimin *self, PyObject *args) { if(PyGSL_multimin_isf(self)){ return PyGSL_multimin_set_f(self, args); }else { return PyGSL_multimin_set_fdf(self, args); } } */ static PyObject* PyGSL_multimin_iterate(PyGSL_multimin *self, PyObject *args) { int result, flag; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if ( self->min.f ==NULL || self->func.f ==NULL) { gsl_error("Got a NULL Pointer of min.f", filename, __LINE__ - 3, GSL_EFAULT); return NULL; } if((flag = setjmp(self->buffer)) == 0){ self->isset = 1; if(PyGSL_multimin_isf(self)){ result = gsl_multimin_fminimizer_iterate(self->min.f); } else { result = gsl_multimin_fdfminimizer_iterate(self->min.fdf); } } else { PyGSL_ERROR_FLAG(flag); self->isset = 0; return NULL; } self->isset = 0; FUNC_MESS_END(); return PyGSL_error_flag_to_pyint(result); } static PyObject* PyGSL_multimin_x(PyGSL_multimin *self, PyObject *args) { gsl_vector* result; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if (self->min.f==NULL || self->func.f==NULL) { gsl_error("Got a NULL Pointer for min.f", filename, __LINE__ - 3, GSL_EFAULT); return NULL; } if(PyGSL_multimin_isf(self)){ result=gsl_multimin_fminimizer_x(self->min.f); } else { result=gsl_multimin_fdfminimizer_x(self->min.fdf); } if (result==NULL) { gsl_error("How could that happen?", filename, __LINE__ - 3, GSL_ESANITY); return NULL; } FUNC_MESS_END(); return (PyObject *) PyGSL_copy_gslvector_to_pyarray(result); } static PyObject* PyGSL_multimin_minimum(PyGSL_multimin *self, PyObject *args) { double min; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if (self->min.f == NULL || self->func.f ==NULL) { gsl_error("Got a NULL Pointer of min.f", filename, __LINE__ - 3, GSL_EFAULT); return NULL; } if(PyGSL_multimin_isf(self)){ min = gsl_multimin_fminimizer_minimum(self->min.f); } else { min = gsl_multimin_fdfminimizer_minimum(self->min.fdf); } FUNC_MESS_END(); return PyFloat_FromDouble(min); } static PyObject* PyGSL_multimin_name(PyGSL_multimin *self, PyObject *args) { const char * name; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if(PyGSL_multimin_isf(self)){ name = gsl_multimin_fminimizer_name(self->min.f); } else { name = gsl_multimin_fdfminimizer_name(self->min.fdf); } FUNC_MESS_END(); return PyString_FromString(name); } static PyObject* PyGSL_multimin_size(PyGSL_multimin *self, PyObject *args) { double size; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if ( self->min.f ==NULL || self->func.f ==NULL) { PyErr_SetString(PyExc_RuntimeError,"no function specified!"); return NULL; } if(PyGSL_multimin_isf(self)){ size = gsl_multimin_fminimizer_size(self->min.f); } else { gsl_error("Can not calculate size for a FDF", filename, __LINE__, GSL_ESANITY); return NULL; } FUNC_MESS_END(); return PyFloat_FromDouble(size); } static PyObject* PyGSL_multimin_test_size_method(PyGSL_multimin *self, PyObject *args) { int flag=GSL_EFAILED; double epsabs; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if ( self->min.f ==NULL || self->func.f ==NULL) { PyErr_SetString(PyExc_RuntimeError,"no function specified!"); return NULL; } if(PyGSL_multimin_isf(self)){ if (0==PyArg_ParseTuple(args,"d", &epsabs)) return NULL; flag = gsl_multimin_test_size(gsl_multimin_fminimizer_size(self->min.f), epsabs); } else { gsl_error("Can not calculate size for a FDF", filename, __LINE__, GSL_ESANITY); return NULL; } FUNC_MESS_END(); return PyGSL_ERROR_FLAG_TO_PYINT(flag); } static PyObject* PyGSL_multimin_restart(PyGSL_multimin *self, PyObject *args) { int flag; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if(PyGSL_multimin_isf(self)){ gsl_error("Can not restart for a F type solver", filename, __LINE__, GSL_ESANITY); return NULL; } flag = gsl_multimin_fdfminimizer_restart(self->min.fdf); if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){ return NULL; } FUNC_MESS_END(); Py_INCREF(Py_None); return Py_None; } static PyObject* PyGSL_multimin_vec_fdf(PyGSL_multimin *self, PyObject *args, gsl_vector *(*func)(gsl_multimin_fdfminimizer * s)) { gsl_vector *result; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if(PyGSL_multimin_isf(self)){ gsl_error("Can not retrieve this information for a F type solver!", filename, __LINE__, GSL_ESANITY); return NULL; } else { result=func(self->min.fdf); } FUNC_MESS_END(); return (PyObject *) PyGSL_copy_gslvector_to_pyarray(result); } static PyObject* PyGSL_multimin_istype(PyGSL_multimin *self, PyObject *args) { static const char *f = "F-Minimizer", *fdf = "Fdf-Minimizer"; const char *p; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if(PyGSL_multimin_isf(self)){ p = f; } else { p = fdf; } FUNC_MESS_END(); return PyString_FromString(p); } static PyObject* PyGSL_multimin_dx(PyGSL_multimin *self, PyObject *args) { return PyGSL_multimin_vec_fdf(self, args, gsl_multimin_fdfminimizer_dx); } static PyObject* PyGSL_multimin_gradient(PyGSL_multimin *self, PyObject *args) { return PyGSL_multimin_vec_fdf(self, args, gsl_multimin_fdfminimizer_gradient); } static PyObject* PyGSL_multimin_test_gradient_method(PyGSL_multimin * self, PyObject *args) { double epsabs; int flag; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if (0==PyArg_ParseTuple(args,"d", &epsabs)) return NULL; if(PyGSL_multimin_isf(self)){ gsl_error("Can not retrieve this information for a F type solver!", filename, __LINE__, GSL_ESANITY); return NULL; } flag = gsl_multimin_test_gradient(gsl_multimin_fdfminimizer_gradient(self->min.fdf), epsabs); FUNC_MESS_END(); return PyGSL_ERROR_FLAG_TO_PYINT(flag); } #define PyGSL_MULTIMIN_COMMON_METHODS \ {"iterate", (PyCFunction)PyGSL_multimin_iterate,METH_NOARGS,(char *)multimin_iterate_doc,}, \ {"x", (PyCFunction)PyGSL_multimin_x, METH_NOARGS,(char *)multimin_x_doc, }, \ {"minimum", (PyCFunction)PyGSL_multimin_minimum,METH_NOARGS,(char *)multimin_minimum_doc,}, \ {"name", (PyCFunction)PyGSL_multimin_name, METH_NOARGS,(char *)multimin_name_doc, }, \ {"type", (PyCFunction)PyGSL_multimin_istype, METH_NOARGS,(char *)multimin_istype_doc, }, static PyMethodDef PyGSL_multimin_fmethods[] = { PyGSL_MULTIMIN_COMMON_METHODS {"set", (PyCFunction)PyGSL_multimin_set_f, METH_VARARGS|METH_KEYWORDS, (char *)multimin_set_f_doc }, {"size", (PyCFunction)PyGSL_multimin_size, METH_NOARGS, (char *)multimin_size_doc }, {"test_size",(PyCFunction)PyGSL_multimin_test_size_method,METH_VARARGS, (char *)multimin_test_size_doc}, {NULL, NULL, 0, NULL} /* sentinel */ }; static PyMethodDef PyGSL_multimin_fdfmethods[] = { PyGSL_MULTIMIN_COMMON_METHODS {"set", (PyCFunction)PyGSL_multimin_set_fdf, METH_VARARGS|METH_KEYWORDS, (char *)multimin_set_fdf_doc }, {"restart", (PyCFunction)PyGSL_multimin_restart, METH_NOARGS, (char *)multimin_restart_doc }, {"dx", (PyCFunction)PyGSL_multimin_dx, METH_NOARGS, (char *)multimin_dx_doc }, {"gradient", (PyCFunction)PyGSL_multimin_gradient, METH_NOARGS, (char *)multimin_gradient_doc }, {"test_gradient",(PyCFunction)PyGSL_multimin_test_gradient_method,METH_VARARGS, (char *)multimin_test_gradient_doc}, {NULL, NULL, 0, NULL} /* sentinel */ }; static PyObject* PyGSL_multimin_init(PyObject *self, PyObject *args, union pygsl_multimin_minimizer_type type, int t) { PyGSL_multimin *min_o=NULL; size_t n; /* static const char functionname [] = __FUNCTION__; */ FUNC_MESS_BEGIN(); min_o = (PyGSL_multimin *) PyObject_NEW(PyGSL_multimin, &PyGSL_multimin_pytype); if(min_o == NULL){ return NULL; } if (0==PyArg_ParseTuple(args,"l", &n)) return NULL; if (n<=0) { PyErr_SetString(PyExc_RuntimeError, "dimension must be >0"); return NULL; } min_o->n=n; min_o->min.f=NULL; min_o->min.fdf=NULL; min_o->func.f=NULL; min_o->func.fdf=NULL; min_o->py_f=NULL; min_o->py_df=NULL; min_o->py_fdf=NULL; min_o->trailing_params=NULL; min_o->mytype=NULL; if(t == 0){ min_o->min.f = gsl_multimin_fminimizer_alloc(type.f,n); if (min_o->min.f == NULL) { gsl_error("Could not allocate the object for the minimizer", filename, __LINE__ - 3, GSL_ENOMEM); goto fail; } min_o->mytype = my_solvers.f_minimizer; assert(PyGSL_multimin_isf(min_o)); } else { min_o->min.fdf = gsl_multimin_fdfminimizer_alloc(type.fdf,n); if (min_o->min.fdf == NULL) { gsl_error("Could not allocate the object for the fdfminimizer", filename, __LINE__ - 3, GSL_ENOMEM); goto fail; } min_o->mytype = my_solvers.fdf_minimizer; assert(!PyGSL_multimin_isf(min_o)); } FUNC_MESS_END(); return (PyObject *) min_o; fail: Py_XDECREF(min_o); return NULL; } #define AMINIMIZER(name) \ static PyObject* PyGSL_multimin_init_ ## name (PyObject *self, PyObject *args)\ { \ PyObject *tmp = NULL; \ union pygsl_multimin_minimizer_type type; \ FUNC_MESS_BEGIN(); \ type.f = gsl_multimin_fminimizer_ ## name; \ tmp = PyGSL_multimin_init(self, args, type, 0); \ if (tmp == NULL){ \ PyGSL_add_traceback(module, (char *) filename, __FUNCTION__, __LINE__); \ } \ FUNC_MESS_END(); \ return tmp; \ } #define AMINIMIZER_FDF(name) \ static PyObject* PyGSL_multimin_init_ ## name (PyObject *self, PyObject *args)\ { \ PyObject *tmp = NULL; \ union pygsl_multimin_minimizer_type type; \ FUNC_MESS_BEGIN(); \ type.fdf = gsl_multimin_fdfminimizer_ ## name; \ tmp = PyGSL_multimin_init(self, args, type, 1); \ if (tmp == NULL){ \ PyGSL_add_traceback(module, (char *) filename, __FUNCTION__, __LINE__); \ } \ FUNC_MESS_END(); \ return tmp; \ } AMINIMIZER(nmsimplex) AMINIMIZER_FDF(steepest_descent) AMINIMIZER_FDF(vector_bfgs) AMINIMIZER_FDF(conjugate_pr) AMINIMIZER_FDF(conjugate_fr) static void PyGSL_multimin_dealloc(PyGSL_multimin *self) { FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if(PyGSL_multimin_isf(self)){ if (self->min.f != NULL) gsl_multimin_fminimizer_free(self->min.f); if (self->func.f != NULL) free(self->func.f); }else{ if (self->min.fdf != NULL) gsl_multimin_fdfminimizer_free(self->min.fdf); if (self->func.fdf != NULL) free(self->func.fdf); } Py_XDECREF(self->trailing_params); Py_XDECREF(self->py_f); Py_XDECREF(self->py_df); Py_XDECREF(self->py_fdf); PyMem_Free(self); FUNC_MESS_END(); } static PyObject* PyGSL_multimin_getattr(PyGSL_multimin *self, char *name) { PyObject *tmp = NULL; FUNC_MESS_BEGIN(); assert(PyGSL_multimin_check(self)); if(PyGSL_multimin_isf(self)){ tmp = Py_FindMethod(PyGSL_multimin_fmethods, (PyObject *) self, name); } else { tmp = Py_FindMethod(PyGSL_multimin_fdfmethods, (PyObject *) self, name); } FUNC_MESS_END(); return tmp; } static PyObject* PyGSL_multimin_test_size(PyObject * self, PyObject *args) { double size, epsabs; int flag = GSL_EFAILED; FUNC_MESS_BEGIN(); if (0==PyArg_ParseTuple(args,"dd", &size, &epsabs)) return NULL; flag = gsl_multimin_test_size(size, epsabs); FUNC_MESS_END(); return PyGSL_ERROR_FLAG_TO_PYINT(flag); } static PyObject* PyGSL_multimin_test_gradient(PyObject * self, PyObject *args) { PyObject *g=NULL; PyArrayObject *ga=NULL; gsl_vector_view gradient; double epsabs; int flag = GSL_EFAILED, stride_recalc=-1; FUNC_MESS_BEGIN(); if (0==PyArg_ParseTuple(args,"Od", &g, &epsabs)) return NULL; ga = PyGSL_PyArray_PREPARE_gsl_vector_view(g, PyArray_DOUBLE, 0, -1, 1, NULL); if (ga == NULL){ PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1); return NULL; } if((PyGSL_STRIDE_RECALC(ga->strides[0],sizeof(double), &stride_recalc)) != GSL_SUCCESS){ Py_XDECREF(ga); return NULL; } gradient = gsl_vector_view_array_with_stride((double *)(ga->data), stride_recalc, ga->dimensions[0]); flag = gsl_multimin_test_gradient(&gradient.vector, epsabs); FUNC_MESS_END(); return PyGSL_ERROR_FLAG_TO_PYINT(flag); } static PyMethodDef multiminMethods[] = { {"nmsimplex", PyGSL_multimin_init_nmsimplex, METH_VARARGS, (char *)nmsimplex_doc }, {"steepest_descent", PyGSL_multimin_init_steepest_descent, METH_VARARGS, (char *)steepest_descent_doc}, {"vector_bfgs", PyGSL_multimin_init_vector_bfgs, METH_VARARGS, (char *)vector_bfgs_doc }, {"conjugate_pr", PyGSL_multimin_init_conjugate_pr, METH_VARARGS, (char *)conjugate_pr_doc }, {"conjugate_fr", PyGSL_multimin_init_conjugate_fr, METH_VARARGS, (char *)conjugate_fr_doc }, {"test_size", PyGSL_multimin_test_size, METH_VARARGS, (char *)test_size_doc }, {"test_gradient", PyGSL_multimin_test_gradient, METH_VARARGS, (char *)test_gradient_doc }, {NULL, NULL, 0, NULL} /* Sentinel */ }; void initmultimin(void) { PyObject* m, *dict, *item; m=Py_InitModule("multimin", multiminMethods); import_array(); init_pygsl(); /* init multimin type */ PyGSL_multimin_pytype.ob_type = &PyType_Type; module = m; Py_INCREF((PyObject*)&PyGSL_multimin_pytype); dict = PyModule_GetDict(m); if(!dict) goto fail; if (!(item = PyString_FromString((char*)PyGSL_multimin_module_doc))){ PyErr_SetString(PyExc_ImportError, "I could not generate module doc string!"); goto fail; } if (PyDict_SetItemString(dict, "__doc__", item) != 0){ PyErr_SetString(PyExc_ImportError, "I could not init doc string!"); goto fail; } fail: return; }
{ "alphanum_fraction": 0.6160266501, "avg_line_length": 31.6168981481, "ext": "c", "hexsha": "96e6562364d3b6e3cd22b2de8d2fb6f5605f115c", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/multiminmodule.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/multiminmodule.c", "max_line_length": 140, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/multiminmodule.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7747, "size": 27317 }
// // Created by L. Jonathan Feldstein // #ifndef CIMPLE_CIMPLE_CONTROLLER_H #define CIMPLE_CIMPLE_CONTROLLER_H #include <stddef.h> #include <math.h> #include "cimple_system.h" #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include "cimple_polytope_library.h" #include <pthread.h> #include "cimple_mpc_computation.h" /** * @brief Action to get plant from current abstract state to target_abs_state. * * @param target target region the plant is supposed to reach * @param now current state of the plant * @param d_dyn discrete abstraction of the system * @param s_dyn system dynamics including auxiliary matrices * @param f_cost cost function to be minimized on the path */ void ACT(int target, current_state * now, discrete_dynamics * d_dyn, system_dynamics * s_dyn, cost_function * f_cost, double sec); /** * @brief Apply the calculated control to the current state using system dynamics * @param x current state at time [0] * @param u matrix with next N inputs calculated by the MPC controller * @param A system dynamics * @param B input dynamics */ void apply_control(gsl_vector *x, gsl_vector *u, gsl_matrix *A, gsl_matrix *B, gsl_matrix *E, gsl_vector *w, size_t current_time); /** * Fill a vector with gaussian distributed noise * @param w */ void simulate_disturbance(gsl_vector *w, double mu, double sigma); void * main_computation(void *arg); #endif //CIMPLE_CIMPLE_CONTROLLER_H
{ "alphanum_fraction": 0.6582976118, "avg_line_length": 26.7704918033, "ext": "h", "hexsha": "c6a3bff11833747d06a7f59a5d2259b6a03f522b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "shaesaert/TuLiPXML", "max_forks_repo_path": "Interface/Cimple/cimple_controller.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z", "max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "shaesaert/TuLiPXML", "max_issues_repo_path": "Interface/Cimple/cimple_controller.h", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "shaesaert/TuLiPXML", "max_stars_repo_path": "Interface/Cimple/cimple_controller.h", "max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z", "num_tokens": 363, "size": 1633 }
#pragma once #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> gsl_rng *RandomNumberGenerator; /* Random number generator. */ unsigned RandomSeed; /* Random seed. */ unsigned GetRandomSeed() { FILE *random_file; unsigned seed; int error; seed = 0; random_file = fopen("/dev/urandom", "rb"); if (!random_file) return 0; do { error = fread(&seed, 1, sizeof(unsigned int), random_file); if (error != sizeof(unsigned int)) return 0; } while (!seed); fclose(random_file); return seed; } /** InitialiseRandom. - Initialises the random number generator. **/ int InitialiseRandom(const gsl_rng_type *random_generator) { RandomSeed = GetRandomSeed(); if (!RandomSeed) return EXIT_FAILURE; RandomNumberGenerator = gsl_rng_alloc(random_generator); if (!RandomNumberGenerator) return EXIT_FAILURE; gsl_rng_set(RandomNumberGenerator, RandomSeed); return EXIT_SUCCESS; } /** FinaliseRandom. - Finalises the random number generator. **/ int FinaliseRandom() { /* Release random number generator memory. */ if (RandomNumberGenerator) { gsl_rng_free(RandomNumberGenerator); return EXIT_SUCCESS; // EXIT_SUCCESS = 0 } return EXIT_FAILURE; // EXIT_FAILURE = 1 } /////////////
{ "alphanum_fraction": 0.6907216495, "avg_line_length": 20.0158730159, "ext": "h", "hexsha": "69b218ed8776e3eb9fa141350173bd85a0c9de8c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "eduardomgutierrez/RIAF_radproc", "max_forks_repo_path": "src/lib/nrMath/random.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "eduardomgutierrez/RIAF_radproc", "max_issues_repo_path": "src/lib/nrMath/random.h", "max_line_length": 63, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "eduardomgutierrez/RIAF_radproc", "max_stars_repo_path": "src/lib/nrMath/random.h", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z", "num_tokens": 310, "size": 1261 }
// -*- C++ -*- // // michael a.g. aïvázis // orthologue // (c) 1998-2021 all rights reserved // // get the headers #include <cblas.h> // smallest possible driver int main() { // allocate the scala double alpha = 1; // allocate a vector double x[] = {0.0, 0.0, 0.0}; double y[] = {0.0, 0.0, 0.0}; // do it cblas_daxpy(3, alpha, x, 1, y, 1); // all done return 0; } // end of file
{ "alphanum_fraction": 0.5344418052, "avg_line_length": 15.0357142857, "ext": "c", "hexsha": "d95c07eece28afc2797dae4a583a3eabb37db93b", "lang": "C", "max_forks_count": 12, "max_forks_repo_forks_event_max_datetime": "2022-02-20T17:27:23.000Z", "max_forks_repo_forks_event_min_datetime": "2018-04-23T22:50:40.000Z", "max_forks_repo_head_hexsha": "e9ff3f8c04661f8b2cd2ba0caded08b6fe8054e2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "gmgunter/pyre", "max_forks_repo_path": "etc/externals/atlas/sanity.c", "max_issues_count": 53, "max_issues_repo_head_hexsha": "e9ff3f8c04661f8b2cd2ba0caded08b6fe8054e2", "max_issues_repo_issues_event_max_datetime": "2021-10-07T21:41:32.000Z", "max_issues_repo_issues_event_min_datetime": "2018-05-31T04:55:00.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "gmgunter/pyre", "max_issues_repo_path": "etc/externals/atlas/sanity.c", "max_line_length": 38, "max_stars_count": 25, "max_stars_repo_head_hexsha": "e9ff3f8c04661f8b2cd2ba0caded08b6fe8054e2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "gmgunter/pyre", "max_stars_repo_path": "etc/externals/atlas/sanity.c", "max_stars_repo_stars_event_max_datetime": "2021-12-10T06:01:23.000Z", "max_stars_repo_stars_event_min_datetime": "2018-04-23T01:45:39.000Z", "num_tokens": 157, "size": 421 }
#pragma once #include <gsl.h> #include <boost/optional.hpp> #include <mitkDataStorage.h> #include <mitkNodePredicateBase.h> #include <mitkOperationActor.h> #include "uk_ac_kcl_HierarchyManager_Export.h" #define DECLARE_HIERARCHY_MANAGER_NODE_TYPE(nodeTypeName) static const crimson::HierarchyManager::NodeType& nodeTypeName(); #define DEFINE_HIERARCHY_MANAGER_NODE_TYPE(containerClass, nodeTypeName) \ const crimson::HierarchyManager::NodeType& containerClass::nodeTypeName() \ { \ static const crimson::HierarchyManager::NodeType type = crimson::HierarchyManager::getInstance()->createNodeType(); \ return type; \ } namespace crimson { /*! \brief A singleton class for managing the hierarchical relations of CRIMSON data objects. * * The hierarchical relations define the dependencies between various data objects. * This mostly affects how the nodes are presented to the user in the MITK's Data Manager view. * For example, the vessel paths belonging to the same vessel tree must be grouped under the node * representing this vessel tree. Thus, deleting the vessel tree node will also delete the vessel * paths belonging to it. * * Hierarchical grouping also facilitates the discovery of th nodes using the mitk::DataStorage. * For example, to find all the contours defining a vessel, it is sufficient to iterate the * child nodes of the vessel path and select the nodes containing contours. * * HierarchyManager allows adding new node types and relationships between them. The most * convenient way to do so is to use the DECLARE_HIERARCHY_MANAGER_NODE_TYPE and * DEFINE_HIERARCHY_MANAGER_NODE_TYPE macro pair. This will correctly register the node types in * the hierarchy mananger. * * Example usage: * * // MyNodeTypes.h * #pragma once * #include <HierarchyManager.h> * * struct MyNodeTypes { * DECLARE_HIERARCHY_MANAGER_NODE_TYPE(MyParentNode) * DECLARE_HIERARCHY_MANAGER_NODE_TYPE(MyChildNode) * }; * * // MyNodeTypes.cpp * #include "MyNodeTypes.h" * * DEFINE_HIERARCHY_MANAGER_NODE_TYPE(MyNodeTypes, MyParentNode) * DEFINE_HIERARCHY_MANAGER_NODE_TYPE(MyNodeTypes, MyChildNode) * * // UsingHierarchyManager.cpp * void initialize() * { * auto hm = crimson::HierarchyManager::getInstance(); * hm->addNodeType(MyNodeTypes::MyParentNode(), ParentNodePredicate::New()); * hm->addNodeType(MyNodeTypes::MyChildNode(), ChildNodePredicate::New()); * hm->addRelation(MyNodeTypes::MyParentNode(), MyNodeTypes::MyChildNode(), crimson::HierarchyManager::rtOneToMany); * } * * void addNode(mitk::DataNode* parent, mitkDataNode* child) * { * auto hm = crimson::HierarchyManager::getInstance(); * hm->addNodeToHierarchy(parent, MyNodeTypes::MyParentNode(), child, MyNodeTypes::MyChildNode()); * // ... * } */ class HIERARCHYMANAGER_EXPORT HierarchyManager : public itk::Object, public mitk::OperationActor { public: /*! \name Singleton interface */ ///@{ static bool init(); static HierarchyManager* getInstance(); static void term(); ///@} using NodeType = int; /*! * \brief Creates a unique id for a new node type. */ int createNodeType() { return _lastAssignedNodeType++; } /*! \brief Values that represent relation types between parent and child nodes. */ enum RelationType { rtOneToOne = 0, ///< Only one child of a particular type is allowed for the parent rtOneToMany, ///< Multiple children of a particular type are allowed for the parent rtUnknown ///< No information about the relations between types }; /*! \brief Values that represent node type flags. */ enum NodeTypeFlags { ntfNone = 0x00, ///< No flags ntfRecursiveDeletion = 0x01, ///< Deleting a parent node also deletes all its children ntfUndoableDeletion = 0x02, ///< If the node is deleted, it should be put onto undo stack to allow deletion undo ntfPickable = 0x04 ///< The node should be allowed to be picked with mouse clicks in 3D rendering window }; ///@{ /*! * \brief Adds a new node type. * * \param type The new node type identifier. * \param predicate The predicate defining the node. * \param flags The flags to be applied for nodes of this type. */ bool addNodeType(const NodeType& type, const mitk::NodePredicateBase::Pointer& predicate, int flags = ntfNone); /*! * \brief Adds a relation between the parent and child node types. * * \param parentType Type of the parent. * \param childType Type of the child. * \param relation The type of relation. */ bool addRelation(const NodeType& parentType, const NodeType& childType, const RelationType& relation); /*! * \brief Gets a relation between the parent and child node types. * * \param parentNodeType Type of the parent node. * \param childNodeType Type of the child node. */ RelationType getRelation(const NodeType& parentNodeType, const NodeType& childNodeType) const; ///@} /*! * \brief Gets data storage that the HierarchyManager operates upon. */ mitk::DataStorage::Pointer getDataStorage() const; /*! * \brief Set the flag whether to start a new undo group when adding nodes to hierarchy. * * By default, addNodeToHierarchy() will start a new undo group meaning that undoing the * addition will remove nodes one by one. However, when multiple nodes are to be added as a * single unit, set this flag to false (and reset it to true after all nodes are added). */ void setStartNewUndoGroup(bool start); /*! * \brief Determine if a child node of a particular type can be added to the parent node of a different type. * * \param parentNode The desired parent node. * \param parentNodeType Type of the parent node. * \param childNodeType Type of the child node. * \param allowReplacement true if replacing a node is allowed (useful for rtOneToOne relationship). */ bool canAddNode(mitk::DataNode* parentNode, const NodeType& parentNodeType, const NodeType& childNodeType, bool allowReplacement) const; /*! * \brief Adds a node to hierarchy. * * \param parentNode The parent node. * \param parentNodeType Type of the parent node. * \param newNode The new node. * \param newNodeType Type of the new node. * * \return false if the relationship between the node types is unknown. */ bool addNodeToHierarchy(const mitk::DataNode* parentNode, const NodeType& parentNodeType, const mitk::DataNode* newNode, const NodeType& newNodeType); /*! * \brief Searches for the first node type that the node satisfies. */ boost::optional<NodeType> findFittingNodeType(mitk::DataNode* node) const; /*! * \brief Searches for the potential parents of the node with a particular nodeType. */ std::unordered_set<mitk::DataNode*> findPotentialParents(mitk::DataNode* node, NodeType nodeType) const; /*! * \brief Change the parent of the node. */ bool reparentNode(const mitk::DataNode::Pointer& node, const mitk::DataNode::Pointer& newParent); /*! * \brief Gets a predicate associated with the node type. */ mitk::NodePredicateBase::Pointer getPredicate(const NodeType& type) const; ///@{ /*! * \brief Gets an ancestor of the node of a particular type. * * \param node The child node. * \param parentType Type of the parent. * \param directOnly false to search parents of parents. */ mitk::DataNode::Pointer getAncestor(const mitk::DataNode* node, const NodeType& parentType, bool directOnly = false) const; /*! * \brief Gets the first descendant node of a particular type. * * \param node The parent node. * \param descendantType Type of the descendant. * \param directOnly false to search children of children. */ mitk::DataNode::Pointer getFirstDescendant(const mitk::DataNode* node, const NodeType& descendantType, bool directOnly = false) const; /*! * \brief Gets all the descendant nodes of a particular type. * * \param node The parent node. * \param descendantsType Type of the descendants. * \param directOnly false to search children of children. */ mitk::DataStorage::SetOfObjects::ConstPointer getDescendants(const mitk::DataNode* node, const NodeType& descendantsType, bool directOnly = false) const; ///@} static const char* nodeUIDPropertyName; ///< The name of the DataNode property where the nodeUID is stored /*! * \brief Searches for the node with a particular UID. */ mitk::DataNode::Pointer findNodeByUID(gsl::cstring_span<> nodeUID) const; /*! * \brief Enables/disables the undo for adding and deleting nodes. */ void enableUndo(bool enable); /*! * \brief Overriden from mitk::Operation for undo/redo support. */ void ExecuteOperation(mitk::Operation* operation) override; private: HierarchyManager(); ~HierarchyManager(); HierarchyManager(const HierarchyManager&) = delete; HierarchyManager& operator=(const HierarchyManager&) = delete; void _connectDataStorageEvents(); void _disconnectDataStorageEvents(); void nodeAdded(const mitk::DataNode*); void nodeRemoved(const mitk::DataNode*); private: static HierarchyManager* _instance; struct HierarchyManagerImpl; std::unique_ptr<HierarchyManagerImpl> _impl; int _lastAssignedNodeType = 0; bool _testFlags(const mitk::DataNode* node, NodeTypeFlags flags) const; std::vector<std::pair<std::vector<const mitk::DataNode*>, mitk::DataNode::ConstPointer>> _getUndoableRemoveNodes(const mitk::DataNode* node) const; }; } // namespace crimson
{ "alphanum_fraction": 0.63920953, "avg_line_length": 39.8125, "ext": "h", "hexsha": "464d4379d51f32bf16ec1b64486fc9a4a1bd2196", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_path": "Plugins/uk.ac.kcl.HierarchyManager/src/HierarchyManager.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_path": "Plugins/uk.ac.kcl.HierarchyManager/src/HierarchyManager.h", "max_line_length": 128, "max_stars_count": 10, "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_path": "Plugins/uk.ac.kcl.HierarchyManager/src/HierarchyManager.h", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "num_tokens": 2421, "size": 10829 }
/* * Copyright (c) 2015, Aleksas Mazeliauskas and Derek Teaney * All rights reserved. * * rnavier is distributed under MIT license; * see the LICENSE file that should be present in the root * of the source distribution, or alternately available at: * https://github.com/rnavier/rnavier/ */ #ifndef RNAVIER_TBjFluctuation_h #define RNAVIER_TBjFluctuation_h #include <gsl/gsl_odeiv.h> #include <memory> #include "THModel3D.h" #include "TIC3D.h" class THydro3DBj ; class TRNavier3DBj ; class TBjFluctuation{ private: THModel3D *fModel ; double fTau ; double fH ; double fKx; double fKy; double fKeta; static constexpr double fEpsAbs = 1.e-10; static constexpr double fEpsRel = 1.e-4 ; static const size_t fSize= 9 ; double fY[fSize] ; const gsl_odeiv_step_type *fType ; gsl_odeiv_step *fStep ; gsl_odeiv_control *fControl ; gsl_odeiv_evolve *fEvolve ; gsl_odeiv_system fSystem ; void setY(const double &e0, const std::complex<double> &de, const std::complex<double> &gx, const std::complex<double> &gy, const std::complex<double> &gz, double y[]) ; void getY(const double y[], double &e0, std::complex<double> &de, std::complex<double> &gx, std::complex<double> &gy, std::complex<double> &gz) ; int step(double &t , const double &tf, double &h, double y[]) { return gsl_odeiv_evolve_apply(fEvolve, fControl, fStep, &fSystem, &t, tf, &h, y) ; } void eos_params(const double &e0, double &p0, double &cs0, double &s0, double &T0, double &eta0) ; public: TBjFluctuation(THModel3D *hmodel) ; ~TBjFluctuation() ; void setic(const double &t0, const double &kx, const double &ky, const double &keta, const double &e0, const std::complex<double> &de, const std::complex<double> &gx, const std::complex<double> &gy, const std::complex<double> &gz) ; void get_hydro_ic(const TICPoint3D &pnt, double &e, double &n, double *uI, double *piIJ_ns); int run(const double &t1, const bool &verbose = false) ; void get_timescales_cartesian(double &tauR, double &tau_sound, double &tau_damp) ; friend int tbjfluctuation_func (double t, const double y[], double f[], void *params) ; } ; int tbjfluctuation_func (double t, const double y[], double f[], void *params) ; ////////////////////////////////////////////////////////////////////////////// class TICBjFluctuation : public TIC3D { private: THModel3D *fModel ; double fTau0 ; double fLx; double fLy ; double fLeta; double fInitialS0; double fInitialE0; double fNKx; double fNKy; double fNKeta; double fDeOverE0; double fPhaseE; std::unique_ptr<TBjFluctuation> fFluctuation; public: TICBjFluctuation(TRNavier3DBj *rn, TGrid3D *gr) ; virtual void nextEvent(const double &bgen) override ; virtual void IC(const TICPoint3D &pnt, const TNDArray1D &auxi) override ; using TIC3D::fillGrid ; void evolve_to_time(const double &t) { fFluctuation->run(t) ; } void get_timescales_cartesian(double &tauR, double &tau_sound, double &tau_damp) { fFluctuation->get_timescales_cartesian(tauR, tau_sound, tau_damp) ; } }; std::unique_ptr<TIC3D> make_ic_icbjfluctuation(THydro3DBj *hy, const std::string &icname) ; #endif //RNAVIER_TBjFluctuation_h
{ "alphanum_fraction": 0.5941300899, "avg_line_length": 25.7278911565, "ext": "h", "hexsha": "9aac95043af66c239aa04cc196e7662225737cad", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6f30abc9969daa1a8e6b72d0c1069e2a477ad610", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rnavier/rnavier", "max_forks_repo_path": "src/bjperturbation/TBjFluctuation.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6f30abc9969daa1a8e6b72d0c1069e2a477ad610", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "rnavier/rnavier", "max_issues_repo_path": "src/bjperturbation/TBjFluctuation.h", "max_line_length": 98, "max_stars_count": 2, "max_stars_repo_head_hexsha": "6f30abc9969daa1a8e6b72d0c1069e2a477ad610", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rnavier/rnavier", "max_stars_repo_path": "src/bjperturbation/TBjFluctuation.h", "max_stars_repo_stars_event_max_datetime": "2021-05-05T15:03:33.000Z", "max_stars_repo_stars_event_min_datetime": "2015-08-04T14:02:15.000Z", "num_tokens": 1064, "size": 3782 }
/** * * @file qwrapper_claswp.c * * PLASMA core_blas quark wrapper * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mathieu Faverge * @date 2010-11-15 * @generated c Tue Jan 7 11:44:58 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * **/ void QUARK_CORE_claswp(Quark *quark, Quark_Task_Flags *task_flags, int n, PLASMA_Complex32_t *A, int lda, int i1, int i2, const int *ipiv, int inc) { DAG_CORE_LASWP; QUARK_Insert_Task( quark, CORE_claswp_quark, task_flags, sizeof(int), &n, VALUE, sizeof(PLASMA_Complex32_t)*lda*n, A, INOUT | LOCALITY, sizeof(int), &lda, VALUE, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*n, ipiv, INPUT, sizeof(int), &inc, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_claswp_quark = PCORE_claswp_quark #define CORE_claswp_quark PCORE_claswp_quark #endif void CORE_claswp_quark(Quark *quark) { int n, lda, i1, i2, inc; int *ipiv; PLASMA_Complex32_t *A; quark_unpack_args_7(quark, n, A, lda, i1, i2, ipiv, inc); LAPACKE_claswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc ); } /***************************************************************************//** * **/ void QUARK_CORE_claswp_f2(Quark *quark, Quark_Task_Flags *task_flags, int n, PLASMA_Complex32_t *A, int lda, int i1, int i2, const int *ipiv, int inc, PLASMA_Complex32_t *fake1, int szefake1, int flag1, PLASMA_Complex32_t *fake2, int szefake2, int flag2) { DAG_CORE_LASWP; QUARK_Insert_Task( quark, CORE_claswp_f2_quark, task_flags, sizeof(int), &n, VALUE, sizeof(PLASMA_Complex32_t)*lda*n, A, INOUT | LOCALITY, sizeof(int), &lda, VALUE, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*n, ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(PLASMA_Complex32_t)*szefake1, fake1, flag1, sizeof(PLASMA_Complex32_t)*szefake2, fake2, flag2, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_claswp_f2_quark = PCORE_claswp_f2_quark #define CORE_claswp_f2_quark PCORE_claswp_f2_quark #endif void CORE_claswp_f2_quark(Quark* quark) { int n, lda, i1, i2, inc; int *ipiv; PLASMA_Complex32_t *A; void *fake1, *fake2; quark_unpack_args_9(quark, n, A, lda, i1, i2, ipiv, inc, fake1, fake2); LAPACKE_claswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc ); } /***************************************************************************//** * **/ void QUARK_CORE_claswp_ontile(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_desc descA, PLASMA_Complex32_t *Aij, int i1, int i2, const int *ipiv, int inc, PLASMA_Complex32_t *fakepanel) { DAG_CORE_LASWP; if (fakepanel == Aij) { QUARK_Insert_Task( quark, CORE_claswp_ontile_quark, task_flags, sizeof(PLASMA_desc), &descA, VALUE, sizeof(PLASMA_Complex32_t)*1, Aij, INOUT | LOCALITY, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(PLASMA_Complex32_t)*1, fakepanel, SCRATCH, 0); } else { QUARK_Insert_Task( quark, CORE_claswp_ontile_quark, task_flags, sizeof(PLASMA_desc), &descA, VALUE, sizeof(PLASMA_Complex32_t)*1, Aij, INOUT | LOCALITY, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(PLASMA_Complex32_t)*1, fakepanel, INOUT, 0); } } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_claswp_ontile_quark = PCORE_claswp_ontile_quark #define CORE_claswp_ontile_quark PCORE_claswp_ontile_quark #endif void CORE_claswp_ontile_quark(Quark *quark) { int i1, i2, inc; int *ipiv; PLASMA_Complex32_t *A, *fake; PLASMA_desc descA; quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake); CORE_claswp_ontile(descA, i1, i2, ipiv, inc); } /***************************************************************************//** * **/ void QUARK_CORE_claswp_ontile_f2(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_desc descA, PLASMA_Complex32_t *Aij, int i1, int i2, const int *ipiv, int inc, PLASMA_Complex32_t *fake1, int szefake1, int flag1, PLASMA_Complex32_t *fake2, int szefake2, int flag2) { DAG_CORE_LASWP; QUARK_Insert_Task( quark, CORE_claswp_ontile_f2_quark, task_flags, sizeof(PLASMA_desc), &descA, VALUE, sizeof(PLASMA_Complex32_t)*1, Aij, INOUT | LOCALITY, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(PLASMA_Complex32_t)*szefake1, fake1, flag1, sizeof(PLASMA_Complex32_t)*szefake2, fake2, flag2, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_claswp_ontile_f2_quark = PCORE_claswp_ontile_f2_quark #define CORE_claswp_ontile_f2_quark PCORE_claswp_ontile_f2_quark #endif void CORE_claswp_ontile_f2_quark(Quark *quark) { int i1, i2, inc; int *ipiv; PLASMA_Complex32_t *A; PLASMA_desc descA; void *fake1, *fake2; quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, fake1, fake2); CORE_claswp_ontile(descA, i1, i2, ipiv, inc); } /***************************************************************************//** * **/ void QUARK_CORE_cswptr_ontile(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_desc descA, PLASMA_Complex32_t *Aij, int i1, int i2, const int *ipiv, int inc, const PLASMA_Complex32_t *Akk, int ldak) { DAG_CORE_TRSM; QUARK_Insert_Task( quark, CORE_cswptr_ontile_quark, task_flags, sizeof(PLASMA_desc), &descA, VALUE, sizeof(PLASMA_Complex32_t)*1, Aij, INOUT | LOCALITY, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(PLASMA_Complex32_t)*ldak, Akk, INPUT, sizeof(int), &ldak, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_cswptr_ontile_quark = PCORE_cswptr_ontile_quark #define CORE_cswptr_ontile_quark PCORE_cswptr_ontile_quark #endif void CORE_cswptr_ontile_quark(Quark *quark) { int i1, i2, inc, ldak; int *ipiv; PLASMA_Complex32_t *A, *Akk; PLASMA_desc descA; quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, Akk, ldak); CORE_cswptr_ontile(descA, i1, i2, ipiv, inc, Akk, ldak); } /***************************************************************************//** * **/ void QUARK_CORE_claswpc_ontile(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_desc descA, PLASMA_Complex32_t *Aij, int i1, int i2, const int *ipiv, int inc, PLASMA_Complex32_t *fakepanel) { DAG_CORE_LASWP; if (fakepanel == Aij) { QUARK_Insert_Task( quark, CORE_claswpc_ontile_quark, task_flags, sizeof(PLASMA_desc), &descA, VALUE, sizeof(PLASMA_Complex32_t)*1, Aij, INOUT | LOCALITY, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(PLASMA_Complex32_t)*1, fakepanel, SCRATCH, 0); } else { QUARK_Insert_Task( quark, CORE_claswpc_ontile_quark, task_flags, sizeof(PLASMA_desc), &descA, VALUE, sizeof(PLASMA_Complex32_t)*1, Aij, INOUT | LOCALITY, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(PLASMA_Complex32_t)*1, fakepanel, INOUT, 0); } } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_claswpc_ontile_quark = PCORE_claswpc_ontile_quark #define CORE_claswpc_ontile_quark PCORE_claswpc_ontile_quark #endif void CORE_claswpc_ontile_quark(Quark *quark) { int i1, i2, inc; int *ipiv; PLASMA_Complex32_t *A, *fake; PLASMA_desc descA; quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake); CORE_claswpc_ontile(descA, i1, i2, ipiv, inc); }
{ "alphanum_fraction": 0.4972172437, "avg_line_length": 37.5921985816, "ext": "c", "hexsha": "2406944d837cc189a664fb27dcbcd26436ac66aa", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas-qwrapper/qwrapper_claswp.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas-qwrapper/qwrapper_claswp.c", "max_line_length": 103, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_claswp.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2978, "size": 10601 }
/* eigen/gsl_eigen.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2006, 2007 Gerard Jungman, Brian Gough, Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_EIGEN_H__ #define __GSL_EIGEN_H__ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; double * d; double * sd; } gsl_eigen_symm_workspace; gsl_eigen_symm_workspace * gsl_eigen_symm_alloc (const size_t n); void gsl_eigen_symm_free (gsl_eigen_symm_workspace * w); int gsl_eigen_symm (gsl_matrix * A, gsl_vector * eval, gsl_eigen_symm_workspace * w); typedef struct { size_t size; double * d; double * sd; double * gc; double * gs; } gsl_eigen_symmv_workspace; gsl_eigen_symmv_workspace * gsl_eigen_symmv_alloc (const size_t n); void gsl_eigen_symmv_free (gsl_eigen_symmv_workspace * w); int gsl_eigen_symmv (gsl_matrix * A, gsl_vector * eval, gsl_matrix * evec, gsl_eigen_symmv_workspace * w); typedef struct { size_t size; double * d; double * sd; double * tau; } gsl_eigen_herm_workspace; gsl_eigen_herm_workspace * gsl_eigen_herm_alloc (const size_t n); void gsl_eigen_herm_free (gsl_eigen_herm_workspace * w); int gsl_eigen_herm (gsl_matrix_complex * A, gsl_vector * eval, gsl_eigen_herm_workspace * w); typedef struct { size_t size; double * d; double * sd; double * tau; double * gc; double * gs; } gsl_eigen_hermv_workspace; gsl_eigen_hermv_workspace * gsl_eigen_hermv_alloc (const size_t n); void gsl_eigen_hermv_free (gsl_eigen_hermv_workspace * w); int gsl_eigen_hermv (gsl_matrix_complex * A, gsl_vector * eval, gsl_matrix_complex * evec, gsl_eigen_hermv_workspace * w); typedef struct { size_t size; /* matrix size */ size_t max_iterations; /* max iterations since last eigenvalue found */ size_t n_iter; /* number of iterations since last eigenvalue found */ size_t n_evals; /* number of eigenvalues found so far */ int compute_t; /* compute Schur form T = Z^t A Z */ gsl_matrix *H; /* pointer to Hessenberg matrix */ gsl_matrix *Z; /* pointer to Schur vector matrix */ } gsl_eigen_francis_workspace; gsl_eigen_francis_workspace * gsl_eigen_francis_alloc (void); void gsl_eigen_francis_free (gsl_eigen_francis_workspace * w); void gsl_eigen_francis_T (const int compute_t, gsl_eigen_francis_workspace * w); int gsl_eigen_francis (gsl_matrix * H, gsl_vector_complex * eval, gsl_eigen_francis_workspace * w); int gsl_eigen_francis_Z (gsl_matrix * H, gsl_vector_complex * eval, gsl_matrix * Z, gsl_eigen_francis_workspace * w); typedef struct { size_t size; /* size of matrices */ gsl_vector *diag; /* diagonal matrix elements from balancing */ gsl_vector *tau; /* Householder coefficients */ gsl_matrix *Z; /* pointer to Z matrix */ int do_balance; /* perform balancing transformation? */ size_t n_evals; /* number of eigenvalues found */ gsl_eigen_francis_workspace *francis_workspace_p; } gsl_eigen_nonsymm_workspace; gsl_eigen_nonsymm_workspace * gsl_eigen_nonsymm_alloc (const size_t n); void gsl_eigen_nonsymm_free (gsl_eigen_nonsymm_workspace * w); void gsl_eigen_nonsymm_params (const int compute_t, const int balance, gsl_eigen_nonsymm_workspace *w); int gsl_eigen_nonsymm (gsl_matrix * A, gsl_vector_complex * eval, gsl_eigen_nonsymm_workspace * w); int gsl_eigen_nonsymm_Z (gsl_matrix * A, gsl_vector_complex * eval, gsl_matrix * Z, gsl_eigen_nonsymm_workspace * w); typedef struct { size_t size; /* size of matrices */ gsl_vector *work; /* scratch workspace */ gsl_vector *work2; /* scratch workspace */ gsl_vector *work3; /* scratch workspace */ gsl_matrix *Z; /* pointer to Schur vectors */ gsl_eigen_nonsymm_workspace *nonsymm_workspace_p; } gsl_eigen_nonsymmv_workspace; gsl_eigen_nonsymmv_workspace * gsl_eigen_nonsymmv_alloc (const size_t n); void gsl_eigen_nonsymmv_free (gsl_eigen_nonsymmv_workspace * w); void gsl_eigen_nonsymmv_params (const int balance, gsl_eigen_nonsymmv_workspace *w); int gsl_eigen_nonsymmv (gsl_matrix * A, gsl_vector_complex * eval, gsl_matrix_complex * evec, gsl_eigen_nonsymmv_workspace * w); int gsl_eigen_nonsymmv_Z (gsl_matrix * A, gsl_vector_complex * eval, gsl_matrix_complex * evec, gsl_matrix * Z, gsl_eigen_nonsymmv_workspace * w); typedef struct { size_t size; /* size of matrices */ gsl_eigen_symm_workspace *symm_workspace_p; } gsl_eigen_gensymm_workspace; gsl_eigen_gensymm_workspace * gsl_eigen_gensymm_alloc (const size_t n); void gsl_eigen_gensymm_free (gsl_eigen_gensymm_workspace * w); int gsl_eigen_gensymm (gsl_matrix * A, gsl_matrix * B, gsl_vector * eval, gsl_eigen_gensymm_workspace * w); int gsl_eigen_gensymm_standardize (gsl_matrix * A, const gsl_matrix * B); typedef struct { size_t size; /* size of matrices */ gsl_eigen_symmv_workspace *symmv_workspace_p; } gsl_eigen_gensymmv_workspace; gsl_eigen_gensymmv_workspace * gsl_eigen_gensymmv_alloc (const size_t n); void gsl_eigen_gensymmv_free (gsl_eigen_gensymmv_workspace * w); int gsl_eigen_gensymmv (gsl_matrix * A, gsl_matrix * B, gsl_vector * eval, gsl_matrix * evec, gsl_eigen_gensymmv_workspace * w); typedef struct { size_t size; /* size of matrices */ gsl_eigen_herm_workspace *herm_workspace_p; } gsl_eigen_genherm_workspace; gsl_eigen_genherm_workspace * gsl_eigen_genherm_alloc (const size_t n); void gsl_eigen_genherm_free (gsl_eigen_genherm_workspace * w); int gsl_eigen_genherm (gsl_matrix_complex * A, gsl_matrix_complex * B, gsl_vector * eval, gsl_eigen_genherm_workspace * w); int gsl_eigen_genherm_standardize (gsl_matrix_complex * A, const gsl_matrix_complex * B); typedef struct { size_t size; /* size of matrices */ gsl_eigen_hermv_workspace *hermv_workspace_p; } gsl_eigen_genhermv_workspace; gsl_eigen_genhermv_workspace * gsl_eigen_genhermv_alloc (const size_t n); void gsl_eigen_genhermv_free (gsl_eigen_genhermv_workspace * w); int gsl_eigen_genhermv (gsl_matrix_complex * A, gsl_matrix_complex * B, gsl_vector * eval, gsl_matrix_complex * evec, gsl_eigen_genhermv_workspace * w); typedef struct { size_t size; /* size of matrices */ gsl_vector *work; /* scratch workspace */ size_t n_evals; /* number of eigenvalues found */ size_t max_iterations; /* maximum QZ iterations allowed */ size_t n_iter; /* number of iterations since last eigenvalue found */ double eshift; /* exceptional shift counter */ int needtop; /* need to compute top index? */ double atol; /* tolerance for splitting A matrix */ double btol; /* tolerance for splitting B matrix */ double ascale; /* scaling factor for shifts */ double bscale; /* scaling factor for shifts */ gsl_matrix *H; /* pointer to hessenberg matrix */ gsl_matrix *R; /* pointer to upper triangular matrix */ int compute_s; /* compute generalized Schur form S */ int compute_t; /* compute generalized Schur form T */ gsl_matrix *Q; /* pointer to left Schur vectors */ gsl_matrix *Z; /* pointer to right Schur vectors */ } gsl_eigen_gen_workspace; gsl_eigen_gen_workspace * gsl_eigen_gen_alloc (const size_t n); void gsl_eigen_gen_free (gsl_eigen_gen_workspace * w); void gsl_eigen_gen_params (const int compute_s, const int compute_t, const int balance, gsl_eigen_gen_workspace * w); int gsl_eigen_gen (gsl_matrix * A, gsl_matrix * B, gsl_vector_complex * alpha, gsl_vector * beta, gsl_eigen_gen_workspace * w); int gsl_eigen_gen_QZ (gsl_matrix * A, gsl_matrix * B, gsl_vector_complex * alpha, gsl_vector * beta, gsl_matrix * Q, gsl_matrix * Z, gsl_eigen_gen_workspace * w); typedef struct { size_t size; /* size of matrices */ gsl_vector *work1; /* 1-norm of columns of A */ gsl_vector *work2; /* 1-norm of columns of B */ gsl_vector *work3; /* real part of eigenvector */ gsl_vector *work4; /* imag part of eigenvector */ gsl_vector *work5; /* real part of back-transformed eigenvector */ gsl_vector *work6; /* imag part of back-transformed eigenvector */ gsl_matrix *Q; /* pointer to left Schur vectors */ gsl_matrix *Z; /* pointer to right Schur vectors */ gsl_eigen_gen_workspace *gen_workspace_p; } gsl_eigen_genv_workspace; gsl_eigen_genv_workspace * gsl_eigen_genv_alloc (const size_t n); void gsl_eigen_genv_free (gsl_eigen_genv_workspace * w); int gsl_eigen_genv (gsl_matrix * A, gsl_matrix * B, gsl_vector_complex * alpha, gsl_vector * beta, gsl_matrix_complex * evec, gsl_eigen_genv_workspace * w); int gsl_eigen_genv_QZ (gsl_matrix * A, gsl_matrix * B, gsl_vector_complex * alpha, gsl_vector * beta, gsl_matrix_complex * evec, gsl_matrix * Q, gsl_matrix * Z, gsl_eigen_genv_workspace * w); typedef enum { GSL_EIGEN_SORT_VAL_ASC, GSL_EIGEN_SORT_VAL_DESC, GSL_EIGEN_SORT_ABS_ASC, GSL_EIGEN_SORT_ABS_DESC } gsl_eigen_sort_t; /* Sort eigensystem results based on eigenvalues. * Sorts in order of increasing value or increasing * absolute value. * * exceptions: GSL_EBADLEN */ int gsl_eigen_symmv_sort(gsl_vector * eval, gsl_matrix * evec, gsl_eigen_sort_t sort_type); int gsl_eigen_hermv_sort(gsl_vector * eval, gsl_matrix_complex * evec, gsl_eigen_sort_t sort_type); int gsl_eigen_nonsymmv_sort(gsl_vector_complex * eval, gsl_matrix_complex * evec, gsl_eigen_sort_t sort_type); int gsl_eigen_gensymmv_sort (gsl_vector * eval, gsl_matrix * evec, gsl_eigen_sort_t sort_type); int gsl_eigen_genhermv_sort (gsl_vector * eval, gsl_matrix_complex * evec, gsl_eigen_sort_t sort_type); int gsl_eigen_genv_sort (gsl_vector_complex * alpha, gsl_vector * beta, gsl_matrix_complex * evec, gsl_eigen_sort_t sort_type); /* Prototypes for the schur module */ int gsl_schur_gen_eigvals(const gsl_matrix *A, const gsl_matrix *B, double *wr1, double *wr2, double *wi, double *scale1, double *scale2); int gsl_schur_solve_equation(double ca, const gsl_matrix *A, double z, double d1, double d2, const gsl_vector *b, gsl_vector *x, double *s, double *xnorm, double smin); int gsl_schur_solve_equation_z(double ca, const gsl_matrix *A, gsl_complex *z, double d1, double d2, const gsl_vector_complex *b, gsl_vector_complex *x, double *s, double *xnorm, double smin); /* The following functions are obsolete: */ /* Eigensolve by Jacobi Method * * The data in the matrix input is destroyed. * * exceptions: */ int gsl_eigen_jacobi(gsl_matrix * matrix, gsl_vector * eval, gsl_matrix * evec, unsigned int max_rot, unsigned int * nrot); /* Invert by Jacobi Method * * exceptions: */ int gsl_eigen_invert_jacobi(const gsl_matrix * matrix, gsl_matrix * ainv, unsigned int max_rot); __END_DECLS #endif /* __GSL_EIGEN_H__ */
{ "alphanum_fraction": 0.6586560193, "avg_line_length": 38.1436781609, "ext": "h", "hexsha": "146ebd23f5a04f9627603aaec2ef71ecfac9fefd", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "snipekill/FPGen", "max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_eigen.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "snipekill/FPGen", "max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_eigen.h", "max_line_length": 106, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "snipekill/FPGen", "max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_eigen.h", "max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z", "num_tokens": 3291, "size": 13274 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_math.h> #include <sys/stat.h> #include <sys/types.h> #include "allvars.h" #include "proto.h" #ifdef SUBFIND #include "fof.h" #include "subfind.h" /*! Structure for communication during the density computation. Holds data that is sent to other processors. */ static struct contamdata_in { MyDouble Pos[3]; MyFloat R200; int NodeList[NODELISTLENGTH]; } *ContamIn, *ContamGet; static struct contamdata_out { double ContaminationMass; int ContaminationLen; } *ContamResult, *ContamOut; void subfind_contamination(void) { int i, j, ndone, ndone_flag, dummy, count; int ngrp, sendTask, recvTask, place, nexport, nimport; struct unbind_data *d; d = (struct unbind_data *) mymalloc(NumPart * sizeof(struct unbind_data)); for(i = 0, count = 0; i < NumPart; i++) #ifdef DENSITY_SPLIT_BY_TYPE if(!((1 << P[i].Type) & (DENSITY_SPLIT_BY_TYPE))) #else if(!((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES))) #endif d[count++].index = i; force_treebuild(count, d); /* construct tree only with boundary particles */ myfree(d); /* allocate buffers to arrange communication */ All.BunchSize = (int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) + sizeof(struct contamdata_in) + sizeof(struct contamdata_out) + sizemax(sizeof(struct contamdata_in), sizeof(struct contamdata_out)))); DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index)); DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist)); /* we will repeat the whole thing for those groups where we didn't converge to a SO radius yet */ i = 0; /* begin with this index */ do { for(j = 0; j < NTask; j++) { Send_count[j] = 0; Exportflag[j] = -1; } /* do local particles and prepare export list */ for(nexport = 0; i < Ngroups; i++) { if(Group[i].R_Mean200 > 0) { if(subfind_contamination_evaluate(i, 0, &nexport, Send_count) < 0) break; } else { Group[i].ContaminationLen = 0; Group[i].ContaminationMass = 0; } } qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare); MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD); for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++) { Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask]; nimport += Recv_count[j]; if(j > 0) { Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1]; Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1]; } } ContamGet = (struct contamdata_in *) mymalloc(nimport * sizeof(struct contamdata_in)); ContamIn = (struct contamdata_in *) mymalloc(nexport * sizeof(struct contamdata_in)); /* prepare particle data for export */ for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; ContamIn[j].Pos[0] = Group[place].Pos[0]; ContamIn[j].Pos[1] = Group[place].Pos[1]; ContamIn[j].Pos[2] = Group[place].Pos[2]; ContamIn[j].R200 = Group[place].R_Mean200; memcpy(ContamIn[j].NodeList, DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int)); } /* exchange data */ for(ngrp = 1; ngrp < (1 << PTask); ngrp++) { sendTask = ThisTask; recvTask = ThisTask ^ ngrp; if(recvTask < NTask) { if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0) { /* get the data */ MPI_Sendrecv(&ContamIn[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct contamdata_in), MPI_BYTE, recvTask, TAG_DENS_A, &ContamGet[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct contamdata_in), MPI_BYTE, recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } myfree(ContamIn); ContamResult = (struct contamdata_out *) mymalloc(nimport * sizeof(struct contamdata_out)); ContamOut = (struct contamdata_out *) mymalloc(nexport * sizeof(struct contamdata_out)); /* now do the locations that were sent to us */ for(j = 0; j < nimport; j++) subfind_contamination_evaluate(j, 1, &dummy, &dummy); if(i >= Ngroups) ndone_flag = 1; else ndone_flag = 0; MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); /* get the result */ for(ngrp = 1; ngrp < (1 << PTask); ngrp++) { sendTask = ThisTask; recvTask = ThisTask ^ ngrp; if(recvTask < NTask) { if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0) { /* send the results */ MPI_Sendrecv(&ContamResult[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct contamdata_out), MPI_BYTE, recvTask, TAG_DENS_B, &ContamOut[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct contamdata_out), MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } /* add the result to the local particles */ for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; Group[place].ContaminationLen += ContamOut[j].ContaminationLen; Group[place].ContaminationMass += ContamOut[j].ContaminationMass; } myfree(ContamOut); myfree(ContamResult); myfree(ContamGet); } while(ndone < NTask); myfree(DataNodeList); myfree(DataIndexTable); } /*! This function represents the core of the SPH density computation. The * target particle may either be local, or reside in the communication * buffer. */ int subfind_contamination_evaluate(int target, int mode, int *nexport, int *nsend_local) { int startnode, listindex = 0; double h, mass, masssum; int count, countsum; MyDouble *pos; masssum = 0; countsum = 0; if(mode == 0) { pos = Group[target].Pos; h = Group[target].R_Mean200; } else { pos = ContamGet[target].Pos; h = ContamGet[target].R200; } if(mode == 0) { startnode = All.MaxPart; /* root node */ } else { startnode = ContamGet[target].NodeList[0]; startnode = Nodes[startnode].u.d.nextnode; /* open it */ } while(startnode >= 0) { while(startnode >= 0) { count = subfind_contamination_treefind(pos, h, target, &startnode, mode, nexport, nsend_local, &mass); if(count < 0) return -1; masssum += mass; countsum += count; } if(mode == 1) { listindex++; if(listindex < NODELISTLENGTH) { startnode = ContamGet[target].NodeList[listindex]; if(startnode >= 0) startnode = Nodes[startnode].u.d.nextnode; /* open it */ } } } if(mode == 0) { Group[target].ContaminationMass = masssum; Group[target].ContaminationLen = countsum; } else { ContamResult[target].ContaminationMass = masssum; ContamResult[target].ContaminationLen = countsum; } return 0; } int subfind_contamination_treefind(MyDouble searchcenter[3], MyFloat hsml, int target, int *startnode, int mode, int *nexport, int *nsend_local, double *Mass) { int no, p, task, nexport_save; struct NODE *current; double mass; int count; MyDouble dx, dy, dz, dist, r2; #ifdef PERIODIC MyDouble xtmp; #endif nexport_save = *nexport; mass = 0; count = 0; no = *startnode; while(no >= 0) { if(no < All.MaxPart) /* single particle */ { p = no; no = Nextnode[no]; dist = hsml; dx = NGB_PERIODIC_LONG_X(P[p].Pos[0] - searchcenter[0]); if(dx > dist) continue; dy = NGB_PERIODIC_LONG_Y(P[p].Pos[1] - searchcenter[1]); if(dy > dist) continue; dz = NGB_PERIODIC_LONG_Z(P[p].Pos[2] - searchcenter[2]); if(dz > dist) continue; if(dx * dx + dy * dy + dz * dz > dist * dist) continue; mass += P[p].Mass; count++; } else { if(no >= All.MaxPart + MaxNodes) /* pseudo particle */ { if(mode == 1) endrun(12312); if(mode == 0) { if(Exportflag[task = DomainTask[no - (All.MaxPart + MaxNodes)]] != target) { Exportflag[task] = target; Exportnodecount[task] = NODELISTLENGTH; } if(Exportnodecount[task] == NODELISTLENGTH) { if(*nexport >= All.BunchSize) { *nexport = nexport_save; if(nexport_save == 0) endrun(13005); /* in this case, the buffer is too small to process even a single particle */ for(task = 0; task < NTask; task++) nsend_local[task] = 0; for(no = 0; no < nexport_save; no++) nsend_local[DataIndexTable[no].Task]++; return -1; } Exportnodecount[task] = 0; Exportindex[task] = *nexport; DataIndexTable[*nexport].Task = task; DataIndexTable[*nexport].Index = target; DataIndexTable[*nexport].IndexGet = *nexport; *nexport = *nexport + 1; nsend_local[task]++; } DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]++] = DomainNodeIndex[no - (All.MaxPart + MaxNodes)]; if(Exportnodecount[task] < NODELISTLENGTH) DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]] = -1; } no = Nextnode[no - MaxNodes]; continue; } current = &Nodes[no]; if(mode == 1) { if(current->u.d.bitflags & (1 << BITFLAG_TOPLEVEL)) /* we reached a top-level node again, which means that we are done with the branch */ { *startnode = -1; *Mass = mass; return count; } } no = current->u.d.sibling; /* in case the node can be discarded */ dist = hsml + 0.5 * current->len;; dx = NGB_PERIODIC_LONG_X(current->center[0] - searchcenter[0]); if(dx > dist) continue; dy = NGB_PERIODIC_LONG_Y(current->center[1] - searchcenter[1]); if(dy > dist) continue; dz = NGB_PERIODIC_LONG_Z(current->center[2] - searchcenter[2]); if(dz > dist) continue; /* now test against the minimal sphere enclosing everything */ dist += FACT1 * current->len; if((r2 = (dx * dx + dy * dy + dz * dz)) > dist * dist) continue; no = current->u.d.nextnode; /* ok, we need to open the node */ } } *startnode = -1; *Mass = mass; return count; } #endif
{ "alphanum_fraction": 0.6221002984, "avg_line_length": 24.7357142857, "ext": "c", "hexsha": "4b761d5f8fdb1f112f1f46ea4f3e01da7d2193d2", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "egpbos/egp", "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_cont.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "egpbos/egp", "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_cont.c", "max_line_length": 144, "max_stars_count": null, "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "egpbos/egp", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_cont.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3105, "size": 10389 }
#ifndef _GENMAP_QUALITY_H_ #define _GENMAP_QUALITY_H_ #include <gslib.h> void printPartStat(long long *vtx, int nel, int nv, comm_ext ce); #endif
{ "alphanum_fraction": 0.7718120805, "avg_line_length": 16.5555555556, "ext": "h", "hexsha": "dc127097a66eecd178a51bd5777a7f7df1c46151", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-09-10T20:12:48.000Z", "max_forks_repo_forks_event_min_datetime": "2019-09-10T20:12:48.000Z", "max_forks_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "neams-th-coe/nekRS", "max_forks_repo_path": "3rd_party/nek5000_parRSB/src/genmap-quality.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb", "max_issues_repo_issues_event_max_datetime": "2021-08-24T04:47:42.000Z", "max_issues_repo_issues_event_min_datetime": "2021-06-27T02:07:27.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "neams-th-coe/nekRS", "max_issues_repo_path": "3rd_party/nek5000_parRSB/src/genmap-quality.h", "max_line_length": 65, "max_stars_count": 2, "max_stars_repo_head_hexsha": "ffc02bca33ece6ba3330c4ee24565b1c6b5f7242", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "RonRahaman/nekRS", "max_stars_repo_path": "3rd_party/nek5000_parRSB/src/genmap-quality.h", "max_stars_repo_stars_event_max_datetime": "2021-12-06T18:08:27.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-07T03:00:53.000Z", "num_tokens": 44, "size": 149 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_integration.h> /* GSL Integration Library */ #include "funs.c" /* Integration functions */ #include "timing_funs.h" /* Timing functions */ #define NMAX 100 int main(void) { /* Declaration and initialization */ int i; double vals1[NMAX+1], vals2[NMAX+1]; /*Uses functions declared in "funs.c" to compute I(n) using the recurrence and the generic integrator methods, and stores the results in their respective arrays.*/ integral_recur(0, 100, vals1); integral_gen(0, 100, vals2); /*Prints "n" and the result I(n) for each method above. The absolute error multiplied by a factor of 1.e9 is reported in the last column.*/ printf("n Recurrence Generic Scaled Abs Err\n"); for(i = 0; i <=NMAX; i++) { printf("%d %.8f %.8f %f\n", i, vals1[i], vals2[i], (fabs(vals1[i]-vals2[i]))*1.e9); } /* Define the intial number of counts, tmin, tmax*/ double time, trr, tgsl; int tmin = 1; int tmax = 2; int count = 1000; /* Computes the time per function call of the recurrence integration method. Calls the function integral_recur() "count" times and adjusts count until the total time is between 1 and 2 seconds.*/ printf("\n Timing for Recurrence Relation:\n"); do { timer_start (); for(i = 0; i < count; i++) { integral_recur(0, 100, vals1); } time = timer_stop (); trr = time /count; printf (" %10.2f usec %10.6f sec %10d\n",trr * 1.e6, time, count); count = adjust_rep_count (count, time, tmin, tmax); } while ((time >tmax) || (time <tmin)); /* Computes the time per function call of the GSL integrator method. Calls the function integral_gen() "count" times and adjusts count until the total time is between 1 and 2 seconds. */ printf("\n Timing for GSL Integrator:\n"); do { timer_start (); for(i = 0; i < count; i++) { integral_gen(0, 100, vals1); } time = timer_stop (); tgsl = time /count; printf (" %10.2f usec %10.6f sec %10d\n",tgsl * 1.e6, time, count); count = adjust_rep_count (count, time, tmin, tmax); } while ((time >tmax) || (time <tmin)); /*Prints time per function call for leibniz and bbp series, and then takes the ratio between the times to compare the relative speed*/ printf("\nTime per function call for Recur: %10.6f usec", trr*1.e6); printf("\nTime per function call for GSL: %10.6f usec", tgsl*1.e6); int ratio = round(tgsl/trr); printf("\nRatio of function times tgsl/trr: %d\n",ratio); }
{ "alphanum_fraction": 0.6434714621, "avg_line_length": 32.3797468354, "ext": "c", "hexsha": "2d17f17c08234a90c3af65754b765ef3094f1679", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "7846ce240e6c5460bd6da5d693cac645f4dc6ad9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "connor-occhialini/hw07", "max_forks_repo_path": "hw07.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "7846ce240e6c5460bd6da5d693cac645f4dc6ad9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "connor-occhialini/hw07", "max_issues_repo_path": "hw07.c", "max_line_length": 201, "max_stars_count": null, "max_stars_repo_head_hexsha": "7846ce240e6c5460bd6da5d693cac645f4dc6ad9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "connor-occhialini/hw07", "max_stars_repo_path": "hw07.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 787, "size": 2558 }
/* Copyright (c) 2011-2012, Jérémy Fix. All rights reserved. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions are met: */ /* * Redistributions of source code must retain the above copyright notice, */ /* this list of conditions and the following disclaimer. */ /* * Redistributions in binary form must reproduce the above copyright notice, */ /* this list of conditions and the following disclaimer in the documentation */ /* and/or other materials provided with the distribution. */ /* * None of the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. */ /* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE */ /* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL */ /* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR */ /* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */ /* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */ /* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */ /* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef UKF_PARAMETER_SCALAR_H #define UKF_PARAMETER_SCALAR_H #include <gsl/gsl_linalg.h> // For the Cholesky decomposition #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include "ukf_types.h" #include "ukf_math.h" namespace ukf { /** * @short UKF for parameter estimation. * The notations follow "Sigma-Point Kalman Filters for Probabilistic Inference in Dynamic State-Space Models",p93, PhD, van Der Merwe */ namespace parameter { /** * @short Allocation of the vectors/matrices and initialization * */ inline void ukf_scalar_init(ukf_param &p, ukf_scalar_state &s) { // Init the lambda p.lambda = p.alpha * p.alpha * (p.n + p.kpa) - p.n; p.gamma = sqrt(p.n + p.lambda); p.nbSamples = 2 * p.n + 1; // Init the matrices used to iterate s.Kk = gsl_vector_alloc(p.n); // Kalman gain gsl_vector_set_zero(s.Kk); s.Kk_mat = gsl_matrix_alloc(p.n,1); gsl_matrix_set_zero(s.Kk_mat); s.Kk_mat_T = gsl_matrix_alloc(1,p.n); gsl_matrix_set_zero(s.Kk_mat_T); s.Pwdk = gsl_vector_alloc(p.n); // Covariance of the parameters and output gsl_vector_set_zero(s.Pwdk); // Whatever the type of evolution noise, its covariance is set to evolution_noise s.Prrk = gsl_matrix_alloc(p.n,p.n); p.evolution_noise->init(p,s); s.Peek = p.observation_noise; // Covariance of the observation noise s.Pddk = 0.0; // Covariance of the output s.w = gsl_vector_alloc(p.n); // Parameter vector gsl_vector_set_zero(s.w); s.wk = gsl_vector_alloc(p.n); // Vector holding one sigma point gsl_vector_set_zero(s.wk); s.Pk = gsl_matrix_alloc(p.n,p.n); // Covariance matrix gsl_matrix_set_identity(s.Pk); gsl_matrix_scale(s.Pk,p.prior_pi); s.Sk = gsl_matrix_alloc(p.n,p.n); // Matrix holding the cholesky decomposition of Pk // Initialize Sk to the cholesky decomposition of Pk gsl_matrix_memcpy(s.Sk, s.Pk); gsl_linalg_cholesky_decomp(s.Sk); // Set all the elements of Lpi strictly above the diagonal to zero for(int k = 0 ; k < p.n ; k++) for(int j = 0 ; j < k ; j++) gsl_matrix_set(s.Sk,j,k,0.0); s.cSk = gsl_vector_alloc(p.n); // Vector holding one column of Lpi gsl_vector_set_zero(s.cSk); s.wm = gsl_vector_alloc(p.nbSamples); // Weights used to compute the mean of the sigma points images s.wc = gsl_vector_alloc(p.nbSamples); // Weights used to update the covariance matrices // Set the weights gsl_vector_set(s.wm, 0, p.lambda / (p.n + p.lambda)); gsl_vector_set(s.wc, 0, p.lambda / (p.n + p.lambda) + (1.0 - p.alpha*p.alpha + p.beta)); for(int j = 1 ; j < p.nbSamples; j ++) { gsl_vector_set(s.wm, j, 1.0 / (2.0 * (p.n + p.lambda))); gsl_vector_set(s.wc, j, 1.0 / (2.0 * (p.n + p.lambda))); } s.dk = gsl_vector_alloc(p.nbSamples); // Holds the image of the sigma points gsl_vector_set_zero(s.dk); s.d_mean = 0; // Holds the mean of the sigma points images s.sigmaPoints = gsl_matrix_alloc(p.n,p.nbSamples); // Holds the sigma points in the columns gsl_matrix_set_zero(s.sigmaPoints); s.temp_n = gsl_vector_alloc(p.n); gsl_vector_set_zero(s.temp_n); s.temp_n_n = gsl_matrix_alloc(p.n,p.n); gsl_matrix_set_zero(s.temp_n_n); } /** * @short Free of memory allocation * */ inline void ukf_scalar_free(ukf_param &p, ukf_scalar_state &s) { gsl_vector_free(s.Kk); gsl_matrix_free(s.Kk_mat); gsl_matrix_free(s.Kk_mat_T); gsl_vector_free(s.Pwdk); gsl_matrix_free(s.Prrk); gsl_vector_free(s.w); gsl_vector_free(s.wk); gsl_matrix_free(s.Pk); gsl_matrix_free(s.Sk); gsl_vector_free(s.cSk); gsl_vector_free(s.wm); gsl_vector_free(s.wc); gsl_vector_free(s.dk); gsl_matrix_free(s.sigmaPoints); gsl_vector_free(s.temp_n); gsl_matrix_free(s.temp_n_n); } /** * @short Iteration for UKF for parameter estimation, in case of a scalar output * */ template<typename GFUNC> void ukf_scalar_iterate(ukf_param &p, ukf_scalar_state &s, GFUNC g, gsl_vector * xk, double dk) { // Here, we implement the UKF for parameter estimation in the scalar case // The notations follow p93 of the PhD thesis of Van Der Merwe, "Sigma-Point Kalman Filters for Probabilistic Inference in Dynamic State-Space Models" // ************************************************** // // ************ Time update equations ************ // // ************************************************** // // Add the evolution noise to the parameter covariance Eq 3.137 gsl_matrix_add(s.Pk, s.Prrk); // ************************************************** // // ************ Compute the sigma points ************ // // ************************************************** // // Equations 3.138 // w_k^j = w_(k-1) <-- this is here denoted s.w // w_k^j = w_(k-1) + gamma Sk_j for 1 <= j <= n // w_k^j = w_(k-1) - gamma Sk_j for n+1 <= j <= 2n // Perform a cholesky decomposition of Pk gsl_matrix_memcpy(s.Sk, s.Pk); gsl_linalg_cholesky_decomp(s.Sk); // Set all the elements of Lpi strictly above the diagonal to zero for(int k = 0 ; k < p.n ; k++) for(int j = 0 ; j < k ; j++) gsl_matrix_set(s.Sk,j,k,0.0); gsl_matrix_set_col(s.sigmaPoints,0, s.w); for(int j = 1 ; j < p.n+1 ; ++j) for(int i = 0 ; i < p.n ; ++i) gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) + p.gamma * gsl_matrix_get(s.Sk,i,j-1)); for(int j = p.n+1 ; j < p.nbSamples ; ++j) for(int i = 0 ; i < p.n ; ++i) gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) - p.gamma * gsl_matrix_get(s.Sk,i,j-(p.n+1))); // ************************************************** // // ***** Compute the images of the sigma points ***** // // ************************************************** // // Compute the images of the sigma points // and the mean of the yj s.d_mean = 0.0; gsl_vector_set_zero(s.dk); for(int j = 0 ; j < p.nbSamples ; j++) { // Equation 3.139 gsl_matrix_get_col(s.wk, s.sigmaPoints,j); s.dk->data[j] = g(s.wk,xk); // Update the mean : y_mean = sum_[j=0..2n] wm_j y_j // Equation 3.140 s.d_mean += s.wm->data[j] * s.dk->data[j]; } // ************************************************** // // ************** Update the statistics ************* // // ************************************************** // gsl_vector_set_zero(s.Pwdk); // The covariance of the output is initialized with the observation noise covariance // Eq 3.142 s.Pddk = s.Peek; for(int j = 0 ; j < p.nbSamples ; j++) { // Eq 3.142 s.Pddk += s.wc->data[j] * gsl_pow_2(s.dk->data[j] - s.d_mean); // Eq 3.143 for(int i = 0 ; i < p.n ; ++i) { s.Pwdk->data[i] = s.Pwdk->data[i] + s.wc->data[j] * (gsl_matrix_get(s.sigmaPoints,i,j) - s.w->data[i]) * (s.dk->data[j] - s.d_mean) ; } } // ************************************************** // // ******* Kalman gain and parameters update ******** // // ************************************************** // //if(s.Pddk == 0.0) // printf("[Error] Output covariance is null !"); // May not occur as soon as the observation noise covariance is set != 0.0 // Eq. 3.144 for(int i = 0 ; i < p.n ; ++i) s.Kk->data[i] = s.Pwdk->data[i] / s.Pddk; // Eq 3.145 // wk = w_(k-1) + Kk * (dk - d_mean) s.ino_dk = dk - s.d_mean; for(int i = 0 ; i < p.n ; ++i) s.w->data[i] = s.w->data[i] + s.Kk->data[i] * s.ino_dk; // Eq. 3.146 // Pk = P_(k-1) - Pddk . Kk Kk^T for(int i = 0 ; i < p.n ; ++i) { gsl_matrix_set(s.Kk_mat, i, 0, s.Kk->data[i]); gsl_matrix_set(s.Kk_mat_T, 0, i, s.Kk->data[i]); } gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,-s.Pddk, s.Kk_mat, s.Kk_mat_T,1.0,s.Pk); // Update of the evolution noise p.evolution_noise->updateEvolutionNoise(p,s); } /** * @short Evaluation of the output from the sigma points * */ void ukf_scalar_evaluate(ukf_param &p, ukf_scalar_state &s, double(*g)(gsl_vector*, gsl_vector*), gsl_vector * xk, double &dk) { // ************************************************** // // ************ Compute the sigma points ************ // // ************************************************** // // 1- Compute the cholesky decomposition of Pk gsl_matrix_memcpy(s.temp_n_n, s.Pk); gsl_linalg_cholesky_decomp(s.temp_n_n); // 2 - Set all the elements of Sk_temp strictly above the diagonal to zero for(int k = 0 ; k < p.n ; k++) for(int j = 0 ; j < k ; j++) gsl_matrix_set(s.temp_n_n,j,k,0.0); // Now Sk_temp is a lower triangular matrix containing the cholesky decomposition of Pk // 3- Compute the sigma points // Equations 3.138 // w_k^j = w_(k-1) <-- this is here denoted s.w // w_k^j = w_(k-1) + gamma Sk_j for 1 <= j <= n // w_k^j = w_(k-1) - gamma Sk_j for n+1 <= j <= 2n gsl_matrix_set_col(s.sigmaPoints,0, s.w); for(int j = 1 ; j < p.n+1 ; j++) for(int i = 0 ; i < p.n ; ++i) gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) + p.gamma * gsl_matrix_get(s.temp_n_n,i,j-1)); for(int j = p.n+1 ; j < p.nbSamples ; j++) for(int i = 0 ; i < p.n ; ++i) gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) - p.gamma * gsl_matrix_get(s.temp_n_n,i,j-(p.n+1))); // ************************************************** // // ***** Compute the images of the sigma points ***** // // ************************************************** // // Compute the images of the sigma points // and their mean dk = 0.0; for(int j = 0 ; j < p.nbSamples ; j++) { gsl_matrix_get_col(s.wk, s.sigmaPoints,j); // Update the mean : d_mean = sum_[j=0..2n] w_j y_j dk += gsl_vector_get(s.wm,j) * g(s.wk,xk); } } } // parameter } // ukf #endif // UKF_PARAMETER_SCALAR_H
{ "alphanum_fraction": 0.5034231284, "avg_line_length": 41.8629283489, "ext": "h", "hexsha": "f4dec0256622722ba4b754035e7cad8123d1f2f7", "lang": "C", "max_forks_count": 52, "max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z", "max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z", "max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "bahia14/C-Kalman-filtering", "max_forks_repo_path": "src/ukf_parameter_scalar.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z", "max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "bahia14/C-Kalman-filtering", "max_issues_repo_path": "src/ukf_parameter_scalar.h", "max_line_length": 162, "max_stars_count": 101, "max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "bahia14/C-Kalman-filtering", "max_stars_repo_path": "src/ukf_parameter_scalar.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z", "num_tokens": 3313, "size": 13438 }
// The MIT License (MIT) // // Copyright (c) 2018 Mateusz Pusz // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <gsl/gsl-lite.hpp> #include <units/bits/constexpr_math.h> #include <units/bits/math_concepts.h> #include <units/bits/pow.h> #include <units/bits/ratio_maths.h> #include <cmath> namespace units::detail { template<std::intmax_t N, typename F> requires gt_zero<N> [[nodiscard]] constexpr std::intmax_t iroot_impl(std::intmax_t v, F const& pow_function) noexcept { if constexpr (N == 1) { return v; } else { gsl_Expects(v >= 0); if (v == 0) { return 0; } constexpr double exponent = 1.0 / static_cast<double>(N); const auto root = static_cast<std::intmax_t>(pow_function(static_cast<double>(v), exponent)); // integer roots may be truncated down by 1 or in even rarer cases up by 1 due to finite precision of pow and // exponent, check both cases if (v == pow_impl<N>(root + 1)) { return root + 1; } if (v < pow_impl<N>(root)) { return root - 1; } return root; } } // maximum v is std::numeric_limits<std::intmax_t>::max() which is the worst case for exp convergence // ExpOrder = 12 and Factor = 64 give a precision of about O(1e-15) for a wide range of 1 / N exponents // Factor = 32 needs quite a few more terms to converge // https://godbolt.org/z/odWq1o template<std::intmax_t N, std::size_t ExpOrder = 12, std::intmax_t Factor = 64> requires gt_zero<N> [[nodiscard]] constexpr std::intmax_t iroot_compile(std::intmax_t v) noexcept { return iroot_impl<N>(v, [](double x, double exponent) { return constexpr_pow<ExpOrder, Factor>(x, exponent); }); } template<std::intmax_t N> requires gt_zero<N> [[nodiscard]] std::intmax_t iroot_runtime(std::intmax_t v) noexcept { return iroot_impl<N>(v, [](double x, [[maybe_unused]] double exponent) { if constexpr (N == 2) { return std::sqrt(x); } else if constexpr (N == 3) { return std::cbrt(x); } else { return std::pow(x, exponent); } }); } template<std::intmax_t N> requires gt_zero<N> [[nodiscard]] constexpr std::intmax_t iroot(std::intmax_t v) noexcept { // compile time version is much slower, use faster version at runtime if (std::is_constant_evaluated()) { return iroot_compile<N>(v); } return iroot_runtime<N>(v); } } // namespace units::detail
{ "alphanum_fraction": 0.6994712103, "avg_line_length": 34.04, "ext": "h", "hexsha": "e718ef8a284f3238a9131b55d413b6c0a4db8546", "lang": "C", "max_forks_count": 70, "max_forks_repo_forks_event_max_datetime": "2022-03-24T01:57:29.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-14T01:04:22.000Z", "max_forks_repo_head_hexsha": "1d2b9205383f967e4d21df20ac2fd4168b6ff7a8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "HazardyKnusperkeks/units", "max_forks_repo_path": "src/core/include/units/bits/root.h", "max_issues_count": 283, "max_issues_repo_head_hexsha": "1d2b9205383f967e4d21df20ac2fd4168b6ff7a8", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:25:11.000Z", "max_issues_repo_issues_event_min_datetime": "2018-11-01T05:31:28.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "HazardyKnusperkeks/units", "max_issues_repo_path": "src/core/include/units/bits/root.h", "max_line_length": 114, "max_stars_count": 571, "max_stars_repo_head_hexsha": "1d2b9205383f967e4d21df20ac2fd4168b6ff7a8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "HazardyKnusperkeks/units", "max_stars_repo_path": "src/core/include/units/bits/root.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:53:22.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-17T14:57:59.000Z", "num_tokens": 897, "size": 3404 }
/* LAPACKE Example : Calling DGELS using col-major layout ===================================================== The program computes the solution to the system of linear equations with a square matrix A and multiple right-hand sides B, where A is the coefficient matrix and b is the right-hand side matrix: Description =========== In this example, we wish solve the least squares problem min_x || B - Ax || for two right-hand sides using the LAPACK routine DGELS. For input we will use the 5-by-3 matrix ( 1 1 1 ) ( 2 3 4 ) A = ( 3 5 2 ) ( 4 2 5 ) ( 5 4 3 ) and the 5-by-2 matrix ( -10 -3 ) ( 12 14 ) B = ( 14 12 ) ( 16 16 ) ( 18 16 ) We will first store the input matrix as a static C two-dimensional array, which is stored in col-major layout, and let LAPACKE handle the work space array allocation. The LAPACK base name for this function is gels, and we will use double precision (d), so the LAPACKE function name is LAPACKE_dgels. lda=5 and ldb=5. The output for each right hand side is stored in b as consecutive vectors of length 3. The correct answer for this problem is the 3-by-2 matrix ( 2 1 ) ( 1 1 ) ( 1 2 ) A complete C program for this example is given below. Note that when the arrays are passed to the LAPACK routine, they must be dereferenced, since LAPACK is expecting arrays of type double *, not double **. LAPACKE Interface ================= LAPACKE_dgels (col-major, high-level) Example Program Results -- LAPACKE Example routine (version 3.7.0) -- -- LAPACK is a software package provided by Univ. of Tennessee, -- -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- December 2016 */ /* Calling DGELS using col-major layout */ /* Includes */ #include <stdio.h> #include <lapacke.h> int main() { double A[5][3] = {{1,2,3},{4,5,1},{3,5,2},{4,1,4},{2,5,3}}; double b[5][2] = {{-10,12},{14,16},{18,-3},{14,12},{16,16}}; const lapack_int m = 5; const lapack_int n = 3; const lapack_int lda = 5; const lapack_int ldb = 5; const lapack_int nrhs = 2; printf("LAPACKE_dgels (col-major, high-level) Example Program Results\n" ); const lapack_int info = LAPACKE_dgels(LAPACK_COL_MAJOR,'N',m, n, nrhs, *A, lda, *b, ldb); printf( "Solution: %d %d %lf %d\n", n, nrhs, b[0][0], ldb); return info; }
{ "alphanum_fraction": 0.6061452514, "avg_line_length": 31.7215189873, "ext": "c", "hexsha": "2c1196f3630495d8bd91ae685cccdb238b50c3d7", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2021-02-27T20:52:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-06-25T20:49:58.000Z", "max_forks_repo_head_hexsha": "f6aeafd21b36f33599dae82605189817f8716219", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "nabbelbabbel/conan-lapack", "max_forks_repo_path": "test_package/test_package.c", "max_issues_count": 4, "max_issues_repo_head_hexsha": "f6aeafd21b36f33599dae82605189817f8716219", "max_issues_repo_issues_event_max_datetime": "2020-03-08T17:19:50.000Z", "max_issues_repo_issues_event_min_datetime": "2018-06-26T13:22:38.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "nabbelbabbel/conan-lapack", "max_issues_repo_path": "test_package/test_package.c", "max_line_length": 92, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f6aeafd21b36f33599dae82605189817f8716219", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "nabbelbabbel/conan-lapack", "max_stars_repo_path": "test_package/test_package.c", "max_stars_repo_stars_event_max_datetime": "2020-03-03T19:29:57.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-03T19:29:57.000Z", "num_tokens": 755, "size": 2506 }
#pragma once #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include <gsl\gsl> namespace Library { class RasterizerStates final { public: inline static winrt::com_ptr<ID3D11RasterizerState> BackCulling; inline static winrt::com_ptr<ID3D11RasterizerState> FrontCulling; inline static winrt::com_ptr<ID3D11RasterizerState> DisabledCulling; inline static winrt::com_ptr<ID3D11RasterizerState> Wireframe; static void Initialize(gsl::not_null<ID3D11Device*> direct3DDevice); static void Shutdown(); RasterizerStates() = delete; RasterizerStates(const RasterizerStates&) = delete; RasterizerStates& operator=(const RasterizerStates&) = delete; RasterizerStates(RasterizerStates&&) = delete; RasterizerStates& operator=(RasterizerStates&&) = delete; ~RasterizerStates() = default; }; }
{ "alphanum_fraction": 0.778319123, "avg_line_length": 29.3214285714, "ext": "h", "hexsha": "7e9b075a8b875476a3fabe343e09855bca1afdc3", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_path": "source/Library.Shared/RasterizerStates.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_path": "source/Library.Shared/RasterizerStates.h", "max_line_length": 70, "max_stars_count": null, "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_path": "source/Library.Shared/RasterizerStates.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 229, "size": 821 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_math.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_randist.h> #include <Python.h> static char module_docstring[] = "GSL Statistics module"; static char t_test_docstring[] = "Perform an independent samples t-test"; double t_test(const double *data1, int n1, const double *data2, int n2) { double mean1, mean2, var1, var2, num, sp, denom, t, dof, p; mean1 = gsl_stats_mean(data1, 1, n1); mean2 = gsl_stats_mean(data2, 1, n2); var1 = gsl_stats_variance(data1, 1, n1); var2 = gsl_stats_variance(data2, 1, n2); num = mean1 - mean2; sp = sqrt((((n1 - 1) * var1) + ((n2 - 1) * var2)) / (n1 + n2 - 2)); denom = sp * sqrt((1 / (double) n1) + (1 / (double) n2)); t = fabs(num / denom); dof = (double) n1 + n2 - 2; p = (1 - gsl_cdf_tdist_P(t, dof)) * 2; return p; } static double* PySequence_ToDoubleArray(PyObject* inp, int n) { // Allocate array double *out; out = malloc(n * sizeof(double)); for (int i = 0; i < n; i++) { PyObject *fitem; PyObject *item = PySequence_Fast_GET_ITEM(inp, i); if(!item) { Py_DECREF(inp); free(out); return NULL; } fitem = PyNumber_Float(item); if(!fitem) { Py_DECREF(inp); free(out); PyErr_SetString(PyExc_TypeError, "all items must be numbers"); return NULL; } out[i] = PyFloat_AS_DOUBLE(fitem); Py_DECREF(fitem); } return out; } static PyObject *t_test_py(PyObject *self, PyObject *args) { PyObject *inp1, *inp2; PyObject* data1; PyObject* data2; double *d1, *d2; int n1, n2; double res; if (!PyArg_ParseTuple(args, "OO", &inp1, &inp2)) return 0; data1 = PySequence_Fast(inp1, "argument must be iterable"); data2 = PySequence_Fast(inp2, "argument must be iterable"); n1 = PySequence_Fast_GET_SIZE(data1); n2 = PySequence_Fast_GET_SIZE(data2); d1 = PySequence_ToDoubleArray(data1, n1); d2 = PySequence_ToDoubleArray(data2, n2); Py_DECREF(data1); Py_DECREF(data2); res = t_test(d1, n1, d2, n2); free(d1); free(d2); return Py_BuildValue("d", res); } static PyMethodDef module_methods[] = { {"t_test_py", t_test_py, METH_VARARGS, t_test_docstring}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef gslstatsmodule = { PyModuleDef_HEAD_INIT, "gslstats", module_docstring, -1, module_methods, }; PyMODINIT_FUNC PyInit_gslstats(void) { Py_Initialize(); return PyModule_Create(&gslstatsmodule); }
{ "alphanum_fraction": 0.611090296, "avg_line_length": 26.1666666667, "ext": "c", "hexsha": "8fdbf7866560a425da33fe9a76a35c2298b7e260", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "96a89cf9ee32a074185ffce842a999975ba0de19", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kgoettler/python-c-ext", "max_forks_repo_path": "python-c-api/v1/gslstats.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "96a89cf9ee32a074185ffce842a999975ba0de19", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kgoettler/python-c-ext", "max_issues_repo_path": "python-c-api/v1/gslstats.c", "max_line_length": 74, "max_stars_count": null, "max_stars_repo_head_hexsha": "96a89cf9ee32a074185ffce842a999975ba0de19", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kgoettler/python-c-ext", "max_stars_repo_path": "python-c-api/v1/gslstats.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 813, "size": 2669 }
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <math.h> #include <float.h> #include <string.h> #include <mpi.h> #include "compearth.h" #include "parmt_mtsearch.h" #ifdef PARMT_USE_INTEL #include <mkl_lapacke.h> #include <mkl_cblas.h> #else #include <lapacke.h> #include <cblas.h> #endif #include "iscl/array/array.h" #include "iscl/memory/memory.h" /* int main_temp() { double *betas, *gammas, *kappas, *M0s, *mts, *sigmas, *thetas; int i, ierr, nmt; const int ng = 29; const int nb = 29; const int nk = 6; const int ns = 6; const int nt = 6; const int nm = 1; const int ldm = 8; const double oneDeg = M_PI/180.0; const double betaMin = 0.0 + oneDeg; const double betaMax = M_PI - oneDeg; const double gammaMin =-M_PI/6.0 + oneDeg; const double gammaMax = M_PI/6.0 - oneDeg; const double kappaMin = 0.0 + oneDeg; const double kappaMax = 2.0*M_PI - oneDeg; const double thetaMin = 0.0 + oneDeg; const double thetaMax = 0.5*M_PI - oneDeg; const double sigmaMin =-0.5*M_PI + oneDeg; const double sigmaMax = 0.5*M_PI - oneDeg; nmt = nm*nb*ng*nk*ns*nt; mts = memory_calloc64f(nmt*ldm); //(double *)calloc((size_t) (nmt*ldm), sizeof(double)); M0s = memory_calloc64f(nm); //(double *)calloc((size_t) nm, sizeof(double)); betas = memory_calloc64f(nb); //(double *)calloc((size_t) nb, sizeof(double)); gammas = memory_calloc64f(ng); //(double *)calloc((size_t) ng, sizeof(double)); kappas = memory_calloc64f(nk); //(double *)calloc((size_t) nk, sizeof(double)); sigmas = memory_calloc64f(ns); //(double *)calloc((size_t) ns, sizeof(double)); thetas = memory_calloc64f(nt); //(double *)calloc((size_t) nt, sizeof(double)); ierr = array_linspace64f_work(1.0/sqrt(2.0), 1.0/sqrt(2.0), nm, M0s); ierr = array_linspace64f_work(betaMin+0.001, betaMax-0.001, nb, betas); ierr = array_linspace64f_work(gammaMin, gammaMax, ng, gammas); ierr = array_linspace64f_work(kappaMin, kappaMax, nk, kappas); ierr = array_linspace64f_work(thetaMin, thetaMax, nt, thetas); ierr = array_linspace64f_work(sigmaMin, sigmaMax, ns, sigmas); // avoid warnings on theta in tt2cmt ierr = gridSearch_discretizeMT64f(ng, gammas, nb, betas, nm, M0s, nk, kappas, nt, thetas, ns, sigmas, ldm, nmt, mts); double Mdc[6], lam[3], U[6], theta; compearth_tt2cmt(0.0, 0.0, 1./sqrt(2.), 0.0, 0.1, 0.0, Mdc, lam, U); FILE *ofl = fopen("mts.txt", "w"); for (i=0; i<nmt; i++) { compearth_angleMT(1, Mdc, &mts[ldm*i], &theta); fprintf(ofl, "%f %f %f %f %f %f %f\n", //i+1, mts[ldm*i+0], mts[ldm*i+1], mts[ldm*i+2], mts[ldm*i+3], mts[ldm*i+4], mts[ldm*i+5], theta); } fclose(ofl); free(mts); free(M0s); free(betas); free(gammas); free(kappas); free(sigmas); free(thetas); return 0; } */ //============================================================================// /*! * @brief Provides a cell based discretization of the moment tensor space. * * @param[in] nb Number of colatitudes. * @param[in] betaLower Lower colatitude in grid search [0, betaUpper). * @param[in] betaUpper Upper colatitude in grid search (betaLower, pi]. * @param[in] ng Number of longitudes. * @param[in] gammaLower Lower longitude in grid search [-pi/6, gammaUpper). * @param[in] gammaUpper Upper longitude in grid search (gammaLower, pi/6]. * @param[in] nk Number of strikes in grid search. * @param[in] kappaLower Lower strike in grid search [0, kappaUpper). * @param[in] kappaUpper Upper strike in grid search (kappaLower, 2*pi]. * @param[in] ns Number of slips in grid search. * @param[in] sigmaLower Lower slip angle in grid search [-pi, sigmaUpper). * @param[in] sigmaUpper Upper slip angle in grid search (sigmaUpper, pi]. * @param[in] nt Number of dips in grid search. * @param[in] thetaLower Lower dip in grid search [0,dipUpper). * @param[in] thetaUpper Upper dip in grid search (dipLower, pi/2]. * @param[in] nm Number of magnitudes. * @param[in] m0Lower Lower scalar moment in grid search (Newton-meters). * @param[in] m0Upper Upper scalar moment in grid search (Newton-meters). * @param[in] luseLog If true then the the scalar moments will be * discretized on a log scale. * * @param[out] betas Colatitudes (radians) at cell centers [nb]. * @param[out] gammas Longitudes (radians) at cell centers [ng]. * @param[out] kappas Strike angles (radians) at cell centers [nk]. * @param[out] sigmas Slip angles (radians) at cell centers [ns]. * @param[out] thetas Dip angles (radians) at cell centers [nt]. * @param[out] M0s Scalar moments (Newton-meters) in grid search [nm]. * * @author Ben Baker * * @copyright ISTI distributed under Apache 2 * */ int parmt_discretizeCells64f( const int nb, const double betaLower, const double betaUpper, const int ng, const double gammaLower, const double gammaUpper, const int nk, const double kappaLower, const double kappaUpper, const int ns, const double sigmaLower, const double sigmaUpper, const int nt, const double thetaLower, const double thetaUpper, const int nm, const double m0Lower, const double m0Upper, const bool luseLog, double **betas, double **gammas, double **kappas, double **sigmas, double **thetas, double **M0s) { const char *fcnm = "parmt_discretizeCells64f\0"; double *mwl, *u, *v, *h; double du, du2, dv, dv2, dh, dh2, dk, dk2, ds, ds2, hLower, hUpper, mwll, mwul, uLower, uUpper, vLower, vUpper; int ierr; const double two = 2.0; // Initialize and do some basic error checks u = NULL; v = NULL; h = NULL; if (nb < 1 || ng < 1 || nk < 1 || ns < 1 || nt < 1 || nm < 1) { if (nb < 1){printf("%s: no betas\n", fcnm);} if (ng < 1){printf("%s: no gammas\n", fcnm);} if (nk < 1){printf("%s: no kappas\n", fcnm);} if (ns < 1){printf("%s: no sigmas\n", fcnm);} if (nt < 1){printf("%s: no thetas\n", fcnm);} if (nm < 1){printf("%s: no magnitudes\n", fcnm);} return -1; } // Discretize the moment tensor space in (u, v, h) space compearth_beta2u(1, &betaLower, &uLower); compearth_beta2u(1, &betaUpper, &uUpper); compearth_gamma2v(1, &gammaLower, &vLower); compearth_gamma2v(1, &gammaUpper, &vUpper); compearth_theta2h(1, &thetaLower, &hLower); compearth_theta2h(1, &thetaUpper, &hUpper); du = (uUpper - uLower)/(double) nb; dv = (vUpper - vLower)/(double) ng; dh =-(hUpper - hLower)/(double) nt; // negative sign makes +theta increasing dk = (kappaUpper - kappaLower)/(double) nk; ds = (sigmaUpper - sigmaLower)/(double) ns; du2 = du/two; dv2 = dv/two; dh2 = dh/two; u = array_linspace64f(uLower+du2, uUpper-du2, nb, &ierr); v = array_linspace64f(vLower+dv2, vUpper-dv2, ng, &ierr); h = array_linspace64f(hLower-dh2, hUpper+dh2, nt, &ierr); *betas = memory_calloc64f(nb); *gammas = memory_calloc64f(ng); *thetas = memory_calloc64f(nt); //compearth_u2beta(nb, 20, 2, u, 1.e-6, *betas); compearth_u2beta(nb, u, *betas); compearth_v2gamma(ng, v, *gammas); compearth_h2theta(nt, h, *thetas); // discretize the magnitudes, kappa, and sigma dk2 = dk/two; ds2 = ds/two; if (!luseLog || nm == 1) { *M0s = array_linspace64f(m0Lower, m0Upper, nm, &ierr); } else { // TODO: I doubt this is correct because I don't understand how // lune volumes map to `spherical volumes'. For simplicity I'll // use a shell but I think I should be looking at the `active // area' of the beta and gamma grid search. In the interim I'll // use the volume of a spherical shell which is given by // \frac{4 \pi R^3}{3} where R is the radius (magnitude). // To get some form of uniform volume spacing I'll take the log // at the upper and lower limit and discretize evenly in logspace // then come back to M0. /* m0ll = 3.0*log(4.0*M_PI*m0Lower/3.0); m0ul = 3.0*log(4.0*M_PI*m0Upper/3.0); m0l = array_linspace64f(m0ll, m0ul, nm, &ierr); // Now solve for m0: 3/(4*pi)*exp(m0l/3) cblas_dscal(nm, 1.0/3.0, m0l, 1); // m0l = m0l/3 *M0s = array_exp64f(nm, m0l, &ierr); // *M0 = exp(m0l/3) cblas_dscal(nm, 3.0/(4.0*M_PI), *M0s, 1); // *M0 = 3/(4*pi)exp(m0l/3) memory_free64f(&m0l); */ // TODO: An alternative to doing math is just discretizing on a // the magnitude scale compearth_m02mw(1, CE_KANAMORI_1978, &m0Lower, &mwll); compearth_m02mw(1, CE_KANAMORI_1978, &m0Upper, &mwul); mwl = array_linspace64f(mwll, mwul, nm, &ierr); *M0s = memory_calloc64f(nm); ierr = compearth_mw2m0(nm, CE_KANAMORI_1978, mwl, *M0s); memory_free64f(&mwl); } *kappas = array_linspace64f(kappaLower+dk2, kappaUpper-dk2, nk, &ierr); *sigmas = array_linspace64f(sigmaLower+ds2, sigmaUpper-ds2, ns, &ierr); memory_free64f(&u); memory_free64f(&v); memory_free64f(&h); return ierr; } //============================================================================// /*! * @brief Computes the moment tensors in the grid search. * The grid search ordering is: * Loop on magnitudes * Loop on colatitudes * Loop on longitudes * Loop on strikes * Loop on slips * Loop on dips * * @param[in] comm MPI communicator on which moment tensor will be split * @param[in] ng number of longitudes * @param[in] gammas longitudes (radians) on lune s.t. * \f$ \gamma \in [-\pi/6, \pi/6] \f$ [ng] * @param[in] nb number of colatitudes * @param[in] betas colatitudes (radians) on lune s.t. * \f$ \beta \in [0, \pi] \f$ [nb] * @param[in] nm number of scalar moments * @param[in] M0s scalar moments in Newton-meters [nm]. * for a `unit' moment tensor choose M0 = 1/sqrt(2) * @param[in] nk number of strike angles * @param[in] kappas strike angles (radians) s.t. * \f$ \kappa \in [0, 2\pi] \f$ [nk] * @param[in] nt number of dip angles * @param[in] thetas dips angles (radians) s.t. * \f$ \theta \in [0, \pi/2] \f$ [nt] * @param[in] ns number of slip angles * @param[in] sigmas slip angles (radians) s.t. * \f$ \sigma \in [-\pi/2, \pi/2] \f$ [ns] * @param[in] ldm leading dimension of mts. must be >= 6. * @param[in] nmt number of moment tensors (=nm*nb*ng*nk*ns*nt) * * @param[out] mts moment tensors (Newton-meters) in north,east,down s.t. * \f$ \textbf{m} * = \f$ \{m_{xx}, m_{yy}, m_{zz}, * m_{xy}, m_{xz}, m_{yz}\} \f$. * This has dimensions [nm*nb*ng*nk*ns*nt x ldm]. Observe * the ordering as defind above. * * @result 0 indicates success * * @author Ben Baker * * @copyright ISTI licensed under Apached 2 * */ int parmt_discretizeMT64f_MPI(const MPI_Comm comm, const int ng, const double *__restrict__ gammas, const int nb, const double *__restrict__ betas, const int nm, const double *__restrict__ M0s, const int nk, const double *__restrict__ kappas, const int nt, const double *__restrict__ thetas, const int ns, const double *__restrict__ sigmas, const int ldm, struct localMT_struct *mts) { const char *fcnm = "parmt_discretizeMT64f_MPI\0"; double *mtWork; int64_t nmt64; int *displ, *nmtProc, *offset, *sendCounts; int dmt, i, ierr, imt1, imt2, myid, nmtall, nmt, nprocs; const int master = 0; //------------------------------------------------------------------------// ierr = 0; MPI_Comm_size(comm, &nprocs); MPI_Comm_rank(comm, &myid); memset(mts, 0, sizeof(struct localMT_struct)); mts->comm = comm; // Check for integer overflow nmt64 = (int64_t) ng * (int64_t) nb * (int64_t) nm *(int64_t) nk * (int64_t) nt * (int64_t) ns; if (nmt64 > INT_MAX) { printf("%s: Error integer overflow - gridsearch too large\n", fcnm); return -1; } nmt = (int) nmt64; // Verify the inputs if (ldm < 6 || ng < 1 || nb < 1 || nm < 1 || nk < 1 || nt < 1 || ns < 1 || gammas == NULL || betas == NULL || M0s == NULL || kappas == NULL || thetas == NULL || sigmas == NULL) { if (ldm < 6){printf("%s: Invalid leading dimension\n", fcnm);} if (ng < 1){printf("%s: ng must be positive\n", fcnm);} if (nb < 1){printf("%s: nb must be positive\n", fcnm);} if (nm < 1){printf("%s: nm must be positive\n", fcnm);} if (nk < 1){printf("%s: nk must be positive\n", fcnm);} if (nt < 1){printf("%s: nt must be positive\n", fcnm);} if (ns < 1){printf("%s: ns must be positive\n", fcnm);} if (gammas == NULL){printf("%s: gammas is NULL\n", fcnm);} if (betas == NULL){printf("%s: betas is NULL\n", fcnm);} if (M0s == NULL){printf("%s: M0s is NULL\n", fcnm);} if (kappas == NULL){printf("%s: kappas is NULL\n", fcnm);} if (thetas == NULL){printf("%s: thetas is NULL\n", fcnm);} if (sigmas == NULL){printf("%s: sigmas is NULL\n", fcnm);} return -1; } // divide the moment tensor grid dmt = MAX(nmt/nprocs, 1); imt1 = myid*dmt; imt2 = (myid + 1)*dmt; if (myid == nprocs - 1){imt2 = nmt;} mts->nmt = imt2 - imt1; mts->ldm = ldm; MPI_Allreduce(&mts->nmt, &nmtall, 1, MPI_INTEGER, MPI_SUM, mts->comm); if (nmtall != nmt) { if (myid == master) { printf("%s: Failed to partition domain %d %d\n", fcnm, nmtall, nmt); } return -1; } // create the requisite information for an MPI_GATHER mts->nmtProc = memory_calloc32i(nprocs); mts->offset = memory_calloc32i(nprocs); nmtProc = memory_calloc32i(nprocs); offset = memory_calloc32i(nprocs); nmtProc[myid] = mts->nmt; offset[myid] = imt1; MPI_Allreduce(nmtProc, mts->nmtProc, nprocs, MPI_INTEGER, MPI_SUM, mts->comm); MPI_Allreduce(offset, mts->offset, nprocs, MPI_INTEGER, MPI_SUM, mts->comm); mts->commSize = nprocs; mts->nmtAll = nmtall; mts->myid = myid; memory_free32i(&nmtProc); memory_free32i(&offset); // have master process compute all mts and scatter them // TODO this should be parallel if (mts->myid == master) { mtWork = memory_calloc64f(mts->ldm*mts->nmtAll); ierr = parmt_discretizeMT64f(ng, gammas, nb, betas, nm, M0s, nk, kappas, nt, thetas, ns, sigmas, mts->ldm, mts->nmtAll, mtWork); } else { mtWork = memory_calloc64f(1); } MPI_Bcast(&ierr, 1, MPI_INT, master, mts->comm); if (mts->commSize > 1) { // figure out who gets what part of the moment tensor space sendCounts = memory_calloc32i(mts->commSize); displ = memory_calloc32i(mts->commSize); for (i=0; i<mts->commSize; i++) { sendCounts[i] = mts->nmtProc[i]*mts->ldm; displ[i] = mts->ldm*mts->offset[i]; } // set the memory and distribute it mts->mts = memory_calloc64f(mts->ldm*MAX(1,mts->nmt)); MPI_Scatterv(mtWork, sendCounts, displ, MPI_DOUBLE, mts->mts, mts->ldm*mts->nmt, MPI_DOUBLE, master, mts->comm); memory_free64f(&mtWork); } else { mts->mts = mtWork; } return ierr; } //============================================================================// /*! * @brief Computes the moment tensors in the grid search. * The grid search ordering is: * Loop on magnitudes * Loop on colatitudes * Loop on longitudes * Loop on strikes * Loop on slips * Loop on dips * * @param[in] ng number of longitudes * @param[in] gammas longitudes (radians) on lune s.t. * \f$ \gamma \in [-\pi/6, \pi/6] \f$ [ng] * @param[in] nb number of colatitudes * @param[in] betas colatitudes (radians) on lune s.t. * \f$ \beta \in [0, \pi] \f$ [nb] * @param[in] nm number of scalar moments * @param[in] M0s scalar moments in Newton-meters [nm]. * for a `unit' moment tensor choose M0 = 1/sqrt(2) * @param[in] nk number of strike angles * @param[in] kappas strike angles (radians) s.t. * \f$ \kappa \in [0, 2\pi] \f$ [nk] * @param[in] nt number of dip angles * @param[in] thetas dips angles (radians) s.t. * \f$ \theta \in [0, \pi/2] \f$ [nt] * @param[in] ns number of slip angles * @param[in] sigmas slip angles (radians) s.t. * \f$ \sigma \in [-\pi/2, \pi/2] \f$ [ns] * @param[in] ldm leading dimension of mts. must be >= 6. * @param[in] nmt number of moment tensors (=nm*nb*ng*nk*ns*nt) * * @param[out] mts moment tensors (Newton-meters) in north,east,down s.t. * \f$ \textbf{m} * = \f$ \{m_{xx}, m_{yy}, m_{zz}, * m_{xy}, m_{xz}, m_{yz}\} \f$. * This has dimensions [nm*nb*ng*nk*ns*nt x ldm]. Observe * the ordering as defind above. * * @result 0 indicates success * * @author Ben Baker * * @copyright ISTI licensed under Apached 2 * */ int parmt_discretizeMT64f(const int ng, const double *__restrict__ gammas, const int nb, const double *__restrict__ betas, const int nm, const double *__restrict__ M0s, const int nk, const double *__restrict__ kappas, const int nt, const double *__restrict__ thetas, const int ns, const double *__restrict__ sigmas, const int ldm, const int nmt, double *__restrict__ mts) { const char *fcnm = "parmt_discretizeMT64f\0"; double lam[3], Muse[6], U[9] __attribute__ ((aligned (64))); double *mtWork, deltaDeg, gammaDeg, kappaDeg, sigmaDeg, thetaDeg; int i, ierr, ierr1, ib, ig, indx, im, imt, ik, is, it, nmtBase; const double M01[1] = {1.0}; const double pi180i = 180.0/M_PI; const double betaMin = 0.0; const double betaMax = M_PI; const double gammaMin =-M_PI/6.0; const double gammaMax = M_PI/6.0; const double kappaMin = 0.0; const double kappaMax = 2.0*M_PI; const double thetaMin = 0.0; const double thetaMax = M_PI_2; const double sigmaMin =-M_PI_2; const double sigmaMax = M_PI_2; //const double sqrt2i = 1.0/sqrt(2.0); // unit magnitude MT //------------------------------------------------------------------------// ierr = 0; // Verify the inputs if (ldm < 6 || ng < 1 || nb < 1 || nm < 1 || nk < 1 || nt < 1 || ns < 1 || nmt != ng*nb*nm*nk*nt*ns || gammas == NULL || betas == NULL || M0s == NULL || kappas == NULL || thetas == NULL || sigmas == NULL) { if (ldm < 6){printf("%s: Invalid leading dimension\n", fcnm);} if (ng < 1){printf("%s: ng must be positive\n", fcnm);} if (nb < 1){printf("%s: nb must be positive\n", fcnm);} if (nm < 1){printf("%s: nm must be positive\n", fcnm);} if (nk < 1){printf("%s: nk must be positive\n", fcnm);} if (nt < 1){printf("%s: nt must be positive\n", fcnm);} if (ns < 1){printf("%s: ns must be positive\n", fcnm);} if (nmt != ng*nb*nm*nk*nt*ns) { printf("%s: nmt != ng*nb*nm*nk*nt*ns %d %d\n", fcnm, nmt, ng*nb*nm*nk*nt*ns); } if (gammas == NULL){printf("%s: gammas is NULL\n", fcnm);} if (betas == NULL){printf("%s: betas is NULL\n", fcnm);} if (M0s == NULL){printf("%s: M0s is NULL\n", fcnm);} if (kappas == NULL){printf("%s: kappas is NULL\n", fcnm);} if (thetas == NULL){printf("%s: thetas is NULL\n", fcnm);} if (sigmas == NULL){printf("%s: sigmas is NULL\n", fcnm);} return -1; } for (i=0; i<ng; i++) { if (gammas[i] < gammaMin || gammas[i] > gammaMax) { printf("%s: gammas %f out or range [%f,%f]\n", fcnm, gammas[i], gammaMin, gammaMax); return -1; } } for (i=0; i<nb; i++) { if (betas[i] < betaMin || betas[i] > betaMax) { printf("%s: betas %f out or range [%f,%f]\n", fcnm, betas[i], betaMin, betaMax); return -1; } } for (i=0; i<nk; i++) { if (kappas[i] < kappaMin || kappas[i] > kappaMax) { printf("%s: kappas %f out or range [%f,%f]\n", fcnm, kappas[i], kappaMin, kappaMax); return -1; } } for (i=0; i<nt; i++) { if (thetas[i] < thetaMin || thetas[i] > thetaMax) { printf("%s: thetas %f out or range [%f,%f]\n", fcnm, thetas[i], thetaMin, thetaMax); return -1; } } for (i=0; i<ns; i++) { if (sigmas[i] < sigmaMin || sigmas[i] > sigmaMax) { printf("%s: sigmas %f out or range [%f,%f]\n", fcnm, sigmas[i], sigmaMin, sigmaMax); return -1; } } // The moment tensors are equivalent up to a scaling factor - so compute // the unit moment tensor nmtBase = nb*ng*nk*ns*nt; if (nm == 1) { mtWork = mts; } else { mtWork = memory_calloc64f(nmtBase*ldm); } #ifdef _OPENMP #pragma omp parallel for collapse(5) \ firstprivate (lam, M01, Muse, U) \ private (deltaDeg, gammaDeg, kappaDeg, \ sigmaDeg, thetaDeg, ierr1, imt, ib, ig, ik, is, it) \ shared (fcnm, M0s, betas, gammas, kappas, sigmas, mtWork, thetas) \ reduction (max:ierr) \ default (none) #endif // Loop on colatitudes for (ib=0; ib<nb; ib++) { // Loop on longitudes for (ig=0; ig<ng; ig++) { // Loop on strike for (ik=0; ik<nk; ik++) { // Loop on slip for (is=0; is<ns; is++) { // Loop on dip for (it=0; it<nt; it++) { // tape**2 space term //M0 = sqrt2i; deltaDeg = (M_PI/2.0 - betas[ib])*pi180i; gammaDeg = gammas[ig]*pi180i; kappaDeg = kappas[ik]*pi180i; sigmaDeg = sigmas[is]*pi180i; thetaDeg = thetas[it]*pi180i; // index imt = ib*ng*nk*ns*nt + ig*nk*ns*nt + ik*ns*nt + is*nt + it; // Compute the corresponding moment tensor. // Silver and Jordan compute M0 = 1/sqrt(2)norm(M) // hence, if it is the scalar moment computation // that handles the 1/sqrt(2) which means I should // use unity here. This has been verified b/c // apply CMT2m0 on this moment tensor will yield // the input M0. ierr1 = compearth_TT2CMT(1, &gammaDeg, &deltaDeg, M01, &kappaDeg, &thetaDeg, &sigmaDeg, Muse, lam, U); /* ierr1 = compearth_tt2cmt(gammaDeg, deltaDeg, 1.0, //sqrt2i, kappaDeg, thetaDeg, sigmaDeg, Muse, lam, U); */ // Convert from USE to our NED estimation basis ierr1 = compearth_convertMT(1, CE_USE, CE_NED, Muse, &mtWork[imt*ldm]); if (ierr1 != 0) { printf("%s: Error changing coords\n", fcnm); ierr = ierr + 1; continue; } } // loop on dip } // loop on slip } // loop on strike } // loop on longitudes } // loop on latitudes if (ierr != 0) { printf("%s: Errors during mt computation\n", fcnm); ierr = 1; } // Now copy all moment tensors over if (nm == 1) { cblas_dscal(ldm*nmtBase, M0s[0], mtWork, 1); } else { for (im=0; im<nm; im++) { indx = im*nmtBase*ldm; //nb*ng*nk*ns*nt; for (imt=0; imt<ldm*nmtBase; imt++) { mts[indx+imt] = M0s[im]*mtWork[imt]; } } memory_free64f(&mtWork); } mtWork = NULL; return ierr; }
{ "alphanum_fraction": 0.5156055402, "avg_line_length": 40.2689969605, "ext": "c", "hexsha": "6d46d24907184aa6ccb517c68bd0d847a59546f9", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": [ "Intel" ], "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_path": "src/discretizeMT.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Intel" ], "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_path": "src/discretizeMT.c", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": [ "Intel" ], "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_path": "src/discretizeMT.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7991, "size": 26497 }
#ifndef __GSL_BLOCK_H__ #define __GSL_BLOCK_H__ #include <gsl/block/gsl_block_double.h> #endif /* __GSL_BLOCK_H__ */
{ "alphanum_fraction": 0.7899159664, "avg_line_length": 17, "ext": "h", "hexsha": "b1e1e2ab1f7a655df9ada523c9bfd6d7ad3075c9", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/block/gsl_block.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/block/gsl_block.h", "max_line_length": 39, "max_stars_count": null, "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/block/gsl_block.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 34, "size": 119 }
#include <stdio.h> #include <math.h> #include "wf.h" #include "alphas.h" #include "glasma.h" #include <gsl/gsl_integration.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> //workspace and global variables for integration static double abserr = 1.e-200; static double relerr = 1.e-20; double phiKernel(double x, void *params); static double result,error; static size_t neval; static gsl_function phiIntKernel; double d2Nglasma0(double pT, double qT, double phipq, double yp, double yq, double rts) { static struct glasma_params params; params.pT = pT; params.qT = qT; params.yp = yp; params.yq = yq; params.rts = rts; params.phipq = phipq; phiIntKernel.function = &phiKernel; (params.Kernel).function = &doubleKernel; phiIntKernel.params = &params; gsl_integration_qng(&phiIntKernel, -M_PI, M_PI, abserr, relerr,\ &result, &error, &neval); double norm = (Nc*Nc)/gsl_pow_3(Nc*Nc-1.)/(4.*pow(M_PI,10.))/gsl_pow_2(pT* qT)*alpha(pT)*alpha(qT); return norm*result; } double d2Nglasma1(double pT, double yp, double yq, double rts) { double sinres, cosres; static struct glasma_params params; params.pT = pT; params.yp = yp; params.yq = yq; params.rts = rts; phiIntKernel.function = &phiKernel; (params.Kernel).function = &cosKernel; phiIntKernel.params = &params; gsl_integration_qng(&phiIntKernel, -M_PI, M_PI, abserr, relerr, &cosres, &error, &neval); (params.Kernel).function = &sinKernel; phiIntKernel.params = &params; gsl_integration_qng(&phiIntKernel, -M_PI, M_PI, abserr, relerr, &sinres, &error, &neval); double norm = (Nc*Nc)/gsl_pow_3(Nc*Nc-1.)/(4.*pow(M_PI,10.))/gsl_pow_2(pT*pT)*alpha(pT)*alpha(pT) ; return norm*(cosres*cosres + sinres*sinres); } double doubleKernel(double x, void *p) { struct glasma_params params = *(struct glasma_params *)p; double rts = params.rts; double pT, qT, yp, yq; double x1p, x2p, x1q, x2q, x1max, x2max; double phi = params.phi; double phipq = params.phipq; double kT = x; pT = params.pT; qT = params.qT; yp = params.yp; yq = params.yq; x1p = pT/rts*exp(+yp); x2p = pT/rts*exp(-yp); x1q = qT/rts*exp(+yq); x2q = qT/rts*exp(-yq); x1max = gsl_max(x1p,x1q); x2max = gsl_max(x2p,x2q); double qTmkT = sqrt( qT*qT + kT*kT - 2.0*qT*kT*cos(phipq-phi) ); double qTpkT = sqrt( qT*qT + kT*kT + 2.0*qT*kT*cos(phipq-phi) ); double pTmkT = sqrt( pT*pT + kT*kT - 2.0*pT*kT*cos(phi) ); double pTpkT = sqrt( pT*pT + kT*kT + 2.0*pT*kT*cos(phi) ); double pTmkTmqT = sqrt( pT*pT + kT*kT + qT*qT \ -2.0*pT*qT*cos(phipq) \ -2.0*pT*kT*cos(phi) \ +2.0*qT*kT*cos(phipq-phi)\ ); double pTmkTpqT = sqrt( pT*pT + kT*kT + qT*qT \ +2.0*pT*qT*cos(phipq) \ -2.0*pT*kT*cos(phi) \ -2.0*qT*kT*cos(phipq-phi)\ ); //diagram A & E //this factor of 0.5 is from //symmetrizing wrt pTmkT double AE = 0.5*kT*pow(wf(1,x1max,kT),2.0)\ *( wf(2,x2p,pTmkT) + wf(2,x2p,pTpkT) )\ *( wf(2,x2q,qTmkT) + wf(2,x2q,qTpkT) ); //diagram B & F double BF = 0.5*kT*pow(wf(2,x2max,kT),2.0)\ *( wf(1,x1p,pTmkT) + wf(1,x1p,pTpkT) )\ *( wf(1,x1q,qTmkT) + wf(1,x1q,qTpkT) ); double T1D, T2D, T1H, T2H, denD, denH; T1D = ( kT*pT*cos(phi)-kT*kT )\ *( pT*pT - pT*qT*cos(phipq) - pT*kT*cos(phi) - pow(pTmkTmqT,2.0) ) \ - (pT*kT*sin(phi))*(pT*qT*sin(phipq) + pT*kT*sin(phi) ); T1H = ( kT*pT*cos(phi)-kT*kT )\ *( pT*pT + pT*qT*cos(phipq) - pT*kT*cos(phi) - pow(pTmkTpqT,2.0) ) \ - (pT*kT*sin(phi))*(-pT*qT*sin(phipq) + pT*kT*sin(phi) ); T2D = ( kT*qT*cos(phipq-phi)+kT*kT )\ *( -qT*qT + pT*qT*cos(phipq) - qT*kT*cos(phipq-phi) + pow(pTmkTmqT,2.0) ) \ + (qT*kT*sin(phipq-phi))*(pT*qT*sin(phipq) - qT*kT*sin(phipq-phi) ); T2H = ( -kT*qT*cos(phipq-phi)+kT*kT )\ *( -qT*qT - pT*qT*cos(phipq) + qT*kT*cos(phipq-phi) + pow(pTmkTpqT,2.0) ) \ + (qT*kT*sin(phipq-phi))*(pT*qT*sin(phipq) - qT*kT*sin(phipq-phi) ); denD = pow(kT*pTmkTmqT*pTmkT*qTpkT,2.0); denH = pow(kT*pTmkTpqT*pTmkT*qTmkT,2.0); //this factor of 0.5 is from the different f^4\delta^4 structure double D = 0.5*kT*T1D*T2D/denD\ *wf(1,x1max,kT)*wf(1,x1max,pTmkTmqT)*wf(2,x2max,pTmkT)*wf(2,x2max,qTpkT); double H = 0.5*kT*T1H*T2H/denH\ *wf(1,x1max,kT)*wf(1,x1max,pTmkTpqT)*wf(2,x2max,pTmkT)*wf(2,x2max,qTmkT); return (AE + BF + D + H); } double cosKernel(double x, void *p) { struct glasma_params params = *(struct glasma_params *)p; double rts = params.rts; double pT, yp, yq; double x1p, x2p, x1q, x2q, x1max, x2max; double phi = params.phi; double kT = x; pT = params.pT; yp = params.yp; yq = params.yq; x1p = pT/rts*exp(+yp); x2p = pT/rts*exp(-yp); x1q = pT/rts*exp(+yq); x2q = pT/rts*exp(-yq); x1max = gsl_max(x1p,x1q); x2max = gsl_max(x2p,x2q); double pTmkT = sqrt( pT*pT + kT*kT - 2.0*pT*kT*cos(phi) ); double num = pow( kT*pT*cos(phi)-kT*kT, 2.0); double den = pow(kT*pTmkT,2.); return kT*wf(1,x1p,kT)*wf(2,x2p,pTmkT)*num/den; } double sinKernel(double x, void *p) { struct glasma_params params = *(struct glasma_params *)p; double rts = params.rts; double pT, yp, yq; double x1p, x2p, x1q, x2q, x1max, x2max; double phi = params.phi; double kT = x; pT = params.pT; yp = params.yp; yq = params.yq; x1p = pT/rts*exp(+yp); x2p = pT/rts*exp(-yp); x1q = pT/rts*exp(+yq); x2q = pT/rts*exp(-yq); x1max = gsl_max(x1p,x1q); x2max = gsl_max(x2p,x2q); double pTmkT = sqrt( pT*pT + kT*kT - 2.0*pT*kT*cos(phi) ); double num = pow( kT*pT*sin(phi), 2.0); double den = pow( kT*pTmkT ,2.0); return kT*wf(1,x1max,kT)*wf(2,x2max,pTmkT)*num/den; } //does phi integration over d^2k_\perp double phiKernel(double x, void *p) { struct glasma_params params = *(struct glasma_params *)p; double result, error; params.phi = x; gsl_function F = params.Kernel; F.params = &params; gsl_integration_qng(&F, kT_min, 2.0*kT_max, abserr, relerr,\ &result, &error, &neval); return result; } void TabulateGlasma(FILE *out, double rts) { //returns dN/d^2p_T d^2q_T dy_p dy_q / (S_\perp) [GeV^-2] //this is the delta function contribution //of the glasma graphs double yp, yq, rtpT; //double yrange = 6.0; double dy = 0.25; double yrange = dy; for (yp = -yrange; yp <= yrange; yp += dy) for (yq = -yrange; yq <= yrange; yq += dy) for (rtpT = .1; rtpT <= 5.11; rtpT += .2){ fprintf(out,"%10.2f\t%10.2f\t%10.2f\t%10.5e\n", yp, yq, rtpT,\ d2Nglasma1(pow(rtpT,2.),yp,yq,rts) ); } fclose(out); return; }
{ "alphanum_fraction": 0.5759296054, "avg_line_length": 28.0717131474, "ext": "c", "hexsha": "9d5bf334ebf6fbc66097a93f89cefcc6d6c0ff81", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kdusling/mpc", "max_forks_repo_path": "src/glasma.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kdusling/mpc", "max_issues_repo_path": "src/glasma.c", "max_line_length": 104, "max_stars_count": null, "max_stars_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kdusling/mpc", "max_stars_repo_path": "src/glasma.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2855, "size": 7046 }
/****************************************************************************** * gsl_sprng.c: rewrite of gsl-sprng.h to use sprng streams * * Author: Yan Y. Liu <yanliu@illinois.edu> * * Date: 2014/08/17 * * Copyright and license of this source file are specified in LICENSE.TXT * * under the root directory of this software package. * ******************************************************************************/ #ifndef GSL_SPRNG_C #define GSL_SPRNG_C #include <sys/time.h> #include <stdio.h> #include <gsl/gsl_rng.h> #include "gsl-sprng.h" /***************************/ /* gsl definition of sprng */ /***************************/ void sprng_set(void * vstate, unsigned long int seed) { gsl_sprng_state_t *mysprng = (gsl_sprng_state_t*) vstate; if (mysprng->stream != NULL) { free_sprng(mysprng->stream); } mysprng->stream = init_sprng( DEFAULT_RNG_TYPE, mysprng->streamnum, mysprng->nstreams, seed, SPRNG_DEFAULT); } unsigned long sprng_get(void * vstate) { return( (long) isprng( ((gsl_sprng_state_t*) vstate)->stream ) ); } double sprng_get_double(void * vstate) { return( (double) sprng( ((gsl_sprng_state_t*) vstate)->stream ) ); } /* global sprng 2.0 type for gsl initialization */ const gsl_rng_type gsl_rng_sprng20 = { "sprng20", /* name */ 0x7fffffffUL, /* RAND_MAX */ 0, /* RAND_MIN */ 0, /* size of state - not sure about this */ &sprng_set, /* initialisation */ &sprng_get, /* get integer RN */ &sprng_get_double /* get double RN */ }; /***************************/ /* gsl_sprng API */ /***************************/ // if stream=NULL, create a new stream // otherwise, just use the stream gsl_rng *gsl_sprng_alloc (int streamnum, int nstreams, int seed, int * stream) { gsl_sprng_state_t * gsl_sprng_state = (gsl_sprng_state_t*) malloc( sizeof( gsl_sprng_state_t ) ); if (gsl_sprng_state == NULL) { GSL_ERROR_VAL ( "failed to allocate space for gsl_sprng_state_t struct", GSL_ENOMEM, 0); return NULL; // not reachable } gsl_sprng_state->streamnum = streamnum; gsl_sprng_state->nstreams = nstreams; // set seed if (seed == -1) { struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); seed = (int)(tv.tv_sec * streamnum); } else if (seed == 0) { seed = gsl_rng_default_seed; // zero, too, in fact } gsl_sprng_state->seed = seed; // sprng init if (stream == NULL) { stream = init_sprng( DEFAULT_RNG_TYPE, streamnum, nstreams, seed, SPRNG_DEFAULT); } gsl_sprng_state->stream = stream; // gsl_rng init gsl_rng * r = (gsl_rng *) malloc (sizeof (gsl_rng)); if (r == NULL) { GSL_ERROR_VAL ("gsl_sprng: failed to allocate space for gsl_rng struct", GSL_ENOMEM, 0); free(gsl_sprng_state); // not reachable return NULL; } r->type = &gsl_rng_sprng20; r->state = gsl_sprng_state; return r; } void gsl_sprng_free (gsl_rng * r) { if (r==NULL) return; gsl_sprng_state_t * gsl_sprng_state = (gsl_sprng_state_t *) r->state; if (gsl_sprng_state != NULL) { int numAvail = free_sprng(gsl_sprng_state->stream); fprintf(stdout, "gsl_sprng: free random stream. %d streams left\n", numAvail); free(r->state); } free(r); } void gsl_sprng_print (gsl_rng *r) { if (r==NULL) return; gsl_sprng_state_t * gsl_sprng_state = (gsl_sprng_state_t *) r->state; if (gsl_sprng_state == NULL) return; printf("gsl_sprng: streamnum=%d, nstreams=%d, seed=%d\n", gsl_sprng_state->streamnum, gsl_sprng_state->nstreams, gsl_sprng_state->seed); int * stream = gsl_sprng_state->stream; if (stream == NULL) return; print_sprng(stream); } int gsl_sprng_fread (char * fpath, gsl_rng * r) { // delete old stream if (r!=NULL) { gsl_sprng_free(r); r = NULL; } // allocate memory to load data char buf[MAX_PACKED_LENGTH]; // read stream from file to array FILE * f; int size; if ((f=fopen(fpath, "r")) == NULL) { fprintf(stderr, "gsl_sprng_fread(): failed to open %s for reading\n", fpath); return 0; } fread(&size,sizeof(int),1,f); fprintf(stdout, "sprng_fread[%s]: size=%d\n", fpath, size); int numRead = fread(buf, sizeof(char), size, f); if (numRead != size) { fprintf(stderr, "gsl_sprng_fread(): failed to read stream of size %d\n", size); fclose(f); return 0; } fclose(f); // load stream from array int * stream = unpack_sprng(buf); if (stream == NULL) { fprintf(stderr, "gsl_sprng_fread(): failed to read stream of size %d\n", size); return 0; } print_sprng(stream); // create new gsl_rng r = gsl_sprng_alloc(0, 0, 0, stream); if (r==NULL) return 0; return 1; } int gsl_sprng_fwrite (char * fpath, const gsl_rng * r) { if (r==NULL) return 0; gsl_sprng_state_t * gsl_sprng_state = (gsl_sprng_state_t*) r->state; if (gsl_sprng_state == NULL) return 0; int * stream = gsl_sprng_state->stream; if (stream==NULL) return 0; // write state to array char *buf; int size = pack_sprng(stream, &buf); // write array to file FILE * f; if ((f=fopen(fpath, "w")) == NULL) { fprintf(stderr, "gsl_sprng_fwrite(): failed to open %s for writing\n", fpath); return 0; } // our format: filesize, filecontent fwrite(&size,sizeof(int),1,f); int numWrote = fwrite(buf, sizeof(char), size, f); if (numWrote != size) { fprintf(stderr, "gsl_sprng_fwrite(): failed to write stream of size %d\n", size); } fclose(f); // sprng uses malloc() to allocate buf, we must free it properly free(buf); return 1; } #endif
{ "alphanum_fraction": 0.5596389426, "avg_line_length": 31.4923857868, "ext": "c", "hexsha": "048c48d9b264f6db02abc1a19875b914fa1a83c6", "lang": "C", "max_forks_count": 20, "max_forks_repo_forks_event_max_datetime": "2021-06-17T14:29:16.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-28T15:28:48.000Z", "max_forks_repo_head_hexsha": "bb0c21ca479db5ac3ecf789ab280d5e45c3c7805", "max_forks_repo_licenses": [ "NCSA", "BSD-3-Clause" ], "max_forks_repo_name": "ElsevierSoftwareX/SOFTX-D-15-00005", "max_forks_repo_path": "pgap/gsl-sprng.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "bb0c21ca479db5ac3ecf789ab280d5e45c3c7805", "max_issues_repo_issues_event_max_datetime": "2016-07-25T17:38:26.000Z", "max_issues_repo_issues_event_min_datetime": "2016-07-25T02:25:20.000Z", "max_issues_repo_licenses": [ "NCSA", "BSD-3-Clause" ], "max_issues_repo_name": "ElsevierSoftwareX/SOFTX-D-15-00005", "max_issues_repo_path": "pgap/gsl-sprng.c", "max_line_length": 140, "max_stars_count": 22, "max_stars_repo_head_hexsha": "9a7d7c02b2f1d7b6bfd1b08fbb2150c30ddd1046", "max_stars_repo_licenses": [ "NCSA", "BSD-3-Clause" ], "max_stars_repo_name": "ElsevierSoftwareX/SOFTX_2018_242", "max_stars_repo_path": "pgap/gsl-sprng.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T15:38:19.000Z", "max_stars_repo_stars_event_min_datetime": "2015-07-16T01:05:44.000Z", "num_tokens": 1739, "size": 6204 }
/** * @file batchf_zgemm_stride.c * * @brief BBLAS batchf_zgemm_stride double _Complex routine. * * BBLAS is a software package provided by Univ. of Manchester, * Univ. of Tennessee. * * @version 1.0.0 * @author Samuel D. Relton * @author Pedro V. Lara * @author Mawussi Zounon * @date 2016-04-06 * **/ #ifndef DOXYGEN_SHOULD_SKIP_THIS /** * Code generation * @precisions normal z -> c d s **/ #endif #include <cblas.h> #include "bblas.h" #define COMPLEX /** Purpose ------- <b>batchf_zgemm_stride</b> is a batch version of zgemm for fixed size. It performs the matrix-matrix operations arrayC[i] = alpha[i]*op( arrayA[i] )*op( arrayB[i] ) + beta[i]*arrayC[i], where op( X ) is one of op( X ) = X or op( X ) = X**T or op( X ) = X**H, alpha[i] and beta[i] are scalars, and arrayA[i], arrayB[i] and C are matrices, with op( arrayA[i] ) an m by k matrix, op( arrayB[i] ) a k by n matrix and arrayC[i] an m by n matrix. Fixed Batch Operations ----------------------------------- - all parameters that are arrays must have length at least batch_count. - all parameters that are arrays must have all values set. the values of transA, transB, M, N, K, alpha, beta, lda, ldb, and ldc are used for all computations. Parameters ---------- @param[in] transA <tt>enum BBLAS_TRANS</tt>. transA specifies the form of op( arrayA[i] ) to be used in the matrix multiplication as follows: - = BblasNoTrans: op( arrayA[i] ) = arrayA[i]. - = BblasTrans: op( arrayA[i] ) = arrayA[i]**T. - = BblasConjTrans: op( arrayA[i] ) = arrayA[i]**H. @param[in] transB <tt>enum BBLAS_TRANS</tt>. On entry, transB specifies the form of op( arrayB[i] ) to be used in the matrix multiplication as follows: - = BblasNoTrans: op( arrayB[i] ) = arrayB[i]. - = BblasTrans: op( arrayB[i] ) = arrayB[i]**T. - = BblasConjTrans: op( arrayB[i] ) = arrayB[i]**H. @param[in] M <tt>int</tt>. M specifies the number of rows of the matrix op( arrayA[i] ) and of the matrix arrayC[i]. M must be greater than zero. @param[in] N <tt>int</tt>. N specifies the number of columns of the matrix op( arrayB[i] ) and the number of columns of the matrix arrayC[i]. N must be greater than zero. @param[in] K <tt>int</tt>. K specifies the number of columns of the matrix op( arrayA[i] ) and the number of rows of the matrix op( arrayB[i] ). K must be greater than zero. @param[in] alpha <tt>complex_16</tt>. @param[in] arrayA Array of pointers. Each element arrayA[i] is a pointer to a COMPLEX_16 matrix of dimension lda by Ka, where Ka is K when transA = BblasNoTrans, and is M otherwise. When using transA = BblasNoTrans the leading M by K part of arrayA[i] must contain the matrix elements, otherwise the leading K by M part of arrayA[i] must contain the matrix elements. @param[in] lda <tt>int</tt>. lda specifies the first dimension of arrayA[i] as declared in the calling (sub) program. When transA = BblasNoTrans then lda must be at least max( 1, M ), otherwise lda must be at least max( 1, K ). @param[in] strideA <tt>int</tt>. strideA specifies the storage spacing between A matrices. strideA must be at least M by K. @param[in] arrayB Array of pointers. Each element arrayB[i] is a pointer to a COMPLEX_16 matrix of dimension ldb by Kb, where Kb is N when transB = BblasNoTrans, and is K otherwise. When using transB = BblasNoTrans the leading K by N part of arrayB[i] must contain the matrix elements, otherwise the leading N by K part of arrayB[i] must contain the matrix elements. @param[in] ldb <tt>int</tt>. ldb specifies the first dimension of arrayB[i] as declared in the calling (sub) program. When transB = BblasNoTrans then ldb must be at least max( 1, K ), otherwise ldb must be at least max( 1, N ). @param[in] strideB <tt>int</tt>. strideB specifies the storage spacing between A matrices. strideB must be at least K by N. @param[in] beta <tt>complex_16</tt>. When beta is set to zero arrayC[i] need not be set on input. @param[in,out] arrayC Array of pointers. Each element arrayC[i] is a pointer to a COMPLEX_16 matrix of dimension ldc by N. Before entry, the leading M by N part of the arrayC[i] must contain a matrix C, except when beta is zero, in which case C need not be set on entry. On exit, the matrix arrayC[i] is overwritten by the M by N matrix ( alpha*op( arrayA[i] )*op( arrayB[i] ) + beta*arrayC[i] ). @param[in] ldc <tt>int</tt>. Each element ldc specifies the first dimension of arrayC[i] as declared in the calling (sub) program. The value ldc must be at least max( 1, M ) @param[in] strideC <tt>int</tt>. strideC specifies the storage spacing between A matrices. strideC must be at least M by N. @param[in] batch_count <tt>int</tt> The number of matrices to operate on. @param[in,out] info <tt>int</tt>. info is the error return code of the batch. The error codes can be found in bblas_macros.h. **/ void batchf_zgemm_stride( const enum BBLAS_TRANS transA, const enum BBLAS_TRANS transB, const int M, const int N, const int K, const BBLAS_Complex64_t alpha, const BBLAS_Complex64_t *arrayA, const int lda, const int strideA, const BBLAS_Complex64_t *arrayB, const int ldb, const int strideB, const BBLAS_Complex64_t beta, BBLAS_Complex64_t *arrayC, const int ldc, const int strideC, const int batch_count, int *info) { /* Local variables */ int batch_iter; int LDA, LDB; char func_name[15] = "batchf_zgemm_op"; /* Check input arguments */ if (batch_count < 0) { xerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1); } if ((transA != BblasNoTrans) && (transA != BblasTrans) && (transA != BblasConjTrans)) { xerbla_batch(func_name, BBLAS_ERR_TRANSA, -1); *info = BBLAS_ERR_TRANSA; return; } if ((transB != BblasNoTrans) && (transB != BblasTrans) && (transB != BblasConjTrans)) { xerbla_batch(func_name, BBLAS_ERR_TRANSB, -1); *info = BBLAS_ERR_TRANSB; return; } if ( transA == BblasNoTrans ) { LDA = M; } else { LDA = K; } if ( transB == BblasNoTrans ) { LDB = K; } else { LDB = N; } if (M < 0) { xerbla_batch(func_name, BBLAS_ERR_M, -1); *info = BBLAS_ERR_M; return; } if (N < 0) { xerbla_batch(func_name, BBLAS_ERR_N, -1); *info = BBLAS_ERR_N; return; } if (K < 0) { xerbla_batch(func_name, BBLAS_ERR_K, -1); *info = BBLAS_ERR_K; return; } if (lda < max(1, LDA)) { xerbla_batch(func_name, BBLAS_ERR_LDA, -1); *info = BBLAS_ERR_LDA; return; } if (ldb < max(1, LDB)) { xerbla_batch(func_name, BBLAS_ERR_LDB, -1); *info = BBLAS_ERR_LDB; return; } if (ldc < max(1, M)) { xerbla_batch(func_name, BBLAS_ERR_LDC, -1); *info = BBLAS_ERR_LDC; return; } if (strideA < M*K) { xerbla_batch(func_name, BBLAS_ERR_STRIDEA, -1); *info = BBLAS_ERR_STRIDEA; return; } if (strideB < K*N) { xerbla_batch(func_name, BBLAS_ERR_STRIDEB, -1); *info = BBLAS_ERR_STRIDEB; return; } if (strideC < M*N) { xerbla_batch(func_name, BBLAS_ERR_STRIDEC, -1); *info = BBLAS_ERR_STRIDEC; return; } /* Skip subproblems where nothing needs to be done */ if (M == 0 || N == 0 || ((alpha == (BBLAS_Complex64_t)0.0 || K == 0) && beta == (BBLAS_Complex64_t)1.0 )) { *info = BBLAS_SUCCESS; return; } for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { /* Call to cblas_zgemm */ cblas_zgemm( BblasColMajor, transA, transB, M, N, K, CBLAS_SADDR(alpha), //&arrayA[batch_iter*M*K], &arrayA[batch_iter*strideA], lda, //&arrayB[batch_iter*K*N], &arrayB[batch_iter*strideB], ldb, CBLAS_SADDR(beta), //&arrayC[batch_iter*M*N], &arrayC[batch_iter*strideC], ldc); } /* Successful */ *info = BBLAS_SUCCESS; } #undef COMPLEX
{ "alphanum_fraction": 0.5755173932, "avg_line_length": 29.4935064935, "ext": "c", "hexsha": "53546d4cb8ba85b0137e459f2d261a187c1be77b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "sdrelton/bblas_api_test", "max_forks_repo_path": "src/batchf_zgemm_stride.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "sdrelton/bblas_api_test", "max_issues_repo_path": "src/batchf_zgemm_stride.c", "max_line_length": 84, "max_stars_count": 3, "max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "mawussi/BBLAS-group", "max_stars_repo_path": "src/batchf_zgemm_stride.c", "max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z", "max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z", "num_tokens": 2661, "size": 9084 }
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <gsl/gsl_linalg.h> int DEBUG = 1; int DEBUG_SOLUTION = 1; int STORE_TIMING = 0; FILE* decompFile; FILE* solveFile; double* generateVector(int size) { double* vec = calloc(sizeof(double), size); for (int i = 0; i < size; ++i){ double val = (double)rand() / RAND_MAX; // double [0, 1] vec[i] = val; } return vec; } void printMatrix(double* m, int size) { for (int i = 0; i < size; ++i){ for (int j = 0; j < size; ++j){ printf("%g ", m[j + i * size]); } printf("\n"); } printf("\n"); } void printVector(double* v, int size) { for (int i = 0; i < size; ++i){ printf("%g", v[i]); printf("\n"); } printf("\n"); } double* copyVector(double* src, int size) { double* vec = calloc(sizeof(double), size); for (int i = 0; i < size; ++i){ vec[i] = src[i]; } return vec; } void checkSolution(double* m, double* b, gsl_vector x, int size) { const double epsilon = 0.0001; int failures = 0; for (int i = 0; i < size; ++i){ double sum = 0; for (int j = 0; j < size; ++j){ sum += m[j + i * size] * x.data[j]; // printf("%g * %g = %g\n", m[j + i * size], x.data[j], m[j + i * size] * x.data[j]); } if (abs(sum - b[i]) > epsilon){ failures++; if (DEBUG_SOLUTION){ printf("Wrong solution was calculated: %g --- %g\n", sum, b[i]); printf("\n"); } } } if (DEBUG_SOLUTION){ if (failures == 0){ printf("All calculated values were correct"); } else { printf("Total %n errors in calculated value", failures); } printf("\n"); } } void decomp(gsl_matrix *A, gsl_permutation* p, int *signum, int size) { clock_t start = clock(); gsl_linalg_LU_decomp(A, p, signum); clock_t end = clock(); double t = ((double) (end - start)) / CLOCKS_PER_SEC; if (STORE_TIMING) fprintf (decompFile,"%d %g\n", size, t); } void solve(const gsl_matrix* LU, const gsl_permutation* p, const gsl_vector* b, gsl_vector* x, int size) { clock_t start = clock(); gsl_linalg_LU_solve(LU, p, b, x); clock_t end = clock(); double t = ((double) (end - start)) / CLOCKS_PER_SEC; if (STORE_TIMING) fprintf (solveFile,"%d %g\n", size, t); } void calculate(int n) { double* a_data = generateVector(n * n); double* b_data = generateVector(n); double* originalMatrix = copyVector(a_data, n * n); gsl_matrix_view m = gsl_matrix_view_array(a_data, n, n); gsl_vector_view b = gsl_vector_view_array(b_data, n); if (DEBUG){ printf("Matrix M:\n"); printMatrix(a_data, n); printf("Vector B:\n"); printVector(b_data, n); } gsl_vector *x = gsl_vector_alloc(n); int s; gsl_permutation *p = gsl_permutation_alloc(n); decomp(&m.matrix, p, &s, n); solve(&m.matrix, p, &b.vector, x, n); if (DEBUG){ printf("Solution X:\n"); gsl_vector_fprintf(stdout, x, "%g"); printf("\n"); } checkSolution(originalMatrix, b_data, *x, n); gsl_permutation_free(p); gsl_vector_free(x); } int main(int argc, char* argv[]) { if (argc != 2){ return -1; } char *pEnd; int n = strtol(argv[1], &pEnd, 0); srand(time(NULL)); decompFile = fopen("decomp.txt", "w"); solveFile = fopen("solve.txt", "w"); if (n == 0){ return -1; } else if (n < 0){ DEBUG = 0; DEBUG_SOLUTION = 0; STORE_TIMING = 1; for (int i = 10; i <= 1000; i+=10){ calculate(i); } } else { calculate(n); } return 0; }
{ "alphanum_fraction": 0.5272010512, "avg_line_length": 23.3435582822, "ext": "c", "hexsha": "a0968b6fa47972b02dd26ad87f25ab77128575b1", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "komilll/mownit_linux", "max_forks_repo_path": "zad6/linear.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "komilll/mownit_linux", "max_issues_repo_path": "zad6/linear.c", "max_line_length": 104, "max_stars_count": null, "max_stars_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "komilll/mownit_linux", "max_stars_repo_path": "zad6/linear.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1126, "size": 3805 }
/* linalg/ldlt_band.c * * Copyright (C) 2018 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* L D L^T decomposition of a symmetric banded positive semi-definite matrix */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> static double symband_norm1(const gsl_matrix * A); static int ldlt_band_Ainv(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params); /* gsl_linalg_ldlt_band_decomp() L D L^T decomposition of a square symmetric positive semi-definite banded matrix Inputs: A - matrix in symmetric banded format, N-by-ndiag where N is the size of the matrix and ndiag is the number of nonzero diagonals. Notes: 1) The matrix D is stored in the first column of A; the first subdiagonal of L in the second column and so on. 2) If ndiag > 1, the 1-norm of A is stored in A(N,ndiag) on output 3) At each diagonal element, the matrix is factored as A(j:end,j:end) = [ A11 A21^T ] = [ 1 0 ] [ alpha 0 ] [ 1 v^T ] [ A21 A22 ] [ v L ] [ 0 D ] [ 0 L^T ] where: alpha = A(j,j) v = A(j+1:end, j) / alpha A22 = L D L^T + alpha v v^T So we start at A(1,1) and work right. Pseudo-code is: loop j = 1, ..., N alpha = A(j,j) A(j+1:end, j) := A(j+1:end, j) / alpha (DSCAL) A(j+1:end, j+1:end) -= alpha v v^T (DSYR) Due to the banded structure, v has at most p non-zero elements, where p is the lower bandwidth */ int gsl_linalg_ldlt_band_decomp(gsl_matrix * A) { const size_t N = A->size1; /* size of matrix */ const size_t ndiag = A->size2; /* number of diagonals in band, including main diagonal */ if (ndiag > N) { GSL_ERROR ("invalid matrix dimensions", GSL_EBADLEN); } else { const size_t p = ndiag - 1; /* lower bandwidth */ const int kld = (int) GSL_MAX(1, p); double Anorm; size_t j; /* check for quick return */ if (ndiag == 1) return GSL_SUCCESS; /* * calculate 1-norm of A and store in lower right of matrix, which is not accessed * by rest of routine. gsl_linalg_ldlt_band_rcond() will use this later. If * A is diagonal, there is no empty slot to store the 1-norm, so the rcond routine * will have to compute it. */ Anorm = symband_norm1(A); gsl_matrix_set(A, N - 1, p, Anorm); for (j = 0; j < N - 1; ++j) { double ajj = gsl_matrix_get(A, j, 0); size_t lenv; if (ajj == 0.0) { GSL_ERROR("matrix is singular", GSL_EDOM); } /* number of elements in v, which will normally be p, unless we * are in lower right corner of matrix */ lenv = GSL_MIN(p, N - j - 1); if (lenv > 0) { gsl_vector_view v = gsl_matrix_subrow(A, j, 1, lenv); gsl_matrix_view m = gsl_matrix_submatrix(A, j + 1, 0, lenv, lenv); gsl_blas_dscal(1.0 / ajj, &v.vector); m.matrix.tda = kld; gsl_blas_dsyr(CblasUpper, -ajj, &v.vector, &m.matrix); } } return GSL_SUCCESS; } } int gsl_linalg_ldlt_band_solve (const gsl_matrix * LDLT, const gsl_vector * b, gsl_vector * x) { if (LDLT->size1 != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (LDLT->size1 != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else { int status; /* copy x <- b */ gsl_vector_memcpy (x, b); status = gsl_linalg_ldlt_band_svx(LDLT, x); return status; } } int gsl_linalg_ldlt_band_svx (const gsl_matrix * LDLT, gsl_vector * x) { if (LDLT->size1 != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else { gsl_vector_const_view diag = gsl_matrix_const_column(LDLT, 0); /* solve for z using forward-substitution, L z = b */ cblas_dtbsv(CblasColMajor, CblasLower, CblasNoTrans, CblasUnit, (int) LDLT->size1, (int) (LDLT->size2 - 1), LDLT->data, LDLT->tda, x->data, x->stride); /* solve for y, D y = z */ gsl_vector_div(x, &diag.vector); /* perform back-substitution, L^T x = y */ cblas_dtbsv(CblasColMajor, CblasLower, CblasTrans, CblasUnit, (int) LDLT->size1, (int) (LDLT->size2 - 1), LDLT->data, LDLT->tda, x->data, x->stride); return GSL_SUCCESS; } } /* gsl_linalg_ldlt_band_unpack() Unpack symmetric banded format matrix LDLT into larger matrix L and diagonal vector D */ int gsl_linalg_ldlt_band_unpack (const gsl_matrix * LDLT, gsl_matrix * L, gsl_vector * D) { const size_t N = LDLT->size1; if (N != L->size1) { GSL_ERROR("L matrix does not match LDLT dimensions", GSL_EBADLEN); } else if (L->size1 != L->size2) { GSL_ERROR("L matrix is not square", GSL_ENOTSQR); } else if (N != D->size) { GSL_ERROR("D vector does not match LDLT dimensions", GSL_EBADLEN); } else { const size_t p = LDLT->size2 - 1; /* lower bandwidth */ gsl_vector_const_view diag = gsl_matrix_const_column(LDLT, 0); gsl_vector_view diagL = gsl_matrix_diagonal(L); size_t i; /* copy diagonal entries */ gsl_vector_memcpy(D, &diag.vector); /* copy subdiagonals into L */ for (i = 1; i <= p; ++i) { gsl_vector_const_view v = gsl_matrix_const_subcolumn(LDLT, i, 0, N - i); gsl_vector_view w = gsl_matrix_subdiagonal(L, i); gsl_vector_memcpy(&w.vector, &v.vector); } /* set main diagonal of L */ gsl_vector_set_all(&diagL.vector, 1.0); /* zero out remaining subdiagonals */ for (i = p + 1; i < N; ++i) { gsl_vector_view w = gsl_matrix_subdiagonal(L, i); gsl_vector_set_zero(&w.vector); } return GSL_SUCCESS; } } int gsl_linalg_ldlt_band_rcond (const gsl_matrix * LDLT, double * rcond, gsl_vector * work) { const size_t N = LDLT->size1; if (work->size != 3 * N) { GSL_ERROR ("work vector must have length 3*N", GSL_EBADLEN); } else { int status; const size_t ndiag = LDLT->size2; double Anorm; /* ||A||_1 */ double Ainvnorm; /* ||A^{-1}||_1 */ if (ndiag == 1) { /* diagonal matrix, compute 1-norm since it has not been stored */ Anorm = symband_norm1(LDLT); } else { /* 1-norm is stored in A(N, ndiag) by gsl_linalg_ldlt_band_decomp() */ Anorm = gsl_matrix_get(LDLT, N - 1, ndiag - 1); } *rcond = 0.0; /* return if matrix is singular */ if (Anorm == 0.0) return GSL_SUCCESS; status = gsl_linalg_invnorm1(N, ldlt_band_Ainv, (void *) LDLT, &Ainvnorm, work); if (status) return status; if (Ainvnorm != 0.0) *rcond = (1.0 / Anorm) / Ainvnorm; return GSL_SUCCESS; } } /* compute 1-norm of symmetric banded matrix */ static double symband_norm1(const gsl_matrix * A) { const size_t N = A->size1; const size_t ndiag = A->size2; /* number of diagonals in band, including main diagonal */ double value; if (ndiag == 1) { /* diagonal matrix */ gsl_vector_const_view v = gsl_matrix_const_column(A, 0); CBLAS_INDEX_t idx = gsl_blas_idamax(&v.vector); value = gsl_vector_get(&v.vector, idx); } else { size_t j; value = 0.0; for (j = 0; j < N; ++j) { size_t ncol = GSL_MIN(ndiag, N - j); /* number of elements in column j below and including main diagonal */ gsl_vector_const_view v = gsl_matrix_const_subrow(A, j, 0, ncol); double sum = gsl_blas_dasum(&v.vector); size_t k, l; /* sum now contains the absolute sum of elements below and including main diagonal for column j; we * have to add the symmetric elements above the diagonal */ k = j; l = 1; while (k > 0 && l < ndiag) { double Akl = gsl_matrix_get(A, --k, l++); sum += fabs(Akl); } value = GSL_MAX(value, sum); } } return value; } /* x := A^{-1} x = A^{-t} x, A = L D L^T */ static int ldlt_band_Ainv(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params) { gsl_matrix * LDLT = (gsl_matrix * ) params; gsl_vector_const_view diag = gsl_matrix_const_column(LDLT, 0); (void) TransA; /* unused parameter warning */ /* compute x := L^{-1} x */ cblas_dtbsv(CblasColMajor, CblasLower, CblasNoTrans, CblasUnit, (int) LDLT->size1, (int) (LDLT->size2 - 1), LDLT->data, LDLT->tda, x->data, x->stride); /* compute x := D^{-1} x */ gsl_vector_div(x, &diag.vector); /* compute x := L^{-T} x */ cblas_dtbsv(CblasColMajor, CblasLower, CblasTrans, CblasUnit, (int) LDLT->size1, (int) (LDLT->size2 - 1), LDLT->data, LDLT->tda, x->data, x->stride); return GSL_SUCCESS; }
{ "alphanum_fraction": 0.5939516129, "avg_line_length": 28.2621082621, "ext": "c", "hexsha": "9c78e26eeaf542c592352808668755c0d849b006", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/ldlt_band.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/linalg/ldlt_band.c", "max_line_length": 117, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/linalg/ldlt_band.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 2939, "size": 9920 }
#ifndef ALM_L_KATYUSHA_H #define ALM_L_KATYUSHA_H #include "L_Katyusha.h" #include <string> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <stdio.h> /* printf */ #include <time.h> #include <fstream> #include <algorithm> #include <iomanip> #include <ctime> #include <sstream> //#include "cmd_line.h" //This class implements the method IPALM_L_Katyusha /* The optimization problem to solve is: min f_0(x)+\sum_{i=1}^m h_i(f_i(x))+P(x) x is a d-dimensional vector. // Each subproblem solves problem of the form f_0(x)+ \sum_{i=1}^m h_{\beta_s}^i(f_i(x);\lambda_s^i) +g(x)+ \beta_s/2\|x-x_s\|^2 by L_Katyuhsa */ template<typename L, typename D> class ALM_L_Katyusha: public L_Katyusha<L, D> { private: protected: std::vector<D> x_s; std::vector<D> old_x_s; std::vector<D> lambda_s; std::vector<D> old_lambda_s; std::vector<D> x_tmp; std::vector<D> g_tmp; std::vector<D> g_tmp_x; std::vector<D> g_tmp_w; std::vector<D> valuefi; std::vector<D> is_feasiblity_constraint; D beta_s; D epsilon_s; D m_s; D m_0; L m; L d; D eta; D rho; D tau_s; std::vector<D> L_phi; D function_value; D infeasibility; L print_every_N_ALM; D running_time_ALM; L nb_outer_iters; ofstream samp_ALM; public: D mu_g; D lambda1; D lambda2; virtual inline void set_Li_Lf(){} virtual inline D value_of_P(vector<D> &){return D(NULL);} virtual inline void prox_of_P(D, vector<D> &, vector<D> &){} //prox_of_P(L,x,y) computes y=argmin{P(u)+L/2||u-x||^2} virtual inline D prox_of_h_star_j(D,D, L){return D(NULL);} //prox_of_h_star_j(x,beta,j) computes argmin{h*(y)+beta/2(y-x)^2} virtual inline D value_of_h_star_j(D, L){return D(NULL);} virtual inline void compute_gradient_f0(vector<D> &,vector<D> &){} //compute_gradient_f0(x,g) computes g=nabla f0(x) virtual inline D compute_gradient_and_value_f_i(vector<D> &,vector<D> &, L){return D(NULL);}//compute_gradient_and_value_f_i(i,x,g) computes g=nabla f_i(x) and return f_i(x) virtual inline D value_of_h_j(D, L){return D(NULL);} virtual inline D distance_to_domain_of_h_j(D,L){return D(NULL);} virtual inline D value_of_f0(vector<D> &){return D(NULL);} //f0(x) virtual inline D value_of_f_i(vector<D> &,L){return D(NULL);} // f_i(x) virtual inline void set_dimension(){} // set the value of m and d virtual inline void set_is_feasibility_constraint(){} ALM_L_Katyusha() : L_Katyusha<L,D>() { } D value_of_phi_i(L i){ D res= 0; if (i==0) res=value_of_f0(this->x); else { D fi=value_of_f_i(this->x,i); i=i-1; D lambdasi=lambda_s[i]; D tmp= prox_of_h_star_j(fi/beta_s+ lambdasi,beta_s,i); res=fi*tmp- value_of_h_star_j(tmp,i)- beta_s/2*(tmp- lambdasi)*(tmp- lambdasi); } return this->nsamples*res; } void compute_full_gradient(vector<D> & x, vector<D> & gx){ compute_gradient_f0(x,gx); for(L i=0;i<m;i++){ D fi=compute_gradient_and_value_f_i(x,g_tmp,i+1); D tmp= prox_of_h_star_j(fi/beta_s+ lambda_s[i],beta_s,i); for(L j=0;j<d;j++) gx[j]+=g_tmp[j]*tmp; } } void compute_batch_delta_gradient(){ for (L j=0; j< this->batch_size; j++){ L s= this->batch_i[j]; if(s==0){ compute_gradient_f0(this->x,g_tmp_x); compute_gradient_f0(this->w,g_tmp_w); add_up(1.,1.,this->theta_S[s]); } else{ L i=s-1; D fi_x=compute_gradient_and_value_f_i(this->x,g_tmp_x,s); D tmp_x= prox_of_h_star_j(fi_x/beta_s+ lambda_s[i],beta_s,i); D fi_w=compute_gradient_and_value_f_i(this->w,g_tmp_w,s); D tmp_w= prox_of_h_star_j(fi_w/beta_s+ lambda_s[i],beta_s,i); add_up(tmp_x,tmp_w,this->theta_S[s]); } } } void add_up(D fx, D fw, D c){ for(L i=0;i<d;i++) this->batch_delta_gradient[i]+=(fx*g_tmp_x[i]-fw*g_tmp_w[i])*c; } inline D value_of_g(){ D res= value_of_P(this->x); for(L i=0;i<d;i++) res+= 0.5*beta_s*(this->x[i]- x_s[i])*(this->x[i]- x_s[i]); return res; } void prox_of_g(D stepsz, vector<D> & x, vector<D> & g, vector<D> & nextx){ D tmp0=beta_s+stepsz; for(L i=0;i<d;i++) x_tmp[i]=(beta_s*x_s[i]+stepsz*x[i]-g[i])/tmp0; prox_of_P(tmp0, x_tmp, nextx); } void compute_x(){ for (L i=0; i< d; i++){ x_s[i]= this->x[i]; } for (L i= 0; i< m; i++){ valuefi[i]=value_of_f_i(x_s,i+1); } } void update_lambda(){ for(L j=0;j<m;j++) { D fi= valuefi[j]; lambda_s[j]= prox_of_h_star_j(fi/beta_s+ lambda_s[j],beta_s,j); } } void compute_function_value(){ function_value=value_of_f0(x_s); D res= 0; for (L i= 0; i< m; i++){ D fi=value_of_f_i(x_s,i+1); if(is_feasiblity_constraint[i]==1){ D tmp=distance_to_domain_of_h_j(fi,i); res+=tmp*tmp; } else function_value+=value_of_h_j(fi,i); } function_value+=value_of_P(x_s); infeasibility=sqrt(res); } inline void compute_m0(D beta0, D val_eta, D val_rho, L val_tau){ cout<<"beta0="<<beta0<<"val_eta="<<val_eta<<"; val_rho="<<val_rho<<"; val_tau="<<val_tau<<endl; m_s= this->nsamples/val_tau*1e+6; //D tmp7=1-val_tau/this->n*sqrt(beta0/(max_Lf_s+max_M_s/beta0+beta0)); //cout<<"tmp7: "<<tmp7<<"; "<<val_tau/(this->n+0.)*sqrt(beta0/(max_Lf_s+max_M_s/beta0+beta0))<<endl; //m_0=(2*log(val_rho)+log(val_eta)+log(2))/log(tmp7); cout<<" m_s="<<m_s<<endl; } void Initialize(D beta_0, D epsilon_0, D val_eta, D val_rho,L val_tau, vector<D> & x0,vector<D> & y0){ cout<<"start initializing ALM"<<endl; set_dimension(); this->nsamples=m+1; this->nfeatures=d; this->tau=val_tau; beta_s=beta_0; tau_s= 1; epsilon_s=epsilon_0; compute_m0(beta_s,val_eta,val_rho,val_tau); eta=val_eta; rho=val_rho; x_s.resize(d,0); old_x_s.resize(d,0); lambda_s.resize(m,0); old_lambda_s.resize(m,0); for(L i=0;i<d;i++){ x_s[i]=x0[i]; old_x_s[i]= x0[i]; } for(L j=0;j<m;j++){ lambda_s[j]=y0[j]; old_lambda_s[j]= y0[j]; } g_tmp.clear(); g_tmp.resize(d,0); g_tmp_x.clear(); g_tmp_x.resize(d,0); g_tmp_w.clear(); g_tmp_w.resize(d,0); valuefi.clear(); valuefi.resize(m,0); x_tmp.clear(); x_tmp.resize(d,0); is_feasiblity_constraint.resize(m,0); set_is_feasibility_constraint(); cout<<"Initialization ALM finished!"<<endl; } void reset_everything(){ epsilon_s*=rho; beta_s*=eta; } void update_m_s(L val_tau){ D tmp= 0; D tmpx= 0; D tmpy= 0; D tmpy2= 0; for(L j=0;j<m;j++) { D tmp_p= prox_of_h_star_j(valuefi[j]/beta_s/eta+ lambda_s[j], beta_s/eta, j); tmpy+=(tmp_p- lambda_s[j])*(tmp_p- lambda_s[j]); tmp+= (lambda_s[j]- old_lambda_s[j])*(lambda_s[j]- old_lambda_s[j]); tmpy2+= (beta_s*eta*lambda_s[j]- beta_s*old_lambda_s[j])*(beta_s*eta*lambda_s[j]- beta_s*old_lambda_s[j]); } for (L i= 0; i< d;i++){ tmpx= (x_s[i]- old_x_s[i])*(x_s[i]- old_x_s[i]); } D tmp4= 2*epsilon_s+ beta_s*tmp; D tmp5= (1- eta)*beta_s/2*tmpy; D tmp6= 0; D tmp7= sqrt(tmp)*sqrt(tmpy2); D tmp1= log(tmp4+ tmp5+ tmp6+ tmp7+ 2/(2*eta- 1)*tau_s*beta_s/2*tmpx); D tmp2= log(epsilon_s)+ log(rho)- log(2); D tmp3= sqrt(beta_s/this->sumLi); m_s= ceil((tmp1- tmp2)/log(2)*4*max(1.0+this->nsamples,1/tmp3)/val_tau); cout<<"here here="<<tmp4<<" tmp5="<<tmp5<<" tmp6="<<tmp6<<" tmp7="<<tmp7<<" tmp1="<<tmp1<<" tmp2="<<tmp2<<" tmp3="<<tmp3<<endl; } inline void compute_and_record_res(){ if(nb_outer_iters%print_every_N_ALM==0){ compute_function_value(); cout<<setprecision(9)<<"Iteration: "<<nb_outer_iters<<"; time="<<running_time_ALM<< "; function value="<<function_value<<"; infeasibility= "<< infeasibility<<endl; samp_ALM<<setprecision(9)<<nb_outer_iters<<" "<<running_time_ALM<<" "<< function_value<<" "<< infeasibility<<endl; } } void ALM_solve_with_L_Katyusha(D beta_0, D epsilon_0, D eta, D rho,vector<D> & x0,vector<D> & y0, L val_tau, L max_nb_outer, L p_N_1, L p_N_2, string filename1, string filename2, D time){ Initialize(beta_0, epsilon_0, eta, rho,val_tau, x0, y0); nb_outer_iters=0; filename1= "results/ALM_"+filename1; samp_ALM.open(filename1.c_str()); running_time_ALM=0; print_every_N_ALM=p_N_1; this->set_print_every_N(p_N_2); compute_and_record_res(); while(nb_outer_iters<max_nb_outer){ D start= std::clock(); cout<<"m_s= "<< ceil(m_s/this->nsamples*val_tau)<<"; beta_s="<<beta_s<<"; epsilon_s="<<epsilon_s<<endl; this->loopless2(x_s, filename2, mu_g+ tau_s*beta_s, ceil(m_s/this->nsamples*val_tau), epsilon_s, val_tau, 1, 1, 0, 1); for(L i=0;i<d;i++){ old_x_s[i]=x_s[i]; } for(L i=0;i<m;i++){ old_lambda_s[i]=lambda_s[i]; } compute_x(); update_lambda(); update_m_s(val_tau); nb_outer_iters++; running_time_ALM+=( std::clock() - start ) / (double) CLOCKS_PER_SEC; compute_and_record_res(); start = std::clock(); reset_everything(); running_time_ALM+=( std::clock() - start ) / (double) CLOCKS_PER_SEC; if (running_time_ALM> time){ break; } } } }; #endif /* MIN_SMOOTH_CONVEX_H */
{ "alphanum_fraction": 0.6352091088, "avg_line_length": 24.2925531915, "ext": "h", "hexsha": "509369ffc0255ba641bd454d27c670d660cf5b7a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_forks_repo_licenses": [ "BSD-Source-Code" ], "max_forks_repo_name": "lifei16/supplementary_code", "max_forks_repo_path": "IPALM/ALM_L_Katyusha.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-Source-Code" ], "max_issues_repo_name": "lifei16/supplementary_code", "max_issues_repo_path": "IPALM/ALM_L_Katyusha.h", "max_line_length": 188, "max_stars_count": null, "max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_stars_repo_licenses": [ "BSD-Source-Code" ], "max_stars_repo_name": "lifei16/supplementary_code", "max_stars_repo_path": "IPALM/ALM_L_Katyusha.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3121, "size": 9134 }
/* -*- c -*- */ /* * Copyright 2002-2018 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * generate MMSE FIR interpolation table values */ #include <math.h> #include <assert.h> #include <gsl/gsl_integration.h> #define MU 0.5 /* the MU for which we're computing coeffs */ #define Ts (1.0) /* sampling period */ #define B (1.0/(4*Ts)) /* one-sided signal bandwidth */ //#define B (1.0/(8./3*Ts)) /* one-sided signal bandwidth */ static unsigned global_n; static double *global_h; double global_mu = MU; double global_B = B; gsl_integration_workspace *global_gsl_int_workspace = NULL; /* * This function computes the difference squared between the ideal * interpolator frequency response at frequency OMEGA and the * approximation defined by the FIR coefficients in global_h[] * * See eqn (9-7), "Digital Communication Receivers", Meyr, Moeneclaey * and Fechtel, Wiley, 1998. */ static double integrand (double omega, void *params) { double real_ideal; double real_approx; double real_diff; double imag_ideal; double imag_approx; double imag_diff; int i, n; int I1; double *h; real_ideal = cos (omega * Ts * global_mu); imag_ideal = sin (omega * Ts * global_mu); n = global_n; h = global_h; I1 = -(n / 2); real_approx = 0; imag_approx = 0; for (i = 0; i < n; i++){ real_approx += h[i] * cos (-omega * Ts * (i + I1)); imag_approx += h[i] * sin (-omega * Ts * (i + I1)); } real_diff = real_ideal - real_approx; imag_diff = imag_ideal - imag_approx; return real_diff * real_diff + imag_diff * imag_diff; } /* * Integrate the difference squared over all frequencies of interest. */ double c_fcn (double *x, int n) { gsl_function F; double result, error; F.function = integrand; F.params = NULL; assert ((n & 1) == 0); /* assert n is even */ global_n = n; global_h = x; gsl_integration_qag(&F, -2 * M_PI * global_B, 2 * M_PI * global_B, 0.0, 1e-12, 1000, GSL_INTEG_GAUSS61, global_gsl_int_workspace, &result, &error); return result; } /* this is the interface expected by the calling fortran code */ double objective (double x[], int *ndim) { return c_fcn (x, *ndim); } static double si (double x) { if (fabs (x) < 1e-9) return 1.0; return sin(x) / x; } /* * starting guess for optimization */ void initpt (double x[], int ndim) { int i; for (i = 0; i < ndim; i++){ x[i] = si (M_PI * ((double) (i - ndim/2) + global_mu)); } }
{ "alphanum_fraction": 0.6592592593, "avg_line_length": 23.8235294118, "ext": "c", "hexsha": "061fdf4970eb8e176bcb8c3d3732fbb985f78322", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "v1259397/cosmic-gnuradio", "max_forks_repo_path": "gnuradio-3.7.13.4/gr-filter/lib/gen_interpolator_taps/objective_fct.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "v1259397/cosmic-gnuradio", "max_issues_repo_path": "gnuradio-3.7.13.4/gr-filter/lib/gen_interpolator_taps/objective_fct.c", "max_line_length": 71, "max_stars_count": 1, "max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "v1259397/cosmic-gnuradio", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-filter/lib/gen_interpolator_taps/objective_fct.c", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z", "num_tokens": 938, "size": 3240 }
/* $Id$ */ /*--------------------------------------------------------------------*/ /*; Copyright (C) 2003-2013 */ /*; Associated Universities, Inc. Washington DC, USA. */ /*; */ /*; This program is free software; you can redistribute it and/or */ /*; modify it under the terms of the GNU General Public License as */ /*; published by the Free Software Foundation; either version 2 of */ /*; the License, or (at your option) any later version. */ /*; */ /*; This program is distributed in the hope that it will be useful, */ /*; but WITHOUT ANY WARRANTY; without even the implied warranty of */ /*; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /*; GNU General Public License for more details. */ /*; */ /*; You should have received a copy of the GNU General Public */ /*; License along with this program; if not, write to the Free */ /*; Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, */ /*; MA 02139, USA. */ /*; */ /*;Correspondence about this software should be addressed as follows: */ /*; Internet email: bcotton@nrao.edu. */ /*; Postal address: William Cotton */ /*; National Radio Astronomy Observatory */ /*; 520 Edgemont Road */ /*; Charlottesville, VA 22903-2475 USA */ /*--------------------------------------------------------------------*/ #ifndef OBITFFT_H #define OBITFFT_H /* FFTW3 ? */ #if HAVE_FFTW3==1 #include <fftw3.h> #elif HAVE_FFTW==1 /* else Try FFTW 2 */ #include <fftw.h> #include <rfftw.h> #elif HAVE_GSL==1 /* Else try GSL version */ #include <gsl/gsl_fft_complex_float.h> #include <gsl/gsl_fft_halfcomplex_float.h> #include <gsl/gsl_fft_real_float.h> #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_fft_halfcomplex.h> #include <gsl/gsl_fft_real.h> #endif /* HAVE_GSL */ #include "Obit.h" #include "ObitThread.h" #include "ObitFArray.h" #include "ObitCArray.h" /*-------- Obit: Merx mollis mortibus nuper ------------------*/ /** * \file ObitFFT.h * ObitFFT Fast Fourier Transform class definition. * * This class is derived from the #Obit class. * * This class is for performing FFT on memory resident data. * This implementation uses the FFTW package if available, else gsl * * \section FFTOrder Data order * Data passed to and from ObitFFT routines are as an ObitFArray or ObitCArray * which are stored in column major (Fortran) order. * Data are passed and returned in "center-at-the-edge" (i.e. unnatural) order * and there is NO transpose of the array axes. * In the half complex form, the first axis is nx/2+1 where nx is the number of * real elements. * Only even numbers of elements on each axis will work well. * * \section ObitFFTaccess Creators and Destructors * An ObitFFT can be created using newObitFFT which allows specifying * a name for the object, and the type, size and direction of the transform. * * A copy of a pointer to an ObitFFT should always be made using the * #ObitFFTRef function which updates the reference count in the object. * Then whenever freeing an ObitFFT or changing a pointer, the function * #ObitFFTUnref will decrement the reference count and destroy the object * when the reference count hits 0. * There is no explicit destructor. * * \section Multi-threaded operation * If this module is compiled with the -DHAVE_FFTW3THREADS==1 option * and linked with the -lfftw3f_threads option, multithreaded operation * is enabled. * NOTE: this should NOT be used inside ObitThreads as the threading will * collide. * The maximum number of threads to be used in subsequent ObitFFT objects is * set using #ObitFFTNThreads; setting nThreads to 1 turns off threading. * After all ObitFFT objects are destroyed, calling #ObitFFTClearThreads * will clean up after the threading. */ /*-------------- enumerations -------------------------------------*/ /** * \enum ObitFFTdir * enum for FFT direction * This specifies the status of the connection a disk resident data. */ enum obitFFTdir { /** Sign of exponent in transform = -1, real to complex */ OBIT_FFT_Forward, /** Sign of exponent in transform = +1, complex to real */ OBIT_FFT_Reverse }; /* end enum obitFFTdir */ /** typedef for enum for ObitIO object status. */ typedef enum obitFFTdir ObitFFTdir; /** * \enum ObitFFTtype * enum for FFT type, complex to complex or real to complex/ * This specifies the status of the connection a disk resident data. */ enum obitFFTtype { /** Full complex to complex transforms */ OBIT_FFT_FullComplex, /** Real to half complex or reverse. */ OBIT_FFT_HalfComplex }; /* end enum obitFFTtype */ /** typedef for enum for ObitIO object status. */ typedef enum obitFFTtype ObitFFTtype; /*--------------Class definitions-------------------------------------*/ /** ObitFFT Class structure. */ typedef struct { #include "ObitFFTDef.h" /* this class definition */ } ObitFFT; /*----------------- Macroes ---------------------------*/ /** * Macro to unreference (and possibly destroy) an ObitFFT * returns a ObitFFT*. * in = object to unreference */ #define ObitFFTUnref(in) ObitUnref (in) /** * Macro to reference (update reference count) an ObitFFT. * returns a ObitFFT*. * in = object to reference */ #define ObitFFTRef(in) ObitRef (in) /** * Macro to determine if an object is the member of this or a * derived class. * Returns TRUE if a member, else FALSE * in = object to reference */ #define ObitFFTIsA(in) ObitIsA (in, ObitFFTGetClass()) /*---------------Public functions---------------------------*/ /** Public: Class initializer. */ void ObitFFTClassInit (void); /** Public: Constructor. */ ObitFFT* newObitFFT (gchar* name, ObitFFTdir dir, ObitFFTtype type, olong rank, olong *dim); /** Typedef for definition of class pointer structure */ typedef ObitFFT* (*newObitFFTFP) (gchar *name, ObitFFTdir dir, ObitFFTtype type, olong rank, olong *dim); /** Public: ClassInfo pointer */ gconstpointer ObitFFTGetClass (void); /** Public: Suggest efficient size for a transform */ olong ObitFFTSuggestSize (olong length); /** Public: Enable threading */ void ObitFFTNThreads (olong nThreads); /** Public: Cleanup threading */ void ObitFFTClearThreads (void); /** Public: Real to half Complex. */ void ObitFFTR2C (ObitFFT *in, ObitFArray *inArray, ObitCArray *outArray); typedef void (*ObitFFTR2CFP) (ObitFFT *in, ObitFArray *inArray, ObitCArray *outArray); /** Public: Half Complex to Real. */ void ObitFFTC2R (ObitFFT *in, ObitCArray *inArray, ObitFArray *outArray); typedef void (*ObitFFTC2RFP) (ObitFFT *in, ObitCArray *inArray, ObitFArray *outArray); /** Public: Full Complex to Complex. */ void ObitFFTC2C (ObitFFT *in, ObitCArray *inArray, ObitCArray *outArray); typedef void (*ObitFFTC2CFP) (ObitFFT *in, ObitCArray *inArray, ObitCArray *outArray); /*----------- ClassInfo Structure -----------------------------------*/ /** * ClassInfo Structure. * Contains class name, a pointer to any parent class * (NULL if none) and function pointers. */ typedef struct { #include "ObitFFTClassDef.h" } ObitFFTClassInfo; #endif /* OBITFFT_H */
{ "alphanum_fraction": 0.6213063764, "avg_line_length": 38.58, "ext": "h", "hexsha": "868302fc26f5347db5656c47f357e73ca92a1c18", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z", "max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": [ "Linux-OpenIB" ], "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_path": "ObitSystem/Obit/include/ObitFFT.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Linux-OpenIB" ], "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_path": "ObitSystem/Obit/include/ObitFFT.h", "max_line_length": 80, "max_stars_count": 5, "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": [ "Linux-OpenIB" ], "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_path": "ObitSystem/Obit/include/ObitFFT.h", "max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z", "num_tokens": 1889, "size": 7716 }
//-------------------------------------------------------------------------------------------------- // // WIN-BLUETOOTH // //-------------------------------------------------------------------------------------------------- // // The MIT License (MIT) // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //-------------------------------------------------------------------------------------------------- // // Copyright (c) 2018 Nic Holthaus // //-------------------------------------------------------------------------------------------------- // // ATTRIBUTION: // https://github.com/martinmoene/gsl-lite/releases // //-------------------------------------------------------------------------------------------------- // /// @file obexResponse.h /// @brief OBEX server response classes // //-------------------------------------------------------------------------------------------------- #pragma once #ifndef obexResponse_h__ #define obexResponse_h__ //------------------------- // INCLUDES //------------------------- #include <QObject> #include <gsl-lite.h> #include <obexHeader.h> //------------------------- // FORWARD DECLARATIONS //------------------------- class QDataStream; //-------------------------------------------------------------------------------------------------- // OBEXResponse //-------------------------------------------------------------------------------------------------- class OBEXResponse { Q_GADGET public: friend QDataStream& operator>>(QDataStream& in, OBEXResponse& response); // OBEX operation response codes. See OBEX standard chapter 3.2.1 class Code { public: enum class Enum : quint8 { INVALID = 0x00, CONTINUE = 0x90, SUCCESS = 0xA0, SERVICEUNAVAILABLE = 0xD3, }; Code(quint8 value); operator quint8() const; bool isFinal() const; bool operator==(const Code& other) const; bool operator!=(const Code& other) const; private: Code::Enum m_code; bool m_isFinal = false; }; public: OBEXResponse() = default; virtual ~OBEXResponse() = default; virtual gsl::string_span data() = 0; // returns a span representing the response-specific data storage virtual quint16 packetLength() = 0; // packet length value from the response data virtual bool validateAndFixup() = 0; // called at the end of operator>>. Used to validate code fields, and convert // large types from big to little endian. Returns true on success. bool isValid() const; protected: bool m_valid = false; std::vector<OBEXHeader> m_optionalHeaders; }; QDataStream& operator>>(QDataStream& in, OBEXResponse& response); //-------------------------------------------------------------------------------------------------- // OBEXConnectResponse //-------------------------------------------------------------------------------------------------- class OBEXConnectResponse : public OBEXResponse { public: OBEXConnectResponse() = default; virtual ~OBEXConnectResponse() = default; virtual gsl::string_span data() override; virtual quint16 packetLength() override; // the return value will generally not be valid until after data has been streamed into the class. virtual bool validateAndFixup() override; quint16 maxPacketLength() const; private: #pragma pack(push, 1) struct Data { OBEXResponse::Code::Enum code = Code::Enum::INVALID; quint16 length = 0; quint8 version = 0; quint8 flags = 0; quint16 maxPacketLength = 0; } m_data; #pragma pack(pop) }; //-------------------------------------------------------------------------------------------------- // OBEXDisconnectResponse //-------------------------------------------------------------------------------------------------- class OBEXDisconnectResponse : public OBEXResponse { public: OBEXDisconnectResponse() = default; virtual ~OBEXDisconnectResponse() = default; virtual gsl::string_span data() override; virtual quint16 packetLength() override; virtual bool validateAndFixup() override; #pragma pack(push, 1) struct Data { OBEXResponse::Code::Enum code = Code::Enum::SUCCESS; quint16 length = 0; } m_data; #pragma pack(pop) }; //-------------------------------------------------------------------------------------------------- // OBEXPutResponse //-------------------------------------------------------------------------------------------------- class OBEXPutResponse : public OBEXResponse { public: OBEXPutResponse() = default; virtual ~OBEXPutResponse() = default; virtual gsl::string_span data() override; virtual quint16 packetLength() override; virtual bool validateAndFixup() override; bool continueSending() const; protected: #pragma pack(push, 1) struct Data { OBEXResponse::Code::Enum code = Code::Enum::CONTINUE; // assume success until proven otherwise quint16 length = 0; } m_data; #pragma pack(pop) }; #endif // obexResponse_h__
{ "alphanum_fraction": 0.5380727763, "avg_line_length": 30.7564766839, "ext": "h", "hexsha": "5cc1a8798b14c9a597244f84098e88bc3ebcb19e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2018-07-30T08:41:16.000Z", "max_forks_repo_forks_event_min_datetime": "2018-07-17T12:06:28.000Z", "max_forks_repo_head_hexsha": "f0b7f961e3e1d8dd00f5536a203f94e8316c1c17", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "nholthaus/win-bluetooth", "max_forks_repo_path": "include/obexResponse.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "f0b7f961e3e1d8dd00f5536a203f94e8316c1c17", "max_issues_repo_issues_event_max_datetime": "2021-09-28T21:16:07.000Z", "max_issues_repo_issues_event_min_datetime": "2021-08-19T11:18:04.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "nholthaus/win-bluetooth", "max_issues_repo_path": "include/obexResponse.h", "max_line_length": 140, "max_stars_count": 5, "max_stars_repo_head_hexsha": "f0b7f961e3e1d8dd00f5536a203f94e8316c1c17", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "nholthaus/win-bluetooth", "max_stars_repo_path": "include/obexResponse.h", "max_stars_repo_stars_event_max_datetime": "2021-03-17T09:43:30.000Z", "max_stars_repo_stars_event_min_datetime": "2018-07-18T01:31:37.000Z", "num_tokens": 1171, "size": 5936 }
#include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_roots.h> #include "demo_fn.h" #include "demo_fn.c" int main (void) { int status; int iter = 0, max_iter = 100; const gsl_root_fdfsolver_type *T; gsl_root_fdfsolver *s; double x0, x = 5.0, r_expected = sqrt (5.0); gsl_function_fdf FDF; struct quadratic_params params = {1.0, 0.0, -5.0}; FDF.f = &quadratic; FDF.df = &quadratic_deriv; FDF.fdf = &quadratic_fdf; FDF.params = &params; T = gsl_root_fdfsolver_newton; s = gsl_root_fdfsolver_alloc (T); gsl_root_fdfsolver_set (s, &FDF, x); printf ("using %s method\n", gsl_root_fdfsolver_name (s)); printf ("%-5s %10s %10s %10s\n", "iter", "root", "err", "err(est)"); do { iter++; status = gsl_root_fdfsolver_iterate (s); x0 = x; x = gsl_root_fdfsolver_root (s); status = gsl_root_test_delta (x, x0, 0, 1e-3); if (status == GSL_SUCCESS) printf ("Converged:\n"); printf ("%5d %10.7f %+10.7f %10.7f\n", iter, x, x - r_expected, x - x0); } while (status == GSL_CONTINUE && iter < max_iter); gsl_root_fdfsolver_free (s); return status; }
{ "alphanum_fraction": 0.6104218362, "avg_line_length": 22.8113207547, "ext": "c", "hexsha": "fea5f110192870f94da343a123486f0c75ecfe68", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/rootnewt.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/rootnewt.c", "max_line_length": 52, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/rootnewt.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 413, "size": 1209 }
/* randist/gumbel.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> /* The Type I Gumbel distribution has the form, p(x) dx = a b exp(-(b exp(-ax) + ax)) dx and the Type II Gumbel distribution has the form, p(x) dx = b a x^-(a+1) exp(-b x^-a)) dx */ double gsl_ran_gumbel1 (const gsl_rng * r, const double a, const double b) { double x = gsl_rng_uniform_pos (r); double z = (log(b) - log(-log(x))) / a; return z; } double gsl_ran_gumbel1_pdf (const double x, const double a, const double b) { double p = a * b * exp (-(b * exp(-a * x) + a * x)); return p; } double gsl_ran_gumbel2 (const gsl_rng * r, const double a, const double b) { double x = gsl_rng_uniform_pos (r); double z = pow(-b / log(x), 1/a); return z; } double gsl_ran_gumbel2_pdf (const double x, const double a, const double b) { if (x <= 0) { return 0 ; } else { double p = b * a * pow(x,-(a+1)) * exp (-b * pow(x, -a)); return p; } }
{ "alphanum_fraction": 0.6553980371, "avg_line_length": 23.2151898734, "ext": "c", "hexsha": "65aff8d3d5b24c7d3318eff7c86cea8b5c989e93", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/randist/gumbel.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/randist/gumbel.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/randist/gumbel.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 561, "size": 1834 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_errno.h> #include "ccl.h" //Spline creator //n -> number of points //x -> x-axis //y -> f(x)-axis //y0,yf -> values of f(x) to use beyond the interpolation range ccl_f1d_t *ccl_f1d_t_new(int n,double *x,double *y,double y0,double yf) { ccl_f1d_t *spl=malloc(sizeof(ccl_f1d_t)); if(spl==NULL) return NULL; spl->spline=gsl_spline_alloc(gsl_interp_cspline,n); if (spl->spline == NULL) { free(spl); return NULL; } int parstatus=gsl_spline_init(spl->spline,x,y,n); if(parstatus) { gsl_spline_free(spl->spline); free(spl); return NULL; } spl->x0=x[0]; spl->xf=x[n-1]; spl->y0=y0; spl->yf=yf; return spl; } //Evaluates spline at x checking for bound errors double ccl_f1d_t_eval(ccl_f1d_t *spl,double x) { if(x<=spl->x0) return spl->y0; else if(x>=spl->xf) return spl->yf; else { double y; int stat=gsl_spline_eval_e(spl->spline,x,NULL,&y); if (stat!=GSL_SUCCESS) { ccl_raise_gsl_warning(stat, "ccl_utils.c: ccl_splin_eval():"); return NAN; } return y; } } //Spline destructor void ccl_f1d_t_free(ccl_f1d_t *spl) { if (spl != NULL) { gsl_spline_free(spl->spline); } free(spl); }
{ "alphanum_fraction": 0.6340125392, "avg_line_length": 19.0447761194, "ext": "c", "hexsha": "ba12b6463d4ab53fcdab8a88659ca0882022633b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z", "max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "benediktdiemer/CCL", "max_forks_repo_path": "src/ccl_f1d.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "benediktdiemer/CCL", "max_issues_repo_path": "src/ccl_f1d.c", "max_line_length": 71, "max_stars_count": null, "max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "benediktdiemer/CCL", "max_stars_repo_path": "src/ccl_f1d.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 447, "size": 1276 }
#include "../include/paralleltt.h" #include <math.h> #include <stdlib.h> #include <stdio.h> #include <mpi.h> #include <cblas.h> #include <string.h> #include <lapacke.h> #define min(a,b) ((a)>(b)?(b):(a)) #define abs(a) ((a)>(0)?(a):(-a)) #ifndef HEAD #define HEAD (int) 0 #endif matrix_tt* matrix_tt_init(const int m, const int n) { matrix_tt* A = (matrix_tt*) malloc(sizeof(matrix_tt)); A->m = m; A->n = n; A->transpose = 0; A->offset = 0; A->lda = m; A->X_size = (long) m*n; A->X = (double*) malloc(A->X_size*sizeof(double)); return A; } void matrix_tt_wrap_update(matrix_tt* A, int m, int n, double* X) { A->m = m; A->n = n; A->transpose = 0; A->offset = 0; A->lda = m; A->X_size = (long) m*n; A->X = X; } matrix_tt* matrix_tt_wrap(int m, int n, double* X) { matrix_tt* A = (matrix_tt*) malloc(sizeof(matrix_tt)); A->m = m; A->n = n; A->transpose = 0; A->offset = 0; A->lda = m; A->X_size = (long) m*n; A->X = X; return A; } matrix_tt* matrix_tt_copy(const matrix_tt* A) { matrix_tt* B = (matrix_tt*) malloc(sizeof(matrix_tt)); int m = A->m; int n = A->n; int X_size = A->X_size; B->m = m; B->n = n; B->transpose = A->transpose; B->offset = A->offset; B->lda = A->lda; B->X_size = X_size; B->X = (double*) malloc(X_size * sizeof(double)); memcpy(B->X, A->X, X_size * sizeof(double)); return B; } // Copy from matrix A to matrix B void matrix_tt_copy_data(matrix_tt* B, const matrix_tt* A) { int BT = (B->transpose == 0) ? 0 : 1; int AT = (A->transpose == 0) ? 0 : 1; if (BT == AT){ if ((B->m != A->m) || (B->n != A->n)){ printf("matrix_tt_copy_data: B (%d x %d) is not the same size as A (%d x %d)\n", B->n, B->m, A->n, A->m); return; } for (int jj = 0; jj < B->n; ++jj){ memcpy((B->X) + (B->offset) + (B->lda)*jj, (A->X) + (A->offset) + jj*(A->lda), (B->m)*sizeof(double)); } } else{ if ((B->m != A->n) || (B->n != A->m)){ printf("matrix_tt_copy_data: B (%d x %d, transpose = %d) is not the same size as A (%d x %d, transpose = %d)\n", B->n, B->m, B->transpose, A->n, A->m, A->transpose); return; } for (int jj = 0; jj < B->n; ++jj){ double* BX = (B->X) + (B->offset) + (B->lda)*jj; double* AX = (A->X) + (A->offset) + jj; for (int ii = 0; ii < B->m; ++ii){ BX[ii] = AX[ii*(A->lda)]; } } } } matrix_tt* submatrix_copy(const matrix_tt* A) { matrix_tt* B = (matrix_tt*) malloc(sizeof(matrix_tt)); int m = A->m; int n = A->n; int X_size = m*n; B->m = m; B->n = n; B->transpose = A->transpose; B->offset = 0; B->lda = m; B->X_size = X_size; B->X = (double*) malloc(X_size * sizeof(double)); matrix_tt_copy_data(B, A); return(B); } // NOTE: reshape and submatrix will not work well together. void matrix_tt_reshape(int m, int n, matrix_tt* A) { long new_size = (long) m*n; if (new_size > A->X_size){ printf("Reshape failed: m*n=%ld is too large for X_size=%ld\n", (long) new_size, A->X_size); } else{ A->m = m; A->n = n; A->offset = 0; A->lda = m; } } // In matlab notation, returns A[ii1:ii2-1, jj1:jj2-1] matrix_tt* submatrix(const matrix_tt* A, int ii1, int ii2, int jj1, int jj2) { int mA = A->m; int nA = A->n; int lda = A->lda; if ((ii1 < 0) || (ii2 < ii1) || (mA < ii2) || (jj1 < 0) || (jj2 < jj1) || (nA < jj2)){ printf("Cannot take the A[%d:%d,%d:%d] of a %d by %d matrix (Matlab notation)\n", ii1, ii2-1, jj1, jj2-1, mA, nA); } matrix_tt* B = (matrix_tt*) malloc(sizeof(matrix_tt)); B->m = ii2 - ii1; B->n = jj2 - jj1; B->transpose = A->transpose; B->offset = ii1 + jj1*lda; B->lda = lda; B->X_size = A->X_size; B->X = A->X + A->offset; return B; } // Updates the indices of the submatrix A void submatrix_update(matrix_tt* A, int ii1, int ii2, int jj1, int jj2) { A->m = ii2 - ii1; A->n = jj2 - jj1; A->offset = ii1 + jj1*(A->lda); } // Get an element of the matrix double matrix_tt_element(const matrix_tt* A, int ii, int jj) { return A->X[A->offset + ii + (A->lda)*jj]; } void matrix_tt_free(matrix_tt* A) { free(A->X); A->X = NULL; free(A); return; } void matrix_tt_print(const matrix_tt* A, int just_the_matrix) { int m = A->m; int n = A->n; int T = A->transpose; int offset = A->offset; int lda = A->lda; if (!just_the_matrix){ printf("Size of matrix: m=%d, n=%d\n", m, n); printf("Transpose=%d, offset=%d, lda=%d\n", T, offset, lda); printf("X_size=%ld\n", A->X_size); printf("X"); if (T){ printf("^T"); } printf(" is \n"); } int mloop = T ? m : n; int nloop = T ? n : m; printf("["); for (int jj = 0; jj < nloop; ++jj){ for (int ii = 0; ii < mloop; ++ii){ if (!T){ printf("%f",A->X[lda*ii + jj + offset]); } else{ printf("%f",A->X[lda*jj + ii + offset]); } if (ii < mloop-1){ printf(", "); } } if (jj == nloop - 1){ printf("]\n"); } else{ printf(",\n "); } } } double frobenius_norm(matrix_tt* A){ double norm = 0; if (A->m == A->lda){ norm = cblas_dnrm2(A->m * A->n, A->offset + A->X, 1); } else{ for (int ii = 0; ii < A->n; ++ii){ double tmp = cblas_dnrm2(A->m, A->offset + (A->lda)*ii + A->X, 1); norm = sqrt(norm*norm + tmp*tmp); } } return norm; } // Performs the operation C = alpha*A*B + beta*C, where A and B are appropriately transposed int matrix_tt_dgemm(const matrix_tt* A, const matrix_tt* B, matrix_tt* C, const double alpha, const double beta) { int mA = A->m; int nA = A->n; int mB = B->m; int nB = B->n; int m_check = C->m; int n_check = C->n; int k_check; int m; int n; int k; CBLAS_TRANSPOSE TransA; CBLAS_TRANSPOSE TransB; if (A->transpose == 0){ TransA = CblasNoTrans; m = mA; k = nA; } else{ TransA = CblasTrans; m = nA; k = mA; } if (B->transpose == 0){ TransB = CblasNoTrans; k_check = mB; n = nB; } else{ TransB = CblasTrans; k_check = nB; n = mB; } if ((m != m_check) || (n != n_check) || (k != k_check)){ printf("Dimensions of input arrays do not match:\n"); printf("A: m=%d, n=%d, tranpose=%d\n",mA,nA,A->transpose); printf("B: m=%d, n=%d, tranpose=%d\n",mB,nB,B->transpose); printf("C: m=%d, n=%d, tranpose=%d\n",m_check,n_check,C->transpose); return 1; } C->transpose = 0; cblas_dgemm(CblasColMajor, TransA, TransB, m, n, k, alpha, A->X + A->offset, A->lda, B->X + B->offset, B->lda, beta, C->X + C->offset, C->lda); return 0; } // Solves the least squares problem Ax = b // At the end, it just copies the result into x. This probably isn't the most efficient way to do this void matrix_tt_dgels(matrix_tt* x, matrix_tt* A, const matrix_tt* b) { if (x->transpose != 0){ printf("matrix_tt_least_squares: x cannot be transposed for dgels\n"); return; } if (b->transpose != 0){ printf("matrix_tt_least_squares: b cannot be transposed for dgels\n"); return; } int nrhs = x->n; char TransA; int m_check; int n_check; if (A->transpose == 0){ TransA = 'N'; m_check = A->m; n_check = A->n; } else{ TransA = 'T'; m_check = A->n; n_check = A->m; } if (n_check != x->m){ printf("right index of A (%d) does not match left index of x (%d)\n", n_check, x->m); } if (m_check != b->m){ printf("left index of A (%d) does not match left index of b (%d)\n", m_check, b->m); } if (x->n != b->n){ printf("right index of x (%d) does not match right index of b (%d)\n", x->n, b->n); } int m = A->m; int n = A->n; int info = LAPACKE_dgels(LAPACK_COL_MAJOR, TransA, m, n, nrhs, A->X + A->offset, A->lda, b->X + b->offset, b->lda); matrix_tt* result = submatrix(b, 0, x->m, 0, x->n); matrix_tt_copy_data(x, result); free(result); } // Input: // Q - the matrix you want to take the QR // Output: // Q - the Q matrix of QR // R - (input is NULL) ? nothing : the R matrix of QR // NOTE: Currently assumes R and Q are not transposed int matrix_tt_truncated_qr(matrix_tt* Q, matrix_tt* R, int r) { int Qm = Q->m; int Qn = Q->n; double* QX = Q->X; int Qtranspose = Q->transpose; long Qoffset = Q->offset; int Qlda = Q->lda; lapack_int info; if (Qtranspose == 0){ if (r > Qn) { printf("ERROR: (matrix_tt_truncated_qr) r = %d is too large for Q->n = %d \n", r, Qn); return 1; } // The QR step double* tau = (double*) malloc(sizeof(double)*min(Qm,Qn)); info = LAPACKE_dgeqrf(LAPACK_COL_MAJOR, Qm, Qn, QX + Qoffset, Qlda, tau); if (R != NULL){ int Rm = R->m; int Rn = R->n; double* RX = R->X; int Rtranspose = R->transpose; long Roffset = R->offset; int Rlda = R->lda; if ((Rm != r) || (Rn != r)){ printf("ERROR: (matrix_tt_truncated_qr) R->m = %d or R->n = %d is not equal to r = %d\n", Rm, Rn, r); return 1; } if (Rtranspose != 0){ printf("ERROR: (matrix_tt_truncated_qr) Only defined for R->transpose = 0\n"); return 1; } for (int jj = 0; jj < r; ++jj){ int r_col_length = (Qm < jj+1) ? (Qm) : jj+1; memcpy(RX + Roffset + jj*Rlda, QX + Qoffset + jj*Qlda, r_col_length*sizeof(double)); memset(RX + Roffset + jj*Rlda + r_col_length, 0, (r-r_col_length)*sizeof(double)); } } if (r > Qm){ LAPACKE_dorgqr(LAPACK_COL_MAJOR, Qm, Qm, Qm, QX + Qoffset, Qlda, tau); matrix_tt* Q_sub = submatrix(Q, 0, Qm, Qm, r); matrix_tt_fill_zeros(Q_sub); free(Q_sub); } else{ LAPACKE_dorgqr(LAPACK_COL_MAJOR, Qm, r, r, QX + Qoffset, Qlda, tau); } Q->n = r; free(tau); tau = NULL; } else{ if (r > Qm) { printf("ERROR: (matrix_tt_truncated_qr) r = %d is too large for Q->n = %d \n", r, Qn); return 1; } // The LQ step printf("Performing LQ\n"); double* tau = (double*) malloc(sizeof(double)*min(Qm,Qn)); info = LAPACKE_dgelqf(LAPACK_COL_MAJOR, Qm, Qn, QX + Qoffset, Qlda, tau); printf("\nRight after LQ, Q = \n"); matrix_tt_print(Q, 1); if (R != NULL){ int Rm = R->m; int Rn = R->n; double* RX = R->X; int Rtranspose = R->transpose; long Roffset = R->offset; int Rlda = R->lda; if ((Rm != r) || (Rn != r)){ printf("ERROR: (matrix_tt_truncated_qr) R->m = %d or R->n = %d is not equal to r = %d\n", Rm, Rn, r); return 1; } if (Rtranspose == 0){ printf("ERROR: (matrix_tt_truncated_qr) Only defined for R->transpose = Q->transpose\n"); return 1; } int ncols = (r > Qm) ? Qm : r; for (int jj = 0; jj < r; ++jj){ if (jj < Qm){ memcpy(RX + Roffset + jj*Rlda + jj, QX + Qoffset + jj*Qlda + jj, (Qm - jj)*sizeof(double)); memset(RX + Roffset + jj*Rlda, 0, jj*sizeof(double)); } } } if (r > Qn){ printf("Doing first dorglq\n"); LAPACKE_dorglq(LAPACK_COL_MAJOR, Qn, Qn, Qn, QX + Qoffset, Qlda, tau); matrix_tt* Q_sub = submatrix(Q, Qn, r, 0, Qn); matrix_tt_fill_zeros(Q_sub); free(Q_sub); } else{ printf("Doing second dorglq\n"); LAPACKE_dorglq(LAPACK_COL_MAJOR, Qm, Qn, Qm, QX + Qoffset, Qlda, tau); } Q->m = r; free(tau); tau = NULL; } return 0; }/**/ void matrix_tt_group_reduce(MPI_Comm comm, int rank, matrix_tt* A, matrix_tt* buf, int head, int* group_ranks, int nranks) { int in_the_group = 0; for (int ii = 0; ii < nranks; ++ii){ if (rank == group_ranks[ii]){ in_the_group = 1; } } if (in_the_group){ int buf_assigned = 0; if (!buf){ buf_assigned = 1; buf = matrix_tt_init(A->m, A->n); } if ((buf->m < A->m) || (buf->n < A->n)){ printf("buf (%d x %d) must be larger than A (%d x %d)\n", buf->m, buf->n, A->m, A->n); } int send = -1; int recv = -1; while (nranks > 1){ int half_nranks = (nranks + 1) / 2; for (int ii = 0; ii < half_nranks; ++ii){ if (ii + half_nranks >= nranks){ recv = group_ranks[ii]; send = -1; } else if (group_ranks[ii + half_nranks] == head){ recv = head; send = group_ranks[ii]; } else{ recv = group_ranks[ii]; send = group_ranks[ii + half_nranks]; } if (rank == send){ matrix_tt_send(comm, A, recv); } else if ((rank == recv) && (send != -1)){ matrix_tt_recv(comm, buf, send); for (int jj = 0; jj < A->n; ++jj){ // MPI_Recv(buf->X + buf->offset, A->m, MPI_DOUBLE, send, 0, comm, MPI_STATUS_IGNORE); long A_offset = A->offset + jj * (A->lda); long buf_offset = buf->offset + jj * (buf->lda); for (int kk = 0; kk < A->m; ++kk){ A->X[A_offset + kk] = A->X[A_offset + kk] + buf->X[buf_offset + kk]; } } } group_ranks[ii] = recv; } nranks = half_nranks; } if (buf_assigned){ matrix_tt_free(buf); } } } // buf just has to be size A->lda x 1 or more void matrix_tt_reduce(MPI_Comm comm, int rank, matrix_tt* A, matrix_tt* buf, int head) { if (buf == NULL){ matrix_tt* buf = matrix_tt_init(A->m, 1); matrix_tt_reduce(comm, rank, A, buf, head); matrix_tt_free(buf); } else{ int size; MPI_Comm_size(comm, &size); if ((head < 0) || (head >= size)){ printf("matrix_tt_reduce: head = %d is not a valid rank for size = %d\n", head, size); } if (buf->lda < A->m){ printf("buf->lda = %d must be larger than A->m = %d\n", buf->lda, A->m); } int* activated_ranks = (int*) calloc(size, sizeof(int)); for (int ii = 0; ii < size; ++ii){ activated_ranks[ii] = ii; } int send = -1; int recv = -1; while (size > 1){ int half_size = (size + 1) / 2; for (int ii = 0; ii < half_size; ++ii){ if (ii + half_size >= size){ recv = activated_ranks[ii]; send = -1; } else if (activated_ranks[ii + half_size] == head){ recv = head; send = activated_ranks[ii]; } else{ recv = activated_ranks[ii]; send = activated_ranks[ii + half_size]; } if (rank == send){ for (int jj = 0; jj < A->n; ++jj){ MPI_Send(A->X + A->offset + A->lda * jj, A->m, MPI_DOUBLE, recv, 0, comm); } } else if ((rank == recv) && (send != -1)){ for (int jj = 0; jj < A->n; ++jj){ MPI_Recv(buf->X + buf->offset, A->m, MPI_DOUBLE, send, 0, comm, MPI_STATUS_IGNORE); long A_offset = A->offset + jj * (A->lda); for (int kk = 0; kk < A->m; ++kk){ A->X[A_offset + kk] = A->X[A_offset + kk] + buf->X[buf->offset + kk]; } } } activated_ranks[ii] = recv; } size = half_size; } free(activated_ranks); } } void matrix_tt_allreduce(MPI_Comm comm, matrix_tt* A) { for (int jj = 0; jj < A->n; ++jj){ MPI_Allreduce(MPI_IN_PLACE, A->X + A->offset + jj*(A->lda), A->m, MPI_DOUBLE, MPI_SUM, comm); } } void matrix_tt_broadcast(MPI_Comm comm, matrix_tt* buf) { int count = buf->m * buf->n; MPI_Bcast(buf->X, count, MPI_DOUBLE, HEAD, comm); } void matrix_tt_send(MPI_Comm comm, matrix_tt* buf, int dest){ MPI_Datatype buf_type; MPI_Type_vector(buf->n, buf->m, buf->lda, MPI_DOUBLE, &buf_type); MPI_Type_commit(&buf_type); MPI_Send(buf->X + buf->offset, 1, buf_type, dest, 0, comm); MPI_Type_free(&buf_type); } void matrix_tt_recv(MPI_Comm comm, matrix_tt* buf, int source){ MPI_Datatype buf_type; MPI_Type_vector(buf->n, buf->m, buf->lda, MPI_DOUBLE, &buf_type); MPI_Type_commit(&buf_type); MPI_Recv(buf->X + buf->offset, 1, buf_type, source, 0, comm, MPI_STATUS_IGNORE); MPI_Type_free(&buf_type); } // Column khatri-rao product C = A x B void khatri_rao(const matrix_tt* restrict A, const matrix_tt* restrict B, matrix_tt* restrict C){ int n = A->n; int m_A = A->m; int n_B = B->n; int m_B = B->m; int n_C = C->n; int m_C = C->m; if ((n != n_B) || (n != n_C) || (m_A*m_B != m_C)){ printf("khatri_rao: the sizes dont work!\n"); printf("A is %d x %d\n", m_A, n); printf("B is %d x %d\n", m_B, n_B); printf("C is %d x %d\n", m_C, n_C); } for (int kk = 0; kk < n; ++kk){ for (int ii = 0; ii < m_B; ++ii){ double Bii = B->X[kk*m_B + ii]; for (int jj = 0; jj < m_A; ++jj){ C->X[kk*m_C + ii*m_B + jj] = Bii * A->X[kk*m_A + jj]; } } } } // Recursively KR multiply the list of matrices A void list_khatri_rao(int d_kr, matrix_tt** A, matrix_tt* Omega){ if (d_kr == 1){ for (int ii = 0; ii < A[0]->X_size; ++ii){ Omega->X[ii] = A[0]->X[ii]; } return; } if (d_kr == 2){ khatri_rao(A[0], A[1], Omega); } else{ int m_B = 1; int n_B = Omega->n; for (int ii = 0; ii < d_kr-1; ++ii){ m_B = m_B * A[ii]->m; } matrix_tt* B = matrix_tt_init(m_B, n_B); list_khatri_rao(d_kr - 1, A, B); khatri_rao(B, A[d_kr - 1], Omega); matrix_tt_free(B); B = NULL; } } void matrix_tt_dlarnv(matrix_tt* A){ int r1 = rand()%4096, r2 = rand()%4096, r3 = rand()%4096, r4 = rand()%4096; int iseed[4] = {r1, r2, r3, r4+(r4%2 == 0?1:0)}; LAPACKE_dlarnv(3, iseed, (A->n) * (A->m), A->X); } void matrix_tt_fill_zeros(matrix_tt* A) { for (int jj = 0; jj < A->n; ++jj){ memset(A->X + A->offset + jj*A->lda, 0, A->m * sizeof(double)); } } // Takes a matrix in row major and transforms it to column major void row_to_col_major(const matrix_tt* mat_row, matrix_tt* mat_col) { int m = mat_col->m; int n = mat_col->n; if ((m != mat_row->n) || (n != mat_row->m)){ printf("The dimensions don't work out! mat_row should have the dimensions of mat_col transposed\n"); printf("mat_row->m = %d, mat_row->n = %d\n", mat_row->m, mat_row->n); printf("mat_col->m = %d, mat_col->n = %d\n", mat_col->m, mat_col->n); } for (int ii = 0; ii < m; ++ii){ for (int jj = 0; jj < n; ++jj){ mat_col->X[jj * (mat_col->lda) + ii + mat_col->offset] = mat_row->X[ii * (mat_row->lda) + jj + mat_row->offset]; } } }
{ "alphanum_fraction": 0.4853993141, "avg_line_length": 29.5369030391, "ext": "c", "hexsha": "da3056e2c74e7cf9beb79b1748d71c7e45554294", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "SidShi/Parallel_TT_sketching", "max_forks_repo_path": "src/matrix_tt.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "SidShi/Parallel_TT_sketching", "max_issues_repo_path": "src/matrix_tt.c", "max_line_length": 124, "max_stars_count": null, "max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "SidShi/Parallel_TT_sketching", "max_stars_repo_path": "src/matrix_tt.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6462, "size": 20410 }
#pragma once #include "utility/types.h" #include "utility/c++std/optional.h" #include "utility/c++std/string_view.h" #include <fmt/format.h> #include <gsl/gsl> namespace cws80 { class NkScreen; class NativeUI; struct Bank; struct Program; /// class UIController { public: virtual ~UIController() {} virtual NkScreen &screen() const = 0; virtual NativeUI &native_ui() const = 0; virtual const Program &program() const = 0; virtual uint bank_number() const = 0; virtual uint program_number() const = 0; virtual gsl::span<const std::string> program_names() const = 0; virtual i32 get_parameter(uint idx) const = 0; virtual bool set_parameter(uint idx, i32 val) = 0; virtual f32 get_f32_parameter(uint idx) const = 0; virtual bool set_f32_parameter(uint idx, f32 val) = 0; virtual void currently_editing_parameter(cxx::optional<uint> idx) = 0; virtual void request_next_bank() = 0; virtual void request_bank(uint num) = 0; virtual void request_program(uint num) = 0; virtual void request_rename_program(cxx::string_view name) = 0; virtual void request_init_program() = 0; virtual void request_write_program() = 0; virtual void dlg_rename_program() = 0; virtual void dlg_load_bank() = 0; virtual void dlg_save_bank() = 0; virtual void send_piano_events(const i8 events[128]) = 0; virtual const std::string &led_message() = 0; virtual void led_message(std::string msg) = 0; virtual void led_priority_message(f64 timeout, std::string msg) = 0; virtual const std::string &status_message() = 0; virtual void status_message(std::string msg) = 0; // template <class A, class... As> void led_fmt(const char *fmt, const A &x, const As &... xs) { led_message(fmt::format(fmt, x, xs...)); } template <class A, class... As> void led_priority_fmt(f64 timeout, const char *fmt, const A &x, const As &... xs) { led_priority_message(timeout, fmt::format(fmt, x, xs...)); } // template <class A, class... As> void status_fmt(const char *fmt, const A &x, const As &... xs) { status_message(fmt::format(fmt, x, xs...)); } // enum { debugging_input = true, debugging_logic = true, }; inline void debug_input(std::string str) { if (debugging_input) status_message(std::move(str)); } inline void debug_logic(std::string str) { if (debugging_logic) status_message(std::move(str)); } template <class A, class... As> void debug_input_fmt(const char *fmt, const A &x, const As &... xs) { if (debugging_input) status_fmt(fmt, x, xs...); } template <class A, class... As> void debug_logic_fmt(const char *fmt, const A &x, const As &... xs) { if (debugging_logic) status_fmt(fmt, x, xs...); } }; } // namespace cws80
{ "alphanum_fraction": 0.6346023114, "avg_line_length": 31.6344086022, "ext": "h", "hexsha": "bd0832e593f0b18fb9fd55dc6d39db6e4570b656", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "jpcima/cws80", "max_forks_repo_path": "sources/ui/cws80_ui_controller.h", "max_issues_count": 5, "max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z", "max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "jpcima/cws80", "max_issues_repo_path": "sources/ui/cws80_ui_controller.h", "max_line_length": 85, "max_stars_count": 4, "max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "jpcima/cws80", "max_stars_repo_path": "sources/ui/cws80_ui_controller.h", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z", "num_tokens": 780, "size": 2942 }
/* gsl_sf_hermite.h * * Copyright (C) 2011-2014 Konrad Griessinger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /*----------------------------------------------------------------------* * (konradg(at)gmx.net) * *----------------------------------------------------------------------*/ #ifndef __GSL_SF_HERMITE_H__ #define __GSL_SF_HERMITE_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <gsl/gsl_sf_result.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS GSL_FUN int gsl_sf_hermite_prob_e(const int n, const double x, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_prob(const int n, const double x); GSL_FUN int gsl_sf_hermite_prob_deriv_e(const int m, const int n, const double x, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_prob_deriv(const int m, const int n, const double x); GSL_FUN int gsl_sf_hermite_e(const int n, const double x, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite(const int n, const double x); GSL_FUN int gsl_sf_hermite_deriv_e(const int m, const int n, const double x, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_deriv(const int m, const int n, const double x); GSL_FUN int gsl_sf_hermite_func_e(const int n, const double x, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_func(const int n, const double x); GSL_FUN int gsl_sf_hermite_func_fast_e(const int n, const double x, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_func_fast(const int n, const double x); GSL_FUN int gsl_sf_hermite_prob_array(const int nmax, const double x, double * result_array); GSL_FUN int gsl_sf_hermite_prob_array_deriv(const int m, const int nmax, const double x, double * result_array); GSL_FUN int gsl_sf_hermite_prob_deriv_array(const int mmax, const int n, const double x, double * result_array); GSL_FUN int gsl_sf_hermite_prob_series_e(const int n, const double x, const double * a, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_prob_series(const int n, const double x, const double * a); GSL_FUN int gsl_sf_hermite_array(const int nmax, const double x, double * result_array); GSL_FUN int gsl_sf_hermite_array_deriv(const int m, const int nmax, const double x, double * result_array); GSL_FUN int gsl_sf_hermite_deriv_array(const int mmax, const int n, const double x, double * result_array); GSL_FUN int gsl_sf_hermite_series_e(const int n, const double x, const double * a, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_series(const int n, const double x, const double * a); GSL_FUN int gsl_sf_hermite_func_array(const int nmax, const double x, double * result_array); GSL_FUN int gsl_sf_hermite_func_series_e(const int n, const double x, const double * a, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_func_series(const int n, const double x, const double * a); GSL_FUN int gsl_sf_hermite_func_der_e(const int m, const int n, const double x, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_func_der(const int m, const int n, const double x); GSL_FUN int gsl_sf_hermite_prob_zero_e(const int n, const int s, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_prob_zero(const int n, const int s); GSL_FUN int gsl_sf_hermite_zero_e(const int n, const int s, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_zero(const int n, const int s); GSL_FUN int gsl_sf_hermite_func_zero_e(const int n, const int s, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_func_zero(const int n, const int s); #ifndef GSL_DISABLE_DEPRECATED GSL_FUN int gsl_sf_hermite_phys_e(const int n, const double x, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_phys(const int n, const double x); GSL_FUN int gsl_sf_hermite_phys_der_e(const int m, const int n, const double x, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_phys_der(const int m, const int n, const double x); GSL_FUN int gsl_sf_hermite_phys_array(const int nmax, const double x, double * result_array); GSL_FUN int gsl_sf_hermite_phys_series_e(const int n, const double x, const double * a, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_phys_series(const int n, const double x, const double * a); GSL_FUN int gsl_sf_hermite_phys_array_der(const int m, const int nmax, const double x, double * result_array); GSL_FUN int gsl_sf_hermite_phys_der_array(const int mmax, const int n, const double x, double * result_array); GSL_FUN int gsl_sf_hermite_phys_zero_e(const int n, const int s, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_phys_zero(const int n, const int s); GSL_FUN int gsl_sf_hermite_prob_array_der(const int m, const int nmax, const double x, double * result_array); GSL_FUN int gsl_sf_hermite_prob_der_array(const int mmax, const int n, const double x, double * result_array); GSL_FUN int gsl_sf_hermite_prob_der_e(const int m, const int n, const double x, gsl_sf_result * result); GSL_FUN double gsl_sf_hermite_prob_der(const int m, const int n, const double x); #endif /* !GSL_DISABLE_DEPRECATED */ __END_DECLS #endif /* __GSL_SF_HERMITE_H__ */
{ "alphanum_fraction": 0.7510137875, "avg_line_length": 56.5596330275, "ext": "h", "hexsha": "61c652fe1c87fe24fa82733c2c70a4de2e33c4ea", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_sf_hermite.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_sf_hermite.h", "max_line_length": 113, "max_stars_count": 2, "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_path": "vendor/gsl/gsl/gsl_sf_hermite.h", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "num_tokens": 1603, "size": 6165 }
/* * Copyright (c) 1997-1999 Massachusetts Institute of Technology * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* fftw.h -- system-wide definitions */ /* $Id: fftw-int.h,v 1.39 1999/02/19 17:22:00 athena Exp $ */ #ifndef FFTW_INT_H #define FFTW_INT_H #include <config.h> #include <fftw.h> #ifdef __cplusplus extern "C" { #else #endif /* __cplusplus */ /****************************************************************************/ /* Private Functions */ /****************************************************************************/ extern fftw_twiddle *fftw_create_twiddle(int n, const fftw_codelet_desc *d); extern void fftw_destroy_twiddle(fftw_twiddle *tw); extern void fftw_strided_copy(int, fftw_complex *, int, fftw_complex *); extern void fftw_executor_simple(int, const fftw_complex *, fftw_complex *, fftw_plan_node *, int, int); extern fftwnd_plan fftwnd_create_plan_aux(int rank, const int *n, fftw_direction dir, int flags); extern fftw_plan *fftwnd_new_plan_array(int rank); extern fftw_plan *fftwnd_create_plans_generic(fftw_plan *plans, int rank, const int *n, fftw_direction dir, int flags); extern fftw_plan *fftwnd_create_plans_specific(fftw_plan *plans, int rank, const int *n, const int *n_after, fftw_direction dir, int flags, fftw_complex *in, int istride, fftw_complex *out, int ostride); extern int fftwnd_work_size(int rank, const int *n, int flags, int ncopies); extern void fftwnd_aux(fftwnd_plan p, int cur_dim, fftw_complex *in, int istride, fftw_complex *out, int ostride, fftw_complex *work); extern void fftwnd_aux_howmany(fftwnd_plan p, int cur_dim, int howmany, fftw_complex *in, int istride, int idist, fftw_complex *out, int ostride, int odist, fftw_complex *work); /* wisdom prototypes */ enum fftw_wisdom_category { FFTW_WISDOM, RFFTW_WISDOM }; extern int fftw_wisdom_lookup(int n, int flags, fftw_direction dir, enum fftw_wisdom_category category, int istride, int ostride, enum fftw_node_type *type, int *signature, int replace_p); extern void fftw_wisdom_add(int n, int flags, fftw_direction dir, enum fftw_wisdom_category cat, int istride, int ostride, enum fftw_node_type type, int signature); /* Private planner functions: */ extern double fftw_estimate_node(fftw_plan_node *p); extern fftw_plan_node *fftw_make_node_notw(int size, const fftw_codelet_desc *config); extern fftw_plan_node *fftw_make_node_real2hc(int size, const fftw_codelet_desc *config); extern fftw_plan_node *fftw_make_node_hc2real(int size, const fftw_codelet_desc *config); extern fftw_plan_node *fftw_make_node_twiddle(int n, const fftw_codelet_desc *config, fftw_plan_node *recurse, int flags); extern fftw_plan_node *fftw_make_node_hc2hc(int n, fftw_direction dir, const fftw_codelet_desc *config, fftw_plan_node *recurse, int flags); extern fftw_plan_node *fftw_make_node_generic(int n, int size, fftw_generic_codelet *codelet, fftw_plan_node *recurse, int flags); extern fftw_plan_node *fftw_make_node_rgeneric(int n, int size, fftw_direction dir, fftw_rgeneric_codelet * codelet, fftw_plan_node *recurse, int flags); extern int fftw_factor(int n); extern fftw_plan_node *fftw_make_node(void); extern fftw_plan fftw_make_plan(int n, fftw_direction dir, fftw_plan_node *root, int flags, enum fftw_node_type wisdom_type, int wisdom_signature); extern void fftw_use_plan(fftw_plan p); extern void fftw_use_node(fftw_plan_node *p); extern void fftw_destroy_plan_internal(fftw_plan p); extern fftw_plan fftw_pick_better(fftw_plan p1, fftw_plan p2); extern fftw_plan fftw_lookup(fftw_plan *table, int n, int flags); extern void fftw_insert(fftw_plan *table, fftw_plan this_plan, int n); extern void fftw_make_empty_table(fftw_plan *table); extern void fftw_destroy_table(fftw_plan *table); extern void fftw_complete_twiddle(fftw_plan_node *p, int n); extern fftw_plan_node *fftw_make_node_rader(int n, int size, fftw_direction dir, fftw_plan_node *recurse, int flags); extern fftw_rader_data *fftw_rader_top; /****************************************************************************/ /* Floating Point Types */ /****************************************************************************/ /* * We use these definitions to make it easier for people to change * FFTW to use long double and similar types. You shouldn't have to * change this just to use float or double. */ /* * Change this if your floating-point constants need to be expressed * in a special way. For example, if fftw_real is long double, you * will need to append L to your fp constants to make them of the * same precision. Do this by changing "x" below to "x##L". */ #define FFTW_KONST(x) ((fftw_real) x) #define FFTW_TRIG_SIN sin #define FFTW_TRIG_COS cos typedef double FFTW_TRIG_REAL; /* the argument type for sin and cos */ #define FFTW_K2PI FFTW_KONST(6.2831853071795864769252867665590057683943388) /****************************************************************************/ /* gcc/x86 hacks */ /****************************************************************************/ /* * gcc 2.[78].x and x86 specific hacks. These macros align the stack * pointer so that the double precision temporary variables in the * codelets will be aligned to a multiple of 8 bytes (*way* faster on * pentium and pentiumpro) */ #ifdef __GNUC__ #ifdef __i386__ #ifdef FFTW_ENABLE_I386_HACKS #ifndef FFTW_ENABLE_FLOAT #define FFTW_USING_I386_HACKS #define HACK_ALIGN_STACK_EVEN() { \ if ((((long) (__builtin_alloca(0))) & 0x7)) __builtin_alloca(4); \ } #define HACK_ALIGN_STACK_ODD() { \ if (!(((long) (__builtin_alloca(0))) & 0x7)) __builtin_alloca(4); \ } #ifdef FFTW_DEBUG_ALIGNMENT #define ASSERT_ALIGNED_DOUBLE() { \ double __foo; \ if ((((long) &__foo) & 0x7)) abort(); \ } #endif #endif #endif #endif #endif #ifndef HACK_ALIGN_STACK_EVEN #define HACK_ALIGN_STACK_EVEN() #endif #ifndef HACK_ALIGN_STACK_ODD #define HACK_ALIGN_STACK_ODD() #endif #ifndef ASSERT_ALIGNED_DOUBLE #define ASSERT_ALIGNED_DOUBLE() #endif /****************************************************************************/ /* Timers */ /****************************************************************************/ /* * Here, you can use all the nice timers available in your machine. */ /* * Things you should define to include your own clock: fftw_time -- the data type used to store a time extern fftw_time fftw_get_time(void); -- a function returning the current time. (We have implemented this as a macro in most cases.) extern fftw_time fftw_time_diff(fftw_time t1, fftw_time t2); -- returns the time difference (t1 - t2). If t1 < t2, it may simply return zero (although this is not required). (We have implemented this as a macro in most cases.) extern double fftw_time_to_sec(fftw_time t); -- returns the time t expressed in seconds, as a double. (Implemented as a macro in most cases.) FFTW_TIME_MIN -- a double-precision macro holding the minimum time interval (in seconds) for accurate time measurements. This should probably be at least 100 times the precision of your clock (we use even longer intervals, to be conservative). This will determine how long the planner takes to measure the speeds of different possible plans. Bracket all of your definitions with an appropriate #ifdef so that they will be enabled on your machine. If you do add your own high-precision timer code, let us know (at fftw@theory.lcs.mit.edu). Only declarations should go in this file. Any function definitions that you need should go into timer.c. */ /* * define a symbol so that we know that we have the fftw_time_diff * function/macro (it did not exist prior to FFTW 1.2) */ #define FFTW_HAS_TIME_DIFF /********************************************** * SOLARIS **********************************************/ #if defined(HAVE_GETHRTIME) /* we use the nanosecond virtual timer */ #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif typedef hrtime_t fftw_time; #define fftw_get_time() gethrtime() #define fftw_time_diff(t1,t2) ((t1) - (t2)) #define fftw_time_to_sec(t) ((double) t / 1.0e9) /* * a measurement is valid if it runs for at least * FFTW_TIME_MIN seconds. */ #define FFTW_TIME_MIN (1.0e-4) /* for Solaris nanosecond timer */ #define FFTW_TIME_REPEAT 8 /********************************************** * Pentium time stamp counter **********************************************/ #elif defined(__GNUC__) && defined(__i386__) && defined(FFTW_ENABLE_PENTIUM_TIMER) /* * Use internal Pentium register (time stamp counter). Resolution * is 1/FFTW_CYCLES_PER_SEC seconds (e.g. 5 ns for Pentium 200 MHz). * (This code was contributed by Wolfgang Reimer) */ #ifndef FFTW_CYCLES_PER_SEC #error "Must define FFTW_CYCLES_PER_SEC in fftw/config.h to use the Pentium cycle counter" #endif typedef unsigned long long fftw_time; static __inline__ fftw_time read_tsc() { struct { long unsigned lo, hi; } counter; long unsigned sav_eax, sav_edx; __asm__("movl %%eax,%0":"=m"(sav_eax)); __asm__("movl %%edx,%0":"=m"(sav_edx)); __asm__("rdtsc"); __asm__("movl %%eax,%0":"=m"(counter.lo)); __asm__("movl %%edx,%0":"=m"(counter.hi)); __asm__("movl %0,%%eax": : "m"(sav_eax):"eax"); __asm__("movl %0,%%edx": : "m"(sav_edx):"edx"); return *(fftw_time *) & counter; } #define fftw_get_time() read_tsc() #define fftw_time_diff(t1,t2) ((t1) - (t2)) #define fftw_time_to_sec(t) (((double) (t)) / FFTW_CYCLES_PER_SEC) #define FFTW_TIME_MIN (1.0e-4) /* for Pentium TSC register */ /************* generic systems having gettimeofday ************/ #elif defined(HAVE_GETTIMEOFDAY) || defined(HAVE_BSDGETTIMEOFDAY) #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #define FFTW_USE_GETTIMEOFDAY typedef struct timeval fftw_time; extern fftw_time fftw_gettimeofday_get_time(void); extern fftw_time fftw_gettimeofday_time_diff(fftw_time t1, fftw_time t2); #define fftw_get_time() fftw_gettimeofday_get_time() #define fftw_time_diff(t1, t2) fftw_gettimeofday_time_diff(t1, t2) #define fftw_time_to_sec(t) ((double)(t).tv_sec + (double)(t).tv_usec * 1.0E-6) #ifndef FFTW_TIME_MIN /* this should be fine on any system claiming a microsecond timer */ #define FFTW_TIME_MIN (1.0e-2) #endif /********************************************** * MACINTOSH **********************************************/ #elif defined(HAVE_MAC_TIMER) /* * By default, use the microsecond-timer in the Mac Time Manager. * Alternatively, by changing the following #if 1 to #if 0, you * can use the nanosecond timer available *only* on PCI PowerMacs. */ #ifndef HAVE_MAC_PCI_TIMER /* use time manager */ /* * Use Macintosh Time Manager routines (maximum resolution is about 20 * microseconds). */ typedef struct fftw_time_struct { unsigned long hi, lo; } fftw_time; extern fftw_time get_Mac_microseconds(void); #define fftw_get_time() get_Mac_microseconds() /* define as a function instead of a macro: */ extern fftw_time fftw_time_diff(fftw_time t1, fftw_time t2); #define fftw_time_to_sec(t) ((t).lo * 1.0e-6 + 4294967295.0e-6 * (t).hi) /* very conservative, since timer should be accurate to 20e-6: */ /* (although this seems not to be the case in practice) */ #define FFTW_TIME_MIN (5.0e-2) /* for MacOS Time Manager timer */ #else /* use nanosecond timer */ /* Use the nanosecond timer available on PCI PowerMacs. */ #include <DriverServices.h> typedef AbsoluteTime fftw_time; #define fftw_get_time() UpTime() #define fftw_time_diff(t1,t2) SubAbsoluteFromAbsolute(t1,t2) #define fftw_time_to_sec(t) (AbsoluteToNanoseconds(t).lo * 1.0e-9) /* Extremely conservative minimum time: */ /* for MacOS PCI PowerMac nanosecond timer */ #define FFTW_TIME_MIN (5.0e-3) #endif /* use nanosecond timer */ /********************************************** * WINDOWS **********************************************/ #elif defined(HAVE_WIN32_TIMER) #include <time.h> typedef unsigned long fftw_time; extern unsigned long GetPerfTime(void); extern double GetPerfSec(double ticks); #define fftw_get_time() GetPerfTime() #define fftw_time_diff(t1,t2) ((t1) - (t2)) #define fftw_time_to_sec(t) GetPerfSec(t) #define FFTW_TIME_MIN (5.0e-2) /* for Win32 timer */ /********************************************** * CRAY **********************************************/ #elif defined(_CRAYMPP) /* Cray MPP system */ double SECONDR(void); /* * I think you have to link with -lsci to * get this */ typedef double fftw_time; #define fftw_get_time() SECONDR() #define fftw_time_diff(t1,t2) ((t1) - (t2)) #define fftw_time_to_sec(t) (t) #define FFTW_TIME_MIN (1.0e-1) /* for Cray MPP SECONDR timer */ /********************************************** * VANILLA UNIX/ISO C SYSTEMS **********************************************/ /* last resort: use good old Unix clock() */ #else #include <time.h> typedef clock_t fftw_time; #ifndef CLOCKS_PER_SEC #ifdef sun /* stupid sunos4 prototypes */ #define CLOCKS_PER_SEC 1000000 extern long clock(void); #else /* not sun, we don't know CLOCKS_PER_SEC */ #error Please define CLOCKS_PER_SEC #endif #endif #define fftw_get_time() clock() #define fftw_time_diff(t1,t2) ((t1) - (t2)) #define fftw_time_to_sec(t) (((double) (t)) / CLOCKS_PER_SEC) /* * ***VERY*** conservative constant: this says that a * measurement must run for 200ms in order to be valid. * You had better check the manual of your machine * to discover if it can do better than this */ #define FFTW_TIME_MIN (2.0e-1) /* for default clock() timer */ #endif /* UNIX clock() */ /* take FFTW_TIME_REPEAT measurements... */ #ifndef FFTW_TIME_REPEAT #define FFTW_TIME_REPEAT 4 #endif /* but do not run for more than TIME_LIMIT seconds while measuring one FFT */ #ifndef FFTW_TIME_LIMIT #define FFTW_TIME_LIMIT 2.0 #endif #ifdef __cplusplus } /* extern "C" */ #endif /* __cplusplus */ #endif /* FFTW_INT_H */
{ "alphanum_fraction": 0.6478663472, "avg_line_length": 32.9978632479, "ext": "h", "hexsha": "637f537b06040647f03460adb5ee966bc9aca320", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-07-09T00:20:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-09T00:20:49.000Z", "max_forks_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jlprieur/jlplib", "max_forks_repo_path": "jlp_numeric/old/fftw2_src/fftw-int.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jlprieur/jlplib", "max_issues_repo_path": "jlp_numeric/old/fftw2_src/fftw-int.h", "max_line_length": 90, "max_stars_count": null, "max_stars_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jlprieur/jlplib", "max_stars_repo_path": "jlp_numeric/old/fftw2_src/fftw-int.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3840, "size": 15443 }
/*************************************************************************** File : muParserScripting.h Project : QtiPlot -------------------------------------------------------------------- Copyright : (C) 2006 by Ion Vasilief, Knut Franke Email (use @ for *) : ion_vasilief*yahoo.fr, knut.franke*gmx.de Description : Evaluate mathematical expressions using muParser ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301 USA * * * ***************************************************************************/ #ifndef MUPARSER_SCRIPTING_H #define MUPARSER_SCRIPTING_H #include "ScriptingEnv.h" #include "Script.h" #include "muParserScript.h" #include <muParser.h> #include "math.h" #include <gsl/gsl_sf.h> #include <gsl/gsl_cdf.h> #include <q3asciidict.h> //! TODO class muParserScripting: public ScriptingEnv { Q_OBJECT public: static const char *langName; muParserScripting(ApplicationWindow *parent) : ScriptingEnv(parent, langName) { d_initialized=true; } static ScriptingEnv *constructor(ApplicationWindow *parent) { return new muParserScripting(parent); } bool isRunning() const { return true; } Script *newScript(const QString &code, QObject *context, const QString &name="<input>") { return new muParserScript(this, code, context, name); } // we do not support global variables bool setQObject(QObject*, const char*) { return false; } bool setInt(int, const char*) { return false; } bool setDouble(double, const char*) { return false; } const QStringList mathFunctions() const; const QString mathFunctionDoc (const QString &name) const; struct mathFunction { char *name; int numargs; double (*fun1)(double); double (*fun2)(double,double); double (*fun3)(double,double,double); char *description; }; static const mathFunction math_functions[]; private: static double mod(double x, double y) { return fmod(x,y); } static double bessel_J0(double x) { return gsl_sf_bessel_J0 (x); } static double bessel_J1(double x) { return gsl_sf_bessel_J1 (x); } static double bessel_Jn(double x, double n) { return gsl_sf_bessel_Jn ((int)n, x); } static double bessel_Yn(double x, double n) { return gsl_sf_bessel_Yn ((int)n, x); } static double bessel_Jn_zero(double n, double s) { return gsl_sf_bessel_zero_Jnu(n, (unsigned int) s); } static double bessel_Y0(double x) { return gsl_sf_bessel_Y0 (x); } static double bessel_Y1(double x) { return gsl_sf_bessel_Y1 (x); } static double beta(double a, double b) { return gsl_sf_beta (a,b); } static double erf(double x) { return gsl_sf_erf (x); } static double erfc(double x) { return gsl_sf_erfc (x); } static double erf_Z(double x) { return gsl_sf_erf_Z (x); } static double erf_Q(double x) { return gsl_sf_erf_Q (x); } static double gamma(double x) { return gsl_sf_gamma (x); } static double lngamma(double x) { return gsl_sf_lngamma (x); } static double hazard(double x) { return gsl_sf_hazard (x); } static double lambert_W0(double x) { return gsl_sf_lambert_W0(x); } static double lambert_Wm1(double x) { return gsl_sf_lambert_Wm1(x); } static double ttable(double x, double n) { return gsl_cdf_tdist_Pinv(x, n); } }; class EmptySourceError : public mu::ParserError { public: EmptySourceError() {} }; #endif
{ "alphanum_fraction": 0.5573163202, "avg_line_length": 38.5634920635, "ext": "h", "hexsha": "065bca3355c74b7148fe396729913f8247332b19", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": [ "IJG" ], "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_path": "thirdparty/qtiplot/qtiplot/src/muParserScripting.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_licenses": [ "IJG" ], "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_path": "thirdparty/qtiplot/qtiplot/src/muParserScripting.h", "max_line_length": 105, "max_stars_count": 6, "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": [ "IJG" ], "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_path": "thirdparty/qtiplot/qtiplot/src/muParserScripting.h", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "num_tokens": 1072, "size": 4859 }
// // parameter.h // EpiGenMCMC // // Created by Lucy Li on 08/04/2016. // Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved. // #ifndef EpiGenMCMC_parameter_h #define EpiGenMCMC_parameter_h #include <fstream> #include <sstream> #include <vector> #include <string> #include <algorithm> #include <cmath> #include <limits> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> class Parameter { std::vector <double> parameter_values; std::vector <std::string> parameter_names; std::vector <bool> estimate; std::vector <std::string> transform; std::vector <std::string> prior; std::vector <double> prior_par_1; std::vector <double> prior_par_2; std::vector <double> prior_par_3; std::vector <std::string> proposal; std::vector <double> proposal_sd; std::vector <double> proposal_lower; std::vector <double> proposal_upper; std::vector <double> accepted; std::vector <double> rejected; std::vector <double> acceptance_rate; std::vector <int> params_to_estim; int total_params; int curr_param_to_estimate; double old_param_value; double optimal_acceptance; double lower_acceptance; double upper_acceptance; int adapt_every; int max_adapt_times; bool stop_adapting; double get_prior(double, int) const; double get_transform(double, std::string, bool) const; public: Parameter(); Parameter(const Parameter &); Parameter (std::string); bool is_estim(int) const; int get_curr_estim() const; void set_next_param(); int get_total_params() const; int get_total_params_to_estim() const; int get_estim_index(int) const; double get(std::string) const; double get(int) const; double get_lower(int) const; double get_upper(int) const; void set(int, double); std::vector<double> get_values_vector() const; std::vector <std::string> get_names_vector() const; std::string getname(int) const; void reset(); void accept(); void reject(); double get_acceptance() const; void stop_adapt(); void start_adapt(); void adapt(); double propose(gsl_rng *); double get_prior_ratio() const; double get_prior_all() const; bool param_exists(std::string) const; void transform_param(int, bool); double get_lognormal_sd (double, double) const; double get_lognormal_mean (double, double) const; }; struct MCMCoptions { int particles; int iterations; int log_every; int pfilter_every; double pfilter_threshold; int which_likelihood; int num_trees; std::string log_filename; std::string traj_filename; std::string model; int total_dt; double sim_dt; int num_groups; int seed; bool verbose; bool save_traj; bool use_lhs; int lhs_divides; int lhs_iterations; int num_threads; double heat_factor; int heat_length; double cool_rate; gsl_rng ** rng; MCMCoptions(); MCMCoptions(const MCMCoptions&); MCMCoptions(std::string); }; #endif
{ "alphanum_fraction": 0.6851008458, "avg_line_length": 24.9918699187, "ext": "h", "hexsha": "73f15bb8d2d2656217107e53435bd62629ad7a8e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-16T22:17:38.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-13T16:20:40.000Z", "max_forks_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lucymli/EpiGenMCMC", "max_forks_repo_path": "src/parameter.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_issues_repo_issues_event_max_datetime": "2021-01-15T04:48:15.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-05T05:49:07.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lucymli/EpiGenMCMC", "max_issues_repo_path": "src/parameter.h", "max_line_length": 77, "max_stars_count": 3, "max_stars_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lucymli/EpiGenMCMC", "max_stars_repo_path": "src/parameter.h", "max_stars_repo_stars_event_max_datetime": "2020-04-09T16:14:41.000Z", "max_stars_repo_stars_event_min_datetime": "2018-04-01T09:55:40.000Z", "num_tokens": 784, "size": 3074 }
/* * The MIT License is a permissive free software license, which permits reuse * within both open source and proprietary software. The software is licensed * as is, and no warranty is given as to fitness for purpose or absence of * infringement of third parties' rights, such as patents. Generally use for * research activities is allowed regardless of any third party patents, but * commercial use may be subject to a separate license. * * * The MIT License (MIT) * * Copyright (c) 2015 Tuomo Raitio * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * * * * <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> * GlottHMM Speech Synthesis * <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> * * This program reads speech parameters and a glottal pulse/ * pulse library, and synthesizes speech from them. * * This program has been written in Aalto University, * Department of Signal Processign and Acoustics, Espoo, Finland * * Main author: Tuomo Raitio * Acknowledgements: Antti Suni, Paavo Alku, Martti Vainio * * File SynthesisFunctions.c * Version: 1.1 * */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <string.h> #include <sndfile.h> /* Read and write wav */ #include <gsl/gsl_vector.h> /* GSL, Vector */ #include <gsl/gsl_matrix.h> /* GSL, Matrix */ #include <gsl/gsl_fft_real.h> /* GSL, FFT */ #include <gsl/gsl_fft_complex.h> /* GSL, FFT complex */ #include <gsl/gsl_fft_halfcomplex.h>/* GSL, FFT halfcomplex */ #include <gsl/gsl_permutation.h> /* GSL, Permutations */ #include <gsl/gsl_linalg.h> /* GSL, Linear algebra */ #include <gsl/gsl_spline.h> /* GSL, Interpolation */ #include <gsl/gsl_errno.h> /* GSL, Error handling */ #include <gsl/gsl_poly.h> /* GSL, Polynomials */ #include <gsl/gsl_sort_double.h> /* GSL, Sort double */ #include <gsl/gsl_sort_vector.h> /* GSL, Sort vector */ #include <gsl/gsl_complex.h> /* GSL, Complex numbers */ #include <gsl/gsl_complex_math.h> /* GSL, Arithmetic operations for complex numbers */ #include <gsl/gsl_rng.h> /* GSL, Random number generation */ #include <gsl/gsl_randist.h> /* GSL, Random number generation */ #include <libconfig.h> #include "SynthesisFunctions.h" /** * Function Check_command_line * * Checks command line formant and prints instructions * * @param argc number of input arguments */ int Check_command_line(int argc) { if (argc < 3 || argc > 4) { /* Incorrect command line, print instructions */ printf("\n<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n"); printf(" GlottHMM - Speech Synthesizer (%s)\n",VERSION); printf("<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n\n"); printf("Description:\n\n"); printf(" Synthesis of speech signal according to speech parameters.\n\n"); printf("Usage:\n\n"); printf(" Synthesis file_name config_default config_user\n\n"); printf(" file_name - File name without extensions (.wav, .lab)\n"); printf(" config_default - Default config file name\n"); printf(" config_user - User config file name (OPTIONAL)\n\n"); printf(" Synthesized speech signal is saved to \"file_name.syn.wav\".\n\n"); printf("Version:\n\n"); printf(" %s (%s)\n\n",VERSION,DATE); return EXIT_FAILURE; } else { /* Correct command line, print program title */ printf("\n<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n"); printf(" Speech Synthesizer (%s)\n",VERSION); printf("<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n\n"); return EXIT_SUCCESS; } } /** * Function Read_config * * Read configuration file * * @param filename name of the configuration file * @return conf pointer to configuration structure */ struct config_t *Read_config(char *filename) { struct config_t *conf = (struct config_t *)malloc(sizeof(struct config_t)); config_init(conf); if(config_read_file(conf,filename) != CONFIG_TRUE) { printf("\nError reading configuration file \"%s\", line %i\n",filename,config_error_line(conf)); printf("%s\n",config_error_text(conf)); config_destroy(conf); free(conf); return NULL; } return conf; } /** * Function Assign_config_parameters * * Assign configuration parameters to variables. Destroy and free config file. * * @param conf config file * @param params parameter structure */ int Assign_config_parameters(const char *filename, struct config_t *conf, PARAM *params, int conf_type) { int i,bool,multisyn_old = 0,synlistlen_old = 0; long int ival; double fval; const char *tmp; const config_setting_t *paramweights_conf; const config_setting_t *dnn_dim_conf; /* For synthesis list */ if(conf_type == DEF_CONF) { multisyn_old = 0; synlistlen_old = 0; } else if(conf_type == USR_CONF) { multisyn_old = params->multisyn; synlistlen_old = params->synlistlen; } /* Assign configuration file parameters */ if(config_lookup(conf,SAMPLING_FREQUENCY) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", SAMPLING_FREQUENCY); return EXIT_FAILURE; } else if(config_lookup(conf,SAMPLING_FREQUENCY) != NULL) { config_lookup_int(conf, SAMPLING_FREQUENCY,&ival); params->FS = (int)ival; } if(config_lookup(conf,FRAME_LENGTH) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", FRAME_LENGTH); return EXIT_FAILURE; } else if(config_lookup(conf,FRAME_LENGTH) != NULL) { config_lookup_float(conf, FRAME_LENGTH,&fval); params->frame_length_ms = fval; } if(config_lookup(conf,FRAME_SHIFT) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", FRAME_SHIFT); return EXIT_FAILURE; } else if(config_lookup(conf,FRAME_SHIFT) != NULL) { config_lookup_float(conf, FRAME_SHIFT,&fval); params->shift_ms = fval; } if(config_lookup(conf,F0_FRAME_LENGTH) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", F0_FRAME_LENGTH); return EXIT_FAILURE; } else if(config_lookup(conf,F0_FRAME_LENGTH) != NULL) { config_lookup_float(conf, F0_FRAME_LENGTH,&fval); params->f0_frame_length_ms = fval; } if(config_lookup(conf,LPC_ORDER) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",LPC_ORDER); return EXIT_FAILURE; } else if(config_lookup(conf,LPC_ORDER) != NULL) { config_lookup_int(conf,LPC_ORDER,&ival); params->lpc_order_vt = (int)ival; } if(config_lookup(conf,LPC_ORDER_SOURCE) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",LPC_ORDER_SOURCE); return EXIT_FAILURE; } else if(config_lookup(conf,LPC_ORDER_SOURCE) != NULL) { config_lookup_int(conf,LPC_ORDER_SOURCE,&ival); params->lpc_order_gl = (int)ival; } if(config_lookup(conf,WARPING_VT) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",WARPING_VT); return EXIT_FAILURE; } else if(config_lookup(conf,WARPING_VT) != NULL) { config_lookup_float(conf,WARPING_VT,&fval); params->lambda_vt = fval; } if(config_lookup(conf,WARPING_GL) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",WARPING_GL); return EXIT_FAILURE; } else if(config_lookup(conf,WARPING_GL) != NULL) { config_lookup_float(conf,WARPING_GL,&fval); params->lambda_gl = fval; } if(config_lookup(conf,DIFFERENTIAL_LSF) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", DIFFERENTIAL_LSF); return EXIT_FAILURE; } else if(config_lookup(conf,DIFFERENTIAL_LSF) != NULL) { config_lookup_bool(conf, DIFFERENTIAL_LSF,&bool); params->differential_lsf = bool; } if(config_lookup(conf,USE_PULSE_LIBRARY) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",USE_PULSE_LIBRARY); return EXIT_FAILURE; } else if(config_lookup(conf,USE_PULSE_LIBRARY) != NULL) { config_lookup_bool(conf,USE_PULSE_LIBRARY,&bool); params->use_pulselib = bool; } if(config_lookup(conf,NUMBER_OF_PULSE_CANDIDATES) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",NUMBER_OF_PULSE_CANDIDATES); return EXIT_FAILURE; } else if(config_lookup(conf,NUMBER_OF_PULSE_CANDIDATES) != NULL) { config_lookup_int(conf,NUMBER_OF_PULSE_CANDIDATES,&ival); params->n_pulsecandidates = (int)ival; } if(config_lookup(conf,CONCATENATION_COST) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",CONCATENATION_COST); return EXIT_FAILURE; } else if(config_lookup(conf,CONCATENATION_COST) != NULL) { config_lookup_float(conf,CONCATENATION_COST,&fval); params->concatenation_cost = fval; } if(config_lookup(conf,PULSE_ERROR_BIAS) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",PULSE_ERROR_BIAS); return EXIT_FAILURE; } else if(config_lookup(conf,PULSE_ERROR_BIAS) != NULL) { config_lookup_float(conf,PULSE_ERROR_BIAS,&fval); params->pulse_error_bias = fval; } if(config_lookup(conf,TARGET_COST) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",TARGET_COST); return EXIT_FAILURE; } else if(config_lookup(conf,TARGET_COST) != NULL) { config_lookup_float(conf,TARGET_COST,&fval); params->target_cost = fval; } if(config_lookup(conf,USE_PULSE_CLUSTERING) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",USE_PULSE_CLUSTERING); return EXIT_FAILURE; } else if(config_lookup(conf,USE_PULSE_CLUSTERING) != NULL) { config_lookup_bool(conf,USE_PULSE_CLUSTERING,&bool); params->pulse_clustering = bool; } if(config_lookup(conf,USE_PULSE_INTERPOLATION) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",USE_PULSE_INTERPOLATION); return EXIT_FAILURE; } else if(config_lookup(conf,USE_PULSE_INTERPOLATION) != NULL) { config_lookup_bool(conf,USE_PULSE_INTERPOLATION,&bool); params->pulse_interpolation = bool; } if(config_lookup(conf,MAX_PULSES_IN_CLUSTER) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",MAX_PULSES_IN_CLUSTER); return EXIT_FAILURE; } else if(config_lookup(conf,MAX_PULSES_IN_CLUSTER) != NULL) { config_lookup_int(conf,MAX_PULSES_IN_CLUSTER,&ival); params->max_pulses_in_cluster = (int)ival; } if(config_lookup(conf,NOISE_GAIN_VOICED) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",NOISE_GAIN_VOICED); return EXIT_FAILURE; } else if(config_lookup(conf,NOISE_GAIN_VOICED) != NULL) { config_lookup_float(conf,NOISE_GAIN_VOICED,&fval); params->noise_gain_voiced = fval; } if(config_lookup(conf,USE_HMM) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",USE_HMM); return EXIT_FAILURE; } else if(config_lookup(conf,USE_HMM) != NULL) { config_lookup_bool(conf,USE_HMM,&bool); params->use_hmm = bool; } if(config_lookup(conf,POSTFILTER_COEFFICIENT) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",POSTFILTER_COEFFICIENT); return EXIT_FAILURE; } else if(config_lookup(conf,POSTFILTER_COEFFICIENT) != NULL) { config_lookup_float(conf,POSTFILTER_COEFFICIENT,&fval); params->postfilter_alpha = fval; } if(config_lookup(conf,PITCH) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",PITCH); return EXIT_FAILURE; } else if(config_lookup(conf,PITCH) != NULL) { config_lookup_float(conf,PITCH,&fval); params->pitch = fval; } if(config_lookup(conf,SPEED) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",SPEED); return EXIT_FAILURE; } else if(config_lookup(conf,SPEED) != NULL) { config_lookup_float(conf,SPEED,&fval); params->speed = fval; } if(config_lookup(conf,GAIN_UNVOICED) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",GAIN_UNVOICED); return EXIT_FAILURE; } else if(config_lookup(conf,GAIN_UNVOICED) != NULL) { config_lookup_float(conf,GAIN_UNVOICED,&fval); params->gain_unvoiced = fval; } if(config_lookup(conf,FILTER_UPDATE_INTERVAL_VT) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",FILTER_UPDATE_INTERVAL_VT); return EXIT_FAILURE; } else if(config_lookup(conf,FILTER_UPDATE_INTERVAL_VT) != NULL) { config_lookup_float(conf,FILTER_UPDATE_INTERVAL_VT,&fval); params->filter_update_interval_vt_ms = fval; } if(config_lookup(conf,FILTER_UPDATE_INTERVAL_GL) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",FILTER_UPDATE_INTERVAL_GL); return EXIT_FAILURE; } else if(config_lookup(conf,FILTER_UPDATE_INTERVAL_GL) != NULL) { config_lookup_float(conf,FILTER_UPDATE_INTERVAL_GL,&fval); params->filter_update_interval_gl_ms = fval; } if(config_lookup(conf,GLFLOWSP_SMOOTH_LEN) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",GLFLOWSP_SMOOTH_LEN); return EXIT_FAILURE; } else if(config_lookup(conf,GLFLOWSP_SMOOTH_LEN) != NULL) { config_lookup_int(conf,GLFLOWSP_SMOOTH_LEN,&ival); params->glflowsp_smooth_len = (int)ival; } if(config_lookup(conf,LSF_SMOOTH_LEN) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",LSF_SMOOTH_LEN); return EXIT_FAILURE; } else if(config_lookup(conf,LSF_SMOOTH_LEN) != NULL) { config_lookup_int(conf,LSF_SMOOTH_LEN,&ival); params->lsf_smooth_len = (int)ival; } if(config_lookup(conf,HARMONICS_SMOOTH_LEN) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",HARMONICS_SMOOTH_LEN); return EXIT_FAILURE; } else if(config_lookup(conf,HARMONICS_SMOOTH_LEN) != NULL) { config_lookup_int(conf,HARMONICS_SMOOTH_LEN,&ival); params->harmonics_smooth_len = (int)ival; } if(config_lookup(conf,GAIN_SMOOTH_LEN) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",GAIN_SMOOTH_LEN); return EXIT_FAILURE; } else if(config_lookup(conf,GAIN_SMOOTH_LEN) != NULL) { config_lookup_int(conf,GAIN_SMOOTH_LEN,&ival); params->gain_smooth_len = (int)ival; } if(config_lookup(conf,NORM_GAIN_SMOOTH_V_LEN) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",NORM_GAIN_SMOOTH_V_LEN); return EXIT_FAILURE; } else if(config_lookup(conf,NORM_GAIN_SMOOTH_V_LEN) != NULL) { config_lookup_int(conf,NORM_GAIN_SMOOTH_V_LEN,&ival); params->norm_gain_smooth_v_len = (int)ival; } if(config_lookup(conf,NORM_GAIN_SMOOTH_UV_LEN) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",NORM_GAIN_SMOOTH_UV_LEN); return EXIT_FAILURE; } else if(config_lookup(conf,NORM_GAIN_SMOOTH_UV_LEN) != NULL) { config_lookup_int(conf,NORM_GAIN_SMOOTH_UV_LEN,&ival); params->norm_gain_smooth_uv_len = (int)ival; } if(config_lookup(conf,GAIN_UNVOICED_FRAME_LENGTH) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",GAIN_UNVOICED_FRAME_LENGTH); return EXIT_FAILURE; } else if(config_lookup(conf,GAIN_UNVOICED_FRAME_LENGTH) != NULL) { config_lookup_float(conf,GAIN_UNVOICED_FRAME_LENGTH,&fval); params->gain_unvoiced_frame_length_ms = fval; } if(config_lookup(conf,GAIN_VOICED_FRAME_LENGTH) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",GAIN_VOICED_FRAME_LENGTH); return EXIT_FAILURE; } else if(config_lookup(conf,GAIN_VOICED_FRAME_LENGTH) != NULL) { config_lookup_float(conf,GAIN_VOICED_FRAME_LENGTH,&fval); params->gain_voiced_frame_length_ms = fval; } if(config_lookup(conf,HNR_SMOOTH_LEN) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",HNR_SMOOTH_LEN); return EXIT_FAILURE; } else if(config_lookup(conf,HNR_SMOOTH_LEN) != NULL) { config_lookup_int(conf,HNR_SMOOTH_LEN,&ival); params->hnr_smooth_len = (int)ival; } if(config_lookup(conf,HNR_CHANNELS) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", HNR_CHANNELS); return EXIT_FAILURE; } else if(config_lookup(conf,HNR_CHANNELS) != NULL) { config_lookup_int(conf, HNR_CHANNELS,&ival); params->hnr_channels = (int)ival; } if(config_lookup(conf,NOISE_LOW_FREQ_LIMIT) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", NOISE_LOW_FREQ_LIMIT); return EXIT_FAILURE; } else if(config_lookup(conf,NOISE_LOW_FREQ_LIMIT) != NULL) { config_lookup_float(conf, NOISE_LOW_FREQ_LIMIT,&fval); params->noise_low_freq_limit = fval; } if(config_lookup(conf,ADD_NOISE_PULSELIB) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", ADD_NOISE_PULSELIB); return EXIT_FAILURE; } else if(config_lookup(conf,ADD_NOISE_PULSELIB) != NULL) { config_lookup_bool(conf, ADD_NOISE_PULSELIB,&bool); params->add_noise_pulselib = bool; } if(config_lookup(conf,USE_HARMONIC_MODIFICATION) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", USE_HARMONIC_MODIFICATION); return EXIT_FAILURE; } else if(config_lookup(conf,USE_HARMONIC_MODIFICATION) != NULL) { config_lookup_bool(conf, USE_HARMONIC_MODIFICATION,&bool); params->use_harmonic_modification = bool; } if(config_lookup(conf,NUMBER_OF_HARMONICS) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", NUMBER_OF_HARMONICS); return EXIT_FAILURE; } else if(config_lookup(conf,NUMBER_OF_HARMONICS) != NULL) { config_lookup_int(conf, NUMBER_OF_HARMONICS,&ival); params->number_of_harmonics = (int)ival; } if(config_lookup(conf,HP_FILTER_F0) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", HP_FILTER_F0); return EXIT_FAILURE; } else if(config_lookup(conf,HP_FILTER_F0) != NULL) { config_lookup_bool(conf, HP_FILTER_F0,&bool); params->hpfiltf0 = bool; } if(config_lookup(conf,WAVEFORM_SAMPLES) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", WAVEFORM_SAMPLES); return EXIT_FAILURE; } else if(config_lookup(conf,WAVEFORM_SAMPLES) != NULL) { config_lookup_int(conf, WAVEFORM_SAMPLES,&ival); params->waveform_samples = (int)ival; } if(config_lookup(conf,NOISE_ROBUST_SPEECH) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", NOISE_ROBUST_SPEECH); return EXIT_FAILURE; } else if(config_lookup(conf,NOISE_ROBUST_SPEECH) != NULL) { config_lookup_bool(conf, NOISE_ROBUST_SPEECH,&bool); params->noise_robust_speech = bool; } if(config_lookup(conf,SEPARATE_VOICED_UNVOICED_SPECTRUM) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", SEPARATE_VOICED_UNVOICED_SPECTRUM); return EXIT_FAILURE; } else if(config_lookup(conf,SEPARATE_VOICED_UNVOICED_SPECTRUM) != NULL) { config_lookup_bool(conf, SEPARATE_VOICED_UNVOICED_SPECTRUM,&bool); params->sep_vuv_spectrum = bool; } if(config_lookup(conf,SYNTHESIZE_MULTIPLE_FILES) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", SYNTHESIZE_MULTIPLE_FILES); return EXIT_FAILURE; } else if(config_lookup(conf,SYNTHESIZE_MULTIPLE_FILES) != NULL) { config_lookup_bool(conf, SYNTHESIZE_MULTIPLE_FILES,&bool); params->multisyn = bool; } if(config_lookup(conf,USE_TILT) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", USE_TILT); return EXIT_FAILURE; } else if(config_lookup(conf,USE_TILT) != NULL) { config_lookup_bool(conf, USE_TILT,&bool); params->use_tilt = bool; } if(config_lookup(conf,USE_HNR) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", USE_HNR); return EXIT_FAILURE; } else if(config_lookup(conf,USE_HNR) != NULL) { config_lookup_bool(conf, USE_HNR,&bool); params->use_hnr = bool; } if(config_lookup(conf,USE_HARMONICS) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", USE_HARMONICS); return EXIT_FAILURE; } else if(config_lookup(conf,USE_HARMONICS) != NULL) { config_lookup_bool(conf, USE_HARMONICS,&bool); params->use_harmonics = bool; } if(config_lookup(conf,USE_H1H2) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", USE_H1H2); return EXIT_FAILURE; } else if(config_lookup(conf,USE_H1H2) != NULL) { config_lookup_bool(conf, USE_H1H2,&bool); params->use_h1h2 = bool; } if(config_lookup(conf,USE_NAQ) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", USE_NAQ); return EXIT_FAILURE; } else if(config_lookup(conf,USE_NAQ) != NULL) { config_lookup_bool(conf, USE_NAQ,&bool); params->use_naq = bool; } if(config_lookup(conf,USE_WAVEFORM) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", USE_WAVEFORM); return EXIT_FAILURE; } else if(config_lookup(conf,USE_WAVEFORM) != NULL) { config_lookup_bool(conf, USE_WAVEFORM,&bool); params->use_waveform = bool; } if(config_lookup(conf,WRITE_EXCITATION_TO_WAV) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", WRITE_EXCITATION_TO_WAV); return EXIT_FAILURE; } else if(config_lookup(conf,WRITE_EXCITATION_TO_WAV) != NULL) { config_lookup_bool(conf, WRITE_EXCITATION_TO_WAV,&bool); params->write_excitation_to_wav = bool; } if(config_lookup(conf,JITTER) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", JITTER); return EXIT_FAILURE; } else if(config_lookup(conf,JITTER) != NULL) { config_lookup_float(conf,JITTER,&fval); params->jitter = fval; } if (config_lookup(conf, NOISE_REDUCTION_SYNTHESIS) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", NOISE_REDUCTION_SYNTHESIS); return EXIT_FAILURE; } else if (config_lookup(conf, NOISE_REDUCTION_SYNTHESIS) != NULL) { config_lookup_bool(conf, NOISE_REDUCTION_SYNTHESIS,&bool); params->noise_reduction_synthesis = bool; } if (config_lookup(conf, NOISE_REDUCTION_LIMIT_DB) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", NOISE_REDUCTION_LIMIT_DB); return EXIT_FAILURE; } else if (config_lookup(conf, NOISE_REDUCTION_LIMIT_DB) != NULL) { config_lookup_float(conf, NOISE_REDUCTION_LIMIT_DB,&fval); params->noise_reduction_limit_db = fval; } if (config_lookup(conf, NOISE_REDUCTION_DB) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", NOISE_REDUCTION_DB); return EXIT_FAILURE; } else if (config_lookup(conf, NOISE_REDUCTION_DB) != NULL) { config_lookup_float(conf, NOISE_REDUCTION_DB,&fval); params->noise_reduction_db = fval; } if (config_lookup(conf, NORMALIZE_PULSELIB) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", NORMALIZE_PULSELIB); return EXIT_FAILURE; } else if (config_lookup(conf, NORMALIZE_PULSELIB) != NULL) { config_lookup_bool(conf, NORMALIZE_PULSELIB,&bool); params->normalize_pulselib = bool; } if (config_lookup(conf, ADAPT_TO_PULSELIB) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", ADAPT_TO_PULSELIB); return EXIT_FAILURE; } else if (config_lookup(conf, ADAPT_TO_PULSELIB) != NULL) { config_lookup_bool(conf, ADAPT_TO_PULSELIB,&bool); params->adapt_to_pulselib = bool; } if (config_lookup(conf, ADAPT_COEFF) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", ADAPT_COEFF); return EXIT_FAILURE; } else if (config_lookup(conf, ADAPT_COEFF) != NULL) { config_lookup_float(conf, ADAPT_COEFF,&fval); params->adapt_coeff = fval; } if (config_lookup(conf, USE_PULSELIB_LSF) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", USE_PULSELIB_LSF); return EXIT_FAILURE; } else if (config_lookup(conf, USE_PULSELIB_LSF) != NULL) { config_lookup_bool(conf, USE_PULSELIB_LSF,&bool); params->use_pulselib_lsf = bool; } if (config_lookup(conf, AVERAGE_N_ADJACENT_PULSES) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", AVERAGE_N_ADJACENT_PULSES); return EXIT_FAILURE; } else if (config_lookup(conf, AVERAGE_N_ADJACENT_PULSES) != NULL) { config_lookup_int(conf, AVERAGE_N_ADJACENT_PULSES,&ival); params->average_n_adjacent_pulses = (int)ival; } if (config_lookup(conf, LOG_F0) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", LOG_F0); return EXIT_FAILURE; } else if (config_lookup(conf, LOG_F0) != NULL) { config_lookup_bool(conf, LOG_F0,&bool); params->logf0 = bool; } if (config_lookup(conf, USE_DNN_PULSEGEN) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", USE_DNN_PULSEGEN); return EXIT_FAILURE; } else if (config_lookup(conf, USE_DNN_PULSEGEN) != NULL) { config_lookup_bool(conf, USE_DNN_PULSEGEN,&bool); params->use_dnn_pulsegen = bool; } if (config_lookup(conf, USE_DNN_PULSELIB_SEL) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", USE_DNN_PULSELIB_SEL); return EXIT_FAILURE; } else if (config_lookup(conf, USE_DNN_PULSELIB_SEL) != NULL) { config_lookup_bool(conf, USE_DNN_PULSELIB_SEL,&bool); params->use_dnn_pulselib_sel = bool; } if (config_lookup(conf, USE_DNN_SPECMATCH) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", USE_DNN_SPECMATCH); return EXIT_FAILURE; } else if (config_lookup(conf, USE_DNN_SPECMATCH) != NULL) { config_lookup_bool(conf, USE_DNN_SPECMATCH,&bool); params->use_dnn_specmatch = bool; } if (config_lookup(conf, DNN_INPUT_NORMALIZED) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", DNN_INPUT_NORMALIZED); return EXIT_FAILURE; } else if (config_lookup(conf, DNN_INPUT_NORMALIZED) != NULL) { config_lookup_bool(conf, DNN_INPUT_NORMALIZED,&bool); params->dnn_input_normalized = bool; } if (config_lookup(conf, DNN_NUMBER_OF_STACKED_FRAMES) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", DNN_NUMBER_OF_STACKED_FRAMES); return EXIT_FAILURE; } else if (config_lookup(conf, DNN_NUMBER_OF_STACKED_FRAMES) != NULL) { config_lookup_int(conf, DNN_NUMBER_OF_STACKED_FRAMES,&ival); params->dnn_number_of_stacked_frames = (int)ival; } if (config_lookup(conf, HNR_COMPENSATION) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", HNR_COMPENSATION); return EXIT_FAILURE; } else if (config_lookup(conf, HNR_COMPENSATION) != NULL) { config_lookup_bool(conf, HNR_COMPENSATION,&bool); params->hnr_compensation = bool; } if (config_lookup(conf, UNVOICED_PRE_EMPHASIS) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", UNVOICED_PRE_EMPHASIS); return EXIT_FAILURE; } else if (config_lookup(conf, UNVOICED_PRE_EMPHASIS) != NULL) { config_lookup_bool(conf, UNVOICED_PRE_EMPHASIS,&bool); params->unvoiced_pre_emphasis = bool; } /* Pulse PCA as target cost */ if (config_lookup(conf, USE_PULSE_PCA) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", USE_PULSE_PCA); return EXIT_FAILURE; } else if (config_lookup(conf, USE_PULSE_PCA) != NULL) { config_lookup_bool(conf, USE_PULSE_PCA,&bool); params->use_pulse_pca = bool; } /* Pulse library PCA */ if (config_lookup(conf, USE_PULSELIB_PCA) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", USE_PULSELIB_PCA); return EXIT_FAILURE; } else if (config_lookup(conf, USE_PULSELIB_PCA) != NULL) { config_lookup_bool(conf, USE_PULSELIB_PCA,&bool); params->use_pulselib_pca = bool; } if (config_lookup(conf, PCA_ORDER) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", PCA_ORDER); return EXIT_FAILURE; } else if (config_lookup(conf, PCA_ORDER) != NULL) { config_lookup_int(conf, PCA_ORDER,&ival); params->pca_order = (int)ival; } if (config_lookup(conf, PCA_ORDER_SYNTHESIS) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", PCA_ORDER_SYNTHESIS); return EXIT_FAILURE; } else if (config_lookup(conf, PCA_ORDER_SYNTHESIS) != NULL) { config_lookup_int(conf, PCA_ORDER_SYNTHESIS,&ival); params->pca_order_synthesis = (int)ival; } if (config_lookup(conf, PCA_SPECTRAL_MATCHING) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", PCA_SPECTRAL_MATCHING); return EXIT_FAILURE; } else if (config_lookup(conf, PCA_SPECTRAL_MATCHING) != NULL) { config_lookup_bool(conf, PCA_SPECTRAL_MATCHING,&bool); params->pca_spectral_matching = bool; } if (config_lookup(conf, PCA_PULSE_LENGTH) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", PCA_PULSE_LENGTH); return EXIT_FAILURE; } else if (config_lookup(conf, PCA_PULSE_LENGTH) != NULL) { config_lookup_int(conf, PCA_PULSE_LENGTH,&ival); params->pca_pulse_length = (int)ival; } if (config_lookup(conf, TWO_PITCH_PERIOD_DIFF_PULSE) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read default configuration \"%s\".\n", TWO_PITCH_PERIOD_DIFF_PULSE); return EXIT_FAILURE; } else if (config_lookup(conf, TWO_PITCH_PERIOD_DIFF_PULSE) != NULL) { config_lookup_bool(conf, TWO_PITCH_PERIOD_DIFF_PULSE,&bool); params->two_pitch_period_diff_pulse = bool; } /* Read data format */ if (config_lookup(conf, DATA_FORMAT) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",DATA_FORMAT); return EXIT_FAILURE; } else if (config_lookup(conf, DATA_FORMAT) != NULL) { config_lookup_string(conf,DATA_FORMAT,&tmp); if(strcmp(tmp,DATA_FORMAT_ASCII) == 0) params->data_format = DATA_FORMAT_ID_ASCII; else if(strcmp(tmp,DATA_FORMAT_BINARY) == 0) params->data_format = DATA_FORMAT_ID_BINARY; else { printf("\nError: Invalid configuration value \"%s\".\n", DATA_FORMAT); return EXIT_FAILURE; } } /* Read formant enhancement method */ if (config_lookup(conf, POSTFILTER_METHOD) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",POSTFILTER_METHOD); return EXIT_FAILURE; } else if (config_lookup(conf, POSTFILTER_METHOD) != NULL) { config_lookup_string(conf,POSTFILTER_METHOD,&tmp); if(strcmp(tmp,POSTFILTER_LSF) == 0) params->postfilter_method = POSTFILTER_ID_LSF; else if(strcmp(tmp,POSTFILTER_LPC) == 0) params->postfilter_method = POSTFILTER_ID_LPC; else if(strcmp(tmp,POSTFILTER_NONE) == 0) params->postfilter_method = POSTFILTER_ID_NONE; else { printf("\nError: Invalid configuration value \"%s\".\n", POSTFILTER_METHOD); return EXIT_FAILURE; } } /* Read parameter weights */ paramweights_conf = config_lookup(conf,PARAMETER_WEIGHTS); if(paramweights_conf == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", PARAMETER_WEIGHTS); return EXIT_FAILURE; } else if(paramweights_conf != NULL) { if(conf_type == USR_CONF) gsl_vector_free(params->paramweights); params->paramweights = gsl_vector_alloc(config_setting_length(paramweights_conf)); for(i=0;i<config_setting_length(paramweights_conf);i++) gsl_vector_set(params->paramweights,i,config_setting_get_float_elem(paramweights_conf, i)); } /* Read DNN weight dimensions */ dnn_dim_conf = config_lookup(conf,DNN_WEIGHT_DIMS); if(dnn_dim_conf == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n", DNN_WEIGHT_DIMS); return EXIT_FAILURE; } else if(dnn_dim_conf != NULL) { if(conf_type == USR_CONF) gsl_vector_free(params->dnn_weight_dims); params->dnn_weight_dims = gsl_vector_alloc(config_setting_length(dnn_dim_conf)); for(i=0;i<config_setting_length(dnn_dim_conf);i++) gsl_vector_set(params->dnn_weight_dims,i,config_setting_get_int_elem(dnn_dim_conf, i)); } /* Read pulse filename */ if(config_lookup(conf,GLOTTAL_PULSE_NAME) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",GLOTTAL_PULSE_NAME); return EXIT_FAILURE; } else if(config_lookup(conf,GLOTTAL_PULSE_NAME) != NULL) { if(conf_type == USR_CONF) free(params->pulse_filename); config_lookup_string(conf,GLOTTAL_PULSE_NAME,&tmp); params->pulse_filename = (char *)malloc((strlen(tmp)+1)*sizeof(char)); strcpy(params->pulse_filename,tmp); } /* Read pulse library filename */ if(config_lookup(conf,PULSE_LIBRARY_NAME) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",PULSE_LIBRARY_NAME); return EXIT_FAILURE; } else if(config_lookup(conf,PULSE_LIBRARY_NAME) != NULL) { if(conf_type == USR_CONF) free(params->pulselibrary_filename); config_lookup_string(conf,PULSE_LIBRARY_NAME,&tmp); params->pulselibrary_filename = (char *)malloc((strlen(tmp)+1)*sizeof(char)); strcpy(params->pulselibrary_filename,tmp); } /* Read synthesis list filename */ if(config_lookup(conf,SYNTHESIS_LIST) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",SYNTHESIS_LIST); return EXIT_FAILURE; } else if(config_lookup(conf,SYNTHESIS_LIST) != NULL) { if(conf_type == USR_CONF) free(params->synlist_filename); config_lookup_string(conf,SYNTHESIS_LIST,&tmp); params->synlist_filename = (char *)malloc((strlen(tmp)+1)*sizeof(char)); strcpy(params->synlist_filename,tmp); } /* Read DNN path */ if(config_lookup(conf,DNN_WEIGHT_PATH) == NULL && conf_type == DEF_CONF) { printf("\nError: Could not read configuration \"%s\".\n",DNN_WEIGHT_PATH); return EXIT_FAILURE; } else if(config_lookup(conf,DNN_WEIGHT_PATH) != NULL) { if(conf_type == USR_CONF) free(params->dnnpath); config_lookup_string(conf,DNN_WEIGHT_PATH,&tmp); params->dnnpath = (char *)malloc((strlen(tmp)+1)*sizeof(char)); strcpy(params->dnnpath,tmp); } /* Free memory if previously a synthesis list was allocated */ if(conf_type == USR_CONF) { for(i=0;i<synlistlen_old;i++) free(params->synlist[i]); free(params->synlist); } /* Create synthesis list */ if(params->multisyn == 1) { if(ReadSynthesisList(params) == EXIT_FAILURE) return EXIT_FAILURE; } else { params->synlistlen = 1; params->synlist = (char **)malloc(sizeof(char *)); params->synlist[0] = (char *)malloc((strlen(filename)+1)*sizeof(char)); strcpy(params->synlist[0],filename); } /* Convert milliseconds to samples */ params->frame_length = rint(params->FS*params->frame_length_ms/1000); params->shift = rint(params->FS*params->shift_ms/1000); params->f0_frame_length = rint(params->FS*params->f0_frame_length_ms/1000); params->gain_voiced_frame_length = rint(params->FS*params->gain_voiced_frame_length_ms/1000); params->gain_unvoiced_frame_length = rint(params->FS*params->gain_unvoiced_frame_length_ms/1000); params->filter_update_interval_vt = GSL_MAX(rint(params->FS*params->filter_update_interval_vt_ms/1000),1); params->filter_update_interval_gl = GSL_MAX(rint(params->FS*params->filter_update_interval_gl_ms/1000),1); /* Set time */ if(conf_type == DEF_CONF) params->time_temp = (double)clock(); /* Free memory */ config_destroy(conf); free(conf); return EXIT_SUCCESS; } /** * Function ReadSynthesisList * * Read list of synthesis file names * * @param name filename * @return number of files in the list */ int ReadSynthesisList(PARAM *params) { FILE *file; char s[DEF_STRING_LEN]; int ind; /* Open file */ file = fopen(params->synlist_filename, "r"); if(!file) { printf("Error opening synthesis list file \"%s\": %s\n", params->synlist_filename, strerror(errno)); return EXIT_FAILURE; } /* Read lines until EOF */ ind = 0; while(fscanf(file,"%s",s) != EOF) ind++; /* Allocate memory for strings */ params->synlistlen = ind; char **filenames = (char **)malloc(ind*sizeof(char *)); /* Read file names to array */ fseek(file, 0, SEEK_SET); ind = 0; char *fn; while(fscanf(file,"%s",s) != EOF) { fn = (char *)malloc((strlen(s)+1)*sizeof(char)); strcpy(fn,s); filenames[ind] = fn; ind++; } fclose(file); /* Set list to params */ params->synlist = filenames; return EXIT_SUCCESS; } /** * Read_DNN_weights * * Read DNN pulse generation weights from file, check validity * */ int Read_DNN_weights(PARAM *params, gsl_matrix **DNN_W) { /* Do not read if DNNs are not used */ if(params->use_dnn_pulsegen == 0) return EXIT_SUCCESS; /* Allocate weight matrices and read data from files */ int i,numlayers = params->dnn_weight_dims->size/2; char temp[DEF_STRING_LEN]; char num[20]; FILE *wfile; for(i=0;i<numlayers;i++) { DNN_W[i] = gsl_matrix_alloc(gsl_vector_get(params->dnn_weight_dims,2*i),gsl_vector_get(params->dnn_weight_dims,2*i+1)); strcpy(temp,params->dnnpath); strcat(temp,FILENAME_DNN_W); sprintf(num,"%d",i+1); strcat(temp,num); wfile = fopen(temp, "r"); if(wfile == NULL) { printf("Error opening file \"%s\": %s\n",temp,strerror(errno)); return EXIT_FAILURE; } gsl_matrix_fscanf(wfile,DNN_W[i]); fclose(wfile); } /* Return */ return EXIT_SUCCESS; } /** * Read_input_minmax * * Read input data minimum and maximum for normalizing the input data for DNN pulse generation * */ int Read_input_minmax(PARAM *params, gsl_vector **input_minmax) { /* Do not read if DNNs are not used */ if(params->use_dnn_pulsegen == 0 || params->dnn_input_normalized == 0) return EXIT_SUCCESS; /* Allocate weight matrices and read data from files */ char temp[DEF_STRING_LEN]; char num[20]; FILE *datafile; input_minmax[0] = gsl_vector_alloc(2*(gsl_vector_get(params->dnn_weight_dims,0)-1)/params->dnn_number_of_stacked_frames); strcpy(temp,params->dnnpath); strcat(temp,FILENAME_INPUT_MINMAX); datafile = fopen(temp, "r"); if(datafile == NULL) { printf("Error opening file \"%s\": %s\n",temp,strerror(errno)); return EXIT_FAILURE; } gsl_vector_fscanf(datafile,input_minmax[0]); fclose(datafile); /* Return */ return EXIT_SUCCESS; } /** * Read_pulse_library * * Read pulse library from file, check validity * */ int Read_pulse_library(PARAM *params,gsl_matrix **pulses,gsl_matrix **pulses_rs,gsl_matrix **plsf,gsl_matrix **ptilt,gsl_matrix **pharm, gsl_matrix **phnr,gsl_matrix **pwaveform, gsl_matrix **pca_pc,gsl_matrix **pca_w_lib,gsl_vector **stoch_env,gsl_vector **stoch_sp,gsl_vector **pgain, gsl_vector **ph1h2, gsl_vector **pnaq, gsl_vector **pca_mean, gsl_vector **pulse_lengths) { /* Do not read if pulse library is not used */ if(params->use_pulselib == 0) { params->n_pulsecandidates = 1; params->pulsemaxlen = 1; params->rspulsemaxlen = 1; return EXIT_SUCCESS; } /* Initialize */ printf(" - Loading pulse library...\n"); double time1 = (double)clock(); char temp[DEF_STRING_LEN]; /* Load params file for pulse library, */ strcpy(temp, params->pulselibrary_filename); FILE *plparams_file = fopen(strcat(temp,FILENAME_ENDING_INFO), "r"); if(plparams_file == NULL) { printf(" - Pulse library \"%s\" was not found\n",params->pulselibrary_filename); return EXIT_FAILURE; } /* Read pulse library parameterers */ gsl_vector *plparams = gsl_vector_alloc(NPARAMS); gsl_vector_fscanf(plparams_file,plparams); params->number_of_pulses = gsl_vector_get(plparams,9); params->pulsemaxlen_ms = gsl_vector_get(plparams,10); params->rspulsemaxlen_ms = gsl_vector_get(plparams,11); /* Convert milliseconds to samples */ params->pulsemaxlen = rint((double)params->FS*(double)params->pulsemaxlen_ms/1000.0); params->rspulsemaxlen = rint(params->FS*params->rspulsemaxlen_ms/1000); /* Check compatibility with configuration parameters */ if(params->lpc_order_vt != (int)gsl_vector_get(plparams,3)) {printf("\nPulse library error: Different vocal tract LPC order\n\n"); return EXIT_FAILURE;} if(params->lpc_order_gl != (int)gsl_vector_get(plparams,4)) {printf("\nPulse library error: Different source LPC order\n\n"); return EXIT_FAILURE;} if(params->hnr_channels != gsl_vector_get(plparams,7)) {printf("\nPulse library error: Different number of HNR channels\n\n"); return EXIT_FAILURE;} if(params->number_of_harmonics != gsl_vector_get(plparams,8)) {printf("\nPulse library error: Different number of harmonics\n\n"); return EXIT_FAILURE;} if(params->waveform_samples != gsl_vector_get(plparams,12)) {printf("\nPulse library error: Different number of samples in Waveform\n\n"); return EXIT_FAILURE;} if(params->FS != gsl_vector_get(plparams,13)) {printf("\nPulse library error: Different sampling frequency\n\n"); return EXIT_FAILURE;} if(params->data_format != (int)gsl_vector_get(plparams,14)) {printf("\nPulse library error: Different data format (ascii/binary)\n\n"); return EXIT_FAILURE;} if(params->number_of_pulses < params->n_pulsecandidates) { printf(" - Warning: Number of pulse candidates is greater than the total number of pulses.\n"); printf(" Number of pulse candidates changed to: %i.\n",params->number_of_pulses); params->n_pulsecandidates = params->number_of_pulses; } gsl_vector_free(plparams); fclose(plparams_file); /* Allocate space for pulse library data */ *(pulses) = gsl_matrix_alloc(params->number_of_pulses,params->pulsemaxlen); *(pulses_rs) = gsl_matrix_alloc(params->number_of_pulses,params->rspulsemaxlen); *(pulse_lengths) = gsl_vector_alloc(params->number_of_pulses); *(plsf) = gsl_matrix_calloc(params->number_of_pulses,params->lpc_order_vt); *(pgain) = gsl_vector_calloc(params->number_of_pulses); if(params->use_tilt == 1) *(ptilt) = gsl_matrix_calloc(params->number_of_pulses,params->lpc_order_gl); else *(ptilt) = NULL; if(params->use_harmonics == 1) *(pharm) = gsl_matrix_calloc(params->number_of_pulses,params->number_of_harmonics); else *(pharm) = NULL; if(params->use_hnr == 1) *(phnr) = gsl_matrix_calloc(params->number_of_pulses,params->hnr_channels); else *(phnr) = NULL; if(params->use_waveform == 1) *(pwaveform) = gsl_matrix_calloc(params->number_of_pulses,params->waveform_samples); else *(pwaveform) = NULL; if(params->use_h1h2 == 1) *(ph1h2) = gsl_vector_calloc(params->number_of_pulses); else *(ph1h2) = NULL; if(params->use_naq == 1) *(pnaq) = gsl_vector_calloc(params->number_of_pulses); else *(pnaq) = NULL; /* Load pulse data */ strcpy(temp, params->pulselibrary_filename); FILE *pulses_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_PULSES), "r"); if(pulses_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} strcpy(temp, params->pulselibrary_filename);FILE *pulses_rs_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_RSPULSES), "r"); if(pulses_rs_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} strcpy(temp, params->pulselibrary_filename);FILE *pulse_lengths_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_PULSELENGTHS), "r"); if(pulse_lengths_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} if(params->data_format == DATA_FORMAT_ID_ASCII) { gsl_matrix_fscanf(pulses_file,*(pulses)); gsl_matrix_fscanf(pulses_rs_file,*(pulses_rs)); gsl_vector_fscanf(pulse_lengths_file,*(pulse_lengths)); } else if(params->data_format == DATA_FORMAT_ID_BINARY) { gsl_matrix_fread(pulses_file,*(pulses)); gsl_matrix_fread(pulses_rs_file,*(pulses_rs)); gsl_vector_fread(pulse_lengths_file,*(pulse_lengths)); } fclose(pulses_file); fclose(pulses_rs_file); fclose(pulse_lengths_file); /* Load parameter data */ strcpy(temp, params->pulselibrary_filename);FILE *plsf_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_LSF), "r"); if(plsf_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_matrix_fscanf(plsf_file,*(plsf)); else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(plsf_file,*(plsf)); fclose(plsf_file); strcpy(temp, params->pulselibrary_filename);FILE *pgain_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_GAIN), "r"); if(pgain_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_vector_fscanf(pgain_file,*(pgain)); else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(pgain_file,*(pgain)); fclose(pgain_file); if(params->use_tilt == 1) {strcpy(temp, params->pulselibrary_filename);FILE *ptilt_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_TILT), "r"); if(ptilt_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_matrix_fscanf(ptilt_file,*(ptilt)); else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(ptilt_file,*(ptilt)); fclose(ptilt_file);} if(params->use_harmonics == 1) {strcpy(temp, params->pulselibrary_filename);FILE *pharm_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_HARM), "r"); if(pharm_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_matrix_fscanf(pharm_file,*(pharm)); else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(pharm_file,*(pharm)); fclose(pharm_file);} if(params->use_hnr == 1) {strcpy(temp, params->pulselibrary_filename);FILE *phnr_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_HNR), "r"); if(phnr_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_matrix_fscanf(phnr_file,*(phnr)); else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(phnr_file,*(phnr)); fclose(phnr_file);} if(params->use_waveform == 1) {strcpy(temp, params->pulselibrary_filename);FILE *pwaveform_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_WAVEFORM), "r"); if(pwaveform_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_matrix_fscanf(pwaveform_file,*(pwaveform)); else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(pwaveform_file,*(pwaveform)); fclose(pwaveform_file);} if(params->use_h1h2 == 1) {strcpy(temp, params->pulselibrary_filename);FILE *ph1h2_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_H1H2), "r"); if(ph1h2_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_vector_fscanf(ph1h2_file,*(ph1h2)); else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(ph1h2_file,*(ph1h2)); fclose(ph1h2_file);} if(params->use_naq == 1) {strcpy(temp, params->pulselibrary_filename);FILE *pnaq_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_NAQ), "r"); if(pnaq_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_vector_fscanf(pnaq_file,*(pnaq)); else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(pnaq_file,*(pnaq)); fclose(pnaq_file);} /* Normalize the sum of paramweights to one */ double sum = 0; int i; for(i=0;i<params->paramweights->size;i++) sum += gsl_vector_get(params->paramweights,i); for(i=0;i<params->paramweights->size;i++) gsl_vector_set(params->paramweights,i,gsl_vector_get(params->paramweights,i)/sum); /* Allocate space for pulse library PCA parameters */ if(params->use_pulselib_pca == 1) { *(pca_pc) = gsl_matrix_calloc(params->pca_pulse_length,params->pca_order); *(pca_mean) = gsl_vector_calloc(params->pca_pulse_length); *(stoch_env) = gsl_vector_calloc(params->rspulsemaxlen); *(stoch_sp) = gsl_vector_calloc(STOCH_SP_LPC_ORDER); strcpy(temp, params->pulselibrary_filename);FILE *pca_pc_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_PCA_PC), "r"); if(pca_pc_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_matrix_fscanf(pca_pc_file,*(pca_pc)); else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(pca_pc_file,*(pca_pc)); fclose(pca_pc_file); strcpy(temp, params->pulselibrary_filename);FILE *pca_mean_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_PCA_MEAN), "r"); if(pca_mean_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_vector_fscanf(pca_mean_file,*(pca_mean)); else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(pca_mean_file,*(pca_mean)); fclose(pca_mean_file); //strcpy(temp, params->pulselibrary_filename);FILE *stoch_env_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_STOCH_ENV), "r"); //if(stoch_env_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} //if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_vector_fscanf(stoch_env_file,*(stoch_env)); //else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(stoch_env_file,*(stoch_env)); //fclose(stoch_env_file); //strcpy(temp, params->pulselibrary_filename);FILE *stoch_sp_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_STOCH_SP), "r"); //if(stoch_sp_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} //if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_vector_fscanf(stoch_sp_file,*(stoch_sp)); //else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(stoch_sp_file,*(stoch_sp)); //fclose(stoch_sp_file); } else { *(pca_pc) = NULL; *(pca_mean) = NULL; *(stoch_env) = NULL; *(stoch_sp) = NULL; } /* Allocate space for pulse PCA parameters */ if(params->use_pulse_pca == 1) { *(pca_w_lib) = gsl_matrix_calloc(params->number_of_pulses,params->pca_order); strcpy(temp, params->pulselibrary_filename);FILE *pca_w_lib_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_PCA_W), "r"); if(pca_w_lib_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_matrix_fscanf(pca_w_lib_file,*(pca_w_lib)); else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_matrix_fread(pca_w_lib_file,*(pca_w_lib)); fclose(pca_w_lib_file); } else { *(pca_w_lib) = NULL; } /* Print elapsed time */ printf(" (%1.2lf s)\n",((double)clock()-time1)/(double)CLOCKS_PER_SEC); params->time_temp = (double)clock(); return EXIT_SUCCESS; } /** * Function ReadPulseFile * * Read pulse values from file * * @param name filename * @return vector containing the values */ gsl_vector *ReadPulseFile(PARAM *params) { FILE *file; double values[1000]; char s[50]; int i,ind; /* Open file */ file = fopen(params->pulse_filename, "r"); if(!file) { printf("Error opening pulse file \"%s\": %s\n", params->pulse_filename, strerror(errno)); return NULL; } /* Read lines until EOF */ ind = 0; while(fscanf(file,"%s",s) != EOF) { values[ind] = atof(s); ind++; } /* Copy values to vector and return vector pointer */ gsl_vector *pulse = gsl_vector_alloc(ind); for(i=0;i<ind;i++) { gsl_vector_set(pulse,i,values[i]); } fclose(file); return pulse; } /** * Function Initialize_params * * Initialize params file * * @param params * @return synfilenumber */ int Initialize_params(PARAM *params, int synfilenumber) { /* Initialize parameters for synthesizing new file */ params->synfilenumber = synfilenumber; params->resynth = 0; params->compcoeff = 1.0; params->hnr_reestimated = 0; params->pulse_tilt_decrease_coeff = 1; /* Modification for noise robust speech */ Noise_robust_speech1(params); /* Count the number of frames */ char temp[DEF_STRING_LEN]; strcpy(temp, params->synlist[params->synfilenumber]); params->n_frames = EvalFileLength(strcat(temp,FILENAME_ENDING_F0),params); /* Evaluate signal length */ params->signal_length = rint(params->n_frames*params->shift/params->speed); // For replicating the exact analysis-synthesis file length //int empty_frames = rint((params->frame_length/(double)params->shift - 1)/2); //int frames_orig = params->n_frames - 2*empty_frames; //params->signal_length = (frames_orig + params->frame_length/(double)params->shift/params->speed - 1.0)*(double)params->shift/params->speed; /* Return */ if(params->n_frames == -1) { return EXIT_FAILURE; } if(params->n_frames == 0) { printf("\nError: Zero length F0 vector\n\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } /** * Function EvalFileLength * * If file is in ASCII mode, read file and count the number of lines. * If file is in BINARY mode, read file size. * * @param name filename * @return number of parameters */ int EvalFileLength(const char *name, PARAM *params) { FILE *file; char s[50]; int fileSize = 0; /* Open file */ file = fopen(name, "r"); if(!file) { printf("Error opening file \"%s\": %s\n", name, strerror(errno)); return -1; } /* Read lines until EOF */ if(params->data_format == DATA_FORMAT_ID_ASCII) { while(fscanf(file,"%s",s) != EOF) fileSize++; } else if(params->data_format == DATA_FORMAT_ID_BINARY) { fseek(file, 0, SEEK_END); fileSize = ftell(file)/sizeof(double); } fclose(file); return fileSize; } /** * Function Print_synthesis_settings_start * * Print synthesis settings in the beginning * * @param params */ void Print_synthesis_settings_start(PARAM *params) { printf("Synthesis of %s\n",params->synlist[0]); } /** * Function Print_synthesis_settings_middle * * Print synthesis settings in progress * * @param params */ void Print_synthesis_settings_middle(PARAM *params) { if(params->synfilenumber > 0) { printf("Synthesis of %s\n",params->synlist[params->synfilenumber]); } } /** * Function Print_synthesis_settings_end * * Print synthesis settings in the end * * @param filename * @param params */ void Print_synthesis_settings_end(PARAM *params, double time1) { /* Speech file name */ char temp[DEF_STRING_LEN]; strcpy(temp, params->synlist[params->synfilenumber]); strcat(temp,FILENAME_ENDING_SYNTHESIS); /* Print at the end of synthesis of one file */ if(params->multisyn == 1) { printf(" (%1.2lf s)\n",((double)clock()-params->time_temp)/(double)CLOCKS_PER_SEC); printf(" - Finished synthesis of %s\n\n",temp); } /* Print at the of the program */ if(params->synfilenumber == params->synlistlen-1) { if(params->multisyn == 0) { printf(" (%1.2lf s)\n",((double)clock()-params->time_temp)/(double)CLOCKS_PER_SEC); printf(" - Finished synthesis.\n\n"); printf("Elapsed time: %1.2lf seconds.\n",((double)clock()-time1)/(double)CLOCKS_PER_SEC); printf("Synthesized speech saved to file \"%s\".\n\n",temp); } else { printf("Finished synthesis of files:\n\n"); int i; for(i=0;i<params->synlistlen;i++) printf(" %s\n",params->synlist[i]); double t = ((double)clock()-time1)/(double)CLOCKS_PER_SEC; printf("\nTotal elapsed time: %1.2lf seconds (average %1.2lf seconds per file).\n\n",t,t/(double)params->synlistlen); } } } /** * Function Compatibility_check * * Check the compatibility with configuration and pulse library parameters * * @param params */ int Compatibility_check(PARAM *params) { /* Initialize */ char temp[DEF_STRING_LEN]; FILE *parameter_file; /* Open parameter file */ strcpy(temp, params->synlist[params->synfilenumber]); parameter_file = fopen(strcat(temp,FILENAME_ENDING_INFO), "r"); /* If parameter file is found, check compatibility */ if(parameter_file == NULL) { if(params->use_hmm == 0) printf("\"%s\" was not found, proceed without compatibility check.\n\n",temp); if(parameter_file != NULL) fclose(parameter_file); } else { gsl_vector *parameters = gsl_vector_alloc(NPARAMS); gsl_vector_fscanf(parameter_file,parameters); if(params->frame_length_ms != gsl_vector_get(parameters,0)) {printf("\nWarning: Different frame length in analysis and synthesis\n\n");} if(params->shift_ms != gsl_vector_get(parameters,1)) {printf("\nWarning: Different shift length in analysis and synthesis\n\n");} if(params->n_frames != (int)gsl_vector_get(parameters,2)) {printf("\nWarning: infofile indicates a different number of frames compared to actual files\n\n");} if(params->n_frames < 1) {printf("\nError: Zero-length input parameters\n\n");return EXIT_FAILURE;} if(params->lpc_order_vt != (int)gsl_vector_get(parameters,3)) {printf("\nError: Different vocal tract LPC order in analysis and synthesis\n\n"); return EXIT_FAILURE;} if(params->lpc_order_gl != (int)gsl_vector_get(parameters,4)) {printf("\nError: Different source LPC order in analysis and synthesis\n\n"); return EXIT_FAILURE;} if(params->lambda_gl != gsl_vector_get(parameters,6)) {printf("\nError: Different source warping coefficient in analysis and synthesis\n\n"); return EXIT_FAILURE;} if(params->hnr_channels != gsl_vector_get(parameters,7)) {printf("\nError: Different number of HNR channels in analysis and synthesis\n\n"); return EXIT_FAILURE;} if(params->number_of_harmonics != gsl_vector_get(parameters,8)) {printf("\nError: Different number of harmonics in analysis and synthesis\n\n"); return EXIT_FAILURE;} if(params->lambda_vt != gsl_vector_get(parameters,5)) {printf("\nWarning: Different vocal tract warping coefficient in analysis and synthesis\n\n");} if(params->FS != gsl_vector_get(parameters,13)) {printf("\nWarning: Different sampling frequency in analysis and synthesis\n\n");} if(params->gain_voiced_frame_length_ms > params->frame_length_ms || params->gain_unvoiced_frame_length_ms > params->frame_length_ms) {printf("\nError: Voiced/unvoiced frame length must be less or equal to frame length\n\n"); return EXIT_FAILURE;} if(params->data_format != (int)gsl_vector_get(parameters,14)) {printf("\nError: Different data format (ascii/binary)\n\n"); return EXIT_FAILURE;} gsl_vector_free(parameters); fclose(parameter_file); } /* Check compatibility with used parameters and synthesis method */ if(params->use_pulselib == 0) { if(params->use_tilt == 0) {printf("\nError: Spectral tilt (LSFsource) must be used with single pulse technique.\n\n");return EXIT_FAILURE;} if(params->use_hnr == 0) {printf("\nError: Harmonic to noise ratio (HNR) must be used with single pulse technique.\n\n");return EXIT_FAILURE;} if(params->use_harmonic_modification == 1 && params->use_harmonics == 0) {printf("\nError: Harmonics must be used with harmonic modification of the pulse.\n\n");return EXIT_FAILURE;} } /* Check compatibility with PCA/ICA */ if(params->use_pulselib_pca == 1 && params->use_pulselib == 0) {printf("\nError: Pulse library must be used with PCA/ICA based pulse reconstruction.\n\n");return EXIT_FAILURE;} return EXIT_SUCCESS; } /** * Function Allocate_params * * Allocate synthesis parameters * * @param params */ void Allocate_params(gsl_vector **excitation_voiced, gsl_vector **excitation_unvoiced, gsl_vector **resynthesis_pulse_index, gsl_vector **gain_new, gsl_matrix **glflowsp_new, gsl_matrix **hnr_new, PARAM *params) { /* Allocate */ *(excitation_voiced) = gsl_vector_calloc(params->signal_length); *(excitation_unvoiced) = gsl_vector_calloc(params->signal_length); *(gain_new) = gsl_vector_calloc(params->n_frames); *(hnr_new) = gsl_matrix_calloc(params->n_frames,params->hnr_channels); *(glflowsp_new) = gsl_matrix_calloc(params->n_frames,params->lpc_order_gl); *(resynthesis_pulse_index) = gsl_vector_calloc(params->n_frames); } /** * Function Read_synthesis_parameters * * Allocate and read synthesis parameters * * @param params */ int Read_synthesis_parameters(gsl_vector **gain, gsl_vector **fundf, gsl_matrix **LSF, gsl_matrix **LSF2, gsl_matrix **glflowsp, gsl_matrix **hnr, gsl_matrix **harmonics, gsl_matrix **waveform, gsl_vector **h1h2, gsl_vector **naq, gsl_matrix **pca_w, PARAM *params) { /* Initialize */ char temp[DEF_STRING_LEN]; /* Define variables */ FILE *LSF_file = NULL,*LSF2_file = NULL,*Gain_file = NULL,*F0_file = NULL,*LSFsource_file = NULL,*hnr_file = NULL; FILE *harmonics_file = NULL,*waveform_file = NULL,*h1h2_file = NULL,*naq_file = NULL; /* Allocate memory for variables (affected by differential LSFs processing) */ if(params->differential_lsf == 1) *(LSF) = gsl_matrix_alloc(params->n_frames,params->lpc_order_vt+1); else *(LSF) = gsl_matrix_alloc(params->n_frames,params->lpc_order_vt); if(params->use_tilt == 1) if(params->differential_lsf == 1) *(glflowsp) = gsl_matrix_alloc(params->n_frames,params->lpc_order_gl+1); else *(glflowsp) = gsl_matrix_alloc(params->n_frames,params->lpc_order_gl); else *(glflowsp) = NULL; if(params->sep_vuv_spectrum == 1) if(params->differential_lsf == 1) *(LSF2) = gsl_matrix_alloc(params->n_frames,params->lpc_order_vt+1); else *(LSF2) = gsl_matrix_alloc(params->n_frames,params->lpc_order_vt); else *(LSF2) = NULL; /* Allocate memory for variables */ *(gain) = gsl_vector_alloc(params->n_frames); *(fundf) = gsl_vector_alloc(params->n_frames); if(params->use_hnr == 1) *(hnr) = gsl_matrix_alloc(params->n_frames,params->hnr_channels); else *(hnr) = NULL; if(params->use_harmonics == 1) *(harmonics) = gsl_matrix_alloc(params->n_frames,params->number_of_harmonics); else *(harmonics) = NULL; if(params->use_waveform == 1) *(waveform) = gsl_matrix_alloc(params->n_frames,params->waveform_samples); else *(waveform) = NULL; if(params->use_h1h2 == 1) *(h1h2) = gsl_vector_alloc(params->n_frames); else *(h1h2) = NULL; if(params->use_naq == 1) *(naq) = gsl_vector_alloc(params->n_frames); else *(naq) = NULL; /* Open files */ strcpy(temp, params->synlist[params->synfilenumber]);LSF_file = fopen(strcat(temp,FILENAME_ENDING_LSF), "r"); if(LSF_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} strcpy(temp, params->synlist[params->synfilenumber]);Gain_file = fopen(strcat(temp,FILENAME_ENDING_GAIN), "r"); if(Gain_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} strcpy(temp, params->synlist[params->synfilenumber]);F0_file = fopen(strcat(temp,FILENAME_ENDING_F0), "r"); if(F0_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} if(params->use_tilt == 1) {strcpy(temp, params->synlist[params->synfilenumber]);LSFsource_file = fopen(strcat(temp,FILENAME_ENDING_LSFSOURCE), "r"); if(LSFsource_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;}} if(params->use_hnr == 1) {strcpy(temp, params->synlist[params->synfilenumber]);hnr_file = fopen(strcat(temp,FILENAME_ENDING_HNR), "r"); if(hnr_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;}} if(params->use_harmonics == 1) {strcpy(temp, params->synlist[params->synfilenumber]);harmonics_file = fopen(strcat(temp,FILENAME_ENDING_HARMONICS), "r"); if(harmonics_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;}} if(params->use_waveform == 1) {strcpy(temp, params->synlist[params->synfilenumber]);waveform_file = fopen(strcat(temp,FILENAME_ENDING_WAVEFORM), "r"); if(waveform_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;}} if(params->use_h1h2 == 1) {strcpy(temp, params->synlist[params->synfilenumber]);h1h2_file = fopen(strcat(temp,FILENAME_ENDING_H1H2), "r"); if(h1h2_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;}} if(params->use_naq == 1) {strcpy(temp, params->synlist[params->synfilenumber]);naq_file = fopen(strcat(temp,FILENAME_ENDING_NAQ), "r"); if(naq_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;}} if(params->sep_vuv_spectrum == 1) {strcpy(temp, params->synlist[params->synfilenumber]);LSF2_file = fopen(strcat(temp,FILENAME_ENDING_LSF2), "r"); if(LSF2_file==NULL){printf("Error opening file \"%s\": %s.\nSet configuration parameter SEPARATE_VOICED_UNVOICED_SPECTRUM to zero if single spectrum is used.\n",temp,strerror(errno));return EXIT_FAILURE;}} /* Read parameters from files */ if(params->data_format == DATA_FORMAT_ID_ASCII) { gsl_vector_fscanf(Gain_file,*(gain)); gsl_vector_fscanf(F0_file,*(fundf)); gsl_matrix_fscanf(LSF_file,*(LSF)); if(params->use_tilt == 1) gsl_matrix_fscanf(LSFsource_file,*(glflowsp)); if(params->use_hnr == 1) gsl_matrix_fscanf(hnr_file,*(hnr)); if(params->use_harmonics == 1) gsl_matrix_fscanf(harmonics_file,*(harmonics)); if(params->use_waveform == 1) gsl_matrix_fscanf(waveform_file,*(waveform)); if(params->use_h1h2 == 1) gsl_vector_fscanf(h1h2_file,*(h1h2)); if(params->use_naq == 1) gsl_vector_fscanf(naq_file,*(naq)); if(params->sep_vuv_spectrum == 1) gsl_matrix_fscanf(LSF2_file,*(LSF2)); } else if(params->data_format == DATA_FORMAT_ID_BINARY) { gsl_vector_fread(Gain_file,*(gain)); gsl_vector_fread(F0_file,*(fundf)); gsl_matrix_fread(LSF_file,*(LSF)); if(params->use_tilt == 1) gsl_matrix_fread(LSFsource_file,*(glflowsp)); if(params->use_hnr == 1) gsl_matrix_fread(hnr_file,*(hnr)); if(params->use_harmonics == 1) gsl_matrix_fread(harmonics_file,*(harmonics)); if(params->use_waveform == 1) gsl_matrix_fread(waveform_file,*(waveform)); if(params->use_h1h2 == 1) gsl_vector_fread(h1h2_file,*(h1h2)); if(params->use_naq == 1) gsl_vector_fread(naq_file,*(naq)); if(params->sep_vuv_spectrum == 1) gsl_matrix_fread(LSF2_file,*(LSF2)); } /* Close files */ fclose(F0_file); fclose(LSF_file); fclose(Gain_file); if(params->use_tilt == 1) fclose(LSFsource_file); if(params->use_hnr == 1) fclose(hnr_file); if(params->use_harmonics == 1)fclose(harmonics_file); if(params->use_waveform == 1) fclose(waveform_file); if(params->use_h1h2 == 1) fclose(h1h2_file); if(params->use_naq == 1) fclose(naq_file); if(params->sep_vuv_spectrum == 1) fclose(LSF2_file); /* Read pulse library PCA weights */ if(params->use_pulselib_pca == 1 || params->use_pulse_pca == 1) { /* Initialize */ FILE *pca_w_file; *(pca_w) = gsl_matrix_calloc(params->n_frames,params->pca_order); /* Load only if PC weights are used in synthesis of the mean pulse */ if(params->use_pulselib_pca == 1 && params->pca_order_synthesis > 0 && params->use_dnn_pulsegen == 0) { strcpy(temp, params->synlist[params->synfilenumber]); pca_w_file = fopen(strcat(temp,FILENAME_ENDING_PULSELIB_PCA_W), "r"); if(pca_w_file==NULL) { printf("Error opening file \"%s\": %s\n",temp,strerror(errno)); return EXIT_FAILURE; } if(params->data_format == DATA_FORMAT_ID_ASCII) { gsl_matrix_fscanf(pca_w_file,*(pca_w)); } else if(params->data_format == DATA_FORMAT_ID_BINARY) { gsl_matrix_fread(pca_w_file,*(pca_w)); } fclose(pca_w_file); } } return EXIT_SUCCESS; } /** * Function Print_elapsed_time * * Print elapsed time * * @param */ void Print_elapsed_time(PARAM *params) { printf(" (%1.2lf s)\n",((double)clock()-params->time_temp)/(double)CLOCKS_PER_SEC); params->time_temp = (double)clock(); } /** * Function Pulse_clustering * * Read file and count the number of lines * * @param pulse_clus_id pointer to pulse cluster ids * @param pulse_clusters pointer to pulse clusters * @param params paramteres structure * @param synfilenumber * @return */ int Pulse_clustering(gsl_vector **pulse_clus_id_POINTER, gsl_matrix **pulse_clusters_POINTER, PARAM *params) { if(params->pulse_clustering == 1) { /* Initialize */ gsl_vector *pulse_clus_id; gsl_matrix *pulse_clusters; FILE *pulse_clus_id_file; char temp[DEF_STRING_LEN]; int i,j; /* Read cluster ids per frame */ strcpy(temp, params->synlist[params->synfilenumber]);pulse_clus_id_file = fopen(strcat(temp,FILENAME_ENDING_PULSECLUSTER), "r"); if(pulse_clus_id_file==NULL){printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} pulse_clus_id = gsl_vector_alloc(params->n_frames); if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_vector_fscanf(pulse_clus_id_file, pulse_clus_id); else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(pulse_clus_id_file, pulse_clus_id); fclose(pulse_clus_id_file); /* Read clusters that are used in utterance */ pulse_clusters = gsl_matrix_alloc((int)(gsl_vector_max(pulse_clus_id)+1), params->max_pulses_in_cluster); gsl_matrix_set_all(pulse_clusters, -1); for(i=0;i<pulse_clus_id->size;i++) { sprintf(temp, "%s_clusters/%d", params->pulselibrary_filename, (int)gsl_vector_get(pulse_clus_id, i)); int n_p = EvalFileLength(temp,params); FILE *cluster_file = fopen(temp, "r"); if(cluster_file==NULL) {printf("Error opening file \"%s\": %s\n",temp,strerror(errno));return EXIT_FAILURE;} /* Allocate correctly sized vector */ gsl_vector *temp_v; if(n_p > 0) { temp_v = gsl_vector_alloc(n_p); cluster_file = fopen(temp, "r"); if(params->data_format == DATA_FORMAT_ID_ASCII) gsl_vector_fscanf(cluster_file, temp_v); else if(params->data_format == DATA_FORMAT_ID_BINARY) gsl_vector_fread(cluster_file, temp_v); fclose(cluster_file); /* Add clusters to matrix (terribly sparse) */ for(j=0;j<temp_v->size;j++) { if(j == params->max_pulses_in_cluster) break; gsl_matrix_set(pulse_clusters, gsl_vector_get(pulse_clus_id, i), j, gsl_vector_get(temp_v, j)); } gsl_vector_free(temp_v); } } /* Set pointers */ *(pulse_clus_id_POINTER) = pulse_clus_id; *(pulse_clusters_POINTER) = pulse_clusters; return EXIT_SUCCESS; } return EXIT_SUCCESS; } /** * Function LSF_fix_vector * * Check the validity of LSF and fix found errors (vector) * * @param lsf vector */ void LSF_fix_vector(gsl_vector *lsf) { int i,ok = 0; double mean; int flag_neg = 0; int flag_zero = 0; int flag_pi = 0; int flag_piplus = 0; int flag_nan = 0; int flag_dec = 0; int flag_close = 0; /* Repeat until LSF is fixed */ while(ok == 0) { /* Set ok */ ok = 1; /* Check and correct values less than zero or greater than pi */ for(i=0;i<lsf->size;i++) { if(gsl_vector_get(lsf,i) < 0) { gsl_vector_set(lsf,i,LSF_EPSILON); flag_neg++; ok = 0; } else if(gsl_vector_get(lsf,i) < LSF_EPSILON) { gsl_vector_set(lsf,i,LSF_EPSILON); flag_zero++; ok = 0; } else if(gsl_vector_get(lsf,i) > M_PI) { gsl_vector_set(lsf,i,M_PI-LSF_EPSILON); flag_piplus++; ok = 0; } else if(gsl_vector_get(lsf,i) > M_PI-LSF_EPSILON) { gsl_vector_set(lsf,i,M_PI-LSF_EPSILON); flag_pi++; ok = 0; } if(gsl_isnan(gsl_vector_get(lsf,i))) { if(i == 0) gsl_vector_set(lsf,i,LSF_EPSILON); else if(i == lsf->size-1) gsl_vector_set(lsf,i,M_PI-LSF_EPSILON); else gsl_vector_set(lsf,i,(gsl_vector_get(lsf,i-1)+gsl_vector_get(lsf,i+1))/2.0); flag_nan++; ok = 0; } } /* Check and correct non-increasing values or coefficients too close */ for(i=0;i<lsf->size-1;i++) { if(gsl_vector_get(lsf,i) > gsl_vector_get(lsf,i+1)) { mean = (gsl_vector_get(lsf,i)+gsl_vector_get(lsf,i+1))/2.0; gsl_vector_set(lsf,i,mean - LSF_EPSILON/2.0); gsl_vector_set(lsf,i+1,mean + LSF_EPSILON/2.0); flag_dec++; ok = 0; } else if(gsl_vector_get(lsf,i) > gsl_vector_get(lsf,i+1)-LSF_EPSILON/10.0) { mean = (gsl_vector_get(lsf,i)+gsl_vector_get(lsf,i+1))/2.0; gsl_vector_set(lsf,i,mean - LSF_EPSILON/2.0); gsl_vector_set(lsf,i+1,mean + LSF_EPSILON/2.0); flag_close++; ok = 0; } } } /* Report */ if(flag_dec > 0) printf("Warning: %i decreasing LSFs -> Fixed!\n",flag_dec); if(flag_neg > 0) printf("Warning: %i negative LSFs -> Fixed!\n",flag_neg); if(flag_piplus > 0) printf("Warning: %i LSFs greater than Pi -> Fixed!\n",flag_piplus); if(flag_zero > 0) printf("Warning: %i LSFs too close to 0 -> Fixed!\n",flag_zero); if(flag_piplus > 0) printf("Warning: %i LSFs greater than Pi -> Fixed!\n",flag_pi); if(flag_close > 0) printf("Warning: %i LSFs too close to each other -> Fixed!\n",flag_close); if(flag_nan > 0) printf("Warning: %i NaN LSF value(s) -> Fixed!\n",flag_nan); } /** * Function LSF_fix_matrix * * Check the validity of LSF and fix found errors * * @param lsf matrix */ void LSF_fix_matrix(gsl_matrix *lsf) { int n,i,ok = 0; double mean; int flag_neg = 0; int flag_zero = 0; int flag_pi = 0; int flag_piplus = 0; int flag_nan = 0; int flag_dec = 0; int flag_close = 0; /* Repeat until LSF is fixed */ while(ok == 0) { /* Set ok */ ok = 1; /* Check and correct values less than zero or greater than pi */ for(n=0;n<lsf->size1;n++) { for(i=0;i<lsf->size2;i++) { if(gsl_matrix_get(lsf,n,i) < 0) { gsl_matrix_set(lsf,n,i,LSF_EPSILON); flag_neg++; ok = 0; } else if(gsl_matrix_get(lsf,n,i) < LSF_EPSILON) { gsl_matrix_set(lsf,n,i,LSF_EPSILON); flag_zero++; ok = 0; } else if(gsl_matrix_get(lsf,n,i) > M_PI) { gsl_matrix_set(lsf,n,i,M_PI-LSF_EPSILON); flag_piplus++; ok = 0; } else if(gsl_matrix_get(lsf,n,i) > M_PI-LSF_EPSILON) { gsl_matrix_set(lsf,n,i,M_PI-LSF_EPSILON); flag_pi++; ok = 0; } if(gsl_isnan(gsl_matrix_get(lsf,n,i))) { if(i == 0) gsl_matrix_set(lsf,n,i,LSF_EPSILON); else if(i == lsf->size2-1) gsl_matrix_set(lsf,n,i,M_PI-LSF_EPSILON); else gsl_matrix_set(lsf,n,i,(gsl_matrix_get(lsf,n,i-1)+gsl_matrix_get(lsf,n,i+1))/2.0); flag_nan++; ok = 0; } } /* Check and correct non-increasing values or coefficients too close */ for(i=0;i<lsf->size2-1;i++) { if(gsl_matrix_get(lsf,n,i) > gsl_matrix_get(lsf,n,i+1)) { mean = (gsl_matrix_get(lsf,n,i)+gsl_matrix_get(lsf,n,i+1))/2.0; gsl_matrix_set(lsf,n,i,mean - LSF_EPSILON/2.0); gsl_matrix_set(lsf,n,i+1,mean + LSF_EPSILON/2.0); flag_dec++; ok = 0; } else if(gsl_matrix_get(lsf,n,i) > gsl_matrix_get(lsf,n,i+1)-LSF_EPSILON/10.0) { mean = (gsl_matrix_get(lsf,n,i)+gsl_matrix_get(lsf,n,i+1))/2.0; gsl_matrix_set(lsf,n,i,mean - LSF_EPSILON/2.0); gsl_matrix_set(lsf,n,i+1,mean + LSF_EPSILON/2.0); flag_close++; ok = 0; } } } } /* Report */ if(flag_dec > 0) printf("Warning: %i decreasing LSFs -> Fixed!\n",flag_dec); if(flag_neg > 0) printf("Warning: %i negative LSFs -> Fixed!\n",flag_neg); if(flag_piplus > 0) printf("Warning: %i LSFs greater than Pi -> Fixed!\n",flag_piplus); if(flag_zero > 0) printf("Warning: %i LSFs too close to 0 -> Fixed!\n",flag_zero); if(flag_pi > 0) printf("Warning: %i LSFs too close to Pi -> Fixed!\n",flag_pi); if(flag_close > 0) printf("Warning: %i LSFs too close to each other -> Fixed!\n",flag_close); if(flag_nan > 0) printf("Warning: %i NaN LSF value(s) -> Fixed!\n",flag_nan); } /** * Function Merge_voiced_unvoiced_spectra * * Merge voiced and unvoiced spectra, i.e., replace unvoiced spectrum of LSF with LSF2 if two spectra is used * * @param LSF * @param LSF2 * @param params */ void Merge_voiced_unvoiced_spectra(gsl_matrix *LSF, gsl_matrix *LSF2, gsl_vector *fundf, PARAM *params) { int i,j; if(params->sep_vuv_spectrum == 1) for(i=0; i<params->n_frames; i++) if(gsl_vector_get(fundf, i) == 0) for(j=0; j<LSF->size2; j++) gsl_matrix_set(LSF, i, j, gsl_matrix_get(LSF2, i, j)); } /** * Function Integrate_LSFs * * Integrate line spectral frequency (LSF) based parameters if differential LSFs are used. * First raise to the power of 2, integrate, scale according to the distance to PI. * * @param LSF * @param LSF2 * @param params */ void Integrate_LSFs(gsl_matrix **LSFd, PARAM *params) { if(params->differential_lsf == 0) return; /* Initialize */ int i,k; double len_orig,len_new,c; gsl_matrix *LSF = gsl_matrix_calloc((*LSFd)->size1,(*LSFd)->size2-1); /* Remove sqrt */ for(i=0;i<LSF->size1;i++) { for(k=0;k<LSF->size2;k++) gsl_matrix_set(*LSFd,i,k,pow(gsl_matrix_get(*LSFd,i,k),2)); /* Set initial LSF */ gsl_matrix_set(LSF,i,0,gsl_matrix_get(*LSFd,i,0)); } /* Integrate */ for(i=0;i<LSF->size1;i++) for(k=1;k<LSF->size2;k++) gsl_matrix_set(LSF,i,k,gsl_matrix_get(*LSFd,i,k) + gsl_matrix_get(LSF,i,k-1)); /* Scale LSFs according to the last coefficient so that the distance to PI matches */ for(i=0;i<LSF->size1;i++) { len_orig = M_PI - pow(gsl_matrix_get(*LSFd,i,(*LSFd)->size2-1),2); len_new = gsl_matrix_get(LSF,i,LSF->size2-1); c = len_orig/len_new; for(k=0;k<LSF->size2;k++) gsl_matrix_set(LSF,i,k,gsl_matrix_get(LSF,i,k)*c); } /* Free old matrix */ gsl_matrix_free(*(LSFd)); /* Set pointer to new matrix */ *(LSFd) = LSF; } /** * Function Noise_robust_speech1 * * Modification for noise robust speech synthesis (1st stage) * * @param pulse_clus_id pointer to pulse cluster ids * @param pulse_clusters pointer to pulse clusters * @param params paramteres structure * @param synfilenumber * @return */ void Noise_robust_speech1(PARAM *params) { if(params->noise_robust_speech == 0) return; /* Modifications */ params->hpfiltf0 = 1; params->postfilter_alpha = 0.15; // 0<c<1, 1:OFF params->compcoeff = 0.2; // 0<c<1, 1:OFF /* Pitch and speed */ params->pitch = 1.4; params->speed = 0.8; } /** * Function Noise_robust_speech2 * * Modification for noise robust speech synthesis (2nd stage) * * @param pulse_clus_id pointer to pulse cluster ids * @param pulse_clusters pointer to pulse clusters * @param params paramteres structure * @param synfilenumber * @return */ void Noise_robust_speech2(gsl_vector *gain, gsl_matrix *harmonics, PARAM *params) { if(params->noise_robust_speech == 0) return; /* Modify harmonics */ if(params->use_harmonics == 1) Modify_harmonics(harmonics,0.5); // 0<c<1, 1:OFF else { params->pulse_tilt_decrease_coeff = 0.5; // 0<c<1, 1:OFF params->use_harmonic_modification = 1; } /* Compression of gain */ if(params->use_pulselib == 1) { int i; double compression = 0.99; // The lower the number, the more compression will take effect double addition = 9; // dB, rises the baseline gain double mingain = gsl_vector_min(gain); for(i=0;i<gain->size;i++) gsl_vector_set(gain,i,pow(gsl_vector_get(gain,i) - mingain, compression) + addition + mingain); } } /** * Function CreateExcitation * * Creates excitation... * * @param ... * */ void CreateExcitation(PARAM *params,gsl_vector *excitation_voiced,gsl_vector *excitation_unvoiced,gsl_vector *fundf,gsl_vector *gain, gsl_matrix *lsf,gsl_matrix *glflowsp,gsl_matrix *hnr,gsl_matrix *harmonics,gsl_matrix *waveform,gsl_vector *h1h2, gsl_vector *naq,gsl_vector *original_pulse,gsl_matrix *pulses,gsl_matrix *pulses_rs,gsl_vector *pulse_lengths, gsl_vector *pgain,gsl_matrix *plsf,gsl_matrix *ptilt,gsl_matrix *phnr,gsl_matrix *pharm,gsl_matrix *pwaveform, gsl_vector *ph1h2, gsl_vector *pnaq,gsl_vector *resynthesis_pulse_index,gsl_vector *pulse_clus_id, gsl_matrix *pulse_clusters,gsl_vector *oldgain,gsl_matrix *glflowsp_new,gsl_matrix *hnr_new, gsl_vector *pca_mean, gsl_matrix *pca_pc, gsl_matrix *pca_w, gsl_matrix *pca_w_lib, gsl_vector *stoch_env, gsl_vector *stoch_sp, gsl_matrix **DNN_W, gsl_vector **input_minmax, gsl_vector *dnnpulseindices, gsl_vector *dnnpulses) { /* Clear parameters (if resynth) */ gsl_vector_set_zero(excitation_voiced); gsl_vector_set_zero(excitation_unvoiced); gsl_matrix_set_zero(glflowsp_new); /* Allocate memory */ int sample_index = 0,frame_index_old = 0; int frame_index_center,frame_index,i,j,N,NN,pulseind = 0; double ngain_uv,gain_v,sum,sum_d,modg; int end_flag = 0; gsl_vector *noise; gsl_vector *pulse_train; gsl_vector *inds = gsl_vector_alloc(params->n_pulsecandidates); gsl_vector *inds_next = gsl_vector_alloc(params->n_pulsecandidates); gsl_vector *eparam = gsl_vector_alloc(params->n_pulsecandidates); gsl_vector *eparam_next = gsl_vector_alloc(params->n_pulsecandidates); gsl_vector *epulse = gsl_vector_alloc(params->n_pulsecandidates); gsl_vector *efinal = gsl_vector_alloc(params->n_pulsecandidates); gsl_vector *prevpulse = gsl_vector_alloc(params->rspulsemaxlen); /* Modulation */ int mod_pulse_index = 0; double mod_pulse_gain = 0.0; /* DNN */ int dnnpind = 0; int dnnpulseind = 0; /***********************************************************/ /* Create excitation: loop until signal length is reached */ /***********************************************************/ while(sample_index < params->signal_length) { /* Define current time index */ frame_index = floor(params->n_frames*(sample_index/(double)params->signal_length)); if(frame_index > params->n_frames-1) {frame_index = params->n_frames-1;} /****************************************************/ /* 1. Segment is voiced */ /****************************************************/ if(gsl_vector_get(fundf,frame_index) != 0) { /****************************************************/ /* Interpolate one pulse (original implementation) */ /****************************************************/ if(params->use_pulselib == 0 && params->use_pulselib_pca == 0 && params->use_dnn_pulsegen == 0) { /* Interpolate the original pulse according to T0 (N), use cubic spline interpolation */ N = rint(params->FS/gsl_vector_get(fundf,frame_index)/params->pitch); gsl_vector *pulse; if(params->two_pitch_period_diff_pulse == 0) pulse = gsl_vector_calloc(N); else pulse = gsl_vector_calloc(2*N); Interpolate(original_pulse,pulse); /* Create synthetic pulse train */ if(params->two_pitch_period_diff_pulse == 0) pulse_train = Create_pulse_train(pulse,original_pulse,hnr,fundf,harmonics,frame_index,sample_index,params); else { pulse_train = Create_pulse_train_diff(pulse,original_pulse,hnr,fundf,harmonics,frame_index,sample_index,params); Integrate(pulse_train,LEAK); } /* Re-estimate HNR */ if(params->hnr_reestimated == 0) { Upper_lower_envelope(pulse_train, hnr_new, gsl_vector_get(fundf,frame_index), frame_index, params); FillHNRValues(hnr_new,frame_index_old,frame_index); frame_index_old = frame_index; gsl_vector_free(pulse_train); } else { /* Add noise and analyse pulse train spectrum */ if(params->two_pitch_period_diff_pulse == 1) Integrate(pulse,LEAK); Phase_manipulation(pulse,hnr,harmonics,frame_index,params); if(params->two_pitch_period_diff_pulse == 1) { Differentiate(pulse,LEAK); gsl_vector_set(pulse,0,0); // Fix DC error } Analyse_pulse_train_spectrum(pulse_train,glflowsp_new,N,sample_index,frame_index,params); frame_index_old = frame_index; gsl_vector_free(pulse_train); } /* Add jitter */ int N_orig = N; if(params->jitter > 0) { N = N + rint(RAND()*N*params->jitter); gsl_vector *pulse_jitter; if(params->two_pitch_period_diff_pulse == 0) pulse_jitter = gsl_vector_alloc(N); else pulse_jitter = gsl_vector_alloc(2*N); Interpolate(pulse,pulse_jitter); gsl_vector_free(pulse); pulse = pulse_jitter; } /* Truncate pulse for unvoiced sections */ if(params->two_pitch_period_diff_pulse == 0) { pulse = Truncate_pulse(pulse,fundf,sample_index,frame_index,params); N_orig = pulse->size; N = pulse->size; } /* Prevent going over signal length */ if(params->two_pitch_period_diff_pulse == 0) { if(sample_index+N > params->signal_length) { gsl_vector_free(pulse); break; } } /* Normalize gain according to one pitch period */ if(params->two_pitch_period_diff_pulse == 0) { gsl_vector *pulse_d = gsl_vector_alloc(pulse->size); gsl_vector_memcpy(pulse_d,pulse); LipRadiation(pulse_d); sum_d = 0; for(i=0;i<N;i++) sum_d = sum_d + gsl_vector_get(pulse_d,i)*gsl_vector_get(pulse_d,i); gsl_vector_free(pulse_d); } else { sum = 0; for(j=0;j<pulse->size;j++) sum = sum + gsl_vector_get(pulse,j)*gsl_vector_get(pulse,j); } /* Evaluate gain */ if(params->two_pitch_period_diff_pulse == 0) { frame_index_center = GSL_MIN(floor(params->n_frames*((sample_index + 0.5*N_orig)/(double)params->signal_length)),params->n_frames-1); gain_v = sqrt(N*E_REF*powf(10.0,gsl_vector_get(gain,frame_index_center)/10.0)/sum_d); } else gain_v = sqrt(pulse->size*E_REF*powf(10.0,gsl_vector_get(gain,frame_index)/10.0)/(sum/0.375)); /* Modulation */ modg = 1 + sin(M_PI*mod_pulse_index/2.0)*mod_pulse_gain; gain_v = modg*gain_v; mod_pulse_index++; /* Set pulse to excitation */ if(params->two_pitch_period_diff_pulse == 0) { for(i=0;i<N;i++) gsl_vector_set(excitation_voiced, sample_index+i, gain_v*(gsl_vector_get(pulse,i) - gsl_vector_get(pulse,0))); } else { for(j=0;j<pulse->size;j++) { gsl_vector_set(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(pulse->size/2),0),excitation_voiced->size-1), gsl_vector_get(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(pulse->size/2),0),excitation_voiced->size-1)) + gain_v*gsl_vector_get(pulse,j)); } } /* Free memory */ gsl_vector_free(pulse); /* Increment sample index */ sample_index += N_orig; } else if(params->use_pulselib_pca == 0 && params->use_dnn_pulsegen == 0) { /*******************************************/ /* Use voice source unit selection */ /*******************************************/ /* Get the length of voiced section in frames and pulses */ int cur_frame_index = frame_index; int cur_sample_index = sample_index; int n_pulses_in_section = 0; double mf0 = 0; while(1) { if(cur_frame_index > params->n_frames-1) { end_flag = 1; break; } n_pulses_in_section++; mf0 += gsl_vector_get(fundf,cur_frame_index); N = rint(params->FS/gsl_vector_get(fundf,cur_frame_index)/params->pitch); cur_frame_index = floor(params->n_frames*((cur_sample_index+N)/(double)params->signal_length)); cur_sample_index += N; if(cur_frame_index > params->n_frames-1) { end_flag = 1; break; } if(gsl_vector_get(fundf,cur_frame_index) == 0 || gsl_vector_get(fundf,GSL_MIN(floor(params->n_frames*((cur_sample_index + rint(0.5*params->FS/gsl_vector_get(fundf,cur_frame_index)/params->pitch))/(double)params->signal_length)),params->n_frames-1)) == 0) break; } /* Evaluate mean f0 for the voiced section */ mf0 = mf0/(double)n_pulses_in_section; /* Variables for Viterbi */ gsl_matrix *v_trellis; gsl_matrix *v_indices; gsl_vector *final_pulses = gsl_vector_alloc(n_pulses_in_section); /* If pulse indices not known */ if(params->resynth == 0) { /* Print number of pulses in voiced section */ //printf(" Voiced section: %i pulse(s)\n",n_pulses_in_section); /* Allocate lattices for viterbi */ v_trellis = gsl_matrix_alloc(n_pulses_in_section, params->n_pulsecandidates+1); // Onko oikein +1? v_indices = gsl_matrix_alloc(n_pulses_in_section, params->n_pulsecandidates+1); gsl_matrix_set_all(v_trellis, BIGGER_POS_NUMBER); gsl_matrix_set_all(v_indices, 1); /* Populate targets according to lowest target error */ cur_frame_index = frame_index; cur_sample_index = sample_index; for(i=0;i<n_pulses_in_section;i++) { gsl_vector_view inds = gsl_matrix_row(v_indices,i); gsl_vector_view eparam = gsl_matrix_row(v_trellis,i); Evaluate_target_error(lsf,glflowsp,harmonics,hnr,waveform,h1h2,naq,oldgain,fundf,plsf,ptilt,pharm,phnr,pwaveform,ph1h2,pnaq, pgain,pca_w,pca_w_lib,pulse_lengths,cur_frame_index,&inds.vector,&eparam.vector,pulse_clus_id,pulse_clusters,params); N = rint(params->FS/gsl_vector_get(fundf,cur_frame_index)/params->pitch); cur_frame_index = floor(params->n_frames*((cur_sample_index+N)/(double)params->signal_length)); cur_sample_index += N; } if(n_pulses_in_section > 1) { /* Viterbi, forward */ /* Cumulative score */ gsl_matrix *v_scores = gsl_matrix_alloc(n_pulses_in_section, params->n_pulsecandidates+1); gsl_matrix_set_all(v_scores, BIGGER_POS_NUMBER); /* Best node indices leading to each node */ gsl_matrix *v_best = gsl_matrix_alloc(n_pulses_in_section, params->n_pulsecandidates+1); gsl_matrix_set_all(v_best, -1); /* Evaluate concatenation error */ cur_frame_index = frame_index; cur_sample_index = sample_index; int dist_to_unvoiced; double additional_cost; for(i=0;i<n_pulses_in_section-1;i++) { gsl_vector_view inds = gsl_matrix_row(v_indices,i); gsl_vector_view inds_next = gsl_matrix_row(v_indices,i+1); gsl_vector_view eparam = gsl_matrix_row(v_trellis,i); gsl_vector_view eparam_next = gsl_matrix_row(v_trellis,i+1); /* Define distance to unvoiced */ dist_to_unvoiced = i+1; /* Define additional cost (consisting of HNR and F0) */ if(params->use_hnr == 1) { additional_cost = 0; for(j=0;j<hnr->size2;j++) additional_cost += 1.0-pow(10,gsl_matrix_get(hnr,cur_frame_index,j)/20.0); additional_cost = powf(additional_cost/hnr->size2,3.0); } else additional_cost = 1; additional_cost *= gsl_vector_get(fundf, frame_index)/120.0; // Add cost if high f0 (many concatenation points) /* Evaluate concatenation cost */ Evaluate_concatenation_error_viterbi(&eparam.vector,&eparam_next.vector,&inds.vector,&inds_next.vector, pulses_rs, v_scores, v_best, i, dist_to_unvoiced, additional_cost, params); N = rint(params->FS/gsl_vector_get(fundf,cur_frame_index)/params->pitch); cur_frame_index = floor(params->n_frames*((cur_sample_index+N)/(double)params->signal_length)); cur_sample_index += N; } /* Viterbi, get best path by backtracking */ double best_sc = BIGGER_POS_NUMBER; int best_i = -1; for(i=0;i<params->n_pulsecandidates;i++) { if(gsl_matrix_get(v_scores,n_pulses_in_section-1, i) < best_sc) { best_sc = gsl_matrix_get(v_scores, n_pulses_in_section-1,i); best_i = i; } } gsl_vector_set(final_pulses, n_pulses_in_section-1, gsl_matrix_get(v_indices, n_pulses_in_section-1, best_i)); for(i=n_pulses_in_section-2;i>= 0;i--) { gsl_vector_set(final_pulses, i, gsl_matrix_get(v_indices, i+1, best_i)); best_i = (int)gsl_matrix_get(v_best, i+1,best_i); } /* Free viterbi structures */ gsl_matrix_free(v_best); gsl_matrix_free(v_scores); } else { /* Only one pulse in section */ gsl_vector_set(final_pulses,0,gsl_matrix_get(v_indices,0,i)); // TODO: Should be best_i(i) ? } /* Free viterbi structures */ gsl_matrix_free(v_trellis); gsl_matrix_free(v_indices); } /* After this, same for resynthesis */ /* Make pulse train */ double prev_f0 = 0.0; for(i=0;i<=n_pulses_in_section-1;i++) { /* Define pulse index */ if(params->resynth == 0) { pulseind = (int)gsl_vector_get(final_pulses, i); gsl_vector_set(resynthesis_pulse_index,frame_index,gsl_vector_get(final_pulses,i)); } else { pulseind = gsl_vector_get(resynthesis_pulse_index, frame_index); } /* Print pulse index */ //if(params->resynth == 0) // printf("%i\n",pulseind); /* Get pulse length and f0 shift */ double f0 = gsl_vector_get(fundf,frame_index); if(f0 == 0) f0 = prev_f0; if(f0 == 0) f0 = mf0; N = rint(params->FS/f0/params->pitch); NN = gsl_vector_get(pulse_lengths,pulseind); /* Get pulse to vector */ gsl_vector *pulse; if(params->pulse_interpolation == 0) { if(sample_index+rint(NN/2) > params->signal_length) break; pulse = gsl_vector_alloc(NN); for(j=0;j<NN;j++) gsl_vector_set(pulse,j,gsl_matrix_get(pulses,pulseind,j)); } else { if(sample_index+N > params->signal_length) break; gsl_vector *pulse_orig = gsl_vector_calloc(NN); pulse = gsl_vector_calloc(2*N); for(j=0;j<NN;j++) gsl_vector_set(pulse_orig,j,gsl_matrix_get(pulses,pulseind,j)); Interpolate(pulse_orig,pulse); gsl_vector_free(pulse_orig); NN = 2*N; } /* Average pulses */ Average_pulses(pulse, fundf, resynthesis_pulse_index, pulses, pulse_lengths, frame_index, params); /* Add jitter */ if(params->jitter > 0) { NN = pulse->size + rint(RAND()*2*N*params->jitter); gsl_vector *pulse_jitter = gsl_vector_alloc(NN); Interpolate(pulse,pulse_jitter); gsl_vector_free(pulse); pulse = pulse_jitter; } /* Phase manipulation of the library pulse */ if(params->add_noise_pulselib == 1 && params->resynth == 1) { Integrate(pulse, LEAK); Phase_manipulation(pulse,hnr,harmonics,frame_index,params); Differentiate(pulse,LEAK); gsl_vector_set(pulse,0,0); // Fix DC error } /* Evaluate gain */ sum = 0; for(j=0;j<NN;j++) sum = sum + gsl_vector_get(pulse,j)*gsl_vector_get(pulse,j); gain_v = sqrt(NN*E_REF*powf(10.0,gsl_vector_get(gain,frame_index)/10.0)/(sum/0.375)); /* Modulation */ modg = 1 + sin(M_PI*mod_pulse_index/2.0)*mod_pulse_gain; gain_v = modg*gain_v; mod_pulse_index++; /* Set pulse to excitation (OLA) */ for(j=0;j<NN;j++) { gsl_vector_set(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(NN/2),0),excitation_voiced->size-1), gsl_vector_get(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(NN/2),0),excitation_voiced->size-1)) + gain_v*gsl_vector_get(pulse,j)); } gsl_vector_free(pulse); /* Go directly to the beginning of unvoiced segent if pulse exceeds the boundary */ int frame_index_tmp = frame_index; int next_unvoiced_sample = sample_index; while(gsl_vector_get(fundf,frame_index_tmp) > 0) { frame_index_tmp = floor(params->n_frames*((next_unvoiced_sample)/(double)params->signal_length)); next_unvoiced_sample++; } N = GSL_MIN(N, next_unvoiced_sample-sample_index); /* Previous F0, increment sample index */ prev_f0 = gsl_vector_get(fundf, frame_index); sample_index += N; frame_index = floor(params->n_frames*((sample_index)/(double)params->signal_length)); } /* Free memory */ gsl_vector_free(final_pulses); /* Stop in the end */ if(end_flag == 1) break; } /****************************************/ /* Construct pulses from PCA parameters */ /****************************************/ else if(params->use_pulselib_pca == 1 && params->use_dnn_pulsegen == 0) { /* Allocate PCA pulse */ gsl_vector *pca_pulse = gsl_vector_calloc(params->pca_pulse_length); /* Define pulse from PC and weights */ if(params->pca_order_synthesis < 0 || params->pca_order_synthesis > params->pca_order) { printf("PCA_ORDER_SYNTHESIS must be between 0 and PCA_ORDER. PCA_ORDER_SYNTHESIS set to PCA_ORDER.\n"); params->pca_order_synthesis = params->pca_order; } for(i=0;i<params->pca_order_synthesis;i++) for(j=0;j<params->pca_pulse_length;j++) gsl_vector_set(pca_pulse,j,gsl_vector_get(pca_pulse,j) + gsl_matrix_get(pca_w,frame_index,i)*gsl_matrix_get(pca_pc,j,i)); /* Add mean */ for(i=0;i<params->pca_pulse_length;i++) gsl_vector_set(pca_pulse,i,gsl_vector_get(pca_pulse,i) + gsl_vector_get(pca_mean,i)); /* Define pulse length, add jitter */ N = rint(params->FS/gsl_vector_get(fundf,frame_index)/params->pitch); NN = 2*N; if(params->jitter > 0) NN = rint(NN*(1.0 + RAND()*params->jitter)); if(sample_index+NN/2.0 > params->signal_length) { gsl_vector_free(pca_pulse); break; } /* Allocate and interpolate pulse */ gsl_vector *pulse = gsl_vector_alloc(NN); Interpolate(pca_pulse,pulse); /* Add noise */ Integrate(pulse,LEAK); Phase_manipulation(pulse,hnr,harmonics,frame_index,params); Differentiate(pulse,LEAK); gsl_vector_set(pulse,0,0); // Fix DC error /* Create synthetic pulse train, analyse pulse train spectrum */ pulse_train = Create_pulse_train_diff(pulse,pca_pulse,hnr,fundf,harmonics,frame_index,sample_index,params); Integrate(pulse_train,LEAK); Analyse_pulse_train_spectrum(pulse_train,glflowsp_new,N,sample_index,frame_index,params); frame_index_old = frame_index; gsl_vector_free(pulse_train); /* Evaluate gain */ sum = 0; for(j=0;j<NN;j++) sum = sum + gsl_vector_get(pulse,j)*gsl_vector_get(pulse,j); gain_v = sqrt(NN*E_REF*powf(10.0,gsl_vector_get(gain,frame_index)/10.0)/(sum/0.375)); /* Modulation (NOT USED) */ modg = 1; gain_v = modg*gain_v; mod_pulse_index++; /* Set pulse to excitation (OLA) */ for(j=0;j<NN;j++) { gsl_vector_set(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(NN/2),0),excitation_voiced->size-1), gsl_vector_get(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(NN/2),0),excitation_voiced->size-1)) + gain_v*gsl_vector_get(pulse,j)); } /* Free memory */ gsl_vector_free(pulse); gsl_vector_free(pca_pulse); /* Increment sample index */ sample_index += N; } /****************************************/ /* DNN pulse generation */ /****************************************/ // LOWER FOR DNN-PCA (switch commenting) else if(params->use_pulselib_pca == 0 && params->use_dnn_pulsegen == 1) { //else if(params->use_pulselib_pca == 1 && params->use_dnn_pulsegen == 1) { /* Generate pulse from DNNs */ N = rint(params->FS/gsl_vector_get(fundf,frame_index)/params->pitch); gsl_vector *pulse = gsl_vector_calloc(2*N); /* If first synthesis, generate DNN pulse and search for closest library pulse (index) */ if(params->resynth == 0) { /* Generate DNN pulse */ /* FOR DNN-PCA, switch comments below and in Generate_excitation, set one switch as well */ Generate_DNN_pulse(pulse,fundf,gain,naq,h1h2,hnr,glflowsp,lsf,DNN_W,input_minmax,frame_index,params); //Generate_DNN_pulse_PCA(pulse,fundf,gain,naq,h1h2,hnr,glflowsp,lsf,DNN_W,pca_pc,frame_index,params); /* Select between using DNN pulse itself, or selecting a natural pulse from library */ if(params->use_dnn_pulselib_sel == 0) { /* Use DNN pulse and save it to memory */ for(i=0;i<pulse->size;i++) gsl_vector_set(dnnpulses,dnnpulseind+i,gsl_vector_get(pulse,i)); dnnpulseind += pulse->size; dnnpind++; } else { /* Select pulse from library, resample DNN pulse and normalize energy */ gsl_vector *dnn_pulse_rs = gsl_vector_alloc(pulses_rs->size2); Interpolate(pulse,dnn_pulse_rs); double e = 0; for(i=0;i<dnn_pulse_rs->size;i++) e += gsl_vector_get(dnn_pulse_rs,i)*gsl_vector_get(dnn_pulse_rs,i); e = sqrt(e); for(i=0;i<dnn_pulse_rs->size;i++) gsl_vector_set(dnn_pulse_rs,i,gsl_vector_get(dnn_pulse_rs,i)/e); /* Search for a best matching pulse from pulse library */ gsl_vector *error = gsl_vector_calloc(pulses_rs->size1); for(i=0;i<error->size;i++) for(j=0;j<dnn_pulse_rs->size;j++) gsl_vector_set(error,i,gsl_vector_get(error,i) + powf(gsl_matrix_get(pulses_rs,i,j) - gsl_vector_get(dnn_pulse_rs,j),2)); /* Save pulse index */ gsl_vector_set(dnnpulseindices,dnnpind,gsl_vector_min_index(error)); /* Free memory */ gsl_vector_free(error); gsl_vector_free(dnn_pulse_rs); } } else { /* Load DNN pulse from memory in resynthesis */ if(params->use_dnn_pulselib_sel == 0) { /* Load DNN pulse from memory */ for(i=0;i<pulse->size;i++) gsl_vector_set(pulse,i,gsl_vector_get(dnnpulses,dnnpulseind+i)); dnnpulseind += pulse->size; dnnpind++; } } /* If pulse selection is used, get pulse from library according to index */ if(params->use_dnn_pulselib_sel == 1) { gsl_vector *libpulse_orig = gsl_vector_alloc(gsl_vector_get(pulse_lengths,gsl_vector_get(dnnpulseindices,dnnpind))); for(i=0;i<libpulse_orig->size;i++) gsl_vector_set(libpulse_orig,i,gsl_matrix_get(pulses,gsl_vector_get(dnnpulseindices,dnnpind),i)); Interpolate(libpulse_orig,pulse); //if(params->resynth == 0) // printf("%i\n",(int)gsl_vector_get(dnnpulseindices,dnnpind)); gsl_vector_free(libpulse_orig); dnnpind++; } /* Evaluate voice source spectrum */ gsl_vector *tmp_pulse = gsl_vector_alloc(pulse->size); gsl_vector_memcpy(tmp_pulse,pulse); pulse_train = Create_pulse_train_diff(pulse,tmp_pulse,hnr,fundf,harmonics,frame_index,sample_index,params); Integrate(pulse_train,LEAK); gsl_vector_free(tmp_pulse); /* Re-estimate HNR */ if(params->hnr_reestimated == 0) { Upper_lower_envelope(pulse_train, hnr_new, gsl_vector_get(fundf,frame_index), frame_index, params); FillHNRValues(hnr_new,frame_index_old,frame_index); frame_index_old = frame_index; gsl_vector_free(pulse_train); } else { /* Add noise and analyse pulse train spectrum */ Integrate(pulse,LEAK); Phase_manipulation(pulse,hnr,harmonics,frame_index,params); Differentiate(pulse,LEAK); gsl_vector_set(pulse,0,0); // Fix DC error Analyse_pulse_train_spectrum(pulse_train,glflowsp_new,N,sample_index,frame_index,params); frame_index_old = frame_index; gsl_vector_free(pulse_train); } /* Evaluate gain */ sum = 0; for(j=0;j<pulse->size;j++) sum = sum + gsl_vector_get(pulse,j)*gsl_vector_get(pulse,j); gain_v = sqrt(pulse->size*E_REF*powf(10.0,gsl_vector_get(gain,frame_index)/10.0)/(sum/0.375)); /* Set pulse to excitation (OLA) */ for(j=0;j<pulse->size;j++) { gsl_vector_set(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(pulse->size/2),0),excitation_voiced->size-1), gsl_vector_get(excitation_voiced,GSL_MIN(GSL_MAX(sample_index+j-rint(pulse->size/2),0),excitation_voiced->size-1)) + gain_v*gsl_vector_get(pulse,j)); } /* Free memory */ gsl_vector_free(pulse); /* Increment sample index */ sample_index += N; } // End single pulse / source unit selection / PCA pulse / DNN pulsegen } else { /****************************************************/ /* 2. Segment is unvoiced */ /****************************************************/ /* Allocate noise vector */ if(sample_index + params->shift/params->speed < params->signal_length) noise = gsl_vector_alloc(params->shift/params->speed); else noise = gsl_vector_alloc(params->signal_length-sample_index); /* Create noise excitation */ double sum = 0; for(i=0;i<noise->size;i++) { gsl_vector_set(noise,i,RAND()); sum += gsl_vector_get(noise,i)*gsl_vector_get(noise,i); } /* Add noise to voiced excitation */ frame_index_center = GSL_MIN(floor(params->n_frames*((sample_index + 0.5*params->shift/params->speed)/(double)params->signal_length)),params->n_frames-1); ngain_uv = params->gain_unvoiced*sqrt(params->shift/params->speed*E_REF*powf(10.0,gsl_vector_get(gain,frame_index_center)/10.0)/sum); for(i=0;i<noise->size;i++) gsl_vector_set(excitation_unvoiced, sample_index+i, ngain_uv*gsl_vector_get(noise,i)); gsl_vector_free(noise); /* Set synthetic source spectrum the same as original when unvoiced (FLAT FOR TESTING) */ FillUnvoicedSyntheticSourceSpectrum(glflowsp,glflowsp_new,frame_index,frame_index_old); //FillUnvoicedSyntheticSourceSpectrum_FLAT(glflowsp,glflowsp_new,frame_index,frame_index_old); /* Update, increment sample index */ frame_index_old = frame_index; sample_index += rint(params->shift/params->speed); } } /* Free memory */ gsl_vector_free(prevpulse); gsl_vector_free(inds); gsl_vector_free(inds_next); gsl_vector_free(eparam); gsl_vector_free(eparam_next); gsl_vector_free(efinal); gsl_vector_free(epulse); } /** * Generate_DNN_pulse * * Generate glottal flow pulse from DNN through mapping of the synthesis parameters to the pulse waveform. * */ void Generate_DNN_pulse(gsl_vector *pulse, gsl_vector *fundf, gsl_vector *gain, gsl_vector *naq, gsl_vector *h1h2, gsl_matrix *hnr, gsl_matrix *glflowsp, gsl_matrix *lsf, gsl_matrix **DNN_W, gsl_vector **input_minmax, int index, PARAM *params) { /* Initialize */ int i,j,L,numlayers = params->dnn_weight_dims->size/2; /* Allocate memory */ gsl_vector *inputdata = gsl_vector_calloc(DNN_W[0]->size1); gsl_vector **WProbs = (gsl_vector**)malloc((numlayers-1)*sizeof(gsl_vector*)); for(i=0;i<numlayers-1;i++) WProbs[i] = gsl_vector_calloc(DNN_W[i]->size2+1); gsl_vector *pulse_tmp = gsl_vector_calloc(DNN_W[numlayers-1]->size2); /* Assign input data to vector [F0 Gain HNR LSFsource LSF (Bias)] */ /* Dimensions = [1 1 5 10 30 (1)] = 47 (+1) */ int NPAR = 47; int f,cur_index,stack = 0; int lim1 = -floor(params->dnn_number_of_stacked_frames/2.0); int lim2 = ceil(params->dnn_number_of_stacked_frames/2.0); for(f=lim1;f<lim2;f++) { /* Evaluate current frame */ cur_index = GSL_MIN(GSL_MAX(index+f,0),params->n_frames-1); /* Assign parameters */ gsl_vector_set(inputdata,0+stack*NPAR,gsl_vector_get(fundf,cur_index)); // F0 gsl_vector_set(inputdata,1+stack*NPAR,gsl_vector_get(gain,cur_index)); // Gain for(i=0;i<5;i++) gsl_vector_set(inputdata,2+stack*NPAR+i,gsl_matrix_get(hnr,cur_index,i)); // HNR for(i=0;i<10;i++) gsl_vector_set(inputdata,7+stack*NPAR+i,gsl_matrix_get(glflowsp,cur_index,i)); // LSFsource for(i=0;i<30;i++) gsl_vector_set(inputdata,17+stack*NPAR+i,gsl_matrix_get(lsf,cur_index,i)); // LSF /* Normalize input data to values between [0.1,0.9] (if done so in DNN training) */ /* data_norm = 0.1 + 0.8*(data - min)/(max - min); */ if(params->dnn_input_normalized == 1) { double min,max; for(i=0;i<NPAR;i++) { min = gsl_vector_get(input_minmax[0],i); max = gsl_vector_get(input_minmax[0],i+NPAR); gsl_vector_set(inputdata,i+stack*NPAR, 0.1 + 0.8*(gsl_vector_get(inputdata,i+stack*NPAR) - min)/(max-min)); } } /* Increment stack */ stack++; } /* Set the bias at the end of the vector */ gsl_vector_set(inputdata,inputdata->size-1,1); /* Evaluate WProbs[0] = 1./(1 + exp(-data*DNN_W[0])) (sigmoid layer) */ for(i=0;i<DNN_W[0]->size2;i++) { for(j=0;j<DNN_W[0]->size1;j++) gsl_vector_set(WProbs[0],i,gsl_vector_get(WProbs[0],i) + gsl_vector_get(inputdata,j)*gsl_matrix_get(DNN_W[0],j,i)); gsl_vector_set(WProbs[0],i,1.0/(1.0 + exp(-gsl_vector_get(WProbs[0],i)))); } gsl_vector_set(WProbs[0],WProbs[0]->size-1,1); // Set bias term /* Evaluate WPprobs[i] = 1./(1 + exp(-WProbs[i-1]*DNN_W[i])) (sigmoid layer) */ for(L=1;L<numlayers-1;L++) { for(i=0;i<DNN_W[L]->size2;i++) { for(j=0;j<DNN_W[L]->size1;j++) gsl_vector_set(WProbs[L],i,gsl_vector_get(WProbs[L],i) + gsl_vector_get(WProbs[L-1],j)*gsl_matrix_get(DNN_W[L],j,i)); gsl_vector_set(WProbs[L],i,1.0/(1.0 + exp(-gsl_vector_get(WProbs[L],i)))); } gsl_vector_set(WProbs[L],WProbs[L]->size-1,1); // Set bias term } /* Evaluate pulses = WProbs[end]*DNN_W[end] (linear layer) */ for(i=0;i<DNN_W[numlayers-1]->size2;i++) for(j=0;j<DNN_W[numlayers-1]->size1;j++) gsl_vector_set(pulse_tmp,i,gsl_vector_get(pulse_tmp,i) + gsl_vector_get(WProbs[numlayers-2],j)*gsl_matrix_get(DNN_W[numlayers-1],j,i)); /* Interpolate pulse to desired length */ Interpolate(pulse_tmp,pulse); /* Free memory */ gsl_vector_free(inputdata); for(i=0;i<numlayers-1;i++) gsl_vector_free(WProbs[i]); free(WProbs); gsl_vector_free(pulse_tmp); } /** * Generate_DNN_pulse_PCA * * Generate glottal flow pulse by mapping the synthesis parameters to the PC weights and then reconstructing the pulse through PC weights and PCs. * */ void Generate_DNN_pulse_PCA(gsl_vector *pulse, gsl_vector *fundf, gsl_vector *gain, gsl_vector *naq, gsl_vector *h1h2, gsl_matrix *hnr, gsl_matrix *glflowsp, gsl_matrix *lsf, gsl_matrix **DNN_W, gsl_vector **input_minmax, gsl_matrix *pca_pc, int index, PARAM *params) { /* Initialize */ int i,j,L,numlayers = params->dnn_weight_dims->size/2; /* Allocate memory */ gsl_vector *inputdata = gsl_vector_calloc(DNN_W[0]->size1); gsl_vector **WProbs = (gsl_vector**)malloc((numlayers-1)*sizeof(gsl_vector*)); for(i=0;i<numlayers-1;i++) WProbs[i] = gsl_vector_calloc(DNN_W[i]->size2+1); gsl_vector *pcw = gsl_vector_calloc(DNN_W[numlayers-1]->size2); /***** NORMAL *****/ /* Assign input data to vector [F0 Gain HNR LSFsource LSF Bias] */ /* Dimensions = [1 1 5 10 30 1] = 48 */ gsl_vector_set(inputdata,0,gsl_vector_get(fundf,index)); // F0 gsl_vector_set(inputdata,1,gsl_vector_get(gain,index)); // Gain for(i=0;i<5;i++) gsl_vector_set(inputdata,2+i,gsl_matrix_get(hnr,index,i)); // HNR for(i=0;i<10;i++) gsl_vector_set(inputdata,7+i,gsl_matrix_get(glflowsp,index,i)); // LSFsource for(i=0;i<30;i++) gsl_vector_set(inputdata,17+i,gsl_matrix_get(lsf,index,i)); // LSF gsl_vector_set(inputdata,47,1); // Bias /***** INCLUDING NAQ AND H1H2 *****/ /* Assign input data to vector [F0 Gain NAQ H1H2 HNR LSFsource LSF Bias] */ /* Dimensions = [1 1 1 1 5 10 30 1] = 50 gsl_vector_set(inputdata,0,gsl_vector_get(fundf,index)); // F0 gsl_vector_set(inputdata,1,gsl_vector_get(gain,index)); // Gain gsl_vector_set(inputdata,2,gsl_vector_get(naq,index)); // NAQ gsl_vector_set(inputdata,3,gsl_vector_get(h1h2,index)); // H1H2 for(i=0;i<5;i++) gsl_vector_set(inputdata,4+i,gsl_matrix_get(hnr,index,i)); // HNR for(i=0;i<10;i++) gsl_vector_set(inputdata,9+i,gsl_matrix_get(glflowsp,index,i)); // LSFsource for(i=0;i<30;i++) gsl_vector_set(inputdata,19+i,gsl_matrix_get(lsf,index,i)); // LSF gsl_vector_set(inputdata,49,1); // Bias */ /* Evaluate WProbs[0] = 1./(1 + exp(-data*DNN_W[0])) (sigmoid layer) */ for(i=0;i<DNN_W[0]->size2;i++) { for(j=0;j<DNN_W[0]->size1;j++) gsl_vector_set(WProbs[0],i,gsl_vector_get(WProbs[0],i) + gsl_vector_get(inputdata,j)*gsl_matrix_get(DNN_W[0],j,i)); gsl_vector_set(WProbs[0],i,1.0/(1.0 + exp(-gsl_vector_get(WProbs[0],i)))); } gsl_vector_set(WProbs[0],WProbs[0]->size-1,1); // Set bias term /* Evaluate WPprobs[i] = 1./(1 + exp(-WProbs[i-1]*DNN_W[i])) (sigmoid layer) */ for(L=1;L<numlayers-1;L++) { for(i=0;i<DNN_W[L]->size2;i++) { for(j=0;j<DNN_W[L]->size1;j++) gsl_vector_set(WProbs[L],i,gsl_vector_get(WProbs[L],i) + gsl_vector_get(WProbs[L-1],j)*gsl_matrix_get(DNN_W[L],j,i)); gsl_vector_set(WProbs[L],i,1.0/(1.0 + exp(-gsl_vector_get(WProbs[L],i)))); } gsl_vector_set(WProbs[L],WProbs[L]->size-1,1); // Set bias term } /* Evaluate pulses = WProbs[end]*DNN_W[end] (linear layer) */ for(i=0;i<DNN_W[numlayers-1]->size2;i++) for(j=0;j<DNN_W[numlayers-1]->size1;j++) gsl_vector_set(pcw,i,gsl_vector_get(pcw,i) + gsl_vector_get(WProbs[numlayers-2],j)*gsl_matrix_get(DNN_W[numlayers-1],j,i)); /* Allocate PCA pulse */ gsl_vector *pca_pulse = gsl_vector_calloc(params->pca_pulse_length); /* Define pulse from PC and weights */ if(params->pca_order_synthesis < 0 || params->pca_order_synthesis > params->pca_order) { printf("PCA_ORDER_SYNTHESIS must be between 0 and PCA_ORDER. PCA_ORDER_SYNTHESIS set to PCA_ORDER.\n"); params->pca_order_synthesis = params->pca_order; } for(i=0;i<params->pca_order_synthesis;i++) for(j=0;j<params->pca_pulse_length;j++) gsl_vector_set(pca_pulse,j,gsl_vector_get(pca_pulse,j) + gsl_vector_get(pcw,i)*gsl_matrix_get(pca_pc,j,i)); /* Interpolate pulse to desired length */ Interpolate(pca_pulse,pulse); /* Free memory */ gsl_vector_free(inputdata); for(i=0;i<numlayers-1;i++) gsl_vector_free(WProbs[i]); free(WProbs); gsl_vector_free(pcw); gsl_vector_free(pca_pulse); } /** * Shift_right_and_add * * Shift all the elements of the vector one index to the right, and add the new value in the beginning. * * @param vector * @param value */ void Shift_right_and_add(gsl_vector *vector, double value) { int i; for(i=vector->size-1;i>0;i--) gsl_vector_set(vector,i,gsl_vector_get(vector,i-1)); gsl_vector_set(vector,0,value); } /** * Truncate_pulse * * Truncate pulse for unvoiced regions * * @param pulse * @param fundf * @param sample_index * @param frame_index * @param params */ gsl_vector *Truncate_pulse(gsl_vector *pulse, gsl_vector *fundf, int sample_index, int frame_index, PARAM *params) { /* Initialize */ int sample_index_tmp,frame_index_tmp,i = 1,edit_flag = 0; int uvshift = rint(params->shift/params->speed); /* Find unvoiced */ while(i*uvshift < pulse->size) { sample_index_tmp = sample_index + i*uvshift; frame_index_tmp = floor(params->n_frames*(sample_index_tmp/(double)params->signal_length)); if(frame_index_tmp > fundf->size-1) break; if(gsl_vector_get(fundf,frame_index_tmp) == 0) { edit_flag = 1; break; } i = i + 1; } /* Truncate */ if(edit_flag == 1) { gsl_vector *pulse_short = gsl_vector_alloc(i*uvshift); for(i=0;i<pulse_short->size;i++) gsl_vector_set(pulse_short,i,gsl_vector_get(pulse,i)*HANN(pulse_short->size+i,2*pulse_short->size)); gsl_vector_free(pulse); pulse = pulse_short; } /* Return */ return pulse; } /** * Average_pulses * * Average adjacent pulses in time and quality * * @param ... */ void Average_pulses(gsl_vector *pulse, gsl_vector *fundf, gsl_vector *resynthesis_pulse_index, gsl_matrix *pulses, gsl_vector *pulse_lengths, int frame_index, PARAM *params) { /* Perform only in resynthesis */ if(params->resynth == 0) return; /* Sanity check, the number of pulses must be odd */ if(params->average_n_adjacent_pulses < 2) params->average_n_adjacent_pulses = 1; if(params->average_n_adjacent_pulses%2 == 0) params->average_n_adjacent_pulses++; /* Initialize */ int j,k,N = pulse->size; gsl_matrix *adjacent_pulses = gsl_matrix_alloc(params->average_n_adjacent_pulses,N); gsl_vector *pulse_N = gsl_vector_alloc(N); gsl_vector *pulse_temp; /* Fill pulse matrix with the original pulse */ Interpolate(pulse,pulse_N); for(j=0;j<params->average_n_adjacent_pulses;j++) for(k=0;k<N;k++) gsl_matrix_set(adjacent_pulses,j,k,gsl_vector_get(pulse_N,k)); /* Fill possible earlier pulses */ j = 1; int added_pulses = 0; while(frame_index-j >= 0 && gsl_vector_get(fundf,frame_index-j) > 0 && added_pulses != floor(params->average_n_adjacent_pulses/2)) { if(gsl_vector_get(resynthesis_pulse_index,frame_index-j) != 0) { int pulseind_back = gsl_vector_get(resynthesis_pulse_index,frame_index-j); int pulselen = gsl_vector_get(pulse_lengths,pulseind_back); pulse_temp = gsl_vector_alloc(pulselen); for(k=0;k<pulselen;k++) gsl_vector_set(pulse_temp,k,gsl_matrix_get(pulses,pulseind_back,k)); Interpolate(pulse_temp,pulse_N); gsl_vector_free(pulse_temp); for(k=0;k<N;k++) gsl_matrix_set(adjacent_pulses,floor(params->average_n_adjacent_pulses/2)-added_pulses-1,k,gsl_vector_get(pulse_N,k)); added_pulses++; } j++; } /* Fill possible latter pulses */ j = 1; added_pulses = 0; while(frame_index+j < params->n_frames && gsl_vector_get(fundf,frame_index+j) > 0 && added_pulses != floor(params->average_n_adjacent_pulses/2)) { if(gsl_vector_get(resynthesis_pulse_index,frame_index+j) != 0) { int pulseind_forward = gsl_vector_get(resynthesis_pulse_index,frame_index+j); int pulselen = gsl_vector_get(pulse_lengths,pulseind_forward); pulse_temp = gsl_vector_alloc(pulselen); for(k=0;k<pulselen;k++) gsl_vector_set(pulse_temp,k,gsl_matrix_get(pulses,pulseind_forward,k)); Interpolate(pulse_temp,pulse_N); gsl_vector_free(pulse_temp); for(k=0;k<N;k++) gsl_matrix_set(adjacent_pulses,floor(params->average_n_adjacent_pulses/2)+added_pulses+1,k,gsl_vector_get(pulse_N,k)); added_pulses++; } j++; } /* Average adjacent pulses to pulse */ gsl_vector_set_zero(pulse); for(k=0;k<N;k++) for(j=0;j<params->average_n_adjacent_pulses;j++) gsl_vector_set(pulse,k,gsl_vector_get(pulse,k) + gsl_matrix_get(adjacent_pulses,j,k)/params->average_n_adjacent_pulses); /* Free memory */ gsl_vector_free(pulse_N); gsl_matrix_free(adjacent_pulses); } /** * Function Fill_pulse_indices * * Fill pulse indices with 0 values with nearest pulsi indices * * @param ... */ void Fill_pulse_indices(gsl_vector *ind) { int i,k,k1,k2; /* Copy original vector */ gsl_vector *ind_new = gsl_vector_alloc(ind->size); gsl_vector_memcpy(ind_new,ind); /* Fill */ for(i=0;i<ind->size;i++) { if(gsl_vector_get(ind,i) == 0) { /* If gap is found, find the nearest non-zero value */ if(gsl_vector_get(ind,i) == 0) { k1 = i+1; while(k1 < ind->size-1 && gsl_vector_get(ind,k1) == 0) k1++; k2 = i-1; while(k2 > 0 && gsl_vector_get(ind,k2) == 0) k2--; if(fabs(k1-i) < fabs(k2-i)) { if(k1 < ind->size-1) k = k1; else k = k2; } else { if(k2 > 0) k = k2; else k = k1; } /* Sanity check */ if(k < 0 || k > ind->size-1) break; /* Fill the gap with the nearest found non-zero value */ gsl_vector_set(ind_new,i,gsl_vector_get(ind,k)); } } } /* Copy fixed vector to the original one and free memory */ gsl_vector_memcpy(ind,ind_new); gsl_vector_free(ind_new); } /** * Function Evaluate_target_error * * Evaluate error between target parameters and pulse parameters. * * @param ... */ void Evaluate_target_error(gsl_matrix *lsf, gsl_matrix *glflowsp, gsl_matrix *harmonics, gsl_matrix *hnr_i, gsl_matrix *waveform, gsl_vector *h1h2, gsl_vector *naq, gsl_vector *gain, gsl_vector *fundf, gsl_matrix *plsf, gsl_matrix *ptilt, gsl_matrix *pharm, gsl_matrix *phnr, gsl_matrix *pwaveform, gsl_vector *ph1h2, gsl_vector *pnaq, gsl_vector *pgain, gsl_matrix *pca_w, gsl_matrix *pca_w_lib, gsl_vector *pulse_lengths, int frame_index, gsl_vector *inds, gsl_vector *eparam, gsl_vector *pulse_clus_id, gsl_matrix *pulse_clusters, PARAM *params) { int i,j,k,use_clusters = 0,npulses = params->number_of_pulses; int n_pulsecandidates = params->n_pulsecandidates; int nparams = params->paramweights->size; double m,std; gsl_vector_view cur_pulses; gsl_vector *lsfw = gsl_vector_calloc(lsf->size2); gsl_vector *lsfsourcew = gsl_vector_calloc(glflowsp->size2); gsl_vector_set_all(eparam, BIGGER_POS_NUMBER); /* Use pulse clusters */ if(params->pulse_clustering == 1) { use_clusters = 1; cur_pulses = gsl_matrix_row(pulse_clusters, (int)(gsl_vector_get(pulse_clus_id, frame_index))); /* Get number of pulses in cluster (awkward) */ npulses = 0; for(i=0;i<(&cur_pulses.vector)->size;i++) { if((int)gsl_vector_get(&cur_pulses.vector, i) == -1) break; npulses++; } if(npulses == 0) { use_clusters = 0; npulses = params->number_of_pulses; } if(params->n_pulsecandidates > npulses){ n_pulsecandidates = npulses; } } /* Evaluate LSF weighting vector */ for(i=1;i<lsf->size2-1;i++) gsl_vector_set(lsfw,i,1.0/(gsl_matrix_get(lsf,frame_index,i)-gsl_matrix_get(lsf,frame_index,i-1)) + 1.0/(gsl_matrix_get(lsf,frame_index,i+1)-gsl_matrix_get(lsf,frame_index,i))); double mean = Mean(lsfw); gsl_vector_set(lsfw,0,mean); gsl_vector_set(lsfw,lsfw->size-1,mean); /* Evaluate source LSF weighting vector */ for(i=1;i<glflowsp->size2-1;i++) gsl_vector_set(lsfsourcew,i,1.0/(gsl_matrix_get(glflowsp,frame_index,i)-gsl_matrix_get(glflowsp,frame_index,i-1)) + 1.0/(gsl_matrix_get(glflowsp,frame_index,i+1)-gsl_matrix_get(glflowsp,frame_index,i))); mean = Mean(lsfsourcew); gsl_vector_set(lsfsourcew,0,gsl_vector_get(lsfsourcew,1)); gsl_vector_set(lsfsourcew,lsfsourcew->size-1,mean); /* Initialize */ gsl_matrix *error = gsl_matrix_calloc(npulses,nparams); gsl_vector *E = gsl_vector_calloc(npulses); gsl_permutation *p = gsl_permutation_alloc(E->size); /* FOR PULSE CLUSTERS! */ if(use_clusters == 1) { /* Evaluate absolute error of every parameter: 0: LSF, 1:tilt, 2:harm, 3:hnr, 4:gain, 5:f0, 6:waveform, 7: h1h2, 8: naq*/ for(k=0;k<npulses;k++){ i = (int)gsl_vector_get((&cur_pulses.vector), k); if(i == -1) break; /* LSF */ if(gsl_vector_get(params->paramweights,0) > 0) { for(j=0;j<plsf->size2;j++) gsl_matrix_set(error,k,0, gsl_matrix_get(error,k,0) + gsl_vector_get(lsfw,j)*powf(gsl_matrix_get(lsf,frame_index,j)-gsl_matrix_get(plsf,i,j),2)); gsl_matrix_set(error,k,0,sqrt(gsl_matrix_get(error,k,0))); } /* Tilt */ if(gsl_vector_get(params->paramweights,1) > 0 && params->use_tilt == 1) { for(j=0;j<ptilt->size2;j++) gsl_matrix_set(error,k,1, gsl_matrix_get(error,k,1) + gsl_vector_get(lsfsourcew,j)*powf(gsl_matrix_get(glflowsp,frame_index,j)-gsl_matrix_get(ptilt,i,j),2)); gsl_matrix_set(error,k,1,sqrt(gsl_matrix_get(error,k,1))); } /* Harmonics */ if(gsl_vector_get(params->paramweights,2) > 0 && params->use_harmonics == 1) { for(j=0;j<pharm->size2;j++) gsl_matrix_set(error,k,2, gsl_matrix_get(error,k,2) + powf(gsl_matrix_get(harmonics,frame_index,j)-gsl_matrix_get(pharm,i,j),2)); gsl_matrix_set(error,k,2,sqrt(gsl_matrix_get(error,k,2))); } /* HNR */ if(gsl_vector_get(params->paramweights,3) > 0 && params->use_hnr == 1) { for(j=0;j<phnr->size2;j++) gsl_matrix_set(error,k,3, gsl_matrix_get(error,k,3) + powf(gsl_matrix_get(hnr_i,frame_index,j)-gsl_matrix_get(phnr,i,j),2)); gsl_matrix_set(error,k,3,sqrt(gsl_matrix_get(error,k,3))); } /* Gain */ if(gsl_vector_get(params->paramweights,4) > 0) { gsl_matrix_set(error,k,4,fabs(gsl_vector_get(gain,frame_index)-gsl_vector_get(pgain,i))); } /* F0 */ if(gsl_vector_get(params->paramweights,5) > 0) { gsl_matrix_set(error,k,5,fabs(gsl_vector_get(fundf,frame_index)*params->pitch-2.0*params->FS/gsl_vector_get(pulse_lengths,i))); } /* Waveform */ if(gsl_vector_get(params->paramweights,6) > 0 && params->use_waveform == 1) { for(j=0;j<pwaveform->size2;j++) gsl_matrix_set(error,k,6, gsl_matrix_get(error,k,6) + powf(gsl_matrix_get(waveform,frame_index,j)-gsl_matrix_get(pwaveform,i,j),2)); gsl_matrix_set(error,k,6,sqrt(gsl_matrix_get(error,k,6))); } /* H1H2 */ if(gsl_vector_get(params->paramweights,7) > 0 && params->use_h1h2 == 1) { gsl_matrix_set(error,k,7,fabs(gsl_vector_get(h1h2,frame_index)-gsl_vector_get(ph1h2,i))); } /* NAQ */ if(gsl_vector_get(params->paramweights,8) > 0 && params->use_naq == 1) { gsl_matrix_set(error,k,8,fabs(gsl_vector_get(naq,frame_index)-gsl_vector_get(pnaq,i))); } /* PCA */ if(gsl_vector_get(params->paramweights,9) > 0 && params->use_pulselib_pca == 1) { for(j=0;j<pca_w->size2;j++) gsl_matrix_set(error,k,9, gsl_matrix_get(error,k,9) + powf(gsl_matrix_get(pca_w,frame_index,j)-gsl_matrix_get(pca_w_lib,i,j),2)); gsl_matrix_set(error,k,9,sqrt(gsl_matrix_get(error,k,9))); } } /* Normalize error of every parameter (subtract mean and divide by standard deviation) and weight */ for(i=0;i<nparams;i++) { if(gsl_vector_get(params->paramweights,i) > 0) { /* Evaluate mean of each error */ m = 0; for(j=0;j<npulses;j++) m += gsl_matrix_get(error,j,i); m = m/npulses; /* Evaluate standard deviation or each error */ std = 0; for(j=0;j<npulses;j++) std += (gsl_matrix_get(error,j,i)-m)*(gsl_matrix_get(error,j,i)-m); std = sqrt(std/(npulses-1)); if(std == 0) std = 1; /* Weight */ for(j=0;j<npulses;j++) gsl_matrix_set(error,j,i,(gsl_matrix_get(error,j,i)-m)/std*gsl_vector_get(params->paramweights, i)); } } /* Evaluate total error */ double min_err = BIG_POS_NUMBER; int min_i = 0; gsl_vector *avg_err = gsl_vector_alloc(nparams); gsl_vector_set_zero(avg_err); for(i=0;i<npulses;i++){ for(j=0;j<nparams;j++){ gsl_vector_set(E,i,gsl_vector_get(E,i) + gsl_matrix_get(error,i,j)); gsl_vector_set(avg_err, j, gsl_vector_get(avg_err, j) + gsl_matrix_get(error,i,j)); } if (gsl_vector_get(E,i) < min_err){ min_err = gsl_vector_get(E,i); min_i = i; } } gsl_vector_free(avg_err); gsl_sort_vector_index(p,E); for(i=0;i<n_pulsecandidates;i++) { gsl_vector_set(inds,i,gsl_permutation_get(p,i)); gsl_vector_set(eparam,i,gsl_vector_get(E,gsl_vector_get(inds,i))); gsl_vector_set(inds,i,(int)gsl_vector_get(&cur_pulses.vector,gsl_permutation_get(p,i))); } /* Add best candidates to cluster of next frame */ if(gsl_vector_get(pulse_clus_id, frame_index) != gsl_vector_get(pulse_clus_id, frame_index+1)) { if(npulses > 1000) npulses = 1000; for(i=0;i<n_pulsecandidates;i++) { gsl_matrix_set(pulse_clusters, (int)(gsl_vector_get(pulse_clus_id, frame_index+1)), npulses+i, gsl_vector_get(inds, i)); } } /* Sanity check */ int from_cluster = 0; for(i=0;i<(&cur_pulses.vector)->size;i++) { if(gsl_vector_get(&cur_pulses.vector, i) == gsl_vector_get(inds, 0)) from_cluster = 1; } } else { /* FOR NORMAL ERROR CALCULATION */ // TODO: SET LIMITS FOR EACH PARAMETER THAT PREVENT SELECTING A PULSE! // TODO: MAE OR RMSE /* Evaluate RMSE of every parameter: 0: LSF, 1:tilt, 2:harm, 3:hnr, 4:gain, 5:f0, 6:waveform, 7:h1h2, 8: naq */ for(i=0;i<npulses;i++) { /* LSF, with weighting */ if(gsl_vector_get(params->paramweights,0) > 0) { for(j=0;j<plsf->size2;j++) gsl_matrix_set(error,i,0, gsl_matrix_get(error,i,0) + gsl_vector_get(lsfw,j)*powf(gsl_matrix_get(lsf,frame_index,j)-gsl_matrix_get(plsf,i,j),2)); gsl_matrix_set(error,i,0,sqrt(gsl_matrix_get(error,i,0))); } /* Tilt, with weighting */ if(gsl_vector_get(params->paramweights,1) > 0 && params->use_tilt == 1) { for(j=0;j<ptilt->size2;j++) gsl_matrix_set(error,i,1, gsl_matrix_get(error,i,1) + gsl_vector_get(lsfsourcew,j)*powf(gsl_matrix_get(glflowsp,frame_index,j)-gsl_matrix_get(ptilt,i,j),2)); gsl_matrix_set(error,i,1,sqrt(gsl_matrix_get(error,i,1))); } /* Harmonics */ if(gsl_vector_get(params->paramweights,2) > 0 && params->use_harmonics == 1) { for(j=0;j<pharm->size2;j++) gsl_matrix_set(error,i,2, gsl_matrix_get(error,i,2) + powf(gsl_matrix_get(harmonics,frame_index,j)-gsl_matrix_get(pharm,i,j),2)); gsl_matrix_set(error,i,2,sqrt(gsl_matrix_get(error,i,2))); } /* HNR */ if(gsl_vector_get(params->paramweights,3) > 0 && params->use_hnr == 1) { for(j=0;j<phnr->size2;j++) gsl_matrix_set(error,i,3, gsl_matrix_get(error,i,3) + powf(gsl_matrix_get(hnr_i,frame_index,j)-gsl_matrix_get(phnr,i,j),2)); gsl_matrix_set(error,i,3,sqrt(gsl_matrix_get(error,i,3))); } /* Gain */ if(gsl_vector_get(params->paramweights,4) > 0) { gsl_matrix_set(error,i,4,fabs(gsl_vector_get(gain,frame_index)-gsl_vector_get(pgain,i))); } /* F0 */ if(gsl_vector_get(params->paramweights,5) > 0) { gsl_matrix_set(error,i,5,fabs(gsl_vector_get(fundf,frame_index)*params->pitch-2.0*params->FS/gsl_vector_get(pulse_lengths,i))); } /* Waveform */ if(gsl_vector_get(params->paramweights,6) > 0 && params->use_waveform == 1) { for(j=0;j<pwaveform->size2;j++) gsl_matrix_set(error,i,6, gsl_matrix_get(error,i,6) + powf(gsl_matrix_get(waveform,frame_index,j)-gsl_matrix_get(pwaveform,i,j),2)); gsl_matrix_set(error,i,6,sqrt(gsl_matrix_get(error,i,6))); } /* H1H2 */ if(gsl_vector_get(params->paramweights,7) > 0 && params->use_h1h2 == 1) { gsl_matrix_set(error,i,7,fabs(gsl_vector_get(h1h2,frame_index)-gsl_vector_get(ph1h2,i))); } /* Gain */ if(gsl_vector_get(params->paramweights,8) > 0 && params->use_naq == 1) { gsl_matrix_set(error,i,8,fabs(gsl_vector_get(naq,frame_index)-gsl_vector_get(pnaq,i))); } /* PCA */ if(gsl_vector_get(params->paramweights,9) > 0 && params->use_pulse_pca == 1) { for(j=0;j<pca_w->size2;j++) gsl_matrix_set(error,i,9, gsl_matrix_get(error,i,9) + powf(gsl_matrix_get(pca_w,frame_index,j)-gsl_matrix_get(pca_w_lib,i,j),2)); gsl_matrix_set(error,i,9,sqrt(gsl_matrix_get(error,i,9))); } } /* Normalize error of every parameter (subtract mean and divide by standard deviation) and weight */ for(i=0;i<nparams;i++) { if(gsl_vector_get(params->paramweights,i) > 0) { /* Evaluate mean error of each parameter */ m = 0; for(j=0;j<npulses;j++) m += gsl_matrix_get(error,j,i); m = m/npulses; /* Evaluate standard deviation of error of each parameter */ std = 0; for(j=0;j<npulses;j++) std += (gsl_matrix_get(error,j,i)-m)*(gsl_matrix_get(error,j,i)-m); std = sqrt(std/(npulses-1)); if(std == 0) std = 1; /* Normalize and weight */ for(j=0;j<npulses;j++) gsl_matrix_set(error,j,i,(gsl_matrix_get(error,j,i)-m)/std*gsl_vector_get(params->paramweights,i)); } } /* Evaluate total error, apply penalty for gross errors */ // TODO: DOES THIS YIELD BETTER QUALITY? double gross_error_penalty_limit = 0; // For normally distributed data (mean = 0, sigma = 1) double gross_error_penalty = 1.0; for(i=0;i<npulses;i++) { for(j=0;j<nparams;j++) { gsl_vector_set(E,i,gsl_vector_get(E,i) + gsl_matrix_get(error,i,j)); if(gsl_matrix_get(error,i,j) > gross_error_penalty_limit) gsl_vector_set(E,i,gsl_vector_get(E,i) + gross_error_penalty); } } /* Select best candidates according to lowest target error and compare * them to the previous pulse */ gsl_sort_vector_index(p,E); for(i=0;i<n_pulsecandidates;i++) { gsl_vector_set(inds,i,gsl_permutation_get(p,i)); gsl_vector_set(eparam,i,gsl_vector_get(E,gsl_vector_get(inds,i))); } } /* Free memory */ gsl_matrix_free(error); gsl_vector_free(E); gsl_vector_free(lsfw); gsl_vector_free(lsfsourcew); gsl_permutation_free(p); } /** * Function Evaluate_concatenation_error_viterbi * * Eval concatenation error for viterbi pulse search * * @param ... */ void Evaluate_concatenation_error_viterbi(gsl_vector *target, gsl_vector* target_next, gsl_vector *inds, gsl_vector *inds_next,gsl_matrix *pulses_rs, gsl_matrix *v_scores, gsl_matrix *v_best, int index, int dist_to_unvoiced, double additional_cost, PARAM *params) { int i, j, k = 0, num_skipped = 0; double e = 0,ccost; //double em = 0; /* Define concatenation cost according to distance to unvoiced and HNR */ ccost = params->concatenation_cost*additional_cost*(1.0-(1.0/sqrt((double)(dist_to_unvoiced)))); /* Current pulses */ for(i=0;i<params->n_pulsecandidates;i++) { /* Next pulses */ for(j=0;j<params->n_pulsecandidates;j++){ /* Possible optimization: skip comparison if highly unlikely to beat the best score */ if(index > 0) { double current_best = gsl_matrix_get(v_scores, index+1, j); if(ccost * 0.1 + params->target_cost * gsl_vector_get(target,i) + gsl_matrix_get(v_scores,index,i) >= current_best) { num_skipped++; continue; } } /* Compare downsampled waveforms */ e = 0; for(k = 0;k<pulses_rs->size2;k++){ e += powf(gsl_matrix_get(pulses_rs,gsl_vector_get(inds,i),k) - gsl_matrix_get(pulses_rs,gsl_vector_get(inds_next,j),k),2); } e = sqrt(e); /* Bias against same pulse */ if(e == 0) e = params->pulse_error_bias; /* Combine the two error measures */ //e = (e + em)/2.0; /* Evaluate combined score */ double combined_score; if(index == 0) { combined_score = params->target_cost * gsl_vector_get(target,i); gsl_matrix_set(v_scores, index,i, combined_score); } else combined_score = ccost * e + params->target_cost * gsl_vector_get(target,i) + gsl_matrix_get(v_scores, index, i); /* Set scores and indices */ if(combined_score < gsl_matrix_get(v_scores, index+1, j)) { gsl_matrix_set(v_scores, index+1, j, combined_score); gsl_matrix_set(v_best, index+1, j, i); } } } } /** * Function Reestimate_hnr * * Re-estimate HNR for pulse library * * @param excitation_voiced * @param excitation_unvoiced * @param hnr HNR matrix * @param fundf F0 vector * @param params */ void Reestimate_hnr(gsl_vector *excitation_voiced, gsl_vector *excitation_unvoiced, gsl_matrix *hnr, gsl_vector *fundf, PARAM *params) { /* Only if pulse library and harmonics are used */ if(params->use_pulselib == 0 && params->use_hnr == 1) return; /* Integrate voiced excitation signal */ int i; gsl_vector *excitation_voiced_flow = gsl_vector_alloc(excitation_voiced->size); gsl_vector_memcpy(excitation_voiced_flow,excitation_voiced); for(i=1;i<excitation_voiced_flow->size;i++) gsl_vector_set(excitation_voiced_flow,i,gsl_vector_get(excitation_voiced_flow,i-1)*LEAK + gsl_vector_get(excitation_voiced_flow,i)); /* Evaluate HNR */ HNR_eval_vu(excitation_voiced_flow, excitation_unvoiced, hnr, fundf, params); Smooth_matrix(hnr,params->hnr_smooth_len); gsl_vector_free(excitation_voiced_flow); } /** * Function HNR_compensation * * Compensate HNR values based on the new values * * @param hnr old HNR values * @param hnr_new new HNR values */ void HNR_compensation(gsl_matrix *hnr, gsl_matrix *hnr_new, PARAM *params) { /* Set params */ params->hnr_reestimated = 1; /* Return if HNR compensation is not used, or HNR is not used, or pulse library is used */ if(params->hnr_compensation == 0 || hnr == NULL || params->use_pulselib == 1) return; /* Make compensation based on the estimated HNR of synthesized excitation */ Smooth_matrix(hnr_new,params->hnr_smooth_len); int i,j; for(j=0;j<hnr->size1;j++) { for(i=0;i<hnr->size2;i++) gsl_matrix_set(hnr,j,i,gsl_matrix_get(hnr,j,i) + gsl_matrix_get(hnr,j,i) - gsl_matrix_get(hnr_new,j,i)); } } /** * Function HNR_eval_vu * * Evaluate HNR of signal (voiced/unvoiced) * * @param signal_v input signal voiced * @param signal_uv input signal unvoiced * @param hnr HNR matrix * @param fundf fundamental frequency * @param frame_length frame length in samples * @paran shift shift length in samples * @param speed synthesis speed * */ void HNR_eval_vu(gsl_vector *signal_v,gsl_vector *signal_uv,gsl_matrix *hnr,gsl_vector *fundf, PARAM *params) { int i,j,add = rint((params->f0_frame_length/(double)params->shift/params->speed-1.0)*params->shift/params->speed/2.0); gsl_vector *frame = gsl_vector_alloc(rint(params->f0_frame_length/params->speed)); gsl_vector *signal = gsl_vector_calloc(signal_v->size); gsl_vector_add(signal,signal_v); gsl_vector_add(signal,signal_uv); /* Zeropad signal */ gsl_vector *signal_zp = gsl_vector_calloc(signal->size + 2*add); for(i=0;i<signal->size;i++) gsl_vector_set(signal_zp,i+add,gsl_vector_get(signal,i)); /* Window and calculate glottal flow spectrum */ for(i=0;i<hnr->size1;i++) { for(j=rint(i*params->shift/params->speed);j<GSL_MIN(rint(i*params->shift/params->speed+params->f0_frame_length/params->speed),signal_zp->size-1);j++) { gsl_vector_set(frame,GSL_MIN(j-rint(i*params->shift/params->speed),frame->size-1),gsl_vector_get(signal_zp,j)); } Upper_lower_envelope(frame, hnr, gsl_vector_get(fundf,i), i, params); } gsl_vector_free(frame); gsl_vector_free(signal_zp); gsl_vector_free(signal); } /** * Function Phase_manipulation * * Modify the phase and magnitude of the pulse to create noise. * The modified pulse is saved inplace to pulse. * * @param pulse original pulse * @param hnr HNR matrix * @param harmonics harmonic magnitudes * @param index current frame index * @param params parameter structure */ void Phase_manipulation(gsl_vector *pulse, gsl_matrix *hnr, gsl_matrix *harmonics, int index, PARAM *params) { /* Initialize */ int i,n = pulse->size; double data[n]; /* Set pulse data to array "data" */ for(i=0;i<n;i++) data[i] = gsl_vector_get(pulse,i); /* FFT */ gsl_fft_real_wavetable *wreal = gsl_fft_real_wavetable_alloc(n); gsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(n); gsl_fft_real_transform(data,1,n,wreal,work); gsl_fft_real_wavetable_free(wreal); /* Extract real and imaginary parts to vectors */ double x[2*n]; gsl_complex_packed_array complex_coefficients = x; gsl_vector *real = gsl_vector_alloc(n); gsl_vector *imag = gsl_vector_alloc(n); gsl_fft_halfcomplex_unpack(data,complex_coefficients,1,n); for(i=0;i<n;i++) { gsl_vector_set(real,i,REAL(complex_coefficients,i)); gsl_vector_set(imag,i,IMAG(complex_coefficients,i)); } /* Get HNR values in ERB scale to vector, convert to Hz scale */ gsl_vector *hnr_values_erb = gsl_vector_alloc(params->hnr_channels); gsl_vector *hnr_values = gsl_vector_alloc(ceil((imag->size-1)/2.0)); for(i=0;i<params->hnr_channels;i++) gsl_vector_set(hnr_values_erb,i,gsl_matrix_get(hnr,index,i)); Convert_ERB2Hz(hnr_values_erb,hnr_values,params); /* Noise power equals to pulse power minus the difference between harmonics and noise (indicated by HNR values) */ gsl_vector *pulse_power = gsl_vector_alloc(hnr_values->size); for(i=0;i<hnr_values->size;i++) gsl_vector_set(pulse_power, i, 20*log10(sqrt(pow(gsl_vector_get(real,i+1), 2) + pow(gsl_vector_get(imag,i+1), 2)))); MA(pulse_power,11); for(i=0;i<hnr_values->size;i++) gsl_vector_set(hnr_values, i, gsl_vector_get(hnr_values,i) + gsl_vector_get(pulse_power,i)); gsl_vector_free(hnr_values_erb); gsl_vector_free(pulse_power); /* Convert HNR values from logarithmic scale to linear scale (actual noise amplitudes) */ for(i=0;i<hnr_values->size;i++) gsl_vector_set(hnr_values,i,pow(10,(gsl_vector_get(hnr_values,i)/20.0))); /* Modification of the amplitudes of the harmonics */ if(params->use_harmonic_modification != 0) { /* Extract radius and phase */ gsl_vector *radius = gsl_vector_alloc(imag->size); gsl_vector *phase = gsl_vector_alloc(imag->size); for(i=0;i<radius->size;i++) gsl_vector_set(radius,i,sqrt(pow(gsl_vector_get(real,i),2) + pow(gsl_vector_get(imag,i),2))); for(i=0;i<phase->size;i++) gsl_vector_set(phase,i,atan2(gsl_vector_get(imag,i),gsl_vector_get(real,i))); /* Get pulse magnitude */ gsl_vector *magnitude = gsl_vector_alloc(radius->size); for(i=0;i<magnitude->size;i++) gsl_vector_set(magnitude,i,20*log10(gsl_vector_get(radius,i))); /* Modify harmonics, use harmonics or modify by rule */ if(params->use_harmonics == 1) { /* Use harmonics */ /* Get harmonic log-magnitudes from matrix "harmonics" */ gsl_vector *rnew = gsl_vector_alloc(params->number_of_harmonics+1); gsl_vector_set(rnew,0,20*log10(gsl_vector_get(radius,1))); for(i=0;i<params->number_of_harmonics;i++) gsl_vector_set(rnew,i+1,gsl_matrix_get(harmonics,index,i) + gsl_vector_get(rnew,0)); /* Modify pulse magnitude */ double diff_mag = gsl_vector_get(rnew,params->number_of_harmonics)-20.0*log10(gsl_vector_get(radius,params->number_of_harmonics+1)); for(i=0;i<params->number_of_harmonics+1;i++) gsl_vector_set(magnitude,i+1,gsl_vector_get(rnew,i)); for(i=params->number_of_harmonics+2;i<magnitude->size;i++) gsl_vector_set(magnitude,i,gsl_vector_get(magnitude,i)+diff_mag); /* Free memory */ gsl_vector_free(rnew); } else if(params->pulse_tilt_decrease_coeff < 1) { /* Decrease spectral tilt by rule */ /* Modify magnitude */ double m0 = gsl_vector_get(magnitude,0); for(i=0;i<magnitude->size;i++) gsl_vector_set(magnitude,i,m0 + params->pulse_tilt_decrease_coeff*(gsl_vector_get(magnitude,i)-m0)); } /* Set log-magnitude back to magnitude */ for(i=0;i<radius->size;i++) gsl_vector_set(radius,i,pow(10,gsl_vector_get(magnitude,i)/20.0)); /* Reconstruct imag and real */ for(i=1;i<imag->size;i++) { gsl_vector_set(real,i,gsl_vector_get(radius,i)*cos(gsl_vector_get(phase,i))); gsl_vector_set(imag,i,gsl_vector_get(radius,i)*sin(gsl_vector_get(phase,i))); } /* Free memory */ gsl_vector_free(radius); gsl_vector_free(phase); gsl_vector_free(magnitude); } /* Change noise low frequency limit from Hz to relative to FS */ double noise_low_freq_limit_rel = params->noise_low_freq_limit/params->FS*2; /* Add noise by modifying both the magnitude and the phase of the spectrum of the pulse */ for(i=rint(noise_low_freq_limit_rel*hnr_values->size);i<hnr_values->size;i++) { gsl_vector_set(imag,i+1,gsl_vector_get(imag,i+1) + params->noise_gain_voiced*RAND()*gsl_vector_get(hnr_values,i)); gsl_vector_set(real,i+1,gsl_vector_get(real,i+1) + params->noise_gain_voiced*RAND()*gsl_vector_get(hnr_values,i)); } /* Copy the noise to the folded spectrum as well */ if(imag->size%2 == 0) { for(i=0;i<hnr_values->size;i++) { gsl_vector_set(imag,hnr_values->size+i,-gsl_vector_get(imag,hnr_values->size-i)); gsl_vector_set(real,hnr_values->size+i,gsl_vector_get(real,hnr_values->size-i)); } } else { for(i=0;i<hnr_values->size;i++) { gsl_vector_set(imag,hnr_values->size+1+i,-gsl_vector_get(imag,hnr_values->size-i)); gsl_vector_set(real,hnr_values->size+1+i,gsl_vector_get(real,hnr_values->size-i)); } } /* Create halfcomplex data */ data[0] = gsl_vector_get(real,0); for(i=1;i<n;i++) { if(i%2 == 1) data[i] = gsl_vector_get(real,(i+1)/2); else data[i] = gsl_vector_get(imag,i/2); } /* Inverse FFT */ gsl_fft_halfcomplex_wavetable *whc = gsl_fft_halfcomplex_wavetable_alloc(n); gsl_fft_halfcomplex_inverse(data,1,n,whc,work); gsl_fft_halfcomplex_wavetable_free(whc); gsl_fft_real_workspace_free(work); /* Set data from array "data" to vector "pulse" */ for(i=0;i<n;i++) gsl_vector_set(pulse,i,data[i]); /* Free memory */ gsl_vector_free(real); gsl_vector_free(imag); gsl_vector_free(hnr_values); } /** * Function Highpassfilter_fft * */ void Highpassfilter_fft(gsl_vector *signal) { /* Initialize */ int i,n = signal->size; double data[n]; /* Set signal to array "data" */ for(i=0;i<n;i++) data[i] = gsl_vector_get(signal,i); /* FFT */ gsl_fft_real_wavetable *wreal = gsl_fft_real_wavetable_alloc(n); gsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(n); gsl_fft_real_transform(data,1,n,wreal,work); gsl_fft_real_wavetable_free(wreal); /* Extract real and imaginary parts to vectors */ double x[2*n]; gsl_complex_packed_array complex_coefficients = x; gsl_vector *real = gsl_vector_alloc(n); gsl_vector *imag = gsl_vector_alloc(n); gsl_fft_halfcomplex_unpack(data,complex_coefficients,1,n); for(i=0;i<n;i++) { gsl_vector_set(real,i,REAL(complex_coefficients,i)); gsl_vector_set(imag,i,IMAG(complex_coefficients,i)); } /* Extract radius and phase */ gsl_vector *radius = gsl_vector_alloc(imag->size); gsl_vector *phase = gsl_vector_alloc(imag->size); for(i=0;i<radius->size;i++) gsl_vector_set(radius,i,sqrt(pow(gsl_vector_get(real,i),2) + pow(gsl_vector_get(imag,i),2))); for(i=0;i<phase->size;i++) gsl_vector_set(phase,i,atan2(gsl_vector_get(imag,i),gsl_vector_get(real,i))); /* Modify radius for high-pass filtering: Remove first half of the spectrum */ int Nrem = rint(radius->size/4); for(i=0;i<Nrem;i++) { gsl_vector_set(radius,i+1,0); gsl_vector_set(radius,radius->size-1-i,0); } /* Reconstruct imag and real */ for(i=1;i<imag->size;i++) { gsl_vector_set(real,i,gsl_vector_get(radius,i)*cos(gsl_vector_get(phase,i))); gsl_vector_set(imag,i,gsl_vector_get(radius,i)*sin(gsl_vector_get(phase,i))); } gsl_vector_set(imag,0,0); gsl_vector_set(real,0,0); /* Create halfcomplex data */ data[0] = gsl_vector_get(real,0); for(i=1;i<n;i++) { if(i%2 == 1) data[i] = gsl_vector_get(real,(i+1)/2); else data[i] = gsl_vector_get(imag,i/2); } /* Inverse FFT */ gsl_fft_halfcomplex_wavetable *whc = gsl_fft_halfcomplex_wavetable_alloc(n); gsl_fft_halfcomplex_inverse(data,1,n,whc,work); gsl_fft_halfcomplex_wavetable_free(whc); gsl_fft_real_workspace_free(work); /* Set data from array "data" to vector "signal" */ for(i=0;i<n;i++) gsl_vector_set(signal,i,data[i]); /* Free memory */ gsl_vector_free(radius); gsl_vector_free(phase); gsl_vector_free(real); gsl_vector_free(imag); } /** * Function Highpassfilter_fir * */ void Highpassfilter_fir(gsl_vector *signal, gsl_vector *coeffs) { /* Initialize */ int i,j,n = coeffs->size; double sum; gsl_vector *temp = gsl_vector_calloc(signal->size+round(coeffs->size/2.0)-1); gsl_vector *signal_temp = gsl_vector_calloc(signal->size+round(coeffs->size/2.0)-1); for(i=0;i<signal->size;i++) gsl_vector_set(signal_temp,i,gsl_vector_get(signal,i)); /* Filter signal */ for(i=0; i<signal_temp->size; i++) { sum = 0; for(j=0; j<=GSL_MIN(i, n-1); j++) sum += gsl_vector_get(signal_temp,i-j)*gsl_vector_get(coeffs,j); gsl_vector_set(temp, i, sum); } /* Copy "temp" samples to "signal" */ for(i=0; i<signal->size; i++) gsl_vector_set(signal, i, gsl_vector_get(temp, i+coeffs->size/2)); /* Free memory */ gsl_vector_free(temp); gsl_vector_free(signal_temp); } /** * Function Convert_ERB2Hz * * Convert vector scale from ERB to Hz * * @param vector_erb pointer to vector of ERB-scale HNR values * @param vector pointer to reconstructed HNR vector * */ void Convert_ERB2Hz(gsl_vector *vector_erb, gsl_vector *vector, PARAM *params) { int i,j,hnr_channels = vector_erb->size; gsl_vector *erb = gsl_vector_alloc(vector->size); /* Evaluate ERB scale indices for vector */ for(i=0;i<vector->size;i++) gsl_vector_set(erb,i,log10(0.00437*(i/(vector->size-1.0)*(params->FS/2.0))+1.0)/log10(0.00437*(params->FS/2.0)+1.0)*(hnr_channels-SMALL_NUMBER)); /* Evaluate values according to ERB rate, smooth */ for(i=0;i<vector->size;i++) { j = floor(gsl_vector_get(erb,i)); gsl_vector_set(vector,i,gsl_vector_get(vector_erb,j)); } MA(vector,3); /* Free memory */ gsl_vector_free(erb); } /** * Function Upper_lower_envelope * * Extract the amount of aperiodicity according to smoothed upper and lower spectral envelopes. * * @param frame pointer to frame * @param hnr pointer to matrix where the results are saved * @param f0 fundamental frequency * @param index time index * */ void Upper_lower_envelope(gsl_vector *frame, gsl_matrix *hnr, double f0, int index, PARAM *params) { /* Define FFT length */ int FFT_LENGTH = MIN_FFT_LENGTH; while(FFT_LENGTH < frame->size) FFT_LENGTH = FFT_LENGTH*2; /* Variables */ int i,j,guess_index = 0,h_values_size,harmonic_search_range; int hnr_channels = hnr->size2; double ind[MAX_HARMONICS] = {0}; double guess_index_double = 0; double data[FFT_LENGTH]; double h_values[MAX_HARMONICS] = {0}; double n_values[MAX_HARMONICS] = {0}; gsl_vector *fft = gsl_vector_alloc(FFT_LENGTH/2); gsl_vector *find; /* Initialize data */ for(i=0;i<FFT_LENGTH;i++) data[i] = 0; /* FFT (with windowing) */ for (i=0; i<frame->size; i++) data[i] = gsl_vector_get(frame, i)*HANN(i,frame->size); gsl_fft_real_radix2_transform(data, 1, FFT_LENGTH); for(i=1; i<FFT_LENGTH/2; i++) gsl_vector_set(fft, i, 20*log10(sqrt(pow(data[i], 2) + pow(data[FFT_LENGTH-i], 2)))); gsl_vector_set(fft, 0, 20*log10(abs(data[0]))); /* Set (possible) infinity values to zero */ for(i=0;i<fft->size;i++) { if(!gsl_finite(gsl_vector_get(fft,i))) gsl_vector_set(fft,i,MIN_LOG_POWER); } /* Find the indices and magnitudes of the harmonic peaks */ i = 0; while(1) { /* Define harmonics search range, decreasing to the higher frequencies */ harmonic_search_range = GSL_MAX(HARMONIC_SEARCH_COEFF*f0/(params->FS/(double)FFT_LENGTH)*((fft->size-1-guess_index)/(double)(fft->size-1)),1.0); find = gsl_vector_alloc(harmonic_search_range); /* Estimate the index of the i_th harmonic * Use an iterative estimation based on earlier values */ if(i > 0) { guess_index_double = 0; for(j=0;j<i;j++) guess_index_double += ind[j]/(j+1.0)*(i+1.0); guess_index = (int)GSL_MAX(guess_index_double/j - (harmonic_search_range-1)/2.0,0); } else guess_index = (int)GSL_MAX(f0/(params->FS/(double)FFT_LENGTH) - (harmonic_search_range-1)/2.0,0); /* Stop search if the end of the fft vector or the maximum number of harmonics is reached */ if(guess_index + rint(HNR_UNCERTAINTY_COEFF*FFT_LENGTH) > fft->size-1 || i > MAX_HARMONICS-1) { gsl_vector_free(find); break; } /* Find the maximum of the i_th harmonic */ for(j=0; j<harmonic_search_range; j++) { if(guess_index+j < fft->size) gsl_vector_set(find, j, gsl_vector_get(fft, guess_index+j)); else gsl_vector_set(find, j, BIG_NEG_NUMBER); } ind[i] = guess_index + gsl_vector_max_index(find); h_values[i] = gsl_vector_get(fft, ind[i]); gsl_vector_free(find); i++; } h_values_size = i; /* Estimate the level of interharmonic noise */ double ind_n[MAX_HARMONICS] = {0}; for(i=0;i<h_values_size-1;i++) { /* Evaluate value exactly between the harmonics */ ind_n[i] = rint((ind[i]+ind[i+1])/2.0); n_values[i] = gsl_vector_get(fft,ind_n[i]); } /* Postfilter and iterpolate vectors */ gsl_vector *hnr_est = gsl_vector_alloc(h_values_size-1); gsl_vector *hnr_est_erb = gsl_vector_calloc(hnr_channels); for(i=0;i<hnr_est->size;i++) gsl_vector_set(hnr_est,i,n_values[i]-h_values[i]); MedFilt3(hnr_est); Convert_Hz2ERB(hnr_est, hnr_est_erb, params); /* Set values to hnr matrix */ for(i=0;i<hnr_channels;i++) gsl_matrix_set(hnr,index,i,gsl_vector_get(hnr_est_erb,i)); /* Free memory */ gsl_vector_free(fft); gsl_vector_free(hnr_est); gsl_vector_free(hnr_est_erb); } /** * Function Convert_Hz2ERB * * Convert vector scale from Hz to ERB * * @param vector pointer to original HNR vector * @param vector_erb pointer to vector of ERB-scale HNR values * */ void Convert_Hz2ERB(gsl_vector *vector, gsl_vector *vector_erb, PARAM *params) { int i,j,hnr_channels = vector_erb->size; gsl_vector *erb = gsl_vector_alloc(vector->size); gsl_vector *erb_sum = gsl_vector_calloc(hnr_channels); /* Evaluate ERB scale indices for vector */ for(i=0;i<vector->size;i++) gsl_vector_set(erb,i,log10(0.00437*(i/(vector->size-1.0)*(params->FS/2.0))+1.0)/log10(0.00437*(params->FS/2.0)+1.0)*(hnr_channels-SMALL_NUMBER)); /* Evaluate values according to ERB rate */ for(i=0;i<vector->size;i++) { j = floor(gsl_vector_get(erb,i)); gsl_vector_set(vector_erb,j,gsl_vector_get(vector_erb,j)+gsl_vector_get(vector,i)); gsl_vector_set(erb_sum,j,gsl_vector_get(erb_sum,j)+1); } /* Average values */ for(i=0;i<hnr_channels;i++) gsl_vector_set(vector_erb,i,gsl_vector_get(vector_erb,i)/gsl_vector_get(erb_sum,i)); /* Prevent NaN-values (due to division by zero) */ for(i=0;i<hnr_channels;i++) { if(gsl_vector_get(erb_sum,i) == 0) { j = 1; while(gsl_vector_get(erb_sum,i+j) == 0) j++; gsl_vector_set(vector_erb,i,0.5*gsl_vector_get(vector_erb,i-1)+0.5*gsl_vector_get(vector_erb,i+j)); } } /* Free memory */ gsl_vector_free(erb); gsl_vector_free(erb_sum); } /** * Function Create_pulse_train * * Reconstruct voice source in a frame * * @param ... */ gsl_vector *Create_pulse_train(gsl_vector *pulse, gsl_vector *original_pulse, gsl_matrix *hnr, gsl_vector *fundf, gsl_matrix *harmonics, int frame_index, int sample_index, PARAM *params) { /* Initialize */ int i,frame_index_new,sample_index_new,N,pulse_start,pulse_end; gsl_vector *pulsetrain = gsl_vector_calloc(params->f0_frame_length+pulse->size); gsl_vector *pulse_copy = gsl_vector_alloc(pulse->size); int ptlen = pulsetrain->size; /* Set first pulse to pulsetrain in the middle of the frame */ gsl_vector_memcpy(pulse_copy,pulse); Phase_manipulation(pulse_copy,hnr,harmonics,frame_index,params); for(i=0;i<pulse->size;i++) gsl_vector_set(pulsetrain,i+ptlen/2.0-pulse->size/2.0,gsl_vector_get(pulse_copy,i)); gsl_vector_free(pulse_copy); pulse_start = ptlen/2.0-pulse->size/2.0+1; pulse_end = ptlen/2.0-pulse->size/2.0+i-1; /* Set earlier pulses to pulsetrain */ frame_index_new = frame_index; sample_index_new = sample_index; N = pulse->size; while(1) { sample_index_new = GSL_MAX(sample_index_new - N,0); frame_index_new = GSL_MIN(rint(params->n_frames*((sample_index_new+0.5*N)/(double)params->signal_length)),params->n_frames-1); N = rint(params->FS/gsl_vector_get(fundf,frame_index_new)/params->pitch); if(gsl_vector_get(fundf,frame_index_new)/params->pitch == 0) { N = params->shift/params->speed; pulse_start = pulse_start-N; if(pulse_start-N >= 0) continue; else break; } gsl_vector *pulse_new = gsl_vector_alloc(N); Interpolate(original_pulse,pulse_new); Phase_manipulation(pulse_new,hnr,harmonics,frame_index_new,params); for(i=0;i<N;i++) gsl_vector_set(pulsetrain,GSL_MAX(pulse_start-N+i,0),gsl_vector_get(pulse_new,i)); pulse_start = pulse_start-N+1; gsl_vector_free(pulse_new); if(pulse_start < 0) break; } /* Set later pulses to pulsetrain */ frame_index_new = frame_index; sample_index_new = sample_index; N = pulse->size; while(1) { sample_index_new = GSL_MIN(sample_index_new + N,params->signal_length-1); frame_index_new = GSL_MIN(rint(params->n_frames*((sample_index_new-0.5*N)/(double)params->signal_length)),params->n_frames-1); N = rint(params->FS/gsl_vector_get(fundf,frame_index_new)/params->pitch); if(gsl_vector_get(fundf,frame_index_new)/params->pitch == 0) { N = params->shift/params->speed; pulse_end = pulse_end+N; if(pulse_end+N < pulsetrain->size) continue; else break; } gsl_vector *pulse_new = gsl_vector_alloc(N); Interpolate(original_pulse,pulse_new); Phase_manipulation(pulse_new,hnr,harmonics,frame_index_new,params); for(i=0;i<N;i++) { if(pulse_end+i > pulsetrain->size-1) break; gsl_vector_set(pulsetrain,pulse_end+i,gsl_vector_get(pulse_new,i)); } pulse_end = pulse_end+N-1; gsl_vector_free(pulse_new); if(pulse_end > pulsetrain->size-1) break; } /* Return result */ return pulsetrain; } /** * Function Create_pulse_train_diff * * Reconstruct voice source in a frame (for differentiated two-pitch-period pulses) * * @param ... */ gsl_vector *Create_pulse_train_diff(gsl_vector *pulse, gsl_vector *original_pulse, gsl_matrix *hnr, gsl_vector *fundf, gsl_matrix *harmonics, int frame_index, int sample_index, PARAM *params) { /* Initialize */ int i,frame_index_new,sample_index_new,N,pulse_start,pulse_end; gsl_vector *pulsetrain = gsl_vector_calloc(params->f0_frame_length+round(pulse->size/2)); gsl_vector *pulse_copy = gsl_vector_alloc(pulse->size); int ptlen = pulsetrain->size; /* Add noise to pulse copy */ gsl_vector_memcpy(pulse_copy,pulse); Integrate(pulse_copy,LEAK); Phase_manipulation(pulse_copy,hnr,harmonics,frame_index,params); Differentiate(pulse_copy,LEAK); gsl_vector_set(pulse_copy,0,0); /* Set first pulse to pulsetrain in the middle of the frame */ for(i=0;i<GSL_MIN(pulse->size,ptlen);i++) gsl_vector_set(pulsetrain,GSL_MAX(i+ptlen/2.0-pulse->size/2.0,0),gsl_vector_get(pulse_copy,i)); gsl_vector_free(pulse_copy); pulse_start = ptlen/2.0-pulse->size/2.0+1; pulse_end = ptlen/2.0-pulse->size/2.0+i-1; /* Set earlier pulses to pulsetrain */ frame_index_new = frame_index; sample_index_new = sample_index; N = pulse->size; while(1) { sample_index_new = GSL_MAX(sample_index_new - round(N/2),0); frame_index_new = GSL_MIN(rint(params->n_frames*((sample_index_new+0.25*N)/(double)params->signal_length)),params->n_frames-1); N = rint(2.0*params->FS/gsl_vector_get(fundf,frame_index_new)/params->pitch); if(gsl_vector_get(fundf,frame_index_new)/params->pitch == 0) { N = params->shift/params->speed; pulse_start = pulse_start-N; if(pulse_start-N >= 0) continue; else break; } gsl_vector *pulse_new = gsl_vector_alloc(N); Interpolate(original_pulse,pulse_new); /* Add noise */ Integrate(pulse_new, LEAK); Phase_manipulation(pulse_new,hnr,harmonics,frame_index_new,params); Differentiate(pulse_new,LEAK); gsl_vector_set(pulse_new,0,0); // Fix DC error /* Set to excitation */ for(i=0;i<N;i++) gsl_vector_set(pulsetrain,GSL_MAX(pulse_start-round(N/2)+i,0),gsl_vector_get(pulsetrain,GSL_MAX(pulse_start-round(N/2)+i,0)) + gsl_vector_get(pulse_new,i)); pulse_start = pulse_start-round(N/2+1); gsl_vector_free(pulse_new); if(pulse_start < 0) break; } /* Set later pulses to pulsetrain */ frame_index_new = frame_index; sample_index_new = sample_index; N = pulse->size; while(1) { sample_index_new = GSL_MIN(sample_index_new + round(N/2),params->signal_length-1); frame_index_new = GSL_MIN(rint(params->n_frames*((sample_index_new-0.25*N)/(double)params->signal_length)),params->n_frames-1); N = rint(2*params->FS/gsl_vector_get(fundf,frame_index_new)/params->pitch); if(gsl_vector_get(fundf,frame_index_new)/params->pitch == 0) { N = params->shift/params->speed; pulse_end = pulse_end+N; if(pulse_end+N < pulsetrain->size) continue; else break; } gsl_vector *pulse_new = gsl_vector_alloc(N); Interpolate(original_pulse,pulse_new); /* Add noise */ Integrate(pulse_new, LEAK); Phase_manipulation(pulse_new,hnr,harmonics,frame_index_new,params); Differentiate(pulse_new,LEAK); gsl_vector_set(pulse_new,0,0); // Fix DC error /* Set to excitation */ for(i=0;i<N;i++) { if(pulse_end-round(N/2)+i > pulsetrain->size-1 || pulse_end-round(N/2)+i < 0) break; gsl_vector_set(pulsetrain,pulse_end-round(N/2)+i,gsl_vector_get(pulsetrain,pulse_end-round(N/2)+i) + gsl_vector_get(pulse_new,i)); } pulse_end = pulse_end+round(N/2)-1; gsl_vector_free(pulse_new); if(pulse_end > pulsetrain->size-1) break; } /* Return result */ return pulsetrain; } /** * Function Analyse_pulse_train_spectrum * * Analyse LP spectrum of the pulse train * * @param ... */ void Analyse_pulse_train_spectrum(gsl_vector *pulse_train, gsl_matrix *glflowsp_new, int N, int sample_index, int frame_index, PARAM *params) { int i; gsl_vector *a; /* Apply pre-emphasis */ if(USE_PRE_EMPH == 1) { gsl_vector *e_pulse_train = gsl_vector_alloc(pulse_train->size); gsl_vector_set(e_pulse_train,0,gsl_vector_get(pulse_train,0)); for(i=1;i<pulse_train->size;i++) gsl_vector_set(e_pulse_train,i,gsl_vector_get(pulse_train,i) - 0.99*gsl_vector_get(pulse_train,i-1)); a = WLPC(e_pulse_train, params->lpc_order_gl, params->lambda_gl); gsl_vector_free(e_pulse_train); } else { a = WLPC(pulse_train, params->lpc_order_gl, params->lambda_gl); } /* Set spectrum to matrix, fill in empty values */ for(i=frame_index;i<GSL_MIN(floor(params->n_frames*((sample_index+N)/(double)params->signal_length)),params->n_frames);i++) Convert_to_LSF(glflowsp_new,a,i); /* Free memory */ gsl_vector_free(a); } /** * Function Mean * * Evaluate mean of a vector * * @param vector pointer to vector * @return mean * */ double Mean(gsl_vector *vector) { int i; double mean = 0; for(i=0; i<vector->size; i++) { mean += gsl_vector_get(vector, i); } return (mean/(double)vector->size); } /** * Function NonZeroMean * * Evaluate mean of a vector from elements that are not zeros * * @param vector pointer to vector * @return mean * */ double NonZeroMean(gsl_vector *vector) { int i,ind = 0; double mean = 0; for(i=0; i<vector->size; i++) { if(gsl_vector_get(vector,i) != 0) { mean += gsl_vector_get(vector, i); ind++; } } return (mean/(double)ind); } /** * Function FillHNRValues * * Fill missing HNR values * * @param hnr HNR values * @param frame_index_old old index * @param frame_index current index */ void FillHNRValues(gsl_matrix *hnr, int frame_index_old, int frame_index) { int i,j; for(i=frame_index_old+1;i<frame_index;i++) { for(j=0;j<hnr->size2;j++) gsl_matrix_set(hnr,i,j,gsl_matrix_get(hnr,frame_index,j)); } } /** * Function FillUnvoicedSyntheticSourceSpectrum * * Fill current and previous source spectrum values * * @param glflowsp original spectrum * @param glflowsp_new new spectrum * @param frame_index_old old index * @param frame_index current index */ void FillUnvoicedSyntheticSourceSpectrum(gsl_matrix *glflowsp, gsl_matrix *glflowsp_new, int frame_index, int frame_index_old) { if(glflowsp == NULL) return; /* Set */ int i,j; for(i=0;i<glflowsp->size2;i++) gsl_matrix_set(glflowsp_new, frame_index, i, gsl_matrix_get(glflowsp, frame_index, i)); for(j=frame_index_old+1;j<frame_index;j++) { if(gsl_matrix_get(glflowsp_new,j,0) == 0) { for(i=0;i<glflowsp->size2;i++) gsl_matrix_set(glflowsp_new, j, i, gsl_matrix_get(glflowsp, j, i)); } } /* Double check */ if(frame_index+1 < glflowsp_new->size1) for(i=0;i<glflowsp_new->size2;i++) gsl_matrix_set(glflowsp_new, frame_index+1, i, gsl_matrix_get(glflowsp, frame_index+1, i)); } /** * Function FillUnvoicedSyntheticSourceSpectrum_FLAT * * Fill current and previous source spectrum values * * @param glflowsp original spectrum * @param glflowsp_new new spectrum * @param frame_index_old old index * @param frame_index current index */ void FillUnvoicedSyntheticSourceSpectrum_FLAT(gsl_matrix *glflowsp, gsl_matrix *glflowsp_new, int frame_index, int frame_index_old) { if(glflowsp == NULL) return; /* Set */ int i,j; for(i=0;i<glflowsp->size2;i++) gsl_matrix_set(glflowsp_new, frame_index, i, (i+1.0)*(M_PI/glflowsp->size2)); for(j=frame_index_old+1;j<frame_index;j++) { if(gsl_matrix_get(glflowsp_new,j,0) == 0) { for(i=0;i<glflowsp->size2;i++) gsl_matrix_set(glflowsp_new, j, i, (i+1.0)*(M_PI/glflowsp->size2)); } } /* Double check */ if(frame_index+1 < glflowsp_new->size1) for(i=0;i<glflowsp_new->size2;i++) gsl_matrix_set(glflowsp_new, frame_index+1, i, gsl_matrix_get(glflowsp, frame_index+1, i)); } /** * Function MedFilt5_matrix * * 5-point median filtering for matrices. * Filter along the first dimension. * * @param frame pointer to matrix to be filtered * */ void MedFilt5_matrix(gsl_matrix *matrix) { int i,j; gsl_vector *temp = gsl_vector_alloc(matrix->size1); for(i=0;i<matrix->size2;i++) { for(j=0;j<matrix->size1;j++) { gsl_vector_set(temp,j,gsl_matrix_get(matrix,j,i)); } MedFilt5(temp); for(j=0;j<matrix->size1;j++) { gsl_matrix_set(matrix,j,i,gsl_vector_get(temp,j)); } } gsl_vector_free(temp); } /** * Function Modify_harmonics * * Modification of the harmonic information for speech in the presence of noise * * @param harmonics pointer to harmonics matrix * @param fundf pointer to F0 vector * */ void Modify_harmonics(gsl_matrix *harmonics, double scale) { /* Decrease the tilt of the spectrum */ gsl_matrix_scale(harmonics, scale); } /** * Function Compression * * Dynamic range compression * Nonlinear power of k, 0<k<1, and linear response below threshold * * @param signal pointer to signal * */ void Compression(gsl_vector *signal, double k) { /* Check validity */ if(k >= 1 || k <= 0) return; /* Dynamic range compression */ double th = powf((1.0/k),(1.0/(k-1.0))); // Point where the derivative of the curve is one -> start nonlinearity after this threshold double a = powf(th,k) - th; // The difference at the the turning point int i; for(i=0;i<signal->size;i++) { if(gsl_vector_get(signal,i) < -th) gsl_vector_set(signal,i,-powf(-gsl_vector_get(signal,i),k) + a); else if(gsl_vector_get(signal,i) > th) gsl_vector_set(signal,i,powf(gsl_vector_get(signal,i),k) - a); } /* Scale maximum to one */ double absmax = GSL_MAX(gsl_vector_max(signal),-gsl_vector_min(signal)); for(i=0;i<signal->size;i++) gsl_vector_set(signal,i,WAV_SCALE*gsl_vector_get(signal,i)/absmax); } /** * Function MedFilt5 * * 5-point median filtering * * @param frame pointer to vector to be filtered * */ void MedFilt5(gsl_vector *frame) { int i,j,n = 5; double temp1 = gsl_vector_get(frame, 0); double temp2 = gsl_vector_get(frame,1); double temp3; gsl_vector *samples = gsl_vector_alloc(n); for(i=0; i<frame->size-(n-1); i++) { for(j=0; j<n; j++) { gsl_vector_set(samples, j, gsl_vector_get(frame, i+j)); } gsl_sort_vector(samples); temp3 = gsl_vector_get(samples, 2); gsl_vector_set(frame, i, temp1); temp1 = temp2; temp2 = temp3; } gsl_vector_free(samples); } /** * Function MedFilt3 * * 3-point median filtering * * @param frame pointer to vector to be filtered * */ void MedFilt3(gsl_vector *frame) { int i,j,n; double temp1 = 0; double temp2 = gsl_vector_get(frame, 0); n = 3; gsl_vector *samples = gsl_vector_alloc(n); for(i=0; i<frame->size-2; i++) { for(j=0; j<n; j++) { gsl_vector_set(samples, j, gsl_vector_get(frame, i+j)); } gsl_sort_vector(samples); temp1 = gsl_vector_get(samples, 1); gsl_vector_set(frame, i, temp2); temp2 = temp1; } gsl_vector_free(samples); } /** * Function Smooth_interp_lsf * * Smooth and interpolate LSF-matrix * * @param LSF_interp pointer to interpolated LSF-matrix * @param LSF original LSF-matrix * @param signal_len signal length * @param use_hmm HMM-switch * @param lsf_smooth_len smoothing length in samples * */ void Smooth_interp_lsf(gsl_matrix *LSF_i, gsl_matrix *LSF, int signal_len, int use_hmm, int lsf_smooth_len) { int i,j; gsl_vector *temp = gsl_vector_alloc(LSF->size1); gsl_vector *temp_i = gsl_vector_alloc(signal_len); for(i=0;i<LSF->size2;i++) { for(j=0;j<LSF->size1;j++) { gsl_vector_set(temp,j,gsl_matrix_get(LSF,j,i)); } /* Smooth vectors in time */ if(use_hmm == 0) MA(temp,lsf_smooth_len); /* Interpolate vector */ Interpolate(temp,temp_i); /* Set smoothed and interpolated LSFs to matrices */ for(j=0;j<signal_len;j++) { gsl_matrix_set(LSF_i,j,i,gsl_vector_get(temp_i,j)); } } /* Free memory */ gsl_vector_free(temp); gsl_vector_free(temp_i); } /** * Function Filter_excitation * * Filter excitation (normal/warped) * * @param excitation excitation * @param LSF lsf matrix * @param params * */ void Filter_excitation(gsl_vector *excitation, gsl_matrix *LSF, PARAM *params) { /* Normal filtering */ if(params->lambda_vt == 0) { int i,j; double sum; gsl_vector *A = gsl_vector_alloc(params->lpc_order_vt+1); for(i=0;i<params->signal_length;i++) { /* Update filter coeffs: convert LSF to poly */ if(i%params->filter_update_interval_vt == 0) { lsf2poly(LSF,A,i,params->use_hmm); for(j=0;j<params->lpc_order_vt+1;j++) { gsl_vector_set(A,j,gsl_vector_get(A,j)*(-1)); } gsl_vector_set(A,0,1); } /* Filter */ sum = 0; for(j=0;j<GSL_MIN(params->lpc_order_vt+1,i);j++) { sum += gsl_vector_get(excitation,i-j)*gsl_vector_get(A,j); } gsl_vector_set(excitation,i,sum); } gsl_vector_free(A); /* Warped filtering */ } else { int i,q,mlen; long int o; double xr,x,ffr,tmpr,Bb; double *sigma; long int len = params->signal_length; int adim = 1; int bdim = LSF->size2 + 1; double *Ar = (double *)calloc(adim,sizeof(double)); double *Br = (double *)calloc(bdim,sizeof(double)); double *ynr = (double *)calloc(excitation->size,sizeof(double)); double *rsignal = (double *)calloc(excitation->size,sizeof(double)); double *rmem = (double *)calloc(GSL_MAX(adim,bdim)+2,sizeof(double)); gsl_vector *B = gsl_vector_alloc(bdim); /* Set excitation to array */ for(i=0;i<len;i++) { rsignal[i] = gsl_vector_get(excitation,i); } /* Initialize */ Ar[0] = 1; Bb = 0; sigma = NFArray(bdim+2); if(adim >= bdim) mlen = adim; else mlen = bdim + 1; /* Warped filtering */ for(o=0;o<len;o++) { /* Update filter coefficients */ if(o%params->filter_update_interval_vt == 0) { lsf2poly(LSF,B,o,params->use_hmm); for(i=0;i<bdim;i++) { Br[i] = gsl_vector_get(B,i); } alphas2sigmas(Br,sigma,params->lambda_vt,bdim-1); Bb = 1/Br[0]; } xr = rsignal[o]*Bb; /* Update feedbackward sum */ for(q=0;q<bdim;q++) { xr -= sigma[q]*rmem[q]; } xr = xr/sigma[bdim]; x = xr*Ar[0]; /* Update inner states */ for(q=0;q<mlen;q++) { tmpr = rmem[q] + params->lambda_vt*(rmem[q+1] - xr); rmem[q] = xr; xr = tmpr; } /* Update feedforward sum */ for(q=0,ffr=0.0;q<adim-1;q++) { ffr += Ar[q+1]*rmem[q+1]; } /* Update output */ ynr[o] = x + ffr; } /* Set output to vector */ for(i=0;i<len;i++) { gsl_vector_set(excitation,i,ynr[i]); } /* Free memory */ free(ynr); free(rsignal); free(Ar); free(Br); free(rmem); free(sigma); gsl_vector_free(B); } } /** * Function LipRadiation * * Lip radiation * * @param excitation_voiced excitation * */ void LipRadiation(gsl_vector *excitation_voiced) { int i,j; double coeffs[2] = {1,-LIP_RADIATION}; double sum; gsl_vector *temp = gsl_vector_alloc(excitation_voiced->size); gsl_vector_memcpy(temp, excitation_voiced); for(i=0; i<excitation_voiced->size; i++) { sum = 0; for(j=0; j<=GSL_MIN(i, 1); j++) { sum += gsl_vector_get(excitation_voiced, i-j)*coeffs[j]; } gsl_vector_set(temp, i, sum); } for(i=0; i<excitation_voiced->size; i++) { gsl_vector_set(excitation_voiced, i, gsl_vector_get(temp, i)); } gsl_vector_free(temp); } /** * Function Differentiate * * Differentiate signal with leak * * @param signal signal to be differentiated * @param leak leaky parameter (e.g. 0.99) * */ void Differentiate(gsl_vector *signal, double leak) { int i,j; double coeffs[2] = {1,-leak}; double sum; gsl_vector *temp = gsl_vector_alloc(signal->size); gsl_vector_memcpy(temp, signal); for(i=0; i<signal->size; i++) { sum = 0; for(j=0; j<=GSL_MIN(i, 1); j++) { sum += gsl_vector_get(signal, i-j)*coeffs[j]; } gsl_vector_set(temp, i, sum); } for(i=0; i<signal->size; i++) { gsl_vector_set(signal, i, gsl_vector_get(temp, i)); } gsl_vector_free(temp); } /** * Function Differentiate_noleak * * Differentiate signal (no leakage) * * @param signal signal to be differentiated * */ void Differentiate_noleak(gsl_vector *signal) { int i,j; double coeffs[2] = {1,-1}; double sum; gsl_vector *temp = gsl_vector_alloc(signal->size); gsl_vector_memcpy(temp, signal); for(i=0; i<signal->size; i++) { sum = 0; for(j=0; j<=GSL_MIN(i, 1); j++) { sum += gsl_vector_get(signal, i-j)*coeffs[j]; } gsl_vector_set(temp, i, sum); } for(i=0; i<signal->size; i++) { gsl_vector_set(signal, i, gsl_vector_get(temp, i)); } gsl_vector_free(temp); } /** * Function Evaluate_new_gain * * Evaluate new gain for synthesis by comparing synthetic and original gains * * @param gain original gain * @param gain_new new gain * @param params */ void Evaluate_new_gain(gsl_vector *signal, gsl_vector *gain_new, gsl_vector *gain, gsl_vector *fundf, PARAM *params) { /* Estimate the gain of the synthetic signal */ Gain_eval(signal,gain_new,fundf,params); MA_voiced(gain_new,fundf,params->norm_gain_smooth_v_len); MA_unvoiced(gain_new,fundf,params->norm_gain_smooth_uv_len); /* Evaluate new gain for synthesis by comparing synthetic and original gains */ Modify_gain(gain_new,gain); } /** * Function Gain_eval * * Evaluate gain of a signal * * @param signal input signal * @param gain gain vector * @param fundf F0 vector * @param params * */ void Gain_eval(gsl_vector *signal, gsl_vector *gain, gsl_vector *fundf, PARAM *params) { int i,j; gsl_vector *frame = gsl_vector_alloc(rint(params->frame_length/params->speed)); int add = rint((params->frame_length/(double)params->shift/params->speed-1.0)*params->shift/params->speed/2.0); /* Zeropad signal */ gsl_vector *signal_zp = gsl_vector_calloc(signal->size + 2*add); for(i=0;i<signal->size;i++) gsl_vector_set(signal_zp,i+add,gsl_vector_get(signal,i)); /* Calculate gain vector */ for(i=0;i<gain->size;i++) { for(j=rint(i*params->shift/params->speed);j<GSL_MIN(rint(i*params->shift/params->speed+params->frame_length/params->speed),signal_zp->size-1);j++) { gsl_vector_set(frame,GSL_MIN(j-rint(i*params->shift/params->speed),frame->size-1),gsl_vector_get(signal_zp,j)); } if(gsl_vector_get(fundf,i) > 0) uvGain(frame,gain,i,NO_WINDOWING,rint(params->gain_voiced_frame_length/params->speed)); else uvGain(frame,gain,i,NO_WINDOWING,rint(params->gain_unvoiced_frame_length/params->speed)); } gsl_vector_free(frame); gsl_vector_free(signal_zp); } /** * Function Modify_gain * * Compare gain (gain) and synthetic gain (gain_new), and normalize the result inplace to gain_new * * @param gain_new synthetic gain * @param gain original gain * */ void Modify_gain(gsl_vector *gain_new, gsl_vector *gain) { int i; for(i=0;i<gain->size;i++) { gsl_vector_set(gain_new,i,gsl_vector_get(gain,i) + gsl_vector_get(gain,i) - gsl_vector_get(gain_new,i)); } } /** * Function Noise_reduction * * Reduce noise by reducing the gain of low level parts of the signal * * @param gain vector * @param params */ void Noise_reduction(gsl_vector *gain, PARAM *params) { /* Apply noise reduction */ if(params->noise_reduction_synthesis == 1) { int i; for(i=0;i<gain->size;i++) if(gsl_vector_get(gain,i) < params->noise_reduction_limit_db) gsl_vector_set(gain,i,gsl_vector_get(gain,i)-params->noise_reduction_db); } } /** * Function uvGain * * Calculate energy from potentially unvoiced frames (shorter window) * * @param frame pointer to the samples * @param gain vector for results * @param index time index * @param windowing switch for using windowing * @param unvoiced_frame_length */ void uvGain(gsl_vector *frame, gsl_vector *gain, int index, int windowing, int unvoiced_frame_length) { int i,cntr; double sum; gsl_vector *uvframe = gsl_vector_alloc(unvoiced_frame_length); /* Take shorter frame for unvoiced analysis */ cntr = rint((frame->size-unvoiced_frame_length)/2.0); for(i=0;i<unvoiced_frame_length;i++) gsl_vector_set(uvframe,i,gsl_vector_get(frame,i+cntr)); /* Windowing switch */ if(windowing == 1) { /* Windowing */ for(i=0;i<uvframe->size;i++) gsl_vector_set(uvframe,i,gsl_vector_get(uvframe,i)*HANN(i,uvframe->size)); /* Evaluate gain of uvframe, normalize energy per sample basis */ sum = 0; for(i=0;i<uvframe->size;i++) { sum = sum + gsl_vector_get(uvframe,i)*gsl_vector_get(uvframe,i); } gsl_vector_set(gain, index, 10.0*log10((8.0/3.0)*sum/E_REF/((double)(uvframe->size)))); } else { /* Evaluate gain of frame, normalize energy per sample basis */ sum = 0; for(i=0;i<uvframe->size;i++) { sum = sum + gsl_vector_get(uvframe,i)*gsl_vector_get(uvframe,i); } gsl_vector_set(gain, index, 10.0*log10(sum/E_REF/((double)(uvframe->size)))); } /* Ensure non-infinity values */ if(isinf(gsl_vector_get(gain,index)) != 0) gsl_vector_set(gain,index,MIN_LOG_POWER); /* Free memory */ gsl_vector_free(uvframe); } /** * Function Smooth_matrix * * Moving average smoothing for matrix parameters * * @param matrix matrix to smooth * @param len smoothing length in samples * */ void Smooth_matrix(gsl_matrix *matrix, int len) { if(matrix == NULL) return; int i,j; gsl_vector *temp = gsl_vector_alloc(matrix->size1); for(i=0;i<matrix->size2;i++) { for(j=0;j<matrix->size1;j++) { gsl_vector_set(temp,j,gsl_matrix_get(matrix,j,i)); } MA(temp,len); for(j=0;j<matrix->size1;j++) { gsl_matrix_set(matrix,j,i,gsl_vector_get(temp,j)); } } gsl_vector_free(temp); } /** * Function Spectral_match * * Match the synthetic excitation spectrum to real one (normal/warped) * * @param signal excitation vector * @param flow original glottal flow spectrum * @param flow_new synthetic glottal flow spectrum * @param * */ void Spectral_match(gsl_vector *signal, gsl_matrix *flow, gsl_matrix *flow_new, PARAM *params) { /* Do not perform if noise robust speech is used */ if(params->noise_robust_speech == 1) return; /* Normal filtering */ if(params->lambda_gl == 0) { int i,j; double sum; /* Check compatibility */ if(params->lpc_order_gl < MIN_P_TILT) { printf("\n Warning: The degree of spectral model is too low - spectral matching is not performed!\n\n"); return; } /* Smooth and interpolate glottal flow spectra */ gsl_matrix *flow_i = gsl_matrix_alloc(params->signal_length,params->lpc_order_gl); gsl_matrix *flow_new_i = gsl_matrix_alloc(params->signal_length,params->lpc_order_gl); Smooth_interp_lsf(flow_i,flow,params->signal_length,params->use_hmm,params->glflowsp_smooth_len); Smooth_interp_lsf(flow_new_i,flow_new,params->signal_length,0,params->glflowsp_smooth_len); // Smooth always flow_new /* Initialize spectral correction */ gsl_vector *A = gsl_vector_alloc(params->lpc_order_gl+1); gsl_vector *B = gsl_vector_alloc(params->lpc_order_gl+1); gsl_vector *signal_orig = gsl_vector_alloc(params->signal_length); gsl_vector_memcpy(signal_orig, signal); /* Spectral correction */ for(i=0;i<params->signal_length;i++) { /* Update filter coeffs: convert LSF to poly */ if(i%params->filter_update_interval_gl == 0) { lsf2poly(flow_new_i,A,i,params->use_hmm); lsf2poly(flow_i,B,i,params->use_hmm); gsl_vector_set(B,0,0); } /* Filter */ sum = 0; for(j=0;j<GSL_MIN(params->lpc_order_gl+1,i);j++) { sum += gsl_vector_get(signal_orig,i-j)*gsl_vector_get(A,j) - gsl_vector_get(signal,i-j)*gsl_vector_get(B,j); } gsl_vector_set(signal,i,sum); } /* Free memory */ gsl_matrix_free(flow_new_i); gsl_matrix_free(flow_i); gsl_vector_free(signal_orig); gsl_vector_free(A); gsl_vector_free(B); /* Warped filtering */ } else { /* Check compatibility */ if(params->lpc_order_gl+1 < MIN_P_TILT-1) { printf("\n Warning: The degree of spectral model is too low - spectral matching is not performed!\n\n"); return; } int i,q,mlen; long int o; double xr,x,ffr,tmpr,Bb; double *sigma; long int len = params->signal_length; int adim = params->lpc_order_gl + 1; int bdim = params->lpc_order_gl + 1; double *Ar = (double *)calloc(adim,sizeof(double)); double *Br = (double *)calloc(bdim,sizeof(double)); double *ynr = (double *)calloc(len,sizeof(double)); double *rsignal = (double *)calloc(len,sizeof(double)); double *rmem = (double *)calloc((bdim+2),sizeof(double)); gsl_vector *A = gsl_vector_alloc(adim); gsl_vector *B = gsl_vector_alloc(bdim); /* Smooth and interpolate glottal flow spectrums */ gsl_matrix *flow_i = gsl_matrix_alloc(params->signal_length,params->lpc_order_gl); gsl_matrix *flow_new_i = gsl_matrix_alloc(params->signal_length,params->lpc_order_gl); Smooth_interp_lsf(flow_i,flow,len,params->use_hmm,params->glflowsp_smooth_len); Smooth_interp_lsf(flow_new_i,flow_new,len,0,params->glflowsp_smooth_len); // Smooth always flow_new /* Set signal to array */ for(i=0;i<len;i++) { rsignal[i] = gsl_vector_get(signal,i); } /* Initialize */ sigma = NFArray(bdim+2); Bb = 0; if(adim >= bdim) mlen = adim; else mlen = bdim + 1; /* Warped filtering */ for(o=0;o<len;o++) { /* Update filter coefficients */ if(o%params->filter_update_interval_gl == 0) { lsf2poly(flow_new_i,A,o,params->use_hmm); lsf2poly(flow_i,B,o,params->use_hmm); for(i=0;i<adim;i++) { Ar[i] = gsl_vector_get(A,i); } for(i=0;i<bdim;i++) { Br[i] = gsl_vector_get(B,i); } alphas2sigmas(Br,sigma,params->lambda_gl,bdim-1); Bb = 1/Br[0]; } xr = rsignal[o]*Bb; /* Update feedbackward sum */ for(q=0;q<bdim;q++) { xr -= sigma[q]*rmem[q]; } xr = xr/sigma[bdim]; x = xr*Ar[0]; /* Update inner states */ for(q=0;q<mlen;q++) { tmpr = rmem[q] + params->lambda_gl*(rmem[q+1] - xr); rmem[q] = xr; xr = tmpr; } /* Update feedforward sum */ for(q=0,ffr=0.0;q<adim-1;q++) { ffr += Ar[q+1]*rmem[q+1]; } /* Update output */ ynr[o] = x + ffr; } /* Set output to vector */ for(i=0;i<len;i++) { gsl_vector_set(signal,i,ynr[i]); } /* Free memory */ free(ynr); free(rsignal); free(Ar); free(Br); free(rmem); free(sigma); gsl_matrix_free(flow_i); gsl_matrix_free(flow_new_i); gsl_vector_free(A); gsl_vector_free(B); } } /** * Function alphas2sigmas * * Convert alhas to sigmas. * * @param alp alphas * @param sigm sigmas * @param lambda warping coefficient * @param dim dimension * */ void alphas2sigmas(double *alp, double *sigm, double lambda, int dim) { int q; double S=0,Sp; sigm[dim] = lambda*alp[dim]/alp[0]; Sp = alp[dim]/alp[0]; for(q=dim;q>1;q--) { S = alp[q-1]/alp[0] - lambda*Sp; sigm[q-1] = lambda*S + Sp; Sp = S; } sigm[0] = S; sigm[dim+1] = 1 - lambda*S; } /** * Function NFArray * * Create array. * * @param size * @return array * */ double *NFArray(int size) { double *p; p = (double *)calloc(sizeof(*p),size); return p; } /** * Function Scale_signal * * Scale signal if maximum value is greater than 1.0 * * @param signal */ void Scale_signal(gsl_vector *signal, int mode) { /* Evaluate the absolute maximum of the signal */ int i; double absmax = GSL_MAX(gsl_vector_max(signal),-gsl_vector_min(signal)); /* Scale maximum to one if absmax is greater than one */ if(mode == SCALE_IF_GREATER_THAN_ONE && absmax > 1.0) { printf(" Maximum value of the signal (%1.3lf) is greater than 1.0. Signal values rescaled!\n",absmax); absmax = WAV_SCALE/absmax; for(i=0;i<signal->size;i++) gsl_vector_set(signal,i,gsl_vector_get(signal,i)*absmax); } /* Scale absmax of signal to one */ if(mode == FORCE_MAX_TO_ONE) { absmax = WAV_SCALE/absmax; for(i=0;i<signal->size;i++) gsl_vector_set(signal,i,gsl_vector_get(signal,i)*absmax); } } /** * Function Save_signal_to_file * * Save signal to file * * @param signal * @param params */ int Save_signal_to_file(gsl_vector *signal, PARAM *params, char *alternative_filename_ending) { /* Copy values to array */ double *samples = (double *)calloc(params->signal_length, sizeof(double)); int i; for(i=0;i<params->signal_length;i++) samples[i] = gsl_vector_get(signal,i); /* Save synthesized speech to wav-file */ SNDFILE *soundfile; SF_INFO sfinfo; sfinfo.samplerate = params->FS; sfinfo.channels = 1; sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16; char temp[DEF_STRING_LEN]; strcpy(temp, params->synlist[params->synfilenumber]); /* Open file with default ending or givend ending */ if(alternative_filename_ending == NULL) soundfile = sf_open(strcat(temp,FILENAME_ENDING_SYNTHESIS), SFM_WRITE, &sfinfo); else soundfile = sf_open(strcat(temp,alternative_filename_ending), SFM_WRITE, &sfinfo); /* Check if success */ if(soundfile==NULL) { printf("\n\nError creating file \"%s\": %s\n\n",temp,strerror(errno)); return EXIT_FAILURE; } /* Write to file */ sf_write_double(soundfile, samples, params->signal_length); /* Free memory */ free(samples); sf_close(soundfile); return EXIT_SUCCESS; } /** * Function WLPC * * Calculate Warped Linear Prediction (WLP) coefficients using * autocorrelation method. * * @param frame pointer to the samples * @param a pointer to coefficiets * @param p LPC degree * @param lambda warping coefficient * @return pointer to the WLP-coefficients */ gsl_vector *WLPC(gsl_vector *frame, int p, double lambda) { int i,j,s; double win = 0; gsl_vector *a = gsl_vector_alloc(p+1); gsl_vector *wframe = gsl_vector_alloc(frame->size); gsl_vector *a_temp = gsl_vector_calloc(p); gsl_vector *r = gsl_vector_calloc(p+1); gsl_vector *b = gsl_vector_alloc(p); gsl_matrix *R = gsl_matrix_alloc (p, p); gsl_permutation *perm = gsl_permutation_alloc(p); /* Windowing (choose window) */ for(i=0; i<frame->size; i++) { if (WIN_TYPE == HANN_WIN) win = HANN(i,frame->size); else if (WIN_TYPE == BLACKMAN_WIN) win = BLACKMAN(i,frame->size); else if (WIN_TYPE == HAMMING_WIN) win = HAMMING(i,frame->size); else win = 1.0; gsl_vector_set(wframe, i, gsl_vector_get(frame, i)*win); } /* Copy warped frame */ gsl_vector *wframe_w = gsl_vector_alloc(wframe->size); gsl_vector_memcpy(wframe_w,wframe); /* Set r(0) */ for(i=0;i<wframe->size;i++) { gsl_vector_set(r, 0, gsl_vector_get(r,0) + gsl_vector_get(wframe,i)*gsl_vector_get(wframe,i)); } /* Evaluate r */ for(i=1;i<p+1;i++) { AllPassDelay(wframe_w,lambda); for(j=0;j<wframe->size;j++) { gsl_vector_set(r, i, gsl_vector_get(r,i) + gsl_vector_get(wframe,j)*gsl_vector_get(wframe_w,j)); } } /* Autocorrelation matrix (Toeplitz) */ for(i=0; i<p;i++) { for(j=0; j<p; j++) { gsl_matrix_set(R, i, j, gsl_vector_get(r, abs(i-j))); } } /* Vector b */ for(i=1; i<p+1; i++) { gsl_vector_set(b, i-1, gsl_vector_get(r, i)); } /* Ra=r solver (LU-decomposition) */ gsl_linalg_LU_decomp(R, perm, &s); gsl_linalg_LU_solve(R, perm, b, a_temp); /* Construct vector a and return */ for(i=1;i<p+1;i++) { gsl_vector_set(a, i, -1.0*gsl_vector_get(a_temp,i-1)); } gsl_vector_set(a,0,1); /* Replace NaN-values with zeros in case of all-zero frames */ for(i=0;i<a->size;i++) { if(gsl_isnan(gsl_vector_get(a,i))) gsl_vector_set(a,i,0); } /* Free memory */ gsl_vector_free(wframe); gsl_vector_free(wframe_w); gsl_vector_free(a_temp); gsl_vector_free(r); gsl_vector_free(b); gsl_matrix_free(R); gsl_permutation_free(perm); return a; } /** * Function AllPassDelay * * All pass delay filter for WLPC. * * @param signal pointer to the samples * @param lambda all-pass filter coefficient */ void AllPassDelay(gsl_vector *signal, double lambda) { int i,j,n=2; double sum; /* Create coefficient arrays: B = [-lambda 1], A = [1 -lambda] */ double B[2] = {-lambda,1.0}; double A[2] = {0,lambda}; /* Zeropad the beginning of the signal */ gsl_vector *signal_zp = gsl_vector_calloc(signal->size+n); for(i=n;i<signal_zp->size;i++) { gsl_vector_set(signal_zp,i,gsl_vector_get(signal,i-n)); } /* Copy vector signal */ gsl_vector *signal_zp_orig = gsl_vector_alloc(signal_zp->size); gsl_vector_memcpy(signal_zp_orig,signal_zp); /* Filter */ for(i=n;i<signal_zp->size;i++) { sum = 0; for(j=0;j<n;j++) { sum += gsl_vector_get(signal_zp_orig,i-j)*B[j] + gsl_vector_get(signal_zp,i-j)*A[j]; } gsl_vector_set(signal_zp,i,sum); } /* Remove zeropadding from the signal */ for(i=n;i<signal_zp->size;i++) { gsl_vector_set(signal,i-n,gsl_vector_get(signal_zp,i)); } /* Free memory */ gsl_vector_free(signal_zp); gsl_vector_free(signal_zp_orig); } /** * Function SWLP * * Calculate Stabilized Weighted Linear Prediction (SWLP) coefficients * (unstabilized can be evaluated by switching "stabilized" to zero) * * @param frame pointer to the samples * @param a pointer to coefficiets * @param p LPC degree * @param M weighting window length * @param lag lag of the weighting window */ void SWLP(gsl_vector *frame, gsl_vector *a, int M, int lag, int weighting, gsl_vector *fundf, int FS, int index, gsl_vector *glottsig, int stabilized) { int i,j,k,s,p = a->size-1; double win = 0,sum = 0; gsl_vector *wframe = gsl_vector_alloc(frame->size); gsl_vector *weight = gsl_vector_calloc(frame->size+p); /* Windowing (choose window) */ for(i=0; i<frame->size; i++) { if (WIN_TYPE == HANN_WIN) win = HANN(i,frame->size); else if (WIN_TYPE == BLACKMAN_WIN) win = BLACKMAN(i,frame->size); else if (WIN_TYPE == HAMMING_WIN) win = HAMMING(i,frame->size); else win = 1.0; gsl_vector_set(wframe, i, gsl_vector_get(frame, i)*win); } /* Evaluate weighting function */ if(weighting == 0) Eval_STE_weight(wframe,weight,M,lag); else Eval_GCI_weight(glottsig,weight,fundf,FS,index); /* Create partial weights */ gsl_matrix *Z = gsl_matrix_calloc(wframe->size+p,p+1); // Partial weights gsl_matrix *Y = gsl_matrix_calloc(wframe->size+p,p+1); // Delayed and weighted versions of the signal for(i=0;i<weight->size;i++) gsl_matrix_set(Z,i,0,sqrt(gsl_vector_get(weight,i))); for(i=0;i<wframe->size;i++) gsl_matrix_set(Y,i,0,gsl_vector_get(wframe,i)*sqrt(gsl_vector_get(weight,i))); for(i=0;i<p;i++) { if(stabilized == 1) { for(j=i+1;j<Z->size1;j++) { gsl_matrix_set(Z,j,i+1,GSL_MAX(sqrt(gsl_vector_get(weight,j)/gsl_vector_get(weight,j-1)),1)*gsl_matrix_get(Z,j-1,i)); } } else { for(j=i+1;j<Z->size1;j++) { gsl_matrix_set(Z,j,i+1,sqrt(gsl_vector_get(weight,j))); } } for(j=0;j<wframe->size;j++) { gsl_matrix_set(Y,j+i+1,i+1,gsl_matrix_get(Z,j+i+1,i+1)*gsl_vector_get(wframe,j)); } } /* Autocorrelation matrix R (R = (YT*Y)/N, size p*p) and vector b (size p) */ gsl_matrix *R = gsl_matrix_calloc(p,p); gsl_vector *b = gsl_vector_calloc(p); for(i=0;i<Y->size2;i++) { for(j=0;j<Y->size2;j++) { if(i > 0 && j > 0) { for(k=0;k<Y->size1;k++) { gsl_matrix_set(R,i-1,j-1,gsl_matrix_get(R,i-1,j-1) + gsl_matrix_get(Y,k,i)*gsl_matrix_get(Y,k,j)); } gsl_matrix_set(R,i-1,j-1,gsl_matrix_get(R,i-1,j-1)/wframe->size); } if(i > 0 && j == 0) { for(k=0;k<Y->size1;k++) gsl_vector_set(b,i-1,gsl_vector_get(b,i-1) + gsl_matrix_get(Y,k,i)*gsl_matrix_get(Y,k,j)); gsl_vector_set(b,i-1,gsl_vector_get(b,i-1)/wframe->size); sum += gsl_vector_get(b,i-1); } } } /* Ra=r solver (LU-decomposition) (Do not evaluate LU if sum = 0) */ gsl_vector *a_temp = gsl_vector_calloc(p); gsl_permutation *perm = gsl_permutation_alloc(p); if(sum != 0) { gsl_linalg_LU_decomp(R, perm, &s); gsl_linalg_LU_solve(R, perm, b, a_temp); } /* Set LP-coefficients to vector "a" */ for(i=1; i<a->size; i++) { gsl_vector_set(a, i, (-1)*gsl_vector_get(a_temp, i-1)); } gsl_vector_set(a, 0, 1); /* Stabilize through LSFs if the method itself is not guaranteed to produce a stable filter */ if(stabilized == 0) LSF_stabilize(a); /* Free memory */ gsl_vector_free(weight); gsl_vector_free(wframe); gsl_matrix_free(Z); gsl_matrix_free(Y); gsl_matrix_free(R); gsl_vector_free(b); gsl_vector_free(a_temp); gsl_permutation_free(perm); } /** * Function LSF_stabilize * * Check the validity of polynomial through LSFs and fix found errors * * @param lsf vector */ void LSF_stabilize(gsl_vector *a) { gsl_vector *lsf = gsl_vector_calloc(a->size-1); Convert_vector_to_LSF(a, lsf); LSF_fix_vector(lsf); lsf_vector2poly(lsf,a); } /** * Function Convert_vector_to_LSF * * Convert LPC-coefficients to Line Spectrum Frequencies (LSF) * Maximum LPC-polynomial degree is 36! * * * @param a pointer to LPC-vector * @param LSF pointer to the LSF matrix * */ void Convert_vector_to_LSF(gsl_vector *a, gsl_vector *LSF) { int i,n; /* Count the number of nonzero elements in "a" */ n = 0; for(i=0; i<a->size; i++) { if(gsl_vector_get(a, i) != 0) { n++; } } /* In case of only one non-zero element */ if(n == 1) { for(i=0; i<LSF->size; i++) gsl_vector_set(LSF, i, (i+1)*M_PI/LSF->size); return; } gsl_vector *aa = gsl_vector_calloc(n+1); gsl_vector *flip_aa = gsl_vector_calloc(n+1); gsl_vector *p = gsl_vector_calloc(n+1); gsl_vector *q = gsl_vector_calloc(n+1); /* Construct vectors aa=[a 0] and flip_aa=[0 flip(a)] */ for(i=0; i<n; i++) { gsl_vector_set(aa, i, gsl_vector_get(a, i)); gsl_vector_set(flip_aa, flip_aa->size-1-i, gsl_vector_get(a, i)); } /* Construct vectors p and q */ for(i=0; i<n+1; i++) { gsl_vector_set(p, i, gsl_vector_get(aa, i) + gsl_vector_get(flip_aa, i)); gsl_vector_set(q, i, gsl_vector_get(aa, i) - gsl_vector_get(flip_aa, i)); } /* Remove trivial zeros */ if((n+1)%2 == 0) { double y; /* Deconvolve p with [1 1] */ y = 0; for(i=0; i<p->size; i++) { gsl_vector_set(p, i, gsl_vector_get(p, i)-y); y = gsl_vector_get(p, i); } gsl_vector_set(p, p->size-1, 0); /* Deconvolve q with [1 -1] */ y = 0; for(i=0; i<q->size; i++) { gsl_vector_set(q, i, gsl_vector_get(q, i)+y); y = gsl_vector_get(q, i); } gsl_vector_set(q, q->size-1, 0); } else { double y; /* Deconvolve q with [1 1] */ y = 0; for(i=0; i<q->size; i++) { gsl_vector_set(q, i, gsl_vector_get(q, i)-y); y = gsl_vector_get(q, i); } /* Deconvolve q with [1 -1] */ y = 0; for(i=0; i<q->size; i++) { gsl_vector_set(q, i, gsl_vector_get(q, i)+y); y = gsl_vector_get(q, i); } gsl_vector_set(q, q->size-1, 0); gsl_vector_set(q, q->size-2, 0); } /* Count the number of nonzero elements in "p" and "q" */ int n_p = 0; int n_q = 0; for(i=0; i<p->size; i++) { if(gsl_vector_get(p, i) != 0) n_p++; if(gsl_vector_get(q, i) != 0) n_q++; } /* Take the last half of "p" and "q" to vectors "TP" and "TQ" */ gsl_vector *TP = gsl_vector_alloc((n_p+1)/2); gsl_vector *TQ = gsl_vector_alloc((n_q+1)/2); for(i=0; i<TP->size; i++) { gsl_vector_set(TP, i, gsl_vector_get(p, i+(n_p-1)/2)); } for(i=0; i<TQ->size; i++) { gsl_vector_set(TQ, i, gsl_vector_get(q, i+(n_q-1)/2)); } /* Chebyshev transform */ Chebyshev(TP); Chebyshev(TQ); /* Initialize root arrays */ int nroots_TP = 2*(TP->size-1); int nroots_TQ = 2*(TQ->size-1); double TP_coeffs[TP->size]; double TQ_coeffs[TQ->size]; double TP_roots[nroots_TP]; double TQ_roots[nroots_TQ]; /* Copy coefficients to arrays */ for(i=0; i<TP->size; i++) { TP_coeffs[i] = gsl_vector_get(TP, i); } for(i=0; i<TQ->size; i++) { TQ_coeffs[i] = gsl_vector_get(TQ, i); } /* Solve roots */ gsl_poly_complex_workspace *w_TP = gsl_poly_complex_workspace_alloc(TP->size); gsl_poly_complex_workspace *w_TQ = gsl_poly_complex_workspace_alloc(TQ->size); gsl_poly_complex_solve(TP_coeffs, TP->size, w_TP, TP_roots); gsl_poly_complex_solve(TQ_coeffs, TQ->size, w_TQ, TQ_roots); /* Convert to LSF and sort */ double sorted_LSF[(nroots_TP+nroots_TQ)/2]; for(i=0; i<nroots_TP; i=i+2) { sorted_LSF[i/2] = acos(TP_roots[i]/2); } for(i=0; i<nroots_TQ; i=i+2) { sorted_LSF[(i+nroots_TP)/2] = acos(TQ_roots[i]/2); } gsl_sort(sorted_LSF, 1, (nroots_TP+nroots_TQ)/2); /* Copy LSFs to vector LSF */ for(i=0; i<(nroots_TP+nroots_TQ)/2; i++) gsl_vector_set(LSF, i, sorted_LSF[i]); /* Free memory */ gsl_poly_complex_workspace_free(w_TP); gsl_poly_complex_workspace_free(w_TQ); gsl_vector_free(aa); gsl_vector_free(flip_aa); gsl_vector_free(p); gsl_vector_free(q); gsl_vector_free(TP); gsl_vector_free(TQ); } /** * Function lsf_vector2poly * * Convert LSF vector to polynomial * * @param lsf_vector * @param poly * @param index * @param HMM switch for HMM */ void lsf_vector2poly(gsl_vector *lsf_vector, gsl_vector *poly) { int i,l = lsf_vector->size; gsl_vector *fi_p = NULL, *fi_q = NULL; /* Create fi_p and fi_q */ if(l%2 == 0) { fi_p = gsl_vector_alloc(l/2); fi_q = gsl_vector_alloc(l/2); for(i=0;i<l;i=i+2) { gsl_vector_set(fi_p,i/2,gsl_vector_get(lsf_vector,i)); } for(i=1;i<l;i=i+2) { gsl_vector_set(fi_q,(i-1)/2,gsl_vector_get(lsf_vector,i)); } } else { fi_p = gsl_vector_alloc((l+1)/2); for(i=0;i<l;i=i+2) { gsl_vector_set(fi_p,i/2,gsl_vector_get(lsf_vector,i)); } if((l-1)/2 > 0) { fi_q = gsl_vector_alloc((l-1)/2); for(i=1;i<l-1;i=i+2) { gsl_vector_set(fi_q,(i-1)/2,gsl_vector_get(lsf_vector,i)); } } } /* Construct vectors P and Q */ gsl_vector *cp = gsl_vector_calloc(3); gsl_vector *cq = gsl_vector_calloc(3); gsl_vector_add_constant(cp,1); gsl_vector_add_constant(cq,1); gsl_vector *P = gsl_vector_alloc(1); gsl_vector *Q = gsl_vector_alloc(1); gsl_vector_set(P,0,1); gsl_vector_set(Q,0,1); for(i=0;i<fi_p->size;i++) { gsl_vector_set(cp,1,-2*cos(gsl_vector_get(fi_p,i))); P = Conv(P,cp); } if((l-1)/2 > 0) { for(i=0;i<fi_q->size;i++) { gsl_vector_set(cq,1,-2*cos(gsl_vector_get(fi_q,i))); Q = Conv(Q,cq); } } /* Add trivial zeros */ if(l%2 == 0) { gsl_vector *conv = gsl_vector_calloc(2); gsl_vector_add_constant(conv,1); P = Conv(P,conv); gsl_vector_set(conv,0,-1); Q = Conv(Q,conv); gsl_vector_free(conv); } else { gsl_vector *conv = gsl_vector_calloc(3); gsl_vector_set(conv,0,-1); gsl_vector_set(conv,2,1); Q = Conv(Q,conv); gsl_vector_free(conv); } /* Construct polynomial */ for(i=1;i<P->size;i++) { gsl_vector_set(poly,P->size-i-1,0.5*(gsl_vector_get(P,i)+gsl_vector_get(Q,i))); } /* Free memory */ gsl_vector_free(fi_p); if((l-1)/2 > 0) gsl_vector_free(fi_q); gsl_vector_free(cp); gsl_vector_free(cq); gsl_vector_free(P); gsl_vector_free(Q); } /** * Function Eval_STE_weight * * Evaluate short time energy (STE) function for SWLP weighting * * @param frame pointer to the frame * @param ste pointer to the STE function * @param M weighting window length * @param lag time lag of estimating the STE */ void Eval_STE_weight(gsl_vector *frame, gsl_vector *ste, int M, int lag) { int i,j; for(i=0;i<ste->size;i++) { for(j=GSL_MAX(i-lag-M+1,0);j<GSL_MIN(i-lag+1,(int)frame->size);j++) { gsl_vector_set(ste,i,gsl_vector_get(ste,i) + gsl_vector_get(frame,j)*gsl_vector_get(frame,j)); } gsl_vector_set(ste,i,gsl_vector_get(ste,i) + DBL_EPSILON); } } /** * Function Eval_GCI_weight * * Find GCIs (Glottal Closure Instants) and construct weighting for de-emphasizing GCIs in (S)WLP * * @param ... * */ void Eval_GCI_weight(gsl_vector *glottsig, gsl_vector *weight, gsl_vector *fundf, int FS, int index) { /* Estimate glottal closure instants */ gsl_vector *inds = Find_GCI(glottsig, fundf, FS, index); /* If unvoiced or GCIs not found, simply set weight to 1 */ if(inds == NULL || gsl_vector_get(fundf,index) == 0) { if(inds != NULL) gsl_vector_free(inds); gsl_vector_set_all(weight,1); return; } /* Algorithm parameters */ double closed_time = 0.4; double gci_pos = 0.8; double deemph = 0.01; /* Initialize */ int i,j; int csamples = rint(closed_time*FS/gsl_vector_get(fundf,index)); /* Set weight according to GCIs */ gsl_vector_set_all(weight,1); for(i=0;i<inds->size;i++) { for(j=0;j<csamples;j++) { gsl_vector_set(weight,GSL_MIN(GSL_MAX(gsl_vector_get(inds,i)-rint(csamples*gci_pos)+j,0),weight->size-1),deemph); } } /* Free memory */ gsl_vector_free(inds); } /** * Function Find_GCI * * Find GCIs (Glottal Closure Instants) * * @param ... * */ gsl_vector *Find_GCI(gsl_vector *frame_orig, gsl_vector *fundf, int FS, int index) { int i,j,min_ind,ind_ind,t0_tmp; double t0,min_val,temp; gsl_vector *indices = gsl_vector_calloc(100); gsl_vector *final_inds; gsl_vector *frame = gsl_vector_calloc(frame_orig->size); gsl_vector_memcpy(frame,frame_orig); /* Differentiate frame and find minimum */ Differentiate(frame,LEAK); min_ind = gsl_vector_min_index(frame); /* Find t0 minima of the glottal waveform in order to find GCIs, * start evaluating from the mimina, first backward, then forward */ t0 = FS/gsl_vector_get(fundf,index); gsl_vector_set(indices,50,min_ind); t0_tmp = min_ind; ind_ind = 51; /* Backward */ temp = 0; ind_ind = 51; while(1) { t0_tmp = rint(gsl_vector_get(indices,ind_ind-1) - t0 - temp); if(t0_tmp < 0) break; min_val = BIG_POS_NUMBER; for(i=-20;i<21;i++) { if(gsl_vector_get(frame,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)) < min_val) { min_val = gsl_vector_get(frame,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)); gsl_vector_set(indices,ind_ind,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)); } } if(gsl_vector_get(indices,ind_ind-1)-gsl_vector_get(indices,ind_ind) < t0/2.0) { temp = temp + t0; } else { ind_ind++; temp = 0; } } /* Forward */ temp = 0; ind_ind = 49; while(1) { t0_tmp = rint(gsl_vector_get(indices,ind_ind+1) + t0 + temp); if(t0_tmp > frame->size-1) break; min_val = BIG_POS_NUMBER; for(i=-20;i<21;i++) { if(gsl_vector_get(frame,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)) < min_val) { min_val = gsl_vector_get(frame,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)); gsl_vector_set(indices,ind_ind,GSL_MIN(GSL_MAX(t0_tmp + i,0),frame->size-1)); } } if(gsl_vector_get(indices,ind_ind)-gsl_vector_get(indices,ind_ind+1) < t0/2.0) { temp = temp + t0; } else { ind_ind--; temp = 0; } } /* Sort indices */ gsl_sort_vector(indices); /* Allocate vector for non-zero indices and return */ i = 0; while(gsl_vector_get(indices,indices->size-1-i) > 0) i += 1; if(i < 2) { gsl_vector_free(indices); gsl_vector_free(frame); return NULL; } else { final_inds = gsl_vector_alloc(i); for(j=0;j<i;j++) gsl_vector_set(final_inds,j,gsl_vector_get(indices,indices->size-i+j)); gsl_vector_free(indices); gsl_vector_free(frame); return final_inds; } } /** * Function Interpolate * * Interpolates given vector to new vector of given length * * @param vector original vector * @param i_vector interpolated vector */ void Interpolate(gsl_vector *vector, gsl_vector *i_vector) { int i,len = vector->size,length = i_vector->size; /* Read values to array */ double x[len]; double y[len]; for(i=0; i<len; i++) { x[i] = i; y[i] = gsl_vector_get(vector,i); } gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline,len); gsl_spline_init(spline, x, y, len); double xi; i = 0; /* New implementation (27.3.2009, bug fix 8.2.2010) */ /* Bug fix to GSL v.1.15, 26.1.2012 */ xi = x[0]; while(i<length) { gsl_vector_set(i_vector,i,gsl_spline_eval(spline, xi, acc)); xi += (len-1)/(double)(length-1); if(xi > len-1) xi = len-1; i++; } /* Free memory */ gsl_spline_free(spline); gsl_interp_accel_free(acc); } /** * Function Interpolate_matrix * * Interpolates given matrix to new matrix of given length * * @param matrix original matrix * @param imatrix interpolated matrix */ void Interpolate_matrix(gsl_matrix *matrix, gsl_matrix *imatrix) { int i,j; gsl_vector *ivec = gsl_vector_alloc(imatrix->size1); for(i=0;i<matrix->size2;i++) { gsl_vector_view column = gsl_matrix_column(matrix,i); Interpolate((gsl_vector *)(&column),ivec); for(j=0;j<ivec->size;j++) gsl_matrix_set(imatrix,j,i,gsl_vector_get(ivec,j)); } gsl_vector_free(ivec); } /** * Function Interpolate_lin * * Interpolates linearly given vector to new vector of given length * * @param vector original vector * @param i_vector interpolated vector */ void Interpolate_lin(gsl_vector *vector, gsl_vector *i_vector) { int i,len = vector->size,length = i_vector->size; /* Read values to array */ double x[len]; double y[len]; for(i=0; i<len; i++) { x[i] = i; y[i] = gsl_vector_get(vector,i); } gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline *spline = gsl_spline_alloc(gsl_interp_linear, len); gsl_spline_init(spline, x, y, len); double xi; i = 0; /* New implementation (27.3.2009, bug fix 8.2.2010) */ /* Bug fix to GSL v.1.15, 26.1.2012 */ xi = x[0]; while(i<length) { gsl_vector_set(i_vector,i,gsl_spline_eval(spline, xi, acc)); xi += (len-1)/(double)(length-1); if(xi > len-1) xi = len-1; i++; } /* Free memory */ gsl_spline_free(spline); gsl_interp_accel_free(acc); } /** * Function Interpolate_fract * * Interpolates given vector to new vector of given fractional length * * @param vector original vector * @param i_vector interpolated vector * @param flen fractional length */ void Interpolate_fract(gsl_vector *vector, gsl_vector *i_vector, double flen) { int i,len = vector->size,length = i_vector->size; /* Read values to array */ double x[len]; double y[len]; for(i=0; i<len; i++) { x[i] = i; y[i] = gsl_vector_get(vector,i); } gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline,len); gsl_spline_init(spline, x, y, len); double xi = x[0]; i = 0; while(i<length) { gsl_vector_set(i_vector,i,gsl_spline_eval(spline, xi, acc)); xi += (len-1)/(flen-1.0); if(xi > len-1) xi = len-1; i++; } /* Free memory */ gsl_spline_free(spline); gsl_interp_accel_free(acc); } /** * Function Convert_to_LSF * * Converts the LPC-coefficients to Line Spectrum Frequencies (LSF) * Maximum LPC-polynomial degree is 36! * * @param LSF pointer to the LSF matrix * @param a pointer to LPC-vector * @param index time index * */ void Convert_to_LSF(gsl_matrix *LSF, gsl_vector *a, int index) { int i,n; /* Count the number of nonzero elements in "a" */ n = 0; for(i=0; i<a->size; i++) { if(gsl_vector_get(a, i) != 0) { n++; } } /* In case of only one non-zero element */ if(n == 1) { for(i=0; i<LSF->size2; i++) gsl_matrix_set(LSF, index, i, (i+1)*M_PI/LSF->size2); return; } gsl_vector *aa = gsl_vector_calloc(n+1); gsl_vector *flip_aa = gsl_vector_calloc(n+1); gsl_vector *p = gsl_vector_calloc(n+1); gsl_vector *q = gsl_vector_calloc(n+1); /* Construct vectors aa=[a 0] and flip_aa=[0 flip(a)] */ for(i=0; i<n; i++) { gsl_vector_set(aa, i, gsl_vector_get(a, i)); gsl_vector_set(flip_aa, flip_aa->size-1-i, gsl_vector_get(a, i)); } /* Construct vectors p and q */ for(i=0; i<n+1; i++) { gsl_vector_set(p, i, gsl_vector_get(aa, i) + gsl_vector_get(flip_aa, i)); gsl_vector_set(q, i, gsl_vector_get(aa, i) - gsl_vector_get(flip_aa, i)); } /* Remove trivial zeros */ if((n+1)%2 == 0) { double y; /* Deconvolve p with [1 1] */ y = 0; for(i=0; i<p->size; i++) { gsl_vector_set(p, i, gsl_vector_get(p, i)-y); y = gsl_vector_get(p, i); } gsl_vector_set(p, p->size-1, 0); /* Deconvolve q with [1 -1] */ y = 0; for(i=0; i<q->size; i++) { gsl_vector_set(q, i, gsl_vector_get(q, i)+y); y = gsl_vector_get(q, i); } gsl_vector_set(q, q->size-1, 0); } else { double y; /* Deconvolve q with [1 1] */ y = 0; for(i=0; i<q->size; i++) { gsl_vector_set(q, i, gsl_vector_get(q, i)-y); y = gsl_vector_get(q, i); } /* Deconvolve q with [1 -1] */ y = 0; for(i=0; i<q->size; i++) { gsl_vector_set(q, i, gsl_vector_get(q, i)+y); y = gsl_vector_get(q, i); } gsl_vector_set(q, q->size-1, 0); gsl_vector_set(q, q->size-2, 0); } /* Count the number of nonzero elements in "p" and "q" */ int n_p = 0; int n_q = 0; for(i=0; i<p->size; i++) { if(gsl_vector_get(p, i) != 0) n_p++; if(gsl_vector_get(q, i) != 0) n_q++; } /* Take the last half of "p" and "q" to vectors "TP" and "TQ" */ gsl_vector *TP = gsl_vector_alloc((n_p+1)/2); gsl_vector *TQ = gsl_vector_alloc((n_q+1)/2); for(i=0; i<TP->size; i++) { gsl_vector_set(TP, i, gsl_vector_get(p, i+(n_p-1)/2)); } for(i=0; i<TQ->size; i++) { gsl_vector_set(TQ, i, gsl_vector_get(q, i+(n_q-1)/2)); } /* Chebyshev transform */ Chebyshev(TP); Chebyshev(TQ); /* Initialize root arrays */ int nroots_TP = 2*(TP->size-1); int nroots_TQ = 2*(TQ->size-1); double TP_coeffs[TP->size]; double TQ_coeffs[TQ->size]; double TP_roots[nroots_TP]; double TQ_roots[nroots_TQ]; /* Copy coefficients to arrays */ for(i=0; i<TP->size; i++) { TP_coeffs[i] = gsl_vector_get(TP, i); } for(i=0; i<TQ->size; i++) { TQ_coeffs[i] = gsl_vector_get(TQ, i); } /* Solve roots */ gsl_poly_complex_workspace *w_TP = gsl_poly_complex_workspace_alloc(TP->size); gsl_poly_complex_workspace *w_TQ = gsl_poly_complex_workspace_alloc(TQ->size); gsl_poly_complex_solve(TP_coeffs, TP->size, w_TP, TP_roots); if(nroots_TQ > 0) { gsl_poly_complex_solve(TQ_coeffs, TQ->size, w_TQ, TQ_roots); } /* Convert to LSF and sort */ double sorted_LSF[(nroots_TP+nroots_TQ)/2]; for(i=0; i<nroots_TP; i=i+2) { sorted_LSF[i/2] = acos(TP_roots[i]/2); } for(i=0; i<nroots_TQ; i=i+2) { sorted_LSF[(i+nroots_TP)/2] = acos(TQ_roots[i]/2); } gsl_sort(sorted_LSF, 1, (nroots_TP+nroots_TQ)/2); /* Copy LSFs to vector LSF */ for(i=0; i<(nroots_TP+nroots_TQ)/2; i++) gsl_matrix_set(LSF, index, i, sorted_LSF[i]); /* Free memory */ gsl_poly_complex_workspace_free(w_TP); gsl_poly_complex_workspace_free(w_TQ); gsl_vector_free(aa); gsl_vector_free(flip_aa); gsl_vector_free(p); gsl_vector_free(q); gsl_vector_free(TP); gsl_vector_free(TQ); } /** * Function Chebyshev * * Chebyshev transformation * * @param T pointer to polynomial coefficients (result will be computed in-place) * */ void Chebyshev(gsl_vector *T) { int i,j,s; gsl_matrix *C; gsl_vector *cheb = gsl_vector_alloc(T->size); gsl_matrix *inv_C = gsl_matrix_alloc(T->size, T->size); gsl_permutation *perm = gsl_permutation_alloc(T->size); /* Create C, matrix inversion through LU-decomposition */ C = Construct_C(T->size); gsl_linalg_LU_decomp(C, perm, &s); gsl_linalg_LU_invert(C, perm, inv_C); /* Evaluate r = inv(C)'*T */ double sum; for(i=0; i<T->size; i++) { sum = 0; for(j=0; j<T->size; j++) sum += gsl_matrix_get(inv_C, j, i)*gsl_vector_get(T, j); gsl_vector_set(cheb, i, sum); } /* Copy coefficients to T */ for(i=0; i<T->size; i++) { gsl_vector_set(T, i, gsl_vector_get(cheb, i)); } /* Free memory */ gsl_vector_free(cheb); gsl_matrix_free(C); gsl_matrix_free(inv_C); gsl_permutation_free(perm); } /** * Function Construct_C * * Construct data matrix C for Chebyshev transform * * @param size * @return C matrix * */ gsl_matrix *Construct_C(int size) { int i,j; gsl_matrix *C = gsl_matrix_calloc(size,size); gsl_vector *tmp = gsl_vector_alloc(3); gsl_vector *f = gsl_vector_alloc(3); /* Set tmp and f */ gsl_vector_set(tmp,0,1); gsl_vector_set(tmp,1,0); gsl_vector_set(tmp,2,1); gsl_vector_memcpy(f,tmp); /* Set diagonal to 1 */ for(i=0;i<size;i++) gsl_matrix_set(C,i,i,1); /* Construct C */ for(i=2;i<size;i++) { f = Conv(f,tmp); for(j=0;j<i;j++) gsl_matrix_set(C,i,j,gsl_vector_get(f,(f->size-1)/2+j)); } /* Free memory */ gsl_vector_free(tmp); gsl_vector_free(f); return C; } /** * Function MA * * Moving average smoothing (inplace) * * @param vector original vector * @param length smoothing length in samples */ void MA(gsl_vector *vector, int length) { int i,j; double sum; if(length == 0) return; if(length%2 == 0) { printf("Warning: Span of the moving average filter must be odd.\n"); printf(" Span is changed to N-1.\n"); length = length - 1; } if(length < 2) { printf("Warning: Span of the moving average filter must be at least 3.\n"); return; } if(vector->size < length) return; /* Copy vector */ gsl_vector *vector_orig = gsl_vector_alloc(vector->size); gsl_vector_memcpy(vector_orig,vector); /* Filter */ for(i=length;i<vector->size;i++) { sum = 0; for(j=0;j<length;j++) { sum += gsl_vector_get(vector_orig,i-j); } gsl_vector_set(vector,i-length/2,sum/length); } /* Fix the beginning */ for(i=1;i<length+1;i=i+2) { sum = 0; for(j=0;j<i;j++) { sum += gsl_vector_get(vector_orig,j); } gsl_vector_set(vector,(i-1)/2,sum/i); } /* Fix the end */ for(i=1;i<length+1;i=i+2) { sum = 0; for(j=0;j<i;j++) { sum += gsl_vector_get(vector_orig,vector->size-1-j); } gsl_vector_set(vector,vector->size-1-(i-1)/2,sum/i); } /* Free memory */ gsl_vector_free(vector_orig); } /** * Function MA_voiced * * Moving average smoothing (inplace) for voiced regions (fundf > 0) * * @param vector original vector * @param fundf f0 vector * @param length smoothing length in samples for each sample */ void MA_voiced(gsl_vector *vector, gsl_vector *fundf, int len) { int i,j,k; gsl_vector *temp; for(i=0;i<vector->size;i++) { if(gsl_vector_get(fundf,i) > 0) { j = 0; while(i+j < vector->size && gsl_vector_get(fundf,i+j) > 0) j++; if(j>2) { temp = gsl_vector_alloc(j); for(k=0;k<j;k++) gsl_vector_set(temp,k,gsl_vector_get(vector,i+k)); MA(temp,len); for(k=0;k<j;k++) gsl_vector_set(vector,i+k,gsl_vector_get(temp,k)); gsl_vector_free(temp); } i = i + j; } } } /** * Function MA_unvoiced * * Moving average smoothing (inplace) for unvoiced regions (fundf = 0) * * @param vector original vector * @param fundf f0 vector * @param length smoothing length in samples for each sample */ void MA_unvoiced(gsl_vector *vector, gsl_vector *fundf, int len) { int i,j,k; gsl_vector *temp; for(i=0;i<vector->size;i++) { if(gsl_vector_get(fundf,i) == 0) { j = 0; while(i+j < vector->size && gsl_vector_get(fundf,i+j) == 0) j++; if(j>2) { temp = gsl_vector_alloc(j); for(k=0;k<j;k++) gsl_vector_set(temp,k,gsl_vector_get(vector,i+k)); MA(temp,len); for(k=0;k<j;k++) gsl_vector_set(vector,i+k,gsl_vector_get(temp,k)); gsl_vector_free(temp); } i = i + j; } } } /** * Function lsf2poly * * Convert LSF to polynomial * * @param lsf_matrix * @param poly * @param index * @param HMM switch for HMM */ void lsf2poly(gsl_matrix *lsf_matrix, gsl_vector *poly, int index, int HMM) { int i,l = lsf_matrix->size2; gsl_vector *lsf_vector = gsl_vector_calloc(l); gsl_vector *fi_p = NULL, *fi_q = NULL; /* Copy values to vector */ for(i=0;i<l;i++) gsl_vector_set(lsf_vector,i,gsl_matrix_get(lsf_matrix,index,i)); /* Check the validity of LSF and fix found errors (HMM parameters) */ if(HMM == 1) { LSF_fix_vector(lsf_vector); } /* Create fi_p and fi_q */ if(l%2 == 0) { fi_p = gsl_vector_alloc(l/2); fi_q = gsl_vector_alloc(l/2); for(i=0;i<l;i=i+2) { gsl_vector_set(fi_p,i/2,gsl_vector_get(lsf_vector,i)); } for(i=1;i<l;i=i+2) { gsl_vector_set(fi_q,(i-1)/2,gsl_vector_get(lsf_vector,i)); } } else { fi_p = gsl_vector_alloc((l+1)/2); for(i=0;i<l;i=i+2) { gsl_vector_set(fi_p,i/2,gsl_vector_get(lsf_vector,i)); } if((l-1)/2 > 0) { fi_q = gsl_vector_alloc((l-1)/2); for(i=1;i<l-1;i=i+2) { gsl_vector_set(fi_q,(i-1)/2,gsl_vector_get(lsf_vector,i)); } } } /* Construct vectors P and Q */ gsl_vector *cp = gsl_vector_calloc(3); gsl_vector *cq = gsl_vector_calloc(3); gsl_vector_add_constant(cp,1); gsl_vector_add_constant(cq,1); gsl_vector *P = gsl_vector_alloc(1); gsl_vector *Q = gsl_vector_alloc(1); gsl_vector_set(P,0,1); gsl_vector_set(Q,0,1); for(i=0;i<fi_p->size;i++) { gsl_vector_set(cp,1,-2*cos(gsl_vector_get(fi_p,i))); P = Conv(P,cp); } if((l-1)/2 > 0) { for(i=0;i<fi_q->size;i++) { gsl_vector_set(cq,1,-2*cos(gsl_vector_get(fi_q,i))); Q = Conv(Q,cq); } } /* Add trivial zeros */ if(l%2 == 0) { gsl_vector *conv = gsl_vector_calloc(2); gsl_vector_add_constant(conv,1); P = Conv(P,conv); gsl_vector_set(conv,0,-1); Q = Conv(Q,conv); gsl_vector_free(conv); } else { gsl_vector *conv = gsl_vector_calloc(3); gsl_vector_set(conv,0,-1); gsl_vector_set(conv,2,1); Q = Conv(Q,conv); gsl_vector_free(conv); } /* Construct polynomial */ for(i=1;i<P->size;i++) { gsl_vector_set(poly,P->size-i-1,0.5*(gsl_vector_get(P,i)+gsl_vector_get(Q,i))); } /* Free memory */ gsl_vector_free(lsf_vector); gsl_vector_free(fi_p); if((l-1)/2 > 0) gsl_vector_free(fi_q); gsl_vector_free(cp); gsl_vector_free(cq); gsl_vector_free(P); gsl_vector_free(Q); } /** * Function Conv * * Convolve two vectors * * @param conv1 * @param conv2 */ gsl_vector *Conv(gsl_vector *conv1, gsl_vector *conv2) { int i,j,n = conv2->size; double sum; gsl_vector *result = gsl_vector_alloc(conv1->size+conv2->size-1); gsl_vector *temp = gsl_vector_calloc(conv1->size+conv2->size-1); /* Set coefficients to temp */ for(i=0;i<conv1->size;i++) { gsl_vector_set(temp,i,gsl_vector_get(conv1,i)); } /* FIR-filter (Convolution) */ for(i=0;i<temp->size;i++) { sum = 0; for(j=0; j<=GSL_MIN(i, n-1); j++) { sum += gsl_vector_get(temp, i-j)*gsl_vector_get(conv2,j); } gsl_vector_set(result, i, sum); } /* Free memory */ gsl_vector_free(temp); gsl_vector_free(conv1); return result; } /** * Function Postfilter * * Postfilter LSFs * * @param LSF * @param params */ void Postfilter(gsl_matrix *LSF, PARAM *params) { if(params->postfilter_method == POSTFILTER_ID_LSF) LSF_Postfilter(LSF,params->postfilter_alpha); else if(params->postfilter_method == POSTFILTER_ID_LPC) { LPC_Postfilter(LSF, params->postfilter_alpha, params->frame_length); Smooth_matrix(LSF,3); } } /** * Function LSF_Postfilter * * Apply formant enhancement to LSFs * * @param lsf LSF-matrix * @param alpha postfilter coefficient alpha */ void LSF_Postfilter(gsl_matrix *lsf, double alpha) { if(alpha > 0) { int i,j; double d[lsf->size2-1]; for(i=0;i<lsf->size1;i++) { for(j=0;j<lsf->size2-1;j++) { d[j] = alpha*(gsl_matrix_get(lsf,i,j+1) - gsl_matrix_get(lsf,i,j)); if(j>0) { gsl_matrix_set(lsf,i,j, gsl_matrix_get(lsf,i,j-1) + d[j-1] + (pow(d[j-1],2)/(pow(d[j-1],2) + pow(d[j],2))) * ( gsl_matrix_get(lsf,i,j+1) - gsl_matrix_get(lsf,i,j-1) - d[j] - d[j-1] ) ); } } } } } /** * Function LPC_Postfilter * * Enhance Formants by modifying the re-evaluated the LPC power spectrum, * and evaluating the LPC-coefficients again * * @param LSF pointer to the LSF matrix * @param gamma enhancement coefficient * @param frame_length */ void LPC_Postfilter(gsl_matrix *LSF, double gamma, int frame_length) { int i,j,fi,s,nf,p = LSF->size2,n = POWER_SPECTRUM_FRAME_LEN; double A[n]; double B[n]; double data[n]; gsl_vector *a = gsl_vector_alloc(p+1); gsl_vector *a_temp = gsl_vector_calloc(p); gsl_vector *r = gsl_vector_alloc(p+1); gsl_vector *rr = gsl_vector_alloc(n); gsl_vector *S = gsl_vector_alloc(n); gsl_vector *b = gsl_vector_alloc(p); gsl_matrix *R = gsl_matrix_alloc (p, p); gsl_vector *formants = gsl_vector_calloc(100); gsl_permutation *perm = gsl_permutation_alloc(p); gsl_complex ca; gsl_complex cb; gsl_fft_real_wavetable *wreal = gsl_fft_real_wavetable_alloc(n); gsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(n); gsl_fft_complex_wavetable *cwt = gsl_fft_complex_wavetable_alloc(n); gsl_fft_complex_workspace *cwork = gsl_fft_complex_workspace_alloc(n); double xa[2*n]; double xb[2*n]; /* Initialize B */ B[0] = 1; for(i=1;i<n;i++) B[i] = 0; gsl_fft_real_transform(B,1,n,wreal,work); gsl_complex_packed_array complex_coefficients_b = xb; gsl_fft_halfcomplex_unpack(B,complex_coefficients_b,1,n); /* Loop for every index of the LSF matrix */ for(fi=0;fi<LSF->size1;fi++) { /* Convert LSF to LPC */ lsf2poly(LSF,a,fi,1); /* Evaluate power spectrum S, this assumes an all-pole model (B = 1) */ for(i=0;i<p+1;i++) A[i] = gsl_vector_get(a,i); for(i=p+1;i<n;i++) A[i] = 0; gsl_fft_real_transform(A,1,n,wreal,work); gsl_complex_packed_array complex_coefficients_a = xa; gsl_fft_halfcomplex_unpack(A,complex_coefficients_a,1,n); for(i=0;i<n;i++) { GSL_SET_COMPLEX(&ca, REAL(complex_coefficients_a,i), IMAG(complex_coefficients_a,i)); GSL_SET_COMPLEX(&cb, REAL(complex_coefficients_b,i), IMAG(complex_coefficients_b,i)); ca = gsl_complex_div(cb, ca); gsl_vector_set(S,i,gsl_complex_abs2(ca)); } /* Modification of the power spectrum S */ GetFormants(S,formants,&nf); ModPowerSpectrum(S,formants,nf,gamma); /* Construct autocorrelation r */ for(i=0;i<n;i++) data[i] = gsl_vector_get(S,i); gsl_fft_real_unpack(data, complex_coefficients_a, 1, n); gsl_fft_complex_inverse(complex_coefficients_a, 1, n, cwt, cwork); for(i=0;i<2*n;i = i + 2) gsl_vector_set(rr,i/2,xa[i]); for(i=0;i<p+1;i++) gsl_vector_set(r,i,gsl_vector_get(rr,i)); /* Construct LPC */ for(i=0; i<p;i++) for(j=0; j<p; j++) gsl_matrix_set(R, i, j, gsl_vector_get(r, abs(i-j))); for(i=1; i<p+1; i++) gsl_vector_set(b, i-1, gsl_vector_get(r, i)); gsl_linalg_LU_decomp(R, perm, &s); gsl_linalg_LU_solve(R, perm, b, a_temp); for(i=1; i<a->size; i++) gsl_vector_set(a, i, (-1.0)*gsl_vector_get(a_temp, i-1)); gsl_vector_set(a, 0, 1); for(i=0;i<a->size;i++) if(gsl_isnan(gsl_vector_get(a,i))) gsl_vector_set(a,i,0); /* Convert LPC back to LSF */ Convert_to_LSF(LSF, a, fi); } /* Free memory */ gsl_vector_free(formants); gsl_vector_free(a); gsl_vector_free(a_temp); gsl_vector_free(r); gsl_vector_free(rr); gsl_vector_free(S); gsl_vector_free(b); gsl_matrix_free(R); gsl_permutation_free(perm); gsl_fft_real_wavetable_free(wreal); gsl_fft_real_workspace_free(work); gsl_fft_complex_wavetable_free(cwt); gsl_fft_complex_workspace_free(cwork); } /** * Function ModPowerSpectrum * * Modify power spectrum in order to enhance formants * * @param s pointer to power spectrum vector * @param gamma enhancement coefficient */ void ModPowerSpectrum(gsl_vector *s, gsl_vector *formants, int n, double gamma) { int i,j; /* Nonlinearity in power reduction depending on the width of the valley */ double l = 150.0; double d = 40.0; double add = 0.5 + gamma; double c = 0.5; int dist; double mod; /* Modify spectrum between zero and the first formant */ dist = gsl_vector_get(formants,0); mod = c*(-1.0/(1.0 + exp((-dist+l)/d))) + add; for(i=0;i<gsl_vector_get(formants,0) - POWER_SPECTRUM_WIN;i++) gsl_vector_set(s,i,gsl_vector_get(s,i)*gamma); /* Modify spectrum between the last formant and FS/2 */ dist = floor(s->size/2)-gsl_vector_get(formants,n-1); mod = c*(-1.0/(1.0 + exp((-dist+l)/d))) + add; for(i=gsl_vector_get(formants,n-1) + POWER_SPECTRUM_WIN+1;i<s->size/2+1;i++) gsl_vector_set(s,i,gsl_vector_get(s,i)*gamma); /* Modify spectrum within a constant number of bins from the formant peaks */ for(i=0;i<n-1;i++) { dist = gsl_vector_get(formants,i+1) - gsl_vector_get(formants,i); mod = c*(-1.0/(1.0 + exp((-dist+l)/d))) + add; for(j=gsl_vector_get(formants,i) + POWER_SPECTRUM_WIN+1;j<gsl_vector_get(formants,i+1) - POWER_SPECTRUM_WIN;j++) gsl_vector_set(s,j,gsl_vector_get(s,j)*gamma); } /* Reconstruct image spectrum */ if((s->size)%2 == 0) for(i=1;i<s->size/2;i++) gsl_vector_set(s,s->size-i,gsl_vector_get(s,i)); else for(i=1;i<ceil(s->size/2)+1;i++) gsl_vector_set(s,s->size-i,gsl_vector_get(s,i)); } /** * Function GetFormants * * Get formant positions from smooth power spectrum * * @param s pointer to power spectrum vector * @param formants pointer to forman position vector */ void GetFormants(gsl_vector *s, gsl_vector *formants, int *n) { int i,ind; gsl_vector *sd = gsl_vector_alloc(s->size); /* Differentiate s */ gsl_vector_memcpy(sd,s); Differentiate_noleak(sd); /* Find formant peaks */ ind = 0; for(i=0;i<round(s->size/2)+1;i++) { if(gsl_vector_get(sd,i) >= 0 && gsl_vector_get(sd,i+1) <= 0) { gsl_vector_set(formants,ind,i); ind++; } } /* Set the number of formants */ (*n) = ind; /* Free memory */ gsl_vector_free(sd); } /** * Function Hp_filt_f0 * * High-pass filter speech below F0 * * @param signal speech * @param fundf F0 * */ void Hp_filt_below_f0(gsl_vector *signal, gsl_vector *fundf, PARAM *params) { if(params->hpfiltf0 == 0) return; int i,j,fnumber,use_hmm = 0,filter_update_interval = 1; double f0 = 0,lambda = 0,weight; /* Filter cut-off frequencies */ double f[25] = {0,40,60,80,100,120,140,160,180,200,220,240,260,280,300,320,340,360,380,400,420,440,460,480,500}; /* Denominator filter coefficients */ double lsfa[24][7] = {{0.012270374463510, 0.015772995424344, 0.024530703714270, 0.080413887423843, 0.400306289905254, 1.168999898025715, 2.132579893858550}, {0.017920282072328, 0.022791623836745, 0.029864786258385, 0.055369341235469, 0.250523957519273, 1.092123690431822, 2.105116976227308}, {0.021801057749634, 0.028684712190248, 0.034646162981531, 0.057546773586775, 0.246163207189489, 1.093903629649360, 2.108370657386230}, {0.030330579315104, 0.038234559055245, 0.050121987909179, 0.091732027364528, 0.329220914237973, 1.125584823436989, 2.116231821108477}, {0.034811643040824, 0.044349408406948, 0.053516371808008, 0.087458975943472, 0.308231588488585, 1.118896822551608, 2.116399287588925}, {0.043917420002783, 0.054747497330268, 0.074390982686771, 0.143405359634844, 0.436338014468054, 1.182631435560068, 2.136140897442202}, {0.045038897777332, 0.058258259000167, 0.068963787550062, 0.109221377061591, 0.344220168514159, 1.134851229904599, 2.124295109888979}, {0.051022535502281, 0.065831379814600, 0.077573712097764, 0.121610480053570, 0.364861933549680, 1.146550846159653, 2.126584406920744}, {0.057632798735370, 0.073608263773643, 0.086404993167967, 0.134181910858372, 0.384477060556410, 1.154156703313648, 2.134888076326625}, {0.064123563307627, 0.081389884334947, 0.095130140196939, 0.146329709620344, 0.403020870485622, 1.163653230220413, 2.139554601837831}, {0.070489123224552, 0.089082609042766, 0.103643756411925, 0.157832024397575, 0.420045784848692, 1.172254221962511, 2.139045944360825}, {0.076847236579249, 0.096765479627175, 0.112050759011413, 0.168910344402175, 0.436071212884462, 1.181903820775476, 2.140464848942151}, {0.083670629006476, 0.104607866948277, 0.120599031060558, 0.180042602015452, 0.451542294904885, 1.189290523546819, 2.144017570035968}, {0.089932593812542, 0.112338083896512, 0.128836675422754, 0.190418798017626, 0.465709447605648, 1.200408605940246, 2.144702419538647}, {0.097482721230326, 0.120403139593136, 0.137524292415345, 0.201381669315467, 0.480314653853837, 1.205081242188550, 2.149181575561907}, {0.104600479029988, 0.128368705707085, 0.145929375571240, 0.211617389775297, 0.493657999260862, 1.212296579325581, 2.151596677897734}, {0.112590768888632, 0.136542902549503, 0.154586373033906, 0.222085490310900, 0.506940958793273, 1.217511577523374, 2.163600455800026}, {0.120305856730245, 0.144659614898539, 0.163016448320984, 0.231948743065545, 0.519466412869994, 1.224899556795356, 2.172566273838793}, {0.126196196114728, 0.152429039122201, 0.170619462400073, 0.240153856910034, 0.529226373592494, 1.235527230693612, 2.155469675089261}, {0.135957950019333, 0.160953029397963, 0.179571203980533, 0.250426168574974, 0.541985366804235, 1.235994160018460, 2.179609273087876}, {0.144100745276714, 0.169162818316366, 0.187753461107828, 0.259137041396872, 0.552306542274397, 1.240620073961813, 2.183055012971304}, {0.152457690627618, 0.177406803994366, 0.195849185376123, 0.267429744429561, 0.561963473760917, 1.244674940290760, 2.186392580112432}, {0.161053099588424, 0.185684023980750, 0.203849642456801, 0.275267011545265, 0.570885488302771, 1.248003394526696, 2.189775517375000}, {0.169933394492268, 0.193993666339236, 0.211740771952925, 0.282593310976812, 0.579087806020812, 1.250410947768047, 2.193033533970162}}; /* Numerator filter coefficients */ double lsfb[24][5] = {{0.000030707852178, 0.003290687909261, 0.008730452554971, 0.008758594958107, 0.638065301730947}, {0.000345919101634, 0.007464820245500, 0.013446868902239, 0.013524918943862, 0.252043490985464}, {0.009337032323646, 0.012733180521797, 0.018752843006707, 0.018887151908989, 0.124438874030317}, {0.001750143943771, 0.014695620878432, 0.023413418898011, 0.023932233792984, 0.348241402501227}, {0.007451258505131, 0.023588219512075, 0.028822776612533, 0.029638359563087, 0.209598248087015}, {0.001262844775076, 0.019228486757771, 0.034126483729823, 0.034313458775845, 0.533669297472435}, {0.003966950786406, 0.027567085337588, 0.030762627018637, 0.041065592365883, 0.041079101614055}, {0.007300878835979, 0.031740322902411, 0.031817781139977, 0.047113960631324, 0.047413638436212}, {0.013297800640636, 0.036151790887025, 0.037029955814879, 0.053378560084371, 0.053478127353236}, {0.004245482517036, 0.040719988302241, 0.041791183344858, 0.059844792535173, 0.059931017064342}, {0.013325335393929, 0.045481683243416, 0.046722772464647, 0.066520788321735, 0.066692797195485}, {0.011043680418257, 0.050443635379848, 0.052305089861292, 0.073408015773066, 0.073456841095412}, {0.010460216064980, 0.055656179782247, 0.056019990537994, 0.080510475101328, 0.080529142221492}, {0.005042256738375, 0.060986479133597, 0.061700727238748, 0.087811525503098, 0.087832573628210}, {0.021201154212601, 0.066716566424458, 0.070923784343375, 0.095350487083348, 0.095396267816331}, {0.021743620358827, 0.072604498913997, 0.080230354225900, 0.103093601812379, 0.103095461338701}, {0.010361144083279, 0.078885501870204, 0.081497400090665, 0.111068522558155, 0.111953788509510}, {0.035482770544817, 0.085365388042439, 0.094373216452207, 0.119258245225241, 0.119606909976157}, {0.008760915951485, 0.091788399421470, 0.093320007127655, 0.127626103353867, 0.127670078949185}, {0.014865429114325, 0.099220356759925, 0.099842903153314, 0.136297513507208, 0.136872182683673}, {0.010181473814981, 0.106654721678083, 0.107407671710693, 0.145160461404689, 0.145544940575618}, {0.013092604335205, 0.114476964121103, 0.116199737975443, 0.154255878946170, 0.154357148101622}, {0.019538269162167, 0.122717547053384, 0.127482889764472, 0.163581821500224, 0.164070219003255}, {0.006517570557916, 0.131457491434920, 0.135046228721468, 0.173152990621689, 0.173468137485191}}; /* Allocate filter matrices */ gsl_matrix *LSFA = gsl_matrix_alloc(fundf->size,7); gsl_matrix *LSFB = gsl_matrix_alloc(fundf->size,5); /* Find appropriate filter coefficients according to F0 */ for(i=0;i<fundf->size;i++) { /* Fundamental frequency */ if(gsl_vector_get(fundf,i) != 0) f0 = gsl_vector_get(fundf,i); else f0 = 40; /* Search for nearest upper cut-off frequency */ fnumber = 0; while(f[fnumber] < f0 && fnumber != 24) fnumber++; /* Determine weight */ if(fnumber == 0) weight = 1; else if(fnumber == 24) weight = 0; else weight = (f[fnumber]-f0)/(f[fnumber]-f[fnumber-1]); /* Interpolate between two filters */ for(j=0;j<LSFA->size2;j++) gsl_matrix_set(LSFA, i, j, weight*lsfa[GSL_MAX(fnumber-2,0)][j] + (1.0-weight)*lsfa[GSL_MAX(fnumber-1,0)][j]); for(j=0;j<LSFB->size2;j++) gsl_matrix_set(LSFB, i, j, weight*lsfb[GSL_MAX(fnumber-2,0)][j] + (1.0-weight)*lsfb[GSL_MAX(fnumber-1,0)][j]); } /* Initialize filter */ int q,mlen; long int o; double xr,x,ffr,tmpr,Bb; double *sigma; long int len = signal->size; int bdim = LSFA->size2 + 1; int adim = LSFB->size2 + 1; double *Ar = (double *)calloc(adim,sizeof(double)); double *Br = (double *)calloc(bdim,sizeof(double)); double *ynr = (double *)calloc(signal->size,sizeof(double)); double *rsignal = (double *)calloc(signal->size,sizeof(double)); double *rmem = (double *)calloc((bdim+2),sizeof(double)); gsl_vector *A = gsl_vector_alloc(adim); gsl_vector *B = gsl_vector_alloc(bdim); gsl_matrix *LSFA_i = gsl_matrix_alloc(params->signal_length,LSFA->size2); gsl_matrix *LSFB_i = gsl_matrix_alloc(params->signal_length,LSFB->size2); /* Smooth and interpolate */ Smooth_interp_lsf(LSFA_i,LSFA,len,use_hmm,5); Smooth_interp_lsf(LSFB_i,LSFB,len,use_hmm,5); /* Set signal to array */ for(i=0;i<len;i++) { rsignal[i] = gsl_vector_get(signal,i); } /* Initialize */ sigma = NFArray(bdim+2); Bb = 0; if(adim >= bdim) mlen = adim; else mlen = bdim + 1; /* Warped filtering */ for(o=0;o<len;o++) { /* Update filter coefficients */ if(o%filter_update_interval == 0) { lsf2poly(LSFA_i,B,o,params->use_hmm); lsf2poly(LSFB_i,A,o,params->use_hmm); for(i=0;i<adim;i++) Ar[i] = gsl_vector_get(A,i); for(i=0;i<bdim;i++) Br[i] = gsl_vector_get(B,i); alphas2sigmas(Br,sigma,lambda,bdim-1); Bb = 1/Br[0]; } xr = rsignal[o]*Bb; /* Update feedbackward sum */ for(q=0;q<bdim;q++) { xr -= sigma[q]*rmem[q]; } xr = xr/sigma[bdim]; x = xr*Ar[0]; /* Update inner states */ for(q=0;q<mlen;q++) { tmpr = rmem[q] + lambda*(rmem[q+1] - xr); rmem[q] = xr; xr = tmpr; } /* Update feedforward sum */ for(q=0,ffr=0.0;q<adim-1;q++) { ffr += Ar[q+1]*rmem[q+1]; } /* Update output */ ynr[o] = x + ffr; } /* Set output to vector */ for(i=0;i<len;i++) { gsl_vector_set(signal,i,ynr[i]); } /* Free memory */ free(ynr); free(rsignal); free(Ar); free(Br); free(rmem); free(sigma); gsl_vector_free(A); gsl_vector_free(B); gsl_matrix_free(LSFA); gsl_matrix_free(LSFB); gsl_matrix_free(LSFA_i); gsl_matrix_free(LSFB_i); } /** * Function Evaluate_matrix_std * * Evaluate standard deviations of matrix * * @param std vector * @param data matrix */ void Evaluate_matrix_std(gsl_vector *std, gsl_matrix *data) { int i,j; gsl_vector *mean = gsl_vector_calloc(data->size2); /* Evaluate mean and std of matrix data */ for(i=0;i<data->size2;i++) for(j=0;j<data->size1;j++) gsl_vector_set(mean,i,gsl_vector_get(mean,i) + gsl_matrix_get(data,j,i)); for(i=0;i<data->size2;i++) gsl_vector_set(mean,i,gsl_vector_get(mean,i)/data->size1); for(i=0;i<data->size2;i++) for(j=0;j<data->size1;j++) gsl_vector_set(std,i,gsl_vector_get(std,i) + powf(gsl_matrix_get(data,j,i)-gsl_vector_get(mean,i),2)); for(i=0;i<data->size2;i++) gsl_vector_set(std,i,sqrt(gsl_vector_get(std,i)/(data->size1-1))); /* Free memory */ gsl_vector_free(mean); } /** * Function Evaluate_vector_std * * Evaluate standard deviation of vector * * @param std * @param data */ void Evaluate_vector_std(gsl_vector *std, gsl_vector *data) { int i; double mean = 0; /* Evaluate mean and std of vector data */ for(i=0;i<data->size;i++) mean += gsl_vector_get(data,i); mean = mean/data->size; for(i=0;i<data->size;i++) gsl_vector_set(std,0,gsl_vector_get(std,0) + powf(gsl_vector_get(data,i)-mean,2)); gsl_vector_set(std,0,sqrt(gsl_vector_get(std,0)/(data->size-1))); } /** * Function ReadFileDouble * * Read double values from file * * @param name filename * @return vector containing the values */ gsl_vector *ReadFileDouble(char *name) { FILE *file; int fileLen,n,i; /* Open file */ file = fopen(name, "rb"); // Open as binary if(!file) { printf("Error opening file %s: %s\n", name, strerror(errno)); return NULL; } /* Get file length */ fseek(file, 0, SEEK_END); fileLen = ftell(file); fseek(file, 0, SEEK_SET); /* Allocate memory */ double *buffer = (double *)malloc(fileLen); if(!buffer) { printf("Memory error!\n"); fclose(file); return NULL; } /* Read file contents into buffer */ n = fread(buffer, fileLen, 1, file); fclose(file); /* Set values to vector */ gsl_vector *vector = gsl_vector_calloc(fileLen/sizeof(double)); for(i=0;i<fileLen/sizeof(double);i++) { gsl_vector_set(vector,i,buffer[i]); } free(buffer); return vector; } /** * Function ReadFileFloat * * Read float values from file * * @param name filename * @return vector containing the values */ gsl_vector *ReadFileFloat(char *name) { FILE *file; int fileLen,n,i; /* Open file */ file = fopen(name, "rb"); // Open as binary if(!file) { printf("Error opening file %s: %s\n", name, strerror(errno)); return NULL; } /* Get file length */ fseek(file, 0, SEEK_END); fileLen = ftell(file); fseek(file, 0, SEEK_SET); /* Allocate memory */ float *buffer = (float *)malloc(fileLen); if(!buffer) { printf("Memory error!\n"); fclose(file); return NULL; } /* Read file contents into buffer */ n = fread(buffer, fileLen, 1, file); fclose(file); /* Set values to vector */ gsl_vector *vector = gsl_vector_calloc(fileLen/sizeof(float)); for(i=0;i<fileLen/sizeof(float);i++) { gsl_vector_set(vector,i,buffer[i]); } free(buffer); return vector; } /** * Function Gain_normalization * * Normalize the gain of a signal. * Result is saved in-place to vector signal * * @param signal input signal * @param gain gain vector * @param frame_length frame length in samples * @param shift shift length in samples * @param speed syntesis speed * @param pitch synthesis pitch * @param gain_threshold threshold for gain normalization * */ void Gain_normalization(gsl_vector *signal, gsl_vector *gain, int frame_length, int shift, double speed, double pitch, double gain_threshold) { int i,j; double sum; gsl_vector *norm = gsl_vector_calloc(gain->size); gsl_vector *norm_i = gsl_vector_alloc(signal->size); /* Calculate gain normalization vector */ for(i=0;i<gain->size;i++) { sum = 0; for(j=i*shift/speed;j<i*shift/speed+frame_length/speed;j++) { sum += pow(gsl_vector_get(signal,GSL_MIN(signal->size-1,j))*HANN(j-i*shift/speed,frame_length),2); } if(sum < gain_threshold) {sum = gain_threshold;} gsl_vector_set(norm,i,sqrt((E_REF*powf(10.0,gsl_vector_get(gain,i)/10.0))/sum)); } /* Linear interpolation */ Interpolate_lin(norm,norm_i); /* Set gain */ for(i=0;i<signal->size;i++) { gsl_vector_set(signal,i,gsl_vector_get(signal,i)*gsl_vector_get(norm_i,i)); } /* Free memory */ gsl_vector_free(norm); gsl_vector_free(norm_i); } /** * Function LSF_MOD * * Modify LSF matrix * * @param matrix matrix to be modified * */ void LSF_MOD(gsl_matrix *lsf) { int i,j; double d = 1.4; for(i=0;i<lsf->size1;i++) { for(j=0;j<lsf->size2;j++) { gsl_matrix_set(lsf,i,j, gsl_matrix_get(lsf,i,j)/d); } } LSF_fix_matrix(lsf); } /** * Function Integrate_matrix * * Integrate matrix * * @param matrix matrix to be integrated * */ void Integrate_matrix(gsl_matrix *matrix) { int i,j; for(i=0;i<matrix->size1;i++) for(j=1;j<matrix->size2;j++) gsl_matrix_set(matrix,i,j,gsl_matrix_get(matrix,i,j-1) + gsl_matrix_get(matrix,i,j)); } /** * Function Integrate * * Integrate vector * * @param vector to be integrated * */ void Integrate(gsl_vector *vector, double leak) { int i; for(i=1;i<vector->size;i++) gsl_vector_set(vector,i,gsl_vector_get(vector,i-1)*leak + gsl_vector_get(vector,i)); } /** * Function Free_pulselib_variables * * Free pulse library variables * * @param */ void Free_pulselib_variables(gsl_matrix *pulses, gsl_matrix *pulses_rs, gsl_matrix *pwaveform, gsl_vector *pulse_lengths, gsl_matrix *plsf, gsl_matrix *ptilt, gsl_matrix *pharm, gsl_matrix *phnr, gsl_vector *pgain, gsl_vector *ph1h2, gsl_vector *pnaq, gsl_vector *pca_mean, gsl_matrix *pca_pc, gsl_matrix *pca_w_lib, gsl_vector *stoch_env, gsl_vector *stoch_sp, PARAM *params) { /* Do not free if pulse library is not in use */ if(params->use_pulselib == 0) return; /* Free pulse library */ gsl_matrix_free(pulses); gsl_matrix_free(pulses_rs); gsl_vector_free(pulse_lengths); gsl_matrix_free(plsf); gsl_vector_free(pgain); if(params->use_waveform == 1) gsl_matrix_free(pwaveform); if(params->use_tilt == 1) gsl_matrix_free(ptilt); if(params->use_harmonics == 1) gsl_matrix_free(pharm); if(params->use_hnr == 1) gsl_matrix_free(phnr); if(params->use_h1h2 == 1) gsl_vector_free(ph1h2); if(params->use_naq == 1) gsl_vector_free(pnaq); /* Free pulse library pca parameters */ if(params->use_pulselib_pca == 1) { gsl_vector_free(pca_mean); gsl_matrix_free(pca_pc); } /* Free pulse pca parameters */ if(params->use_pulse_pca == 1) gsl_matrix_free(pca_w_lib); } /** * Function Free_variables * * Free synthesis variables * * @param */ void Free_variables(gsl_vector *original_pulse, gsl_vector *excitation_voiced, gsl_vector *excitation_unvoiced, gsl_vector *fundf, gsl_vector *gain, gsl_vector *gain_new, gsl_matrix *LSF, gsl_matrix *LSF2, gsl_matrix *LSF_interp, gsl_matrix *glflowsp, gsl_matrix *glflowsp_new, gsl_matrix *hnr, gsl_matrix *hnr_new, gsl_matrix *harmonics, gsl_matrix *waveform, gsl_vector *h1h2, gsl_vector *naq, gsl_vector *resynthesis_pulse_index, gsl_vector *pulse_clus_id, gsl_matrix *pulse_clusters, gsl_matrix *pca_w, gsl_matrix **DNN_W, gsl_vector **input_minmax, gsl_vector *dnnpulseindices, gsl_vector *dnnpulses, PARAM *params) { /* Free variables */ gsl_vector_free(original_pulse); gsl_vector_free(excitation_voiced); gsl_vector_free(excitation_unvoiced); gsl_vector_free(fundf); gsl_vector_free(gain); gsl_vector_free(gain_new); gsl_matrix_free(LSF); gsl_matrix_free(glflowsp_new); gsl_matrix_free(hnr_new); gsl_vector_free(resynthesis_pulse_index); if(LSF_interp != NULL) gsl_matrix_free(LSF_interp); if(params->use_tilt == 1 && glflowsp != NULL) gsl_matrix_free(glflowsp); if(params->use_hnr == 1 && hnr != NULL) gsl_matrix_free(hnr); if(params->use_harmonics == 1 && harmonics != NULL) gsl_matrix_free(harmonics); if(params->use_waveform == 1 && waveform != NULL) gsl_matrix_free(waveform); if(params->use_h1h2 == 1 && h1h2 != NULL) gsl_vector_free(h1h2); if(params->use_naq == 1 && naq != NULL) gsl_vector_free(naq); if(params->sep_vuv_spectrum == 1 && LSF2 != NULL) gsl_matrix_free(LSF2); if(params->pulse_clustering == 1) { if(pulse_clus_id != NULL) gsl_vector_free(pulse_clus_id); if(pulse_clusters != NULL)gsl_matrix_free(pulse_clusters); } /* Free pulse library PCA weights */ if(params->use_pulselib_pca == 1) gsl_matrix_free(pca_w); /* Free DNN weights if used */ int i; if(params->use_dnn_pulsegen == 1) { for(i=0;i<params->dnn_weight_dims->size/2;i++) gsl_matrix_free(DNN_W[i]); gsl_vector_free(dnnpulseindices); gsl_vector_free(dnnpulses); if(params->dnn_input_normalized == 1) gsl_vector_free(input_minmax[0]); } free(DNN_W); free(input_minmax); /* Free variables in param */ for(i=0;i<params->synlistlen;i++) free(params->synlist[i]); free(params->synlist); free(params->synlist_filename); free(params->dnnpath); free(params->pulse_filename); free(params->pulselibrary_filename); gsl_vector_free(params->paramweights); gsl_vector_free(params->dnn_weight_dims); } /** * Function Save_excitation_to_wav * * Save excitation vector to wav file * * @param excitation vector * @param params parameters */ void Save_excitation_to_wav(gsl_vector *excitation, PARAM *params) { if(params->write_excitation_to_wav == 1) { gsl_vector *temp = gsl_vector_alloc(excitation->size); gsl_vector_memcpy(temp,excitation); Scale_signal(temp,SCALE_IF_GREATER_THAN_ONE); Save_signal_to_file(temp,params,FILENAME_ENDING_EXCITATION); gsl_vector_free(temp); } } /** * Function Normalize_pulse_library_var * * Normalize pulse library parameters according to synthesis parameters (normalize mean and variance) * * @param pulse lib params * @param synthesis params */ void Normalize_pulse_library_var(gsl_matrix *plsf,gsl_matrix *ptilt,gsl_matrix *pharm,gsl_matrix *phnr,gsl_matrix *pwaveform, gsl_vector *pgain,gsl_vector *ph1h2,gsl_vector *pnaq,gsl_matrix *lsf,gsl_matrix *tilt,gsl_matrix *harm,gsl_matrix *hnr, gsl_matrix *waveform,gsl_vector *gain,gsl_vector *h1h2,gsl_vector *naq, gsl_vector *fundf,PARAM *params) { /* Exit if pulse library is not used */ if(params->use_pulselib == 0) return; /* Exit if normalization is not set on */ if(params->normalize_pulselib == 0) return; /* Exit if adaptation to pulse library parameters is set on */ if(params->adapt_to_pulselib == 1) { printf("Warning: Pulse library normalization and adaptation to pulse library parameters cannot be used simultaneously!\n"); return; } /* Initialize */ int i,j,k; double mean_lib,mean_par,std_lib,std_par; /* Normalize LSF */ for(i=0;i<lsf->size2;i++) { /* Evaluate means */ mean_par = 0; mean_lib = 0; for(j=0;j<plsf->size1;j++) mean_lib += gsl_matrix_get(plsf,j,i); k = 0; for(j=0;j<lsf->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { mean_par += gsl_matrix_get(lsf,j,i); k++; } } mean_lib = mean_lib/plsf->size1; mean_par = mean_par/k; /* Evaluate standard deviations */ std_par = 0; std_lib = 0; for(j=0;j<plsf->size1;j++) std_lib += (gsl_matrix_get(plsf,j,i)-mean_lib)*(gsl_matrix_get(plsf,j,i)-mean_lib); std_lib = sqrt(std_lib/(plsf->size1-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<lsf->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_matrix_get(lsf,j,i)-mean_par)*(gsl_matrix_get(lsf,j,i)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; /* Normalize */ for(j=0;j<plsf->size1;j++) gsl_matrix_set(plsf,j,i,(gsl_matrix_get(plsf,j,i)-mean_lib)/std_lib*std_par + mean_par); } /* Normalize LSFsource */ for(i=0;i<tilt->size2;i++) { /* Evaluate means */ mean_par = 0; mean_lib = 0; for(j=0;j<ptilt->size1;j++) mean_lib += gsl_matrix_get(ptilt,j,i); k = 0; for(j=0;j<tilt->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { mean_par += gsl_matrix_get(tilt,j,i); k++; } } mean_lib = mean_lib/ptilt->size1; mean_par = mean_par/k; /* Evaluate standard deviations */ std_par = 0; std_lib = 0; for(j=0;j<ptilt->size1;j++) std_lib += (gsl_matrix_get(ptilt,j,i)-mean_lib)*(gsl_matrix_get(ptilt,j,i)-mean_lib); std_lib = sqrt(std_lib/(ptilt->size1-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<tilt->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_matrix_get(tilt,j,i)-mean_par)*(gsl_matrix_get(tilt,j,i)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; /* Normalize */ for(j=0;j<ptilt->size1;j++) gsl_matrix_set(ptilt,j,i,(gsl_matrix_get(ptilt,j,i)-mean_lib)/std_lib*std_par + mean_par); } /* Normalize HNR */ for(i=0;i<hnr->size2;i++) { /* Evaluate means */ mean_par = 0; mean_lib = 0; for(j=0;j<phnr->size1;j++) mean_lib += gsl_matrix_get(phnr,j,i); k = 0; for(j=0;j<hnr->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { mean_par += gsl_matrix_get(hnr,j,i); k++; } } mean_lib = mean_lib/phnr->size1; mean_par = mean_par/k; /* Evaluate standard deviations */ std_par = 0; std_lib = 0; for(j=0;j<phnr->size1;j++) std_lib += (gsl_matrix_get(phnr,j,i)-mean_lib)*(gsl_matrix_get(phnr,j,i)-mean_lib); std_lib = sqrt(std_lib/(phnr->size1-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<hnr->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_matrix_get(hnr,j,i)-mean_par)*(gsl_matrix_get(hnr,j,i)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; /* Normalize */ for(j=0;j<phnr->size1;j++) gsl_matrix_set(phnr,j,i,(gsl_matrix_get(phnr,j,i)-mean_lib)/std_lib*std_par + mean_par); } /* Normalize Harmonics */ if(params->use_harmonics == 1) { for(i=0;i<hnr->size2;i++) { /* Evaluate means */ mean_par = 0; mean_lib = 0; for(j=0;j<pharm->size1;j++) mean_lib += gsl_matrix_get(pharm,j,i); k = 0; for(j=0;j<harm->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { mean_par += gsl_matrix_get(harm,j,i); k++; } } mean_lib = mean_lib/pharm->size1; mean_par = mean_par/k; /* Evaluate standard deviations */ std_par = 0; std_lib = 0; for(j=0;j<pharm->size1;j++) std_lib += (gsl_matrix_get(pharm,j,i)-mean_lib)*(gsl_matrix_get(pharm,j,i)-mean_lib); std_lib = sqrt(std_lib/(pharm->size1-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<harm->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_matrix_get(harm,j,i)-mean_par)*(gsl_matrix_get(harm,j,i)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; /* Normalize */ for(j=0;j<pharm->size1;j++) gsl_matrix_set(pharm,j,i,(gsl_matrix_get(pharm,j,i)-mean_lib)/std_lib*std_par + mean_par); } } /* Normalize Waveform */ if(params->use_waveform == 1) { for(i=0;i<hnr->size2;i++) { /* Evaluate means */ mean_par = 0; mean_lib = 0; for(j=0;j<pwaveform->size1;j++) mean_lib += gsl_matrix_get(pwaveform,j,i); k = 0; for(j=0;j<waveform->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { mean_par += gsl_matrix_get(waveform,j,i); k++; } } mean_lib = mean_lib/pwaveform->size1; mean_par = mean_par/k; /* Evaluate standard deviations */ std_par = 0; std_lib = 0; for(j=0;j<pwaveform->size1;j++) std_lib += (gsl_matrix_get(pwaveform,j,i)-mean_lib)*(gsl_matrix_get(pwaveform,j,i)-mean_lib); std_lib = sqrt(std_lib/(pwaveform->size1-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<waveform->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_matrix_get(waveform,j,i)-mean_par)*(gsl_matrix_get(waveform,j,i)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; /* Normalize */ for(j=0;j<pwaveform->size1;j++) gsl_matrix_set(pwaveform,j,i,(gsl_matrix_get(pwaveform,j,i)-mean_lib)/std_lib*std_par + mean_par); } } /* Normalize Gain */ mean_lib = Mean(pgain); k = 0; mean_par = 0; for(i=0;i<gain->size;i++) { if(gsl_vector_get(fundf,i) > 0) { mean_par += gsl_vector_get(gain,i); k++; } } mean_par = mean_par/k; std_par = 0; std_lib = 0; for(j=0;j<pgain->size;j++) std_lib += (gsl_vector_get(pgain,j)-mean_lib)*(gsl_vector_get(pgain,j)-mean_lib); std_lib = sqrt(std_lib/(pgain->size-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<gain->size;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_vector_get(gain,j)-mean_par)*(gsl_vector_get(gain,j)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; gsl_vector_add_constant(pgain,-mean_lib); gsl_vector_scale(pgain, std_par/std_lib); gsl_vector_add_constant(pgain,mean_par); /* Normalize H1H2 */ if(params->use_h1h2 == 1) { mean_lib = Mean(ph1h2); k = 0; mean_par = 0; for(i=0;i<h1h2->size;i++) { if(gsl_vector_get(fundf,i) > 0) { mean_par += gsl_vector_get(h1h2,i); k++; } } mean_par = mean_par/k; std_par = 0; std_lib = 0; for(j=0;j<ph1h2->size;j++) std_lib += (gsl_vector_get(ph1h2,j)-mean_lib)*(gsl_vector_get(ph1h2,j)-mean_lib); std_lib = sqrt(std_lib/(ph1h2->size-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<h1h2->size;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_vector_get(h1h2,j)-mean_par)*(gsl_vector_get(h1h2,j)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; gsl_vector_add_constant(ph1h2,-mean_lib); gsl_vector_scale(ph1h2, std_par/std_lib); gsl_vector_add_constant(ph1h2,mean_par); } /* Normalize NAQ */ if(params->use_naq == 1) { mean_lib = Mean(pnaq); k = 0; mean_par = 0; for(i=0;i<naq->size;i++) { if(gsl_vector_get(fundf,i) > 0) { mean_par += gsl_vector_get(naq,i); k++; } } mean_par = mean_par/k; std_par = 0; std_lib = 0; for(j=0;j<pnaq->size;j++) std_lib += (gsl_vector_get(pnaq,j)-mean_lib)*(gsl_vector_get(pnaq,j)-mean_lib); std_lib = sqrt(std_lib/(pnaq->size-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<naq->size;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_vector_get(naq,j)-mean_par)*(gsl_vector_get(naq,j)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; gsl_vector_add_constant(pnaq,-mean_lib); gsl_vector_scale(pnaq, std_par/std_lib); gsl_vector_add_constant(pnaq,mean_par); } } /** * Function Adapt_synthesis_parameters_var * * Adapt synthesis parameters according to pulse library parameters (normalize mean and var) * * @param pulse lib params * @param synthesis params */ void Adapt_synthesis_parameters_var(gsl_matrix *plsf,gsl_matrix *ptilt,gsl_matrix *pharm,gsl_matrix *phnr,gsl_matrix *pwaveform, gsl_vector *pgain,gsl_vector *ph1h2,gsl_vector *pnaq,gsl_matrix *lsf,gsl_matrix *tilt,gsl_matrix *harm,gsl_matrix *hnr, gsl_matrix *waveform,gsl_vector *gain,gsl_vector *h1h2,gsl_vector *naq,gsl_vector *fundf,gsl_vector *pulse_lengths,PARAM *params) { /* Exit if pulse library is not used */ if(params->use_pulselib == 0) return; /* Exit if adaptation is not set on */ if(params->adapt_to_pulselib == 0) return; /* Exit if pulse library normalization is set on */ if(params->normalize_pulselib == 1) { printf("Warning: Pulse library normalization and adaptation to pulse library parameters cannot be used simultaneously!\n"); return; } /* Initialize */ int i,j,k; double mean_lib,mean_par,std_lib,std_par; /* Normalize LSF */ for(i=0;i<lsf->size2;i++) { /* Evaluate means */ mean_par = 0; mean_lib = 0; for(j=0;j<plsf->size1;j++) mean_lib += gsl_matrix_get(plsf,j,i); k = 0; for(j=0;j<lsf->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { mean_par += gsl_matrix_get(lsf,j,i); k++; } } mean_lib = mean_lib/plsf->size1; mean_par = mean_par/k; /* Evaluate standard deviations */ std_par = 0; std_lib = 0; for(j=0;j<plsf->size1;j++) std_lib += (gsl_matrix_get(plsf,j,i)-mean_lib)*(gsl_matrix_get(plsf,j,i)-mean_lib); std_lib = sqrt(std_lib/(plsf->size1-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<lsf->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_matrix_get(lsf,j,i)-mean_par)*(gsl_matrix_get(lsf,j,i)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; /* Normalize */ for(j=0;j<lsf->size1;j++) if(gsl_vector_get(fundf,j) > 0) gsl_matrix_set(lsf,j,i,(gsl_matrix_get(lsf,j,i)-mean_par)/std_par*(std_lib*params->adapt_coeff + std_par*(1.0-params->adapt_coeff)) + params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par); } LSF_fix_matrix(lsf); /* Normalize LSFsource */ for(i=0;i<tilt->size2;i++) { /* Evaluate means */ mean_par = 0; mean_lib = 0; for(j=0;j<ptilt->size1;j++) mean_lib += gsl_matrix_get(ptilt,j,i); k = 0; for(j=0;j<tilt->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { mean_par += gsl_matrix_get(tilt,j,i); k++; } } mean_lib = mean_lib/ptilt->size1; mean_par = mean_par/k; /* Evaluate standard deviations */ std_par = 0; std_lib = 0; for(j=0;j<ptilt->size1;j++) std_lib += (gsl_matrix_get(ptilt,j,i)-mean_lib)*(gsl_matrix_get(ptilt,j,i)-mean_lib); std_lib = sqrt(std_lib/(ptilt->size1-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<tilt->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_matrix_get(tilt,j,i)-mean_par)*(gsl_matrix_get(tilt,j,i)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; /* Normalize */ for(j=0;j<tilt->size1;j++) if(gsl_vector_get(fundf,j) > 0) gsl_matrix_set(tilt,j,i,(gsl_matrix_get(tilt,j,i)-mean_par)/std_par*(std_lib*params->adapt_coeff + std_par*(1.0-params->adapt_coeff)) + params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par); } LSF_fix_matrix(tilt); /* Normalize HNR */ for(i=0;i<hnr->size2;i++) { /* Evaluate means */ mean_par = 0; mean_lib = 0; for(j=0;j<phnr->size1;j++) mean_lib += gsl_matrix_get(phnr,j,i); k = 0; for(j=0;j<hnr->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { mean_par += gsl_matrix_get(hnr,j,i); k++; } } mean_lib = mean_lib/phnr->size1; mean_par = mean_par/k; /* Evaluate standard deviations */ std_par = 0; std_lib = 0; for(j=0;j<phnr->size1;j++) std_lib += (gsl_matrix_get(phnr,j,i)-mean_lib)*(gsl_matrix_get(phnr,j,i)-mean_lib); std_lib = sqrt(std_lib/(phnr->size1-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<hnr->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_matrix_get(hnr,j,i)-mean_par)*(gsl_matrix_get(hnr,j,i)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; /* Normalize */ for(j=0;j<hnr->size1;j++) gsl_matrix_set(hnr,j,i,(gsl_matrix_get(hnr,j,i)-mean_par)/std_par*(std_lib*params->adapt_coeff + std_par*(1.0-params->adapt_coeff)) + params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par); } /* Normalize Harmonics */ if(params->use_harmonics == 1) { for(i=0;i<hnr->size2;i++) { /* Evaluate means */ mean_par = 0; mean_lib = 0; for(j=0;j<pharm->size1;j++) mean_lib += gsl_matrix_get(pharm,j,i); k = 0; for(j=0;j<harm->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { mean_par += gsl_matrix_get(harm,j,i); k++; } } mean_lib = mean_lib/pharm->size1; mean_par = mean_par/k; /* Evaluate standard deviations */ std_par = 0; std_lib = 0; for(j=0;j<pharm->size1;j++) std_lib += (gsl_matrix_get(pharm,j,i)-mean_lib)*(gsl_matrix_get(pharm,j,i)-mean_lib); std_lib = sqrt(std_lib/(pharm->size1-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<harm->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_matrix_get(harm,j,i)-mean_par)*(gsl_matrix_get(harm,j,i)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; /* Normalize */ for(j=0;j<harm->size1;j++) gsl_matrix_set(harm,j,i,(gsl_matrix_get(harm,j,i)-mean_par)/std_par*(std_lib*params->adapt_coeff + std_par*(1.0-params->adapt_coeff)) + params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par); } } /* Normalize Waveform */ if(params->use_waveform == 1) { for(i=0;i<hnr->size2;i++) { /* Evaluate means */ mean_par = 0; mean_lib = 0; for(j=0;j<pwaveform->size1;j++) mean_lib += gsl_matrix_get(pwaveform,j,i); k = 0; for(j=0;j<waveform->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { mean_par += gsl_matrix_get(waveform,j,i); k++; } } mean_lib = mean_lib/pwaveform->size1; mean_par = mean_par/k; /* Evaluate standard deviations */ std_par = 0; std_lib = 0; for(j=0;j<pwaveform->size1;j++) std_lib += (gsl_matrix_get(pwaveform,j,i)-mean_lib)*(gsl_matrix_get(pwaveform,j,i)-mean_lib); std_lib = sqrt(std_lib/(pwaveform->size1-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<waveform->size1;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_matrix_get(waveform,j,i)-mean_par)*(gsl_matrix_get(waveform,j,i)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; /* Normalize */ for(j=0;j<waveform->size1;j++) gsl_matrix_set(waveform,j,i,(gsl_matrix_get(waveform,j,i)-mean_par)/std_par*(std_lib*params->adapt_coeff + std_par*(1.0-params->adapt_coeff)) + params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par); } } /* Normalize Gain */ mean_lib = Mean(pgain); k = 0; mean_par = 0; for(i=0;i<gain->size;i++) { if(gsl_vector_get(fundf,i) > 0) { mean_par += gsl_vector_get(gain,i); k++; } } mean_par = mean_par/k; std_par = 0; std_lib = 0; for(j=0;j<pgain->size;j++) std_lib += (gsl_vector_get(pgain,j)-mean_lib)*(gsl_vector_get(pgain,j)-mean_lib); std_lib = sqrt(std_lib/(pgain->size-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<gain->size;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_vector_get(gain,j)-mean_par)*(gsl_vector_get(gain,j)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; for(i=0;i<gain->size;i++) if(gsl_vector_get(fundf,i) > 0) // only voiced gsl_vector_set(gain,i,(gsl_vector_get(gain,i)-mean_par)/std_par*(std_lib*params->adapt_coeff + std_par*(1.0-params->adapt_coeff)) + params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par); //gsl_vector_add_constant(gain,-params->adapt_coeff*mean_par); //gsl_vector_scale(gain, (params->adapt_coeff*std_lib + (1.0-params->adapt_coeff)*std_par)/std_par); //gsl_vector_add_constant(gain,params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par); /* Normalize H1H2 */ if(params->use_h1h2 == 1) { mean_lib = Mean(ph1h2); k = 0; mean_par = 0; for(i=0;i<h1h2->size;i++) { if(gsl_vector_get(fundf,i) > 0) { mean_par += gsl_vector_get(h1h2,i); k++; } } mean_par = mean_par/k; std_par = 0; std_lib = 0; for(j=0;j<ph1h2->size;j++) std_lib += (gsl_vector_get(ph1h2,j)-mean_lib)*(gsl_vector_get(ph1h2,j)-mean_lib); std_lib = sqrt(std_lib/(ph1h2->size-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<h1h2->size;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_vector_get(h1h2,j)-mean_par)*(gsl_vector_get(h1h2,j)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; gsl_vector_add_constant(h1h2,-params->adapt_coeff*mean_par); gsl_vector_scale(h1h2, (params->adapt_coeff*std_lib + (1.0-params->adapt_coeff)*std_par)/std_par); gsl_vector_add_constant(h1h2,params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par); } /* Normalize NAQ */ if(params->use_naq == 1) { mean_lib = Mean(pnaq); k = 0; mean_par = 0; for(i=0;i<naq->size;i++) { if(gsl_vector_get(fundf,i) > 0) { mean_par += gsl_vector_get(naq,i); k++; } } mean_par = mean_par/k; std_par = 0; std_lib = 0; for(j=0;j<pnaq->size;j++) std_lib += (gsl_vector_get(pnaq,j)-mean_lib)*(gsl_vector_get(pnaq,j)-mean_lib); std_lib = sqrt(std_lib/(pnaq->size-1)); if(std_lib == 0) std_lib = 1; k = 0; for(j=0;j<naq->size;j++) { if(gsl_vector_get(fundf,j) > 0) { std_par += (gsl_vector_get(naq,j)-mean_par)*(gsl_vector_get(naq,j)-mean_par); k++; } } std_par = sqrt(std_par/(k-1)); if(std_par == 0) std_par = 1; gsl_vector_add_constant(naq,-params->adapt_coeff*mean_par); gsl_vector_scale(naq, (params->adapt_coeff*std_lib + (1.0-params->adapt_coeff)*std_par)/std_par); gsl_vector_add_constant(naq,params->adapt_coeff*mean_lib + (1.0-params->adapt_coeff)*mean_par); } /* Normalize f0 */ mean_lib = 0; for(i=0;i<pulse_lengths->size;i++) mean_lib += log10(2.0*params->FS/gsl_vector_get(pulse_lengths,i)); mean_lib = mean_lib/pulse_lengths->size; k = 0; mean_par = 0; for(i=0;i<fundf->size;i++) { if(gsl_vector_get(fundf,i) > 0) { mean_par += log10(gsl_vector_get(fundf,i)); k++; } } mean_par = mean_par/k; for(i=0;i<fundf->size;i++) gsl_vector_set(fundf,i,pow(10,log10(gsl_vector_get(fundf,i)) + params->adapt_coeff*(-mean_par+mean_lib))); } /** * Select_LSFs_from_pulse_library * * Replace vocal tract LSFs with the closes LSFs from the pulse library * * @param lsf original LSFs * @param plsf pulse library LSFs * @param fundf fundamental frequency * @param params */ void Select_LSFs_from_pulse_library(gsl_matrix *lsf, gsl_matrix *plsf, gsl_vector *fundf, int win, PARAM *params) { if(params->use_pulselib == 0) return; if(params->use_pulselib_lsf == 0) return; int i,j,k,n,minind; double mean_par, mean_lib; gsl_vector *error = gsl_vector_alloc(plsf->size1); gsl_matrix *lsf_tmp = gsl_matrix_alloc(lsf->size1,lsf->size2); /* Replace vocal tract LSFs with the closest LSFs from the pulse library */ for(i=0;i<lsf->size1;i++) { if(gsl_vector_get(fundf,i) > 0) { gsl_vector_set_zero(error); for(n=0;n<plsf->size1;n++) for(j=0;j<lsf->size2;j++) gsl_vector_set(error,n,gsl_vector_get(error,n) + powf(gsl_matrix_get(lsf,i,j)-gsl_matrix_get(plsf,n,j),2)); minind = gsl_vector_min_index(error); for(j=0;j<lsf->size2;j++) gsl_matrix_set(lsf_tmp,i,j,gsl_matrix_get(plsf,minind,j)); } } /* Average between original LSFs and new LSFs from pulse library */ for(i=0;i<lsf->size2;i++) { for(j=0;j<lsf->size1;j++) { if(gsl_vector_get(fundf,j) == 0) continue; n = 0; mean_par = 0; mean_lib = 0; for(k=j-win;k<j+win;k++) { if(k > 0 && k < lsf->size1 && gsl_vector_get(fundf,k) > 0) { mean_lib += gsl_matrix_get(lsf_tmp,k,i); mean_par += gsl_matrix_get(lsf,k,i); n++; } } if(n > 0) { mean_lib = mean_lib/n; mean_par = mean_par/n; gsl_matrix_set(lsf,j,i,gsl_matrix_get(lsf,j,i)-mean_par + mean_lib); } } } /* Free memory */ gsl_vector_free(error); gsl_matrix_free(lsf_tmp); } /** * Function Convert_logF0_to_lin * * Convert fundamental frequency vector from natural logarithm to linear scale * * @param fundf * @param params */ void Convert_logF0_to_lin(gsl_vector *fundf, PARAM *params) { if(params->logf0 == 0) return; int i; for(i=0;i<fundf->size;i++) gsl_vector_set(fundf,i,exp(gsl_vector_get(fundf,i))); } /*****************************************************************************/ /* FUNCTIONS NOT IN USE */ /*****************************************************************************/ /** * Function Wrap * * Wrap phase angles between [-pi,pi]. * * @param phase vector of phase values * */ void Wrap(gsl_vector *phase) { int i; for(i=0;i<phase->size;i++) { while(gsl_vector_get(phase,i) < -M_PI) gsl_vector_set(phase,i,gsl_vector_get(phase,i) + 2*M_PI); while(gsl_vector_get(phase,i) > M_PI) gsl_vector_set(phase,i,gsl_vector_get(phase,i) - 2*M_PI); } } /** * Function Unwrap * * Unwrap phase angles. Algorithm minimizes the incremental phase variation * by constraining it to the range [-pi,pi] * * @param phase vector of phase values * */ void Unwrap(gsl_vector *phase) { int i; gsl_vector *dphase = gsl_vector_calloc(phase->size); gsl_vector *dphases = gsl_vector_calloc(phase->size); /* Evaluate incremental phase variation */ for(i=0;i<phase->size-1;i++) gsl_vector_set(dphase,i,gsl_vector_get(phase,i+1)-gsl_vector_get(phase,i)); /* Evaluate equivalent phase variations in [-pi,pi) */ for(i=0;i<phase->size;i++) gsl_vector_set(dphases,i,((gsl_vector_get(dphase,i)+M_PI)/(2*M_PI)-floor((gsl_vector_get(dphase,i)+M_PI)/(2*M_PI)))*2*M_PI - M_PI); /* Preserve variation sign for pi vs. -pi */ for(i=0;i<phase->size;i++) { if(gsl_vector_get(dphases,i) == -M_PI && gsl_vector_get(dphase,i) > 0) gsl_vector_set(dphases,i,M_PI); } /* Incremental phase corrections */ for(i=0;i<phase->size;i++) gsl_vector_set(dphases,i,gsl_vector_get(dphases,i)-gsl_vector_get(dphase,i)); /* Ignore correction when incr. variation is < CUTOFF, CUTOFF = M_PI */ for(i=0;i<phase->size;i++) { if(fabs(gsl_vector_get(dphase,i)) < M_PI) gsl_vector_set(dphases,i,0); } /* Integrate corrections */ for(i=1;i<phase->size;i++) gsl_vector_set(dphases,i,gsl_vector_get(dphases,i-1) + gsl_vector_get(dphases,i)); /* Add correction to phase */ for(i=0;i<phase->size-1;i++) gsl_vector_set(phase,i+1,gsl_vector_get(phase,i+1) + gsl_vector_get(dphases,i)); /* Free memory */ gsl_vector_free(dphase); gsl_vector_free(dphases); } /** * Function Unwrap2 * * Fine-tune unwrapped phase angles. * * @param phase vector of phase values * @param tol tolerance */ void Unwrap2(gsl_vector *phase, double tol) { int i,j,sign; double diff; if(gsl_vector_get(phase,0) < gsl_vector_get(phase,phase->size-1)) sign = -1; else sign = 1; for(i=1;i<phase->size-1;i++) { diff = gsl_vector_get(phase,i) - gsl_vector_get(phase,i+1); if(fabs(diff) > tol) { if(sign*diff > 0) { for(j=i+1;j<phase->size;j++) gsl_vector_set(phase,j,gsl_vector_get(phase,j) + sign*M_PI); } } } } // TEST void Create_highband_excitation(gsl_vector *excitation_highband, gsl_matrix *erbgain, PARAM *params) { ///////////////////////// int FS_high = 44100; //int FS_high = 16000; ///////////////////////// int i,j,frame_index,sample_index = 0,erb_channels = erbgain->size2,signal_length = excitation_highband->size; double r = FS_high/(double)params->FS; gsl_vector *noise; /* Start loop */ while(sample_index < signal_length) { frame_index = floor(params->n_frames*(sample_index/(double)signal_length)); if(frame_index > params->n_frames-1) frame_index = params->n_frames-1; /* Allocate noise vector */ noise = gsl_vector_calloc(rint(2.0*r*params->shift/params->speed)); /**********************************/ /* Create noise */ /**********************************/ /* Initialize */ int n = noise->size; int n2 = ceil((n-1)/2.0); gsl_vector *real = gsl_vector_calloc(n); gsl_vector *imag = gsl_vector_calloc(n); gsl_vector *gain_values = gsl_vector_alloc(n2); gsl_vector *erb_inds = gsl_vector_alloc(n2); /* Evaluate ERB scale indices */ for(i=0;i<n2;i++) gsl_vector_set(erb_inds,i,log10(0.00437*(i/(n2-1.0)*(FS_high/2.0))+1.0)/log10(0.00437*(FS_high/2.0)+1.0)*(erb_channels-SMALL_NUMBER)); /* Evaluate values according to ERB rate */ for(i=0;i<n2;i++) { j = floor(gsl_vector_get(erb_inds,i)); gsl_vector_set(gain_values,i,gsl_matrix_get(erbgain,frame_index,j)); } /* Convert HNR values from logarithmic scale to linear scale (actual noise amplitudes) */ for(i=0;i<n2;i++) gsl_vector_set(gain_values,i,pow(10,(gsl_vector_get(gain_values,i)/20.0))); /* Modify both the magnitude and the phase of the spectrum */ double lfl = 0.3628; for(i=rint(lfl*n2);i<n2;i++) { gsl_vector_set(imag,i+1, RAND()*gsl_vector_get(gain_values,i)); gsl_vector_set(real,i+1, RAND()*gsl_vector_get(gain_values,i)); } /* Copy the noise to the folded spectrum as well */ if(imag->size%2 == 0) { for(i=0;i<n2;i++) { gsl_vector_set(imag,n2+i,-gsl_vector_get(imag,n2-i)); gsl_vector_set(real,n2+i,gsl_vector_get(real,n2-i)); } } else { for(i=0;i<n2;i++) { gsl_vector_set(imag,n2+1+i,-gsl_vector_get(imag,n2-i)); gsl_vector_set(real,n2+1+i,gsl_vector_get(real,n2-i)); } } /* Create halfcomplex data */ double data[n]; data[0] = gsl_vector_get(real,0); for(i=1;i<n;i++) { if(i%2 == 1) data[i] = gsl_vector_get(real,(i+1)/2); else data[i] = gsl_vector_get(imag,i/2); } /* Inverse FFT */ gsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(n); gsl_fft_halfcomplex_wavetable *whc = gsl_fft_halfcomplex_wavetable_alloc(n); gsl_fft_halfcomplex_inverse(data,1,n,whc,work); gsl_fft_halfcomplex_wavetable_free(whc); gsl_fft_real_workspace_free(work); /* Set data from array "data" to vector "noise" */ for(i=0;i<n;i++) gsl_vector_set(noise,i,data[i]); /* Free memory */ gsl_vector_free(real); gsl_vector_free(imag); gsl_vector_free(gain_values); gsl_vector_free(erb_inds); /**********************************/ /* End of create noise */ /**********************************/ /* Windown noise */ for(i=0;i<n;i++) gsl_vector_set(noise,i,gsl_vector_get(noise,i)*HANN(i,n)); /* Set noise to excitation */ int q = rint(0.25*n); int ind; for(i=0;i<noise->size;i++) { ind = GSL_MIN(GSL_MAX(sample_index+i-q,0),excitation_highband->size-1); gsl_vector_set(excitation_highband,ind,gsl_vector_get(excitation_highband,ind) + gsl_vector_get(noise,i)); } /* Free memory */ gsl_vector_free(noise); /* Increment sample index */ sample_index += rint(r*params->shift/params->speed); } } /*********************************************************************/ /* TEST FUNCTIONS */ /*********************************************************************/ // TEST FUNCTION // PRINT VECTOR TO FILE: p1.dat void VPrint1(gsl_vector *vector) { FILE *f = fopen("p1.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p2.dat void VPrint2(gsl_vector *vector) { FILE *f = fopen("p2.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p3.dat void VPrint3(gsl_vector *vector) { FILE *f = fopen("p3.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p4.dat void VPrint4(gsl_vector *vector) { FILE *f = fopen("p4.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p5.dat void VPrint5(gsl_vector *vector) { FILE *f = fopen("p5.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p6.dat void VPrint6(gsl_vector *vector) { FILE *f = fopen("p6.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p7.dat void VPrint7(gsl_vector *vector) { FILE *f = fopen("p7.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p8.dat void VPrint8(gsl_vector *vector) { FILE *f = fopen("p8.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p9.dat void VPrint9(gsl_vector *vector) { FILE *f = fopen("p9.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p10.dat void VPrint10(gsl_vector *vector) { FILE *f = fopen("p10.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p11.dat void VPrint11(gsl_vector *vector) { FILE *f = fopen("p11.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT VECTOR TO FILE: p12.dat void VPrint12(gsl_vector *vector) { FILE *f = fopen("p12.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT MATRIX TO FILE: m1.dat void MPrint1(gsl_matrix *matrix) { FILE *f = fopen("m1.dat", "w"); gsl_matrix_fprintf(f, matrix, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT MATRIX TO FILE: m2.dat void MPrint2(gsl_matrix *matrix) { FILE *f = fopen("m2.dat", "w"); gsl_matrix_fprintf(f, matrix, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT MATRIX TO FILE: m3.dat void MPrint3(gsl_matrix *matrix) { FILE *f = fopen("m3.dat", "w"); gsl_matrix_fprintf(f, matrix, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT MATRIX TO FILE: m4.dat void MPrint4(gsl_matrix *matrix) { FILE *f = fopen("m4.dat", "w"); gsl_matrix_fprintf(f, matrix, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT MATRIX TO FILE: m5.dat void MPrint5(gsl_matrix *matrix) { FILE *f = fopen("m5.dat", "w"); gsl_matrix_fprintf(f, matrix, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT MATRIX TO FILE: m6.dat void MPrint6(gsl_matrix *matrix) { FILE *f = fopen("m6.dat", "w"); gsl_matrix_fprintf(f, matrix, "%.15f"); fclose(f); } // TEST FUNCTION // PRINT ARRAY TO FILE: a1.dat void APrint1(double *array, int size) { int i; gsl_vector *vector = gsl_vector_alloc(size); for(i=0;i<size;i++) gsl_vector_set(vector,i,array[i]); FILE *f = fopen("a1.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); gsl_vector_free(vector); } // TEST FUNCTION // PRINT ARRAY TO FILE: a2.dat void APrint2(double *array, int size) { int i; gsl_vector *vector = gsl_vector_alloc(size); for(i=0;i<size;i++) gsl_vector_set(vector,i,array[i]); FILE *f = fopen("a2.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); gsl_vector_free(vector); } // TEST FUNCTION // PRINT ARRAY TO FILE: a3.dat void APrint3(double *array, int size) { int i; gsl_vector *vector = gsl_vector_alloc(size); for(i=0;i<size;i++) gsl_vector_set(vector,i,array[i]); FILE *f = fopen("a3.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); gsl_vector_free(vector); } // TEST FUNCTION // PRINT ARRAY TO FILE: a4.dat void APrint4(double *array, int size) { int i; gsl_vector *vector = gsl_vector_alloc(size); for(i=0;i<size;i++) gsl_vector_set(vector,i,array[i]); FILE *f = fopen("a4.dat", "w"); gsl_vector_fprintf(f, vector, "%.15f"); fclose(f); gsl_vector_free(vector); } // TEST FUNCTION // PRINT ELAPSED TIME void TimePrint(double start_time) { printf("\n\nElapsed time: %1.2lf seconds.\n\n",((double)clock()-start_time)/(double)CLOCKS_PER_SEC); } // TEST FUNCTION // PAUSE void pause(int print) { if(print == 1) printf("\n\nPAUSED - PRESS ENTER TO CONTINUE\n"); getchar(); } // TEST FUNCTION // TEST FOR NANS AND INFS (MATRIX) int Find_matrix_NaN_Inf(gsl_matrix *m) { int i,j,err = 0; for(i=0;i<m->size1;i++) { for(j=0;j<m->size2;j++) { if(isnan(gsl_matrix_get(m,i,j)) == 1) { printf("Warning: NaN value found!\n"); err = 1; } if(isinf(gsl_matrix_get(m,i,j)) == 1) { printf("Warning: Inf value found!\n"); err = 1; } } } return err; } // TEST FUNCTION // TEST FOR NANS AND INFS (VECTOR) int Find_vector_NaN_Inf(gsl_vector *v) { int i,err = 0; for(i=0;i<v->size;i++) { if(isnan(gsl_vector_get(v,i)) == 1) { printf("Warning: NaN value found!\n"); err = 1; } if(isinf(gsl_vector_get(v,i)) == 1) { printf("Warning: Inf value found!\n"); err = 1; } } return err; }
{ "alphanum_fraction": 0.6823129179, "avg_line_length": 29.4100787402, "ext": "c", "hexsha": "e23f9e98cfd132216bfc741f97f7629d87ab2f44", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:17:33.000Z", "max_forks_repo_forks_event_min_datetime": "2016-08-03T12:08:32.000Z", "max_forks_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mjansche/GlottHMM", "max_forks_repo_path": "src/SynthesisFunctions.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mjansche/GlottHMM", "max_issues_repo_path": "src/SynthesisFunctions.c", "max_line_length": 259, "max_stars_count": 10, "max_stars_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mjansche/GlottHMM", "max_stars_repo_path": "src/SynthesisFunctions.c", "max_stars_repo_stars_event_max_datetime": "2020-09-03T12:46:50.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-29T22:08:09.000Z", "num_tokens": 87142, "size": 280131 }
#pragma once /*************************************************** *************** Auto-Generated File *************** ***************************************************/ #include <cstring> #include <string> #include <gsl/gsl_const_mksa.h> #include <gsl/gsl_const_num.h> #include "../../Utils/BinarySearch.h" enum UnitType { NONE, DISTANCE, TIME, TIMESQUARED, SPEED, ACCELERATION, AREA, VOLUME, MASS, FORCE, MASSDISTANCE, MASSPERTIMESQUARED, ENERGY, MASSAREA }; constexpr const int numUnits = 161; constexpr const char* unitNames[numUnits] = { "acre", "astronomical_unit", "attogram", "attometer", "attometerscubed", "attometerssquared", "attosecond", "barn", "btu", "calorie", "canadian_gallon", "carat", "centimeter", "century", "cup", "decade", "decameter", "decimeter", "dyne", "electron_volt", "erg", "exagram", "exameter", "exameterscubed", "exameterssquared", "exasecond", "fathom", "femtogram", "femtometer", "femtometerscubed", "femtometerssquared", "femtosecond", "fluid_ounce", "foot", "gigagram", "gigameter", "gigameterscubed", "gigameterssquared", "gigasecond", "gram", "gram_force", "grammeter", "grammeterspersecondsquared", "grammeterssquared", "grammeterssquaredpersecondsquared", "grampersecondsquared", "grav_accel", "hectare", "hectometer", "hour", "inch", "joule", "kilogram", "kilometer", "kilometers_per_hour", "kilometerscubed", "kilometerssquared", "kilopound_force", "kilosecond", "knot", "light_year", "liter", "mass_electron", "mass_muon", "mass_neutron", "mass_proton", "megagram", "megameter", "megameterscubed", "megameterssquared", "megasecond", "meter", "meterscubed", "meterspersecond", "meterspersecondsquared", "meterssquared", "metric_ton", "microgram", "microliter", "micrometer", "micrometerscubed", "micrometerssquared", "microsecond", "mil", "mile", "miles_per_hour", "millenium", "milligram", "milliliter", "millimeter", "millimeterscubed", "millimeterssquared", "millisecond", "minute", "month", "nanogram", "nanometer", "nanometerscubed", "nanometerssquared", "nanosecond", "nautical_mile", "newton", "newton_meter", "ounce_mass", "petagram", "petameter", "petameterscubed", "petameterssquared", "petasecond", "picogram", "picometer", "picometerscubed", "picometerssquared", "picosecond", "pint", "pound_force", "pound_mass", "poundal", "quart", "rydberg", "second", "secondsquared", "solar_mass", "speed_of_light", "tablespoon", "teaspoon", "teragram", "terameter", "terameterscubed", "terameterssquared", "terasecond", "therm", "ton", "troy_ounce", "uk_gallon", "uk_ton", "unified_atomic_mass", "us_gallon", "week", "yard", "year", "yoctogram", "yoctometer", "yoctometerscubed", "yoctometerssquared", "yoctosecond", "yottagram", "yottameter", "yottameterscubed", "yottameterssquared", "yottasecond", "zeptogram", "zeptometer", "zeptometerscubed", "zeptometerssquared", "zeptosecond", "zettagram", "zettameter", "zettameterscubed", "zettameterssquared", "zettasecond" }; constexpr const int unitIndices[numUnits] = { 52, 0, 53, 54, 56, 55, 57, 58, 59, 61, 2, 1, 63, 62, 64, 66, 65, 67, 3, 4, 68, 5, 6, 8, 7, 9, 76, 69, 71, 73, 72, 74, 70, 75, 11, 12, 14, 13, 15, 77, 83, 78, 79, 80, 81, 82, 10, 85, 86, 84, 87, 16, 88, 90, 94, 92, 91, 89, 95, 93, 98, 17, 102, 103, 104, 105, 19, 20, 22, 21, 23, 99, 107, 100, 101, 106, 118, 142, 143, 144, 146, 145, 147, 110, 109, 116, 112, 108, 111, 113, 115, 114, 117, 18, 119, 120, 121, 123, 122, 125, 124, 24, 25, 126, 26, 27, 29, 28, 30, 128, 129, 131, 130, 132, 133, 97, 96, 127, 134, 31, 135, 136, 32, 60, 138, 141, 33, 34, 36, 35, 37, 139, 137, 140, 39, 40, 38, 41, 148, 149, 154, 150, 151, 153, 152, 155, 42, 43, 45, 44, 46, 156, 157, 159, 158, 160, 47, 48, 50, 49, 51 }; constexpr const char * unitAbbreviations[numUnits] = { "AU", "CD", "CG", "Dy", "EV", "Eg", "Em", "Em^2", "Em^3", "Es", "G", "Gg", "Gm", "Gm^2", "Gm^3", "Gs", "J", "L", "M", "Mg", "Mm", "Mm^2", "Mm^3", "Ms", "N", "Nm", "Pg", "Pm", "Pm^2", "Pm^3", "Ps", "Ry", "SM", "Tg", "Tm", "Tm^2", "Tm^3", "Ts", "UAM", "UKG", "UKT", "USG", "Yg", "Ym", "Ym^2", "Ym^3", "Ys", "Zg", "Zm", "Zm^2", "Zm^3", "Zs", "ac", "ag", "am", "am^2", "am^3", "as", "bn", "btu", "c", "cal", "cen", "cm", "cp", "dcm", "dec", "dm", "erg", "fg", "floz", "fm", "fm^2", "fm^3", "fs", "ft", "fth", "g", "g*m", "g*m/s^2", "g*m^2", "g*m^2/s^2", "g/s^2", "gF", "h", "hec", "hm", "in", "kg", "klbF", "km", "km^2", "km^3", "knt", "kph", "ks", "lb", "lbF", "ly", "m", "m/s", "m/s^2", "mE", "mMu", "mNt", "mPt", "m^2", "m^3", "mg", "mi", "mil", "ml", "mln", "mm", "mm^2", "mm^3", "mph", "ms", "mt", "mth", "ng", "nm", "nm^2", "nm^3", "nmi", "ns", "oz", "pdl", "pg", "pm", "pm^2", "pm^3", "ps", "pt", "qt", "s", "s^2", "t", "tbsp", "thm", "toz", "tsp", "ug", "ul", "um", "um^2", "um^3", "us", "wk", "yd", "yg", "ym", "ym^2", "ym^3", "yr", "ys", "zg", "zm", "zm^2", "zm^3", "zs" }; constexpr const UnitType unitTypes[numUnits] = { DISTANCE, MASS, VOLUME, FORCE, ENERGY, MASS, DISTANCE, AREA, VOLUME, TIME, ACCELERATION, MASS, DISTANCE, AREA, VOLUME, TIME, ENERGY, VOLUME, TIME, MASS, DISTANCE, AREA, VOLUME, TIME, FORCE, ENERGY, MASS, DISTANCE, AREA, VOLUME, TIME, ENERGY, MASS, MASS, DISTANCE, AREA, VOLUME, TIME, MASS, VOLUME, MASS, VOLUME, MASS, DISTANCE, AREA, VOLUME, TIME, MASS, DISTANCE, AREA, VOLUME, TIME, AREA, MASS, DISTANCE, AREA, VOLUME, TIME, AREA, ENERGY, SPEED, ENERGY, TIME, DISTANCE, VOLUME, DISTANCE, TIME, DISTANCE, ENERGY, MASS, VOLUME, DISTANCE, AREA, VOLUME, TIME, DISTANCE, DISTANCE, MASS, MASSDISTANCE, FORCE, MASSAREA, ENERGY, MASSPERTIMESQUARED, FORCE, TIME, AREA, DISTANCE, DISTANCE, MASS, FORCE, DISTANCE, AREA, VOLUME, SPEED, SPEED, TIME, MASS, FORCE, DISTANCE, DISTANCE, SPEED, ACCELERATION, MASS, MASS, MASS, MASS, AREA, VOLUME, MASS, DISTANCE, DISTANCE, VOLUME, TIME, DISTANCE, AREA, VOLUME, SPEED, TIME, MASS, TIME, MASS, DISTANCE, AREA, VOLUME, DISTANCE, TIME, MASS, FORCE, MASS, DISTANCE, AREA, VOLUME, TIME, VOLUME, VOLUME, TIME, TIMESQUARED, MASS, VOLUME, ENERGY, MASS, VOLUME, MASS, VOLUME, DISTANCE, AREA, VOLUME, TIME, TIME, DISTANCE, MASS, DISTANCE, AREA, VOLUME, TIME, TIME, MASS, DISTANCE, AREA, VOLUME, TIME }; constexpr const double unitConversions[numUnits] = { GSL_CONST_MKSA_ASTRONOMICAL_UNIT, GSL_CONST_MKSA_CARAT*1000.0, GSL_CONST_MKSA_CANADIAN_GALLON, GSL_CONST_MKSA_DYNE*1000.0, GSL_CONST_MKSA_ELECTRON_VOLT*1000.0, GSL_CONST_NUM_EXA, GSL_CONST_NUM_EXA, GSL_CONST_NUM_EXA, GSL_CONST_NUM_EXA, GSL_CONST_NUM_EXA, GSL_CONST_MKSA_GRAV_ACCEL, GSL_CONST_NUM_GIGA, GSL_CONST_NUM_GIGA, GSL_CONST_NUM_GIGA, GSL_CONST_NUM_GIGA, GSL_CONST_NUM_GIGA, GSL_CONST_MKSA_JOULE*1000.0, GSL_CONST_MKSA_LITER, GSL_CONST_MKSA_MINUTE, GSL_CONST_NUM_MEGA, GSL_CONST_NUM_MEGA, GSL_CONST_NUM_MEGA, GSL_CONST_NUM_MEGA, GSL_CONST_NUM_MEGA, GSL_CONST_MKSA_NEWTON*1000.0, 1000, GSL_CONST_NUM_PETA, GSL_CONST_NUM_PETA, GSL_CONST_NUM_PETA, GSL_CONST_NUM_PETA, GSL_CONST_NUM_PETA, GSL_CONST_MKSA_RYDBERG*1000.0, GSL_CONST_MKSA_SOLAR_MASS*1000.0, GSL_CONST_NUM_TERA, GSL_CONST_NUM_TERA, GSL_CONST_NUM_TERA, GSL_CONST_NUM_TERA, GSL_CONST_NUM_TERA, GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS*1000.0, GSL_CONST_MKSA_UK_GALLON, GSL_CONST_MKSA_UK_TON*1000.0, GSL_CONST_MKSA_US_GALLON, GSL_CONST_NUM_YOTTA, GSL_CONST_NUM_YOTTA, GSL_CONST_NUM_YOTTA, GSL_CONST_NUM_YOTTA, GSL_CONST_NUM_YOTTA, GSL_CONST_NUM_ZETTA, GSL_CONST_NUM_ZETTA, GSL_CONST_NUM_ZETTA, GSL_CONST_NUM_ZETTA, GSL_CONST_NUM_ZETTA, GSL_CONST_MKSA_ACRE, GSL_CONST_NUM_ATTO, GSL_CONST_NUM_ATTO, GSL_CONST_NUM_ATTO, GSL_CONST_NUM_ATTO, GSL_CONST_NUM_ATTO, GSL_CONST_MKSA_BARN, GSL_CONST_MKSA_BTU*1000.0, GSL_CONST_MKSA_SPEED_OF_LIGHT, GSL_CONST_MKSA_CALORIE*1000.0, 3153600000, 1e-2, GSL_CONST_MKSA_CUP, 1e1, 315360000, 1e-1, GSL_CONST_MKSA_ERG*1000.0, GSL_CONST_NUM_FEMTO, GSL_CONST_MKSA_FLUID_OUNCE, GSL_CONST_NUM_FEMTO, GSL_CONST_NUM_FEMTO, GSL_CONST_NUM_FEMTO, GSL_CONST_NUM_FEMTO, GSL_CONST_MKSA_FOOT, GSL_CONST_MKSA_FATHOM, 1, 1, 1, 1, 1, 1, GSL_CONST_MKSA_GRAM_FORCE*1000.0, GSL_CONST_MKSA_HOUR, GSL_CONST_MKSA_HECTARE, 1e2, GSL_CONST_MKSA_INCH, GSL_CONST_NUM_KILO, GSL_CONST_MKSA_KILOPOUND_FORCE*1000.0, GSL_CONST_NUM_KILO, GSL_CONST_NUM_KILO, GSL_CONST_NUM_KILO, GSL_CONST_MKSA_KNOT, GSL_CONST_MKSA_KILOMETERS_PER_HOUR, GSL_CONST_NUM_KILO, GSL_CONST_MKSA_POUND_MASS*1000.0, GSL_CONST_MKSA_POUND_FORCE*1000.0, GSL_CONST_MKSA_LIGHT_YEAR, 1, 1, 1, GSL_CONST_MKSA_MASS_ELECTRON*1000.0, GSL_CONST_MKSA_MASS_MUON*1000.0, GSL_CONST_MKSA_MASS_NEUTRON*1000.0, GSL_CONST_MKSA_MASS_PROTON*1000.0, 1, 1, GSL_CONST_NUM_MILLI, GSL_CONST_MKSA_MILE, GSL_CONST_MKSA_MIL, 1e-6, 31536000000, GSL_CONST_NUM_MILLI, GSL_CONST_NUM_MILLI, GSL_CONST_NUM_MILLI, GSL_CONST_MKSA_MILES_PER_HOUR, GSL_CONST_NUM_MILLI, GSL_CONST_MKSA_METRIC_TON*1000.0, 2628288, GSL_CONST_NUM_NANO, GSL_CONST_NUM_NANO, GSL_CONST_NUM_NANO, GSL_CONST_NUM_NANO, GSL_CONST_MKSA_NAUTICAL_MILE, GSL_CONST_NUM_NANO, GSL_CONST_MKSA_OUNCE_MASS*1000.0, GSL_CONST_MKSA_POUNDAL*1000.0, GSL_CONST_NUM_PICO, GSL_CONST_NUM_PICO, GSL_CONST_NUM_PICO, GSL_CONST_NUM_PICO, GSL_CONST_NUM_PICO, GSL_CONST_MKSA_PINT, GSL_CONST_MKSA_QUART, 1, 1, GSL_CONST_MKSA_TON*1000.0, GSL_CONST_MKSA_TABLESPOON, GSL_CONST_MKSA_THERM*1000.0, GSL_CONST_MKSA_TROY_OUNCE*1000.0, GSL_CONST_MKSA_TEASPOON, GSL_CONST_NUM_MICRO, 1e-9, GSL_CONST_NUM_MICRO, GSL_CONST_NUM_MICRO, GSL_CONST_NUM_MICRO, GSL_CONST_NUM_MICRO, GSL_CONST_MKSA_WEEK, GSL_CONST_MKSA_YARD, GSL_CONST_NUM_YOCTO, GSL_CONST_NUM_YOCTO, GSL_CONST_NUM_YOCTO, GSL_CONST_NUM_YOCTO, 31536000, GSL_CONST_NUM_YOCTO, GSL_CONST_NUM_ZEPTO, GSL_CONST_NUM_ZEPTO, GSL_CONST_NUM_ZEPTO, GSL_CONST_NUM_ZEPTO, GSL_CONST_NUM_ZEPTO }; /* Returns index of the unit in the unitNames array. Uses binary search under the hood to search for the index. Parameters ---------- name: The name of the unit Returns ------- The index or -1 if the provided name is not a unit. */ CONSTEXPR_BINARY_SEARCH(getUnitIndex, unitNames, numUnits) CONSTEXPR_BINARY_SEARCH(getAbbrIndex, unitAbbreviations, numUnits) constexpr UnitType getUnitType(const char* name){ int index = getUnitIndex(name); if (index != -1){ return NONE; } return unitTypes[index]; } inline UnitType getUnitType(const std::string& name){ int index = getUnitIndex(name.c_str()); if (index != -1){ return NONE; } return unitTypes[index]; } inline UnitType getUnitType(int index){ if (index < 0 || index >= numUnits){ return NONE; } return unitTypes[index]; } constexpr double getUnitConversion(const char* name){ int index = getUnitIndex(name); if (index != -1){ return NONE; } return unitConversions[index]; } inline double getUnitConversion(const std::string& name){ int index = getUnitIndex(name.c_str()); if (index != -1){ return NONE; } return unitConversions[index]; } inline double getUnitConversion(int index){ if (index < 0 || index >= numUnits){ return NONE; } return unitConversions[index]; }
{ "alphanum_fraction": 0.7092927254, "avg_line_length": 51.4198113208, "ext": "h", "hexsha": "c9ab21ebaeac616bd049152213105fa3198ce11e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "antoniojkim/CalcPlusPlus", "max_forks_repo_path": "MathEngine/Expressions/UnitConversionExpression/Units.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "antoniojkim/CalcPlusPlus", "max_issues_repo_path": "MathEngine/Expressions/UnitConversionExpression/Units.h", "max_line_length": 89, "max_stars_count": null, "max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "antoniojkim/CalcPlusPlus", "max_stars_repo_path": "MathEngine/Expressions/UnitConversionExpression/Units.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4237, "size": 10901 }
// @Copyright 2007-2017 Kristjan Haule #include <iostream> #include <fstream> #include <vector> #include <gsl/gsl_vector.h> #include <gsl/gsl_multiroots.h> #include "logging.h" #include "smesh.h" #include "sfunction.h" #include "tanmesh.h" #include "romberg.h" #include <time.h> #ifdef _MPI #include <mpi.h> #endif using namespace std; inline double fermi_kernel(double t, double w, double beta) { double x = beta*w/2; double y = 2.*t/beta-1.; if (x>100.) return exp(-x*(y+1.)); if (x<-100) return exp(x*(1.-y)); return exp(-x*y)/(2*cosh(x)); } inline double bose_kernel(double t, double w, double beta) { double x = beta*w/2; double y = 2.*t/beta-1.; if (x>200.) return w*exp(-x*(y+1.)); if (x<-200.) return -w*exp(x*(1.-y)); return w*exp(-x*y)/(2*sinh(x)); } inline void create_log_mesh(function1D<int>& ind_om, int nom_all, int nom, int ntail_) { //Creates logarithmic mesh on Matsubara axis // Takes first istart points from mesh om and the rest of om mesh is replaced by ntail poinst redistribued logarithmically. // Input: // om -- original long mesh // nom -- number of points not in the tail // ntail -- tail replaced by ntail points only // Output: // ind_om -- index array which conatins index to kept Matsubara points int istart = min(nom, nom_all); int ntail = min(ntail_, nom_all-istart); ind_om.resize(istart+ntail); double alpha = log((nom_all-1.)/istart)/(ntail-1.); for (int i=0; i< istart; i++) ind_om[i]=i; int ii=istart; for (int i=0; i < ntail; i++){ int t = int(istart*exp(alpha*i)+0.5); if (t != ind_om[ii-1]) ind_om[ii++] = t; } ind_om.resize(ii); } class SVDFunc{ public: vector<spline1D<double> > fU, fU_bose; // SVD functions in imaginary time mesh1D tau; // imaginary time optimized mesh int lmax, lmax_bose; // cutoff for the singular values int k_ovlp; // 2^{k_ovlp}+1 is the number of integration points in romberg method mesh1D om; // real axis mesh for SVD function1D<double> S, S_bose; // eigenvalues of SVD decomposition function2D<double> Vt, Vt_bose; // real axis basis functions function1D<double> dxi; // parts of fU splines stored in more efficient way for fast interpolation function3D<double> ff2; // fU splines stored in different way for fast interpolation double beta, L, x0; // parameters of the mesh should be remembered for reproducibility // SVDFunc() : lmax(0) { }; // bool operator()() // was it ever initialized? { return lmax>0; } double operator()(int l, int i){ if (l<0) l=lmax-l; if (i<0) i=tau.size()+i; return fU[l][i]; } double operator()(int l, int i) const{ if (l<0) l=lmax-l; if (i<0) i=tau.size()+i; return fU[l][i]; } spline1D<double>& operator[](int l){ return fU[l]; } inline vector<int> get_lll(int ii) { // conversion from a single combined index to the three l indices. //int ii = l0 + lmax*l1 + lmax*lmax*lb; int lb_ = ii / (lmax*lmax); int ir = ii % (lmax*lmax); int l1_ = ir / lmax; int l0_ = ir % lmax; int tmp[] = { l0_, l1_, lb_ }; return vector<int>(tmp, tmp+3 ); } void _cmp_(double beta, int& lmax, vector<spline1D<double> >& fU, function1D<double>& S, function2D<double>& Vt, function2D<double>& K, ostream& clog){ clock_t t0 = clock(); int Nl = min(om.size(),tau.size()); S.resize(Nl); Vt.resize(om.size(),Nl); function2D<double> U(Nl,tau.size()); int lwork; { int n = min(tau.size(),om.size()); int mx = max(tau.size(),om.size()); lwork = 4*n*n + 8*max(mx, n*(n+1)); } function1D<double> work(lwork); function1D<int> iwork(8*min(om.size(),tau.size())); int info=0; info = xgesdd(true, tau.size(), om.size(), K.MemPt(), K.fullsize_Nd(), S.MemPt(), U.MemPt(), U.fullsize_Nd(), Vt.MemPt(), Vt.fullsize_Nd(),work.MemPt(), lwork, work.MemPt(), iwork.MemPt()); if (info!=0){ clog << "svd is returning "<<info<<" in svdfunc"<<endl; } double dt = static_cast<double>( clock() - t0 )/CLOCKS_PER_SEC; clog<<"svd time="<<dt<<endl; for (int l=0; l<lmax; l++) if (fabs(S[l])<1e-13){ lmax=l; clog<<"lmax reduced to "<<lmax<<endl; break; } clog<<"last singular value="<<S[lmax-1]<<endl; for (int i=0; i<tau.size(); i++) for (int l=0; l<Nl; l++) U(l,i) *= 1./sqrt(tau.Dh(i)); // Splines functions, which are singular values of the Kernel. vector<spline1D<double> > fu(lmax); for (int l=0; l<lmax; l++){ fu[l].resize(tau.size()); for (int i=0; i<tau.size(); i++) fu[l][i] = U(l,i); int n = tau.size(); double x1 = 0.5*(tau[1]+tau[0]); double df1 = (U(l,1)-U(l,0))/(tau[1]-tau[0]); double x2 = 0.5*(tau[2]+tau[1]); double df2 = (U(l,2)-U(l,1))/(tau[2]-tau[1]); double df0 = df1 + (df2-df1)*(0.0-x1)/(x2-x1); x1 = 0.5*(tau[n-1]+tau[n-2]); df1 = (U(l,n-1)-U(l,n-2))/(tau[n-1]-tau[n-2]); x2 = 0.5*(tau[n-2]+tau[n-3]); df2 = (U(l,n-2)-U(l,n-3))/(tau[n-2]-tau[n-3]); double dfn = df1 + (df2-df1)*(beta-x1)/(x2-x1); fu[l].splineIt(tau, df0, dfn); } // Calculates overlap between spline interpolations function2D<double> overlap(lmax,lmax); cmpOverlap(overlap, fu, tau, beta, k_ovlp); // Calculates eigensystem of the overlap function1D<double> oE(lmax); SymEigensystem(overlap, oE); function2D<double> sou(overlap);// sou = 1/sqrt(overlap) // Computes 1/sqrt(overlap) for (int i=0; i<lmax; i++){ for (int j=0; j<lmax; j++){ double dsum =0.0; for (int k=0; k<lmax; k++) dsum += overlap(k,i)*1/sqrt(oE[k])*overlap(k,j); sou(i,j) = dsum; } } // Prepares new spline functions, which are more precisely orthonormal. fU.resize(lmax); for (int l=0; l<lmax; l++){ fU[l].resize(tau.size()); for (int i=0; i<tau.size(); i++){ double ul=0; for (int lp=0; lp<lmax; lp++) ul += sou(l,lp)*fu[lp][i]; fU[l][i] = ul; } int n = tau.size(); double x1 = 0.5*(tau[1]+tau[0]); double df1 = (fU[l][1]-fU[l][0])/(tau[1]-tau[0]); double x2 = 0.5*(tau[2]+tau[1]); double df2 = (fU[l][2]-fU[l][1])/(tau[2]-tau[1]); double df0 = df1 + (df2-df1)*(0.0-x1)/(x2-x1); x1 = 0.5*(tau[n-1]+tau[n-2]); df1 = (fU[l][n-1]-fU[l][n-2])/(tau[n-1]-tau[n-2]); x2 = 0.5*(tau[n-2]+tau[n-3]); df2 = (fU[l][n-2]-fU[l][n-3])/(tau[n-2]-tau[n-3]); double dfn = df1 + (df2-df1)*(beta-x1)/(x2-x1); fU[l].splineIt(tau, df0, dfn); } } // void cmp(const string& statistics, double beta_, int lmax_, int Ntau, double x0_, double L_, double Nw, ostream& clog, int k_ovlp_=5){ k_ovlp=k_ovlp_; beta = beta_; L = L_; x0 = x0_; GiveTanMesh(om, x0, L, Nw); GiveDoubleExpMesh(tau, beta, Ntau); if (statistics=="fermi" || statistics=="both"){ lmax = lmax_; clock_t t0 = clock(); function2D<double> K(om.size(),tau.size()); for (int j=0; j<om.size(); j++){ for (int i=0; i<tau.size(); i++){ K(j,i) = fermi_kernel(tau[i],om[j],beta); K(j,i) *= om.Dh(j)*sqrt(tau.Dh(i)); } } double dt = static_cast<double>( clock() - t0 )/CLOCKS_PER_SEC; clog<<"setup time="<<dt<<endl; _cmp_(beta, lmax, fU, S, Vt, K, clog); } if (statistics=="bose" || statistics=="both"){ lmax_bose = lmax_; clock_t t0 = clock(); function2D<double> K(om.size(),tau.size()); for (int j=0; j<om.size(); j++){ for (int i=0; i<tau.size(); i++){ K(j,i) = bose_kernel(tau[i],om[j],beta); K(j,i) *= om.Dh(j)*sqrt(tau.Dh(i)); } } double dt = static_cast<double>( clock() - t0 )/CLOCKS_PER_SEC; clog<<"setup time="<<dt<<endl; _cmp_(beta, lmax_bose, fU_bose, S_bose, Vt_bose, K, clog); //cout<<"S_bose="<<S_bose<<endl; } } void Print(const string& filename, const string& statistics="fermi"){ ofstream pul(filename.c_str()); pul<<"# "<<lmax<<" "<<tau.size()<<" "<<L<<" "<<x0<<" "<<(om.size()/2)<<endl; pul.precision(16); for (int i=0; i<tau.size(); i++){ pul<<tau[i]<<" "; if (statistics=="fermi") for (int l=0; l<lmax; l++) pul<<fU[l][i]<<" "; else for (int l=0; l<lmax_bose; l++) pul<<fU_bose[l][i]<<" "; pul<<endl; } } double CheckOverlap(/*double beta*/){ // Now we check how well is the orthogonality obeyed after reorthogonalization function2D<double> overlap(lmax,lmax); cmpOverlap(overlap, fU, tau, beta, k_ovlp); double dsum=0; for (int l1=0; l1<lmax; l1++){ for (int l2=0; l2<lmax; l2++){ if (l1!=l2 && overlap(l1,l2)!=0) dsum += fabs(overlap(l1,l2)); if (l1==l2) dsum += fabs(overlap(l1,l2)-1.0); } } return dsum; } void cmpOverlap(function2D<double>& overlap, const vector<spline1D<double> >& fu, const mesh1D& tau, double beta, int k=5){ int lmax = fu.size(); int M = static_cast<int>(pow(2.0,k))+1; // Number of points in Romberg integration routine vector<double> utu(M); // storage for Romberg overlap.resize(lmax,lmax); overlap=0.0; int nt = tau.size(); for (int l1=0; l1<lmax; l1++){ double odd_1 = fu[l1][0]*fu[l1][nt-1]; for (int l2=0; l2<=l1; l2++){ double odd_2 = fu[l2][0]*fu[l2][nt-1]; if (odd_1*odd_2 > 0){// both are even or odd double oij=0; // overlap between u_{l1} and u_{l2} functions for (int i=0; i<tau.size()-1; i++){ // here we integrate with a fine mesh of M points using romberg routine double a = tau[i]; // integral only between t_i and t_{i+1} points double b = tau[i+1]; double fa = fu[l1][i] * fu[l2][i]; double fb = fu[l1][i+1] * fu[l2][i+1]; utu[0] = fa; utu[M-1] = fb; tint ia=0; for (int j=1; j<M-1; j++){ intpar p = tau.InterpLeft( a + (b-a)*j/(M-1.0), ia); utu[j] = fu[l1](p) * fu[l2](p); } oij += romberg(utu, b-a); } overlap(l1,l2) = oij; overlap(l2,l1) = oij; } } } } template <class container> void CreateGfromCoeff(container& gf, const functionb<double>& gl, const string& statistics="fermi"){ vector<spline1D<double> >* pfU = (statistics=="fermi") ? &fU : &fU_bose; gf.resize(tau.size()); for (int i=0; i<tau.size(); i++) gf[i] = 0.0; for (int l=0; l<lmax; l++) for (int i=0; i<tau.size(); i++) gf[i] += gl[l]*(*pfU)[l][i]; } void CreateSplineFromCoeff(spline1D<double>& gf, const functionb<double>& gl, const string& statistics="fermi"){ CreateGfromCoeff(gf,gl, statistics); { double x1 = 0.5*(tau[1]+tau[0]); double df1 = (gf[1]-gf[0])/(tau[1]-tau[0]); double x2 = 0.5*(tau[2]+tau[1]); double df2 = (gf[2]-gf[1])/(tau[2]-tau[1]); double df0 = df1 + (df2-df1)*(0.0-x1)/(x2-x1); int n = tau.size(); x1 = 0.5*(tau[n-1]+tau[n-2]); df1 = (gf[n-1]-gf[n-2])/(tau[n-1]-tau[n-2]); x2 = 0.5*(tau[n-2]+tau[n-3]); df2 = (gf[n-2]-gf[n-3])/(tau[n-2]-tau[n-3]); double dfn = df1 + (df2-df1)*(tau[n-1]-x1)/(x2-x1); gf.splineIt(tau, df0, dfn); } } template <class container> void MatsubaraFrequency(container& giom, const spline1D<double>& gf, int nmax, const string& statistics="fermi"){ giom.resize(nmax); //double beta=tau[tau.size()-1]; double one = (statistics=="fermi") ? 1.0 : 0.0; for (int in=0; in<nmax; in++){ double iom = (2*in+one)*M_PI/beta; giom[in] = gf.Fourier_(iom, tau); } } template <class functor> void ExpandAnalyticFunction(const functor& fG, function1D<double>& gl, const string& statistics="fermi") const { const vector<spline1D<double> >* pfU = (statistics=="fermi") ? &fU : &fU_bose; gl.resize(lmax); int M = static_cast<int>(pow(2.0,k_ovlp))+1; // Number of points in Romberg integration routine vector<double> utu(M); // storage for Romberg //double beta = tau[tau.size()-1]; for (int l=0; l<lmax; l++){ gl[l]=0; for (int i=0; i<tau.size()-1; i++){ double a = tau[i]; // integral only between t_i and t_{i+1} points double b = tau[i+1]; double fa = (*pfU)[l][i] * fG(a, beta); double fb = (*pfU)[l][i+1] * fG(b, beta); utu[0] = fa; utu[M-1] = fb; tint ia=0; for (int j=1; j<M-1; j++){ double t = a + (b-a)*j/(M-1.0); intpar p = tau.InterpLeft( t, ia); utu[j] = (*pfU)[l](p) * fG(t, beta); } gl[l] += romberg(utu, b-a); } } } int l_critical(const functionb<double>& gl, double max_ratio=3., const string& statistics="fermi"){ int nsa=5; int _lmax_ = statistics=="fermi" ? lmax : lmax_bose; if (_lmax_<=nsa) return _lmax_; function1D<double> gos(_lmax_); function1D<double>* pS = (statistics=="fermi") ? &S : &S_bose; for (int i=0; i<_lmax_; i++) gos[i] = fabs(gl[i]/(*pS)[i]); //cout<<"gos="<<gos<<endl; double* p = gos.begin() + nsa+1; // pointer to the fifth entry for (int l=nsa+1; l<_lmax_; ++l && ++p){ double sa = *max_element(p-nsa,p); // maximum in the past five coefficients //cout<<l<<" g[l]="<<gl[l]<<" gos[l]="<<gos[l]<<" gmax="<<sa<<" g/gmax="<<fabs(gos[l]/sa)<<endl; if (fabs(gos[l]/sa)>max_ratio){ //cout<<"lcritical should be "<<l<<endl; return l; } } return _lmax_; } void GiveRealAxis(function2D<double>& Aw, const functionb<double>& gl, double max_ratio=3., const string& statistics="fermi") { int lcritical = l_critical(gl,max_ratio,statistics); Aw.resize(lcritical,om.size()); function1D<double> gos(gl.size()); function1D<double>* pS = (statistics=="fermi") ? &S : &S_bose; for (int i=0; i<gl.size(); i++) gos[i] = gl[i]/(*pS)[i]; function2D<double>* pVt = (statistics=="fermi") ? &Vt : &Vt_bose; for(int i=0; i<om.size(); i++) Aw(0,i) = -gos[0]*(*pVt)(i,0); for (int l=1; l<lcritical; l++){ for (int i=0; i<om.size(); i++) Aw(l,i) = Aw(l-1,i) - gos[l]*(*pVt)(i,l); } if (statistics=="bose"){ for (int l=0; l<lcritical; l++) for (int iw=0; iw<om.size(); iw++) Aw(l,iw) *= M_PI*om[iw]; } } void SetUpFastInterp() { ff2.resize(tau.size(),lmax,2); dxi.resize(tau.size()); for (int i=0; i<tau.size(); i++) dxi[i] = fU[0].dxi[i]; for (int l=0; l<lmax; l++){ for (int i=0; i<tau.size(); i++){ ff2(i,l,0) = fU[l][i]; ff2(i,l,1) = fU[l].f2[i]; } } } void FastInterp(functionb<double>& res, const intpar& ip, double cst) const { int i= ip.i; double p = ip.p, q=1-ip.p; double dx26 = dxi[i]*dxi[i]/6.; double dq = dx26*q*(q*q-1); double dp = dx26*p*(p*p-1); q *= cst; dq *= cst; p *= cst; dp *= cst; double* __restrict__ _res = res.MemPt(); const double* __restrict__ _ff2 = ff2[i]; // this is fast equivalent of // res[l] += q * fU[l].f[i] + dq * fU[l].f2[i]; for (int l=0; l<lmax; l++) _res[l] += q * _ff2[2*l] + dq * _ff2[2*l+1]; _ff2 += 2*lmax; // this is fast equivalent of // res[l] += p * fu[l].f[i+1] + dp * fU[l].f2[i+1]; for (int l=0; l<lmax; l++) _res[l] += p * _ff2[2*l] + dp * _ff2[2*l+1]; } void FastInterp_(functionb<double>& res, const intpar& ip, double cst) const {// This is the same as FastInterp, except res is zeroth first. int i= ip.i; double p = ip.p, q=1-ip.p; double dx26 = dxi[i]*dxi[i]/6.; double dq = dx26*q*(q*q-1); double dp = dx26*p*(p*p-1); q *= cst; dq *= cst; p *= cst; dp *= cst; double* __restrict__ _res = res.MemPt(); const double* __restrict__ _ff2 = ff2[i]; for (int l=0; l<lmax; l++) _res[l] = q * _ff2[2*l] + dq * _ff2[2*l+1]; _ff2 += 2*lmax; for (int l=0; l<lmax; l++) _res[l] += p * _ff2[2*l] + dp * _ff2[2*l+1]; } #ifdef _MPI void ComputeClCoefficients(function2D<double>& Cl, int my_rank, int mpi_size, int Master, int nw=0, int ntail=0, int cutoff_iom=0){ #else void ComputeClCoefficients(function2D<double>& Cl, int nw=0, int ntail=0, int cutoff_iom=0){ #endif bool BRISI = false; int Nt = tau.size(); //double L = om[om.size()-1]; //double beta = tau[tau.size()-1]; if (nw==0) nw = L*beta/3; // number of Matsubara points treated exactly if (ntail==0) ntail=150; // number of points used for the tail if (cutoff_iom==0) cutoff_iom=100;// how far the tail will extend. We will go to Matsubara index nw*cutoff_iom function1D<int> ind_om; create_log_mesh(ind_om, nw*cutoff_iom, nw, ntail); // log mesh with nw exact points in [0,...nw-1], and ntail points distributed between [nw,nw*cutoff_iom] mesh1D iom(ind_om.size()); for (int in=0; in<ind_om.size(); in++) iom[in] = ind_om[in]; iom.SetUp(0); if (BRISI){ cout.precision(11); cout<<"# Starting single loop for u(iw) "<<endl; } // This creates u_l(iom) from u_l(tau) function2D<complex<double> > u_om(lmax,iom.size()); for (int lf=0; lf<lmax; lf++){ for (int in=0; in<iom.size(); in++){ double om = (2*iom[in]+1.)*M_PI/beta; u_om(lf,in) = fU[lf].Fourier(om, tau); } } if (BRISI) cout<<"# Starting double loop for w(iw) "<<endl; // This creates w_l(iom) from u_l(tau). // w_{lb,lf}(iom) = 1/beta \sum_{iOm} u^b_{lb}(iOm) * u^f_{lf}(iom+iOm) // which is equivalent to // w_{lb,lf}(iom) = Integrate[ u^b_{lb}(beta-t) * u^f_{lf}(t) e^{i*om*t}, {t,0,beta}] int Nl2 = lmax_bose*lmax; #ifdef _MPI int ipr_proc = (Nl2 % mpi_size==0) ? Nl2/mpi_size : Nl2/mpi_size+1; int iistart = ipr_proc*my_rank; int iiend = ipr_proc*(my_rank+1); if (iistart>Nl2) iistart=Nl2; if (iiend >Nl2) iiend=Nl2; int _Nl2_ = max(Nl2, mpi_size*ipr_proc); if (BRISI) cout<<"istart="<<iistart<<" iend="<<iiend<<" pr_proc="<<ipr_proc<<" pr_proc*mpi_size="<<ipr_proc*mpi_size<<" Nl2="<<Nl2<<endl; #else int iistart = 0; int iiend = Nl2; int ipr_proc = Nl2; int _Nl2_ = Nl2; #endif function2D<complex<double> > w_iom(_Nl2_, iom.size()); w_iom = 0.0; for (int ii=iistart; ii<iiend; ii++){ // ii = lb * lmax + lf int lb = ii / lmax; int lf = ii % lmax; spline1D<double> wt(Nt); for (int it=0; it<tau.size(); it++) wt[it] = fU_bose[lb][Nt-1-it]*fU[lf][it]; // wt[t] = u^b_{lb}(beta-t) * u^f_{lf}(t) int n = tau.size(); double x1 = 0.5*(tau[1]+tau[0]); double df1 = (wt[1]-wt[0])/(tau[1]-tau[0]); double x2 = 0.5*(tau[2]+tau[1]); double df2 = (wt[2]-wt[1])/(tau[2]-tau[1]); double df0 = df1 + (df2-df1)*(0.0-x1)/(x2-x1); x1 = 0.5*(tau[n-1]+tau[n-2]); df1 = (wt[n-1]-wt[n-2])/(tau[n-1]-tau[n-2]); x2 = 0.5*(tau[n-2]+tau[n-3]); df2 = (wt[n-2]-wt[n-3])/(tau[n-2]-tau[n-3]); double dfn = df1 + (df2-df1)*(beta-x1)/(x2-x1); wt.splineIt(tau, df0, dfn); // w(iom) = Fourier[ wt[t] ] for (int in=0; in<iom.size(); in++){ double om = (2*iom[in]+1.)*M_PI/beta; //w_om(lb,lf,in) = wt.Fourier(om, tau); w_iom(ii,in) = wt.Fourier(om, tau); } } #ifdef _MPI if (mpi_size>1) MPI_Allgather(MPI_IN_PLACE, ipr_proc*iom.size()*2, MPI_DOUBLE, w_iom.MemPt(), ipr_proc*iom.size()*2, MPI_DOUBLE, MPI_COMM_WORLD); #endif if (BRISI) cout<<"# Starting last part"<<endl; int Nl = (lmax*lmax*lmax_bose); int offset=2; spline1D<double> ftmp(ntail+offset); mesh1D wom(ntail+offset); int ifirst = iom.size()-ntail-offset; for (int in=ifirst; in<iom.size(); in++) wom[in-ifirst] = iom[in]; wom.SetUp(0); deque<pair<int,int> > icase; for (int i=0; i<Nl; i++){ for (int j=i; j<Nl; j++){ vector<int> li = get_lll(i); vector<int> lj = get_lll(j); if ( (li[0] + li[1] + li[2] + lj[0] + lj[1] + lj[2])%2 ) continue; // this vanishes due to symmetry icase.push_back( make_pair(i,j) ); } } #ifdef _MPI int pr_proc = (icase.size() % mpi_size==0) ? icase.size()/mpi_size : icase.size()/mpi_size+1; int istart = pr_proc*my_rank; int iend = pr_proc*(my_rank+1); if (istart>icase.size()) istart=icase.size(); if (iend >icase.size()) iend=icase.size(); if (BRISI) cout<<"istart="<<istart<<" iend="<<iend<<" pr_proc="<<pr_proc<<" pr_proc*mpi_size="<<pr_proc*mpi_size<<" icase.size="<<icase.size()<<endl; #else int istart = 0; int iend = icase.size(); int pr_proc = icase.size(); #endif function1D<double> Cl0(pr_proc); Cl0=0; // This loop is parallelized for (int ii=istart; ii<iend; ii++){ int i = icase[ii].first; int j = icase[ii].second; vector<int> li = get_lll(i); vector<int> lj = get_lll(j); if ( (li[0] + li[1] + li[2] + lj[0] + lj[1] + lj[2])%2 ) continue; // this vanishes due to symmetry // lj[2],lj[1],lj[0] : bose,fermi,fermi // lb * lmax + lf //complex<double> * w_1 = w_iom[ lj[2]*lmax + li[1] ].MemPt(); //complex<double> * w_2 = w_iom[ li[2]*lmax + lj[1] ].MemPt(); //complex<double> * u_1 = u_om[ li[0] ].MemPt(); //complex<double> * u_2 = u_om[ lj[0] ].MemPt(); complex<double> * w_1 = w_iom[ lj[2]*lmax + li[0] ].MemPt(); complex<double> * w_2 = w_iom[ li[2]*lmax + lj[0] ].MemPt(); complex<double> * u_1 = u_om[ li[1] ].MemPt(); complex<double> * u_2 = u_om[ lj[1] ].MemPt(); double wsum = 0.0; for (int in=0; in<iom.size()-ntail; in++) wsum += (w_1[in] * conj(w_2[in]) * u_1[in] * conj(u_2[in])).real(); // fill int the 1D-interpolation for the tail for (int in=ifirst; in<iom.size(); in++) ftmp[in-ifirst] = (w_1[in] * conj(w_2[in]) * u_1[in] * conj(u_2[in])).real(); // intepolate the tail int n=ftmp.size(); ftmp.splineIt(wom, (ftmp[1]-ftmp[0])/(wom[1]-wom[0]), (ftmp[n-1]-ftmp[n-2])/(wom[n-1]-wom[n-2]) ); // Now anlytically evaluate the sum over all points, but loop only over a few points in the tail. // The sum of the spline in the interval [n1,n2] can be analytically evaluated: // 1/2*(f[n2]+f[n1])*(n2-n1) - 1/24*(n2-n1)*((n2-n1)^2-1) * (f2[n2]+f2[n1]) // where f2[n1], f2[n2] is the second derivative at n1 and n2 points. // Note that the first and the last point come in with the weight 1/2, hence we need to correct for that. wsum += 0.5*ftmp[iom.size()-ntail-ifirst] + 0.5*ftmp[iom.size()-1-ifirst]; for (int in=iom.size()-ntail; in<iom.size()-1; in++){ double dh = iom[in+1]-iom[in]; wsum += 0.5*(ftmp[in-ifirst]+ftmp[in+1-ifirst])*dh - dh/24.0*(dh*dh - 1.0)*(ftmp.f2[in+1-ifirst]+ftmp.f2[in-ifirst]); } /* //The above few lines are equivalent to int iom_last = iom[iom.size()-1]; tint ia=0; for (int iw=iom.size()-ntail; iw<iom_last; iw++){ double ww = ftmp( wom.InterpLeft(iw, ia) ); wsum += ww; } */ /* Cl(i,j) = 2*(wsum)/beta; Cl(j,i) = Cl(i,j); */ Cl0[ii-istart] = 2*(wsum)/beta; //cout<<setw(4)<<i<<" "<<setw(4)<<j<<" "<<setw(3)<<li[2]<<" "<<setw(3)<<li[1]<<" "<<setw(3)<<li[0]<<"; "<<setw(3)<<lj[2]<<" "<<setw(3)<<lj[1]<<" "<<setw(3)<<lj[0]<<" "<<setw(10)<<left<<Cl(i,j)<<right<<endl; } #ifdef _MPI if (mpi_size>1){ if (BRISI){ cout<<"MPI_Gather"<<endl; cout.flush(); } function1D<double> cCl0; cCl0.resize(pr_proc*mpi_size); MPI_Gather(Cl0.MemPt(), pr_proc, MPI_DOUBLE, cCl0.MemPt(), pr_proc, MPI_DOUBLE, Master, MPI_COMM_WORLD); if (my_rank==Master){ Cl0.resize(icase.size()); for (int i=0; i<icase.size(); i++) Cl0[i] = cCl0[i]; } } if (my_rank == Master){ #endif Cl.resize(Nl,Nl); Cl=0.0; for (int ii=0; ii<icase.size(); ii++){ int i = icase[ii].first; int j = icase[ii].second; Cl(i,j) = Cl0[ii]; Cl(j,i) = Cl0[ii]; } #ifdef _MPI } #endif } }; /* double fGs(double tau, double beta){ // On real axis, this corresponds to // A(w) = 1/2*(delta(w-x0)+delta(w+x0)) // with x0=1. return -exp(-beta/2.)*cosh(beta/2.-tau); } double chis(double tau, double beta){ // On real axis this corresponds to // chi''(x) = pi*[delta(w-x0)-delta(w+x0)] // with x0=1/beta const double bx2 = 0.5; return cosh(bx2*(1-2.*tau/beta))/sinh(bx2); } class fGspl{ public: spline1D<double>& fg; mesh1D t; fGspl(spline1D<double>& fg_, mesh1D& t_) : fg(fg_), t(t_) {} double operator()(double x, double beta) const{ return fg(t.Interp(x)); } }; int main(){ double x0=0.005; double L=10.; int Nw = 500; //double beta=9.35887; double beta=100; int lmax = 40; int k_ovlp=5; int Ntau = static_cast<int>(5*beta+100); bool readGFile=false;//true; spline1D<double> ginp; mesh1D tc; if (readGFile){ ifstream inp("../Gtau.dat_4"); deque<double> ct, gt; while (inp){ double t, g; inp >> t >> g; //cout<<t<<" "<<g<<endl; if (!inp) break; ct.push_back(t); gt.push_back(g); inp.ignore(numeric_limits<streamsize>::max(), '\n'); } beta = ct.back()+ct[0]; cout<<"beta="<<beta<<endl; ginp.resize(gt.size()); tc.resize(ct.size()); { for (int i=0; i<ct.size(); i++){ tc[i] = ct[i]; ginp[i] = gt[i]; } tc.SetUp(0); double df0 = (ginp[1]-ginp[0])/(tc[1]-tc[0]); int n = tc.size(); double dfn = (ginp[n-1]-ginp[n-2])/(tc[n-1]-tc[n-2]); cout<<"df0="<<df0<<" dfn="<<dfn<<endl; ginp.splineIt(tc, df0, dfn); } } fGspl Fg(ginp, tc); clog<<"beta="<<beta<<" Ntau="<<Ntau<<endl; SVDFunc svdf; svdf.cmp("both", beta, lmax, Ntau, x0, L, Nw, clog); // Print SVD functions svdf.Print("uls.dat",beta); svdf.Print("ulb.dat",beta, "bose"); // Now we check how well is the orthogonality obeyed after reorthogonalization clog<<"Final overlap is smaller than "<<svdf.CheckOverlap(beta)<<endl; ofstream fo("cc.dat"); mesh1D& tau = svdf.tau; function1D<double> Gts(tau.size()); for (int i=0; i<tau.size(); i++){ if (readGFile) Gts[i] = Fg(tau[i],beta); else Gts[i] = fGs(tau[i], beta); fo<<tau[i]<<" "<<Gts[i]<<" "<<svdf[0][i]<<" "<<svdf[2][i]<<endl; } fo.close(); function1D<double> gl(lmax); if (readGFile) svdf.ExpandAnalyticFunction(Fg, gl); else svdf.ExpandAnalyticFunction(fGs, gl); function1D<double> gl2(lmax); svdf.SetUpFastInterp(); { k_ovlp=5; gl2.resize(lmax); gl2 = 0.0; int M = pow(2,k_ovlp)+1; // Number of points in Romberg integration routine function2D<double> utu_T(M,lmax); // storage for Romberg double beta = tau[tau.size()-1]; for (int i=0; i<tau.size()-1; i++){ utu_T=0; double a = tau[i]; // integral only between t_i and t_{i+1} points double b = tau[i+1]; tint ia=0; for (int j=0; j<M; j++){ double t = a + (b-a)*j/(M-1.0); intpar p = tau.InterpLeft( t, ia); double cst; if (readGFile) cst = Fg(t,beta); else cst = fGs(t, beta); ///// Slow equivalent //// //for (int l=0; l<svdf.lmax; l++) utu_T(j,l) += cst * svdf.fU[l](p); svdf.FastInterp(utu_T[j], p, cst ); } function1D<double> utu(M); for (int l=0; l<lmax; l++){ for (int j=0; j<M; j++) utu[j] = utu_T(j,l); gl2[l] += romberg(utu, b-a); } } } cout<<"Should be equal:"<<endl; for (int l=0; l<lmax; l++) cout<<l<<" "<<gl[l]<<" "<<gl2[l]<<" "<<gl[l]-gl2[l]<<endl; spline1D<double> gf; svdf.CreateSplineFromCoeff(gf, gl); int nmax=5000; function1D<complex<double> > giom; svdf.MatsubaraFrequency(giom, gf, nmax); ofstream fig("giom.dat"); fig.precision(16); for (int in=0; in<nmax; in++){ double iom = (2*in+1)*M_PI/beta; double gi_exact = -iom/(iom*iom+1.); fig<<iom<<" "<<giom[in]<<" "<<gi_exact<<endl; } ofstream fog("gl.dat"); fog.precision(16); for (int l=0; l<svdf.lmax; l++) if (fabs(gl[l])>1e-10) fog<<l<<" "<<gl[l]<<endl; fog.close(); ofstream foG("Gapp.dat"); foG.precision(16); for (int i=0; i<tau.size(); i++){ double dval=0; for (int l=0; l<svdf.lmax; l++) dval += svdf[l][i]*gl[l]; foG<<tau[i]<<" "<<dval<<" "<<Gts[i]<<" "<<fabs(dval-Gts[i])<<endl; } foG.close(); //int lc = svdf.l_critical(gl); //cout<<lc<<endl; function2D<double> Aw; ofstream fAw("Aw.out"); svdf.GiveRealAxis(Aw, gl, 2.0); for (int i=0; i<svdf.om.size(); i++){ fAw << svdf.om[i]<<" "; for (int l=0; l<Aw.size_N(); l++){ fAw << Aw(l,i) <<" "; } fAw << endl; } svdf.ExpandAnalyticFunction(chis, gl, "bose"); svdf.CreateSplineFromCoeff(gf, gl, "bose"); ofstream foc("Chid.dat"); foc.precision(16); for (int i=0; i<svdf.tau.size(); i++){ double val = chis(svdf.tau[i],beta); foc<<svdf.tau[i]<<" "<<gf[i]<<" "<<val<<" "<<fabs(val-gf[i])<<endl; } foc.close(); svdf.MatsubaraFrequency(giom, gf, nmax, "bose"); ofstream sig("siom.dat"); sig.precision(16); for (int in=0; in<nmax; in++){ double iom = (2*in+0.0)*M_PI/beta; double x0 = 1./beta; double gi_exact = 2*x0/(x0*x0+iom*iom); sig<<iom<<" "<<giom[in]<<" "<<gi_exact<<" "<<giom[in]-gi_exact<<endl; } cout<<"bose coefficients are"<<gl<<endl; svdf.GiveRealAxis(Aw, gl, 10.0, "bose"); ofstream sAw("sw.out"); for (int i=0; i<svdf.om.size(); i++){ sAw << svdf.om[i]<<" "; for (int l=0; l<Aw.size_N(); l++) sAw << Aw(l,i) <<" "; sAw << endl; } svd.Print("usb.dat",common::beta,"bose"); for (int l=0; l<svdf.lmax_bose; l++) svdf.MatsubaraFrequency(bUw[l], svdf.fU_bose[l], N_W); return 0; } */
{ "alphanum_fraction": 0.5566485867, "avg_line_length": 32.9811111111, "ext": "h", "hexsha": "dca1ce474a38e7a146233eb1dc5649a7c99b27c0", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2016-08-02T15:05:12.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-22T15:46:56.000Z", "max_forks_repo_head_hexsha": "83481be27e8a9ff14b9635d6cc1cd9d96f053487", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "dmft-wien2k/dmft-wien2k", "max_forks_repo_path": "src/impurity/ctqmc/svdfunc.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "83481be27e8a9ff14b9635d6cc1cd9d96f053487", "max_issues_repo_issues_event_max_datetime": "2016-07-12T21:42:01.000Z", "max_issues_repo_issues_event_min_datetime": "2016-07-12T21:37:53.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "dmft-wien2k/dmft-wien2k-v2", "max_issues_repo_path": "src/impurity/ctqmc/svdfunc.h", "max_line_length": 219, "max_stars_count": 5, "max_stars_repo_head_hexsha": "83481be27e8a9ff14b9635d6cc1cd9d96f053487", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "dmft-wien2k/dmft-wien2k-v2", "max_stars_repo_path": "src/impurity/ctqmc/svdfunc.h", "max_stars_repo_stars_event_max_datetime": "2022-01-18T10:08:09.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-13T13:04:26.000Z", "num_tokens": 10880, "size": 29683 }
/* Author: G. Jungman */ /* Convenience header */ #ifndef __GSL_SPECFUNC_H__ #define __GSL_SPECFUNC_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <gsl/gsl_sf.h> #endif /* __GSL_SPECFUNC_H__ */
{ "alphanum_fraction": 0.6995073892, "avg_line_length": 19.3333333333, "ext": "h", "hexsha": "f52c4e2f387413b4da691d6fcbf6d4e3bfa3024e", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_specfunc.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_specfunc.h", "max_line_length": 48, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_specfunc.h", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "num_tokens": 117, "size": 406 }
/* ----------------------------------------------------------------------------- * Copyright 2021 Jonathan Haigh * SPDX-License-Identifier: MIT * ---------------------------------------------------------------------------*/ #ifndef SQ_INCLUDE_GUARD_system_linux_SqFieldSchemaImpl_h_ #define SQ_INCLUDE_GUARD_system_linux_SqFieldSchemaImpl_h_ #include "core/typeutil.h" #include "system/SqFieldSchema.gen.h" #include "system/schema.h" #include <gsl/gsl> namespace sq::system::linux { class SqFieldSchemaImpl : public SqFieldSchema<SqFieldSchemaImpl> { public: explicit SqFieldSchemaImpl(const FieldSchema &field_schema); SQ_ND Result get_name() const; SQ_ND Result get_doc() const; SQ_ND Result get_params() const; SQ_ND Result get_return_type() const; SQ_ND Result get_return_list() const; SQ_ND Result get_null() const; SQ_ND Primitive to_primitive() const override; private: gsl::not_null<const FieldSchema *> field_schema_; }; } // namespace sq::system::linux #endif // SQ_INCLUDE_GUARD_system_linux_SqFieldSchemaImpl_h_
{ "alphanum_fraction": 0.6691943128, "avg_line_length": 28.5135135135, "ext": "h", "hexsha": "dffe25eaaae796556976608d08139eaac5bdddf4", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_path": "src/system/include/system/linux/SqFieldSchemaImpl.h", "max_issues_count": 44, "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_path": "src/system/include/system/linux/SqFieldSchemaImpl.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_path": "src/system/include/system/linux/SqFieldSchemaImpl.h", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "num_tokens": 231, "size": 1055 }
/*-------------------------------------------------------------------------------------------------- FUNCTION: ssblock_lu DESCRIPTION: -------------------------------------------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> #ifdef OPENBLAS #include <cblas.h> #elif MKL #include <mkl.h> #endif #define max(a, b) ( a < b ? b : a ) extern void getlvl2minors_lu_(int*, const int*, double*, int*, double*, int*); void ssblock_lu(double *csc, int no, const int nv1, const int nv2, const int ns1, const int ns2, double *wf1, double *wf2, double *l1minor, double *ss, const int print_level) { int ld_csc; int ld_msum, ld_tmp; int ld_l2minors; int tmp_cols; int i, o1, o2; int pos_tmp, pos_msum; int st1, st2; int num_threads; double *msum = NULL; //Auxiliary matrix to store computed determinants double *tmp = NULL; // Auxiliary matrix for intermediate results double *l2minors = NULL; double zero = 0.0, one = 1.0, neg_one = -1.0; int one_i = 1; double coef; double ss_local; int v1; /* Timing routines */ double start, finish; double time00, time0; double time_l2m, time_det, time_sum, time_tot; /* Auxiliary variables */ int ndevices; int devices[10]; if (print_level >= 2) { time00 = omp_get_wtime(); printf("\n ---- start ssblock subroutine ----\n"); } /* Set times to 0 */ time_l2m = 0.0; time_det = 0.0; time_sum = 0.0; /* Set leading dimensions */ ld_csc = no + nv1; ld_l2minors = no*no*no; ld_tmp = max(no, nv1); tmp_cols = nv2; ld_msum = nv1; /* Allocate arrays */ msum = (double*) malloc (ld_msum * nv2 * sizeof(double)); tmp = (double*) malloc(ld_tmp * tmp_cols * ns2 * sizeof(double)); l2minors = (double*) malloc(ld_l2minors * no * sizeof(double)); #ifdef OPENBLAS num_threads = openblas_get_num_threads(); #elif MKL num_threads = mkl_get_max_threads(); #endif /* Compute the determinants of all possible l2minors of the reference matrix. Pass through all combinations of rows and columns (r1, c1, r2, c2) to removed in order to form a l2minor */ time0 = omp_get_wtime(); getlvl2minors_lu_(&no, &nv2, csc, &ld_csc, l2minors, &ld_l2minors); time_l2m = omp_get_wtime() - time0; /* Scale lower csc matrix block with alternating array (1,-1,1,-1...) i.e. starting from the second * column, scale every second column with -1. * Arrays wf1 and wf2 are used as auxiliary arrays and are not referenced (unchaged on exit). */ cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, nv1, no/2, nv2, zero, wf1, nv1, wf2, nv2, neg_one, &csc[no+nv1 + no], 2*ld_csc); /* Scale ss matrix to zero */ cblas_dscal(ns1*ns2, zero, ss, 1); /* Start iterate through the blocks */ for( o1 = 0; o1 < no; o1++ ){ for( o2 = 0; o2 < no; o2++ ){ /* printf("[ssblock_lu] Computing block (%d, %d)\n", o1, o2); */ /* Apply rows from the right of the ref matrix, cscmat positions (1:no, no+1:np+nv2) * Compute first product l2minors * csc(1:no, no+1:no+nv2) */ time0 = omp_get_wtime(); pos_tmp = o1*no*no + o2*no; ld_tmp = no; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, no, nv2, no, one, &l2minors[pos_tmp], ld_l2minors, &csc[no*ld_csc], ld_csc, zero, tmp, ld_tmp); pos_msum = o1*no*nv1 + o2*nv1; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, nv1, nv2, no, pow(neg_one, o1+2), &csc[no], ld_csc, tmp, ld_tmp, zero, msum, ld_msum); /* Get l1minor determinants and apply permutation sign */ coef = pow(neg_one, o1+o2) * l1minor[o2*no + o1]; /* Get coefficients (no+1:no+nv1, no+1:no+nv2) into auxiliary storage msum */ for( i = 0; i < nv2; i++ ){ cblas_daxpy(nv1, coef, &csc[(no+i)*ld_csc+no], 1, &msum[i*ld_msum], 1); } time_det += omp_get_wtime() - time0; time0 = omp_get_wtime(); /* Compute ss matrix */ for( v1 = 0; v1 < nv1; v1++ ){ cblas_dgemv( CblasColMajor, CblasTrans, nv2, ns2, one, &wf2[o2*nv2], no*nv2, &msum[v1], nv1, zero, tmp, 1 ); cblas_dger( CblasColMajor, ns1, ns2, one, &wf1[o1*nv1+v1], no*nv1, tmp, one, ss, ns1 ); } finish = omp_get_wtime(); time_sum += omp_get_wtime() - time0; } } /* Free allocated spaces */ free(msum); free(tmp); free(l2minors); /* Print timings */ if (print_level >= 2) { printf("\n ssblock time:\n"); printf(" L2 minors - time (sec): %.4lf \n", time_l2m); printf(" Determinants from minors - time (sec): %.4lf \n", time_det); printf(" Final sum - time (sec): %.4lf \n", time_sum); printf(" --------------\n"); printf(" Total - time (sec): %.4lf \n", time_tot); printf(" ---- end ssblock subroutine ----\n"); } }
{ "alphanum_fraction": 0.5712873245, "avg_line_length": 33.4900662252, "ext": "c", "hexsha": "0a871015d55f6065bce0e6d38c149cd214a772c0", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "a13492d3e518e4252909c7dd11f13e492ddab124", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "marin-sapunar/cis_nto", "max_forks_repo_path": "src/util_chem/l2m/ssblock_lu.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "a13492d3e518e4252909c7dd11f13e492ddab124", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "marin-sapunar/cis_nto", "max_issues_repo_path": "src/util_chem/l2m/ssblock_lu.c", "max_line_length": 186, "max_stars_count": 1, "max_stars_repo_head_hexsha": "a13492d3e518e4252909c7dd11f13e492ddab124", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "marin-sapunar/cis_nto", "max_stars_repo_path": "src/util_chem/l2m/ssblock_lu.c", "max_stars_repo_stars_event_max_datetime": "2020-02-08T16:45:16.000Z", "max_stars_repo_stars_event_min_datetime": "2020-02-08T16:45:16.000Z", "num_tokens": 1601, "size": 5057 }
#include <stdio.h> #include <stdlib.h> //#include <gsl_matrix.h> #define IKFAST_HAS_LIBRARY // Build IKFast with API functions #define IKFAST_NO_MAIN // Don't include main() from IKFast #include "ikfast.cpp" #include "kin.h" int KinCalcFowardKinematics(jointAngles_t* angles, eeCoord_t* ee) { int i; double eetrans[3]; double eerot[9]; for(i=0;i<9;i++){ eerot[i] = -48; } ComputeFk((double*)angles,eetrans,eerot); printf("Found fk solution for end frame: \n\n"); printf(" Translation: x: %f y: %f z: %f \n", eetrans[0], eetrans[1], eetrans[2] ); printf("\n"); printf(" Rotation %f %f %f \n", eerot[0], eerot[1], eerot[2] ); printf(" Matrix: %f %f %f \n", eerot[3], eerot[4], eerot[5] ); printf(" %f %f %f \n", eerot[6], eerot[7], eerot[8] ); printf("\n"); return 0; } #ifdef STANDALONE int main(int argc, char **argv){ int i; if(argc != 9) { printf("usage: %s x1 y1 z1 w1 x2 y2 z2 w2\n", argv[0]); return 1; } const int points = 100; waypoint_t waypoint[points]; waypoint[0].x = atof(argv[1]); waypoint[0].y = atof(argv[2]); waypoint[0].z = atof(argv[3]); waypoint[0].w = atof(argv[4]); waypoint[points-1].x = atof(argv[5]); waypoint[points-1].y = atof(argv[6]); waypoint[points-1].z = atof(argv[7]); waypoint[points-1].w = atof(argv[8]); KinCalcFowardKinematics(&angles, &ee); } #endif
{ "alphanum_fraction": 0.6034236805, "avg_line_length": 20.3188405797, "ext": "c", "hexsha": "1a68cf5c4a458a2a62ae7a09a644cc6e6ccfca9f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "fdb293acdd8fd7ccb0761038086c06f12bc7939a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "bcmetz/arm", "max_forks_repo_path": "kin/kin.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "fdb293acdd8fd7ccb0761038086c06f12bc7939a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "bcmetz/arm", "max_issues_repo_path": "kin/kin.c", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "fdb293acdd8fd7ccb0761038086c06f12bc7939a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "bcmetz/arm", "max_stars_repo_path": "kin/kin.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 501, "size": 1402 }
/* # Program to run a Monte Carlo radiation transfer through the 2D # simulations of GRB jets. # # Python code written by D. Lazzati at Oregonstate, C code written by Tyler Parsotan @ Oregon State # ver 0.1 July 8, 2015 # ver 1.1 July 20, 2015: added record of number of scatterings, included # all terms in weight. Should now give correct light curves. # ver 1.2 July 21, 2015: added parameter file to keep track of input # params of each simulation # ver 2.0 July 22, 2015: corrected the problem that arises when there is # no scattering in the time span of one frame. Fixed output arrays dimension. # ver 2.1 July 25, 2015: fixed bug that did not make the number of # scattering grow with the number of photons. # ver 3.0 July 28, 2015: using scipy nearest neighbor interpolation to # speed things up. Gained about factor 2 # ver 3.1 July 29, 2015: added radial spread of photon injection points # ver 3.2 July 31, 2015: added Gamma to the weight of photons!!! # ver 4.0 Aug 5, 2015: try to speed up by inverting cycle # ver 4.1 Aug 8, 2015: add spherical test as an option # ver 4.2 Aug 9, 2015: saving files appending rather than re-writing # ver 4.3 Aug 11, 2015: corrected error in the calculation of the local temperature # ver 4.4 Aug 13, 2015: added cylindrical test # ver 4.5 Aug 18, 2015: fixd various problems pointed by the cylindrical test # ver 4.6 Aug 21, 2015: corrected mean free path for large radii # ver 5.0 Aug 25, 2015: corrected problem with high-T electrons and excess scatterings # ver 5.1 Aug 25, 2015: cleaned-up coding # ver 5.2 Sept 3, 2015: fixed problem with number of scatterings for multiple injections * * ver 6.0 Dec 28, 2016: rewrote the code in C, added checkpoint file so if the code is interrupted all the progress wont be lost, made the code only need to be compiled once for a given MC_XXX directory path so you just need to supply the sub directory of MC_XXX as a command line argument * version 7.0 used OpenMP to parallelize the code by angle and the function findminmfp() version 8.0 added 3D capabilities for RIKEN hydro data and 2D capablities for RIKEN 2D hydro data and made it more efficient with grid selection to speed it up */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <math.h> #include <gsl/gsl_rng.h> #include "mclib_3d.h" #include <omp.h> #include "mpi.h" /* #define THISRUN "Science" #define FILEPATH "/home/physics/parsotat/16OI/" #define FILEROOT "rhd_jet_big_16OI_hdf5_plt_cnt_" #define MC_PATH "MPI_CMC_16OI_SPHERICAL/" #define THISRUN "Science" #define FILEPATH "/Users/Tylerparsotan/Documents/Box Sync/1spike/" #define FILEROOT "m0_rhop0.1big_hdf5_plt_cnt_" #define MC_PATH "CMC_1spike/" //#define MC_PATH "MC_16OI/Single_Photon_Cy_mc_total/" * */ /* #define THISRUN "Science" #define FILEPATH "/home/physics/parsotat/16OM/" #define FILEROOT "rhd_jet_big_16OM_hdf5_plt_cnt_" #define MC_PATH "DIR_TEST/" #define THISRUN "Science" #define FILEPATH "/Volumes/DATA6TB/Collapsars/2D/HUGE_BOXES/VARY/40spikes/" #define FILEROOT "m0_rhop0.1big_hdf5_plt_cnt_" #define MC_PATH "CMC_40spikes_TEST/" * */ #define THISRUN "Spherical" #define FILEPATH "/Volumes/DATA6TB/Collapsars/2D/HUGE_BOXES/CONSTANT/16OI/" //#define FILEPATH "/Users/Tylerparsotan//Documents/16OI_TEST/" #define FILEROOT "rhd_jet_big_16OI_hdf5_plt_cnt_" #define MC_PATH "TEST/" #define MCPAR "mc.par" #define RIKEN_SWITCH 0 int main(int argc, char **argv) { //compile each time a macro is changed, have to supply the subfolder within the MC_PATH directory as a command line argument to the C program eg. MCRAT 1/ // Define variables char flash_prefix[200]=""; char mc_file[200]="" ; char this_run[200]=THISRUN; char *cyl="Cylindrical"; char *sph="Spherical"; char spect;//type of spectrum char restrt;//restart or not double fps, fps_modified, theta_jmin, theta_jmax, hydro_domain_y,hydro_domain_x ;//frames per second of sim, min opening angle of jet, max opening angle of jet in radians, max y value of fluid simulation domain double inj_radius_small, inj_radius_large, ph_weight_suggest, ph_weight_small, ph_weight_large ;//radius at chich photons are injected into sim int frm0,last_frm, frm2_small, frm2_large, j=0, min_photons, max_photons, frm0_small, frm0_large ;//frame starting from, last frame of sim, frame of last injection int dim_switch=0; int find_nearest_grid_switch=0; int increment_inj=1, increment_scatt=1; //increments for injection loop and scattering loop, outer and inner loops respectively, the increment can change for RIKEN 3D hydro files double inj_radius; int frm2; char mc_filename[200]=""; char mc_filename_2[200]=""; char mc_operation[200]=""; char mc_dir[200]="" ; int file_count = 0; DIR * dirp; struct dirent * entry; struct stat st = {0}; double theta_jmin_thread=0, theta_jmax_thread=0; char flash_file[200]=""; char log_file[200]=""; FILE *fPtr=NULL; //pointer to log file for each thread double *xPtr=NULL, *yPtr=NULL, *rPtr=NULL, *thetaPtr=NULL, *velxPtr=NULL, *velyPtr=NULL, *densPtr=NULL, *presPtr=NULL, *gammaPtr=NULL, *dens_labPtr=NULL; double *szxPtr=NULL,*szyPtr=NULL, *tempPtr=NULL; //pointers to hold data from FLASH files double *phiPtr=NULL, *velzPtr=NULL, *zPtr=NULL; int num_ph=0, array_num=0, ph_scatt_index=0, max_scatt=0, min_scatt=0,i=0; //number of photons produced in injection algorithm, number of array elleemnts from reading FLASH file, index of photon whch does scattering, generic counter double dt_max=0, thescatt=0, accum_time=0; double gamma_infinity=0, time_now=0, time_step=0, avg_scatt=0, avg_r=0; //gamma_infinity not used? double ph_dens_labPtr=0, ph_vxPtr=0, ph_vyPtr=0, ph_tempPtr=0, ph_vzPtr=0;;// *ph_cosanglePtr=NULL ; double min_r=0, max_r=0, min_theta=0, max_theta=0; int frame=0, scatt_frame=0, frame_scatt_cnt=0, scatt_framestart=0, framestart=0; struct photon *phPtr=NULL; //pointer to array of photons int num_thread=0, angle_count=0; int num_angles=0, old_num_angle_procs=0; //old_num_angle_procs is to hold the old number of procs in each angle when cont sims, if restarting sims this gets set to angle_procs int *frame_array=NULL, *proc_frame_array=NULL, *element_num=NULL, proc_frame_size=0; double *thread_theta=NULL; //saves ranges of thetas for each thread to go through double delta_theta=1; int myid, numprocs, angle_procs, angle_id, procs_per_angle; //new OpenMPI stuff MPI_Init(NULL,NULL); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); //new muliple threads injecting and propagating photons const gsl_rng_type *rng_t; gsl_rng *rng; gsl_rng_env_setup(); rng_t = gsl_rng_ranlxs0; rng = gsl_rng_alloc (rng_t); //initalize random number generator to seed the others with random numbers //want to break up simulation by angle and injection frame & have each thread save data in its own folder //have each thread check if its directory is made and if its restarting (delete evrything) or if its continuing with a previous simulation //the angle and the injection frames will be the names of mc_dir, therefore read mc.par first in MC_XXX directory //make strings of proper directories etc. snprintf(flash_prefix,sizeof(flash_prefix),"%s%s",FILEPATH,FILEROOT ); snprintf(mc_file,sizeof(flash_prefix),"%s%s%s",FILEPATH, MC_PATH,MCPAR); printf(">> mc.py: Reading mc.par: %s\n", mc_file); readMcPar(mc_file, &hydro_domain_x, &hydro_domain_y, &fps, &theta_jmin, &theta_jmax, &delta_theta, &inj_radius_small,&inj_radius_large, &frm0_small,&frm0_large, &last_frm ,&frm2_small, &frm2_large, &ph_weight_small, &ph_weight_large, &min_photons, &max_photons, &spect, &restrt, &num_thread,&dim_switch); //thetas that comes out is in degrees //printf("%c\n", restrt); //divide up angles and frame injections among threads DONT WANT NUMBER OF THREADS TO BE ODD //assign ranges to array that hold them //leave angles in degrees here num_angles=(int) (((theta_jmax-theta_jmin)/delta_theta)) ;//*(180/M_PI)); thread_theta=malloc( num_angles *sizeof(double) ); *(thread_theta+0)=theta_jmin;//*(180/M_PI); //printf("%e\n", *(thread_theta+0)); for (j=1;j<(num_angles); j++) { *(thread_theta+j)=*(thread_theta+(j-1))+delta_theta; //printf("%e\n", *(thread_theta+j)); } //make comm without the procs that deal with angle //comm for angles procs_per_angle= numprocs/num_angles; //printf("%d\n", procs_per_angle); MPI_Comm angle_comm; if (restrt=='r') //uncomment this when I run MCRAT for sims that didnt originally save angle_procs { MPI_Comm_split(MPI_COMM_WORLD, myid/procs_per_angle , myid, &angle_comm); MPI_Comm_rank(angle_comm, &angle_id); MPI_Comm_size(angle_comm, &angle_procs); //printf("WORLD RANK/SIZE: %d/%d \t ROW RANK/SIZE: %d/%d\n", myid, numprocs, angle_id, angle_procs); theta_jmin_thread= (*(thread_theta+ (myid/procs_per_angle))) *(M_PI/180); theta_jmax_thread= theta_jmin_thread+(delta_theta*(M_PI/180)); snprintf(mc_dir,sizeof(flash_prefix),"%s%s%0.1lf-%0.1lf/",FILEPATH,MC_PATH, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI ); //have to add angle into this old_num_angle_procs=angle_procs; } else { MPI_Group sub_world_group; MPI_Comm sub_world_comm; int incl_procs[procs_per_angle*num_angles], count, sub_world_id; int total_num_to_restart=0; int color=1; int *all_cont_process_idPtr=NULL, *each_num_to_restart_per_anglePtr=NULL, *tmp=NULL; //for restart='c' case if the number of processes isnt a multiple of procs_per_angle*num_angles make a comm out of those that are in order to analyze files and count number of processes for each angle range need to con't count=0; for (j=0;j<numprocs;j++) { if (j<procs_per_angle*num_angles) { incl_procs[count]=j; count++; } } if (myid<procs_per_angle*num_angles) { int myid_2=0; // Get the group of processes in MPI_COMM_WORLD and make a sub group to go through checkpoint files MPI_Group world_group; MPI_Comm root_angle_comm; MPI_Comm_group(MPI_COMM_WORLD, &world_group); MPI_Group_incl(world_group, procs_per_angle*num_angles, incl_procs, &sub_world_group); MPI_Comm_create_group(MPI_COMM_WORLD, sub_world_group, 0, &sub_world_comm); MPI_Comm_rank(sub_world_comm, &myid_2); MPI_Comm_split(sub_world_comm, myid_2/procs_per_angle , myid_2, &angle_comm); MPI_Comm_rank(angle_comm, &angle_id); MPI_Comm_size(angle_comm, &angle_procs); //create group of all the processes that have angle_id==0 if (angle_id==0) { color=0; //set different color for root processes in each group of angle_comm } MPI_Comm_split(sub_world_comm, color , myid_2, &root_angle_comm); //create comm to exchange info about number of processes to restart for each angle range printf("WORLD RANK/SIZE: %d/%d \t ROW RANK/SIZE: %d/%d\n", myid, numprocs, angle_id, angle_procs); theta_jmin_thread= (*(thread_theta+ (myid_2/procs_per_angle))) *(M_PI/180); theta_jmax_thread= theta_jmin_thread+(delta_theta*(M_PI/180)); snprintf(mc_dir,sizeof(flash_prefix),"%s%s%0.1lf-%0.1lf/",FILEPATH,MC_PATH, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI ); //have to add angle into this //call the function to count the num of processes for each angle range that need to be con't int count_cont_procs=0, total_cont_procs_angle=0, global_cont_procs=0; int *cont_proc_idsPtr=NULL, *total_cont_procs_angle_Ptr=NULL, *displPtr=NULL; //becomes the size of the number of old procceses int *cont_proc_ids_anglePtr=NULL; old_num_angle_procs=getOrigNumProcesses(&count_cont_procs, &cont_proc_idsPtr, mc_dir, angle_id, angle_procs, last_frm, dim_switch, RIKEN_SWITCH); if (old_num_angle_procs==-1) { printf("MCRAT wasnt able to get a value of old_num_angle_procs to continue the simulation. Now exiting to prevent data corruption.\n" ); MPI_Abort(MPI_COMM_WORLD, 1); } total_cont_procs_angle_Ptr=malloc(angle_procs*sizeof(int)); displPtr=malloc(angle_procs*sizeof(int)); MPI_Gather(&count_cont_procs,1,MPI_INT, total_cont_procs_angle_Ptr, 1, MPI_INT, 0,angle_comm );//hold the number of elements that each process will send the root process MPI_Barrier(angle_comm); MPI_Barrier(sub_world_comm); if (angle_id==0) { printf("Angle_procs: %d 1st gather: %d, %d, %d\n", angle_procs, *(total_cont_procs_angle_Ptr), *(total_cont_procs_angle_Ptr+1), *(total_cont_procs_angle_Ptr+2)); } MPI_Reduce(&count_cont_procs, &total_cont_procs_angle, 1, MPI_INT, MPI_SUM, 0, angle_comm); //for each angle sum the number of procs to continue and pass it to the root for angle_comm cont_proc_ids_anglePtr=malloc(total_cont_procs_angle*sizeof(int)); //each root proc in angle comm has to hold the id's of the old set of processes to cont *(displPtr+0)=0; if (angle_id==0) { for (j=1;j<angle_procs;j++) { *(displPtr+j)=(*(displPtr+j-1))+(*(total_cont_procs_angle_Ptr+j-1 )); //set the displacement for each proces to put its vector of pprocess IDs that need to be continued printf("Displacement: %d\n", *(displPtr+j)); } } MPI_Gatherv(cont_proc_idsPtr,count_cont_procs,MPI_INT, cont_proc_ids_anglePtr, total_cont_procs_angle_Ptr, displPtr , MPI_INT, 0,angle_comm ); //send the vectors with the ids of the old processes that need to be cont to root in angle_comm MPI_Barrier(angle_comm); MPI_Barrier(sub_world_comm); if (angle_id==0) { printf("Total Cont Procs: %d\n", total_cont_procs_angle); for (j=0;j<total_cont_procs_angle;j++) { { printf("ID: %d\n", *(cont_proc_ids_anglePtr+j)); } } } //each root for angle_comm has the number of processes each angle range needs to restart and the array of what the IDs of those processes used to be //now have to combine all that info for rank 0 in MPI_COMM_WORLD and then end it to all processes in MPI_COMM_WORLD //if (myid==0) { free(displPtr); displPtr=NULL; //initalize variables to hold all data each_num_to_restart_per_anglePtr=malloc(num_angles*sizeof(int)); displPtr=malloc(num_angles*sizeof(int)); *(displPtr+0)=0; } MPI_Barrier(angle_comm); MPI_Barrier(sub_world_comm); if (angle_id==0) { //this is the part where all the root processes of angle_comm transfer thier info to the root proc of MPI_WORLD MPI_Reduce(&total_cont_procs_angle, &total_num_to_restart, 1, MPI_INT, MPI_SUM, 0, root_angle_comm); //for each angle sum the number of procs to continue and pass it to the root for MPI_COMM_WORLD MPI_Gather(&total_cont_procs_angle,1,MPI_INT, each_num_to_restart_per_anglePtr, 1, MPI_INT, 0,root_angle_comm );//hold the number of elements that each process sent the root for MPI_COMM_WORLD if (myid==0) { for (j=1;j<num_angles;j++) { *(displPtr+j)=(*(displPtr+j-1))+(*(each_num_to_restart_per_anglePtr+j-1 )); //set the displacement for each proces to put its vector of pprocess IDs that need to be continued } } all_cont_process_idPtr=malloc(total_num_to_restart*sizeof(int)); MPI_Gatherv(cont_proc_ids_anglePtr, total_cont_procs_angle, MPI_INT, all_cont_process_idPtr, each_num_to_restart_per_anglePtr, displPtr, MPI_INT, 0, root_angle_comm); } MPI_Barrier(angle_comm); MPI_Barrier(sub_world_comm); if (myid==0) { printf("Global Cont Procs: %d\n", total_num_to_restart); for (j=0;j<total_num_to_restart;j++) { { printf("Global ID: %d\n", *(all_cont_process_idPtr+j)); } } } //destroy the old comms MPI_Barrier(angle_comm); MPI_Barrier(sub_world_comm); //destroy current angle comm and recreate a new one MPI_Comm_free(&root_angle_comm); MPI_Comm_free(&angle_comm); MPI_Comm_free(&sub_world_comm); MPI_Group_free(&sub_world_group); MPI_Group_free(&world_group); free(cont_proc_idsPtr); free(cont_proc_ids_anglePtr); free(total_cont_procs_angle_Ptr); free(displPtr); //free(each_num_to_restart_per_anglePtr); //free(all_cont_process_idPtr); } //send all of myid==0 data to all processes in MPI_COMM_WORLD MPI_Bcast( &total_num_to_restart, 1, MPI_INT, 0, MPI_COMM_WORLD ); if (total_num_to_restart>0) { if (myid != 0 ) { //allocate data of appropriate size for all processes to hold the data from MPI_Bcast tmp=realloc(all_cont_process_idPtr,total_num_to_restart *sizeof(int)); if (tmp!=NULL) { all_cont_process_idPtr=tmp; } else { printf("Error with reserving space to hold data about restarting process ID's\n"); } //free(tmp); tmp=realloc(each_num_to_restart_per_anglePtr, num_angles*sizeof(int)); if (tmp!=NULL) { each_num_to_restart_per_anglePtr=tmp; } else { printf("Error with reserving space to hold data about restarting process numbers for each angle range\n"); } //free(tmp); } MPI_Bcast( all_cont_process_idPtr, total_num_to_restart, MPI_INT, 0, MPI_COMM_WORLD ); MPI_Bcast( each_num_to_restart_per_anglePtr, num_angles, MPI_INT, 0, MPI_COMM_WORLD ); MPI_Bcast( &old_num_angle_procs, 1, MPI_INT, 0, MPI_COMM_WORLD ); MPI_Barrier(MPI_COMM_WORLD); if (myid==numprocs-1) { printf("Number of processes: %d\n", old_num_angle_procs); printf("restarting process numbers for each angle range: %d, %d, %d\n", *(each_num_to_restart_per_anglePtr), *(each_num_to_restart_per_anglePtr+1), *(each_num_to_restart_per_anglePtr+2)); } //assign proper number of processes to each angle range to con't sims and then reset angle_id to original value from when simulation was first started color=0; //by default all processes have this value count=0; for (j=0;j<num_angles;j++) { if (myid>=count && myid<count+(*(each_num_to_restart_per_anglePtr+j)) ) { color=j; } count+=(*(each_num_to_restart_per_anglePtr+j)); printf("Myid: %d, Color: %d, Count %d, Num To Start Per Angle: %d\n", myid, color, count, (*(each_num_to_restart_per_anglePtr+j))); } MPI_Comm_split(MPI_COMM_WORLD, color , myid, &angle_comm); MPI_Comm_rank(angle_comm, &angle_id); MPI_Comm_size(angle_comm, &angle_procs); printf("WORLD RANK/SIZE: %d/%d \t ROW RANK/SIZE: %d/%d\n", myid, numprocs, angle_id, angle_procs); angle_procs=old_num_angle_procs; //reset the angle for each process theta_jmin_thread= (*(thread_theta+ color)) *(M_PI/180); theta_jmax_thread= theta_jmin_thread+(delta_theta*(M_PI/180)); //reset the angle_id for each process count=0; for (j=0;j<color;j++) { count+=(*(each_num_to_restart_per_anglePtr+j)); } angle_id=(*(all_cont_process_idPtr+count+angle_id)); snprintf(mc_dir,sizeof(flash_prefix),"%s%s%0.1lf-%0.1lf/",FILEPATH,MC_PATH, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI ); //have to add angle into this } else { //if there are no more processes to continue just break up processes normally so they read in checkpoint files of completed processes and jump to merging files MPI_Comm_split(MPI_COMM_WORLD, myid/procs_per_angle , myid, &angle_comm); MPI_Comm_rank(angle_comm, &angle_id); MPI_Comm_size(angle_comm, &angle_procs); } free(all_cont_process_idPtr); free(each_num_to_restart_per_anglePtr); } MPI_Barrier(MPI_COMM_WORLD); if ((theta_jmin_thread >= 0) && (theta_jmax_thread <= (2*M_PI/180) )) //if within small angle (0-2 degrees) use _small inj_radius and frm2 have to think about this for larger domains { inj_radius=inj_radius_small; frm2=frm2_small; frm0=frm0_small; ph_weight_suggest=ph_weight_small; } else { inj_radius=inj_radius_large; frm2=frm2_large; frm0=frm0_large; ph_weight_suggest=ph_weight_large; } //make vector to hold the frames we are injecting in, vector should have (frm2-frm0)/angle_procs slots, if fps is const proc_frame_size=ceil((frm2-frm0)/ (float) angle_procs); frame_array=malloc(((frm2-frm0)+1)*sizeof(int)); for (j=0;j<((frm2-frm0)+1); j++) { *(frame_array+j)=frm0+j ; //printf("proc: %d frame: %d\n", angle_id, *(frame_array+j)); } { //set this now incase there is no checkpoint file, then this wont be overwritten and the corretc values will be passed even if the user decides to restart framestart=(*(frame_array +(angle_id*proc_frame_size))); scatt_framestart=framestart; if (angle_id != (angle_procs-1)) { frm2=(*(frame_array +((angle_id*proc_frame_size) + proc_frame_size-1) )); //section off blocks of the frame_array to give to each angle_id } else { frm2=(*(frame_array + (frm2-frm0) )); //if angle_id is last give it the last set, even if its uneven } if (restrt=='c') { printf(">> mc.py: Reading checkpoint\n"); //#pragma omp critical readCheckpoint(mc_dir, &phPtr, &frm2, &framestart, &scatt_framestart, &num_ph, &restrt, &time_now, angle_id, &angle_procs, dim_switch, RIKEN_SWITCH); /* for (i=0;i<num_ph;i++) { printf("%e,%e,%e, %e,%e,%e, %e, %e\n",(phPtr+i)->p0, (phPtr+i)->p1, (phPtr+i)->p2, (phPtr+i)->p3, (phPtr+i)->r0, (phPtr+i)->r1, (phPtr+i)->r2, (phPtr+i)->num_scatt ); } */ if (restrt=='c') { printf(">> Rank %d: Starting from photons injected at frame: %d out of %d\n", angle_id,framestart, frm2); printf(">> Rank %d with angles %0.1lf-%0.1lf: Continuing scattering %d photons from frame: %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,num_ph, scatt_framestart); printf(">> Rank %d with angles %0.1lf-%0.1lf: The time now is: %e\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,time_now); } else { printf(">> Rank %d with angles %0.1lf-%0.1lf: Continuing simulation by injecting photons at frame: %d out of %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,framestart, frm2); //starting with new photon injection is same as restarting sim } } else if ((stat(mc_dir, &st) == -1) && (restrt=='r')) { mkdir(mc_dir, 0777); //make the directory with full permissions } else { if (angle_id==0) { printf(">> proc %d with angles %0.1lf-%0.1lf: Cleaning directory \n",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI); dirp = opendir(mc_dir); while ((entry = readdir(dirp)) != NULL) { if (entry->d_type == DT_REG) { /* If the entry is a regular file */ file_count++; //count how many files are in dorectory } } printf("File count %d\n", file_count); if (file_count>0) { for (i=0;i<=last_frm;i++) { snprintf(mc_filename,sizeof(mc_filename),"%s%s%d%s", mc_dir,"mcdata_",i,"_P0.dat"); //snprintf(mc_filename_2,sizeof(mc_filename),"%s%s%d%s", mc_dir,"mcdata_",i,"_P0_0.dat"); for (j=0;j<angle_procs;j++) { snprintf(mc_filename_2,sizeof(mc_filename),"%s%s%d%s%d%s", mc_dir,"mcdata_",i,"_P0_",j, ".dat"); if(( access( mc_filename, F_OK ) != -1 ) || ( access( mc_filename_2, F_OK ) != -1 ) ) { snprintf(mc_operation,sizeof(flash_prefix),"%s%s%s%d%s","exec rm ", mc_dir,"mcdata_",i,"_*.dat"); //prepares string to remove *.dat in mc_dir //printf("%s\n",mc_operation); system(mc_operation); snprintf(mc_operation,sizeof(flash_prefix),"%s%s%s%d%s","exec rm ", mc_dir,"mcdata_",i,"_*"); system(mc_operation); } } } snprintf(mc_operation,sizeof(flash_prefix),"%s%s%s","exec rm ", mc_dir,"mcdata_PW_*.dat"); //prepares string to remove *.dat in mc_dir system(mc_operation); snprintf(mc_operation,sizeof(flash_prefix),"%s%s%s","exec rm ", mc_dir,"mcdata_PW.dat"); //prepares string to remove *.dat in mc_dir system(mc_operation); snprintf(mc_operation,sizeof(flash_prefix),"%s%s%s","exec rm ", mc_dir,"mc_chkpt_*.dat"); //prepares string to remove *.dat in mc_dir system(mc_operation); snprintf(mc_operation,sizeof(flash_prefix),"%s%s%s","exec rm ", mc_dir,"mc_output_*.log"); //prepares string to remove *.log in mc_dir system(mc_operation); } } } if ((RIKEN_SWITCH==1) && (dim_switch==1) && (framestart>=3000)) { increment_inj=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 fps_modified=1; } else { increment_inj=1; fps_modified=fps; } dt_max=1.0/fps_modified; MPI_Barrier(angle_comm); snprintf(log_file,sizeof(log_file),"%s%s%d%s",mc_dir,"mc_output_", angle_id,".log" ); printf("%s\n",log_file); fPtr=fopen(log_file, "a"); printf( "Im Proc %d with angles %0.1lf-%0.1lf proc_frame_size is %d Starting on Frame: %d Injecting until %d scatt_framestart: %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, proc_frame_size, framestart, frm2, scatt_framestart); fprintf(fPtr, "Im Proc %d with angles %0.1lf-%0.1lf Starting on Frame: %d scatt_framestart: %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, framestart, scatt_framestart); fflush(fPtr); free(frame_array); //for a checkpoint implementation, start from the last saved "frame" value and go to the saved "frm2" value //#pragma omp for for (frame=framestart;frame<=frm2;frame=frame+increment_inj) { if ((RIKEN_SWITCH==1) && (dim_switch==1) && (frame>=3000)) { increment_inj=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 fps_modified=1; } else { increment_inj=1; fps_modified=fps; } if (restrt=='r') { time_now=frame/fps; //for a checkpoint implmentation, load the saved "time_now" value when reading the ckeckpoint file otherwise calculate it normally } //printf(">> mc.py: Working on Frame %d\n", frame); fprintf(fPtr,"Im Proc: %d with angles %0.1lf - %0.1lf Working on Frame: %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, frame); fflush(fPtr); if (restrt=='r') { if (dim_switch==0) { if (RIKEN_SWITCH==0) { //if using FLASH data for 2D //put proper number at the end of the flash file modifyFlashName(flash_file, flash_prefix, frame, dim_switch); fprintf(fPtr,">> Im Proc: %d with angles %0.1lf-%0.1lf: Opening FLASH file %s\n",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, flash_file); fflush(fPtr); readAndDecimate(flash_file, inj_radius, fps_modified, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\ &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 1, min_r, max_r, min_theta, max_theta, fPtr); } else { //if using RIKEN hydro data for 2D szx becomes delta r szy becomes delta theta readHydro2D(FILEPATH, frame, inj_radius, fps_modified, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\ &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 1, min_r, max_r, fPtr); //fprintf(fPtr, "%d\n\n", array_num); } } else { fprintf(fPtr,">> Im Proc: %d with angles %0.1lf-%0.1lf\n",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI); fflush(fPtr); read_hydro(FILEPATH, frame, inj_radius, &xPtr, &yPtr, &zPtr, &szxPtr, &szyPtr, &rPtr,\ &thetaPtr, &phiPtr, &velxPtr, &velyPtr, &velzPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 1, min_r, max_r, fps_modified, fPtr); } //check for run type if(strcmp(cyl, this_run)==0) { //printf("In cylindrical prep\n"); cylindricalPrep(gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num); } else if (strcmp(sph, this_run)==0) { printf("In Spherical\n"); sphericalPrep(rPtr, xPtr, yPtr,gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num , fPtr); } //determine where to place photons and how many should go in a given place //for a checkpoint implmentation, dont need to inject photons, need to load photons' last saved data fprintf(fPtr,">> Proc: %d with angles %0.1lf-%0.1lf: Injecting photons\n",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI); fflush(fPtr); if (dim_switch==0) { photonInjection(&phPtr, &num_ph, inj_radius, ph_weight_suggest, min_photons, max_photons,spect, array_num, fps_modified, theta_jmin_thread, theta_jmax_thread, xPtr, yPtr, szxPtr, szyPtr,rPtr,thetaPtr, tempPtr, velxPtr, velyPtr,rng, RIKEN_SWITCH, fPtr ); } else { photonInjection3D(&phPtr, &num_ph, inj_radius, ph_weight_suggest, min_photons, max_photons,spect, array_num, fps_modified, theta_jmin_thread, theta_jmax_thread, xPtr, yPtr, zPtr, szxPtr, szyPtr,rPtr,thetaPtr, phiPtr, tempPtr, velxPtr, velyPtr, velzPtr, rng, fPtr); } //printf("This many Photons: %d\n",num_ph); //num_ph is one more photon than i actually have //for (i=0;i<num_ph;i++) // printf("%e,%e,%e \n",(phPtr+i)->r0, (phPtr+i)->r1, (phPtr+i)->r2 ); } //scatter photons all the way thoughout the jet //for a checkpoint implmentation, start from the last saved "scatt_frame" value eh start_frame=frame or start_frame=cont_frame if (restrt=='r') { scatt_framestart=frame; //have to make sure that once the inner loop is done and the outer loop is incrememnted by one the inner loop starts at that new value and not the one read by readCheckpoint() } for (scatt_frame=scatt_framestart;scatt_frame<=last_frm;scatt_frame=scatt_frame+increment_scatt) { if ((RIKEN_SWITCH==1) && (dim_switch==1) && (scatt_frame>=3000)) { increment_scatt=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 fps_modified=1; //therefore dt between files become 1 second } else { increment_scatt=1; fps_modified=fps; } dt_max=1.0/fps_modified; //if working with RIKEN files and scatt_frame>=3000 dt is 1 second between each subsequent frame fprintf(fPtr,">>\n"); fprintf(fPtr,">> Proc %d with angles %0.1lf-%0.1lf: Working on photons injected at frame: %d out of %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,frame, frm2); fprintf(fPtr,">> Proc %d with angles %0.1lf-%0.1lf: %s - Working on frame %d\n",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, THISRUN, scatt_frame); fprintf(fPtr,">> Proc %d with angles %0.1lf-%0.1lf: Opening file...\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI); fflush(fPtr); //set new seed to increase randomness? gsl_rng_set(rng, gsl_rng_get(rng)); if (dim_switch==0) { if (RIKEN_SWITCH==0) { //put proper number at the end of the flash file modifyFlashName(flash_file, flash_prefix, scatt_frame, dim_switch); phMinMax(phPtr, num_ph, &min_r, &max_r, &min_theta, &max_theta, fPtr); readAndDecimate(flash_file, inj_radius, fps_modified, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\ &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 0, min_r, max_r, min_theta, max_theta, fPtr); } else { phMinMax(phPtr, num_ph, &min_r, &max_r, &min_theta, &max_theta, fPtr); //if using RIKEN hydro data for 2D szx becomes delta r szy becomes delta theta readHydro2D(FILEPATH, scatt_frame, inj_radius, fps_modified, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\ &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 0, min_r, max_r, fPtr); } } else { phMinMax(phPtr, num_ph, &min_r, &max_r, &min_theta, &max_theta, fPtr); read_hydro(FILEPATH, scatt_frame, inj_radius, &xPtr, &yPtr, &zPtr, &szxPtr, &szyPtr, &rPtr,\ &thetaPtr, &phiPtr, &velxPtr, &velyPtr, &velzPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 0, min_r, max_r, fps_modified, fPtr); } fprintf(fPtr, "Number of Flash Elements %d\n", array_num); //check for run type if(strcmp(cyl, this_run)==0) { //printf("In cylindrical prep\n"); cylindricalPrep(gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num); } else if (strcmp(sph, this_run)==0) { sphericalPrep(rPtr, xPtr, yPtr,gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num, fPtr ); } //printf("The result of read and decimate are arrays with %d elements\n", array_num); fprintf(fPtr,">> Proc %d with angles %0.1lf-%0.1lf: propagating and scattering %d photons\n",angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI,num_ph); fflush(fPtr); frame_scatt_cnt=0; find_nearest_grid_switch=1; // set to true so the function findNearestPropertiesAndMinMFP by default finds the index of the grid block closest to each photon since we just read in a file and the prior index is invalid while (time_now<((scatt_frame+increment_scatt)/fps)) { //if simulation time is less than the simulation time of the next frame, keep scattering in this frame //for RIKEN hydro data, theres still 10 fps but after frame 3000, file increment is 10 not 1, therefore modify dt_max not fps //go through each photon and find blocks closest to each photon and properties of those blocks to calulate mean free path //and choose the photon with the smallest mfp and calculate the timestep ph_scatt_index=findNearestPropertiesAndMinMFP(phPtr, num_ph, array_num, hydro_domain_x, hydro_domain_y, &time_step, xPtr, yPtr, zPtr, szxPtr, szyPtr, velxPtr, velyPtr, velzPtr, dens_labPtr, tempPtr,\ &ph_dens_labPtr, &ph_vxPtr, &ph_vyPtr, &ph_vzPtr, &ph_tempPtr, rng, dim_switch, find_nearest_grid_switch, RIKEN_SWITCH, fPtr); find_nearest_grid_switch=0; //set to zero (false) since we do not absolutely need to refind the index, this makes the function findNearestPropertiesAndMinMFP just check if the photon is w/in the given grid box still //fprintf(fPtr, "In main: %e, %d, %e, %e\n",((phPtr+ph_scatt_index)->num_scatt), ph_scatt_index, time_step, time_now); //fflush(fPtr); if (time_step<dt_max) { //update number of scatterings and time ((phPtr+ph_scatt_index)->num_scatt)+=1; frame_scatt_cnt+=1; time_now+=time_step; updatePhotonPosition(phPtr, num_ph, time_step, fPtr); //scatter the photon //fprintf(fPtr, "Passed Parameters: %e, %e, %e\n", (ph_vxPtr), (ph_vyPtr), (ph_tempPtr)); photonScatter( (phPtr+ph_scatt_index), (ph_vxPtr), (ph_vyPtr),ph_vzPtr, (ph_tempPtr), rng, dim_switch, fPtr ); if (frame_scatt_cnt%1000 == 0) { fprintf(fPtr,"Scattering Number: %d\n", frame_scatt_cnt); fprintf(fPtr,"The local temp is: %e\n", (ph_tempPtr)); fprintf(fPtr,"Average photon energy is: %e\n", averagePhotonEnergy(phPtr, num_ph)); //write function to average over the photons p0 and then do (*3e10/1.6e-9) fprintf(fPtr,"The last time step was: %e.\nThe time now is: %e\n", time_step,time_now); fflush(fPtr); } } else { time_now+=dt_max; //for each photon update its position based on its momentum updatePhotonPosition(phPtr, num_ph, dt_max, fPtr); } //printf("In main 2: %e, %d, %e, %e\n", ((phPtr+ph_scatt_index)->num_scatt), ph_scatt_index, time_step, time_now); } //get scattering statistics phScattStats(phPtr, num_ph, &max_scatt, &min_scatt, &avg_scatt, &avg_r); fprintf(fPtr,"The number of scatterings in this frame is: %d\n", frame_scatt_cnt); fprintf(fPtr,"The last time step was: %e.\nThe time now is: %e\n", time_step,time_now); fprintf(fPtr,"The maximum number of scatterings for a photon is: %d\nThe minimum number of scattering for a photon is: %d\n", max_scatt, min_scatt); fprintf(fPtr,"The average number of scatterings thus far is: %lf\nThe average position of photons is %e\n", avg_scatt, avg_r); fflush(fPtr); printPhotons(phPtr, num_ph, scatt_frame , frame, mc_dir, angle_id); //exit(0); fprintf(fPtr, ">> Proc %d with angles %0.1lf-%0.1lf: Making checkpoint file\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI); fflush(fPtr); fprintf(fPtr, " mc_dir: %s\nframe %d\nfrm2: %d\nscatt_frame: %d\n num_photon: %d\ntime_now: %e\nlast_frame: %d\n", mc_dir, frame, frm2, scatt_frame, num_ph, time_now, last_frm ); fflush(fPtr); saveCheckpoint(mc_dir, frame, frm2, scatt_frame, num_ph, time_now, phPtr, last_frm, angle_id, old_num_angle_procs); if (dim_switch==1) { if (RIKEN_SWITCH==1) { free(zPtr);free(phiPtr);free(velzPtr); zPtr=NULL; phiPtr=NULL; velzPtr=NULL; } } free(xPtr);free(yPtr);free(szxPtr);free(szyPtr);free(rPtr);free(thetaPtr);free(velxPtr);free(velyPtr);free(densPtr);free(presPtr); free(gammaPtr);free(dens_labPtr);free(tempPtr); xPtr=NULL; yPtr=NULL; rPtr=NULL;thetaPtr=NULL;velxPtr=NULL;velyPtr=NULL;densPtr=NULL;presPtr=NULL;gammaPtr=NULL;dens_labPtr=NULL; szxPtr=NULL; szyPtr=NULL; tempPtr=NULL; } restrt='r';//set this to make sure that the next iteration of propogating photons doesnt use the values from the last reading of the checkpoint file free(phPtr); phPtr=NULL; } saveCheckpoint(mc_dir, frame, frm2, scatt_frame, 0, time_now, phPtr, last_frm, angle_id, old_num_angle_procs); //this is for processes using the old code that didnt restart efficiently fprintf(fPtr, "Process %d has completed the MC calculation.\n", angle_id); fflush(fPtr); }//end omp parallel inner section MPI_Barrier(angle_comm); //merge files from each worker thread within a directory { increment_scatt=1; file_count=0; //count number of files for (i=frm0;i<=last_frm;i=i+increment_scatt) { if ((RIKEN_SWITCH==1) && (dim_switch==1) && (i>=3000)) { increment_scatt=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 } file_count++; } //holds number of files for each process to merge MPI_Comm_size(angle_comm, &angle_procs); //to get the proper number of processes within the group MPI_Comm_rank(angle_comm, &angle_id); //reset the value of angle_id to what it should actualy be to properly distribute files to merge proc_frame_size=floor(file_count/ (float) angle_procs); frame_array=malloc(file_count*sizeof(int)); proc_frame_array=malloc(angle_procs*sizeof(int)); //sets index of each proceesed acquired value element_num=malloc(angle_procs*sizeof(int)); for (i=0;i<angle_procs;i++) { *(proc_frame_array+i)=i*proc_frame_size; *(element_num+i)=1; } //make vector with the files in order to pass them to each of the processes increment_scatt=1; file_count=0; for (i=frm0;i<=last_frm;i=i+increment_scatt) { if ((RIKEN_SWITCH==1) && (dim_switch==1) && (i>=3000)) { increment_scatt=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 } *(frame_array+file_count)=i ; file_count++; //printf("file_count: %d frame: %d\n", file_count-1, *(frame_array+file_count-1)); } //pass first frame number that each rpocess should start to merge, can calulate the file it should merge until MPI_Scatterv(frame_array, element_num, proc_frame_array, MPI_INT, &frm0, 1, MPI_INT, 0, angle_comm); //fprintf(fPtr, "Value: last_frm: ,%d\n", file_count); //fflush(fPtr); //make sure all files get merged by giving the rest to the last process if (angle_id==angle_procs-1) { proc_frame_size=file_count-proc_frame_size*(angle_procs-1); //for last process take over the remaining number of files } //calculate what the last file the preocess should merge up to i=0; last_frm=frm0; while(i<proc_frame_size) { if ((RIKEN_SWITCH==1) && (dim_switch==1) && (last_frm>=3000)) { increment_scatt=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 } else { increment_scatt=1; } last_frm+=increment_scatt; i++; } //if (angle_id==0) { //fprintf(fPtr, ">> Proc %d with angles %0.1lf-%0.1lf: Merging Files from %d to %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, frm0, last_frm); fprintf(fPtr, ">> Proc %d with angles %0.1lf-%0.1lf: Merging Files from %d to %d\n", angle_id, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, frm0, last_frm); fflush(fPtr); dirFileMerge(mc_dir, frm0, last_frm, old_num_angle_procs, angle_id, dim_switch, RIKEN_SWITCH, fPtr); } } fprintf(fPtr, "Process %d has completed merging files.\n", angle_id); fflush(fPtr); fclose(fPtr); gsl_rng_free (rng); MPI_Finalize(); //free(rng); //free(thread_theta); return 0; }
{ "alphanum_fraction": 0.5533395797, "avg_line_length": 51.8819444444, "ext": "c", "hexsha": "2effc30f3abbb7470d0829cc440344c8c3d154e5", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-11-20T09:12:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "outflows/MCRaT", "max_forks_repo_path": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mcrat.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "outflows/MCRaT", "max_issues_repo_path": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mcrat.c", "max_line_length": 346, "max_stars_count": 4, "max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "outflows/MCRaT", "max_stars_repo_path": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mcrat.c", "max_stars_repo_stars_event_max_datetime": "2021-04-05T14:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-20T08:37:35.000Z", "num_tokens": 12458, "size": 52297 }
/* Copyright [2017-2021] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __API_MCAS_ITF__ #define __API_MCAS_ITF__ #include <api/components.h> #include <api/kvindex_itf.h> #include <api/kvstore_itf.h> #include <boost/optional.hpp> #include <common/byte_span.h> #include <common/pointer_cast.h> #include <common/string_view.h> #include <gsl/span> #include <array> #include <cstdint> /* uint16_t */ #include <memory> #define DECLARE_OPAQUE_TYPE(NAME) \ struct Opaque_##NAME { \ virtual ~Opaque_##NAME() {} \ } namespace component { /** * mcas client interface (this will include both KV and AS capabilities) */ class IMCAS : public component::IBase, public KVStore { public: // clang-format off DECLARE_INTERFACE_UUID(0x33af1b99,0xbc51,0x49ff,0xa27b,0xd4,0xe8,0x19,0x03,0xbb,0x02); // clang-format on public: DECLARE_OPAQUE_TYPE(async_handle); using async_handle_t = Opaque_async_handle*; using pool_t = component::KVStore::pool_t; using key_t = KVStore::key_t; using Attribute = KVStore::Attribute; using Addr = KVStore::Addr; static constexpr async_handle_t ASYNC_HANDLE_INIT = nullptr; enum { FLAGS_NONE = KVStore::FLAGS_NONE, FLAGS_READ_ONLY = KVStore::FLAGS_READ_ONLY, FLAGS_SET_SIZE = KVStore::FLAGS_SET_SIZE, FLAGS_CREATE_ONLY = KVStore::FLAGS_CREATE_ONLY, FLAGS_DONT_STOMP = KVStore::FLAGS_DONT_STOMP, FLAGS_NO_RESIZE = KVStore::FLAGS_NO_RESIZE, FLAGS_MAX_VALUE = KVStore::FLAGS_MAX_VALUE, }; /* per-shard statistics */ struct Shard_stats { uint64_t op_request_count; uint64_t op_put_count; uint64_t op_get_count; uint64_t op_put_direct_count; uint64_t op_get_direct_count; uint64_t op_get_twostage_count; uint64_t op_ado_count; uint64_t op_erase_count; uint64_t op_get_direct_offset_count; uint64_t op_failed_request_count; uint64_t last_op_count_snapshot; uint16_t client_count; public: Shard_stats() : op_request_count(0) , op_put_count(0), op_get_count(0), op_put_direct_count(0), op_get_direct_count(0), op_get_twostage_count(0) , op_ado_count(0), op_erase_count(0), op_get_direct_offset_count(0) , op_failed_request_count(0), last_op_count_snapshot(0), client_count(0) { } } __attribute__((packed)); using ado_flags_t = uint32_t; static constexpr ado_flags_t ADO_FLAG_NONE = 0; /*< operation is asynchronous */ static constexpr ado_flags_t ADO_FLAG_ASYNC = (1 << 0); /*< create KV pair if needed */ static constexpr ado_flags_t ADO_FLAG_CREATE_ON_DEMAND = (1 << 1); /*< create only - allocate key,value but don't call ADO */ static constexpr ado_flags_t ADO_FLAG_CREATE_ONLY = (1 << 2); /*< do not overwrite value if it already exists */ static constexpr ado_flags_t ADO_FLAG_NO_OVERWRITE = (1 << 3); /*< create value but do not attach to key, unless key does not exist */ static constexpr ado_flags_t ADO_FLAG_DETACHED = (1 << 4); /*< only take read lock */ static constexpr ado_flags_t ADO_FLAG_READ_ONLY = (1 << 5); /*< zero any newly allocated value memory */ static constexpr ado_flags_t ADO_FLAG_ZERO_NEW_VALUE = (1 << 6); /*< internal use only: on return provide IO response */ static constexpr ado_flags_t ADO_FLAG_INTERNAL_IO_RESPONSE = (1 << 7); /*< internal use only: on return provide IO response with value buffer */ static constexpr ado_flags_t ADO_FLAG_INTERNAL_IO_RESPONSE_VALUE = (1 << 8); public: /** * Determine thread safety of the component * * * @return THREAD_MODEL_XXXX */ virtual int thread_safety() const = 0; /** * If the ADO is configured for the shard then the ADO process is * instantiated "attached" to the pool. * * The "base" parameter is unused. */ using KVStore::create_pool; using KVStore::open_pool; using KVStore::delete_pool; /** * Close and delete an existing pool from a pool handle. Only one * reference count should exist. Any ADO plugin is notified before * the pool is deleted. * * @param pool Pool handle * * @return S_OK or E_BUSY if reference count > 1 */ virtual status_t delete_pool(const pool_t pool) = 0; /** * Configure a pool * * @param setting Configuration request (e.g., AddIndex::VolatileTree) * * @return S_OK on success */ virtual status_t configure_pool(const pool_t pool, const std::string& setting) = 0; using KVStore::put; virtual status_t put(const pool_t pool, const std::string& key, const std::string& value, const unsigned int flags = FLAGS_NONE) { /* this does not store any null terminator */ return put(pool, key, value.data(), value.length(), flags); } /* * Asynchronous put operation. Use check_async_completion to check for * completion. This operation is not normally used, simple put is fast. * * @param pool Pool handle * @param key Object key * @param value Value * @param value_len Value length in bytes * @param out_handle Async work handle * @param flags Optional flags * * @return S_OK or other error code */ virtual status_t async_put(const IMCAS::pool_t pool, const std::string& key, const void* value, const size_t value_len, async_handle_t& out_handle, const unsigned int flags = IMCAS::FLAGS_NONE) = 0; virtual status_t async_put(const IMCAS::pool_t pool, const std::string& key, const std::string& value, async_handle_t& out_handle, const unsigned int flags = IMCAS::FLAGS_NONE) { (void)out_handle; // unused return async_put(pool, key, value.data(), value.length(), out_handle, flags); } /** * Zero-copy only if value size > ~2MiB or FORCE_DIRECT=1 is set. */ using KVStore::put_direct; /** * Asynchronous put_direct operation. Use check_async_completion to check for * completion. * * @param pool Pool handle * @param key Object key * @param value Value * @param value_len Value length in bytes * @param handle Memory registration handle * @param out_handle Async handle * @param flags Optional flags * * @return S_OK or other error code */ virtual status_t async_put_direct(const IMCAS::pool_t pool, const std::string& key, const void* value, const size_t value_len, async_handle_t& out_handle, const memory_handle_t handle = IMCAS::MEMORY_HANDLE_NONE, const unsigned int flags = IMCAS::FLAGS_NONE) { return async_put_direct( pool , key , std::array<common::const_byte_span,1>{common::make_const_byte_span(value, value_len)} , out_handle, std::array<memory_handle_t,1>{handle} , flags ); } /** * Asynchronous put_direct operation. Use check_async_completion to check for * completion. * * @param pool Pool handle * @param key Object key * @param values list of value sources * @param out_handle Async handle * @param handle List of memory registration handle * @param flags Optional flags * * @return S_OK or other error code */ virtual status_t async_put_direct(const IMCAS::pool_t pool, const std::string& key, gsl::span<const common::const_byte_span> value, async_handle_t& out_handle, gsl::span<const memory_handle_t> handles = gsl::span<const memory_handle_t>(), const unsigned int flags = IMCAS::FLAGS_NONE) = 0; using KVStore::get; virtual status_t get(const pool_t pool, const std::string& key, std::string& out_value) { void* val = nullptr; size_t val_size = 0; auto s = this->get(pool, key, val, val_size); /* copy result */ if (s == S_OK) { out_value.assign(static_cast<char*>(val), val_size); this->free_memory(val); } return s; } /** * Asynchronously read an object value directly into client-provided memory. * * @param pool Pool handle * @param key Object key * @param out_value Client provided buffer for value * @param out_value_len [in] size of value memory in bytes [out] size of value * @param out_handle Async work handle * @param handle Memory registration handle * * @return S_OK, S_MORE if only a portion of value is read, E_BAD_ALIGNMENT on * invalid alignment, or other error code */ virtual status_t async_get_direct(const IMCAS::pool_t pool, const std::string& key, void* out_value, size_t& out_value_len, async_handle_t& out_handle, const IMCAS::memory_handle_t handle = IMCAS::MEMORY_HANDLE_NONE) = 0; /** * Read memory directly into client-provided memory. * * @param pool Pool handle * @param offset offset within ithe concatenation of the pool's memory regions * @param size requested size (becomes available size) * @param out_buffer Client provided buffer for value * @param out_handle Async work handle * @param handle Memory registration handle * * @return S_OK, or error code */ virtual status_t async_get_direct_offset(const IMCAS::pool_t pool, const offset_t offset, size_t &size, void* out_buffer, async_handle_t& out_handle, const IMCAS::memory_handle_t handle = IMCAS::MEMORY_HANDLE_NONE) = 0; virtual status_t get_direct_offset(const IMCAS::pool_t pool, const offset_t offset, size_t &size, void* out_buffer, const IMCAS::memory_handle_t handle = IMCAS::MEMORY_HANDLE_NONE) = 0; /** * Write memory directly into client-provided memory. * * @param pool Pool handle * @param offset offset within ithe concatenation of the pool's memory regions * @param size offered size (becomes available size) * @param buffer Client provided value * @param out_handle Async work handle * @param handle Memory registration handle * * @return S_OK, or error code */ virtual status_t async_put_direct_offset(const IMCAS::pool_t pool, const offset_t offset, size_t &size, const void *const buffer, async_handle_t& out_handle, const IMCAS::memory_handle_t handle = IMCAS::MEMORY_HANDLE_NONE) = 0; virtual status_t put_direct_offset(const IMCAS::pool_t pool, const offset_t offset, size_t &size, const void *const buffer, const IMCAS::memory_handle_t handle = IMCAS::MEMORY_HANDLE_NONE) = 0; /** * Check for completion from asynchronous invocation * * @param handle Asynchronous work handle. * * @return S_OK or E_BUSY if not yet complete */ virtual status_t check_async_completion(async_handle_t& handle) = 0; /** * Perform key search based on regex or prefix * * @param pool Pool handle * @param key_expression Regular expression or prefix (e.g. "prefix:carKey") * @param offset Offset from which to search * @param out_matched_offset Out offset of match * @param out_keys Out vector of matching keys * * @return S_OK on success */ virtual status_t find(const IMCAS::pool_t pool, const std::string& key_expression, const offset_t offset, offset_t& out_matched_offset, std::string& out_matched_key) = 0; /** * Erase an object asynchronously * * @param pool Pool handle * @param key Object key * @param out_handle Async work handle * * @return S_OK or error code */ virtual status_t async_erase(const IMCAS::pool_t pool, const std::string& key, async_handle_t& out_handle) = 0; /** * Retrieve shard statistics * * @param out_stats * * @return S_OK on success */ virtual status_t get_statistics(Shard_stats& out_stats) = 0; /** * ADO_response data structure manages response data sent back from the ADO * invocations. The free function is so we can eventually support zero-copy. * The layer id identifies which ADO plugin the response came from. */ class ADO_response { private: #pragma GCC diagnostic push /* pointer members are considered inefficient */ #pragma GCC diagnostic ignored "-Weffc++" class Data_reference { public: Data_reference(void * data) : _data(data) { assert(data); } Data_reference() = delete; virtual ~Data_reference() { assert(_data); ::free(_data); } void * _data; }; #pragma GCC diagnostic pop public: ADO_response() = delete; ADO_response(void* data, size_t data_len, uint32_t layer_id) : _ref(std::make_shared<Data_reference>(data)), _data_len(data_len), _layer_id(layer_id) {} ADO_response(ADO_response&& src) noexcept : _ref(src.datasp()), _data_len(src.data_len()), _layer_id(src.layer_id()) {} inline std::string str() const { return std::string(data(), data_len()); } inline const char* data() const { return static_cast<const char*>(_ref->_data); } inline size_t data_len() const { return _data_len; } inline uint32_t layer_id() const { return _layer_id; } inline std::shared_ptr<Data_reference>& datasp() { return _ref; } template <typename T> inline T* cast_data() const { return static_cast<T*>(_ref->_data); } private: std::shared_ptr<Data_reference> _ref; /* smart pointer */ size_t _data_len; uint32_t _layer_id; /* optional layer identifier */ }; /** * Used to invoke an operation on an active data object * * Roughly, the shard locates a data value by key and calls ADO (with accessors to both the key and data). * Several variations: * 1) Skip the "locate data" operation (could have been directed by a null * key address in the basic_string_view form, or by a flag, but is * instead indicated by a zero-length key) * 2) Skip the ADO call (directed by ADO_FLAG_CREATE_ONLY) * 3) Create uninitialized data of size value_size if the key was not found * (directed by ADO_FLAG_CREATE_ON_DEMAND) * 4) Create uninitialized data of size value_size if the key was not found(?) * not associated with the key and maybe also create a "root value" which * which is attached to the key (directed by ADO_FLAG_DETACHED) * * @param pool Pool handle * @param key Key. Note, if key is empty, the work request is key-less. * @param request Request data * @param request_len Length of request in bytes * @param flags Flags for invocation (see ADO_FLAG_CREATE_ONLY, ADO_FLAG_READ_ONLY) * @param out_response Responses from invocation * @param value_size Optional parameter to define value size to create for * on-demand * * @return S_OK on success */ virtual status_t invoke_ado(const IMCAS::pool_t pool, const basic_string_view<byte> key, const basic_string_view<byte> request, const ado_flags_t flags, std::vector<ADO_response>& out_response, const size_t value_size = 0) = 0; virtual status_t invoke_ado(const IMCAS::pool_t pool, const std::string& key, const void* request, const size_t request_len, const ado_flags_t flags, std::vector<ADO_response>& out_response, const size_t value_size = 0) { return invoke_ado(pool, basic_string_view<byte>(common::pointer_cast<const byte>(key.data()), key.size()), basic_string_view<byte>(static_cast<const byte *>(request), request_len), flags, out_response, value_size); } inline status_t invoke_ado(const IMCAS::pool_t pool, const std::string& key, const std::string& request, const ado_flags_t flags, std::vector<ADO_response>& out_response, const size_t value_size = 0) { return invoke_ado(pool, key, request.data(), request.length(), flags, out_response, value_size); } /** * Used to asynchronously invoke an operation on an ADO * * Roughly, the shard locates a data value by key and calls ADO (with accessors to both the key and data). * * @param pool Pool handle * @param key Key. Note, if key is empty, the work request is key-less. * @param request Request data * @param request_len Length of request in bytes * @param flags Flags for invocation (see ADO_FLAG_XXX) * @param out_response Response passed back from ADO invocation * @param out_async_handle Handle to task for later result collection * @param value_size Optional parameter to define value size to create for on-demand * * @return S_OK on success */ virtual status_t async_invoke_ado(const IMCAS::pool_t pool, const basic_string_view<byte> key, const basic_string_view<byte> request, const ado_flags_t flags, std::vector<ADO_response>& out_response, async_handle_t& out_async_handle, const size_t value_size = 0) = 0; inline status_t async_invoke_ado(const IMCAS::pool_t pool, const std::string& key, const std::string& request, const ado_flags_t flags, std::vector<ADO_response>& out_response, async_handle_t& out_async_handle, const size_t value_size = 0) { return async_invoke_ado(pool, basic_string_view<byte>(common::pointer_cast<const byte>(key.data()), key.size()), basic_string_view<byte>(common::pointer_cast<const byte>(request.data()), request.length()), flags, out_response, out_async_handle, value_size); } inline status_t async_invoke_ado(const IMCAS::pool_t pool, const std::string& key, const void* request, const size_t request_len, const ado_flags_t flags, std::vector<ADO_response>& out_response, async_handle_t& out_async_handle, const size_t value_size = 0) { return async_invoke_ado(pool, basic_string_view<byte>(common::pointer_cast<const byte>(key.data()), key.size()), basic_string_view<byte>(static_cast<const byte *>(request), request_len), flags, out_response, out_async_handle, value_size); } /** * Used to invoke a combined put + ADO operation on an active data object. * * Roughly, the shard writes a data value by key and calls ADO (with accessors to both the key and data). * * @param pool Pool handle * @param key Key * @param request Request data * @param request_len Length of request data in bytes * @param value Value data * @param value_len Length of value data in bytes * @param root_len Length to allocate for root value (with ADO_FLAG_DETACHED) * @param flags Flags for invocation (ADO_FLAG_NO_OVERWRITE, ADO_FLAG_DETACHED) * @param out_response Response passed back from ADO invocation * * @return S_OK on success */ virtual status_t invoke_put_ado(const IMCAS::pool_t pool, const basic_string_view<byte> key, const basic_string_view<byte> request, const basic_string_view<byte> value, const size_t root_len, const ado_flags_t flags, std::vector<ADO_response>& out_response) = 0; virtual status_t invoke_put_ado(const IMCAS::pool_t pool, const std::string& key, const void* request, const size_t request_len, const void* value, const size_t value_len, const size_t root_len, const ado_flags_t flags, std::vector<ADO_response>& out_response) { return invoke_put_ado(pool, basic_string_view<byte>(common::pointer_cast<const byte>(key.data()), key.size()), basic_string_view<byte>(static_cast<const byte *>(request), request_len), basic_string_view<byte>(static_cast<const byte *>(value), value_len), root_len, flags, out_response); } inline status_t invoke_put_ado(const IMCAS::pool_t pool, const std::string& key, const std::string& request, const std::string& value, const size_t root_len, const ado_flags_t flags, std::vector<ADO_response>& out_response) { return invoke_put_ado(pool, key, request.data(), request.length(), value.data(), value.length(), root_len, flags, out_response); } /** * Used to asynchronously invoke a combined put + ADO operation on an active data object. * * Roughly, the shard writes a data value by key and calls ADO (with accessors to both the key and data). * * @param pool Pool handle * @param key Key * @param request Request data * @param request_len Length of request data in bytes * @param value Value data * @param value_len Length of value data in bytes * @param root_len Length to allocate for root value (with ADO_FLAG_DETACHED) * @param flags Flags for invocation (ADO_FLAG_NO_OVERWRITE, ADO_FLAG_DETACHED) * @param out_response Responses from ADO invocation * @param out_async_handle Handle to task for later result collection * * @return S_OK on success */ virtual status_t async_invoke_put_ado(const IMCAS::pool_t pool, const basic_string_view<byte> key, const basic_string_view<byte> request, const basic_string_view<byte> value, const size_t root_len, const ado_flags_t flags, std::vector<ADO_response>& out_response, async_handle_t& out_async_handle) = 0; virtual status_t async_invoke_put_ado(const IMCAS::pool_t pool, const std::string& key, const void* request, const size_t request_len, const void* value, const size_t value_len, const size_t root_len, const ado_flags_t flags, std::vector<ADO_response>& out_response, async_handle_t& out_async_handle) { return async_invoke_put_ado(pool, basic_string_view<byte>(common::pointer_cast<const byte>(key.data()), key.size()), basic_string_view<byte>(static_cast<const byte *>(request), request_len), basic_string_view<byte>(static_cast<const byte *>(value), value_len), root_len, flags, out_response, out_async_handle); } inline status_t async_invoke_put_ado(const IMCAS::pool_t pool, const std::string& key, const std::string& request, const std::string& value, const size_t root_len, const ado_flags_t flags, std::vector<ADO_response>& out_response, async_handle_t& out_async_handle) { return async_invoke_put_ado(pool, key, request.data(), request.length(), value.data(), value.length(), root_len, flags, out_response, out_async_handle); } /** * Debug routine * * @param pool Pool handle * @param cmd Debug command * @param arg Parameter for debug operation */ virtual void debug(const IMCAS::pool_t pool, const unsigned cmd, const uint64_t arg) = 0; }; class IMCAS_factory : public IKVStore_factory { using string_view = common::string_view; public: // clang-format off DECLARE_INTERFACE_UUID(0xfacf1b99,0xbc51,0x49ff,0xa27b,0xd4,0xe8,0x19,0x03,0xbb,0x02); // clang-format on /** * Create a session to a remote shard * * @param debug_level Debug level (0-3) * @param patience Time out patience in seconds * @param owner Owner info (not used) * @param src_nic_device Client-side network device (e.g., mlx5_0, eth0) * @param src_ip_addr Client-side IP address * @param dest_addr_with_port Server-side IP address and port (e.g. 10.0.0.21:11911, 9.1.75.6:11911:sockets) * @param other Other optional parameters (e.g. { "security":"tls:auth" }) * * @return Pointer to IMCAS instance. Use release_ref() to close. */ virtual IMCAS* mcas_create_nsd(const unsigned, // debug_level const unsigned, // patience const string_view, // owner const string_view, // src_nic_device const string_view, // src_ip_addr const string_view, // dest_addr_with_port const string_view = string_view()) // other { throw API_exception("IMCAS_factory::mcas_create(debug_level,patience,owner,addr_with_port,nic_device) not implemented"); } /** * Create a session to a remote shard (alternative) * * @param debug_level Debug level * @param patience Timeout patience in seconds * @param owner Owner information (not used) * @param dest_addr_with_port Destination server IP address and port * @param nic_device Local NIC device to use (e.g., mlx5_0, eth0) * @param other Other optional parameters (e.g. { "security":"tls:auth" }) * * @return Pointer to IMCAS instance. Use release_ref() to close. */ IMCAS* mcas_create(const unsigned debug_level, const unsigned patience, const string_view owner, const string_view dest_addr_with_port, const string_view nic_device, const string_view other = string_view()) { return mcas_create_nsd(debug_level, patience, owner, nic_device, string_view(), dest_addr_with_port, other); } }; } // namespace component #endif
{ "alphanum_fraction": 0.5580925504, "avg_line_length": 41.1385224274, "ext": "h", "hexsha": "6cd25105178115cf74054b1f7c7c9b94876b9d21", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "IBM/artemis", "max_forks_repo_path": "src/components/api/mcas_itf.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "IBM/artemis", "max_issues_repo_path": "src/components/api/mcas_itf.h", "max_line_length": 124, "max_stars_count": null, "max_stars_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "IBM/artemis", "max_stars_repo_path": "src/components/api/mcas_itf.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6508, "size": 31183 }
// // @author raver119@gmail.com // #ifndef LIBND4J_BLAS_HELPER_H #define LIBND4J_BLAS_HELPER_H #include <pointercast.h> #include <types/float16.h> #include <cblas.h> #include <helpers/logger.h> #ifdef _WIN32 #define CUBLASWINAPI __stdcall #else #define CUBLASWINAPI #endif namespace nd4j { typedef enum{ CUBLAS_STATUS_SUCCESS =0, CUBLAS_STATUS_NOT_INITIALIZED =1, CUBLAS_STATUS_ALLOC_FAILED =3, CUBLAS_STATUS_INVALID_VALUE =7, CUBLAS_STATUS_ARCH_MISMATCH =8, CUBLAS_STATUS_MAPPING_ERROR =11, CUBLAS_STATUS_EXECUTION_FAILED=13, CUBLAS_STATUS_INTERNAL_ERROR =14, CUBLAS_STATUS_NOT_SUPPORTED =15, CUBLAS_STATUS_LICENSE_ERROR =16 } cublasStatus_t; typedef enum { CUBLAS_OP_N=0, CUBLAS_OP_T=1, CUBLAS_OP_C=2 } cublasOperation_t; struct cublasContext; typedef struct cublasContext *cublasHandle_t; typedef enum { CUDA_R_16F= 2, /* real as a half */ CUDA_C_16F= 6, /* complex as a pair of half numbers */ CUDA_R_32F= 0, /* real as a float */ CUDA_C_32F= 4, /* complex as a pair of float numbers */ CUDA_R_64F= 1, /* real as a double */ CUDA_C_64F= 5, /* complex as a pair of double numbers */ CUDA_R_8I = 3, /* real as a signed char */ CUDA_C_8I = 7, /* complex as a pair of signed char numbers */ CUDA_R_8U = 8, /* real as a unsigned char */ CUDA_C_8U = 9, /* complex as a pair of unsigned char numbers */ CUDA_R_32I= 10, /* real as a signed int */ CUDA_C_32I= 11, /* complex as a pair of signed int numbers */ CUDA_R_32U= 12, /* real as a unsigned int */ CUDA_C_32U= 13 /* complex as a pair of unsigned int numbers */ } cublasDataType_t; typedef void (*CblasSgemv)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE TransA, int M, int N, float alpha, float *A, int lda, float *X, int incX, float beta, float *Y, int incY); typedef void (*CblasDgemv)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE TransA, int M, int N, double alpha, double *A, int lda, double *X, int incX, double beta, double *Y, int incY); typedef void (*CblasSgemm)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, int M, int N, int K, float alpha, float *A, int lda, float *B, int ldb, float beta, float *C, int ldc); typedef void (*CblasDgemm)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, int M, int N, int K, double alpha, double *A, int lda, double *B, int ldb, double beta, double *C, int ldc); typedef void (*CblasSgemmBatch)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE *TransA_Array, CBLAS_TRANSPOSE *TransB_Array, int *M_Array, int *N_Array, int *K_Array, float *alpha_Array, float **A_Array, int *lda_Array, float **B_Array, int *ldb_Array, float *beta_Array, float **C_Array, int *ldc_Array, int group_count, int *group_size); typedef void (*CblasDgemmBatch)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE *TransA_Array, CBLAS_TRANSPOSE *TransB_Array, int *M_Array, int *N_Array, int *K_Array, double *alpha_Array, double **A_Array, int *lda_Array, double **B_Array, int* ldb_Array, double *beta_Array, double **C_Array, int *ldc_Array, int group_count, int *group_size); typedef cublasStatus_t (CUBLASWINAPI *CublasSgemv)(cublasHandle_t handle, cublasOperation_t trans, int m, int n, float *alpha, /* host or device pointer */ float *A, int lda, float *x, int incx, float *beta, /* host or device pointer */ float *y, int incy); typedef cublasStatus_t (CUBLASWINAPI *CublasDgemv)(cublasHandle_t handle, cublasOperation_t trans, int m, int n, double *alpha, /* host or device pointer */ double *A, int lda, double *x, int incx, double *beta, /* host or device pointer */ double *y, int incy); typedef cublasStatus_t (CUBLASWINAPI *CublasHgemm)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, __half *alpha, /* host or device pointer */ __half *A, int lda, __half *B, int ldb, __half *beta, /* host or device pointer */ __half *C, int ldc); typedef cublasStatus_t (CUBLASWINAPI *CublasSgemm)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, float *alpha, /* host or device pointer */ float *A, int lda, float *B, int ldb, float *beta, /* host or device pointer */ float *C, int ldc); typedef cublasStatus_t (CUBLASWINAPI *CublasDgemm)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, double *alpha, /* host or device pointer */ double *A, int lda, double *B, int ldb, double *beta, /* host or device pointer */ double *C, int ldc); typedef cublasStatus_t (CUBLASWINAPI *CublasSgemmEx)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, float *alpha, /* host or device pointer */ void *A, cublasDataType_t Atype, int lda, void *B, cublasDataType_t Btype, int ldb, float *beta, /* host or device pointer */ void *C, cublasDataType_t Ctype, int ldc); typedef cublasStatus_t (CUBLASWINAPI *CublasHgemmBatched)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, __half *alpha, /* host or device pointer */ __half *Aarray[], int lda, __half *Barray[], int ldb, __half *beta, /* host or device pointer */ __half *Carray[], int ldc, int batchCount); typedef cublasStatus_t (CUBLASWINAPI *CublasSgemmBatched)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, float *alpha, /* host or device pointer */ float *Aarray[], int lda, float *Barray[], int ldb, float *beta, /* host or device pointer */ float *Carray[], int ldc, int batchCount); typedef cublasStatus_t (CUBLASWINAPI *CublasDgemmBatched)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, double *alpha, /* host or device pointer */ double *Aarray[], int lda, double *Barray[], int ldb, double *beta, /* host or device pointer */ double *Carray[], int ldc, int batchCount); enum BlasFunctions { GEMV = 0, GEMM = 1, }; class BlasHelper { private: static BlasHelper* _instance; bool _hasHgemv = false; bool _hasHgemm = false; bool _hasHgemmBatch = false; bool _hasSgemv = false; bool _hasSgemm = false; bool _hasSgemmBatch = false; bool _hasDgemv = false; bool _hasDgemm = false; bool _hasDgemmBatch = false; CblasSgemv cblasSgemv; CblasDgemv cblasDgemv; CblasSgemm cblasSgemm; CblasDgemm cblasDgemm; CblasSgemmBatch cblasSgemmBatch; CblasDgemmBatch cblasDgemmBatch; CublasSgemv cublasSgemv; CublasDgemv cublasDgemv; CublasHgemm cublasHgemm; CublasSgemm cublasSgemm; CublasDgemm cublasDgemm; CublasSgemmEx cublasSgemmEx; CublasHgemmBatched cublasHgemmBatched; CublasSgemmBatched cublasSgemmBatched; CublasDgemmBatched cublasDgemmBatched; public: static BlasHelper* getInstance(); void initializeFunctions(Nd4jPointer *functions); void initializeDeviceFunctions(Nd4jPointer *functions); template <typename T> bool hasGEMV(); template <typename T> bool hasGEMM(); template <typename T> bool hasBatchedGEMM(); CblasSgemv sgemv(); CblasDgemv dgemv(); CblasSgemm sgemm(); CblasDgemm dgemm(); CblasSgemmBatch sgemmBatched(); CblasDgemmBatch dgemmBatched(); }; } #endif
{ "alphanum_fraction": 0.355244567, "avg_line_length": 49.3787375415, "ext": "h", "hexsha": "a193e52b315b3ac5114cdcb7fc34e937a2a2a681", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-03-25T06:48:25.000Z", "max_forks_repo_forks_event_min_datetime": "2022-03-25T06:48:25.000Z", "max_forks_repo_head_hexsha": "6be4678caf6f820f5b0fd1a5392c0941936f2e43", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "gluonhq/libnd4j", "max_forks_repo_path": "include/helpers/BlasHelper.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6be4678caf6f820f5b0fd1a5392c0941936f2e43", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "gluonhq/libnd4j", "max_issues_repo_path": "include/helpers/BlasHelper.h", "max_line_length": 104, "max_stars_count": null, "max_stars_repo_head_hexsha": "6be4678caf6f820f5b0fd1a5392c0941936f2e43", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "gluonhq/libnd4j", "max_stars_repo_path": "include/helpers/BlasHelper.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2553, "size": 14863 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include <windows.h> // Include ABI composition headers for interop with DCOMP surface handle from MediaEngine #include <windows.ui.composition.h> #include <windows.ui.composition.interop.h> // Include prior to WinRT Headers #include <wil/cppwinrt.h> // WinRT Headers #include <winrt/Windows.Foundation.h> #include <winrt/Windows.Foundation.Collections.h> #include <winrt/Windows.ApplicationModel.Core.h> #include <winrt/Windows.UI.Core.h> #include <winrt/Windows.UI.Composition.h> #include <winrt/Windows.UI.Input.h> #include <winrt/Windows.Media.Protection.h> #include <winrt/Windows.Storage.h> #include <winrt/Windows.Storage.Streams.h> #include <winrt/Windows.Web.Http.Headers.h> #include <winrt/Windows.Data.Xml.Dom.h> #include <winrt/Windows.Security.Cryptography.h> #include <winrt/Windows.ApplicationModel.h> // Direct3D #include <d3d11.h> // Windows Implementation Library #include <wil/com.h> #include <wil/resource.h> #include <wil/result_macros.h> // MediaFoundation headers #include <mfapi.h> #include <mferror.h> #include <mfmediaengine.h> #include <mfidl.h> #include <mfcontentdecryptionmodule.h> // STL headers #include <functional> #include <memory> #include <string> #include <vector> #include <tuple> #include <array> // GSL (C++ Guidelines Support Library) #include <gsl/span>
{ "alphanum_fraction": 0.7621776504, "avg_line_length": 25.8518518519, "ext": "h", "hexsha": "332f8146884f36f730a58435bea2249f24e3fa25", "lang": "C", "max_forks_count": 19, "max_forks_repo_forks_event_max_datetime": "2022-02-17T09:17:10.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-08T17:18:37.000Z", "max_forks_repo_head_hexsha": "dc81175a3e893c7c58fcbf1a943ac342e39f172c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "QPC-database/media-foundation", "max_forks_repo_path": "samples/MediaEngineEMEUWPSample/src/pch.h", "max_issues_count": 14, "max_issues_repo_head_hexsha": "dc81175a3e893c7c58fcbf1a943ac342e39f172c", "max_issues_repo_issues_event_max_datetime": "2022-03-22T12:25:39.000Z", "max_issues_repo_issues_event_min_datetime": "2020-08-06T06:46:00.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "QPC-database/media-foundation", "max_issues_repo_path": "samples/MediaEngineEMEUWPSample/src/pch.h", "max_line_length": 89, "max_stars_count": 62, "max_stars_repo_head_hexsha": "f5a0d6133992514733c42ee2f70c869daf5a75e1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "microsoft/media-foundation", "max_stars_repo_path": "samples/MediaEngineEMEUWPSample/src/pch.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T21:51:19.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-09T01:38:18.000Z", "num_tokens": 334, "size": 1396 }
/* multifit/multilinear.c * * Copyright (C) 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> /* Fit * * y = X c * * where X is an M x N matrix of M observations for N variables. * */ int gsl_multifit_linear (const gsl_matrix * X, const gsl_vector * y, gsl_vector * c, gsl_matrix * cov, double *chisq, gsl_multifit_linear_workspace * work) { if (X->size1 != y->size) { GSL_ERROR ("number of observations in y does not match rows of matrix X", GSL_EBADLEN); } else if (X->size2 != c->size) { GSL_ERROR ("number of parameters c does not match columns of matrix X", GSL_EBADLEN); } else if (cov->size1 != cov->size2) { GSL_ERROR ("covariance matrix is not square", GSL_ENOTSQR); } else if (c->size != cov->size1) { GSL_ERROR ("number of parameters does not match size of covariance matrix", GSL_EBADLEN); } else if (X->size1 != work->n || X->size2 != work->p) { GSL_ERROR ("size of workspace does not match size of observation matrix", GSL_EBADLEN); } else { const size_t n = X->size1; const size_t p = X->size2; size_t i, j; gsl_matrix *A = work->A; gsl_matrix *Q = work->Q; gsl_matrix *QSI = work->QSI; gsl_vector *S = work->S; gsl_vector *xt = work->xt; gsl_vector *D = work->D; /* Copy X to workspace, A <= X */ gsl_matrix_memcpy (A, X); /* Balance the columns of the matrix A */ gsl_linalg_balance_columns (A, D); /* Decompose A into U S Q^T */ gsl_linalg_SV_decomp_mod (A, QSI, Q, S, xt); /* Solve y = A c for c */ gsl_blas_dgemv (CblasTrans, 1.0, A, y, 0.0, xt); /* Scale the matrix Q, Q' = Q S^-1 */ gsl_matrix_memcpy (QSI, Q); for (j = 0; j < p; j++) { gsl_vector_view column = gsl_matrix_column (QSI, j); double alpha = gsl_vector_get (S, j); if (alpha != 0) alpha = 1.0 / alpha; gsl_vector_scale (&column.vector, alpha); } gsl_vector_set_zero (c); gsl_blas_dgemv (CblasNoTrans, 1.0, QSI, xt, 0.0, c); /* Unscale the balancing factors */ gsl_vector_div (c, D); /* Compute chisq, from residual r = y - X c */ { double s2 = 0, r2 = 0; for (i = 0; i < n; i++) { double yi = gsl_vector_get (y, i); gsl_vector_const_view row = gsl_matrix_const_row (X, i); double y_est, ri; gsl_blas_ddot (&row.vector, c, &y_est); ri = yi - y_est; r2 += ri * ri; } s2 = r2 / (n - p); *chisq = r2; /* Form variance-covariance matrix cov = s2 * (Q S^-1) (Q S^-1)^T */ for (i = 0; i < p; i++) { gsl_vector_view row_i = gsl_matrix_row (QSI, i); double d_i = gsl_vector_get (D, i); for (j = i; j < p; j++) { gsl_vector_view row_j = gsl_matrix_row (QSI, j); double d_j = gsl_vector_get (D, j); double s; gsl_blas_ddot (&row_i.vector, &row_j.vector, &s); gsl_matrix_set (cov, i, j, s * s2 / (d_i * d_j)); gsl_matrix_set (cov, j, i, s * s2 / (d_i * d_j)); } } } return GSL_SUCCESS; } } int gsl_multifit_wlinear (const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, gsl_vector * c, gsl_matrix * cov, double *chisq, gsl_multifit_linear_workspace * work) { if (X->size1 != y->size) { GSL_ERROR ("number of observations in y does not match rows of matrix X", GSL_EBADLEN); } else if (X->size2 != c->size) { GSL_ERROR ("number of parameters c does not match columns of matrix X", GSL_EBADLEN); } else if (w->size != y->size) { GSL_ERROR ("number of weights does not match number of observations", GSL_EBADLEN); } else if (cov->size1 != cov->size2) { GSL_ERROR ("covariance matrix is not square", GSL_ENOTSQR); } else if (c->size != cov->size1) { GSL_ERROR ("number of parameters does not match size of covariance matrix", GSL_EBADLEN); } else if (X->size1 != work->n || X->size2 != work->p) { GSL_ERROR ("size of workspace does not match size of observation matrix", GSL_EBADLEN); } else { const size_t n = X->size1; const size_t p = X->size2; size_t i, j; gsl_matrix *A = work->A; gsl_matrix *Q = work->Q; gsl_matrix *QSI = work->QSI; gsl_vector *S = work->S; gsl_vector *t = work->t; gsl_vector *xt = work->xt; gsl_vector *D = work->D; /* Scale X, A = sqrt(w) X */ gsl_matrix_memcpy (A, X); for (i = 0; i < n; i++) { double wi = gsl_vector_get (w, i); if (wi < 0) wi = 0; { gsl_vector_view row = gsl_matrix_row (A, i); gsl_vector_scale (&row.vector, sqrt (wi)); } } /* Balance the columns of the matrix A */ gsl_linalg_balance_columns (A, D); /* Decompose A into U S Q^T */ gsl_linalg_SV_decomp_mod (A, QSI, Q, S, xt); /* Solve sqrt(w) y = A c for c, by first computing t = sqrt(w) y */ for (i = 0; i < n; i++) { double wi = gsl_vector_get (w, i); double yi = gsl_vector_get (y, i); if (wi < 0) wi = 0; gsl_vector_set (t, i, sqrt (wi) * yi); } gsl_blas_dgemv (CblasTrans, 1.0, A, t, 0.0, xt); /* Scale the matrix Q, Q' = Q S^-1 */ gsl_matrix_memcpy (QSI, Q); for (j = 0; j < p; j++) { gsl_vector_view column = gsl_matrix_column (QSI, j); double alpha = gsl_vector_get (S, j); if (alpha != 0) alpha = 1.0 / alpha; gsl_vector_scale (&column.vector, alpha); } gsl_vector_set_zero (c); /* Solution */ gsl_blas_dgemv (CblasNoTrans, 1.0, QSI, xt, 0.0, c); /* Unscale the balancing factors */ gsl_vector_div (c, D); /* Form covariance matrix cov = (Q S^-1) (Q S^-1)^T */ for (i = 0; i < p; i++) { gsl_vector_view row_i = gsl_matrix_row (QSI, i); double d_i = gsl_vector_get (D, i); for (j = i; j < p; j++) { gsl_vector_view row_j = gsl_matrix_row (QSI, j); double d_j = gsl_vector_get (D, j); double s; gsl_blas_ddot (&row_i.vector, &row_j.vector, &s); gsl_matrix_set (cov, i, j, s / (d_i * d_j)); gsl_matrix_set (cov, j, i, s / (d_i * d_j)); } } /* Compute chisq, from residual r = y - X c */ { double r2 = 0; for (i = 0; i < n; i++) { double yi = gsl_vector_get (y, i); double wi = gsl_vector_get (w, i); gsl_vector_const_view row = gsl_matrix_const_row (X, i); double y_est, ri; gsl_blas_ddot (&row.vector, c, &y_est); ri = yi - y_est; r2 += wi * ri * ri; } *chisq = r2; } return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.5773072313, "avg_line_length": 23.3925233645, "ext": "c", "hexsha": "c80cceca3941f60c11703a183dbc73b92b7071a7", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/multifit/multilinear.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/multifit/multilinear.c", "max_line_length": 77, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/multifit/multilinear.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 2367, "size": 7509 }
#include <r.h> #include <string.h> #include <math.h> #include <assert.h> #include <stdlib.h> #include <gsl/gsl_cdf.h> static void uniformly_distributed(uint64_t (*f)(void)) { const size_t B = 10, N = 100000; size_t boxes[B]; memset(boxes, 0, sizeof(boxes)); for(size_t i = 0; i < N; i++) { boxes[f() % B] += 1; } double chi2 = 0; for(size_t i = 0; i < B; i++) { const double E = (double)N/B; const double err = (double)boxes[i] - E; chi2 += err*err/E; } assert(chi2 <= gsl_cdf_chisq_Pinv(0.95, B-1)); } static void normally_distributed(float (*f)(void)) { const size_t B = 5, N = 1000; size_t boxes[B+1]; memset(boxes, 0, sizeof(boxes)); float stddev = 2; for(size_t i = 0; i < N; i++) { size_t j = floor(fabsf(f()) * stddev); boxes[MIN(j, B)] += 1; } double E = 2*N*gsl_cdf_gaussian_Q(B, stddev); double err = (double)boxes[B] - E; double chi2 = err*err/E; for(size_t i = 0; i < B; i++) { E = N * 2 * (gsl_cdf_gaussian_P(i+1, stddev) - gsl_cdf_gaussian_P(i, stddev)); err = (double)boxes[i] - E; chi2 += err*err/E; } assert(chi2 <= gsl_cdf_chisq_Pinv(0.95, B)); } void xorshift_tests(void) { xorshift_state_initialize(); TEST(xorshift64_is_uniform, { uniformly_distributed(xorshift64_i); }); TEST(xorshift128plus_is_uniform, { uniformly_distributed(xorshift128plus_i); }); TEST(normal_dist_is_normal, { normally_distributed(normal_dist_i); }); TEST_ABORT(xorshift64_is_not_normal, { float f() { return uniform_float(xorshift64_i()); } normally_distributed(f); }); TEST_ABORT(normal_dist_is_not_uniform, { uint64_t f() { return llrint(fabsf(normal_dist_i())); } uniformly_distributed(f); }); TEST_ABORT(normal_dist_test_should_respect_stddev, { float f() { return 2*normal_dist_i(); } normally_distributed(f); }); }
{ "alphanum_fraction": 0.5915422886, "avg_line_length": 24.2168674699, "ext": "c", "hexsha": "91dd810454e8f431a9f744af9af8cf16ffdbc861", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "721421394fef92287e5c05248dccd28ed97e01b5", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "rootmos/libr", "max_forks_repo_path": "tests/xorshift.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "721421394fef92287e5c05248dccd28ed97e01b5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "rootmos/libr", "max_issues_repo_path": "tests/xorshift.c", "max_line_length": 86, "max_stars_count": null, "max_stars_repo_head_hexsha": "721421394fef92287e5c05248dccd28ed97e01b5", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "rootmos/libr", "max_stars_repo_path": "tests/xorshift.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 608, "size": 2010 }
/* specfunc/legendre_poly.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "gsl_sf_bessel.h" #include "gsl_sf_exp.h" #include "gsl_sf_gamma.h" #include "gsl_sf_log.h" #include "gsl_sf_pow_int.h" #include "gsl_sf_legendre.h" #include "error.h" /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_legendre_P1_e(double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ { result->val = x; result->err = 0.0; return GSL_SUCCESS; } } int gsl_sf_legendre_P2_e(double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ { result->val = 0.5*(3.0*x*x - 1.0); result->err = GSL_DBL_EPSILON * (fabs(3.0*x*x) + 1.0); return GSL_SUCCESS; } } int gsl_sf_legendre_P3_e(double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ { result->val = 0.5*x*(5.0*x*x - 3.0); result->err = GSL_DBL_EPSILON * (fabs(result->val) + 0.5 * fabs(x) * (fabs(5.0*x*x) + 3.0)); return GSL_SUCCESS; } } int gsl_sf_legendre_Pl_e(const int l, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(l < 0 || x < -1.0 || x > 1.0) { DOMAIN_ERROR(result); } else if(l == 0) { result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else if(l == 1) { result->val = x; result->err = 0.0; return GSL_SUCCESS; } else if(l == 2) { result->val = 0.5 * (3.0*x*x - 1.0); result->err = 3.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x == 1.0) { result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else if(x == -1.0) { result->val = ( GSL_IS_ODD(l) ? -1.0 : 1.0 ); result->err = 0.0; return GSL_SUCCESS; } else if(l < 100000) { /* Compute by upward recurrence on l. */ double p_mm = 1.0; /* P_0(x) */ double p_mmp1 = x; /* P_1(x) */ double p_ell = p_mmp1; int ell; for(ell=2; ell <= l; ell++){ p_ell = (x*(2*ell-1)*p_mmp1 - (ell-1)*p_mm) / ell; p_mm = p_mmp1; p_mmp1 = p_ell; } result->val = p_ell; result->err = (0.5 * ell + 1.0) * GSL_DBL_EPSILON * fabs(p_ell); return GSL_SUCCESS; } else { /* Asymptotic expansion. * [Olver, p. 473] */ double u = l + 0.5; double th = acos(x); gsl_sf_result J0; gsl_sf_result Jm1; int stat_J0 = gsl_sf_bessel_J0_e(u*th, &J0); int stat_Jm1 = gsl_sf_bessel_Jn_e(-1, u*th, &Jm1); double pre; double B00; double c1; /* B00 = 1/8 (1 - th cot(th) / th^2 * pre = sqrt(th/sin(th)) */ if(th < GSL_ROOT4_DBL_EPSILON) { B00 = (1.0 + th*th/15.0)/24.0; pre = 1.0 + th*th/12.0; } else { double sin_th = sqrt(1.0 - x*x); double cot_th = x / sin_th; B00 = 1.0/8.0 * (1.0 - th * cot_th) / (th*th); pre = sqrt(th/sin_th); } c1 = th/u * B00; result->val = pre * (J0.val + c1 * Jm1.val); result->err = pre * (J0.err + fabs(c1) * Jm1.err); result->err += GSL_SQRT_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_J0, stat_Jm1); } } int gsl_sf_legendre_Pl_array(const int lmax, const double x, double * result_array) { /* CHECK_POINTER(result_array) */ if(lmax < 0 || x < -1.0 || x > 1.0) { GSL_ERROR ("domain error", GSL_EDOM); } else if(lmax == 0) { result_array[0] = 1.0; return GSL_SUCCESS; } else if(lmax == 1) { result_array[0] = 1.0; result_array[1] = x; return GSL_SUCCESS; } else { double p_mm = 1.0; /* P_0(x) */ double p_mmp1 = x; /* P_1(x) */ double p_ell = p_mmp1; int ell; result_array[0] = 1.0; result_array[1] = x; for(ell=2; ell <= lmax; ell++){ p_ell = (x*(2*ell-1)*p_mmp1 - (ell-1)*p_mm) / ell; p_mm = p_mmp1; p_mmp1 = p_ell; result_array[ell] = p_ell; } return GSL_SUCCESS; } } int gsl_sf_legendre_Plm_e(const int l, const int m, const double x, gsl_sf_result * result) { /* If l is large and m is large, then we have to worry * about overflow. Calculate an approximate exponent which * measures the normalization of this thing. */ double dif = l-m; double sum = l+m; double exp_check = 0.5 * log(2.0*l+1.0) + 0.5 * dif * (log(dif)-1.0) - 0.5 * sum * (log(sum)-1.0); /* CHECK_POINTER(result) */ if(m < 0 || l < m || x < -1.0 || x > 1.0) { DOMAIN_ERROR(result); } else if(exp_check < GSL_LOG_DBL_MIN + 10.0){ /* Bail out. */ OVERFLOW_ERROR(result); } else { /* Account for the error due to the * representation of 1-x. */ const double err_amp = 1.0 / (GSL_DBL_EPSILON + fabs(1.0-fabs(x))); double p_mm; /* P_m^m(x) */ double p_mmp1; /* P_{m+1}^m(x) */ /* Calculate P_m^m from the analytic result: * P_m^m(x) = (-1)^m (2m-1)!! (1-x^2)^(m/2) , m > 0 */ p_mm = 1.0; if(m > 0){ double root_factor = sqrt(1.0-x)*sqrt(1.0+x); double fact_coeff = 1.0; int i; for(i=1; i<=m; i++) { p_mm *= -fact_coeff * root_factor; fact_coeff += 2.0; } } /* Calculate P_{m+1}^m. */ p_mmp1 = x * (2*m + 1) * p_mm; if(l == m){ result->val = p_mm; result->err = err_amp * 2.0 * GSL_DBL_EPSILON * fabs(p_mm); return GSL_SUCCESS; } else if(l == m + 1) { result->val = p_mmp1; result->err = err_amp * 2.0 * GSL_DBL_EPSILON * fabs(p_mmp1); return GSL_SUCCESS; } else{ double p_ell = 0.0; int ell; /* Compute P_l^m, l > m+1 by upward recurrence on l. */ for(ell=m+2; ell <= l; ell++){ p_ell = (x*(2*ell-1)*p_mmp1 - (ell+m-1)*p_mm) / (ell-m); p_mm = p_mmp1; p_mmp1 = p_ell; } result->val = p_ell; result->err = err_amp * (0.5*(l-m) + 1.0) * GSL_DBL_EPSILON * fabs(p_ell); return GSL_SUCCESS; } } } int gsl_sf_legendre_Plm_array(const int lmax, const int m, const double x, double * result_array) { /* If l is large and m is large, then we have to worry * about overflow. Calculate an approximate exponent which * measures the normalization of this thing. */ double dif = lmax-m; double sum = lmax+m; double exp_check = 0.5 * log(2.0*lmax+1.0) + 0.5 * dif * (log(dif)-1.0) - 0.5 * sum * (log(sum)-1.0); /* CHECK_POINTER(result_array) */ if(m < 0 || lmax < m || x < -1.0 || x > 1.0) { GSL_ERROR ("error", GSL_EDOM); } else if(m > 0 && (x == 1.0 || x == -1.0)) { int ell; for(ell=m; ell<=lmax; ell++) result_array[ell-m] = 0.0; return GSL_SUCCESS; } else if(exp_check < GSL_LOG_DBL_MIN + 10.0){ /* Bail out. */ GSL_ERROR ("error", GSL_EOVRFLW); } else { double p_mm; /* P_m^m(x) */ double p_mmp1; /* P_{m+1}^m(x) */ /* Calculate P_m^m from the analytic result: * P_m^m(x) = (-1)^m (2m-1)!! (1-x^2)^(m/2) , m > 0 */ p_mm = 1.0; if(m > 0){ double root_factor = sqrt(1.0-x)*sqrt(1.0+x); double fact_coeff = 1.0; int i; for(i=1; i<=m; i++){ p_mm *= -fact_coeff * root_factor; fact_coeff += 2.0; } } /* Calculate P_{m+1}^m. */ p_mmp1 = x * (2*m + 1) * p_mm; if(lmax == m){ result_array[0] = p_mm; return GSL_SUCCESS; } else if(lmax == m + 1) { result_array[0] = p_mm; result_array[1] = p_mmp1; return GSL_SUCCESS; } else{ double p_ell; int ell; result_array[0] = p_mm; result_array[1] = p_mmp1; /* Compute P_l^m, l >= m+2, by upward recursion on l. */ for(ell=m+2; ell <= lmax; ell++){ p_ell = (x*(2*ell-1)*p_mmp1 - (ell+m-1)*p_mm) / (ell-m); p_mm = p_mmp1; p_mmp1 = p_ell; result_array[ell-m] = p_ell; } return GSL_SUCCESS; } } } int gsl_sf_legendre_sphPlm_e(const int l, int m, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(m < 0 || l < m || x < -1.0 || x > 1.0) { DOMAIN_ERROR(result); } else if(m == 0) { gsl_sf_result P; int stat_P = gsl_sf_legendre_Pl_e(l, x, &P); double pre = sqrt((2.0*l + 1.0)/(4.0*M_PI)); result->val = pre * P.val; result->err = pre * P.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_P; } else if(x == 1.0 || x == -1.0) { /* m > 0 here */ result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else { /* m > 0 and |x| < 1 here */ /* Starting value for recursion. * Y_m^m(x) = sqrt( (2m+1)/(4pi m) gamma(m+1/2)/gamma(m) ) (-1)^m (1-x^2)^(m/2) / pi^(1/4) */ gsl_sf_result lncirc; gsl_sf_result lnpoch; double lnpre_val; double lnpre_err; gsl_sf_result ex_pre; double sr; const double sgn = ( GSL_IS_ODD(m) ? -1.0 : 1.0); const double y_mmp1_factor = x * sqrt(2.0*m + 3.0); double y_mm, y_mm_err; double y_mmp1; gsl_sf_log_1plusx_e(-x*x, &lncirc); gsl_sf_lnpoch_e(m, 0.5, &lnpoch); /* Gamma(m+1/2)/Gamma(m) */ lnpre_val = -0.25*M_LNPI + 0.5 * (lnpoch.val + m*lncirc.val); lnpre_err = 0.25*M_LNPI*GSL_DBL_EPSILON + 0.5 * (lnpoch.err + fabs(m)*lncirc.err); gsl_sf_exp_err_e(lnpre_val, lnpre_err, &ex_pre); sr = sqrt((2.0+1.0/m)/(4.0*M_PI)); y_mm = sgn * sr * ex_pre.val; y_mmp1 = y_mmp1_factor * y_mm; y_mm_err = 2.0 * GSL_DBL_EPSILON * fabs(y_mm) + sr * ex_pre.err; y_mm_err *= 1.0 + 1.0/(GSL_DBL_EPSILON + fabs(1.0-x)); if(l == m){ result->val = y_mm; result->err = y_mm_err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(y_mm); return GSL_SUCCESS; } else if(l == m + 1) { result->val = y_mmp1; result->err = fabs(y_mmp1_factor) * y_mm_err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(y_mmp1); return GSL_SUCCESS; } else{ double y_ell = 0.0; int ell; /* Compute Y_l^m, l > m+1, upward recursion on l. */ for(ell=m+2; ell <= l; ell++){ const double rat1 = (double)(ell-m)/(double)(ell+m); const double rat2 = (ell-m-1.0)/(ell+m-1.0); const double factor1 = sqrt(rat1*(2*ell+1)*(2*ell-1)); const double factor2 = sqrt(rat1*rat2*(2*ell+1)/(2*ell-3)); y_ell = (x*y_mmp1*factor1 - (ell+m-1)*y_mm*factor2) / (ell-m); y_mm = y_mmp1; y_mmp1 = y_ell; } result->val = y_ell; result->err = (0.5*(l-m) + 1.0) * GSL_DBL_EPSILON * fabs(y_ell); result->err += fabs(y_mm_err/y_mm) * fabs(y_ell); return GSL_SUCCESS; } } } int gsl_sf_legendre_sphPlm_array(const int lmax, int m, const double x, double * result_array) { /* CHECK_POINTER(result_array) */ if(m < 0 || lmax < m || x < -1.0 || x > 1.0) { GSL_ERROR ("error", GSL_EDOM); } else if(m > 0 && (x == 1.0 || x == -1.0)) { int ell; for(ell=m; ell<=lmax; ell++) result_array[ell-m] = 0.0; return GSL_SUCCESS; } else { double y_mm; double y_mmp1; if(m == 0) { y_mm = 0.5/M_SQRTPI; /* Y00 = 1/sqrt(4pi) */ y_mmp1 = x * M_SQRT3 * y_mm; } else { /* |x| < 1 here */ gsl_sf_result lncirc; gsl_sf_result lnpoch; double lnpre; const double sgn = ( GSL_IS_ODD(m) ? -1.0 : 1.0); gsl_sf_log_1plusx_e(-x*x, &lncirc); gsl_sf_lnpoch_e(m, 0.5, &lnpoch); /* Gamma(m+1/2)/Gamma(m) */ lnpre = -0.25*M_LNPI + 0.5 * (lnpoch.val + m*lncirc.val); y_mm = sqrt((2.0+1.0/m)/(4.0*M_PI)) * sgn * exp(lnpre); y_mmp1 = x * sqrt(2.0*m + 3.0) * y_mm; } if(lmax == m){ result_array[0] = y_mm; return GSL_SUCCESS; } else if(lmax == m + 1) { result_array[0] = y_mm; result_array[1] = y_mmp1; return GSL_SUCCESS; } else{ double y_ell; int ell; result_array[0] = y_mm; result_array[1] = y_mmp1; /* Compute Y_l^m, l > m+1, upward recursion on l. */ for(ell=m+2; ell <= lmax; ell++){ const double rat1 = (double)(ell-m)/(double)(ell+m); const double rat2 = (ell-m-1.0)/(ell+m-1.0); const double factor1 = sqrt(rat1*(2*ell+1)*(2*ell-1)); const double factor2 = sqrt(rat1*rat2*(2*ell+1)/(2*ell-3)); y_ell = (x*y_mmp1*factor1 - (ell+m-1)*y_mm*factor2) / (ell-m); y_mm = y_mmp1; y_mmp1 = y_ell; result_array[ell-m] = y_ell; } } return GSL_SUCCESS; } } #ifndef HIDE_INLINE_STATIC int gsl_sf_legendre_array_size(const int lmax, const int m) { return lmax-m+1; } #endif /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_legendre_P1(const double x) { EVAL_RESULT(gsl_sf_legendre_P1_e(x, &result)); } double gsl_sf_legendre_P2(const double x) { EVAL_RESULT(gsl_sf_legendre_P2_e(x, &result)); } double gsl_sf_legendre_P3(const double x) { EVAL_RESULT(gsl_sf_legendre_P3_e(x, &result)); } double gsl_sf_legendre_Pl(const int l, const double x) { EVAL_RESULT(gsl_sf_legendre_Pl_e(l, x, &result)); } double gsl_sf_legendre_Plm(const int l, const int m, const double x) { EVAL_RESULT(gsl_sf_legendre_Plm_e(l, m, x, &result)); } double gsl_sf_legendre_sphPlm(const int l, const int m, const double x) { EVAL_RESULT(gsl_sf_legendre_sphPlm_e(l, m, x, &result)); }
{ "alphanum_fraction": 0.5579562249, "avg_line_length": 25.6018018018, "ext": "c", "hexsha": "5c4cdaff79d2a800f73fc45e3c68375bd4e9ac74", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/legendre_poly.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/legendre_poly.c", "max_line_length": 96, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/legendre_poly.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 5113, "size": 14209 }
/* Copyright [2017-2021] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef _MCAS_HSTORE_POOL_MANAGER_H #define _MCAS_HSTORE_POOL_MANAGER_H #include <api/kvstore_itf.h> /* status_t */ #include "alloc_key.h" /* AK_FORMAL */ #include "pool_error.h" #include <common/logging.h> /* log_source */ #include <common/string_view.h> #include <nupm/region_descriptor.h> #include <gsl/pointers> #include <sys/uio.h> #include <cstddef> #include <functional> #include <string> #include <system_error> struct pool_path; struct dax_manager; template <typename Pool> struct pool_manager : protected common::log_source { using string_view = common::string_view; pool_manager(unsigned debug_level_) : common::log_source(debug_level_) {} virtual ~pool_manager() {} virtual void pool_create_check(const std::size_t size_) = 0; virtual void pool_close_check(const string_view) = 0; virtual nupm::region_descriptor pool_get_regions(const Pool &) const = 0; /* * throws pool_error if create_region fails */ virtual auto pool_create_1( const pool_path &path_ , std::size_t size_ ) -> nupm::region_descriptor = 0; virtual auto pool_create_2( AK_FORMAL const nupm::region_descriptor & rac , component::IKVStore::flags_t flags , std::size_t expected_obj_count ) -> std::unique_ptr<Pool> = 0; virtual auto pool_open_1( const pool_path &path_ ) -> nupm::region_descriptor = 0; virtual auto pool_open_2( AK_FORMAL const nupm::region_descriptor & access_ , component::IKVStore::flags_t flags_ ) -> std::unique_ptr<Pool> = 0; virtual void pool_delete(const pool_path &path) = 0; virtual const std::unique_ptr<dax_manager> & get_dax_manager() const = 0; }; #endif
{ "alphanum_fraction": 0.7110920034, "avg_line_length": 28.7160493827, "ext": "h", "hexsha": "f6725c1eeeabea3f1177eafcf223aff46d24c50c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "fQuinzan/mcas", "max_forks_repo_path": "src/components/store/hstore/src/pool_manager.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "fQuinzan/mcas", "max_issues_repo_path": "src/components/store/hstore/src/pool_manager.h", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "fQuinzan/mcas", "max_stars_repo_path": "src/components/store/hstore/src/pool_manager.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 583, "size": 2326 }
/* gaussiate - generate with the GSL some Gaussian random variates */ #include <err.h> #include <fcntl.h> #include <float.h> #include <getopt.h> #include <limits.h> #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sysexits.h> #include <unistd.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> // https://github.com/thrig/goptfoo #include <goptfoo.h> #define DEFAULT_COUNT 10000UL #define DEFAULT_SIGMA 1.0 unsigned long Flag_Count; /* -n */ float Flag_Sigma; /* -S */ void emit_help(void); int main(int argc, char *argv[]) { int ch; #ifndef __OpenBSD__ int fd; #endif gsl_rng *gsl_rand; uint32_t seed; #ifdef __OpenBSD__ if (pledge("stdio", NULL) == -1) err(1, "pledge failed"); #endif if (!(gsl_rand = gsl_rng_alloc(gsl_rng_taus2))) err(EX_SOFTWARE, "could not gsl_rng_alloc()"); #ifdef __OpenBSD__ seed = arc4random(); #else /* assume there is a random device otherwise */ if ((fd = open("/dev/urandom", O_RDONLY)) == -1) err(EX_OSERR, "could not open /dev/urandom"); if (read(fd, &seed, sizeof(seed)) != sizeof(seed)) err(EX_OSERR, "incomplete read of /dev/urandom"); close(fd); #endif while ((ch = getopt(argc, argv, "h?n:S:")) != -1) { switch (ch) { case 'n': Flag_Count = flagtoul(ch, optarg, 1UL, ULONG_MAX); break; case 'S': Flag_Sigma = (float) flagtod(ch, optarg, 0.0, (double) FLT_MAX); break; case 'h': case '?': default: emit_help(); /* NOTREACHED */ } } argc -= optind; argv += optind; if (Flag_Count == 0) Flag_Count = DEFAULT_COUNT; if (!isnormal(Flag_Sigma)) Flag_Sigma = DEFAULT_SIGMA; gsl_rng_set(gsl_rand, seed); for (unsigned long n = 0; n < Flag_Count; n++) printf("%.6f\n", gsl_ran_gaussian(gsl_rand, Flag_Sigma)); exit(EXIT_SUCCESS); } void emit_help(void) { fputs("Usage: gaussiate [-n count] [-S sigma]\n", stderr); exit(EX_USAGE); }
{ "alphanum_fraction": 0.5923149016, "avg_line_length": 22.4631578947, "ext": "c", "hexsha": "2b5a7955aec5a472cb8df81278181392a383227c", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-04-17T09:25:48.000Z", "max_forks_repo_forks_event_min_datetime": "2020-01-03T15:58:46.000Z", "max_forks_repo_head_hexsha": "cbde9e8ea8c3abcad0745276b06a30f1c21f9221", "max_forks_repo_licenses": [ "0BSD" ], "max_forks_repo_name": "thrig/scripts", "max_forks_repo_path": "math/gaussiate.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "cbde9e8ea8c3abcad0745276b06a30f1c21f9221", "max_issues_repo_issues_event_max_datetime": "2020-01-04T08:43:07.000Z", "max_issues_repo_issues_event_min_datetime": "2020-01-04T08:43:07.000Z", "max_issues_repo_licenses": [ "0BSD" ], "max_issues_repo_name": "thrig/scripts", "max_issues_repo_path": "math/gaussiate.c", "max_line_length": 76, "max_stars_count": 17, "max_stars_repo_head_hexsha": "cbde9e8ea8c3abcad0745276b06a30f1c21f9221", "max_stars_repo_licenses": [ "0BSD" ], "max_stars_repo_name": "thrig/scripts", "max_stars_repo_path": "math/gaussiate.c", "max_stars_repo_stars_event_max_datetime": "2021-11-14T06:31:45.000Z", "max_stars_repo_stars_event_min_datetime": "2017-01-30T18:00:47.000Z", "num_tokens": 599, "size": 2134 }
#ifndef MKL_TEMPLATE #define MKL_TEMPLATE //#include <cblas.h> #include <stddef.h> //#include <blas.h> #ifdef small #undef small #endif //#include <lapack.h> #include <cblas_defvar.h> #ifdef NEW_MATLAB typedef ptrdiff_t INTT; #else typedef int INTT; #endif /// a few static variables for lapack static char low='l'; static char lower='L'; static char nonUnit='n'; static char upper='u'; static INTT info=0; static char incr='I'; static char decr='D'; static char all='A'; static char no='N'; static char reduced='S'; static char allV='V'; #ifdef REMOVE_ #define dnrm2_ dnrm2 #define snrm2_ snrm2 #define dcopy_ dcopy #define scopy_ scopy #define daxpy_ daxpy #define saxpy_ saxpy #define dscal_ dscal #define sscal_ sscal #define dasum_ dasum #define sasum_ sasum #define ddot_ ddot #define sdot_ sdot #define dgemv_ dgemv #define sgemv_ sgemv #define dger_ dger #define sger_ sger #define dtrmv_ dtrmv #define strmv_ strmv #define dsyr_ dsyr #define ssyr_ ssyr #define dsymv_ dsymv #define ssymv_ ssymv #define dgemm_ dgemm #define sgemm_ sgemm #define dsyrk_ dsyrk #define ssyrk_ ssyrk #define dtrmm_ dtrmm #define strmm_ strmm #define dtrtri_ dtrtri #define strtri_ strtri #define idamax_ idamax #define isamax_ isamax #define dsytrf_ dsytrf #define ssytrf_ ssytrf #define dsytri_ dsytri #define ssytri_ ssytri #define dlasrt_ dlasrt #define slasrt_ slasrt #define dgesvd_ dgesvd #define sgesvd_ sgesvd #define dsyev_ dsyev #define ssyev_ ssyev #endif /// external functions #ifdef HAVE_MKL // obsolete extern "C" { #endif size_t cblas_idamin( int n, double* X, int incX); size_t cblas_isamin( int n, float* X, int incX); #ifdef HAVE_MKL }; #endif #ifdef HAVE_MKL extern "C" { void vdSqr( int n, double* vecIn, double* vecOut); void vsSqr( int n, float* vecIn, float* vecOut); void vdSqrt( int n, double* vecIn, double* vecOut); void vsSqrt( int n, float* vecIn, float* vecOut); void vdInvSqrt( int n, double* vecIn, double* vecOut); void vsInvSqrt( int n, float* vecIn, float* vecOut); void vdSub( int n, double* vecIn, double* vecIn2, double* vecOut); void vsSub( int n, float* vecIn, float* vecIn2, float* vecOut); void vdDiv( int n, double* vecIn, double* vecIn2, double* vecOut); void vsDiv( int n, float* vecIn, float* vecIn2, float* vecOut); void vdExp( int n, double* vecIn, double* vecOut); void vsExp( int n, float* vecIn, float* vecOut); void vdInv( int n, double* vecIn, double* vecOut); void vsInv( int n, float* vecIn, float* vecOut); void vdAdd( int n, double* vecIn, double* vecIn2, double* vecOut); void vsAdd( int n, float* vecIn, float* vecIn2, float* vecOut); void vdMul( int n, double* vecIn, double* vecIn2, double* vecOut); void vsMul( int n, float* vecIn, float* vecIn2, float* vecOut); void vdAbs( int n, double* vecIn, double* vecOut); void vsAbs( int n, float* vecIn, float* vecOut); } #endif // INTTerfaces to a few BLAS function, Level 1 /// INTTerface to cblas_*nrm2 template <typename T> T cblas_nrm2( INTT n, T* X, INTT incX); /// INTTerface to cblas_*copy template <typename T> void cblas_copy( INTT n, T* X, INTT incX, T* Y, INTT incY); /// INTTerface to cblas_*axpy template <typename T> void cblas_axpy( INTT n, T a, T* X, INTT incX, T* Y, INTT incY); /// INTTerface to cblas_*scal template <typename T> void cblas_scal( INTT n, T a, T* X, INTT incX); /// INTTerface to cblas_*asum template <typename T> T cblas_asum( INTT n, T* X, INTT incX); /// INTTerface to cblas_*adot template <typename T> T cblas_dot( INTT n, T* X, INTT incX, T* Y, INTT incY); /// interface to cblas_i*amin template <typename T> int cblas_iamin( INTT n, T* X, INTT incX); /// interface to cblas_i*amax template <typename T> int cblas_iamax( INTT n, T* X, INTT incX); // INTTerfaces to a few BLAS function, Level 2 /// INTTerface to cblas_*gemv template <typename T> void cblas_gemv( CBLAS_ORDER order, CBLAS_TRANSPOSE TransA, INTT M, INTT N, T alpha, T *A, INTT lda, T *X, INTT incX, T beta,T *Y, INTT incY); /// INTTerface to cblas_*trmv template <typename T> void inline cblas_trmv( CBLAS_ORDER order, CBLAS_UPLO Uplo, CBLAS_TRANSPOSE TransA, CBLAS_DIAG Diag, INTT N, T *A, INTT lda, T *X, INTT incX); /// INTTerface to cblas_*syr template <typename T> void inline cblas_syr( CBLAS_ORDER order, CBLAS_UPLO Uplo, INTT N, T alpha, T *X, INTT incX, T *A, INTT lda); /// INTTerface to cblas_*symv template <typename T> inline void cblas_symv( CBLAS_ORDER order, CBLAS_UPLO Uplo, INTT N, T alpha, T *A, INTT lda, T *X, INTT incX, T beta,T *Y, INTT incY); // INTTerfaces to a few BLAS function, Level 3 /// INTTerface to cblas_*gemm template <typename T> void cblas_gemm( CBLAS_ORDER order, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, INTT M, INTT N, INTT K, T alpha, T *A, INTT lda, T *B, INTT ldb, T beta, T *C, INTT ldc); /// INTTerface to cblas_*syrk template <typename T> void cblas_syrk( CBLAS_ORDER order, CBLAS_UPLO Uplo, CBLAS_TRANSPOSE Trans, INTT N, INTT K, T alpha, T *A, INTT lda, T beta, T*C, INTT ldc); /// INTTerface to cblas_*ger template <typename T> void cblas_ger( CBLAS_ORDER order, INTT M, INTT N, T alpha, T *X, INTT incX, T* Y, INTT incY, T*A, INTT lda); /// INTTerface to cblas_*trmm template <typename T> void cblas_trmm( CBLAS_ORDER order, CBLAS_SIDE Side, CBLAS_UPLO Uplo, CBLAS_TRANSPOSE TransA, CBLAS_DIAG Diag, INTT M, INTT N, T alpha, T*A, INTT lda,T *B, INTT ldb); // interfaces to a few functions from the intel Vector Mathematical Library /// interface to v*Sqr template <typename T> void vSqrt( int n, T* vecIn, T* vecOut); /// interface to v*Sqr template <typename T> void vInvSqrt( int n, T* vecIn, T* vecOut); /// interface to v*Sqr template <typename T> void vSqr( int n, T* vecIn, T* vecOut); /// interface to v*Sub template <typename T> void vSub( int n, T* vecIn, T* vecIn2, T* vecOut); /// interface to v*Div template <typename T> void vDiv( int n, T* vecIn, T* vecIn2, T* vecOut); /// interface to v*Exp template <typename T> void vExp( int n, T* vecIn, T* vecOut); /// interface to v*Inv template <typename T> void vInv( int n, T* vecIn, T* vecOut); /// interface to v*Add template <typename T> void vAdd( int n, T* vecIn, T* vecIn2, T* vecOut); /// interface to v*Mul template <typename T> void vMul( int n, T* vecIn, T* vecIn2, T* vecOut); /// interface to v*Abs template <typename T> void vAbs( int n, T* vecIn, T* vecOut); // interfaces to a few LAPACK functions /// interface to *trtri template <typename T> void trtri(char& uplo, char& diag, INTT n, T * a, INTT lda); /// interface to *sytri // call sytrf template <typename T> void sytri(char& uplo, INTT n, T* a, INTT lda); //, INTT* ipiv, // T* work); /// interaface to *lasrt template <typename T> void lasrt(char& id, INTT n, T *d); //template <typename T> void lasrt2(char& id, INTT& n, T *d, int* key); template <typename T> void gesvd( char& jobu, char& jobvt, INTT m, INTT n, T* a, INTT lda, T* s, T* u, INTT ldu, T* vt, INTT ldvt); template <typename T> void syev( char& jobz, char& uplo, INTT n, T* a, INTT lda, T* w); /* ****************** * Implementations * *****************/ extern "C" { double dnrm2_(INTT *n,double *x,INTT *incX); float snrm2_(INTT *n,float *x,INTT *incX); void dcopy_(INTT *n,double *x,INTT *incX, double *y,INTT *incY); void scopy_(INTT *n,float *x,INTT *incX, float *y,INTT *incY); void daxpy_(INTT *n,double* a, double *x,INTT *incX, double *y,INTT *incY); void saxpy_(INTT *n,float* a, float *x,INTT *incX, float *y,INTT *incY); void dscal_(INTT *n,double* a, double *x,INTT *incX); void sscal_(INTT *n,float* a, float *x,INTT *incX); double dasum_(INTT *n,double *x,INTT *incX); float sasum_(INTT *n,float *x,INTT *incX); double ddot_(INTT *n,double *x,INTT *incX, double *y,INTT *incY); float sdot_(INTT *n,float *x,INTT *incX, float *y,INTT *incY); void dgemv_(char *trans, INTT *m, INTT *n, double *alpha, double *a, INTT *lda, double *x, INTT *incx, double *beta, double *y,INTT *incy); void sgemv_(char *trans, INTT *m, INTT *n, float *alpha, float *a, INTT *lda, float *x, INTT *incx, float *beta, float *y,INTT *incy); void dger_(INTT *m, INTT *n, double *alpha, double *x, INTT *incx, double *y, INTT *incy, double *a, INTT *lda); void sger_(INTT *m, INTT *n, float *alpha, float *x, INTT *incx, float *y, INTT *incy, float *a, INTT *lda); void dtrmv_(char *uplo, char *trans, char *diag, INTT *n, double *a, INTT *lda, double *x, INTT *incx); void strmv_(char *uplo, char *trans, char *diag, INTT *n, float *a, INTT *lda, float *x, INTT *incx); void dsyr_(char *uplo, INTT *n, double *alpha, double *x, INTT *incx, double *a, INTT *lda); void ssyr_(char *uplo, INTT *n, float *alpha, float *x, INTT *incx, float *a, INTT *lda); void dsymv_(char *uplo, INTT *n, double *alpha, double *a, INTT *lda, double *x, INTT *incx, double *beta, double *y, INTT *incy); void ssymv_(char *uplo, INTT *n, float *alpha, float *a, INTT *lda, float *x, INTT *incx, float *beta, float *y, INTT *incy); void dgemm_(char *transa, char *transb, INTT *m, INTT *n, INTT *k, double *alpha, double *a, INTT *lda, double *b, INTT *ldb, double *beta, double *c, INTT *ldc); void sgemm_(char *transa, char *transb, INTT *m, INTT *n, INTT *k, float *alpha, float *a, INTT *lda, float *b, INTT *ldb, float *beta, float *c, INTT *ldc); void dsyrk_(char *uplo, char *trans, INTT *n, INTT *k, double *alpha, double *a, INTT *lda, double *beta, double *c, INTT *ldc); void ssyrk_(char *uplo, char *trans, INTT *n, INTT *k, float *alpha, float *a, INTT *lda, float *beta, float *c, INTT *ldc); void dtrmm_(char *side,char *uplo,char *transa, char *diag, INTT *m, INTT *n, double *alpha, double *a, INTT *lda, double *b, INTT *ldb); void strmm_(char *side,char *uplo,char *transa, char *diag, INTT *m, INTT *n, float *alpha, float *a, INTT *lda, float *b, INTT *ldb); INTT idamax_(INTT *n, double *dx, INTT *incx); INTT isamax_(INTT *n, float *dx, INTT *incx); void dtrtri_(char* uplo, char* diag, INTT* n, double * a, INTT* lda, INTT* info); void strtri_(char* uplo, char* diag, INTT* n, float * a, INTT* lda, INTT* info); void dsytrf_(char* uplo, INTT* n, double* a, INTT* lda, INTT* ipiv, double* work, INTT* lwork, INTT* info); void ssytrf_(char* uplo, INTT* n, float* a, INTT* lda, INTT* ipiv, float* work, INTT* lwork, INTT* info); void dsytri_(char* uplo, INTT* n, double* a, INTT* lda, INTT* ipiv, double* work, INTT* info); void ssytri_(char* uplo, INTT* n, float* a, INTT* lda, INTT* ipiv, float* work, INTT* info); void dlasrt_(char* id, INTT* n, double *d, INTT* info); void slasrt_(char* id, INTT* n, float*d, INTT* info); void dgesvd_(char*jobu, char *jobvt, INTT *m, INTT *n, double *a, INTT *lda, double *s, double *u, INTT *ldu, double *vt, INTT *ldvt, double *work, INTT *lwork, INTT *info); void sgesvd_(char*jobu, char *jobvt, INTT *m, INTT *n, float *a, INTT *lda, float *s, float *u, INTT *ldu, float *vt, INTT *ldvt, float *work, INTT *lwork, INTT *info); void dsyev_(char *jobz, char *uplo, INTT *n, double *a, INTT *lda, double *w, double *work, INTT *lwork, INTT *info); void ssyev_(char *jobz, char *uplo, INTT *n, float *a, INTT *lda, float *w, float *work, INTT *lwork, INTT *info); } // Implementations of the INTTerfaces, BLAS Level 1 /// Implementation of the INTTerface for cblas_dnrm2 template <> inline double cblas_nrm2<double>( INTT n, double* X, INTT incX) { //return cblas_dnrm2(n,X,incX); return dnrm2_(&n,X,&incX); }; /// Implementation of the INTTerface for cblas_snrm2 template <> inline float cblas_nrm2<float>( INTT n, float* X, INTT incX) { //return cblas_snrm2(n,X,incX); return snrm2_(&n,X,&incX); }; /// Implementation of the INTTerface for cblas_dcopy template <> inline void cblas_copy<double>( INTT n, double* X, INTT incX, double* Y, INTT incY) { //cblas_dcopy(n,X,incX,Y,incY); dcopy_(&n,X,&incX,Y,&incY); }; /// Implementation of the INTTerface for cblas_scopy template <> inline void cblas_copy<float>( INTT n, float* X, INTT incX, float* Y, INTT incY) { //cblas_scopy(n,X,incX,Y,incY); scopy_(&n,X,&incX,Y,&incY); }; /// Implementation of the INTTerface for cblas_scopy template <> inline void cblas_copy<int>( INTT n, int* X, INTT incX, int* Y, INTT incY) { for (int i = 0; i<n; ++i) Y[incY*i]=X[incX*i]; }; /// Implementation of the INTTerface for cblas_scopy template <> inline void cblas_copy<bool>( INTT n, bool* X, INTT incX, bool* Y, INTT incY) { for (int i = 0; i<n; ++i) Y[incY*i]=X[incX*i]; }; /// Implementation of the INTTerface for cblas_daxpy template <> inline void cblas_axpy<double>( INTT n, double a, double* X, INTT incX, double* Y, INTT incY) { //cblas_daxpy(n,a,X,incX,Y,incY); daxpy_(&n,&a,X,&incX,Y,&incY); }; /// Implementation of the INTTerface for cblas_saxpy template <> inline void cblas_axpy<float>( INTT n, float a, float* X, INTT incX, float* Y, INTT incY) { //cblas_saxpy(n,a,X,incX,Y,incY); saxpy_(&n,&a,X,&incX,Y,&incY); }; /// Implementation of the INTTerface for cblas_saxpy template <> inline void cblas_axpy<int>( INTT n, int a, int* X, INTT incX, int* Y, INTT incY) { for (int i = 0; i<n; ++i) Y[i] += a*X[i]; }; /// Implementation of the INTTerface for cblas_saxpy template <> inline void cblas_axpy<bool>( INTT n, bool a, bool* X, INTT incX, bool* Y, INTT incY) { for (int i = 0; i<n; ++i) Y[i] = a*X[i]; }; /// Implementation of the INTTerface for cblas_dscal template <> inline void cblas_scal<double>( INTT n, double a, double* X, INTT incX) { //cblas_dscal(n,a,X,incX); dscal_(&n,&a,X,&incX); }; /// Implementation of the INTTerface for cblas_sscal template <> inline void cblas_scal<float>( INTT n, float a, float* X, INTT incX) { //cblas_sscal(n,a,X,incX); sscal_(&n,&a,X,&incX); }; /// Implementation of the INTTerface for cblas_sscal template <> inline void cblas_scal<int>( INTT n, int a, int* X, INTT incX) { for (int i = 0; i<n; ++i) X[i*incX]*=a; }; /// Implementation of the INTTerface for cblas_sscal template <> inline void cblas_scal<bool>( INTT n, bool a, bool* X, INTT incX) { /// not implemented }; /// Implementation of the INTTerface for cblas_dasum template <> inline double cblas_asum<double>( INTT n, double* X, INTT incX) { //return cblas_dasum(n,X,1); return dasum_(&n,X,&incX); }; /// Implementation of the INTTerface for cblas_sasum template <> inline float cblas_asum<float>( INTT n, float* X, INTT incX) { //return cblas_sasum(n,X,1); return sasum_(&n,X,&incX); }; /// Implementation of the INTTerface for cblas_ddot template <> inline double cblas_dot<double>( INTT n, double* X, INTT incX, double* Y, INTT incY) { //return cblas_ddot(n,X,incX,Y,incY); return ddot_(&n,X,&incX,Y,&incY); }; /// Implementation of the INTTerface for cblas_sdot template <> inline float cblas_dot<float>( INTT n, float* X, INTT incX, float* Y, INTT incY) { //return cblas_sdot(n,X,incX,Y,incY); return sdot_(&n,X,&incX,Y,&incY); }; template <> inline int cblas_dot<int>( INTT n, int* X, INTT incX, int* Y, INTT incY) { int total=0; int i,j; j=0; for (i = 0; i<n; ++i) { total+=X[i*incX]*Y[j]; //j+=incY; j+=(int)incY; } return total; }; /// Implementation of the INTTerface for cblas_sdot template <> inline bool cblas_dot<bool>( INTT n, bool* X, INTT incX, bool* Y, INTT incY) { /// not implemented return true; }; // Implementations of the INTTerfaces, BLAS Level 2 /// Implementation of the INTTerface for cblas_dgemv template <> inline void cblas_gemv<double>( CBLAS_ORDER order, CBLAS_TRANSPOSE TransA, INTT M, INTT N, double alpha, double *A, INTT lda, double *X, INTT incX, double beta, double *Y, INTT incY) { //cblas_dgemv(order,TransA,M,N,alpha,A,lda,X,incX,beta,Y,incY); dgemv_(cblas_transpose(TransA),&M,&N,&alpha,A,&lda,X,&incX,&beta,Y,&incY); }; /// Implementation of the INTTerface for cblas_sgemv template <> inline void cblas_gemv<float>( CBLAS_ORDER order, CBLAS_TRANSPOSE TransA, INTT M, INTT N, float alpha, float *A, INTT lda, float *X, INTT incX, float beta, float *Y, INTT incY) { //cblas_sgemv(order,TransA,M,N,alpha,A,lda,X,incX,beta,Y,incY); sgemv_(cblas_transpose(TransA),&M,&N,&alpha,A,&lda,X,&incX,&beta,Y,&incY); }; /// Implementation of the INTTerface for cblas_sgemv template <> inline void cblas_gemv<int>( CBLAS_ORDER order, CBLAS_TRANSPOSE TransA, INTT M, INTT N, int alpha, int *A, INTT lda, int *X, INTT incX, int beta, int *Y, INTT incY) { /// not implemented }; /// Implementation of the INTTerface for cblas_sgemv template <> inline void cblas_gemv<bool>( CBLAS_ORDER order, CBLAS_TRANSPOSE TransA, INTT M, INTT N, bool alpha, bool *A, INTT lda, bool *X, INTT incX, bool beta, bool *Y, INTT incY) { /// not implemented }; /// Implementation of the INTTerface for cblas_dger template <> inline void cblas_ger<double>( CBLAS_ORDER order, INTT M, INTT N, double alpha, double *X, INTT incX, double* Y, INTT incY, double *A, INTT lda) { //cblas_dger(order,M,N,alpha,X,incX,Y,incY,A,lda); dger_(&M,&N,&alpha,X,&incX,Y,&incY,A,&lda); }; /// Implementation of the INTTerface for cblas_sger template <> inline void cblas_ger<float>( CBLAS_ORDER order, INTT M, INTT N, float alpha, float *X, INTT incX, float* Y, INTT incY, float *A, INTT lda) { //cblas_sger(order,M,N,alpha,X,incX,Y,incY,A,lda); sger_(&M,&N,&alpha,X,&incX,Y,&incY,A,&lda); }; /// Implementation of the INTTerface for cblas_dtrmv template <> inline void cblas_trmv<double>( CBLAS_ORDER order, CBLAS_UPLO Uplo, CBLAS_TRANSPOSE TransA, CBLAS_DIAG Diag, INTT N, double *A, INTT lda, double *X, INTT incX) { //cblas_dtrmv(order,Uplo,TransA,Diag,N,A,lda,X,incX); dtrmv_(cblas_uplo(Uplo),cblas_transpose(TransA),cblas_diag(Diag),&N,A,&lda,X,&incX); }; /// Implementation of the INTTerface for cblas_strmv template <> inline void cblas_trmv<float>( CBLAS_ORDER order, CBLAS_UPLO Uplo, CBLAS_TRANSPOSE TransA, CBLAS_DIAG Diag, INTT N, float *A, INTT lda, float *X, INTT incX) { //cblas_strmv(order,Uplo,TransA,Diag,N,A,lda,X,incX); strmv_(cblas_uplo(Uplo),cblas_transpose(TransA),cblas_diag(Diag),&N,A,&lda,X,&incX); }; /// Implementation of cblas_dsyr template <> inline void cblas_syr( CBLAS_ORDER order, CBLAS_UPLO Uplo, INTT N, double alpha, double*X, INTT incX, double *A, INTT lda) { //cblas_dsyr(order,Uplo,N,alpha,X,incX,A,lda); dsyr_(cblas_uplo(Uplo),&N,&alpha,X,&incX,A,&lda); }; /// Implementation of cblas_ssyr template <> inline void cblas_syr( CBLAS_ORDER order, CBLAS_UPLO Uplo, INTT N, float alpha, float*X, INTT incX, float *A, INTT lda) { //cblas_ssyr(order,Uplo,N,alpha,X,incX,A,lda); ssyr_(cblas_uplo(Uplo),&N,&alpha,X,&incX,A,&lda); }; /// Implementation of cblas_ssymv template <> inline void cblas_symv( CBLAS_ORDER order, CBLAS_UPLO Uplo, INTT N, float alpha, float *A, INTT lda, float *X, INTT incX, float beta,float *Y, INTT incY) { //cblas_ssymv(order,Uplo,N,alpha,A,lda,X,incX,beta,Y,incY); ssymv_(cblas_uplo(Uplo),&N,&alpha,A,&lda,X,&incX,&beta,Y,&incY); } /// Implementation of cblas_dsymv template <> inline void cblas_symv( CBLAS_ORDER order, CBLAS_UPLO Uplo, INTT N, double alpha, double *A, INTT lda, double *X, INTT incX, double beta,double *Y, INTT incY) { //cblas_dsymv(order,Uplo,N,alpha,A,lda,X,incX,beta,Y,incY); dsymv_(cblas_uplo(Uplo),&N,&alpha,A,&lda,X,&incX,&beta,Y,&incY); } // Implementations of the INTTerfaces, BLAS Level 3 /// Implementation of the INTTerface for cblas_dgemm template <> inline void cblas_gemm<double>( CBLAS_ORDER order, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, INTT M, INTT N, INTT K, double alpha, double *A, INTT lda, double *B, INTT ldb, double beta, double *C, INTT ldc) { //cblas_dgemm(Order,TransA,TransB,M,N,K,alpha,A,lda,B,ldb,beta,C,ldc); dgemm_(cblas_transpose(TransA),cblas_transpose(TransB),&M,&N,&K,&alpha,A,&lda,B,&ldb,&beta,C,&ldc); }; /// Implementation of the INTTerface for cblas_sgemm template <> inline void cblas_gemm<float>( CBLAS_ORDER order, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, INTT M, INTT N, INTT K, float alpha, float *A, INTT lda, float *B, INTT ldb, float beta, float *C, INTT ldc) { //cblas_sgemm(Order,TransA,TransB,M,N,K,alpha,A,lda,B,ldb,beta,C,ldc); sgemm_(cblas_transpose(TransA),cblas_transpose(TransB),&M,&N,&K,&alpha,A,&lda,B,&ldb,&beta,C,&ldc); }; template <> inline void cblas_gemm<int>( CBLAS_ORDER order, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, INTT M, INTT N, INTT K, int alpha, int *A, INTT lda, int *B, INTT ldb, int beta, int *C, INTT ldc) { /// not implemented }; /// Implementation of the INTTerface for cblas_sgemm template <> inline void cblas_gemm<bool>( CBLAS_ORDER order, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, INTT M, INTT N, INTT K, bool alpha, bool *A, INTT lda, bool *B, INTT ldb, bool beta, bool *C, INTT ldc) { /// not implemented }; /// Implementation of the INTTerface for cblas_dsyrk template <> inline void cblas_syrk<double>( CBLAS_ORDER order, CBLAS_UPLO Uplo, CBLAS_TRANSPOSE Trans, INTT N, INTT K, double alpha, double *A, INTT lda, double beta, double *C, INTT ldc) { //cblas_dsyrk(Order,Uplo,Trans,N,K,alpha,A,lda,beta,C,ldc); dsyrk_(cblas_uplo(Uplo),cblas_transpose(Trans),&N,&K,&alpha,A,&lda,&beta,C,&ldc); }; /// Implementation of the INTTerface for cblas_ssyrk template <> inline void cblas_syrk<float>( CBLAS_ORDER order, CBLAS_UPLO Uplo, CBLAS_TRANSPOSE Trans, INTT N, INTT K, float alpha, float *A, INTT lda, float beta, float *C, INTT ldc) { //cblas_ssyrk(Order,Uplo,Trans,N,K,alpha,A,lda,beta,C,ldc); ssyrk_(cblas_uplo(Uplo),cblas_transpose(Trans),&N,&K,&alpha,A,&lda,&beta,C,&ldc); }; /// Implementation of the INTTerface for cblas_ssyrk template <> inline void cblas_syrk<int>( CBLAS_ORDER order, CBLAS_UPLO Uplo, CBLAS_TRANSPOSE Trans, INTT N, INTT K, int alpha, int *A, INTT lda, int beta, int *C, INTT ldc) { /// not implemented }; /// Implementation of the INTTerface for cblas_ssyrk template <> inline void cblas_syrk<bool>( CBLAS_ORDER order, CBLAS_UPLO Uplo, CBLAS_TRANSPOSE Trans, INTT N, INTT K, bool alpha, bool *A, INTT lda, bool beta, bool *C, INTT ldc) { /// not implemented }; /// Implementation of the INTTerface for cblas_dtrmm template <> inline void cblas_trmm<double>( CBLAS_ORDER order, CBLAS_SIDE Side, CBLAS_UPLO Uplo, CBLAS_TRANSPOSE TransA, CBLAS_DIAG Diag, INTT M, INTT N, double alpha, double *A, INTT lda,double *B, INTT ldb) { //cblas_dtrmm(Order,Side,Uplo,TransA,Diag,M,N,alpha,A,lda,B,ldb); dtrmm_(cblas_side(Side),cblas_uplo(Uplo),cblas_transpose(TransA),cblas_diag(Diag),&M,&N,&alpha,A,&lda,B,&ldb); }; /// Implementation of the INTTerface for cblas_strmm template <> inline void cblas_trmm<float>( CBLAS_ORDER order, CBLAS_SIDE Side, CBLAS_UPLO Uplo, CBLAS_TRANSPOSE TransA, CBLAS_DIAG Diag, INTT M, INTT N, float alpha, float *A, INTT lda,float *B, INTT ldb) { //cblas_strmm(Order,Side,Uplo,TransA,Diag,M,N,alpha,A,lda,B,ldb); strmm_(cblas_side(Side),cblas_uplo(Uplo),cblas_transpose(TransA),cblas_diag(Diag),&M,&N,&alpha,A,&lda,B,&ldb); }; /// Implementation of the interface for cblas_idamax template <> inline int cblas_iamax<double>( INTT n, double* X, INTT incX) { //return cblas_idamax(n,X,incX); return static_cast<int>(idamax_(&n,X,&incX)-1); }; /// Implementation of the interface for cblas_isamax template <> inline int cblas_iamax<float>( INTT n, float* X, INTT incX) { //return cblas_isamax(n,X,incX); return static_cast<int>(isamax_(&n,X,&incX)-1); }; // Implementations of the interfaces, LAPACK /// Implemenation of the interface for dtrtri template <> inline void trtri<double>(char& uplo, char& diag, INTT n, double * a, INTT lda) { //dtrtri_(&uplo,&diag,&n,a,&lda,&info); dtrtri_(&uplo,&diag,&n,a,&lda,&info); }; /// Implemenation of the interface for strtri template <> inline void trtri<float>(char& uplo, char& diag, INTT n, float* a, INTT lda) { //strtri_(&uplo,&diag,&n,a,&lda,&info); strtri_(&uplo,&diag,&n,a,&lda,&info); }; /// Implemenation of the interface for dsytri template <> inline void sytri<double>(char& uplo, INTT n, double* a, INTT lda) { //, INTT* ipiv, double* work) { //dsytri_(&uplo,&n,a,&lda,ipiv,work,&info); INTT lwork=-1; INTT* ipiv= new INTT[n]; double* query, *work; query = new double[1]; dsytrf_(&uplo,&n,a,&lda,ipiv,query,&lwork,&info); lwork=static_cast<INTT>(*query); delete[](query); work = new double[static_cast<int>(lwork)]; dsytrf_(&uplo,&n,a,&lda,ipiv,work,&lwork,&info); delete[](work); work = new double[static_cast<int>(2*n)]; dsytri_(&uplo,&n,a,&lda,ipiv,work,&info); delete[](work); delete[](ipiv); }; /// Implemenation of the interface for ssytri template <> inline void sytri<float>(char& uplo, INTT n, float* a, INTT lda) { INTT lwork=-1; INTT* ipiv= new INTT[n]; float* query, *work; query = new float[1]; ssytrf_(&uplo,&n,a,&lda,ipiv,query,&lwork,&info); lwork=static_cast<INTT>(*query); delete[](query); work = new float[static_cast<int>(lwork)]; ssytrf_(&uplo,&n,a,&lda,ipiv,work,&lwork,&info); delete[](work); work = new float[static_cast<int>(2*n)]; ssytri_(&uplo,&n,a,&lda,ipiv,work,&info); delete[](work); delete[](ipiv); }; /// interaface to *lasrt template <> inline void lasrt(char& id, INTT n, double *d) { //dlasrt_(&id,const_cast<int*>(&n),d,&info); dlasrt_(&id,&n,d,&info); }; /// interaface to *lasrt template <> inline void lasrt(char& id, INTT n, float *d) { //slasrt_(&id,const_cast<int*>(&n),d,&info); slasrt_(&id,&n,d,&info); }; //template <> inline void lasrt2(char& id, INTT& n, double *d,int* key) { // //dlasrt2_(&id,const_cast<int*>(&n),d,key,&info); // dlasrt2(&id,&n,d,key,&info); //}; ///// interaface to *lasrt //template <> inline void lasrt2(char& id, INTT& n, float *d, int* key) { // //slasrt2_(&id,const_cast<int*>(&n),d,key,&info); // slasrt2(&id,&n,d,key,&info); //}; template <> void inline gesvd( char& jobu, char& jobvt, INTT m, INTT n, double* a, INTT lda, double* s, double* u, INTT ldu, double* vt, INTT ldvt) { double* query = new double[1]; INTT lwork=-1; dgesvd_(&jobu, &jobvt, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, query, &lwork, &info ); lwork=static_cast<INTT>(*query); delete[](query); double* work = new double[static_cast<int>(lwork)]; dgesvd_(&jobu, &jobvt, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork, &info ); delete[](work); } template <> void inline gesvd( char& jobu, char& jobvt, INTT m, INTT n, float* a, INTT lda, float* s, float* u, INTT ldu, float* vt, INTT ldvt) { float* query = new float[1]; INTT lwork=-1; sgesvd_(&jobu, &jobvt, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, query, &lwork, &info ); lwork=static_cast<INTT>(*query); delete[](query); float* work = new float[static_cast<int>(lwork)]; sgesvd_(&jobu, &jobvt, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork, &info ); delete[](work); } template <> void inline syev( char& jobz, char& uplo, INTT n, float* a, INTT lda, float* w) { float* query = new float[1]; INTT lwork=-1; ssyev_(&jobz,&uplo,&n,a,&lda,w,query,&lwork,&info); lwork=static_cast<INTT>(*query); delete[](query); float* work = new float[static_cast<int>(lwork)]; ssyev_(&jobz,&uplo,&n,a,&lda,w,work,&lwork,&info); delete[](work); }; template <> void inline syev( char& jobz, char& uplo, INTT n, double* a, INTT lda, double* w) { double* query = new double[1]; INTT lwork=-1; dsyev_(&jobz,&uplo,&n,a,&lda,w,query,&lwork,&info); lwork=static_cast<INTT>(*query); delete[](query); double* work = new double[static_cast<int>(lwork)]; dsyev_(&jobz,&uplo,&n,a,&lda,w,work,&lwork,&info); delete[](work); }; /// If the MKL is not present, a slow implementation is used instead. #ifdef HAVE_MKL /// Implemenation of the interface for vdSqr template <> inline void vSqr<double>( int n, double* vecIn, double* vecOut) { vdSqr(n,vecIn,vecOut); }; /// Implemenation of the interface for vsSqr template <> inline void vSqr<float>( int n, float* vecIn, float* vecOut) { vsSqr(n,vecIn,vecOut); }; template <> inline void vSqrt<double>( int n, double* vecIn, double* vecOut) { vdSqrt(n,vecIn,vecOut); }; /// Implemenation of the interface for vsSqr template <> inline void vSqrt<float>( int n, float* vecIn, float* vecOut) { vsSqrt(n,vecIn,vecOut); }; template <> inline void vInvSqrt<double>( int n, double* vecIn, double* vecOut) { vdInvSqrt(n,vecIn,vecOut); }; /// Implemenation of the interface for vsSqr template <> inline void vInvSqrt<float>( int n, float* vecIn, float* vecOut) { vsInvSqrt(n,vecIn,vecOut); }; /// Implemenation of the interface for vdSub template <> inline void vSub<double>( int n, double* vecIn, double* vecIn2, double* vecOut) { vdSub(n,vecIn,vecIn2,vecOut); }; /// Implemenation of the interface for vsSub template <> inline void vSub<float>( int n, float* vecIn, float* vecIn2, float* vecOut) { vsSub(n,vecIn,vecIn2,vecOut); }; /// Implemenation of the interface for vdDiv template <> inline void vDiv<double>( int n, double* vecIn, double* vecIn2, double* vecOut) { vdDiv(n,vecIn,vecIn2,vecOut); }; /// Implemenation of the interface for vsDiv template <> inline void vDiv<float>( int n, float* vecIn, float* vecIn2, float* vecOut) { vsDiv(n,vecIn,vecIn2,vecOut); }; /// Implemenation of the interface for vdExp template <> inline void vExp<double>( int n, double* vecIn, double* vecOut) { vdExp(n,vecIn,vecOut); }; /// Implemenation of the interface for vsExp template <> inline void vExp<float>( int n, float* vecIn, float* vecOut) { vsExp(n,vecIn,vecOut); }; /// Implemenation of the interface for vdInv template <> inline void vInv<double>( int n, double* vecIn, double* vecOut) { vdInv(n,vecIn,vecOut); }; /// Implemenation of the interface for vsInv template <> inline void vInv<float>( int n, float* vecIn, float* vecOut) { vsInv(n,vecIn,vecOut); }; /// Implemenation of the interface for vdAdd template <> inline void vAdd<double>( int n, double* vecIn, double* vecIn2, double* vecOut) { vdAdd(n,vecIn,vecIn2,vecOut); }; /// Implemenation of the interface for vsAdd template <> inline void vAdd<float>( int n, float* vecIn, float* vecIn2, float* vecOut) { vsAdd(n,vecIn,vecIn2,vecOut); }; /// Implemenation of the interface for vdMul template <> inline void vMul<double>( int n, double* vecIn, double* vecIn2, double* vecOut) { vdMul(n,vecIn,vecIn2,vecOut); }; /// Implemenation of the interface for vsMul template <> inline void vMul<float>( int n, float* vecIn, float* vecIn2, float* vecOut) { vsMul(n,vecIn,vecIn2,vecOut); }; /// interface to vdAbs template <> inline void vAbs( int n, double* vecIn, double* vecOut) { vdAbs(n,vecIn,vecOut); }; /// interface to vdAbs template <> inline void vAbs( int n, float* vecIn, float* vecOut) { vsAbs(n,vecIn,vecOut); }; /// implemenation of the interface of the non-offical blas, level 1 function /// cblas_idamin template <> inline int cblas_iamin<double>( int n, double* x, int incx) { return (int) cblas_idamin(n,x,incx); }; /// implemenation of the interface of the non-offical blas, level 1 function /// cblas_isamin template <> inline int cblas_iamin<float>( int n, float* x, int incx) { return (int) cblas_isamin(n,x,incx); }; /// slow alternative implementation of some MKL function #else /// Slow implementation of vdSqr and vsSqr template <typename T> inline void vSqr( int n, T* vecIn, T* vecOut) { for (int i = 0; i<n; ++i) vecOut[i]=vecIn[i]*vecIn[i]; }; template <typename T> inline void vSqrt( int n, T* vecIn, T* vecOut) { for (int i = 0; i<n; ++i) vecOut[i]=sqr<T>(vecIn[i]); }; template <typename T> inline void vInvSqrt( int n, T* vecIn, T* vecOut) { for (int i = 0; i<n; ++i) vecOut[i]=T(1.0)/sqr<T>(vecIn[i]); }; /// Slow implementation of vdSub and vsSub template <typename T> inline void vSub( int n, T* vecIn1, T* vecIn2, T* vecOut) { for (int i = 0; i<n; ++i) vecOut[i]=vecIn1[i]-vecIn2[i]; }; /// Slow implementation of vdInv and vsInv template <typename T> inline void vInv( int n, T* vecIn, T* vecOut) { for (int i = 0; i<n; ++i) vecOut[i]=1.0/vecIn[i]; }; /// Slow implementation of vdExp and vsExp template <typename T> inline void vExp( int n, T* vecIn, T* vecOut) { for (int i = 0; i<n; ++i) vecOut[i]=exp(vecIn[i]); }; /// Slow implementation of vdAdd and vsAdd template <typename T> inline void vAdd( int n, T* vecIn1, T* vecIn2, T* vecOut) { for (int i = 0; i<n; ++i) vecOut[i]=vecIn1[i]+vecIn2[i]; }; /// Slow implementation of vdMul and vsMul template <typename T> inline void vMul( int n, T* vecIn1, T* vecIn2, T* vecOut) { for (int i = 0; i<n; ++i) vecOut[i]=vecIn1[i]*vecIn2[i]; }; /// Slow implementation of vdDiv and vsDiv template <typename T> inline void vDiv( int n, T* vecIn1, T* vecIn2, T* vecOut) { for (int i = 0; i<n; ++i) vecOut[i]=vecIn1[i]/vecIn2[i]; }; /// Slow implementation of vAbs template <typename T> inline void vAbs( int n, T* vecIn, T* vecOut) { for (int i = 0; i<n; ++i) vecOut[i]=abs<T>(vecIn[i]); }; /// Slow implementation of cblas_idamin and cblas_isamin template <typename T> int inline cblas_iamin(INTT n, T* X, INTT incX) { int imin=0; double min=fabs(X[0]); for (int j = 1; j<n; j+=incX) { double cur = fabs(X[j]); if (cur < min) { imin=j; min = cur; } } return imin; } #endif #endif
{ "alphanum_fraction": 0.6449932034, "avg_line_length": 37.9291084855, "ext": "h", "hexsha": "e1e6c58f8b5e0c94296bfd104f99cbb2f357e152", "lang": "C", "max_forks_count": 77, "max_forks_repo_forks_event_max_datetime": "2022-02-18T08:37:05.000Z", "max_forks_repo_forks_event_min_datetime": "2017-12-18T01:35:18.000Z", "max_forks_repo_head_hexsha": "d09fa9c57213464f94e37cb3b202dddc6f0b0267", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "XuJiaMing1997/person-reid-benchmark", "max_forks_repo_path": "util/ISR/spams-matlab/linalg/cblas_alt_template.h", "max_issues_count": 13, "max_issues_repo_head_hexsha": "d09fa9c57213464f94e37cb3b202dddc6f0b0267", "max_issues_repo_issues_event_max_datetime": "2020-04-17T17:33:27.000Z", "max_issues_repo_issues_event_min_datetime": "2017-12-18T12:54:20.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "XuJiaMing1997/person-reid-benchmark", "max_issues_repo_path": "util/ISR/spams-matlab/linalg/cblas_alt_template.h", "max_line_length": 113, "max_stars_count": 202, "max_stars_repo_head_hexsha": "d09fa9c57213464f94e37cb3b202dddc6f0b0267", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ChrystleMyrnaLobo/person-reid-benchmark", "max_stars_repo_path": "util/ISR/spams-matlab/linalg/cblas_alt_template.h", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:32:17.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-08T21:23:53.000Z", "num_tokens": 12637, "size": 35312 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "Data\Pose.h" #include "Data\Data.h" #include <gsl\gsl> namespace mage { /** * Converts the contents of a CVMat into the mage::Matrix data container by copying the values */ Matrix ToMageMat(const cv::Matx34f& cvMat); Matrix ToMageMat(const cv::Matx44f& cvMat); Position ToMagePos(const cv::Point3f& cvPt); Direction ToMageDir(const cv::Point3f& cvDir); cv::Vec3f FromMageDir(const Direction& mageDir); Matrix ToMageMat(const std::array<float, 4 * 4>& f); Direction ToMageDir(const std::array<float, 3>& dir); mage::Pose MageMatrixToMagePose(const mage::Matrix& viewMatrix); void ConvertBGRToNV12(const cv::Mat& srcImg, gsl::span<uint8_t> destBuffer); bool IsIdentity(const Matrix& m); inline mage::Matrix CreateIdentityMageMatrix() { return{ 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; }; // Interpolates values between min and max to the range defined from a to b, // [a:b] can be either an increasing or decreasing range, min is always mapped to a, and max to b. unsigned char LinearInterpolationToChar(float value, float min, float max, unsigned char a, unsigned char b); // Construct external normal (z positive) from the X,Y components of the internal normal (z negative). // Synthetic normals are facing the camera (external), // generated normals are not (internal), this function is used to make the conversion, // by changing the sign of the coordinates. cv::Vec3f ConstructExternalNormalFromXY(float normalX, float normalY); }
{ "alphanum_fraction": 0.6790617849, "avg_line_length": 34.2745098039, "ext": "h", "hexsha": "77b05f893debf6c552897668d506c3e54cffa817", "lang": "C", "max_forks_count": 16, "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_path": "Core/MAGESLAM/Source/Utils/MageConversions.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_path": "Core/MAGESLAM/Source/Utils/MageConversions.h", "max_line_length": 113, "max_stars_count": 70, "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_path": "Core/MAGESLAM/Source/Utils/MageConversions.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "num_tokens": 502, "size": 1748 }
// // particle.h // EpiGenMCMC // // Created by Lucy Li on 13/04/2016. // Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved. // #ifndef __EpiGenMCMC__particle__ #define __EpiGenMCMC__particle__ #include <vector> #include <gsl/gsl_randist.h> #include "trajectory.h" class Particle { int num_particles; int num_groups; int num_time_steps; std::vector <Trajectory*> trajectories; std::vector <double> weights; std::vector <double> normalised_weights; std::vector <unsigned int> next_particles; std::vector <int> parents; std::vector <double> overall_traj; // Incidence: P1[Group1[T1, T2...], Group2[T1, T2...]...], P2[] ... std::vector <double> overall_traj2; // Prevalence: P1[Group1[T1, T2...], Group2[T1, T2...]...], P2[] ... std::vector <int> particle_ancestry; std::vector <int> non_zero_particles; std::vector <double> cumulative_weights; std::vector <int> empty; void replace(int, int); void normalise(); public: Particle(); Particle(int, Trajectory); void start_particle_tracing(int, int); void save_traj_to_matrix(int, int); void save_traj_to_matrix(int, int, int); void save_ancestry(int, int); void save_ancestry(int, int, int); void reset_parents(); int get_traj_random(gsl_rng *); void retrace_traj(Trajectory&, gsl_rng *); Trajectory* get_traj(int) const; void set_weight(double, int, bool); double get_weight(int); double get_total_weight(); double get_ESS(); void reset_weights(); void resample(gsl_rng *); void clear(); }; #endif /* defined(__EpiGenMCMC__particle__) */
{ "alphanum_fraction": 0.6743341404, "avg_line_length": 29.5, "ext": "h", "hexsha": "0bed6e03b773ad1d35a9e7b22bd879bf92d13bef", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-16T22:17:38.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-13T16:20:40.000Z", "max_forks_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lucymli/EpiGenMCMC", "max_forks_repo_path": "src/particle.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_issues_repo_issues_event_max_datetime": "2021-01-15T04:48:15.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-05T05:49:07.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lucymli/EpiGenMCMC", "max_issues_repo_path": "src/particle.h", "max_line_length": 108, "max_stars_count": 3, "max_stars_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lucymli/EpiGenMCMC", "max_stars_repo_path": "src/particle.h", "max_stars_repo_stars_event_max_datetime": "2020-04-09T16:14:41.000Z", "max_stars_repo_stars_event_min_datetime": "2018-04-01T09:55:40.000Z", "num_tokens": 460, "size": 1652 }
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <mpfr.h> #include <petsc.h> #include "../ellipsoid/ellipsoid.h" #include "../ellipsoid/ellSolv.h" #include "../constants.h" #include "testFunctions.h" #include "../tanhsinh.h" /* EX3 - PLOTS CONVERGENCE OF A SINGLE NORMALIZATION CONSTANT normConv.py PLOTS RESULT */ #undef __FUNCT__ #define __FUNCT__ "NormConstantIntFixed" PetscErrorCode NormConstantIntFixed(EllipsoidalSystem *e, PetscInt n, PetscInt p, PetscInt prec, PetscInt nPts, PetscReal *intVals, PetscReal *normConst) { PetscErrorCode ierr; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; FuncInfo2 ctx1 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = 1 }; FuncInfo2 ctx2 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = 1 }; FuncInfo2 ctx3 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = -1 }; FuncInfo2 ctx4 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = -1 }; PetscReal integrals[4]; mpfr_t mpfrzero; mpfr_t mpfrone; mpfr_inits(mpfrzero, mpfrone, NULL); mpfr_set_d(mpfrzero, 0.0, MPFR_RNDN); mpfr_set_d(mpfrone, 1.0, MPFR_RNDN); ierr = DEQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e->hp_h, e->hp_k, prec, nPts, integrals+0, &ctx1); intVals[0] = integrals[0]; ierr = DEQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e->hp_h, e->hp_k, prec, nPts, integrals+1, &ctx2); intVals[1] = integrals[1]; ierr = DEQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, mpfrzero, e->hp_h, prec, nPts, integrals+2, &ctx3); intVals[2] = integrals[2]; ierr = DEQuad((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, mpfrzero, e->hp_h, prec, nPts, integrals+3, &ctx4); intVals[3] = integrals[3]; *normConst = 8.0*(integrals[2]*integrals[1] - integrals[0]*integrals[3]); flopCount += 4; mpfr_clears(mpfrzero, mpfrone, NULL); ierr = PetscLogFlops(flopCount);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT_ "normConvergence" PetscErrorCode normConvergence(PetscInt n, PetscInt p) { PetscErrorCode ierr; const PetscInt MPFR_PREC = 64; const PetscInt NUM_SOLUTIONS = 80; const PetscInt POINTS_MIN = 4; const PetscInt POINTS_STEP = 2; const PetscInt prec = 16; const PetscReal a = 3.0; const PetscReal b = 2.0; const PetscReal c = 1.0; mpfr_t solExact; mpfr_t intExact[4]; PetscReal solutions[NUM_SOLUTIONS]; mpfr_t errors [NUM_SOLUTIONS]; PetscReal intSols[4*NUM_SOLUTIONS]; mpfr_t intErrors[4*NUM_SOLUTIONS]; PetscReal sol2, sol3, sol4; PetscLogEvent flopCounts[NUM_SOLUTIONS]; EllipsoidalSystem e; PetscInt i; PetscEventPerfInfo info; //PetscInt n = 7; //PeatscInt p = 4; PetscFunctionBegin; mpfr_set_default_prec(4*MPFR_PREC); initEllipsoidalSystem(&e, a, b, c, MPFR_PREC); mpfr_init(solExact); for(PetscInt k=0; k < 4; ++k) mpfr_init(intExact[k]); for(PetscInt k=0; k < NUM_SOLUTIONS; ++k ) mpfr_init(errors[k]); for(PetscInt k=0; k < 4*NUM_SOLUTIONS; ++k) mpfr_init(intErrors[k]); /* calculate "exact" solution */ ierr = calcNormalization2MPFR(&e, n, p, intExact, &solExact);CHKERRQ(ierr); printf("old norm constant: %15.15f\n", solExact); /* calculate approximate solutions and record flops */ char text[40] = "%d points"; char sText[40]; for(i=0; i<NUM_SOLUTIONS; ++i) { sprintf(sText, text, POINTS_MIN + POINTS_STEP*i); ierr = PetscLogEventRegister(sText, 0, flopCounts+i);CHKERRQ(ierr); ierr = PetscLogEventBegin(flopCounts[i], 0, 0, 0, 0);CHKERRQ(ierr); ierr = NormConstantIntFixed(&e, n, p, prec, POINTS_MIN + POINTS_STEP*i, intSols+4*i, solutions+i);CHKERRQ(ierr); ierr = PetscLogEventEnd(flopCounts[i], 0, 0, 0, 0);CHKERRQ(ierr); printf("new norm constant: %15.15f\n", solutions[i]); } /* calculate errors */ for(i=0; i<NUM_SOLUTIONS; ++i) { //errors[i] = PetscAbsReal((solExact - solutions[i])/solExact); mpfr_sub_d(errors[i], solExact, solutions[i], MPFR_RNDN); mpfr_div(errors[i], errors[i], solExact, MPFR_RNDN); mpfr_abs(errors[i], errors[i], MPFR_RNDN); //intErrors[4*i+0] = PetscAbsReal((intExact[0] - intSols[4*i+0])/intExact[0]); mpfr_sub_d(intErrors[4*i+0], intExact[0], intSols[4*i+0], MPFR_RNDN); mpfr_div(intErrors[4*i+0], intErrors[4*i+0], intExact[0], MPFR_RNDN); mpfr_abs(intErrors[4*i+0], intErrors[4*i+0], MPFR_RNDN); //intErrors[4*i+1] = PetscAbsReal((intExact[1] - intSols[4*i+1])/intExact[1]); mpfr_sub_d(intErrors[4*i+1], intExact[1], intSols[4*i+1], MPFR_RNDN); mpfr_div(intErrors[4*i+1], intErrors[4*i+1], intExact[1], MPFR_RNDN); mpfr_abs(intErrors[4*i+1], intErrors[4*i+1], MPFR_RNDN); //intErrors[4*i+2] = PetscAbsReal((intExact[2] - intSols[4*i+2])/intExact[2]); mpfr_sub_d(intErrors[4*i+2], intExact[2], intSols[4*i+2], MPFR_RNDN); mpfr_div(intErrors[4*i+2], intErrors[4*i+2], intExact[2], MPFR_RNDN); mpfr_abs(intErrors[4*i+2], intErrors[4*i+2], MPFR_RNDN); //intErrors[4*i+3] = PetscAbsReal((intExact[3] - intSols[4*i+3])/intExact[3]); mpfr_sub_d(intErrors[4*i+3], intExact[3], intSols[4*i+3], MPFR_RNDN); mpfr_div(intErrors[4*i+3], intErrors[4*i+3], intExact[3], MPFR_RNDN); mpfr_abs(intErrors[4*i+3], intErrors[4*i+3], MPFR_RNDN); printf("errors[%d] = %15.15f\n", i, errors[i]); } FILE *fp1 = fopen("out/normInt1Prec.txt", "w"); FILE *fp2 = fopen("out/normInt2Prec.txt", "w"); FILE *fp3 = fopen("out/normInt3Prec.txt", "w"); FILE *fp4 = fopen("out/normInt4Prec.txt", "w"); FILE *fp = fopen("out/normWorkPrec.txt", "w"); fprintf(fp, "points flops error\n"); fprintf(fp1, "points error\n"); fprintf(fp2, "points error\n"); fprintf(fp3, "points error\n"); fprintf(fp4, "points error\n"); for(i=0; i<NUM_SOLUTIONS; ++i) { ierr = PetscLogEventGetPerfInfo(PETSC_DETERMINE, flopCounts[i], &info);CHKERRQ(ierr); fprintf(fp, "%d %4.4e %4.4e\n", POINTS_MIN + POINTS_STEP*i, info.flops, mpfr_get_d(errors[i], MPFR_RNDN)); fprintf(fp1, "%d %4.4e\n", POINTS_MIN + POINTS_STEP*i, mpfr_get_d(intErrors[4*i+0], MPFR_RNDN)); fprintf(fp2, "%d %4.4e\n", POINTS_MIN + POINTS_STEP*i, mpfr_get_d(intErrors[4*i+1], MPFR_RNDN)); fprintf(fp3, "%d %4.4e\n", POINTS_MIN + POINTS_STEP*i, mpfr_get_d(intErrors[4*i+2], MPFR_RNDN)); fprintf(fp4, "%d %4.4e\n", POINTS_MIN + POINTS_STEP*i, mpfr_get_d(intErrors[4*i+3], MPFR_RNDN)); } fclose(fp); fclose(fp1); fclose(fp2); fclose(fp3); mpfr_clear(solExact); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "main" PetscErrorCode main(int argc, char **argv) { PetscErrorCode ierr; PetscFunctionBeginUser; ierr = PetscInitialize(&argc, &argv, NULL, NULL);CHKERRQ(ierr); ierr = PetscLogDefaultBegin();CHKERRQ(ierr); ierr = normConvergence(21,22);CHKERRQ(ierr); ierr = PetscFinalize(); PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.6741702742, "avg_line_length": 37.0588235294, "ext": "c", "hexsha": "64890105b37767cc355809698d35455fcd821829", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "tom-klotz/ellipsoid-solvation", "max_forks_repo_path": "src/examples/ex3.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "tom-klotz/ellipsoid-solvation", "max_issues_repo_path": "src/examples/ex3.c", "max_line_length": 153, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "tom-klotz/ellipsoid-solvation", "max_stars_repo_path": "src/examples/ex3.c", "max_stars_repo_stars_event_max_datetime": "2016-11-05T20:15:01.000Z", "max_stars_repo_stars_event_min_datetime": "2016-11-05T20:15:01.000Z", "num_tokens": 2456, "size": 6930 }
/* This files contains some generic utilities */ /* ----- System includes -----*/ #include <stdlib.h> #include <stdio.h> #include <math.h> /* ----- IFU and GSL includes -----*/ #include <gsl/gsl_statistics.h> #include <gsl/gsl_sort.h> #include "IFU_io.h" // #include "IFU_math.h" /* ----- Specific IFU includes ----- */ #include "data_io.h" #ifdef FITS #include <fitsio.h> #endif /* Removing MIDAS by hand - not really clean, but should allow to compile with an IFU with --disable-midas enabled*/ #undef MIDAS #ifdef MIDAS #include "midas_defs.h" #include "tbldef.h" #include "fctext.h" #include "ldbext.h" #include "proto_st.h" #endif extern IO_Format InputIO, OutputIO; /* ----- local includes ----- */ #include "utils.h" /* ----- static functions ---------------------------------------- */ static int ascending(const void *a, const void*b) { if (*(double*)a==*(double*)b) return 0; return (*(double*)a > *(double*)b ) ? 1 : -1; } /* ----- ut_median ---------------------------------------- */ void ut_sort_ascending(double* values, int n) /* median of unsorted values */ { qsort(values,n,sizeof(double),&ascending); } /* ----- ut_median ---------------------------------------- */ double ut_median(double* values, int n) /* median of unsorted values */ { qsort(values,n,sizeof(double),&ascending); /* alternatively, I could have used gsl_stats_median_from_sorted_data but it is fucking the flies ! */ /* i saw also something usable in mathlib : the names might conflict !*/ if (n%2) return values[n/2]; else return (values[n/2-1]+values[n/2])/2; } /* ----- ut_min ---------------------------------------- */ double ut_min(double* values, int n) /* min of array */ { double min = values[0]; int i; for (i=1;i<n;i++) { if (values[i]<min) min=values[i]; } return min; } /* ----------------------------- ut_trunc_sigma_known -------------- */ void ut_trunc_sigma_known(double** values, int * nitems, double sigma, double sigcut){ /* trunc the data set, removing any value outside +/- sigcut sigma if sigcut<0, does noting . it works iteratively by removing too far away values. => slow if the sigcut is too low ! values : pointer to array of values - modified nitems : number of values -> modified sigcut : if <0, does nothing Beware : the number of remaining items might be 0 ! */ int ok=0; if (sigcut<0) return; qsort(*values,*nitems,sizeof(double),ascending); while (!ok && *nitems>1) { double mean=ut_mean(*values,*nitems); double valinf = (mean-(*values)[0])/sigma; double valsup = ((*values)[*nitems-1]-mean)/sigma; if (valsup>sigcut && valsup>=valinf) { double bound = MAX(sigcut,valinf); /* remove more than one for efficiency */ while(valsup>=bound && *nitems>1) { (*nitems)--; valsup = ((*values)[*nitems-1]-mean)/sigma; } } else if (valinf>sigcut && valinf>=valsup) { double bound = MAX(sigcut,valinf); while(valinf>=bound && *nitems>1 ){ (*nitems)--; (*values)++; valinf = (mean-(*values)[0])/sigma; } } else { ok=1; } } } /* ------------------------------- ut_trunc_sigma_unknown ------------------ */ void ut_trunc_sigma_unknown(double** values, int * nitems, double sigcut){ /* trunc the data set, removing any value outside +/- sigcut sigma if sigcut<0, does noting . it works iteratively by removing too far away values. => slow if the sigcut is too low ! Beware : sigma is computed from the distribution itself. Points far away will push the sigma towards greater values. values : pointer to array of values - modified nitems : number of values -> modified sigcut : if <0, does nothing Beware : the number of remaining items might be 0 ! */ int ok=0; if (sigcut<0) return; qsort(*values,*nitems,sizeof(double),ascending); while (!ok && *nitems>1) { double mean,sigma,valinf,valsup; mean = ut_mean((*values),*nitems); sigma = gsl_stats_sd_m(*values,1,*nitems,mean); valinf = (mean-(*values)[0])/sigma; valsup = ((*values)[*nitems-1]-mean)/sigma; if (valsup>sigcut && valsup>=valinf) { (*nitems)--; } else if (valinf>sigcut && valinf>=valsup) { (*nitems)--; (*values)++; } else { ok=1; } } } /* ------------------------------- ut_trunc_sigma_unknown ------------------ */ void ut_trunc_sigma_unknown_fast_sorted(double** values, int * nitems, double sigcut){ /* trunc the data set, removing any value outside +/- sigcut sigma if sigcut<0, does noting . it works grossly, removing each time all what is outside the window, which is not accurate Beware : sigma is computed from the distribution itself. Points far away will push the sigma towards greater values. values : pointer to array of values - modified nitems : number of values -> modified sigcut : if <0, does nothing Beware : the number of remaining items might be 0 ! */ int ok=0; if (sigcut<0) return; /* qsort(*values,*nitems,sizeof(double),ascending); */ while (!ok && *nitems>1) { double mean,sigma,valinf,valsup; int nitems_old = *nitems; mean = ut_mean((*values),*nitems); sigma = gsl_stats_sd_m(*values,1,*nitems,mean); valinf = mean-sigma*sigcut; valsup = mean + sigma*sigcut; while ((*values)[0] < valinf && *nitems>1) { (*nitems)--; (*values)++; } while ((*values)[*nitems-1] > valsup && *nitems>1) { (*nitems)--; } if (nitems_old == (*nitems)) ok=1; } } /*-------------------- ut_fraction_sigcut ----------------------*/ double ut_fraction_sigcut(double fraction) { /* given a distribution with fraction outliers, at infinite distance with respect to normal values, returns the standard deviation of the outliers, when the RMS is computed with it included.*/ /* the computation is performed with fraction values at 1 and 1-fraction at 0 */ double sigcut,rms; /* mean = fraction */ rms = sqrt(fraction*fraction*(1-fraction) + (1-fraction)*(1-fraction)*fraction); sigcut = (1-fraction)/rms; return sigcut; } /*-------------------- ut_mean ----------------------*/ double ut_mean(double* val,int n){ int i; double sum = 0; for (i=0;i<n;i++) sum += val[i]; return sum/n; } /*-------------------- ut_mean ----------------------*/ double ut_mode(double* val,int n){ /* This function returns the highest probability density a set of datas. This only works reliabely if there is only 1 maximum, and in the limit where the data is sufficiently sampled. No error computation is performed ...*/ /* The search is dyadic and iterative, each step looking for the part where the median is the narrower. The time is O(NlnN) (+ the time to run indexx)*/ /* This is a fast and inaccurate algorithm. For a general algorithm, see the Parzenwindow method - the drawback is that it depends on a window size a priori*/ size_t * index; double med; int nmin=0; int nmax=n; /* out of the table */ index = malloc(n*sizeof(size_t)); /* test */ gsl_sort_index(index,val,1,n); do { /* median computation */ if ((nmax-nmin) % 2 == 0) med = (val[index[ (nmin + nmax )/2 ]] + val[index[ (nmin+nmax)/2 -1 ]])/2; else med = val[index[ (nmin + nmax)/2 ]]; /* The density is higher for the upper part */ if ( fabs(med - val[index[nmin]]) > fabs (med - val[index[nmax-1]]) ) nmin =(nmin + nmax - 1 )/2; else if ( fabs(med - val[index[nmin]]) < fabs (med - val[index[nmax-1]]) ) /* rounding in the good direction in order to include the median place */ nmax = ( nmin + nmax)/2 + 1; else /* stop in case of equality */ nmax = nmin; } while (nmax-nmin > 2); return med; } /*-------------------- ut_mean ----------------------*/ double ut_mode2(double* val,int n){ /* This function returns the highest probability density a set of datas. This only works reliabely if there is only 1 maximum, and in the limit where the data is sufficiently sampled. No error computation is performed ...*/ /* The search is dyadic and iterative, each step looking for the part which contains most of the data with respect to the highest value. The time is O(NlnN) (+ the time to run indexx)*/ /* This is a fast and inaccurate algorithm. For a general algorithm, see the Parzenwindow method - the drawback is that it depends on a window size a priori*/ size_t * index; double half; int nmin=0; int nmax=n; /* out of the table */ index = malloc(n*sizeof(size_t)); /* test */ gsl_sort_index(index,val,1,n); do { int i; /* half window computation */ half=(val[index[nmin]]+val[index[nmax-1]])/2; for (i=nmin;i<nmax;i++) { if (val[index[i]]>half) break; } if (i==nmax) return half; else if (i<nmin+(nmax-nmin)/2) nmin=i; else if (i>nmin+(nmax-nmin)/2 || ((nmax-nmin)%2) ) nmax=i; else { nmin++; nmax--; } } while (nmax-nmin>2); return half; } /*-------------------- ut_autocovariance ----------------------*/ void ut_autocovariance(double* data, double* autocorr, int n) { /* data is of dim n, autocorr of dim n */ int decal,i; double mean; /* double var; */ double *mdata = malloc(sizeof(double)*n); /* compute the mean */ mean = ut_mean(data,n); /* substract it (n computations) */ for (i=0;i<n;i++) mdata[i] = data[i]-mean; /* compute variance and what is needed for decal=0*/ decal=0; autocorr[0]=0; for (i=0;i<n;i++) { autocorr[0]+=mdata[i]*mdata[i]; } autocorr[0] /= n; /* var = autocorr[0]; */ /* autocorr[0] = 1.0; */ /* n^2 part */ for (decal=1; decal<n; decal ++) { autocorr[decal]=0; for (i=0;i<n-decal;i++) { autocorr[decal]+=mdata[i]*mdata[i+decal]; } autocorr[decal] /= (n-decal); /* autocorr[decal] /= var; */ } free(mdata); } /*-------------------- ut_varname_from_imname ----------------------*/ void ut_varname_from_imname(char* imname,char* varname){ /* returns the name of the variance image from the name of the image */ /* check standard name */ char extname[lg_name+1]; extname[0]='\0'; varname[0]='\0'; if (strstr(imname,"[chip00]")) strcpy(extname,"[var00]"); if (strstr(imname,"[chip01]")) strcpy(extname,"[var01]"); if (strstr(imname,"[chip02]")) strcpy(extname,"[var02]"); if (strstr(imname,"[chip03]")) strcpy(extname,"[var03]"); if (strstr(imname,"[image]")) strcpy(extname,"[variance]"); if (extname[0]) { /* builds the variance name */ char *ptName; strcpy(varname,imname); ptName = strchr(varname,'['); strcpy(ptName,extname); } } /*-------------------- ut_open_check_name ----------------------*/ char* ut_open_check_name(char* name){ /* if name is a name without extension, tries to see if a [image] exists */ if (!strchr(name,'[')) { char new_name[lg_name+1]; sprintf(new_name,"%s[image]",name); if (exist(new_name)) strcpy(name,new_name); } return name; } /*-------------------- ut_open_check_name ----------------------*/ char* ut_create_check_name(char* name){ /* if name is a name without extension, appends an [image] by default */ if (!strchr(name,'[')) { char new_name[lg_name+1]; sprintf(new_name,"%s[image]",name); strcpy(name,new_name); } return name; } /*-------------------- ut_varname_from_imname ----------------------*/ int ut_is_bichip_detcom(char* filename){ /* returns 1 if the name corresponds to a detcom image */ char testName[lg_name+1]; if (strstr(filename,"%d")) return 1; if (strrchr(filename,'[')) return 0; // .fits file extension default if (strstr(filename,".fits")) sprintf(testName,"%s[chip00]",filename); else sprintf(testName,"%s.fits[chip00]",filename); if (exist(testName)) return 1; else { if (strstr(filename,".fits")) sprintf(testName,"%s[CHIP00]",filename); else sprintf(testName,"%s.fits[CHIP00]",filename); if (exist(testName)) return 1; else return 0; } } /*-------------------- ut_build_tmp_name ----------------------*/ void ut_build_tmp_name(char* filename, char* tmp_prefix){ /* builds a temporary memory file name from the image name and a prefix */ char imname[lg_name+1], *pt_name; if (!(pt_name = strrchr(filename,'/'))) pt_name = filename; else pt_name = pt_name+1; sprintf(imname,"mem://%s_%s",tmp_prefix,pt_name); // sprintf(imname,"%s_%s",tmp_prefix,pt_name); strcpy(filename,imname); } /*-------------------- ut_primary_header_name ----------------------*/ void ut_primary_header_name(char* full_name, char* primary_name){ /* the primary header is the image name without any extension*/ char* pt_name; strcpy(primary_name,full_name); if ((pt_name = strchr(primary_name,'['))) pt_name[0]='\0'; } /* ===== IFU lib disagreement ======================================== */ /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ! !.func open_frame_fast() ! !.purp opens a 2D frame and updates the image structure items !.desc ! open_frame(frame,name,mode) ! ! IMAGE2D *frame; image structure ! char *name; frame name ! char *mode; open mode (Input,Ouput,IO) !.ed -------------------------------------------------------------------- */ int open_frame_fast(IMAGE2D *frame, char *name, char *mode) { char errtext[132], filename[lg_name+1]; int status, nbaxes, iomode, int_datatype; float cuts[4]; int info[5]; #ifdef IRAF int two_dim=2; int len; #endif #ifdef FITS fitsfile *fptr; int nbread; int npix; int group = 0; double pixref; #endif memset(frame->ident,' ',lg_ident); frame->ident[lg_ident] = '\0'; memset(frame->cunit,' ',lg_unit); frame->cunit[lg_unit] = '\0'; memset(frame->history,' ',lg_hist); frame->history[lg_hist] = '\0'; frame->external_info = NULL; frame->file_type = T_IMA2D; frame->data_format = InputIO.basic_io; strcpy(filename,name); first_blk(filename); strcpy(frame->name,filename); append_ima_extension(frame->name,InputIO.basic_io); strcpy(filename,frame->name); if (!exist(filename)) { /* check if fil exists */ status = ERR_OPEN; sprintf(errtext,"open_frame: frame %s",filename); Handle_Error(errtext,status); return(status); } switch(mode[0]) { case 'I' : if (mode[1] == 'O') frame->iomode = (int)IO_MODE; else frame->iomode = (int)I_MODE; break; case 'O' : frame->iomode = (int)O_MODE; break; default : frame->iomode = (int)I_MODE; break; } iomode = get_iomode_code(InputIO.basic_io,frame->iomode); switch (InputIO.basic_io) { #ifdef MIDAS case MIDAS_FORMAT : status = SCFINF(filename,2,info); if (status == 0) { status = SCIGET(filename, info[1], iomode, F_IMA_TYPE, 2, &nbaxes, &(frame->nx), &(frame->startx), &(frame->stepx), frame->ident, frame->cunit, (char **)(&(frame->data)), &(frame->imno)); frame->data_type = info[1]; frame->data_type = decode_datatype(InputIO.basic_io,frame->data_type); if (nbaxes!=2) /* We open a spectrum like an image, and that's not good */ status = ERR_OPEN; } break; #endif #ifdef IRAF case IRAF_FORMAT : case STSDAS_FORMAT : len = strlen(filename); uimopn(filename,&iomode,&(frame->imno),&status,len); if (status != 0) break; uimgid(&(frame->imno),&int_datatype,&two_dim,&(frame->nx),&status); frame->data_type = decode_datatype(InputIO.basic_io,(short)(int_datatype)); if (status != 0) break; alloc_frame_mem(frame, datatype); switch(frame->data_type) { case SHORT : uigs2s(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny), frame->data.s_data,&status); break; case INT : case LONG : uigs2l(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny), frame->data.l_data,&status); break; case FLOAT : uigs2r(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny), frame->data.f_data,&status); break; case DOUBLE : uigs2d(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny), frame->data.d_data,&status); break; } disable_user_warnings(); RD_desc(frame,"IDENT",CHAR,lg_ident,frame->ident); restore_user_warnings(); break; #endif #ifdef FITS case FITS_A_FORMAT : case FITS_B_FORMAT : status =0; if (fits_open_file(&fptr,filename,iomode,&status)) { status = ERR_ACCESS; break; } frame->external_info = (void *)fptr; if (fits_read_key(fptr, TINT,"NAXIS", &nbaxes,NULL, &status)) { status = ERR_READ; break; } if (nbaxes != 2) { status = ERR_IMA_HEAD; break; } if (fits_read_key(fptr, TINT, "NAXIS1", &(frame->nx), NULL, &status)) { status = ERR_READ; break; } if (fits_read_key(fptr, TINT, "NAXIS2", &(frame->ny), NULL, &status)) { status = ERR_READ; break; } if (status == 0) { pixref = 1.0; fits_read_key(fptr, TDOUBLE, "CRPIX1", &pixref, NULL, &status); if (status) { status = 0; pixref = 1; } fits_read_key(fptr, TDOUBLE, "CRVAL1", &(frame->startx), NULL, &status); if (status) { status = 0; frame->startx = (double)1; } fits_read_key(fptr, TDOUBLE, "CDELT1", &(frame->stepx), NULL, &status); if (status) { status = 0; frame->stepx = (double)1; } frame->startx -= (pixref-1)*frame->stepx; pixref = 1.0; fits_read_key(fptr, TDOUBLE, "CRPIX2", &pixref, NULL, &status); if (status) { status = 0; pixref = 1; } fits_read_key(fptr, TDOUBLE, "CRVAL2", &(frame->starty), NULL, &status); if (status) { status = 0; frame->starty = (double)1; } fits_read_key(fptr, TDOUBLE, "CDELT2", &(frame->stepy), NULL, &status); if (status) { status = 0; frame->stepy = (double)1; } frame->starty -= (pixref-1)*frame->stepy; } else break; int_datatype = (fptr->Fptr->tableptr)->tdatatype; frame->data_type = decode_datatype(InputIO.basic_io,(short)int_datatype); if (frame->data_type == SHORT) { if (fptr->Fptr->tableptr[1].tscale == 1 && fptr->Fptr->tableptr[1].tzero == 32768) /* unsigned short !!! */ frame->data_type = LONG; } if (alloc_frame_mem(frame, frame->data_type) < 0) { fits_close_file(fptr,&status); status = ERR_ALLOC; break; } npix = frame->nx*frame->ny; switch (frame->data_type) { case SHORT : if (fits_read_img_sht(fptr,group,1L,npix,(short)0, frame->data.s_data,&nbread,&status)) { status = ERR_READ; break; } break; case LONG : case INT : if (fits_read_img_lng(fptr,group,1L,npix,(int)0, frame->data.l_data,&nbread,&status)) { status = ERR_READ; break; } break; case FLOAT : if (fits_read_img_flt(fptr,group,1L,npix,(float)0, frame->data.f_data,&nbread,&status)) { status = ERR_READ; break; } break; case DOUBLE : if (fits_read_img_dbl(fptr,group,1L,npix,(double)0, frame->data.d_data,&nbread,&status)) { status = ERR_READ; break; } break; } break; #endif } if (status) { sprintf(errtext,"open_frame: frame %s",filename); status = get_tiger_errcode(frame->data_format,status); Handle_Error(errtext,status); } else { disable_user_warnings(); status = RD_desc(frame,"LHCUTS",FLOAT,4,cuts); RD_desc(frame,"HISTORY",CHAR,lg_hist,frame->history); restore_user_warnings(); frame->endx = frame->startx + (frame->nx -1)*frame->stepx; frame->endy = frame->starty + (frame->ny -1)*frame->stepy; if (status <= 0) { /* image_minmax is a really slow routine, and most of the time useless */ frame->min = -ut_big_value; frame->max = +ut_big_value; /* image_minmax(frame); */ } else { frame->min = cuts[2]; frame->max = cuts[3]; } status = 0; /* parse wcs if contained in file */ status = parse_wcs(frame); } return(status); } /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ! !.func close_frame_fast() ! !.purp closes a currently active 2D frame !.desc ! close_frame(frame) ! ! IMAGE2D *frame; image structure !.ed -------------------------------------------------------------------- */ int close_frame_fast(IMAGE2D *frame) /* close active frame */ { char errtext[132], filename[lg_name+1]; int stat, int_datatype; float cuts[4]; #ifdef IRAF int one=1; #endif #ifdef FITS fitsfile *fptr; int npix; #endif strcpy(filename,frame->name); if (frame->iomode == (int)I_MODE) { switch (frame->data_format) { #ifdef MIDAS case MIDAS_FORMAT : stat = SCFCLO(frame->imno); break; #endif #ifdef IRAF case IRAF_FORMAT : case STSDAS_FORMAT : uimclo(&(frame->imno),&stat); break; #endif #ifdef FITS case FITS_A_FORMAT : case FITS_B_FORMAT : stat =0; fptr = (fitsfile *)frame->external_info; fits_close_file(fptr,&stat); free_frame_mem(frame); frame->external_info = NULL; break; #endif } if (stat) { sprintf(errtext,"close_frame: frame %s",filename); stat = get_tiger_errcode(frame->data_format,stat); Handle_Error(errtext,stat); } return(stat); } /* if (frame->data.d_data != NULL) { image_minmax(frame); cuts[0]=(float)frame->min; cuts[2]=(float)frame->min; cuts[1]=(float)frame->max; cuts[3]=(float)frame->max; stat = WR_desc(frame,"LHCUTS",FLOAT,4,cuts); } */ WR_history(frame, (Anyfile *)0); switch (frame->data_format) { #ifdef MIDAS case MIDAS_FORMAT : stat = SCFCLO(frame->imno); break; #endif #ifdef IRAF case IRAF_FORMAT : case STSDAS_FORMAT : switch(frame->data_type) { case SHORT : uips2s(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny), frame->data.s_data,&stat); break; case INT : case LONG : uips2l(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny), frame->data.l_data,&stat); break; case FLOAT : uips2r(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny), frame->data.f_data,&stat); break; case DOUBLE : uips2d(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny), frame->data.d_data,&stat); break; } if (stat == 0) uimclo(&(frame->imno),&stat); free_frame_mem(frame); break; #endif #ifdef FITS case FITS_A_FORMAT : case FITS_B_FORMAT : stat = 0; fptr = (fitsfile *)frame->external_info; if (frame->iomode != (int)I_MODE) { if (frame->data.d_data != NULL) { int_datatype = get_datatype_code(OutputIO.basic_io,frame->data_type); npix = frame->nx*frame->ny; if (fits_write_img(fptr,int_datatype,1L,npix, frame->data.s_data,&stat)) { stat = ERR_WRIT; } } } if (! stat) { fits_close_file(fptr,&stat); stat = wcs_free(frame); } free_frame_mem(frame); frame->external_info = NULL; break; #endif } if (stat) { sprintf(errtext,"close_frame: frame %s",filename); stat = get_tiger_errcode(frame->data_format,stat); Handle_Error(errtext,stat); } else { if (TK && (frame->iomode == O_MODE || frame->iomode == IO_MODE)) { printf("@ N {%s}\n",filename); } } return(stat); } /* ----- juldat --------------------------------------------------------- */ /*C C FUNCTION JULDAT RETURNS THE JULIAN DATE AS A DOUBLE C PRECISION NUMBER. C ALGORITHM FROM "ALAMANAC FOR COMPUTERS" p.B2 C*/ double juldat( int year, int month, int day, double ut) /* year, month, day, ut are the UTC ones ut is the fractional hour */ { double tmp; tmp = 367.0*year + 0.5 + ut/24.0; tmp = tmp - ((7*(year+((month+9)/12)))/4) + ((275*month)/9) + day + 1721013; return tmp; } /* ===== string utilities ===== */ int ut_parse_line(char* line, char** tokens) { /* the token strings will contain the line elements separated by spaces */ /* the original line will be modified (some '/0' char added)*/ char* pt_line = line; int itoken=0; while (pt_line && pt_line[0]!='\0') { tokens[itoken++] = pt_line; pt_line = strchr(pt_line,' '); if (pt_line) while((pt_line)[0]==' ') { pt_line[0]='\0'; pt_line++; } } return itoken; }
{ "alphanum_fraction": 0.5723202926, "avg_line_length": 27.5789473684, "ext": "c", "hexsha": "07424d7e61c0864035aff0f123869ffd87b6f3fb", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "9be356dcf64e411d74a080629ffa2ca67974d530", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "snfactory/preprocess", "max_forks_repo_path": "libsrc/utils.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "9be356dcf64e411d74a080629ffa2ca67974d530", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "snfactory/preprocess", "max_issues_repo_path": "libsrc/utils.c", "max_line_length": 116, "max_stars_count": null, "max_stars_repo_head_hexsha": "9be356dcf64e411d74a080629ffa2ca67974d530", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "snfactory/preprocess", "max_stars_repo_path": "libsrc/utils.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7100, "size": 25152 }
/* Copyright 2018,2019, Alistair Boyle, 3-clause BSD License */ #include "config.h" #include <string.h> /* memset */ #include <stdlib.h> /* free */ #include <lapacke.h> /* inv: dgetrf, dgetri */ #include <math.h> /* fabs, sqrt */ #include <limits.h> /* MAX_INT */ #include <assert.h> /* assert */ #include <stdio.h> /* printf */ #include "matrix.h" #include "model.h" /* references: * [1] A. Boyle, PhD Thesis, 2016, Geophysical Applications of Electrical Impedance Tomography, Carleton University */ #ifdef UNIT_TESTING extern void * _mock_test_malloc(const size_t size, const char * file, const int line); extern void _test_free(void * const ptr, const char * file, const int line); #define malloc(size) _mock_test_malloc(size, __FILE__, __LINE__) #define free(ptr) _test_free(ptr, __FILE__, __LINE__) #endif #define SUCCESS 1 #define FAILURE 0 static void init_mesh(mesh * m) { memset(m, 0, sizeof(mesh)); } static void init_model(model * m) { memset(m, 0, sizeof(model)); } model * malloc_model() { model * m = malloc(sizeof(model)); if(m) { init_model(m); } return m; } static void free_mesh(mesh * m) { free(m->nodes); free(m->elems); free(m->matidx); free(m->surfaceelems); free(m->bc); free(m->pmap_param); free(m->pmap_elem); free(m->pmap_frac); } void reset_model(model * m) { assert(m != NULL); free(m->data); free(m->params); free(m->stimmeas); free(m->measgain); free(m->elec_to_sys); free(m->zcbc); free(m->zc); free_mesh(&(m->fwd)); free_mesh(&(m->rec)); init_model(m); } void * free_model(model * m) { if(m == NULL) { return NULL; } reset_model(m); free(m); return NULL; } int set_model_data(model * m, int rows, int cols) { assert(rows > 0); assert(cols > 0); assert(m != NULL); m->n_data[0] = rows; m->n_data[1] = cols; free(m->data); m->data = malloc(sizeof(double) * rows * cols); if(m->data == NULL) { return FAILURE; } return SUCCESS; } int set_model_params(model * m, int rows, int cols) { assert(rows > 0); assert(cols > 0); assert(m != NULL); m->n_params[0] = rows; m->n_params[1] = cols; free(m->params); m->params = malloc(sizeof(double) * rows * cols); if(m->params == NULL) { return FAILURE; } return SUCCESS; } int set_model_stimmeas(model * m, int rows) { assert(rows > 0); assert(m != NULL); m->n_stimmeas = rows; m->n_elec = 0; free(m->elec_to_sys); m->elec_to_sys = NULL; free(m->stimmeas); m->stimmeas = malloc(sizeof(int) * rows * 4); if(m->stimmeas == NULL) { return FAILURE; } free(m->measgain); m->measgain = malloc(sizeof(double) * rows); if(m->measgain == NULL) { return FAILURE; } return SUCCESS; } void set_mesh_dim(mesh * m, int dim) { assert(dim == 2 || dim == 3); assert(m != NULL); free_mesh(m); init_mesh(m); m->dim = dim; } int set_mesh_nodes(mesh * m, int n_nodes) { assert(n_nodes >= 0); assert(m != NULL); assert(m->dim == 2 || m->dim == 3); m->n_nodes = n_nodes; free(m->nodes); m->nodes = malloc(sizeof(double) * n_nodes * m->dim); if(m->nodes == NULL) { return FAILURE; } return SUCCESS; } int set_mesh_elems(mesh * m, int n_elems) { assert(n_elems >= 0); assert(m != NULL); assert(m->dim == 2 || m->dim == 3); m->n_elems = n_elems; free(m->elems); m->elems = malloc(sizeof(int) * n_elems * (m->dim + 1)); if(m->elems == NULL) { return FAILURE; } free(m->matidx); m->matidx = malloc(sizeof(int) * n_elems); if(m->matidx == NULL) { return FAILURE; } return SUCCESS; } int set_mesh_surfaceelems(mesh * m, int n_se) { assert(n_se >= 0); assert(m != NULL); assert(m->dim == 2 || m->dim == 3); m->n_se = n_se; free(m->surfaceelems); m->surfaceelems = malloc(sizeof(int) * n_se * m->dim); if(m->surfaceelems == NULL) { return FAILURE; } free(m->bc); m->bc = malloc(sizeof(int) * n_se); if(m->bc == NULL) { return FAILURE; } return SUCCESS; } int set_mesh_pmap(mesh * m, int n_pmap) { assert(n_pmap >= 0); assert(m != NULL); m->n_pmap = n_pmap; free(m->pmap_param); m->pmap_param = malloc(sizeof(int) * n_pmap); if(m->pmap_param == NULL) { return FAILURE; } free(m->pmap_elem); m->pmap_elem = malloc(sizeof(int) * n_pmap); if(m->pmap_elem == NULL) { return FAILURE; } free(m->pmap_frac); m->pmap_frac = malloc(sizeof(double) * n_pmap); if(m->pmap_frac == NULL) { return FAILURE; } return SUCCESS; } int set_model_zc(model * m, int rows) { assert(rows > 0); assert(m != NULL); m->n_zc = rows; free(m->zc); m->zc = malloc(sizeof(double) * rows); if(m->zc == NULL) { return FAILURE; } free(m->zcbc); m->zcbc = malloc(sizeof(int) * rows); if(m->zcbc == NULL) { return FAILURE; } return SUCCESS; } int calc_elec_zc_map(model * m) { assert(m != NULL); assert(m->n_elec > 0); double * tmp = malloc(sizeof(double) * m->n_elec); if(tmp == NULL) { return FAILURE; } if((m->n_zc == m->n_elec) && (m->zcbc == NULL)) { free(tmp); return SUCCESS; } for(int i = 0; i < m->n_elec; i++) { tmp[i] = 1e-2; /* default zc = 0.01 Ω/m² */ } for(int i = 0; i < m->n_zc; i++) { /* TODO for now we assume that boundary condition number = electrode# */ const int elec = m->zcbc[i]; assert(elec > 0); assert(elec <= m->n_elec); tmp[elec - 1] = m->zc[i]; } free(m->zcbc); free(m->zc); m->zcbc = NULL; m->zc = tmp; m->n_zc = m->n_elec; return SUCCESS; } double * inv(int n, double A[n][n]) { double * Ap = &(A[0][0]); int ipiv[n + 1]; memset(ipiv, 0, (n + 1)*sizeof(int)); if(LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, Ap, n, ipiv) || LAPACKE_dgetri(LAPACK_ROW_MAJOR, n, Ap, n, ipiv)) { return NULL; } return Ap; } double det(int n, double A[n][n]) { if(n == 2) { return A[0][0] * A[1][1] - A[0][1] * A[1][0]; } double d = 0; double sign = 1.0; for(int i = 0; i < n; i++, sign *= -1.0) { /* construct sub-matrix B */ double B[n - 1][n - 1]; for(int j = 1; j < n; j++) { for(int k = 0, s = 0; k < n; k++) { if(k != i) { B[j - 1][s] = A[j][k]; s++; } } } d += sign * A[0][i] * det(n - 1, B); /* (-1)^n * a1i * |B| */ } return d; } /* shape function * Se from [1] eq (C.31) -- first-order tetrahedral/triangular elements * Se is symmetric, only the lower triangular portion is calculated (E1^T E1 is symmetric) * inputs: nd = # of dimensions (2=2D, 3=3D), * N = ptrs to node coordinates (nd+1 nodes with nd double precision values) * ex: {&n[120], &n[332], &n[556], &n[733]} for 3D, where n[120] = {1.1, 0.1, 3.2}, etc. * NOTE: nodes should be in increasing order so that calc_sys_elem_ij * gives an upper triangular matrix in the global node numbering * output: Se = replaces Se[0..t-1] for t = n(n+1)/2 entries with n=nd+1 elements as * upper triangular symmetric matrix, row-major order * returns: NULL if matrix inverse fails, Se otherwise */ static double calc_elem_vol(const int n, double const * const * const nodes, double E[n][n]) { for(int i = 0; i < n; i++) { E[i][0] = 1; for(int j = 1; j < n; j++) { E[i][j] = nodes[i][j - 1]; } } if(inv(n, E) == NULL) { return -1.0; } return fabs(det(n, E)); } static double * calc_sys_elem_v(const int nd, double const * const * const nodes, double * Se) { const int n = nd + 1; double E[n][n]; /* from [1] eq (C.33) */ const double detE = calc_elem_vol(n, nodes, E); if(detE < 0) { return NULL; } int ndf = 1; /* = !nd = factorial(number of dimensions) */ for(int i = 2; i <= nd; i++ ) { ndf *= i; } const double c = 1 / (ndf * detE); /* Se = c * E1^T E1, where E1 is E without the top row */ int m = 0; for(int i = 0; i < n; i++ ) { for(int j = i; j < n; j++ ) { Se[m] = 0; for(int k = 1; k < n; k++) { Se[m] += E[k][i] * E[k][j]; } /* TODO pull this out and multiply by conductivity D, to save some multiply operations */ Se[m] *= c; m++; } } return Se; } static void calc_sys_elem_ij(const int nd, int const * const elem, int * ii, int * jj) { const int n = nd + 1; int idx = 0; for(int i = 0; i < n; i++ ) { for(int j = i; j < n; j++ ) { int ei = elem[i] - 1; int ej = elem[j] - 1; /* swap indices (symmetric matrix) if this entry would be in the * upper triangular portion of the matrix */ if(ei < ej) { int tmp = ei; ei = ej; ej = tmp; } ii[idx] = ei; jj[idx] = ej; idx++; } } } int calc_sys_elem_n(const int nd) { /* nd=2: 6, nd=3: 10 ... for symmetric (isotropic conductivity)*/ const int n = nd + 1; return n * (n + 1) / 2; } /* returns 0 on success, > 0 on failure as the singular element number e+1 */ int calc_sys_elem(mesh const * const m, int * ii, int * jj, double * Se) { const int nd = m->dim; const int n_elems = m->n_elems; const int * elems = m->elems; const double * nodes = m->nodes; const int n = calc_sys_elem_n(nd); for(int i = 0; i < n_elems; i++) { calc_sys_elem_ij(nd, elems, ii, jj); double const * node_list [4]; for(int j = 0; j < nd + 1; j ++) { int idx = elems[j] - 1; if ( idx < 0 ) { idx = 0; } node_list[j] = &(nodes[idx * nd]); } if(calc_sys_elem_v(nd, node_list, Se) == NULL) { return i + 1; } elems += (nd + 1); ii += n; jj += n; Se += n; } return 0; } void calc_sys_gnd(const int gnd, size_t nnz, int * ii, int * jj, double * Se) { const int gndidx = gnd - 1; int ret = 0; for (int i = 0; i < nnz; i++ ) { const int is_row = (ii[i] == gndidx); const int is_col = (jj[i] == gndidx); if ( is_row || is_col) { if(ret == 0) { /* replace with (gndidx,gndidx)=1.0 */ ii[i] = gndidx; jj[i] = gndidx; Se[i] = 1.0; } else { /* drop this entry */ Se[i] = 0.0; } ret++; } } assert(ret != 0); } #define dot2(a,b) (((a[0])*(b[0])) + ((a[1])*(b[1]))) #define dot3(a,b) (((a[0])*(b[0])) + ((a[1])*(b[1])) + ((a[2])*(b[2]))) #define sum_sq2(a) dot2(a,a) #define sum_sq3(a) dot3(a,a) #define cross3i(a,b) (((a[1])*(b[2])) - ((a[2])*(b[1]))) #define cross3j(a,b) (((a[2])*(b[0])) - ((a[0])*(b[2]))) #define cross3k(a,b) (((a[0])*(b[1])) - ((a[1])*(b[0]))) // static void printf_vec(const int nd, double x[nd]) // { // printf(" ("); // int i; // for(i = 0; i < nd - 1; i++) { // printf("%g, ", x[i]); // } // printf("%g", x[i]); // printf(")\n"); // } static double calc_elem_area(const int nd, double nodes[nd][nd]) { /* len = diff(nodes) .. point to point distances */ // for(int i = 0; i < nd; i++) { // printf("[%d] ", i); printf_vec(nd, nodes[i]); // } for(int i = 0; i < nd - 1; i++) { for(int j = 0; j < nd; j++) { nodes[i][j] -= nodes[i + 1][j]; /* subtract the row below */ } // printf("[%d]-[%d] ", i, i + 1); printf_vec(nd, nodes[i]); } if(nd == 3) { /* cross product of lengths c = a x b*/ // printf("%gi\n",nodes[0][1]*nodes[1][2] - nodes[0][2]*nodes[1][1]); // printf("%gj\n",nodes[0][2]*nodes[1][0] - nodes[0][0]*nodes[1][2]); // printf("%gk\n",nodes[0][0]*nodes[1][1] - nodes[0][1]*nodes[1][0]); const double tmp[3] = { cross3i(nodes[0], nodes[1]), cross3j(nodes[0], nodes[1]), cross3k(nodes[0], nodes[1]), }; // printf("[0] x [1]: "); printf_vec(nd, tmp); assert(dot3(tmp, nodes[0]) == 0); /* confirm c . a = 0 */ assert(dot3(tmp, nodes[1]) == 0); /* confirm c . b = 0 */ nodes[0][0] = sum_sq3(tmp); // printf("∑[0]²: "); printf_vec(1, nodes[0]); } else { nodes[0][0] = sum_sq2(nodes[0]); // printf("∑[0]²: "); printf_vec(1, nodes[0]); } const double area = sqrt(nodes[0][0]) / (double)(nd - 1); return area; } static void copy_nodes_from_surfaceelems(mesh const * const m, const int se_idx, const int nd, double nodes[nd][nd]) { const int dim = m->dim; for(int i = 0; i < dim; i++) { const int nidx = m->surfaceelems[se_idx * dim + i] - 1; /* node index */ for(int j = 0; j < dim; j++) { nodes[i][j] = m->nodes[nidx * dim + j]; } } } static int max_bc(mesh const * const m) { int max = -1; for(int i = 0; i < m->n_se; i++ ) { const int bci = m->bc[i]; if (bci > max) { max = bci; } } return max; } int calc_elec_to_sys_map(model * m) { assert(m != NULL); free(m->elec_to_sys); m->n_elec = 0; m->elec_to_sys = NULL; const int dim = m->fwd.dim; const int n_bc = max_bc(&(m->fwd)) + 1; if(n_bc < 1) { return SUCCESS; } int cnt[n_bc]; int nodes[n_bc]; int pem_nodes[n_bc]; for(int i = 0; i < n_bc; i++) { cnt[i] = 0; nodes[i] = 0; pem_nodes[i] = 0; } for(int i = 0; i < m->fwd.n_se; i ++ ) { const int bci = m->fwd.bc[i]; cnt[bci]++; for(int j = 0; j < dim; j++) { const int nidx = m->fwd.surfaceelems[i * dim + j]; if(nidx > 0) { nodes[bci]++; pem_nodes[bci] = nidx - 1; } } } /* we assume the BC=0 is the generic boundary with no electrodes, so start at i=1 */ int n_elec = 0; for(int i = 1; i < n_bc; i++) { if(cnt[i] > 0) { n_elec++; } } m->elec_to_sys = malloc(sizeof(int) * n_elec); if(m->elec_to_sys == NULL) { return FAILURE; } m->n_elec = n_elec; int n_cem = 0; int electrode = 0; for(int i = 1; i < n_bc; i++) { if((cnt[i] == 1) && (nodes[i] == 1)) { /* PEM */ m->elec_to_sys[electrode++] = pem_nodes[i]; } else if(cnt[i] > 0) { /* CEM */ m->elec_to_sys[electrode++] = n_cem + m->fwd.n_nodes; n_cem++; } } assert(electrode == n_elec); return SUCCESS; } static int count_se_for_this_bc(mesh const * const m, int bc) { int n = 0; for(int i = 0; i < m->n_se; i ++ ) { const int bci = m->bc[i]; if (bci == bc) { n++; } } return n; } /* Construct a dense column vector for Neumann (current) stimulus 'amp' on * boundary m->bc = bc. * Returns number of nodes perturbed: 0 = failure. */ int calc_stim_neumann(mesh const * const m, double amp, int bc, double * b) { assert(m != NULL); assert(b != NULL); const int dim = m->dim; const int n = count_se_for_this_bc(m, bc); int cnt_bc_local_nodes = n * dim; int list[n]; double area[n]; double total_area = 0; for(int i = 0, j = 0; i < m->n_se; i ++ ) { const int bci = m->bc[i]; if (bci != bc) { continue; } double tmp[dim][dim]; copy_nodes_from_surfaceelems(m, i, dim, tmp); area[j] = calc_elem_area(dim, tmp); total_area += area[j]; // printf("bc#%d: area[%d]=%g\n", bc, j, area[j]); list[j] = i; j++; } /* set boundary condition */ for(int j = 0; j < n; j++ ) { const int i = list[j]; for(int k = 0; k < dim; k++) { const int nidx = m->surfaceelems[i * dim + k] - 1; // printf("#%d nidx=%d %g*%g/%g %d\n",j,nidx,amp, area[j],total_area,dim); b[ nidx ] += amp * (area[j] / total_area) / (double) dim; } } return cnt_bc_local_nodes; } int calc_sys_cem_n(const int nd) { /* nn = 2D: 3x3 sym, 3D: 4x4 sym * n_{bc=i} = ∑(n_se_{bc=i})x(nn) for n_se_{bc=i} = number of surface elements with BC=i * total CEM system matrix elements is then * n = ∑_{i=1..ne} n_{bc=i} */ return (nd == 2) ? 6 : 10; } int calc_sys_cem(mesh const * const m, int bc, double zc, int cem_node, int Se_idx, int * ii, int * jj, double * Se) { /* For each segment of the CEM add * 2D: cem -- n1 n2 * A_2d = 6 0 -3 -3 * 1/6 * length / zc * 0 0 0 0 * -3 0 2 1 * -3 0 1 2 * 3D: cem -- n1 n2 n3 * A_3d = 12 0 -4 -4 -4 * 1/12 * area / zc * 0 0 0 0 0 * -4 0 2 1 1 * -4 0 1 2 1 * -4 0 1 1 2 */ assert(m != NULL); const int Se_idx_start = Se_idx; const int dim = m->dim; const int n = count_se_for_this_bc(m, bc); int list[n]; double area[n]; double total_area = 0; for(int i = 0, j = 0; i < m->n_se; i ++ ) { const int bci = m->bc[i]; if (bci != bc) { continue; } double tmp[dim][dim]; copy_nodes_from_surfaceelems(m, i, dim, tmp); area[j] = calc_elem_area(dim, tmp); total_area += area[j]; // printf("bc#%d: area[%d]=%g\n", bc, j, area[j]); list[j] = i; j++; } for(int j = 0; j < n; j++ ) { const int i = list[j]; const double scale = (dim == 2) ? 6.0 : 12.0; const double area_zc = area[j] / zc; Se[Se_idx] = area_zc; ii[Se_idx] = cem_node; jj[Se_idx] = cem_node; Se_idx++; for(int k = 0; k < dim; k++) { const int nidx = m->surfaceelems[i * dim + k] - 1; Se[Se_idx] = ((dim == 2) ? -3.0 : -4.0) / scale * area_zc; ii[Se_idx] = cem_node; jj[Se_idx] = nidx; Se_idx++; Se[Se_idx] = +2.0 / scale * area_zc; ii[Se_idx] = nidx; jj[Se_idx] = nidx; Se_idx++; for(int p = 0; p < k; p++) { const int pidx = m->surfaceelems[i * dim + p] - 1; Se[Se_idx] = +1.0 / scale * area_zc; ii[Se_idx] = pidx; jj[Se_idx] = nidx; Se_idx++; } } } const int nnz_added = calc_sys_cem_n(dim) * n; assert(Se_idx - Se_idx_start == nnz_added); return nnz_added; } enum se_type {UNKNOWN, NONE, PEM, CEM}; static int check_bc(mesh const * const msh) { assert(msh != NULL); const int dim = msh->dim; const int n_bc = max_bc(msh) + 1; enum se_type type[n_bc]; for(int i = 0; i < n_bc; i++) { type[i] = UNKNOWN; } for(int i = 0; i < msh->n_se; i ++ ) { const int bci = msh->bc[i]; /* a PEM is recorded in surfaceelems with a single node * as the first entry and the remaining entries as zero; * so we test the second entry to see if its zero */ int cnt = 0; for(int j = 0; j < msh->dim; j++) { cnt += (msh->surfaceelems[i * dim + j] > 0) ? 1 : 0; } enum se_type newtype; if(cnt == msh->dim) { newtype = CEM; } else if(cnt == 1) { newtype = PEM; } else { printf("error: bad number of nodes on boundary %d\n", bci); return FAILURE; /* bad node#s */ } if(type[bci] == UNKNOWN) { type[bci] = newtype; } else if(type[bci] != newtype) { printf("error: mixed PEM and CEM on boundary %d\n", bci); return FAILURE; /* mixed PEM and CEM syntax in same BC */ } else if(newtype == PEM) { printf("error: multiple PEM surface elements have the same boundary#%d, see surface element %d\n", bci, i + 1); return FAILURE; /* duplicate PEM for same BC */ } if((newtype == PEM) && (msh->surfaceelems[i * dim + 0] <= 0)) { printf("error: for PEM on boundary %d, must have node# on first entry\n", bci); return FAILURE; /* must have se[0] be the node for a PEM */ } } /* expect all BC to be used */ for(int bc = 0; bc < n_bc; bc++) { if(type[bc] == UNKNOWN) { printf("error: unused boundary %d\n", bc); return FAILURE; } } return SUCCESS; } int check_model(model const * const mdl) { return check_bc(&(mdl->fwd)); } static void printf_mesh(mesh const * const msh, int verbosity) { assert(msh != NULL); if(msh->n_elems == 0) { printf(" (none)\n"); return; } printf(" %dD, %d nodes, %d elements, %d surfaces, %d entry parameter map\n", msh->dim, msh->n_nodes, msh->n_elems, msh->n_se, msh->n_pmap); if(verbosity <= 1) { return; } if(msh->n_elems > 0) { printf(" elements\n"); } const int nd = msh->dim; const int nd1 = nd + 1; for(int i = 0; i < msh->n_elems; i++) { printf(" "); for(int j = 0; j < nd1; j++) { printf(" %-5d", msh->elems[i * nd1 + j]); } printf("\n"); } if(msh->n_nodes > 0) { printf(" nodes\n"); } for(int i = 0; i < msh->n_nodes; i++) { printf(" "); for(int j = 0; j < nd; j++) { printf(" %-+7.3f", msh->nodes[i * nd + j]); } printf("\n"); } if(msh->n_se > 0) { printf(" surface elements\n"); } for(int i = 0; i < msh->n_se; i++) { printf(" "); for(int j = 0; j < nd; j++) { printf(" %-5d", msh->surfaceelems[i * nd + j]); } if(msh->bc[i] != 0) { printf(" (bc#%d)", msh->bc[i]); } printf("\n"); } if(msh->n_pmap > 0) { printf(" parameter map\n"); } for(int i = 0; i < msh->n_pmap; i++) { printf(" (%5d,%5d) = %0.3f\n", msh->pmap_elem[i], msh->pmap_param[i], msh->pmap_frac[i]); } } #define plural(a) ((a!=1)?"s":"") void printf_model(model const * const mdl, int verbosity) { printf("model: %d electrodes, %d measurements,", mdl->n_elec, mdl->n_stimmeas); printf(" λ = %g\n", mdl->hp); printf(" %d parameter frame%s", mdl->n_params[1], plural(mdl->n_params[1])); if(mdl->n_params[1] > 0) { printf(" (%d parameter%s/frame)\n", mdl->n_params[0], plural(mdl->n_params[0])); } else { printf("\n"); } printf(" %d measurement frame%s", mdl->n_data[1], plural(mdl->n_data[1])); if(mdl->n_data[1] > 0) { printf(" (%d measurement%s/frame)\n", mdl->n_data[0], plural(mdl->n_data[0])); } else { printf("\n"); } if((verbosity > 1) && (mdl->n_stimmeas > 0)) { printf(" %d stimulus and measurement pairs: A-B M-N (gain)\n", mdl->n_stimmeas); for(int i = 0; i < mdl->n_stimmeas; i++) { printf(" %d-%d %d-%d (%5.2e)\n", mdl->stimmeas[i * 4 + 0], mdl->stimmeas[i * 4 + 1], mdl->stimmeas[i * 4 + 2], mdl->stimmeas[i * 4 + 3], mdl->measgain[i]); } } if((verbosity > 1) && (mdl->n_zc > 0)) { printf(" %d contact impedances\n", mdl->n_zc); if(mdl->zcbc == NULL) { for(int i = 0; i < mdl->n_zc; i++) { printf(" %5.2e (electrode#%d)\n", mdl->zc[i], i + 1); } } else { for(int i = 0; i < mdl->n_zc; i++) { printf(" %5.2e (bc#%d)\n", mdl->zc[i], mdl->zcbc[i]); } } } printf(" forward model:"); printf_mesh(&(mdl->fwd), verbosity); printf(" reconstruction model:"); printf_mesh(&(mdl->rec), verbosity); if((verbosity > 1) && (mdl->n_params[0] > 0)) { const int rows = mdl->n_params[0]; printf(" parameters\n"); for(int i = 0; i < mdl->n_params[0]; i++) { printf(" "); for(int j = 0; j < mdl->n_params[1]; j++) { printf(" %18.8e", mdl->params[i + rows * j]); } printf("\n"); } } if((verbosity > 1) && (mdl->n_data[0] > 0)) { const int rows = mdl->n_data[0]; printf(" data\n"); for(int i = 0; i < mdl->n_data[0]; i++) { printf(" "); for(int j = 0; j < mdl->n_data[1]; j++) { printf(" %18.8e", mdl->data[i + rows * j]); } printf("\n"); } } } int calc_sys_size(model const * const m) { const int dim = m->fwd.dim; const int n_bc = max_bc(&(m->fwd)) + 1; enum se_type type[n_bc]; for(int i = 0; i < n_bc; i++) { type[i] = UNKNOWN; } type[0] = NONE; /* skip bc=0, assuming its the exterior */ for(int i = 0; i < m->fwd.n_se; i ++ ) { const int bci = m->fwd.bc[i]; if (type[bci] != UNKNOWN) { continue; } type[bci] = (m->fwd.surfaceelems[i * dim + 1] == 0) ? PEM : CEM; } int n_cem = 0; for(int bc = 0; bc < n_bc; bc++) { n_cem += (type[bc] == CEM) ? 1 : 0; } return (m->fwd.n_nodes + n_cem); } size_t calc_sys_nnz(model const * const m) { const int dim = m->fwd.dim; const int n_bc = max_bc(&(m->fwd)) + 1; enum se_type type[n_bc]; for(int i = 0; i < n_bc; i++) { type[i] = UNKNOWN; } int cnt[n_bc]; for(int i = 0; i < n_bc; i++) { cnt[i] = 0; } for(int i = 0; i < m->fwd.n_se; i ++ ) { const int bci = m->fwd.bc[i]; type[bci] = (m->fwd.surfaceelems[i * dim + 1] == 0) ? PEM : CEM; cnt[bci]++; } type[0] = NONE; /* force skipping bc=0, assuming its the exterior */ /* count surfaceelems that are CEM */ int se_cem = 0; for(int bc = 0; bc < n_bc; bc++) { se_cem += (type[bc] == CEM) ? cnt[bc] : 0; } const int ne = m->fwd.n_elems; const int se_n = calc_sys_elem_n(dim); /* sparse matrix entries per mesh element */ const int nnz_per_se = calc_sys_cem_n(dim); return (se_n * ne) + (se_cem * nnz_per_se); }
{ "alphanum_fraction": 0.4807899328, "avg_line_length": 28.6585106383, "ext": "c", "hexsha": "db1e3c7e5e11fa202f6f0c9bbf26f3e6fd79bbc6", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "05a10333eda3b1569a9acd6e8b8fca245f9f012e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "boyle/zedhat", "max_forks_repo_path": "src/model.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "05a10333eda3b1569a9acd6e8b8fca245f9f012e", "max_issues_repo_issues_event_max_datetime": "2018-04-12T09:34:48.000Z", "max_issues_repo_issues_event_min_datetime": "2018-03-30T02:37:55.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "boyle/zedhat", "max_issues_repo_path": "src/model.c", "max_line_length": 123, "max_stars_count": 2, "max_stars_repo_head_hexsha": "05a10333eda3b1569a9acd6e8b8fca245f9f012e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "boyle/zedhat", "max_stars_repo_path": "src/model.c", "max_stars_repo_stars_event_max_datetime": "2021-07-06T01:26:06.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-08T16:02:51.000Z", "num_tokens": 8695, "size": 26939 }
/** * * @file core_sgeqp3_update.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mark Gates * @date 2010-11-15 * @generated s Tue Jan 7 11:44:49 2014 * **/ #include <math.h> #include <cblas.h> #include <lapacke.h> #include "common.h" #define A(m,n) BLKADDR( A, float, m, n ) /***************************************************************************//** * * @ingroup CORE_float * * CORE_sgeqp3_update updates row k of one tile of A * and subtracts that row from the column norms. * ******************************************************************************* * * @param[in] Ajj * Diagonal tile (jj,jj) of A. * * @param[in] lda1 * Leading dimension of Ajj. * * @param[in,out] Ajk * Tile (jj,kk) of A, kk >= jj. * On exit, updates row joff+k (i.e., as if Q was applied to trailing matrix). * * @param[in] lda2 * Leading dimension of Ajk. * * @param[in] Fk * Tile kk of F. * * @param[in] ldf * Leading dimension of Fk. * * @param[in] joff * Row offset. * * @param[in] k * Update row joff+k, based on having factored k columns. * (That is, joff columns of this tile were factored in previous panels; * k columns have been factored during this panel.) * * @param[in] koff * Column to start updating. * For diagonal tile, koff=joff+k+1, else koff=0. * * @param[in] nb * Number of columns in kk-th block-column of A. * * @param[in,out] norms1 * kk-th block of partial column norms vector, dimension nb. * On exit, norms1[koff:nb] -= Ajk[k, koff:nb ]. * * @param[in,out] norms2 * kk-th block of original column norms vector, dimension nb. * Unchanged on exit, except if cancellation is detected for * some column j, sets norm2[j] = -1 and sets info = 1. * * @param[out] info * Set to true if numerical instability (cancellation) is detected * in updating column norms. sgeqp3 handles this error. **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_sgeqp3_update = PCORE_sgeqp3_update #define CORE_sgeqp3_update PCORE_sgeqp3_update #endif void CORE_sgeqp3_update( const float *Ajj, int lda1, float *Ajk, int lda2, const float *Fk, int ldf, int joff, int k, int koff, int nb, float *norms1, float *norms2, int *info ) { float temp, temp2; float tol3z = sqrt( LAPACKE_slamch_work('e')); const float zone = 1.0; const float mzone = -1.0; int j; /* update row k of A -- this is vector*matrix */ /* Ajk[k,j:nb] -= Ajj[k,0:k+1] * Fk[j:nb,0:k+1].T */ cblas_sgemm( CblasColMajor, CblasNoTrans, CblasTrans, 1, nb-koff, k+1, (mzone), &Ajj[joff+k + joff*lda1], lda1, &Fk [koff ], ldf, (zone), &Ajk[joff+k + koff*lda2], lda2 ); for( j = koff; j < nb; ++j ) { if ( norms1[j] != 0. ) { /* NOTE: The following lines follow from the analysis in Lapack Working Note 176. */ temp = fabsf( Ajk[joff+k + j*lda2] ) / norms1[j]; temp = max( 0., (1. + temp)*(1. - temp) ); temp2 = norms1[j] / norms2[j]; temp2 = temp * temp2*temp2; norms1[j] = norms1[j]*sqrt( temp ); if( temp2 <= tol3z ) { /* flag numerical problem (i.e., cancellation) in updating norm. * norms1[j] will be re-computed. Above we stored the inaccurate * value anyway to allow comparison with the accurate value, for * easier debugging. */ norms2[j] = -1; *info = 1; } } } }
{ "alphanum_fraction": 0.5292633703, "avg_line_length": 32.7603305785, "ext": "c", "hexsha": "345c1dc722571bd63e92ca83a93aaf8e9bd3afeb", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas/core_sgeqp3_update.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas/core_sgeqp3_update.c", "max_line_length": 96, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_sgeqp3_update.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1117, "size": 3964 }
#ifdef __GNUC__ #define LIBKLR_API #else #ifdef LIBKLR_EXPORTS #define LIBKLR_API __declspec(dllexport) #else #define LIBKLR_API __declspec(dllimport) #endif #endif #pragma once #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #ifdef __APPLE__ #include <Accelerate/Accelerate.h> #else #include <cblas.h> #endif /* Matrix manipulation */ #define MAT(X, row, i, j) ((X)[(i)+(j)*row]) class LIBKLR_API Clibklr { int class_num; /* Number of classes */ int sample_num; /* Number of tatal MFCC's */ int itrKLR0; /* KLR0 iteration*/ int itrCG; /* Conjugate Gradient iteration */ int itrNewton; /* Newton method iteration*/ double tparam; /* if the error of gradient is less than tparam, stop CG*/ double *weight; /* Importance Weight*/ double delta; /* Generalization parameter for KLR*/ double *Vparam; /* KLR parameter*/ public: Clibklr(int c, int n); void set_class_num(int temp){class_num = temp;} void set_sample_num(int temp){sample_num = temp;} void set_itrKLR0(int temp){itrKLR0 = temp;} void set_itrCG(int temp){itrCG = temp;} void set_itrNewton(int temp){itrNewton = temp;} void set_tparam(double temp){tparam = temp;} void set_delta(double temp){delta = temp;} int get_class_num(void){return class_num;} int get_sample_num(void){return sample_num;} int get_itrKLR0(void){return itrKLR0;} int get_itrCG(void){return itrCG;} int get_itrNewton(void){return itrNewton;} double get_tparam(void){return tparam;} double get_delta(void){return delta;} void set_weight(double *inweight){ for(int i = 0; i < sample_num; i++){ weight[i] = inweight[i]; } } void get_V(double* Vexp){ for(int i = 0; i < class_num; i++){ for(int j = 0; j < sample_num; j++){ Vexp[(i)+(j)*class_num] = Vparam[(i)+(j)*class_num]; } } } /* Train Kernel Logistic Regression */ void train(double *Ktrain, int *label); /* Test KLR (vector kernel)*/ double* test(double *Ktest, int n_test, double* V, int c, int n_train); /* Conjugate Gradient Method*/ void CG(double*,double*, double*,double*,int,int,double*,int); /* Label matrix generation*/ void yconst(int*, double*, int, int); /* Logistic Transform*/ void mlogistic(double*, int, int); /* Norm computation */ double norm(double *input, int c, int n); int* malloc_int(int n); double* malloc_double(int n); int display_array(double*, const int, const int); }; extern LIBKLR_API int nlibklr; LIBKLR_API int fnlibklr(void);
{ "alphanum_fraction": 0.6753246753, "avg_line_length": 27.9230769231, "ext": "h", "hexsha": "1c28c254a2d5333a1a999578d1d1b51d11429d28", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "chungying/nuklei", "max_forks_repo_path": "contrib/libklr-2010_05_07/src/libklr.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "chungying/nuklei", "max_issues_repo_path": "contrib/libklr-2010_05_07/src/libklr.h", "max_line_length": 82, "max_stars_count": null, "max_stars_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "chungying/nuklei", "max_stars_repo_path": "contrib/libklr-2010_05_07/src/libklr.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 699, "size": 2541 }
#include <php.h> #include <Zend/zend_interfaces.h> #include <Zend/zend_exceptions.h> #include <ext/spl/spl_iterators.h> #include <ext/spl/spl_exceptions.h> #include <ext/standard/php_rand.h> #include <cblas.h> #include <stdint.h> #include <Interop/Polite/Math/Matrix.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php_rindow_openblas.h" static float s_max(zend_long n,float *x,zend_long incX) { zend_long i; float a; a = x[0]; for(i=1;i<n;i++) { if(a<x[i*incX]) { a = x[i*incX]; } } return a; } static double d_max(zend_long n,double *x,zend_long incX) { zend_long i; double a; a = x[0]; for(i=1;i<n;i++) { if(a<x[i*incX]) { a = x[i*incX]; } } return a; } static zend_long s_argmax(zend_long n,float *x,zend_long incX) { zend_long i; zend_long idx; float a; idx = 0; a = x[0]; for(i=1;i<n;i++) { if(a<x[i*incX]) { idx = i; a = x[i*incX]; } } return idx; } static zend_long d_argmax(zend_long n,double *x,zend_long incX) { zend_long i; zend_long idx; double a; idx = 0; a = x[0]; for(i=1;i<n;i++) { if(a<x[i*incX]) { idx = i; a = x[i*incX]; } } return idx; } static float s_sum(zend_long n,float *x,zend_long incX) { zend_long i; float a=0; for(i=0; i<n; i++) { a += x[i*incX]; } return a; } static double d_sum(zend_long n,double *x,zend_long incX) { zend_long i; double a=0; for(i=0; i<n; i++) { a += x[i*incX]; } return a; } static zend_object_handlers rindow_openblas_math_object_handlers; // destractor static void php_rindow_openblas_math_free_object(zend_object* object) { zend_object_std_dtor(object); } // constructor static zend_object* php_rindow_openblas_math_create_object(zend_class_entry* class_type) /* {{{ */ { zend_object* intern = NULL; intern = (zend_object*)ecalloc(1, sizeof(zend_object) + zend_object_properties_size(class_type)); zend_object_std_init(intern, class_type); object_properties_init(intern, class_type); intern->handlers = &rindow_openblas_math_object_handlers; return intern; } /* }}} */ #define PHP_RINDOW_OPENBLAS_MATH_SUM_TEMPLATE(data_type) { \ data_type *pDataX; \ pDataX = &(((data_type *)buffer->data)[offsetX]); \ result = 0.0; \ for (i=0; i<n; i++,pDataX+=incX) { \ result += (data_type)*pDataX; \ } \ } int php_rindow_openblas_val2int( zval* val_value, zend_long* integer_value, char* message) { switch(Z_TYPE_P(val_value)) { case IS_LONG: *integer_value = Z_LVAL_P(val_value); break; case IS_DOUBLE: *integer_value = (zend_long)Z_DVAL_P(val_value); break; default: zend_throw_exception(spl_ce_InvalidArgumentException, message, 0); return -1; } return 0; } int php_rindow_openblas_val2float( zval* val_value, double* float_value, char* message) { switch(Z_TYPE_P(val_value)) { case IS_LONG: *float_value = (double)Z_LVAL_P(val_value); break; case IS_DOUBLE: *float_value = Z_DVAL_P(val_value); break; default: zend_throw_exception(spl_ce_InvalidArgumentException, message, 0); return -1; } return 0; } #define PHP_RINDOW_OPENBLAS_MATH_ADD_TEMPLATE(data_type) { \ data_type *pDataX; \ data_type *pDataY; \ pDataX = (data_type *)values; \ pDataY = (data_type *)target; \ for (i=0; i<n; i++) { \ *pDataY += *pDataX; \ pDataX+=incValue; \ pDataY+=incTarget; \ } \ } int php_rindow_openblas_math_add( zend_long n, zend_long dtype, void* values, zend_long incValue, void* target, zend_long incTarget ) { switch (dtype) { zend_long i; case php_interop_polite_math_matrix_dtype_float32: PHP_RINDOW_OPENBLAS_MATH_ADD_TEMPLATE(float) break; case php_interop_polite_math_matrix_dtype_float64: PHP_RINDOW_OPENBLAS_MATH_ADD_TEMPLATE(double) break; case php_interop_polite_math_matrix_dtype_int8: PHP_RINDOW_OPENBLAS_MATH_ADD_TEMPLATE(int8_t) break; case php_interop_polite_math_matrix_dtype_uint8: PHP_RINDOW_OPENBLAS_MATH_ADD_TEMPLATE(uint8_t) break; case php_interop_polite_math_matrix_dtype_int16: PHP_RINDOW_OPENBLAS_MATH_ADD_TEMPLATE(int16_t) break; case php_interop_polite_math_matrix_dtype_uint16: PHP_RINDOW_OPENBLAS_MATH_ADD_TEMPLATE(uint16_t) break; case php_interop_polite_math_matrix_dtype_int32: PHP_RINDOW_OPENBLAS_MATH_ADD_TEMPLATE(int32_t) break; case php_interop_polite_math_matrix_dtype_uint32: PHP_RINDOW_OPENBLAS_MATH_ADD_TEMPLATE(uint32_t) break; case php_interop_polite_math_matrix_dtype_int64: PHP_RINDOW_OPENBLAS_MATH_ADD_TEMPLATE(int64_t) break; case php_interop_polite_math_matrix_dtype_uint64: PHP_RINDOW_OPENBLAS_MATH_ADD_TEMPLATE(uint64_t) break; default: zend_throw_exception(spl_ce_InvalidArgumentException, "Unsupported data type.", 0); return -1; } return 0; } #define PHP_RINDOW_OPENBLAS_MATH_COPY_TEMPLATE(data_type) { \ data_type *pDataX; \ data_type *pDataY; \ pDataX = (data_type *)source; \ pDataY = (data_type *)dest; \ for (i=0; i<n; i++) { \ *pDataY += *pDataX; \ pDataX+=incSource; \ pDataY+=incDest; \ } \ } int php_rindow_openblas_math_copy( zend_long n, zend_long dtype, void* source, zend_long incSource, void* dest, zend_long incDest ) { switch (dtype) { zend_long i; case php_interop_polite_math_matrix_dtype_float32: PHP_RINDOW_OPENBLAS_MATH_COPY_TEMPLATE(float) break; case php_interop_polite_math_matrix_dtype_float64: PHP_RINDOW_OPENBLAS_MATH_COPY_TEMPLATE(double) break; case php_interop_polite_math_matrix_dtype_int8: PHP_RINDOW_OPENBLAS_MATH_COPY_TEMPLATE(int8_t) break; case php_interop_polite_math_matrix_dtype_uint8: PHP_RINDOW_OPENBLAS_MATH_COPY_TEMPLATE(uint8_t) break; case php_interop_polite_math_matrix_dtype_int16: PHP_RINDOW_OPENBLAS_MATH_COPY_TEMPLATE(int16_t) break; case php_interop_polite_math_matrix_dtype_uint16: PHP_RINDOW_OPENBLAS_MATH_COPY_TEMPLATE(uint16_t) break; case php_interop_polite_math_matrix_dtype_int32: PHP_RINDOW_OPENBLAS_MATH_COPY_TEMPLATE(int32_t) break; case php_interop_polite_math_matrix_dtype_uint32: PHP_RINDOW_OPENBLAS_MATH_COPY_TEMPLATE(uint32_t) break; case php_interop_polite_math_matrix_dtype_int64: PHP_RINDOW_OPENBLAS_MATH_COPY_TEMPLATE(int64_t) break; case php_interop_polite_math_matrix_dtype_uint64: PHP_RINDOW_OPENBLAS_MATH_COPY_TEMPLATE(uint64_t) break; default: zend_throw_exception(spl_ce_InvalidArgumentException, "Unsupported data type.", 0); return -1; } return 0; } /* Method Rindow\OpenBLAS\Math:: public function sum( int $n, Buffer $X, int $offsetX, int $incX ) : float {{{ */ static PHP_METHOD(Math, sum) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; double result; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { zend_long i; case php_interop_polite_math_matrix_dtype_float32: PHP_RINDOW_OPENBLAS_MATH_SUM_TEMPLATE(float) break; case php_interop_polite_math_matrix_dtype_float64: PHP_RINDOW_OPENBLAS_MATH_SUM_TEMPLATE(double) break; case php_interop_polite_math_matrix_dtype_int8: PHP_RINDOW_OPENBLAS_MATH_SUM_TEMPLATE(int8_t) break; case php_interop_polite_math_matrix_dtype_uint8: PHP_RINDOW_OPENBLAS_MATH_SUM_TEMPLATE(uint8_t) break; case php_interop_polite_math_matrix_dtype_int16: PHP_RINDOW_OPENBLAS_MATH_SUM_TEMPLATE(int16_t) break; case php_interop_polite_math_matrix_dtype_uint16: PHP_RINDOW_OPENBLAS_MATH_SUM_TEMPLATE(uint16_t) break; case php_interop_polite_math_matrix_dtype_int32: PHP_RINDOW_OPENBLAS_MATH_SUM_TEMPLATE(int32_t) break; case php_interop_polite_math_matrix_dtype_uint32: PHP_RINDOW_OPENBLAS_MATH_SUM_TEMPLATE(uint32_t) break; case php_interop_polite_math_matrix_dtype_int64: PHP_RINDOW_OPENBLAS_MATH_SUM_TEMPLATE(int64_t) break; case php_interop_polite_math_matrix_dtype_uint64: PHP_RINDOW_OPENBLAS_MATH_SUM_TEMPLATE(uint64_t) break; case php_interop_polite_math_matrix_dtype_bool: { uint8_t *pBoolX; pBoolX = &(((uint8_t *)buffer->data)[offsetX]); result = 0.0; for (i=0; i<n; i++,pBoolX+=incX) { if(*pBoolX!=0) { result += 1; } } } break; default: zend_throw_exception(spl_ce_InvalidArgumentException, "Unsupported data type.", 0); return; } RETURN_DOUBLE(result); } /* }}} */ /* Method Rindow\OpenBLAS\Math:: public function imax( int $n, Buffer $X, int $offsetX, int $incX) : int {{{ */ static PHP_METHOD(Math, imax) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; float *pFloatX; double *pDoubleX; float floatMax; double doubleMax; zend_long resultIdx; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { zend_long i; case php_interop_polite_math_matrix_dtype_float32: pFloatX = &(((float *)buffer->data)[offsetX]); floatMax = *pFloatX; pFloatX += incX; resultIdx = 0; for (i=1; i<n; i++,pFloatX+=incX) { if(floatMax < *pFloatX) { floatMax = *pFloatX; resultIdx = i; } } break; case php_interop_polite_math_matrix_dtype_float64: pDoubleX = &(((double *)buffer->data)[offsetX]); doubleMax = *pDoubleX; pDoubleX += incX; resultIdx = 0; for (i=1; i<n; i++,pDoubleX+=incX) { if(doubleMax < *pDoubleX) { doubleMax = *pDoubleX; resultIdx = i; } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } RETURN_LONG(resultIdx); } /* }}} */ /* Method Rindow\OpenBLAS\Math:: public function imin( int $n, Buffer $X, int $offsetX, int $incX) : int {{{ */ static PHP_METHOD(Math, imin) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; float *pFloatX; double *pDoubleX; float floatMin; double doubleMin; zend_long resultIdx; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { zend_long i; case php_interop_polite_math_matrix_dtype_float32: pFloatX = &(((float *)buffer->data)[offsetX]); floatMin = *pFloatX; pFloatX += incX; resultIdx = 0; for (i=1; i<n; i++,pFloatX+=incX) { if(floatMin > *pFloatX) { floatMin = *pFloatX; resultIdx = i; } } break; case php_interop_polite_math_matrix_dtype_float64: pDoubleX = &(((double *)buffer->data)[offsetX]); doubleMin = *pDoubleX; pDoubleX += incX; resultIdx = 0; for (i=1; i<n; i++,pDoubleX+=incX) { if(doubleMin > *pDoubleX) { doubleMin = *pDoubleX; resultIdx = i; } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } RETURN_LONG(resultIdx); } /* }}} */ /* X := a*X + b Method Rindow\OpenBLAS\Math:: public function increment( int $n, float $alpha, Buffer $X, int $offsetX, int $incX, float $beta) : void {{{ */ static PHP_METHOD(Math, increment) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; double alpha; double beta; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long i; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 6, 6) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_DOUBLE(beta) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { x[i*incX] = (float)alpha * x[i*incX] + (float)beta; } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { x[i*incX] = (double)alpha * x[i*incX] + (double)beta; } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* X := 1 / (a*X + b) Method Rindow\OpenBLAS\Math:: public function reciprocal( int $n, float $alpha, Buffer $X, int $offsetX, int $incX, float $beta) : void {{{ */ static PHP_METHOD(Math, reciprocal) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; double alpha; double beta; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long i; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 6, 6) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_DOUBLE(beta) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { float t; t = (float)alpha * x[i*incX] + (float)beta; if(t==0.0) { zend_throw_exception(spl_ce_RuntimeException, "Zero divide.", 0); return; } x[i*incX] = 1 / t; } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { double t; t = (double)alpha * x[i*incX] + (double)beta; if(t==0.0) { zend_throw_exception(spl_ce_RuntimeException, "Zero divide.", 0); return; } x[i*incX] = 1 / t; } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* X := X (X > a) X := a (X <= a) Method Rindow\OpenBLAS\Math:: public function maximum( int $n, float $alpha, Buffer $X, int $offsetX, int $incX) : void {{{ */ static PHP_METHOD(Math, maximum) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; double alpha; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long i; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 5, 5) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { if((float)alpha > x[i*incX]) { x[i*incX] = (float)alpha; } } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { if((double)alpha > x[i*incX]) { x[i*incX] = (double)alpha; } } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* X := X (X < a) X := a (X >= a) Method Rindow\OpenBLAS\Math:: public function minimum( int $n, float $alpha, Buffer $X, int $offsetX, int $incX) : void {{{ */ static PHP_METHOD(Math, minimum) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; double alpha; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long i; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 5, 5) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { if((float)alpha < x[i*incX]) { x[i*incX] = (float)alpha; } } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { if((double)alpha < x[i*incX]) { x[i*incX] = (double)alpha; } } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* X := 1 (X > a) X := 0 (X <= a) Method Rindow\OpenBLAS\Math:: public function greater( int $n, float $alpha, Buffer $X, int $offsetX, int $incX) : void {{{ */ static PHP_METHOD(Math, greater) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; double alpha; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long i; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 5, 5) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { if(x[i*incX] > (float)alpha) { x[i*incX] = 1.0; } else { x[i*incX] = 0.0; } } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { if(x[i*incX] > (double)alpha) { x[i*incX] = 1.0; } else { x[i*incX] = 0.0; } } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* X := 1 (X < a) X := 0 (X >= a) Method Rindow\OpenBLAS\Math:: public function less( int $n, float $alpha, Buffer $X, int $offsetX, int $incX) : void {{{ */ static PHP_METHOD(Math, less) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; double alpha; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long i; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 5, 5) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { if(x[i*incX] < (float)alpha) { x[i*incX] = 1.0; } else { x[i*incX] = 0.0; } } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { if(x[i*incX] < (double)alpha) { x[i*incX] = 1.0; } else { x[i*incX] = 0.0; } } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* A(i) := X(i) * A(i) Method Rindow\OpenBLAS\Math:: public function multiply( bool $trans, int $m, int $n, Buffer $X, int $offsetX, int $incX, Buffer $A, int $offsetA, int $ldA ) : void {{{ */ static PHP_METHOD(Math, multiply) { php_interop_polite_math_matrix_linear_buffer_t* bufferX; php_interop_polite_math_matrix_linear_buffer_t* bufferA; zend_bool trans; zend_long m; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; zval* a=NULL; zend_long offsetA; zend_long ldA; zend_long rows,cols; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 9, 9) Z_PARAM_BOOL(trans) Z_PARAM_LONG(m) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_LONG(ldA) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_M, m)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer X bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(bufferX,"x")) { return; } if(!trans) { rows = m; cols = n; } else { rows = n; cols = m; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,cols,offsetX,incX)) { return; } // Check Buffer A bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(bufferA,"a")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,m,n,offsetA,ldA)) { return; } // Check Buffer X and A if(bufferX->dtype!=bufferA->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for X and A", 0); return; } switch (bufferX->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)bufferX->data)[offsetX]); float *a = &(((float *)bufferA->data)[offsetA]); zend_long i,j,incAj,incAi; if(!trans) { incAj = ldA; incAi = 1;} else { incAj = 1; incAi = ldA;} for(j=0; j<rows; j++) { for(i=0; i<cols; i++) { a[j*incAj+i*incAi] = x[i*incX] * a[j*incAj+i*incAi]; } } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)bufferX->data)[offsetX]); double *a = &(((double *)bufferA->data)[offsetA]); zend_long i,j,incAj,incAi; if(!trans) { incAj = ldA; incAi = 1;} else { incAj = 1; incAi = ldA;} for(j=0; j<rows; j++) { for(i=0; i<cols; i++) { a[j*incAj+i*incAi] = x[i*incX] * a[j*incAj+i*incAi]; } } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* A(i) := alpha * X(i) + A(i) Method Rindow\OpenBLAS\Math:: public function add( int $trans, int $m, int $n, float $alpha, Buffer $X, int $offsetX, int $incX, Buffer $A, int $offsetA, int $ldA ) : void {{{ */ static PHP_METHOD(Math, add) { php_interop_polite_math_matrix_linear_buffer_t* bufferX; php_interop_polite_math_matrix_linear_buffer_t* bufferA; zend_bool trans; zend_long m; zend_long n; double alpha; zval* x=NULL; zend_long offsetX; zend_long incX; zval* a=NULL; zend_long offsetA; zend_long ldA; zend_long rows,cols; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 10, 10) Z_PARAM_BOOL(trans) Z_PARAM_LONG(m) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_LONG(ldA) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_M, m)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer X bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(bufferX,"x")) { return; } if(!trans) { rows = m; cols = n; } else { rows = n; cols = m; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,cols,offsetX,incX)) { return; } // Check Buffer A bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(bufferA,"a")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,m,n,offsetA,ldA)) { return; } // Check Buffer X and A if(bufferX->dtype!=bufferA->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for X and A", 0); return; } switch (bufferX->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)bufferX->data)[offsetX]); float *a = &(((float *)bufferA->data)[offsetA]); zend_long j,incAj,incAi; if(!trans) { incAj = ldA; incAi = 1;} else { incAj = 1; incAi = ldA;} for(j=0; j<rows; j++) { cblas_saxpy((blasint)cols,(float)alpha, (float*)x,(blasint)incX, (float*)(&a[j*incAj]),(blasint)incAi); } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)bufferX->data)[offsetX]); double *a = &(((double *)bufferA->data)[offsetA]); zend_long j,incAj,incAi; if(!trans) { incAj = ldA; incAi = 1;} else { incAj = 1; incAi = ldA;} for(j=0; j<rows; j++) { cblas_daxpy((blasint)cols,(double)alpha, (double*)x,(blasint)incX, (double*)(&a[j*incAj]),(blasint)incAi); } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* A(m,n) := X(n) Method Rindow\OpenBLAS\Math:: public function duplicate( bool $trans, int $m, int $n, Buffer $X, int $offsetX, int $incX, Buffer $A, int $offsetA, int $ldA ) : void {{{ */ static PHP_METHOD(Math, duplicate) { php_interop_polite_math_matrix_linear_buffer_t* bufferX; php_interop_polite_math_matrix_linear_buffer_t* bufferA; zend_bool trans; zend_long m; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; zval* a=NULL; zend_long offsetA; zend_long ldA; zend_long rows,cols; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 9, 9) Z_PARAM_BOOL(trans) Z_PARAM_LONG(m) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_LONG(ldA) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_M, m)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } if(!trans) { rows = m; cols = n; } else { rows = n; cols = m; } // Check Buffer X bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(bufferX,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,cols,offsetX,incX)) { return; } // Check Buffer A bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(bufferA,"a")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,m,n,offsetA,ldA)) { return; } // Check Buffer X and Y if(bufferX->dtype!=bufferA->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for X and Y", 0); return; } switch (bufferX->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)bufferX->data)[offsetX]); float *a = &(((float *)bufferA->data)[offsetA]); zend_long j,incAj,incAi; if(!trans) { incAj = ldA; incAi = 1;} else { incAj = 1; incAi = ldA;} for(j=0; j<rows; j++) { cblas_scopy((blasint)cols, x, (blasint)incX, &(a[j*incAj]), (blasint)incAi); } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)bufferX->data)[offsetX]); double *a = &(((double *)bufferA->data)[offsetA]); zend_long j,incAj,incAi; if(!trans) { incAj = ldA; incAi = 1;} else { incAj = 1; incAi = ldA;} for(j=0; j<rows; j++) { cblas_dcopy((blasint)n, x, (blasint)incX, &(a[j*incAj]), (blasint)incAi); } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* X := X ^ 2 Method Rindow\OpenBLAS\Math:: public function square( int $n, Buffer $X, int $offsetX, int $incX) : void {{{ */ static PHP_METHOD(Math, square) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long i; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { x[i*incX] = x[i*incX] * x[i*incX]; } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { x[i*incX] = x[i*incX] * x[i*incX]; } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* X := sqrt(X) Method Rindow\OpenBLAS\Math:: public function sqrt( int $n, Buffer $X, int $offsetX, int $incX) : void {{{ */ static PHP_METHOD(Math, sqrt) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long i; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { float t; t = x[i*incX]; if(t<0.0) { zend_throw_exception(spl_ce_RuntimeException, "Invalid value in sqrt.", 0); return; } x[i*incX] = sqrtf(t); } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { double t; t = x[i*incX]; if(t<0.0) { zend_throw_exception(spl_ce_RuntimeException, "Invalid value in sqrt.", 0); return; } x[i*incX] = sqrt(t); } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* X := 1 / (a * sqrt(X) + b) Method Rindow\OpenBLAS\Math:: public function rsqrt( int $n, float $alpha, Buffer $X, int $offsetX, int $incX, float $beta) : void {{{ */ static PHP_METHOD(Math, rsqrt) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; double alpha; double beta; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long i; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 6, 6) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_DOUBLE(beta) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { float t; if(x[i*incX]<0.0) { zend_throw_exception(spl_ce_RuntimeException, "Invalid value in sqrt.", 0); return; } t = (float)alpha * sqrtf(x[i*incX]) + (float)beta; if(t==0.0) { zend_throw_exception(spl_ce_RuntimeException, "Zero divide.", 0); return; } x[i*incX] = 1 / t; } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { double t; if(x[i*incX]<0.0) { zend_throw_exception(spl_ce_RuntimeException, "Invalid value in sqrt.", 0); return; } t = (double)alpha * sqrt(x[i*incX]) + (double)beta; if(t==0.0) { zend_throw_exception(spl_ce_RuntimeException, "Zero divide.", 0); return; } x[i*incX] = 1 / t; } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* X := X ^ a Method Rindow\OpenBLAS\Math:: public function pow( int $n, float $alpha, Buffer $X, int $offsetX, int $incX) : void {{{ */ static PHP_METHOD(Math, pow) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; double alpha; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long i; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 5, 5) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { x[i*incX] = powf(x[i*incX], (float)alpha); } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { x[i*incX] = pow(x[i*incX], (double)alpha); } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* X(i) := e ^ X(i) Method Rindow\OpenBLAS\Math:: public function exp( int $n, Buffer $X, int $offsetX, int $incX) : void {{{ */ static PHP_METHOD(Math, exp) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long i; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { x[i*incX] = expf(x[i*incX]); } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { x[i*incX] = exp(x[i*incX]); } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* X := log(X) Method Rindow\OpenBLAS\Math:: public function log( int $n, Buffer $X, int $offsetX, int $incX) : void {{{ */ static PHP_METHOD(Math, log) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long i; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { float t; t = x[i*incX]; if(t<=0.0) { zend_throw_exception(spl_ce_RuntimeException, "Invalid value in log.", 0); return; } x[i*incX] = logf(t); } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { double t; t = x[i*incX]; if(t<=0.0) { zend_throw_exception(spl_ce_RuntimeException, "Invalid value in log.", 0); return; } x[i*incX] = log(t); } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* X := tanh(X) Method Rindow\OpenBLAS\Math:: public function tanh( int $n, Buffer $X, int $offsetX, int $incX) : void {{{ */ static PHP_METHOD(Math, tanh) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; zend_long i; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { float t; t = x[i*incX]; x[i*incX] = tanhf(t); } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { double t; t = x[i*incX]; x[i*incX] = tanh(t); } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* X := 0 Method Rindow\OpenBLAS\Math:: public function zeros( int $n, Buffer $X, int $offsetX, int $incX) : void {{{ */ static PHP_METHOD(Math, zeros) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(buffer,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { zend_long i; float *x = &(((float *)buffer->data)[offsetX]); for(i=0;i<n;i++) { x[i*incX] = 0; } } break; case php_interop_polite_math_matrix_dtype_float64: { zend_long i; double *x = &(((double *)buffer->data)[offsetX]); for(i=0;i<n;i++) { x[i*incX] = 0; } } break; default: { zend_long i; int valueSize; uint8_t *x; valueSize = php_rindow_openblas_common_dtype_to_valuesize(buffer->dtype); x = php_rindow_openblas_get_address(buffer,offsetX,valueSize); if(incX==1) { memset(x,0,valueSize*n); } else { for(i=0;i<n;i++) { memset(&x[i*incX],0,valueSize); } } } break; } } /* }}} */ #define RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(data_type,get_type) { \ data_type *x = &(((data_type *)buffer)[offset]); \ *value = (get_type)(x[index*incWidth]); \ return 0; \ } #define RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(data_type) { \ data_type *x = &(((data_type *)buffer)[offset]); \ x[index*incWidth] = (data_type)value; \ return 0; \ } static int rindow_openblas_math_get_integer( zend_long dtype,void *buffer, zend_long offset,zend_long incWidth, zend_long index, zend_long *value) { switch (dtype) { case php_interop_polite_math_matrix_dtype_bool: { uint8_t *x = &(((uint8_t *)buffer)[offset]); if(x[index*incWidth]==0) { *value=0; return 0; } else { *value=1; return 0; } } case php_interop_polite_math_matrix_dtype_int8: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(int8_t,zend_long); case php_interop_polite_math_matrix_dtype_uint8: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(uint8_t,zend_long); case php_interop_polite_math_matrix_dtype_int16: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(int16_t,zend_long); case php_interop_polite_math_matrix_dtype_uint16: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(uint16_t,zend_long); case php_interop_polite_math_matrix_dtype_int32: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(int32_t,zend_long); case php_interop_polite_math_matrix_dtype_uint32: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(uint32_t,zend_long); case php_interop_polite_math_matrix_dtype_int64: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(int64_t,zend_long); case php_interop_polite_math_matrix_dtype_uint64: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(uint64_t,zend_long); case php_interop_polite_math_matrix_dtype_float32: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(float,zend_long); case php_interop_polite_math_matrix_dtype_float64: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(double,zend_long); default: return -1; } } static int rindow_openblas_math_set_integer( zend_long dtype,void *buffer, zend_long offset,zend_long incWidth, zend_long index, zend_long value) { switch (dtype) { case php_interop_polite_math_matrix_dtype_bool: { uint8_t *x = &(((uint8_t *)buffer)[offset]); if(value==0) { x[index*incWidth]=0; return 0; } else { x[index*incWidth]=1; return 0; } } case php_interop_polite_math_matrix_dtype_int8: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(int8_t); case php_interop_polite_math_matrix_dtype_uint8: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(uint8_t); case php_interop_polite_math_matrix_dtype_int16: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(int16_t); case php_interop_polite_math_matrix_dtype_uint16: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(uint16_t); case php_interop_polite_math_matrix_dtype_int32: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(int32_t); case php_interop_polite_math_matrix_dtype_uint32: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(uint32_t); case php_interop_polite_math_matrix_dtype_int64: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(int64_t); case php_interop_polite_math_matrix_dtype_uint64: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(uint64_t); case php_interop_polite_math_matrix_dtype_float32: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(float); case php_interop_polite_math_matrix_dtype_float64: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(double); default: return -1; } } static int rindow_openblas_math_get_float( zend_long dtype,void *buffer, zend_long offset,zend_long incWidth, zend_long index, double *value) { switch (dtype) { case php_interop_polite_math_matrix_dtype_bool: { uint8_t *x = &(((uint8_t *)buffer)[offset]); if(x[index*incWidth]==0) { *value=0; return 0; } else { *value=1; return 0; } } case php_interop_polite_math_matrix_dtype_int8: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(int8_t,double); case php_interop_polite_math_matrix_dtype_uint8: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(uint8_t,double); case php_interop_polite_math_matrix_dtype_int16: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(int16_t,double); case php_interop_polite_math_matrix_dtype_uint16: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(uint16_t,double); case php_interop_polite_math_matrix_dtype_int32: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(int32_t,double); case php_interop_polite_math_matrix_dtype_uint32: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(uint32_t,double); case php_interop_polite_math_matrix_dtype_int64: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(int64_t,double); case php_interop_polite_math_matrix_dtype_uint64: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(uint64_t,double); case php_interop_polite_math_matrix_dtype_float32: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(float,double); case php_interop_polite_math_matrix_dtype_float64: RINDOW_OPENBLAS_MATH_GET_CAST_TEMPLATE(double,double); default: return -1; } } static int rindow_openblas_math_set_float( zend_long dtype,void *buffer, zend_long offset,zend_long incWidth, zend_long index, double value) { switch (dtype) { case php_interop_polite_math_matrix_dtype_bool: { uint8_t *x = &(((uint8_t *)buffer)[offset]); if(value==0) { x[index*incWidth]=0; return 0; } else { x[index*incWidth]=1; return 0; } } case php_interop_polite_math_matrix_dtype_int8: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(int8_t); case php_interop_polite_math_matrix_dtype_uint8: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(uint8_t); case php_interop_polite_math_matrix_dtype_int16: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(int16_t); case php_interop_polite_math_matrix_dtype_uint16: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(uint16_t); case php_interop_polite_math_matrix_dtype_int32: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(int32_t); case php_interop_polite_math_matrix_dtype_uint32: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(uint32_t); case php_interop_polite_math_matrix_dtype_int64: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(int64_t); case php_interop_polite_math_matrix_dtype_uint64: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(uint64_t); case php_interop_polite_math_matrix_dtype_float32: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(float); case php_interop_polite_math_matrix_dtype_float64: RINDOW_OPENBLAS_MATH_SET_CAST_TEMPLATE(double); default: return -1; } } /* Y := a * onehot(X) + Y Method Rindow\OpenBLAS\Math:: public function updateAddOnehot( int $m, int $n, float $a, Buffer $X, int $offsetX, int $incX, Buffer $Y, int $offsetY, int $ldY ) : void {{{ */ static PHP_METHOD(Math, updateAddOnehot) { php_interop_polite_math_matrix_linear_buffer_t* bufferX; php_interop_polite_math_matrix_linear_buffer_t* bufferY; zend_long m; zend_long n; double a; zval* x=NULL; zend_long offsetX; zend_long incX; zval* y=NULL; zend_long offsetY; zend_long ldY; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 9, 9) Z_PARAM_LONG(m) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(a) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_OBJECT(y) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetY) Z_PARAM_LONG(ldY) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_M, m)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer X bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(bufferX,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,m,offsetX,incX)) { return; } // Check Buffer Y bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y); if(php_rindow_openblas_assert_buffer_type(bufferY,"y")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,m,n,offsetY,ldY)) { return; } // Check Buffer A and Y if(bufferX->dtype==php_interop_polite_math_matrix_dtype_bool) { zend_throw_exception(spl_ce_InvalidArgumentException, "Data type of BufferX must not be bool", 0); return; } switch (bufferY->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *y = &(((float *)bufferY->data)[offsetY]); zend_long i,selector; for(i=0; i<m; i++) { if(rindow_openblas_math_get_integer( bufferX->dtype, bufferX->data, offsetX,incX, i, &selector)) { zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type of label number.", 0); return; } if(selector<0||selector>=n) { zend_throw_exception(spl_ce_RuntimeException, "Label number is out of bounds.", 0); return; } y[i*ldY+selector] += (float)a; } } break; case php_interop_polite_math_matrix_dtype_float64: { double *y = &(((double *)bufferY->data)[offsetY]); zend_long i,selector; for(i=0; i<m; i++) { if(rindow_openblas_math_get_integer( bufferX->dtype, bufferX->data, offsetX,incX, i, &selector)) { zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type of label number.", 0); return; } if(selector<0||selector>=n) { zend_throw_exception(spl_ce_RuntimeException, "Label number is out of bounds.", 0); return; } y[i*ldY+selector] += (double)a; } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* A := softmax(A) Method Rindow\OpenBLAS\Math:: public function softmax( int $m, int $n, Buffer $A, int $offsetA, int $ldA) : void {{{ */ static PHP_METHOD(Math, softmax) { php_interop_polite_math_matrix_linear_buffer_t* buffer; zend_long m; zend_long n; zval* a=NULL; zend_long offsetA; zend_long ldA; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 5, 5) Z_PARAM_LONG(m) Z_PARAM_LONG(n) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_LONG(ldA) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_M, m)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(buffer,"a")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_A, buffer,m,n,offsetA,ldA)) { return; } switch (buffer->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *a = &(((float *)buffer->data)[offsetA]); zend_long i,j; for(i=0;i<m;i++,a+=ldA) { float t,max_a,sum_exp; max_a = s_max(n,a,1); sum_exp = 0; for(j=0;j<n;j++) { t = expf(a[j]-max_a); sum_exp += t; a[j] = t; } if(sum_exp==0.0) { zend_throw_exception(spl_ce_RuntimeException, "Zero divide in softmax.", 0); return; } for(j=0;j<n;j++) { a[j] = a[j] / sum_exp; } } } break; case php_interop_polite_math_matrix_dtype_float64: { double *a = &(((double *)buffer->data)[offsetA]); zend_long i,j; for(i=0;i<m;i++,a+=ldA) { double t,max_a,sum_exp; max_a = d_max(n,a,1); sum_exp = 0; for(j=0;j<n;j++) { t = exp(a[j]-max_a); sum_exp += t; a[j] = t; } if(sum_exp==0.0) { zend_throw_exception(spl_ce_RuntimeException, "Zero divide in softmax.", 0); return; } for(j=0;j<n;j++) { a[j] = a[j] / sum_exp; } } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* Y(i) := 1 ( X(i) == Y(i) ) Y(i) := 0 ( X(i) != Y(i) ) Method Rindow\OpenBLAS\Math:: public function equal( int $n, Buffer $X, int $offsetX, int $incX, Buffer $Y, int $offsetY, int $incY ) : void {{{ */ static PHP_METHOD(Math, equal) { php_interop_polite_math_matrix_linear_buffer_t* bufferX; php_interop_polite_math_matrix_linear_buffer_t* bufferY; zend_long n; zval* x=NULL; zend_long offsetX; zend_long incX; zval* y=NULL; zend_long offsetY; zend_long incY; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 7, 7) Z_PARAM_LONG(n) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_OBJECT(y) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetY) Z_PARAM_LONG(incY) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer X bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(bufferX,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,n,offsetX,incX)) { return; } // Check Buffer Y bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y); if(php_rindow_openblas_assert_buffer_type(bufferX,"y")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,n,offsetY,incY)) { return; } // Check Buffer X and Y if(bufferX->dtype!=bufferY->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for X and Y", 0); return; } switch (bufferX->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *x = &(((float *)bufferX->data)[offsetX]); float *y = &(((float *)bufferY->data)[offsetY]); zend_long i; for(i=0; i<n; i++) { if(x[i*incX] == y[i*incY]) y[i*incY] = 1; else y[i*incY] = 0; } } break; case php_interop_polite_math_matrix_dtype_float64: { double *x = &(((double *)bufferX->data)[offsetX]); double *y = &(((double *)bufferY->data)[offsetY]); zend_long i; for(i=0; i<n; i++) { if(x[i*incX] == y[i*incY]) y[i*incY] = 1; else y[i*incY] = 0; } } break; default: if(!php_rindow_openblas_common_dtype_is_int(bufferX->dtype)&& !php_rindow_openblas_common_dtype_is_bool(bufferX->dtype)) { zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } { int valueSize; uint8_t *x, *y; zend_long i,zero,one; zero = 0; one = 1; valueSize = php_rindow_openblas_common_dtype_to_valuesize(bufferX->dtype); x = php_rindow_openblas_get_address(bufferX,offsetX,valueSize); y = php_rindow_openblas_get_address(bufferY,offsetY,valueSize); for(i=0; i<n; i++) { if(memcmp(&x[i*incX*valueSize],&y[i*incY*valueSize],valueSize)==0) { memcpy(&y[i*incY*valueSize],&one,valueSize); } else { memcpy(&y[i*incY*valueSize],&zero,valueSize); } } } break; } } /* }}} */ /* Y := cast<dtype> X Method Rindow\OpenBLAS\Math:: public function astype( int $n, int $dtype, Buffer $X, int $offsetX, int $incX, Buffer $Y, int $offsetY, int $incY) : void {{{ */ static PHP_METHOD(Math, astype) { php_interop_polite_math_matrix_linear_buffer_t* bufferX; php_interop_polite_math_matrix_linear_buffer_t* bufferY; zend_long n; zend_long dtype; zval* x=NULL; zend_long offsetX; zend_long incX; zval* y=NULL; zend_long offsetY; zend_long incY; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 8, 8) Z_PARAM_LONG(n) Z_PARAM_LONG(dtype) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) Z_PARAM_OBJECT(y) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetY) Z_PARAM_LONG(incY) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(bufferX,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,n,offsetX,incX)) { return; } bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y); if(php_rindow_openblas_assert_buffer_type(bufferY,"y")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,n,offsetY,incY)) { return; } // Check dtype and Buffer Y if(dtype!=bufferY->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type for Y", 0); return; } if(php_rindow_openblas_common_dtype_is_int(dtype) || php_rindow_openblas_common_dtype_is_bool(dtype)) { zend_long i,value; for(i=0;i<n;i++) { if(rindow_openblas_math_get_integer( bufferX->dtype, bufferX->data, offsetX,incX, i, &value)) { zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type of X.", 0); return; } rindow_openblas_math_set_integer(bufferY->dtype, bufferY->data, offsetY, incY, i, value); } } else if(php_rindow_openblas_common_dtype_is_float(dtype)) { zend_long i; double value; for(i=0;i<n;i++) { if(rindow_openblas_math_get_float( bufferX->dtype, bufferX->data, offsetX,incX, i, &value)) { zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type of X.", 0); return; } rindow_openblas_math_set_float(bufferY->dtype, bufferY->data, offsetY, incY, i, value); } } else { zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type.", 0); return; } } /* }}} */ /* B(m,n) := A(m,n) : trans=false B(n,m) := A(m,n) : trans=true Method Rindow\OpenBLAS\Math:: public function matrixcopy( bool $trans, int $m, int $n, float $alpha, Buffer $A, int $offsetA, int $ldA, Buffer $B, int $offsetB, int $ldB ) : void {{{ */ static PHP_METHOD(Math, matrixcopy) { php_interop_polite_math_matrix_linear_buffer_t* bufferA; php_interop_polite_math_matrix_linear_buffer_t* bufferB; zend_bool trans; zend_long m; zend_long n; double alpha; zval* a=NULL; zend_long offsetA; zend_long ldA; zval* b=NULL; zend_long offsetB; zend_long ldB; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 10, 10) Z_PARAM_BOOL(trans) Z_PARAM_LONG(m) Z_PARAM_LONG(n) Z_PARAM_DOUBLE(alpha) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_LONG(ldA) Z_PARAM_OBJECT(b) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetB) Z_PARAM_LONG(ldB) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_M, m)) { return; } if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer A bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(bufferA,"a")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,m,n,offsetA,ldA)) { return; } { zend_long rows,cols; if(!trans) { rows = m; cols = n; } else { rows = n; cols = m; } // Check Buffer B bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b); if(php_rindow_openblas_assert_buffer_type(bufferB,"b")) { return; } if(php_rindow_openblas_assert_matrix_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_B, bufferB,rows,cols,offsetB,ldB)) { return; } } if(bufferA->dtype!=bufferB->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type A and B", 0); return; } switch (bufferA->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *a = &(((float *)bufferA->data)[offsetA]); float *b = &(((float *)bufferB->data)[offsetB]); zend_long i,j; if(!trans) { for(i=0;i<m;i++) { for(j=0;j<n;j++) { b[i*ldB+j] = (float)alpha * a[i*ldA+j]; } } } else { for(i=0;i<m;i++) { for(j=0;j<n;j++) { b[j*ldB+i] = (float)alpha * a[i*ldA+j]; } } } } break; case php_interop_polite_math_matrix_dtype_float64: { double *a = &(((double *)bufferA->data)[offsetA]); double *b = &(((double *)bufferB->data)[offsetB]); zend_long i,j; if(!trans) { for(i=0;i<m;i++) { for(j=0;j<n;j++) { b[i*ldB+j] = (double)alpha * a[i*ldA+j]; } } } else { for(i=0;i<m;i++) { for(j=0;j<n;j++) { b[j*ldB+i] = (double)alpha * a[i*ldA+j]; } } } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type of A.", 0); return; } } /* }}} */ /* Method Rindow\OpenBLAS\Math:: public function imagecopy( int $height, int $width, int $channels, Buffer $A, int $offsetA, Buffer $B, int $offsetB, bool $channelsFirst, int $heightShift, int $widthShift, bool $verticalFlip, bool $horizontalFlip ) : void {{{ */ static PHP_METHOD(Math, imagecopy) { zend_long height; zend_long width; zend_long channels; zval* a; zend_long offsetA; zval* b; zend_long offsetB; zend_bool channelsFirst; zend_long heightShift; zend_long widthShift; zend_bool verticalFlip; zend_bool horizontalFlip; php_interop_polite_math_matrix_linear_buffer_t* bufferA; php_interop_polite_math_matrix_linear_buffer_t* bufferB; zend_long ldC,ldY,ldX; zend_long directionY,directionX,biasY,biasX; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 12, 12) Z_PARAM_LONG(height) Z_PARAM_LONG(width) Z_PARAM_LONG(channels) Z_PARAM_OBJECT(a) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetA) Z_PARAM_OBJECT(b) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetB) Z_PARAM_BOOL(channelsFirst) Z_PARAM_LONG(heightShift) Z_PARAM_LONG(widthShift) Z_PARAM_BOOL(verticalFlip) Z_PARAM_BOOL(horizontalFlip) ZEND_PARSE_PARAMETERS_END(); if(height<1) { zend_throw_exception(spl_ce_InvalidArgumentException, "height must be greater then 0", 0); return; } if(width<1) { zend_throw_exception(spl_ce_InvalidArgumentException, "width must be greater then 0", 0); return; } if(channels<1) { zend_throw_exception(spl_ce_InvalidArgumentException, "channels must be greater then 0", 0); return; } // Check Buffer A bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a); if(php_rindow_openblas_assert_buffer_type(bufferA,"a")) { return; } if(bufferA->size < height*width*channels+offsetA) { zend_throw_exception(spl_ce_InvalidArgumentException, "Matrix specification too large for bufferA", 0); return; } // Check Buffer B bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b); if(php_rindow_openblas_assert_buffer_type(bufferA,"b")) { return; } if(bufferB->size < height*width*channels+offsetB) { zend_throw_exception(spl_ce_InvalidArgumentException, "Matrix specification too large for bufferB", 0); return; } if(bufferA->dtype!=bufferB->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type A and B", 0); return; } if(channelsFirst) { ldC = width*height; ldY = width; ldX = 1; } else { ldY = width*channels; ldX = channels; ldC = 1; } directionY = directionX = 1; biasY = biasX = 0; if(verticalFlip) { directionY = -directionY; biasY = height-1; } if(horizontalFlip) { directionX = -directionX; biasX = width-1; } biasY -= heightShift*directionY; biasX -= widthShift*directionX; switch (bufferA->dtype) { case php_interop_polite_math_matrix_dtype_float32: { float *a = &(((float *)bufferA->data)[offsetA]); float *b = &(((float *)bufferB->data)[offsetB]); for(zend_long y=0;y<height;y++) { for(zend_long x=0;x<width;x++) { for(zend_long c=0;c<channels;c++) { zend_long sy = y*directionY+biasY; zend_long sx = x*directionX+biasX; if(sy<0) { sy = 0; } else if(sy>=height) { sy = height-1; } if(sx<0) { sx = 0; } else if(sx>=width) { sx = width-1; } b[y*ldY+x*ldX+c*ldC] = a[sy*ldY+sx*ldX+c*ldC]; } } } } break; case php_interop_polite_math_matrix_dtype_float64: { double *a = &(((double *)bufferA->data)[offsetA]); double *b = &(((double *)bufferB->data)[offsetB]); for(zend_long y=0;y<height;y++) { for(zend_long x=0;x<width;x++) { for(zend_long c=0;c<channels;c++) { zend_long sy = y*directionY+biasY; zend_long sx = x*directionX+biasX; if(sy<0) { sy = 0; } else if(sy>=height) { sy = height-1; } if(sx<0) { sx = 0; } else if(sx>=width) { sx = width-1; } b[y*ldY+x*ldX+c*ldC] = a[sy*ldY+sx*ldX+c*ldC]; } } } } break; default: zend_throw_exception(spl_ce_RuntimeException, "Unsupported data type of A.", 0); return; } } /* }}} */ /* X(n) := P Method Rindow\OpenBLAS\Math:: public function fill( int $n, Buffer $value, int $offsetV, Buffer $X, int $offsetX, int $incX ) : void {{{ */ static PHP_METHOD(Math, fill) { php_interop_polite_math_matrix_linear_buffer_t* bufferV; php_interop_polite_math_matrix_linear_buffer_t* bufferX; zend_long n; zval* value=NULL; zend_long offsetV; zval* x=NULL; zend_long offsetX; zend_long incX; ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 6, 6) Z_PARAM_LONG(n) Z_PARAM_OBJECT(value) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetV) Z_PARAM_OBJECT(x) // Interop\Polite\Math\Matrix\LinearBuffer Z_PARAM_LONG(offsetX) Z_PARAM_LONG(incX) ZEND_PARSE_PARAMETERS_END(); if(php_rindow_openblas_assert_shape_parameter( PHP_RINDOW_OPENBLAS_ASSERT_N, n)) { return; } // Check Buffer V bufferV = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(value); if(php_rindow_openblas_assert_buffer_type(bufferV,"value")) { return; } if(offsetV >= bufferV->size) { zend_throw_exception(spl_ce_InvalidArgumentException, "value buffer size is too small", 0); return; } // Check Buffer X bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x); if(php_rindow_openblas_assert_buffer_type(bufferX,"x")) { return; } if(php_rindow_openblas_assert_vector_buffer_spec( PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,n,offsetX,incX)) { return; } if(bufferV->dtype!=bufferX->dtype) { zend_throw_exception(spl_ce_InvalidArgumentException, "Unmatch data type X and value", 0); return; } { size_t value_size = php_rindow_openblas_common_dtype_to_valuesize(bufferV->dtype); char *value = &(((char *)(bufferV->data))[offsetV*value_size]); char *x = &(((char *)(bufferX->data))[offsetX*value_size]); zend_long i; size_t step = incX*value_size; for(i=0;i<n;i++,x+=step) { memcpy(x,value,value_size); } } } /* }}} */ #include "Math_gather.c" #include "Math_repeat.c" #include "Math_slice.c" #include "Math_reduction.c" #include "Math_im2col1d.c" #include "Math_im2col2d.c" #include "Math_im2col3d.c" #include "Math_random.c" ZEND_BEGIN_ARG_INFO_EX(ai_Math_sum, 0, 0, 4) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_imax, 0, 0, 4) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_imin, 0, 0, 4) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_increment, 0, 0, 6) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_INFO(0, beta) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_reciprocal, 0, 0, 6) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_INFO(0, beta) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_maximum, 0, 0, 5) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_minimum, 0, 0, 5) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_greater, 0, 0, 5) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_less, 0, 0, 5) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_multiply, 0, 0, 9) ZEND_ARG_INFO(0, trans) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_OBJ_INFO(0, y, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetY) ZEND_ARG_INFO(0, incY) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_add, 0, 0, 10) ZEND_ARG_INFO(0, trans) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_OBJ_INFO(0, y, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetY) ZEND_ARG_INFO(0, incY) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_duplicate, 0, 0, 9) ZEND_ARG_INFO(0, trans) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_OBJ_INFO(0, y, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetY) ZEND_ARG_INFO(0, incY) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_square, 0, 0, 4) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_sqrt, 0, 0, 4) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_rsqrt, 0, 0, 6) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_INFO(0, beta) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_pow, 0, 0, 5) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_exp, 0, 0, 4) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_log, 0, 0, 4) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_tanh, 0, 0, 4) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_zeros, 0, 0, 4) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_gather, 0, 0, 11) ZEND_ARG_INFO(0, reverse) ZEND_ARG_INFO(0, addMode) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, k) ZEND_ARG_INFO(0, numClass) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_reduceGather, 0, 0, 11) ZEND_ARG_INFO(0, reverse) ZEND_ARG_INFO(0, addMode) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, numClass) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_repeat, 0, 0, 7) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, k) ZEND_ARG_INFO(0, repeats) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_slice, 0, 0, 18) ZEND_ARG_INFO(0, reverse) ZEND_ARG_INFO(0, addMode) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, k) ZEND_ARG_INFO(0, size) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_INFO(0, incA) ZEND_ARG_OBJ_INFO(0, y, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetY) ZEND_ARG_INFO(0, incY) ZEND_ARG_INFO(0, startAxis0) ZEND_ARG_INFO(0, sizeAxis0) ZEND_ARG_INFO(0, startAxis1) ZEND_ARG_INFO(0, sizeAxis1) ZEND_ARG_INFO(0, startAxis2) ZEND_ARG_INFO(0, sizeAxis2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_updateAddOnehot, 0, 0, 9) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, a) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_OBJ_INFO(0, y, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetY) ZEND_ARG_INFO(0, ldY) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_softmax, 0, 0, 5) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_equal, 0, 0, 7) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_OBJ_INFO(0, y, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetY) ZEND_ARG_INFO(0, incY) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_reduceSum, 0, 0, 7) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, k) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_reduceMax, 0, 0, 7) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, k) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_reduceArgMax, 0, 0, 7) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, k) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_astype, 0, 0, 8) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, dtype) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_OBJ_INFO(0, y, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetY) ZEND_ARG_INFO(0, incY) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_matrixcopy, 0, 0, 10) ZEND_ARG_INFO(0, trans) ZEND_ARG_INFO(0, m) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, alpha) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_INFO(0, ldA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_ARG_INFO(0, ldB) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_imagecopy, 0, 0, 12) ZEND_ARG_INFO(0, height) ZEND_ARG_INFO(0, width) ZEND_ARG_INFO(0, channels) ZEND_ARG_OBJ_INFO(0, a, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetA) ZEND_ARG_OBJ_INFO(0, b, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetB) ZEND_ARG_INFO(0, channelsFirst) ZEND_ARG_INFO(0, heightShift) ZEND_ARG_INFO(0, widthShift) ZEND_ARG_INFO(0, verticalFlip) ZEND_ARG_INFO(0, horizontalFlip) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_fill, 0, 0, 6) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, value, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetV) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_im2col1d, 0, 0, 16) ZEND_ARG_INFO(0, reverse) ZEND_ARG_OBJ_INFO(0, images_obj, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, images_offset) ZEND_ARG_INFO(0, images_size) ZEND_ARG_INFO(0, batches) ZEND_ARG_INFO(0, im_w) ZEND_ARG_INFO(0, channels) ZEND_ARG_INFO(0, filter_w) ZEND_ARG_INFO(0, stride_w) ZEND_ARG_INFO(0, padding) ZEND_ARG_INFO(0, channels_first) ZEND_ARG_INFO(0, dilation_w) ZEND_ARG_INFO(0, cols_channels_first) ZEND_ARG_OBJ_INFO(0, cols_obj,Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, cols_offset) ZEND_ARG_INFO(0, cols_size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_im2col2d, 0, 0, 18) ZEND_ARG_INFO(0, reverse) ZEND_ARG_OBJ_INFO(0, images_obj, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, images_offset) ZEND_ARG_INFO(0, images_size) ZEND_ARG_INFO(0, batches) ZEND_ARG_INFO(0, im_h) ZEND_ARG_INFO(0, im_w) ZEND_ARG_INFO(0, channels) ZEND_ARG_INFO(0, filter_h) ZEND_ARG_INFO(0, filter_w) ZEND_ARG_INFO(0, stride_h) ZEND_ARG_INFO(0, stride_w) ZEND_ARG_INFO(0, padding) ZEND_ARG_INFO(0, channels_first) ZEND_ARG_INFO(0, dilation_h) ZEND_ARG_INFO(0, dilation_w) ZEND_ARG_INFO(0, cols_channels_first) ZEND_ARG_OBJ_INFO(0, cols_obj,Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, cols_offset) ZEND_ARG_INFO(0, cols_size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_im2col3d, 0, 0, 24) ZEND_ARG_INFO(0, reverse) ZEND_ARG_OBJ_INFO(0, images_obj, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, images_offset) ZEND_ARG_INFO(0, images_size) ZEND_ARG_INFO(0, batches) ZEND_ARG_INFO(0, im_d) ZEND_ARG_INFO(0, im_h) ZEND_ARG_INFO(0, im_w) ZEND_ARG_INFO(0, channels) ZEND_ARG_INFO(0, filter_d) ZEND_ARG_INFO(0, filter_h) ZEND_ARG_INFO(0, filter_w) ZEND_ARG_INFO(0, stride_d) ZEND_ARG_INFO(0, stride_h) ZEND_ARG_INFO(0, stride_w) ZEND_ARG_INFO(0, padding) ZEND_ARG_INFO(0, channels_first) ZEND_ARG_INFO(0, dilation_d) ZEND_ARG_INFO(0, dilation_h) ZEND_ARG_INFO(0, dilation_w) ZEND_ARG_INFO(0, cols_channels_first) ZEND_ARG_OBJ_INFO(0, cols_obj,Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, cols_offset) ZEND_ARG_INFO(0, cols_size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_randomUniform, 0, 0, 7) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_INFO(0, low) ZEND_ARG_INFO(0, high) ZEND_ARG_INFO(0, seed) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_randomNormal, 0, 0, 7) ZEND_ARG_INFO(0, n) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_INFO(0, mean) ZEND_ARG_INFO(0, scale) ZEND_ARG_INFO(0, seed) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(ai_Math_randomSequence, 0, 0, 6) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, size) ZEND_ARG_OBJ_INFO(0, x, Interop\\Polite\\Math\\Matrix\\LinearBuffer, 0) ZEND_ARG_INFO(0, offsetX) ZEND_ARG_INFO(0, incX) ZEND_ARG_INFO(0, seed) ZEND_END_ARG_INFO() /* {{{ Rindow\OpenBLAS\Blas function entries */ static zend_function_entry php_rindow_openblas_math_me[] = { /* clang-format off */ PHP_ME(Math, sum, ai_Math_sum, ZEND_ACC_PUBLIC) PHP_ME(Math, imax, ai_Math_imax, ZEND_ACC_PUBLIC) PHP_ME(Math, imin, ai_Math_imin, ZEND_ACC_PUBLIC) PHP_ME(Math, increment, ai_Math_increment, ZEND_ACC_PUBLIC) PHP_ME(Math, reciprocal, ai_Math_reciprocal, ZEND_ACC_PUBLIC) PHP_ME(Math, maximum, ai_Math_maximum, ZEND_ACC_PUBLIC) PHP_ME(Math, minimum, ai_Math_minimum, ZEND_ACC_PUBLIC) PHP_ME(Math, greater, ai_Math_greater, ZEND_ACC_PUBLIC) PHP_ME(Math, less, ai_Math_less, ZEND_ACC_PUBLIC) PHP_ME(Math, multiply, ai_Math_multiply, ZEND_ACC_PUBLIC) PHP_ME(Math, add, ai_Math_add, ZEND_ACC_PUBLIC) PHP_ME(Math, duplicate, ai_Math_duplicate, ZEND_ACC_PUBLIC) PHP_ME(Math, square, ai_Math_square, ZEND_ACC_PUBLIC) PHP_ME(Math, sqrt, ai_Math_sqrt, ZEND_ACC_PUBLIC) PHP_ME(Math, rsqrt, ai_Math_rsqrt, ZEND_ACC_PUBLIC) PHP_ME(Math, pow, ai_Math_pow, ZEND_ACC_PUBLIC) PHP_ME(Math, exp, ai_Math_exp, ZEND_ACC_PUBLIC) PHP_ME(Math, log, ai_Math_log, ZEND_ACC_PUBLIC) PHP_ME(Math, tanh, ai_Math_tanh, ZEND_ACC_PUBLIC) PHP_ME(Math, zeros, ai_Math_zeros, ZEND_ACC_PUBLIC) PHP_ME(Math, gather, ai_Math_gather, ZEND_ACC_PUBLIC) PHP_ME(Math, reduceGather, ai_Math_reduceGather, ZEND_ACC_PUBLIC) PHP_ME(Math, repeat, ai_Math_repeat, ZEND_ACC_PUBLIC) PHP_ME(Math, slice, ai_Math_slice, ZEND_ACC_PUBLIC) PHP_ME(Math, updateAddOnehot,ai_Math_updateAddOnehot,ZEND_ACC_PUBLIC) PHP_ME(Math, softmax, ai_Math_softmax, ZEND_ACC_PUBLIC) PHP_ME(Math, equal, ai_Math_equal, ZEND_ACC_PUBLIC) PHP_ME(Math, astype, ai_Math_astype, ZEND_ACC_PUBLIC) PHP_ME(Math, matrixcopy, ai_Math_matrixcopy, ZEND_ACC_PUBLIC) PHP_ME(Math, imagecopy, ai_Math_imagecopy, ZEND_ACC_PUBLIC) PHP_ME(Math, fill, ai_Math_fill, ZEND_ACC_PUBLIC) PHP_ME(Math, reduceSum, ai_Math_reduceSum, ZEND_ACC_PUBLIC) PHP_ME(Math, reduceMax, ai_Math_reduceMax, ZEND_ACC_PUBLIC) PHP_ME(Math, reduceArgMax, ai_Math_reduceArgMax, ZEND_ACC_PUBLIC) PHP_ME(Math, im2col1d, ai_Math_im2col1d, ZEND_ACC_PUBLIC) PHP_ME(Math, im2col2d, ai_Math_im2col2d, ZEND_ACC_PUBLIC) PHP_ME(Math, im2col3d, ai_Math_im2col3d, ZEND_ACC_PUBLIC) PHP_ME(Math, randomUniform, ai_Math_randomUniform, ZEND_ACC_PUBLIC) PHP_ME(Math, randomNormal, ai_Math_randomNormal, ZEND_ACC_PUBLIC) PHP_ME(Math, randomSequence, ai_Math_randomSequence, ZEND_ACC_PUBLIC) PHP_FE_END /* clang-format on */ }; /* }}} */ /* Class Rindow\OpenBLAS\Math {{{ */ static zend_class_entry* rindow_openblas_math_ce; void php_rindow_openblas_math_init_ce(INIT_FUNC_ARGS) { zend_class_entry ce; INIT_NS_CLASS_ENTRY(ce, "Rindow\\OpenBLAS", "Math", php_rindow_openblas_math_me); rindow_openblas_math_ce = zend_register_internal_class(&ce); rindow_openblas_math_ce->create_object = php_rindow_openblas_math_create_object; memcpy(&rindow_openblas_math_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); rindow_openblas_math_object_handlers.offset = 0; rindow_openblas_math_object_handlers.free_obj = php_rindow_openblas_math_free_object; rindow_openblas_math_object_handlers.clone_obj = NULL; //zend_class_implements(rindow_openblas_math_ce, 2, spl_ce_ArrayAccess, spl_ce_Countable); } /* }}} */
{ "alphanum_fraction": 0.5949180266, "avg_line_length": 32.2546998181, "ext": "c", "hexsha": "44f7619e4a26106dc5731e778e9603b2898fc41e", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-08-11T19:59:53.000Z", "max_forks_repo_forks_event_min_datetime": "2021-08-11T19:59:53.000Z", "max_forks_repo_head_hexsha": "c835d5dba089e2e244803de540e57638baeaf8ee", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "yuichiis/rindow-openblas", "max_forks_repo_path": "src/Rindow/OpenBLAS/Math.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c835d5dba089e2e244803de540e57638baeaf8ee", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "yuichiis/rindow-openblas", "max_issues_repo_path": "src/Rindow/OpenBLAS/Math.c", "max_line_length": 115, "max_stars_count": 9, "max_stars_repo_head_hexsha": "c835d5dba089e2e244803de540e57638baeaf8ee", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "yuichiis/rindow-openblas", "max_stars_repo_path": "src/Rindow/OpenBLAS/Math.c", "max_stars_repo_stars_event_max_datetime": "2022-02-28T05:59:12.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-15T05:12:39.000Z", "num_tokens": 27858, "size": 106376 }
#ifndef KABSCH_RMSD #define KABSCH_RMSD #include <cblas.h> #include <lapacke.h> #include <iterator> #include <iostream> #include <fstream> #include <tuple> namespace kabsch { /** Calculates the RMSD @param P - coordinates of molecule P @param Q - coordinates of molecule Q @param N - number of atoms @return double - the RMSD **/ template <class M> double rmsd( M *P, M *Q, const unsigned int N) { double rmsd {0.0}; const unsigned int D {3}; const unsigned int size = N*D; for(unsigned int i = 0; i < size; ++i) { rmsd += (P[i] - Q[i])*(P[i] - Q[i]); } return sqrt(rmsd/N); } template <class M> M* centroid( M *coordinates, unsigned int n_atoms) { double x {0}; double y {0}; double z {0}; // unsigned int size = sizeof(coordinates); // unsigned int n_atoms = size / 3; const unsigned int size = n_atoms*3; unsigned int i = 0; while(i<size) { x += coordinates[i++]; y += coordinates[i++]; z += coordinates[i++]; } x /= n_atoms; y /= n_atoms; z /= n_atoms; M *centroid = new M[3]; centroid[0] = x; centroid[1] = y; centroid[2] = z; return centroid; } template <class Matrix> Matrix* multiply(Matrix *A, Matrix *B, const int M, const int N, const int K) { double one = 1.0; // TODO Matrix C[M*N] = {0} // Compilers doesnt like the following syntax Matrix *C = new Matrix[M*N] {0}; cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, one, A, K, B, N, one, C, N); return C; } template <class Matrix> Matrix* transpose_multiply( Matrix *A, Matrix *B, const int M, const int N, const int K) { double one = 1.0; Matrix *C = new Matrix[M*N] {0}; cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, M, N, K, one, A, M, B, N, one, C, N); return C; } template <class Matrix> std::tuple<Matrix*, Matrix*, Matrix*> matrix_svd( Matrix *A, int rows, int cols) { // lapack_int LAPACKE_dgesvd( int matrix_layout, char jobu, char jobvt, // lapack_int m, lapack_int n, // double* a, lapack_int lda, // double* s, double* u, lapack_int ldu, // double* vt, lapack_int ldvt, // double* superb ); Matrix *U = new Matrix[cols*rows] {0}; Matrix *S = new Matrix[rows] {0}; Matrix *VT = new Matrix[cols*rows] {0}; Matrix *superb = new Matrix[cols*rows] {0}; int info; info = LAPACKE_dgesvd(LAPACK_ROW_MAJOR, 'A', 'A', rows, cols, A, rows, S, U, rows, VT, rows, superb); if(info > 0) { // TODO What if failed } delete[] superb; return std::make_tuple(U, S, VT); } template <class M> double determinant3x3(M A) { // determinant of a square 3x3 matrix double det = A[0]*A[4]*A[8] +A[1]*A[5]*A[6] +A[2]*A[3]*A[7] -A[2]*A[4]*A[6] -A[1]*A[3]*A[8] -A[0]*A[5]*A[7]; return det; } template <class M, class T> M* kabsch( M *P, M *Q, const T n_atoms) { // M *U = new M[3*3] {0}; // U[0] = 1.0; // U[4] = 1.0; // U[8] = 1.0; // return U; M *U; M *S; M *V; M *C = transpose_multiply(P, Q, 3, 3, n_atoms); std::tie(U, S, V) = matrix_svd(C, 3, 3); // Getting the sign of the det(U)*(V) to decide whether we need to correct // our rotation matrix to ensure a right-handed coordinate system. if(determinant3x3(U)*determinant3x3(V) < 0.0) { U[3*0+2] = -U[3*0+2]; U[3*2+2] = -U[3*1+2]; U[3*1+2] = -U[3*2+2]; } M *rotation = multiply(U, V, 3, 3, 3); delete[] C; delete[] U; delete[] S; delete[] V; return rotation; } template <class M, class T> M* kabsch_rotate( M *P, M *Q, T n_atoms) { M *U = kabsch(P, Q, n_atoms); M *product = multiply(P, U, n_atoms, 3, 3); delete[] U; return product; } template <class M, class T> double kabsch_rmsd( M *P, M *Q, T n_atoms) { M *P_rotated = kabsch_rotate(P, Q, n_atoms); double rmsdval = rmsd(P_rotated, Q, n_atoms); delete[] P_rotated; return rmsdval; } } // namespace rmsd #endif
{ "alphanum_fraction": 0.5565947242, "avg_line_length": 16.9512195122, "ext": "h", "hexsha": "9cc718d7d0cd29b5c9b2d47221c1509f50a8c9ce", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-02-23T15:15:00.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-23T15:15:00.000Z", "max_forks_repo_head_hexsha": "0956d8d29417a974809166857de9a978d7fac677", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "chemspacelab/clockwork", "max_forks_repo_path": "src/worker/deprecated/kabsch.h", "max_issues_count": 21, "max_issues_repo_head_hexsha": "0956d8d29417a974809166857de9a978d7fac677", "max_issues_repo_issues_event_max_datetime": "2019-09-23T11:02:59.000Z", "max_issues_repo_issues_event_min_datetime": "2019-01-04T10:55:39.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "chemspacelab/clockwork", "max_issues_repo_path": "src/worker/deprecated/kabsch.h", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "0956d8d29417a974809166857de9a978d7fac677", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "chemspacelab/clockwork", "max_stars_repo_path": "src/worker/deprecated/kabsch.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1415, "size": 4170 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_math.h> #include "allvars.h" #include "proto.h" #ifdef RADTRANSFER #define sigma 6.3e-18/All.UnitLength_in_cm/All.UnitLength_in_cm // in code units #endif #ifdef CS_MODEL #include "cs_metals.h" #endif /*! \file accel.c * \brief driver routines to carry out force computation */ /*! This routine computes the accelerations for all active particles. First, the gravitational forces are * computed. This also reconstructs the tree, if needed, otherwise the drift/kick operations have updated the * tree to make it fullu usable at the current time. * * If gas particles are presented, the `interior' of the local domain is determined. This region is guaranteed * to contain only particles local to the processor. This information will be used to reduce communication in * the hydro part. The density for active SPH particles is computed next. If the number of neighbours should * be outside the allowed bounds, it will be readjusted by the function ensure_neighbours(), and for those * particle, the densities are recomputed accordingly. Finally, the hydrodynamical forces are added. */ void compute_accelerations(int mode) { #ifdef RADTRANSFER double timeeach = 0, timeall = 0, tstart = 0, tend = 0; #endif #if defined(BUBBLES) || defined(MULTI_BUBBLES) double hubble_a; #endif if(ThisTask == 0) { printf("Start force computation...\n"); fflush(stdout); } #ifdef REIONIZATION heating(); #endif CPU_Step[CPU_MISC] += measure_time(); #ifdef PMGRID if(All.PM_Ti_endstep == All.Ti_Current) { long_range_force(); CPU_Step[CPU_MESH] += measure_time(); } #endif #ifndef ONLY_PM gravity_tree(); /* computes gravity accel. */ if(All.TypeOfOpeningCriterion == 1 && All.Ti_Current == 0) gravity_tree(); /* For the first timestep, we redo it * to allow usage of relative opening * criterion for consistent accuracy. */ #endif if(All.Ti_Current == 0 && RestartFlag == 0 && header.flag_ic_info == FLAG_SECOND_ORDER_ICS) second_order_ics(); /* produces the actual ICs from the special second order IC file */ #ifdef FORCETEST gravity_forcetest(); #endif if(All.TotN_gas > 0) { /***** density *****/ if(ThisTask == 0) { printf("Start density computation...\n"); fflush(stdout); } #ifdef CS_MODEL CPU_Step[CPU_MISC] += measure_time(); #if defined(CS_SNI) || defined(CS_SNII) cs_flag_SN_starparticles(); /* mark SNI star particles */ #endif cs_copy_densities(); cs_find_low_density_tail(); CPU_Step[CPU_CSMISC] += measure_time(); #endif #ifndef VORONOI density(); /* computes density, and pressure */ #else voronoi_mesh(); voronoi_density(); #endif #if (defined(SMOOTH_PHI) || defined(SMOOTH_ROTB) || defined(BSMOOTH)) smoothed_values(); #endif #if defined(SNIA_HEATING) snIa_heating(); #endif #if defined(CS_MODEL) && defined(CS_FEEDBACK) CPU_Step[CPU_CSMISC] += measure_time(); cs_find_hot_neighbours(); cs_promotion(); cs_copy_densities(); CPU_Step[CPU_CSMISC] += measure_time(); density(); /* recalculate densities again */ CPU_Step[CPU_CSMISC] += measure_time(); #endif /***** update smoothing lengths in tree *****/ #ifndef VORONOI force_update_hmax(); #endif /***** hydro forces *****/ if(ThisTask == 0) { printf("Start hydro-force computation...\n"); fflush(stdout); } #ifndef VORONOI hydro_force(); /* adds hydrodynamical accelerations and computes du/dt */ #else voronoi_hydro_force(); #endif #ifdef CONDUCTION if(All.Conduction_Ti_endstep == All.Ti_Current) conduction(); #endif #ifdef CR_DIFFUSION if(All.CR_Diffusion_Ti_endstep == All.Ti_Current) cosmic_ray_diffusion(); #endif #ifdef RADTRANSFER if(Flag_FullStep) /* only do it for full timesteps */ { All.Radiation_Ti_endstep = All.Ti_Current; #ifndef NOGRAVITY /***** compute eddington tensor *****/ if(ThisTask == 0) { printf("Start Eddington tensor computation...\n"); fflush(stdout); } eddington(); if(ThisTask == 0) { printf("done Eddington tensor! \n"); fflush(stdout); } star_density(); #else if(All.Time == All.TimeBegin) { if(ThisTask == 0) { printf("Start Eddington tensor computation...\n"); fflush(stdout); } eddington(); if(ThisTask == 0) { printf("done Eddington tensor! \n"); fflush(stdout); } } #endif star_density(); /***** set simple initial conditions *****/ if(All.Time == All.TimeBegin) { if(ThisTask == 0) { printf("Setting simple inits...\n"); fflush(stdout); } radtransfer_set_simple_inits(); if(ThisTask == 0) { printf("done with simple inits! \n"); fflush(stdout); } } /***** evolve the transport of radiation *****/ if(ThisTask == 0) { printf("start radtransfer...\n"); fflush(stdout); } tstart = second(); radtransfer(); tend = second(); timeeach = timediff(tstart, tend); MPI_Allreduce(&timeeach, &timeall, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); if(ThisTask == 0) { printf("time consumed is %g \n", timeall); printf("done with radtransfer! \n"); fflush(stdout); } All.Radiation_Ti_begstep = All.Radiation_Ti_endstep; } #endif #ifdef MHM /***** kinetic feedback *****/ kinetic_feedback_mhm(); #endif #ifdef BLACK_HOLES /***** black hole accretion and feedback *****/ blackhole_accretion(); #ifdef FOF /* this will find new black hole seed halos */ if(All.Time >= All.TimeNextBlackHoleCheck) { fof_fof(-1); if(All.ComovingIntegrationOn) All.TimeNextBlackHoleCheck *= All.TimeBetBlackHoleSearch; else All.TimeNextBlackHoleCheck += All.TimeBetBlackHoleSearch; } #endif #endif #ifdef COOLING /**** radiative cooling and star formation *****/ #ifdef CS_MODEL cs_cooling_and_starformation(); #else #ifdef SFR cooling_and_starformation(); #else cooling_only(); #endif #endif CPU_Step[CPU_COOLINGSFR] += measure_time(); #endif /*ends COOLING */ #if defined(CS_MODEL) && defined(CS_ENRICH) #ifndef CS_FEEDBACK Flag_phase = 0; /* no destinction between phases */ cs_update_weights(); CPU_Step[CPU_WEIGHTS_HOT] += measure_time(); cs_enrichment(); CPU_Step[CPU_ENRICH_HOT] += measure_time(); #else Flag_phase = 1; /* COLD phase Flag_phase = 1 */ cs_update_weights(); CPU_Step[CPU_WEIGHTS_HOT] += measure_time(); cs_enrichment(); CPU_Step[CPU_ENRICH_HOT] += measure_time(); Flag_phase = 2; /* HOT phase Flag_phase = 2 */ cs_update_weights(); CPU_Step[CPU_WEIGHTS_COLD] += measure_time(); cs_enrichment(); CPU_Step[CPU_ENRICH_COLD] += measure_time(); Flag_phase = 0; #endif #endif #ifdef CS_TESTS cs_energy_test(); #endif #ifndef BH_BUBBLES #ifdef BUBBLES /**** bubble feedback *****/ if(All.Time >= All.TimeOfNextBubble) { #ifdef FOFs fof_fof(-1); bubble(); #else bubble(); #endif if(All.ComovingIntegrationOn) { hubble_a = hubble_function(All.Time); All.TimeOfNextBubble *= (1.0 + All.BubbleTimeInterval * hubble_a); } else All.TimeOfNextBubble += All.BubbleTimeInterval / All.UnitTime_in_Megayears; if(ThisTask == 0) printf("Time of the bubble generation: %g\n", 1. / All.TimeOfNextBubble - 1.); } #endif #endif #if defined(MULTI_BUBBLES) && defined(FOF) if(All.Time >= All.TimeOfNextBubble) { fof_fof(-1); if(All.ComovingIntegrationOn) { hubble_a = hubble_func(All.Time); All.TimeOfNextBubble *= (1.0 + All.BubbleTimeInterval * hubble_a); } else All.TimeOfNextBubble += All.BubbleTimeInterval / All.UnitTime_in_Megayears; if(ThisTask == 0) printf("Time of the bubble generation: %g\n", 1. / All.TimeOfNextBubble - 1.); } #endif } if(ThisTask == 0) { printf("force computation done.\n"); fflush(stdout); } }
{ "alphanum_fraction": 0.6447336708, "avg_line_length": 21.6657963446, "ext": "c", "hexsha": "1c8709fcf9116b4c6a796e263288c7f02d8391dc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "egpbos/egp", "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/accel.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "egpbos/egp", "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/accel.c", "max_line_length": 110, "max_stars_count": null, "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "egpbos/egp", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/accel.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2236, "size": 8298 }
/* roots/falsepos.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Reid Priedhorsky, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* falsepos.c -- falsepos root finding algorithm The false position algorithm uses bracketing by linear interpolation. If a linear interpolation step would decrease the size of the bracket by less than a bisection step would then the algorithm takes a bisection step instead. The last linear interpolation estimate of the root is used. If a bisection step causes it to fall outside the brackets then it is replaced by the bisection estimate (x_upper + x_lower)/2. */ #include <config.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> #include "roots.h" typedef struct { double f_lower, f_upper; } falsepos_state_t; static int falsepos_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper); static int falsepos_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper); static int falsepos_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper) { falsepos_state_t * state = (falsepos_state_t *) vstate; double f_lower, f_upper ; *root = 0.5 * (x_lower + x_upper); SAFE_FUNC_CALL (f, x_lower, &f_lower); SAFE_FUNC_CALL (f, x_upper, &f_upper); state->f_lower = f_lower; state->f_upper = f_upper; if ((f_lower < 0.0 && f_upper < 0.0) || (f_lower > 0.0 && f_upper > 0.0)) { GSL_ERROR ("endpoints do not straddle y=0", GSL_EINVAL); } return GSL_SUCCESS; } static int falsepos_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper) { falsepos_state_t * state = (falsepos_state_t *) vstate; double x_linear, f_linear; double x_bisect, f_bisect; double x_left = *x_lower ; double x_right = *x_upper ; double f_lower = state->f_lower; double f_upper = state->f_upper; double w ; if (f_lower == 0.0) { *root = x_left ; *x_upper = x_left; return GSL_SUCCESS; } if (f_upper == 0.0) { *root = x_right ; *x_lower = x_right; return GSL_SUCCESS; } /* Draw a line between f(*lower_bound) and f(*upper_bound) and note where it crosses the X axis; that's where we will split the interval. */ x_linear = x_right - (f_upper * (x_left - x_right) / (f_lower - f_upper)); SAFE_FUNC_CALL (f, x_linear, &f_linear); if (f_linear == 0.0) { *root = x_linear; *x_lower = x_linear; *x_upper = x_linear; return GSL_SUCCESS; } /* Discard the half of the interval which doesn't contain the root. */ if ((f_lower > 0.0 && f_linear < 0.0) || (f_lower < 0.0 && f_linear > 0.0)) { *root = x_linear ; *x_upper = x_linear; state->f_upper = f_linear; w = x_linear - x_left ; } else { *root = x_linear ; *x_lower = x_linear; state->f_lower = f_linear; w = x_right - x_linear; } if (w < 0.5 * (x_right - x_left)) { return GSL_SUCCESS ; } x_bisect = 0.5 * (x_left + x_right); SAFE_FUNC_CALL (f, x_bisect, &f_bisect); if ((f_lower > 0.0 && f_bisect < 0.0) || (f_lower < 0.0 && f_bisect > 0.0)) { *x_upper = x_bisect; state->f_upper = f_bisect; if (*root > x_bisect) *root = 0.5 * (x_left + x_bisect) ; } else { *x_lower = x_bisect; state->f_lower = f_bisect; if (*root < x_bisect) *root = 0.5 * (x_bisect + x_right) ; } return GSL_SUCCESS; } static const gsl_root_fsolver_type falsepos_type = {"falsepos", /* name */ sizeof (falsepos_state_t), &falsepos_init, &falsepos_iterate}; const gsl_root_fsolver_type * gsl_root_fsolver_falsepos = &falsepos_type;
{ "alphanum_fraction": 0.6493227263, "avg_line_length": 25.9832402235, "ext": "c", "hexsha": "d264f697a404dc274f981406006441ebfe070d2b", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/roots/falsepos.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/roots/falsepos.c", "max_line_length": 113, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/roots/falsepos.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 1366, "size": 4651 }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include "core/common/inlined_containers_fwd.h" #include "core/framework/kernel_registry.h" #include "core/graph/graph_viewer.h" #include <gsl/gsl> namespace onnxruntime { /** Returns a list of nodes that are preferred on CPU. They are commonly shape-related computation subgraphs. @param graph Graph viewer @param provider_type The target execution provider type @param kernel_registries Kernel registries for the target EP @param tentative_nodes Nodes that are tentative to be placed on on target EP */ InlinedHashSet<NodeIndex> GetCpuPreferredNodes(const GraphViewer& graph, const std::string& provider_type, gsl::span<const KernelRegistry* const> kernel_registries, gsl::span<const NodeIndex> tentative_nodes); } // namespace onnxruntime
{ "alphanum_fraction": 0.6788537549, "avg_line_length": 37.4814814815, "ext": "h", "hexsha": "fda5fdb188d1eec251e213e12fceb1130305b3c2", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "4ef81b142dbd29abc3c64797084b8e61cf3212d1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Grimig/onnxruntime", "max_forks_repo_path": "onnxruntime/core/framework/fallback_cpu_capability.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4ef81b142dbd29abc3c64797084b8e61cf3212d1", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Grimig/onnxruntime", "max_issues_repo_path": "onnxruntime/core/framework/fallback_cpu_capability.h", "max_line_length": 104, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f4fd67cc2c55730ef15e589870eec8a3d19b16ca", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "anwang2009/onnxruntime", "max_stars_repo_path": "onnxruntime/core/framework/fallback_cpu_capability.h", "max_stars_repo_stars_event_max_datetime": "2022-03-09T21:24:30.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-09T21:24:30.000Z", "num_tokens": 196, "size": 1012 }
/** * Copyright 2017 José Manuel Abuín Mosquera <josemanuel.abuin@usc.es> * * This file is part of Matrix Market Suite. * * Matrix Market Suite is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Matrix Market Suite is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Matrix Market Suite. If not, see <http://www.gnu.org/licenses/>. */ #include <cblas.h> #include "JacobiSolver.h" int JacobiSolver(unsigned long *II, unsigned long *J, double *A, unsigned long M, unsigned long N, unsigned long long nz, double *b, unsigned long M_Vector, unsigned long N_Vector, unsigned long long nz_vector,double *x2, int iterationNumber) { //Jacobi Method as shown in the example from https://en.wikipedia.org/wiki/Jacobi_method unsigned long k = 0; int stop = 0; unsigned int i = 0; double result = 0.0; //Initial solution double *x1=(double *) calloc(nz_vector,sizeof(double)); //double *x2=(double *) calloc(nz_vector,sizeof(double)); double *res=(double *) calloc(nz_vector,sizeof(double)); double *LU=(double *) calloc(nz,sizeof(double)); double *Dinv=(double *) calloc(nz,sizeof(double)); double *T=(double *) calloc(nz,sizeof(double)); double *C=(double *) calloc(nz_vector,sizeof(double)); if(!isDiagonallyDominant(A,M,N,nz)){ fprintf(stderr, "[%s] The matrix is not diagonally dominant\n",__func__); //return 0; } getLUValues(LU, A,M,N,nz); getDInvValues(Dinv, A,M,N,nz); for(i = 0; i< N; i++){ x1[i] = 1.0; } //T=-D^{-1}(L+U) /* void cblas_dgemm (const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE transa, const CBLAS_TRANSPOSE transb, const MKL_INT m, const MKL_INT n, const MKL_INT k, const double alpha, const double *a, const MKL_INT lda, const double *b, const MKL_INT ldb, const double beta, double *c, const MKL_INT ldc); */ cblas_dgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans, M, N, N, -1.0, Dinv, N, LU, N, 0.0, T, N); //writeDenseCoordinateMatrixRowLine("stdout", T,M,N,nz); //C=-D^{-1}b cblas_dgemv(CblasRowMajor, CblasNoTrans, M,N , 1.0, Dinv, N, b, 1, 0.0, C, 1); //writeDenseVector("stdout", C,nz_vector,1, nz_vector); unsigned long maxIterations = M*2; if(iterationNumber != 0 ){ maxIterations = iterationNumber; } while(!stop) { // x^{(1)}= Tx^{(0)}+C //x2 = T*x1 cblas_dgemv(CblasRowMajor, CblasNoTrans, M,N , 1.0, T, N, x1, 1, 0.0, x2, 1); //x2 = x2+C cblas_daxpy(nz_vector,1.0,C, 1, x2, 1); //res = A*x - b memcpy(res, b, nz_vector*sizeof(double)); cblas_dgemv(CblasRowMajor, CblasNoTrans, M,N , 1.0, A, N, x2, 1, -1.0, res, 1); result = vectorSumElements(res,N); if((fabs(result)<=EPSILON)||(k == maxIterations)){ //fprintf(stderr,"Sum vector res is %lg\n",result); stop = 1; } memcpy(x1, x2, nz_vector*sizeof(double)); //writeDenseVector("stdout", x1,nz_vector,1, nz_vector); k++; } //memcpy(b, x2, N*sizeof(double)); free(x1); //free(x2); free(res); fprintf(stderr, "[%s] Number of iterations %lu\n",__func__,k); return 1; }
{ "alphanum_fraction": 0.6748413156, "avg_line_length": 30.6725663717, "ext": "c", "hexsha": "970ee07fd9b6b9295b51ba9e5b6d6e719966b067", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "vkeller/math-454", "max_forks_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/solvers/JacobiSolver.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "vkeller/math-454", "max_issues_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/solvers/JacobiSolver.c", "max_line_length": 298, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "vkeller/math-454", "max_stars_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/solvers/JacobiSolver.c", "max_stars_repo_stars_event_max_datetime": "2021-05-19T13:31:49.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-19T13:31:49.000Z", "num_tokens": 1119, "size": 3466 }
#pragma once #include <string> #include <vector> #include <gsl/gsl_complex.h> #include <MathEngine.h> extern MathEngine engine; bool printDifference(const std::string& input, const expression expr, const double output, const double expected); void requireIsEqual(const std::string& input, const double expected); bool printDifference(const std::string& input, const expression expr, const std::string& output, const std::string& expected); void requireIsEqual(const std::string& input, const std::string& expected, bool evaluate = false); bool printDifference(const std::string& input, const expression expr, const expression output, const std::string& expected); void requireExprIsEqual(const std::string& input, const std::string& expected); void requireErrorIsEqual(const std::string& input, const std::string& expected);
{ "alphanum_fraction": 0.7800480769, "avg_line_length": 39.619047619, "ext": "h", "hexsha": "8b96f483ab86b083e6a9a2a208ab28b92612e8a6", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "antoniojkim/CalcPlusPlus", "max_forks_repo_path": "Tests/Tests/EngineTest.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "antoniojkim/CalcPlusPlus", "max_issues_repo_path": "Tests/Tests/EngineTest.h", "max_line_length": 126, "max_stars_count": null, "max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "antoniojkim/CalcPlusPlus", "max_stars_repo_path": "Tests/Tests/EngineTest.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 182, "size": 832 }
/* linalg/luc.c * * Copyright (C) 2001 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_permute_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_linalg.h> /* Factorise a general N x N complex matrix A into, * * P A = L U * * where P is a permutation matrix, L is unit lower triangular and U * is upper triangular. * * L is stored in the strict lower triangular part of the input * matrix. The diagonal elements of L are unity and are not stored. * * U is stored in the diagonal and upper triangular part of the * input matrix. * * P is stored in the permutation p. Column j of P is column k of the * identity matrix, where k = permutation->data[j] * * signum gives the sign of the permutation, (-1)^n, where n is the * number of interchanges in the permutation. * * See Golub & Van Loan, Matrix Computations, Algorithm 3.4.1 (Gauss * Elimination with Partial Pivoting). */ int gsl_linalg_complex_LU_decomp (gsl_matrix_complex * A, gsl_permutation * p, int *signum) { if (A->size1 != A->size2) { GSL_ERROR ("LU decomposition requires square matrix", GSL_ENOTSQR); } else if (p->size != A->size1) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else { const size_t N = A->size1; size_t i, j, k; *signum = 1; gsl_permutation_init (p); for (j = 0; j < N - 1; j++) { /* Find maximum in the j-th column */ gsl_complex ajj = gsl_matrix_complex_get (A, j, j); double max = gsl_complex_abs (ajj); size_t i_pivot = j; for (i = j + 1; i < N; i++) { gsl_complex aij = gsl_matrix_complex_get (A, i, j); double ai = gsl_complex_abs (aij); if (ai > max) { max = ai; i_pivot = i; } } if (i_pivot != j) { gsl_matrix_complex_swap_rows (A, j, i_pivot); gsl_permutation_swap (p, j, i_pivot); *signum = -(*signum); } ajj = gsl_matrix_complex_get (A, j, j); if (!(GSL_REAL(ajj) == 0.0 && GSL_IMAG(ajj) == 0.0)) { for (i = j + 1; i < N; i++) { gsl_complex aij_orig = gsl_matrix_complex_get (A, i, j); gsl_complex aij = gsl_complex_div (aij_orig, ajj); gsl_matrix_complex_set (A, i, j, aij); for (k = j + 1; k < N; k++) { gsl_complex aik = gsl_matrix_complex_get (A, i, k); gsl_complex ajk = gsl_matrix_complex_get (A, j, k); /* aik = aik - aij * ajk */ gsl_complex aijajk = gsl_complex_mul (aij, ajk); gsl_complex aik_new = gsl_complex_sub (aik, aijajk); gsl_matrix_complex_set (A, i, k, aik_new); } } } } return GSL_SUCCESS; } } int gsl_linalg_complex_LU_solve (const gsl_matrix_complex * LU, const gsl_permutation * p, const gsl_vector_complex * b, gsl_vector_complex * x) { if (LU->size1 != LU->size2) { GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR); } else if (LU->size1 != p->size) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else if (LU->size1 != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (LU->size2 != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else { /* Copy x <- b */ gsl_vector_complex_memcpy (x, b); /* Solve for x */ gsl_linalg_complex_LU_svx (LU, p, x); return GSL_SUCCESS; } } int gsl_linalg_complex_LU_svx (const gsl_matrix_complex * LU, const gsl_permutation * p, gsl_vector_complex * x) { if (LU->size1 != LU->size2) { GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR); } else if (LU->size1 != p->size) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else if (LU->size1 != x->size) { GSL_ERROR ("matrix size must match solution/rhs size", GSL_EBADLEN); } else { /* Apply permutation to RHS */ gsl_permute_vector_complex (p, x); /* Solve for c using forward-substitution, L c = P b */ gsl_blas_ztrsv (CblasLower, CblasNoTrans, CblasUnit, LU, x); /* Perform back-substitution, U x = c */ gsl_blas_ztrsv (CblasUpper, CblasNoTrans, CblasNonUnit, LU, x); return GSL_SUCCESS; } } int gsl_linalg_complex_LU_refine (const gsl_matrix_complex * A, const gsl_matrix_complex * LU, const gsl_permutation * p, const gsl_vector_complex * b, gsl_vector_complex * x, gsl_vector_complex * residual) { if (A->size1 != A->size2) { GSL_ERROR ("matrix a must be square", GSL_ENOTSQR); } if (LU->size1 != LU->size2) { GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR); } else if (A->size1 != LU->size2) { GSL_ERROR ("LU matrix must be decomposition of a", GSL_ENOTSQR); } else if (LU->size1 != p->size) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else if (LU->size1 != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (LU->size1 != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else { /* Compute residual, residual = (A * x - b) */ gsl_vector_complex_memcpy (residual, b); { gsl_complex one = GSL_COMPLEX_ONE; gsl_complex negone = GSL_COMPLEX_NEGONE; gsl_blas_zgemv (CblasNoTrans, one, A, x, negone, residual); } /* Find correction, delta = - (A^-1) * residual, and apply it */ gsl_linalg_complex_LU_svx (LU, p, residual); { gsl_complex negone= GSL_COMPLEX_NEGONE; gsl_blas_zaxpy (negone, residual, x); } return GSL_SUCCESS; } } int gsl_linalg_complex_LU_invert (const gsl_matrix_complex * LU, const gsl_permutation * p, gsl_matrix_complex * inverse) { size_t i, n = LU->size1; int status = GSL_SUCCESS; gsl_matrix_complex_set_identity (inverse); for (i = 0; i < n; i++) { gsl_vector_complex_view c = gsl_matrix_complex_column (inverse, i); int status_i = gsl_linalg_complex_LU_svx (LU, p, &(c.vector)); if (status_i) status = status_i; } return status; } gsl_complex gsl_linalg_complex_LU_det (gsl_matrix_complex * LU, int signum) { size_t i, n = LU->size1; gsl_complex det = gsl_complex_rect((double) signum, 0.0); for (i = 0; i < n; i++) { gsl_complex zi = gsl_matrix_complex_get (LU, i, i); det = gsl_complex_mul (det, zi); } return det; } double gsl_linalg_complex_LU_lndet (gsl_matrix_complex * LU) { size_t i, n = LU->size1; double lndet = 0.0; for (i = 0; i < n; i++) { gsl_complex z = gsl_matrix_complex_get (LU, i, i); lndet += log (gsl_complex_abs (z)); } return lndet; } gsl_complex gsl_linalg_complex_LU_sgndet (gsl_matrix_complex * LU, int signum) { size_t i, n = LU->size1; gsl_complex phase = gsl_complex_rect((double) signum, 0.0); for (i = 0; i < n; i++) { gsl_complex z = gsl_matrix_complex_get (LU, i, i); double r = gsl_complex_abs(z); if (r == 0) { phase = gsl_complex_rect(0.0, 0.0); break; } else { z = gsl_complex_div_real(z, r); phase = gsl_complex_mul(phase, z); } } return phase; }
{ "alphanum_fraction": 0.5947929808, "avg_line_length": 26.0268656716, "ext": "c", "hexsha": "53606797dabfc9a30e023cf358dbe2e616a198b8", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/linalg/luc.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/linalg/luc.c", "max_line_length": 202, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/linalg/luc.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 2438, "size": 8719 }
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <errno.h> #include "kmacros.h" #include <math.h> #include <unistd.h> #include <float.h> #include <time.h> #include <zlib.h> //#include "lapack_wrapper.h" #ifdef INTEL_COMPILER #include "mkl.h" #else #include <cblas.h> #endif // Constants for I/O routines #define DEFAULT_TFAM_NCOLS 6 #define DEFAULT_TPED_NCOLS 4 #define DEFAULT_NDIGITS 5 #define DEFAULT_DELIMS " \t\r\n" #define SZ_LONG_BUF 1000000 #define DEFAULT_SIZE_MATRIX 1000000 #define DEFAULT_SIZE_HEADER 100000 #define MAX_NUM_MARKERS 20000000 // 20M max # snps #define SZBUF 1024 #define DBL_MISSING -1e99 #define DEFAULT_TPED_NUM_HEADER_COLS 4 #define DEFAULT_TFAM_NUM_HEADER_COLS 6 #define DEFAULT_TPED_SNPID_INDEX 1 #define DEFAULT_PHENO_NUM_HEADER_COLS 2 #define KINSHIP_IBS_MEAN 1 #define KINSHIP_IBS_RAND 2 #define KINSHIP_BALDING_NICHOLS 3 // Constants for numerical routines #define FPMIN 1e-30 #define MAXIT 1000 #define EIGEN_EPS 1e-10 #define EIGEN_ADD 1. #define TOL 1e-10 #define EPS 1e-10 #define DEFAULT_NGRIDS 100 #define DEFAULT_LLIM -10 #define DEFAULT_ULIM 10 #define XACCU 1e-4 #define ITMAX 100 #define CGOLD 0.3819660 #define ZEPS 1.0e-10 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); #define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a)) struct HFILE { int gzflag; // 1 if gz if used int wflag; // r(0)/w(1) for plain, rb(0)/wb(1) for gz int nheadercols; // # of header columns (0 if nrows=0) int nvaluecols; // # of value cols (0 if nrows=0) int nrows; // # of rows FILE* fp; // plain file handle gzFile gzfp; // gzip file handle } g_logh; static int g_verbose = 0; #ifdef INTEL_COMPILER static char ct = 'T'; static char cn = 'N'; static double onef = 1.0; static double zerof = 0.0; static double minusonef = -1.0; static int onen = 1; static int dim_int; static int dim_f; #endif static char cv = 'V'; static char cl = 'L'; // Input routines void close_file (struct HFILE* fhp); struct HFILE open_file(char* filename, int gzflag, int wflag); struct HFILE open_file_with_suffix(char* prefix, char* suffix, int gzflag, int wflag); void read_matrix_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, int zero_miss_flag, int symmetric, int* p_nmiss, double** matrix, char*** headers); double* tokenize_line_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, int zero_miss_flag, char* lbuf, double* values, char** headers, int* p_nvalues, int* p_nmiss ); // Output routines void emmax_error( const char* format, ... ); void emmax_log( const char* format, ... ); void print_help(void); // Kinship routines double update_kinship_IBS_mean( double* kins, double* snps, int n ); double update_kinship_IBS_rand( double* kins, double* snps, int n ); double update_kinship_Balding_Nichols( double* kins, double* snps, int n ); void symmetrize_and_normalize_kinship( double* kins, double sum, int n ); // REMLE routines void ensure_symmetry_and_relax_diag( double* mat, int n, double tol, double eps ); int eigen_L_wo_Z(int n, double* kins, double* eLvals, double* eLvecs); int eigen_R_wo_Z(int n, int q, double* kins, double* xs, double* eRvals, double* eRvecs); double REMLE_grid_wo_Z(int n, int q, double* ys, double* xs, double* kins, int ngrids, double llim, double ulim, double* evals, double* evecs, double* optdelta, double* optvg, double* optve, double* pREML0); double centered_trace(double* kin, int n); int matrix_invert(int n, double *X, double *Y); int eigen_decomposition(int n, double* X, double *eigvec, double *eigval); // GLS routines void fill_XDX_X0 ( double* X0, double* eLvals, double delta, int n, int q0, int, double* XDX); void fill_XDX_X1 ( double* X0, double* x1, double* eLvals, double delta, int n, int q0, int, double* XDX ); void fill_XDy_X0 ( double* X0, double* y, double* eLvals, double delta, int n, int q0, double* XDy ); void fill_XDy_X1 ( double* x1, double* y, double* eLvals, double delta, int n, int q0, int, double* XDy ); double compute_yDy ( double* y, double *eLvals, double delta, int n ); double mult_vec_mat_vec ( double* vec, double* mat, int n ); // stat double tcdf(double t, double nu); static void compute_phenotype_summary_stats(double *rval_mean, double *rval_var, double *phenotypes, int n) { int i; double m, msq; m = 0.; msq = 0.; for(i=0; i < n; i++) { m += phenotypes[i]; msq += phenotypes[i]*phenotypes[i]; } m /= n; *rval_mean = m; *rval_var = msq/n - m*m; } static void __attribute__((unused))standardize_phenotype(double *phenotypes, int n, double m, double s) { int i; for(i=0; i < n; i++) phenotypes[i] = (phenotypes[i] - m)/s; } static double __attribute__((unused))compute_regressed_phenotype_variance(double *phenotypes, int n, double *betas, double *covariates, int n_covariates) { int i, j; double m, msq; m = 0.; msq = 0.; for(i=0; i < n; i++) { double p = phenotypes[i]; for(j=0; j < n_covariates; j++) /* covariates (X0 below) is column major format in this version, but I see commented out code below for row major format */ p -= betas[j]*covariates[i + j*n]; m += p; msq += p*p; } m /= n; return msq/n - m*m; } enum { GT_AA = 0, GT_AB, GT_BB, GT_MISSING, N_GT }; static double genotype_values[N_GT] = { -1.0, 0.0, 1.0, DBL_MISSING }; static int encode_genotype(char *q1, char *q2) { if (q1[0] == '0' || q2[0] == '0') { return GT_MISSING; } else if ((q1[0] == '1' && q2[0] == '2') || (q1[0] == '2' && q2[0] == '1')) { return GT_AB; } else if (q1[0] == '1' && q2[0] == '1') { return GT_AA; } else if (q1[0] == '2' && q2[0] == '2') { return GT_BB; } else { fprintf(stderr,"Covariate genotype %s/%s is not understood\n", q1, q2); return GT_MISSING; } } static double compute_allele_frequency(int *gt, int n) { int i, n_obs; double b_freq; b_freq = 0.; n_obs = 0; for(i=0; i < n; i++) { if (gt[i] != GT_MISSING) { n_obs++; if (gt[i] == GT_AB) { b_freq += 0.5; } else if (gt[i] == GT_BB) { b_freq += 1.0; } } } b_freq /= n_obs; return b_freq; } static void set_genotype_values(double *gv, int *g, int n) { int i, nm; double m; nm = 0; m = 0.; for(i=0; i < n; i++) { if (g[i] != GT_MISSING) { gv[i] = genotype_values[ g[i] ]; m += gv[i]; nm++; } } m /= nm; for(i=0; i < n; i++) if (g[i] == GT_MISSING) gv[i] = m; } static void set_interaction_values(double *gi, int *g1, int *g2, int n) { int i; int nvals; double sum; for(i=0; i < n; i++) gi[i] = 0; nvals = 0; sum = 0.; for(i=0; i < n; i++) { if (g1[i] != GT_MISSING || g2[i] != GT_MISSING) { if (g1[i] == GT_AA && g2[i] == GT_AA) { gi[i] = -1.; } else if (g1[i] == GT_AA && g2[i] == GT_BB) { gi[i] = 1.; } else if (g1[i] == GT_BB && g2[i] == GT_AA) { gi[i] = 1.; } else if (g1[i] == GT_BB && g2[i] == GT_BB) { gi[i] = -1.; } sum += gi[i]; nvals++; } else { gi[i] = DBL_MISSING; } } sum /= nvals; for(i=0; i < n; i++) if (gi[i] == DBL_MISSING) gi[i] = sum; } static int extract_covariate_snpids(char ***r_ids, char *snpid_list) { char *p, *q, **snp_ids; int n_snps; if (snpid_list == NULL) { *r_ids = NULL; return 0; } snp_ids = NULL; n_snps = 0; p = snpid_list; while((q = strsep(&p, ",")) != NULL) { if (n_snps % 8 == 0) snp_ids = realloc(snp_ids, sizeof(char *)*(n_snps + 8)); snp_ids[n_snps] = strdup(q); n_snps++; } *r_ids = snp_ids; return n_snps; } /* KONI - 2015-07-10 10 megabytes max input line. Properly, should be dynamically set based on actual input size. TODO: Implement using gzip'd tped file as the rest of the program does */ #define INPUT_LINEMAX (10*1048576) static int *load_covariate_marker(int n_indv, char *tped_basename, char *covariate_snpid) { char *tped_fname; char *inputbuf, *p, *q1, *q2, *snp_id; int *covariate_genotypes; FILE *f; int i, n; tped_fname = (char *) malloc(sizeof(char)*(strlen(tped_basename) + 10)); sprintf(tped_fname,"%s.tped", tped_basename); /* Add code to read gzip'd file */ f = fopen(tped_fname, "r"); if (f == NULL) { fprintf(stderr,"Can't open input file %s (%s)\n", tped_fname, strerror(errno)); exit(-1); } inputbuf = (char *) malloc(sizeof(char)*INPUT_LINEMAX); covariate_genotypes = (int *) malloc(sizeof(int)*n_indv); n = 0; while(fgets(inputbuf, INPUT_LINEMAX, f) != NULL) { CHOMP(inputbuf); if (inputbuf[0] == 0) continue; p = inputbuf; strsep(&p, " \t"); snp_id = strsep(&p, " \t"); if (strcmp(snp_id, covariate_snpid) != 0) continue; strsep(&p, " \t"); strsep(&p, " \t"); while((q1 = strsep(&p, " \t")) != NULL) { q2 = strsep(&p, " \t"); if (n >= n_indv) { fprintf(stderr,"Error: expecting %d individuals for covariate SNP %s but found more\n", n_indv, covariate_snpid); } covariate_genotypes[n] = encode_genotype(q1, q2); n++; } if (n < n_indv) { fprintf(stderr,"Error: expecting %d individuals for covariate SNP %s but found %d\n", n_indv, covariate_snpid, n); exit(-1); } break; } fclose(f); if (n == 0) { fprintf(stderr,"Error: covariate SNP %s was not found in %s. Substituting random genotypes\n", covariate_snpid, tped_fname); for(i=0; i < n_indv; i++) { double r = rand()/(RAND_MAX + 1.0); covariate_genotypes[i] = r < 0.5 ? -1. : 1; } } return covariate_genotypes; } /* KONI - 2015-07-11 - added this routine for aiding debugging */ static void __attribute__((unused))print_matrix(FILE *f, char *label, double *mat, int n, int m) { int j; fprintf(f,"%s\n",label); for(j=0; j < n; ++j) { int k; for(k=0; k < m; k++) fprintf(f," %1.2e\t",mat[j + k*n]); fprintf(f,"\n"); } } static double calculate_rsq(int *a, int *b, int nf) { double n, p1, p2, x00, x01, x10, x11, D; int i; n = 0.; p1 = 0.; p2 = 0.; x00 = x01 = x10 = x11 = 0.; for(i=0; i < nf; i++) { if (a[i] == GT_MISSING || b[i] == GT_MISSING) continue; if (a[i] == GT_AB && b[i] == GT_AB) continue; if (a[i] == GT_AA && b[i] == GT_AA) { x00+=2; } else if (a[i] == GT_AA && b[i] == GT_AB) { x00++; x01++; } else if (a[i] == GT_AA && b[i] == GT_BB) { x01+=2; } else if (a[i] == GT_AB && b[i] == GT_AA) { x00++; x10++; } else if (a[i] == GT_AB && b[i] == GT_AB) { /* Need EM to resolve this */ } else if (a[i] == GT_AB && b[i] == GT_BB) { x01++; x11++; } else if (a[i] == GT_BB && b[i] == GT_AA) { x10+=2; } else if (a[i] == GT_BB && b[i] == GT_AB) { x10++; x11++; } else if (a[i] == GT_BB && b[i] == GT_BB) { x11+=2; } n+=2; } p1 = (x00 + x01)/n; p2 = (x00 + x10)/n; x00 /= n; x01 /= n; x10 /= n; x11 /= n; D = x00 - p1*p2; return (D*D/(p1*(1.-p1)*p2*(1.-p2))); } static void print_output_header(FILE *f, char **covariate_snpids, int n_covariate_snps, int do_genetic_interaction_tests, int n_file_covariates) { int k; /* The simplest part, the tested marker in the scan */ fprintf(f,"Test marker\tchm\tpos\tPVE(model)\tPVE(genetic)\teffect(scan)\tp-value\tallele_freq\tPVE"); for(k=0; k < n_covariate_snps; k++) { fprintf(f,"\t%s\tp-value\trsq\tPVE", covariate_snpids[k]); } if (do_genetic_interaction_tests) { for(k=0; k < n_covariate_snps; k++) { fprintf(f,"\tI(%s)\tp-value", covariate_snpids[k]); } } /* Fixed covariates provided as seperate input file. Would normally contain the intercept term as the first column */ fprintf(f,"\tintercept\tp-value"); for(k=1; k < n_file_covariates; k++) fprintf(f,"\t(cov %d)\tp-value", k); fprintf(f,"\n"); } int main(int argc, char** argv) { int i, j, k, l, n, nf, q, q0, ngrids, ndigits, istart, iend, nelems, nmiss, *wids, c; char *kinf, *phenof, *tpedf, *covf, *outf, *inf, *delims, *lbuf; int mphenoflag, write_eig_flag, gz_flag, tped_nheadercols, tfam_nheadercols, zero_miss_flag, isnpid, gen_kin_method, gls_flag; double *phenos, *covs, *kins, *snps; double sum, llim, ulim, stat, p; clock_t cstart, cend, sum0, sum1, sum2, clapstart, clapend; struct HFILE phenosh, covsh, kinsh, tpedh, tfamh, eLvalsh, eLvecsh, remlh, outh; char **tped_headers, **tfam_headers, **phenos_indids, **covs_indids; double maf_threshold = 0.; char *covariate_snplist = NULL; char **covariate_snpids; int n_covariate_snps; int **covariate_genotypes; double **covariate_values; double *covariate_afreq; double *rsq; int do_genetic_interaction_tests = 0; cstart = clock(); sum0 = sum1 = sum2 = 0; llim = DEFAULT_LLIM; ulim = DEFAULT_ULIM; ngrids = DEFAULT_NGRIDS; mphenoflag = write_eig_flag = gen_kin_method = 0; delims = DEFAULT_DELIMS; tped_nheadercols = DEFAULT_TPED_NUM_HEADER_COLS; tfam_nheadercols = DEFAULT_TFAM_NUM_HEADER_COLS; zero_miss_flag = 1; isnpid = DEFAULT_TPED_SNPID_INDEX; //dosage_flag = 0; gls_flag = 1; // Read optional parameters q0 = i = 0; kinf = covf = tpedf = inf = outf = phenof = NULL; phenos = covs = kins = NULL; tped_headers = tfam_headers = phenos_indids = covs_indids = NULL; ndigits = DEFAULT_NDIGITS; istart = 0; iend = MAX_NUM_MARKERS; while ((c = getopt(argc, argv, "c:d:k:K:S:E:vi:o:p:t:wzD:P:F:ZONm:e:G")) != -1 ) { switch(c) { case 'c': // covariates input file covf = optarg; break; case 'd': // precision of digits ndigits = atoi(optarg); break; case 'k': //kinship file kinf = optarg; break; case 'K': // create kinship matrix with various methods // 1 : IBS matrix with avg fill-in // 2 : IBS matrix with rand fill-in // 3 : Balding-Nichols matrix gen_kin_method = atoi(optarg); break; case 'S': // start SNP index istart = atoi(optarg); break; case 'E': // end SNP index iend = atoi(optarg); break; case 'v': // turn on verbose mode g_verbose = 1; break; case 'i': // input file prefix inf = optarg; break; case 'o': // output file prefix outf = optarg; break; case 'p': // phenotype file phenof = optarg; break; case 't': // prefix for tped/tfam file tpedf = optarg; break; case 'w': // flag for writing eigenvalues/eigenvectors - ignored when -i is used write_eig_flag = 1; // write eigen files break; case 'z': // turn on gzip input mode gz_flag = 1; break; case 'D': // change delimiters : default " \t\n\r" delims = optarg; break; case 'P' : // change number of header columns in TPED file tped_nheadercols = atoi(optarg); break; case 'F' : // change the number of header columns in TFAM file tfam_nheadercols = atoi(optarg); break; case 'Z' : // dosage mode with one item per SNP zero_miss_flag = 0; break; //case 'O' : //dosage_flag = 1; //break; case 'N' : gls_flag = 0; break; /* KONI - 2015-07-09 - minor allele frequency/count threshold. If < 1.0, treated as a frequency. If > 1.0, treated as a minimum minor allele count */ case 'm' : maf_threshold = strtod(optarg, NULL); break; /* KONI - 2015-07-09 - option for specifying a specific marker to use as a fixed effect term in combination with every other marker that is tested. The marker specified itself will not be tested at all */ case 'e': covariate_snplist = optarg; break; /* KONI - 2015-07-10 - option for performing GxG interaction tests when a covariate SNP is specified. */ case 'G': do_genetic_interaction_tests = 1; break; default: fprintf(stderr,"Error : Unknown option character %c",c); print_help(); exit(-1); } } // Sanity check for the number of required parameters if ( argc > optind ) { print_help(); exit(-1);//abort(); } n_covariate_snps = extract_covariate_snpids(&covariate_snpids, covariate_snplist); if ( phenof == NULL ) { print_help(); emmax_error("Phenotype file must be specified\n"); } if ( outf == NULL ) { print_help(); emmax_error("Output prefix must be specified\n"); } if ( tpedf == NULL ) { print_help(); emmax_error("TPED file is not specified\n"); } g_logh = open_file_with_suffix(outf,"log",0,1); emmax_log("\nReading TFAM file %s.tfam ....\n",tpedf); tfamh = open_file_with_suffix(tpedf, "tfam", 0, 0); read_matrix_with_col_headers( &tfamh, tfam_nheadercols, delims, 0, 0, &nmiss, NULL, &tfam_headers); n = tfamh.nrows; snps = (double*)malloc(sizeof(double)*n); // snp matrix tped_headers = (char**)malloc(sizeof(char*)*n); lbuf = (char*) malloc(sizeof(char*) * SZ_LONG_BUF); if ( gen_kin_method > 0 ) { if ( kinf != NULL ) { print_help(); emmax_error("Kinship file cannot be specified with gen_kin_flag. [tped_prefix].kinf will be generated automatically"); } if ( tpedf == NULL ) { print_help(); emmax_error("TPED file must be specified with gen_kin_flag"); } emmax_log( "\nReading TPED file %s.tped to generate a kinship matrix...\n",tpedf); tpedh = open_file_with_suffix(tpedf, "tped", gz_flag, 0); if ( tpedh.gzflag == 0 ) { for(i=0; i < istart; ++i) { if ( fgets(lbuf, SZ_LONG_BUF, tpedh.fp ) == NULL ) { emmax_error("The input file %s ended reading before %d lines\n",tpedf,istart); } } } else { for(i=0; i < istart; ++i) { if ( gzgets( tpedh.gzfp, lbuf, SZ_LONG_BUF ) == NULL ) { emmax_error("The input file %s ended reading before %d lines\n",tpedf,istart); } } } sum = 0; kins = (double*) calloc(n*n, sizeof(double)); tpedh.nheadercols = tped_nheadercols; nmiss = 0; while ( tokenize_line_with_col_headers( &tpedh, tped_nheadercols, delims, zero_miss_flag, lbuf, snps, tped_headers, &nelems, &nmiss) != NULL ) { if ( tpedh.nrows % 1000 == 0 ) { emmax_log("Reading %d-th line of tped file for creating kinship matrix\n",tpedh.nrows); } if ( ( atoi(tped_headers[0]) == 0 ) || ( atoi(tped_headers[0]) > 22 ) ) { nmiss = 0; continue; } switch(gen_kin_method) { case KINSHIP_IBS_MEAN: sum += update_kinship_IBS_mean( kins, snps, n ); break; case KINSHIP_IBS_RAND: sum += update_kinship_IBS_rand( kins, snps, n ); break; case KINSHIP_BALDING_NICHOLS: sum += update_kinship_Balding_Nichols( kins, snps, n); break; } nmiss = 0; } symmetrize_and_normalize_kinship( kins, sum, n ); close_file(&tpedh); kinsh = open_file_with_suffix(tpedf, "kinf", 0, 1); for(i=0; i < n; ++i) { for(j=0; j < n; ++j) { if ( j > 0 ) fprintf(kinsh.fp,"\t"); fprintf(kinsh.fp,"%-.*lg",ndigits,kins[i+j*n]); } fprintf(kinsh.fp,"\t"); } close_file(&kinsh); } else { // Read the kinship matrix from the input file emmax_log( "\nReading kinship file %s...\n",kinf); if ( kinf == NULL ) { kinsh = open_file_with_suffix(tpedf,"kinf",0,0); //print_help(); //emmax_error("Kinship file must be specified without gen_kin_flag\n"); } else { kinsh = open_file(kinf, 0, 0); } read_matrix_with_col_headers(&kinsh, 0, delims, 0, 1, &nmiss, &kins, NULL ); emmax_log(" %d rows and %d columns were observed with %d missing values.\n",kinsh.nrows,kinsh.nvaluecols,nmiss); if ( ( kinsh.nrows != n ) || ( kinsh.nvaluecols != n ) ) { emmax_error("ERROR : Number of rows %d or columns %d is different from %d\n",kinsh.nrows,kinsh.nvaluecols,n); } } ensure_symmetry_and_relax_diag( kins, n, TOL, EIGEN_EPS ); // Read the phenotype matrix from the input file emmax_log("\nReading the phenotype file %s...\n",phenof); phenosh = open_file(phenof, 0, 0); read_matrix_with_col_headers(&phenosh, DEFAULT_PHENO_NUM_HEADER_COLS, delims, 0, 0, &nmiss, &phenos, &phenos_indids ); emmax_log(" %d rows and %d columns were observed with %d missing values\n",phenosh.nrows,phenosh.nvaluecols, nmiss); if ( nmiss > 0 ) { mphenoflag = 1; } fprintf(stderr,"nmiss = %d , mphenoflag = %d\n",nmiss, mphenoflag); if ( phenosh.nvaluecols != 1 ) { emmax_error("The number of columns in the phenotype file must be 1\n"); } if ( phenosh.nrows != n ) { emmax_error("The number of rows in tfam (%d) does not match with the number of phenotypes (%d)",n,phenosh.nrows,n); } if ( covf == NULL ) { emmax_log( "\nNo covariates were found... using intercept only \n"); covs = (double*)malloc(sizeof(double)*n); for(i=0; i < n; ++i) { covs[i] = 1.; } q0 = 1; } else { emmax_log( "\nReading covariate file %s...\n",covf); covsh = open_file(covf, 0, 0); read_matrix_with_col_headers(&covsh, DEFAULT_PHENO_NUM_HEADER_COLS, delims, 0, 0, &nmiss, &covs, &covs_indids ); //covs = read_matrix(covf, delims, &nrows, &ncols, &nmiss, 0); emmax_log(" %d rows and %d columns were observed with %d missing values. Make sure that the intercept is included in the covariates\n",covsh.nrows,covsh.nvaluecols,nmiss); q0 = covsh.nvaluecols; if ( nmiss > 0 ) { emmax_error("At this point, we do not allow missng covariates"); } if ( covsh.nrows != n ) { emmax_error("Number of rows %d is different from %d\n",covsh.nrows,n); } } // scan for missing phenotype and reorganize the inputs wids = (int*)malloc(sizeof(int)*n); double *K, *eLvals, *eLvecs; double trSKS; double optdelta, optvg, optve, REML, REML0, hg; double *X0; double *y, *yt; int n_genetic_effects = 1 + n_covariate_snps + (do_genetic_interaction_tests ? n_covariate_snps : 0); int tmp = q0 + n_genetic_effects; double *XDX = (double*)malloc(sizeof(double)*tmp*tmp); double *iXDX = (double*)malloc(sizeof(double)*tmp*tmp); double *XDy = (double*)malloc(sizeof(double)*tmp); double *betas = (double*)malloc(sizeof(double)*tmp); double yDy; // memory allocation y = (double*)malloc(sizeof(double)*n); yt = (double*)malloc(sizeof(double)*n); //fprintf(stderr,"foo\n"); //fprintf(stderr,"foo %d\n",mphenoflag); if ( mphenoflag == 0 ) { // no missing phenotypes - use the full variables with _b memcpy(y,phenos,sizeof(double)*n); nf = n; for(i=0; i < n; ++i) { wids[i] = i; } X0 = covs; K = kins; } else { // when missing phenotype exists // new y, X0, x1s matrix with wids are generated // variables are replaced with _p nf = 0; // set wids, and subselect y for(k=0; k < n; ++k) { if ( phenos[k] != DBL_MISSING ) { wids[nf] = k; y[nf] = phenos[wids[nf]]; ++nf; } } // subselect X0 from covs X0 = (double*) malloc(sizeof(double) * q0 * nf); for(k=0; k < nf; ++k) { for(l=0; l < q0; ++l) { // X0[k*q0+l] = covs[wids[k]*q0+l]; // RowMajor X0[k+l*nf] = covs[wids[k]+l*n]; // ColMajor } } // subselect K K = (double*) malloc(sizeof(double) * nf * nf); for(k=0; k < nf; ++k) { for(l=0; l < nf; ++l) { K[k+l*nf] = kins[wids[k]+wids[l]*n]; // RowMajor & ColMajor } } } /* KONI - this code should be moved to load_covariate_marker */ if (n_covariate_snps > 0) { covariate_genotypes = (int **) malloc(sizeof(int *)*n_covariate_snps); covariate_values = (double **) malloc(sizeof(double *)*n_covariate_snps); rsq = (double *) malloc(sizeof(double)*n_covariate_snps); covariate_afreq = (double *) malloc(sizeof(double)*n_covariate_snps); for(i=0; i < n_covariate_snps; i++) { covariate_genotypes[i] = load_covariate_marker(n, tpedf, covariate_snpids[i]); covariate_afreq[i] = compute_allele_frequency(covariate_genotypes[i], n); covariate_values[i] = (double *) malloc(sizeof(double)*n); set_genotype_values(covariate_values[i], covariate_genotypes[i], n); } } else { covariate_genotypes = NULL; covariate_values = NULL; rsq = NULL; covariate_afreq = NULL; } /* Koni - 2014-07-02 Added this to have the phenotype total variance in order to calculate how much of the variance is explained by a marker during marker by marker tests */ double phenotype_mean, phenotype_var; compute_phenotype_summary_stats(&phenotype_mean, &phenotype_var, y, nf); fprintf(stderr,"phenotype mean = %1.2f, standard deviation = %1.2f\n", phenotype_mean, sqrt(phenotype_var)); //standardize_phenotype(y, nf, phenotype_mean, sqrt(phenotype_var)); cend = clock(); emmax_log("File reading - elapsed CPU time is %.6lf\n",((double)(cend-cstart))/CLOCKS_PER_SEC); cstart = cend; if ( inf == NULL ) { double *eRvals, *eRvecs; fprintf(stderr,"Computing eigenvectors and eigenvalues.... \n"); eLvals = (double*)malloc(sizeof(double)*nf); eLvecs = (double*)malloc(sizeof(double)*nf*nf); eRvals = (double*)malloc(sizeof(double)*(nf-q0)); eRvecs = (double*)malloc(sizeof(double)*(nf-q0)*nf); trSKS = centered_trace(K,nf); //fprintf(stderr,"%d %d\n",nf,q0); // compute eigen_R and eigen_L eigen_R_wo_Z(nf, q0, K, X0, eRvals, eRvecs); emmax_log("eRvals[0] = %lf, eRvals[n-q-1] = %lf, eRvals[n-q] = %lf",eRvals[0],eRvals[nf-q0-1],eRvals[nf-q0]); cend = clock(); emmax_log("eigen_R - elapsed CPU time is %.6lf",((double)(cend-cstart))/CLOCKS_PER_SEC); cstart = cend; REML = REMLE_grid_wo_Z(nf, q0, y, X0, K, ngrids, llim, ulim, eRvals, eRvecs, &optdelta, &optvg, &optve, &REML0); free(eRvecs); free(eRvals); cend = clock(); emmax_log("REMLE (delta=%lf, REML=%lf, REML0=%lf)- elapsed CPU time is %.6lf",optdelta, REML, REML0, ((double)(cend-cstart))/CLOCKS_PER_SEC); cstart = cend; eigen_L_wo_Z(nf, K, eLvals, eLvecs); cend = clock(); emmax_log("eigen_L - elapsed CPU time is %.6lf\n",((double)(cend-cstart))/CLOCKS_PER_SEC); cstart = cend; hg = trSKS/((nf-1.)*optdelta+trSKS); remlh = open_file_with_suffix(outf,"reml",0,1); fprintf(remlh.fp,"%-.*lg\n",ndigits,REML); fprintf(remlh.fp,"%-.*lg\n",ndigits,REML0); fprintf(remlh.fp,"%-.*lg\n",ndigits,optdelta); fprintf(remlh.fp,"%-.*lg\n",ndigits,optvg); fprintf(remlh.fp,"%-.*lg\n",ndigits,optve); fprintf(remlh.fp,"%-.*lg\n",ndigits,hg); fclose(remlh.fp); if ( write_eig_flag ) { struct HFILE okinsh = open_file_with_suffix(outf,"kinf",0,1); for(i=0; i < nf; ++i) { for(j=0; j < nf; ++j) { if ( j > 0 ) fprintf(okinsh.fp,"\t"); fprintf(okinsh.fp,"%-.*lg",ndigits,K[i+j*nf]); // ColMajor } fprintf(okinsh.fp,"\n"); } fclose(okinsh.fp); eLvalsh = open_file_with_suffix(outf,"eLvals",0,1); for(i=0; i < nf; ++i) { fprintf(eLvalsh.fp,"%-.*lg\n",ndigits,eLvals[i]); } fclose(eLvalsh.fp); eLvecsh = open_file_with_suffix(outf,"eLvecs",0,1); for(i=0; i < nf; ++i) { for(j=0; j < nf; ++j) { if ( j > 0 ) fprintf(eLvecsh.fp,"\t"); fprintf(eLvecsh.fp,"%-.*lg",ndigits,eLvecs[i+j*nf]); // ColMajor } fprintf(eLvecsh.fp,"\n"); } fclose(eLvecsh.fp); } } else { eLvals = (double*)malloc(sizeof(double)*nf); eLvecs = (double*)malloc(sizeof(double)*nf*nf); remlh = open_file_with_suffix(inf,"reml",0,0); fscanf(remlh.fp,"%lf",&REML); fscanf(remlh.fp,"%lf",&REML0); fscanf(remlh.fp,"%lf",&optdelta); fscanf(remlh.fp,"%lf",&optvg); fscanf(remlh.fp,"%lf",&optve); fscanf(remlh.fp,"%lf",&hg); fclose(remlh.fp); eLvalsh = open_file_with_suffix(inf,"eLvals",0,0); for(i=0; i < nf; ++i) { if ( fscanf(eLvalsh.fp,"%lf",&eLvals[i]) == EOF ) { emmax_error("EOF reached while reading the eigenvector file"); } } fclose(eLvalsh.fp); eLvecsh = open_file_with_suffix(inf,"eLvecs",0,0); for(i=0; i < nf; ++i) { for(j=0; j < nf; ++j) { if ( fscanf(eLvecsh.fp,"%lf",&eLvecs[i+j*nf]) == EOF ) { // ColMajor emmax_error("FATAL ERROR : EOF reached while reading the eigenvector file\n"); } } } fclose(eLvecsh.fp); cend = clock(); emmax_log("Reading SVD & REML input - elapsed CPU time is %.6lf\n",((double)(cend-cstart))/CLOCKS_PER_SEC); cstart = cend; } // check if indids matches between phenos, covs, and tfam for(i=0; i < DEFAULT_PHENO_NUM_HEADER_COLS; ++i) { for(j=0; j < n; ++j) { if ( strcmp( tfam_headers[j+i*n], phenos_indids[j+i*n]) != 0 ) { emmax_error("Individual IDs do not match exactly in order between tfam and phenos file, but do not match at %s line %d : %s vs %s\n",(i==0) ? "FAMID" : "INDID", j+1, tfam_headers[j+i*n], phenos_indids[j+i*n]); } if ( covf != NULL ) { if ( strcmp( tfam_headers[j+i*n], covs_indids[j+i*n]) != 0 ) { emmax_error("Individual IDs do not match exactly in order between tfam and covs file, but do not match at %s line %d : %s vs %s\n",(i==0) ? "FAMID" : "INDID", j+1, tfam_headers[j+i*n], covs_indids[j+i*n]); } } } } if ( gls_flag == 1 ) { // transform y_p, X0_p, x1s_p to yt_p, X0t_p, x1ts_p double *X0t, *x1, *x1t; X0t = (double*) malloc(sizeof(double) * q0 * nf); x1 = (double*)malloc(sizeof(double)*nf*n_genetic_effects); // snp matrix x1t = (double*)malloc(sizeof(double)*nf*n_genetic_effects); // snp matrix fprintf(stderr,"Solving t(eLvecs) %%*%% X0...\n"); // X0t = t(eLvecs) %*% X0 // yt = t(eLvecs) %*% y #ifdef INTEL_COMPILER dgemm(&ct,&cn,&nf,&q0,&nf,&onef,eLvecs,&nf,X0,&nf,&zerof,X0t,&nf); dgemv( &ct,&nf, &nf, &onef, eLvecs, &nf, y, &onen, &zerof, yt, &onen); #else cblas_dgemm( CblasColMajor, CblasTrans, CblasNoTrans, nf, q0, nf, 1.0, eLvecs, nf, X0, nf, 0.0, X0t, nf ); cblas_dgemv(CblasColMajor, CblasTrans, nf, nf, 1., eLvecs, nf, y, 1, 0., yt, 1); #endif outh = open_file_with_suffix(outf,"ps",0,1); // symmetric - both RowMajor & ColMajor fill_XDX_X0 ( X0t, eLvals, optdelta, nf, q0, n_genetic_effects, XDX ); fill_XDy_X0 ( X0t, yt, eLvals, optdelta, nf, q0, XDy ); yDy = compute_yDy ( yt, eLvals, optdelta, nf ); // Read the snp matrix from the input file emmax_log( "\nReading TPED file %s...\n",tpedf); tpedh = open_file_with_suffix(tpedf, "tped", gz_flag, 0); tpedh.nheadercols = tped_nheadercols; if ( tpedh.gzflag == 0 ) { for(i=0; i < istart; ++i) { if ( fgets(lbuf, SZ_LONG_BUF, tpedh.fp ) == NULL ) { emmax_error("The input file %s ended reading before %d lines\n",tpedf,istart); } } } else { for(i=0; i < istart; ++i) { if ( gzgets( tpedh.gzfp, lbuf, SZ_LONG_BUF ) == NULL ) { emmax_error("The input file %s ended reading before %d lines\n",tpedf,istart); } } } nmiss = 0; clapstart = clock(); fprintf(stderr,"Starting marker tests...\n"); print_output_header(outh.fp, covariate_snpids, n_covariate_snps, do_genetic_interaction_tests, q0); double *gv = (double *) malloc(sizeof(double)*n); int *genotypes = (int *) malloc(sizeof(int)*n); double **interactions = (double **) malloc(sizeof(double)*n_covariate_snps); for(k=0; k < n_covariate_snps; k++) interactions[k] = (double *) malloc(sizeof(double)*n); /* get a base variance with no genetic effects. This is crude, we are going to substitue random values for the genetic terms of the model, solve it, and recover the variance explained. That variance is just that which is explained by the kinship matrix and any fixed covariate terms supplied as a file that are not genetic terms as per those specified on the command line, a genome scan marker, or any interaction term. */ srand(0xDEADBEEF); int trial; double null_model_residual_var = 0.; for(trial=0; trial < 1000; trial++) { for(k=0; k < n_genetic_effects; k++) { for(j=0; j < nf; j++) { double r = rand()/(RAND_MAX + 1.0); x1[j + nf*k] = r < 0.5 ? -1. : 1.; } } #ifdef INTEL_COMPILER dgemm(&ct, &cn, &nf, &n_genetic_effects, &nf, &onef, eLvecs, &nf, x1, &nf, &zerof, x1t, &nf); #else cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, nf, n_genetic_effects, nf, 1.0, eLvecs, nf, x1, nf, 0.0, x1t, nf); #endif fill_XDX_X1 ( X0t, x1t, eLvals, optdelta, nf, q0, n_genetic_effects, XDX ); fill_XDy_X1 ( x1t, yt, eLvals, optdelta, nf, q0, n_genetic_effects, XDy ); matrix_invert( q0+n_genetic_effects, XDX, iXDX ); q = q0+n_genetic_effects; #ifdef INTEL_COMPILER dgemv(&cn, &q, &q, &onef, iXDX, &q, XDy, &onen, &zerof, betas, &onen); #else // cblas_dgemv(CblasColMajor, CblasNoTrans, q0+1, q0+1, 1., iXDX, q0+1, XDy, 1, 0., betas, 1); cblas_dgemv(CblasColMajor, CblasNoTrans, q, q, 1., iXDX, q, XDy, 1, 0., betas, 1); #endif null_model_residual_var += (yDy - mult_vec_mat_vec(XDy, iXDX, q0 + n_genetic_effects))/ (nf - q0 - n_genetic_effects); } null_model_residual_var /= trial; fprintf(stderr,"Residual variance with no fixed genetic effects is %1.3f, total phenotype var %1.3f\n", null_model_residual_var, phenotype_var); /* genome scan loop */ for(i=istart; (i < iend) && ( tokenize_line_with_col_headers( &tpedh, tped_nheadercols, delims, zero_miss_flag, lbuf, snps, tped_headers, &nelems, &nmiss) != NULL ); ++i) { /* Do not analyze a SNP as a genome scan marker if it is also one of the covariate SNPs */ for(k=0; k < n_covariate_snps; k++) if (strcmp(tped_headers[isnpid], covariate_snpids[k]) == 0) break; if (n_covariate_snps > 0 && k < n_covariate_snps) continue; clapend = clock(); sum0 += (clapend-clapstart); if ( i % 10000 == 0 ) { emmax_log("Reading %d-th SNP and testing association....\n", i); } if ( nelems != n ) { emmax_error("The SNP file %s.tped do not have the adequate number of columns at line %d - (%d vs %d)\n", tpedf, i, nelems, n); } /* This nonsense is trying to stay compatible with the tokenize_line... () function call in the loop gaurd above. It is difficult to modify that function to use the genotype enum codes because it has a dual purpose for reading a matrix of floating point numbers as well. Really, a whole different file reading interface needs to be written to free us from that. What I want though is to have genotypes consistent between the covariate SNP[s] and the scan SNP so I can check for LD, and also so that I can change the decimal encoding of the variable, for whatever reason in ONE PLACE. Fortunately the function as is returns values (but in doubles) as 0, 1, 2, DBL_MISSING as is, so I just convert that to ints and hold my nose */ for(j=0; j < n; j++) { if (snps[j] != DBL_MISSING) { genotypes[j] = (int) snps[j]; } else { genotypes[j] = GT_MISSING; } } double allele_freq = compute_allele_frequency(genotypes, n); set_genotype_values(gv, genotypes, n); for(j=0; j < nf; ++j) x1[j] = gv[wids[j]]; /* KONI - 2015-07-09 - Skip if minor allele count is less than an integer value > 1 specified on command line (-m) */ if (maf_threshold >= 1.0 && (allele_freq*nf < maf_threshold || nf*(1 - allele_freq) < maf_threshold)) continue; /* KONI - 2015-07-09 - Skip if minor allele frequency is less than a proportion < 1.0 specified on the command line (-m) */ if (maf_threshold < 1.0 && (allele_freq < maf_threshold || 1.0 - allele_freq < maf_threshold)) continue; for(k=0; k < n_covariate_snps; k++) { rsq[k] = calculate_rsq(genotypes, covariate_genotypes[k], n); for(j=0; j < nf; j++) x1[j+(k+1)*nf] = covariate_values[k][wids[j]]; } if (do_genetic_interaction_tests) { for(k=0; k < n_covariate_snps; k++) { set_interaction_values(interactions[k], genotypes, covariate_genotypes[k], n); for(j=0; j < nf; j++) x1[j + (k+n_covariate_snps+1)*nf] = interactions[k][wids[j]]; } } clapstart = clock(); // x1t = t(eLvecs) %*% x1 // Ta TB M N K alpha A B Beta C #ifdef INTEL_COMPILER dgemm(&ct, &cn, &nf, &n_genetic_effects, &nf, &onef, eLvecs, &nf, x1, &nf, &zerof, x1t, &nf); #else cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, nf, n_genetic_effects, nf, 1.0, eLvecs, nf, x1, nf, 0.0, x1t, nf); //cblas_dgemv(CblasColMajor, CblasTrans, nf, nf, 1., eLvecs, nf, x1, 1, 0., x1t, 1); #endif fill_XDX_X1 ( X0t, x1t, eLvals, optdelta, nf, q0, n_genetic_effects, XDX ); fill_XDy_X1 ( x1t, yt, eLvals, optdelta, nf, q0, n_genetic_effects, XDy ); matrix_invert( q0+n_genetic_effects, XDX, iXDX ); q = q0+n_genetic_effects; #ifdef INTEL_COMPILER dgemv(&cn, &q, &q, &onef, iXDX, &q, XDy, &onen, &zerof, betas, &onen); #else // cblas_dgemv(CblasColMajor, CblasNoTrans, q0+1, q0+1, 1., iXDX, q0+1, XDy, 1, 0., betas, 1); cblas_dgemv(CblasColMajor, CblasNoTrans, q, q, 1., iXDX, q, XDy, 1, 0., betas, 1); #endif double residual_var = (yDy - mult_vec_mat_vec(XDy, iXDX, q0 + n_genetic_effects))/ (nf - q0 - n_genetic_effects); stat = betas[q0]/sqrt( iXDX[q0*(q0+n_genetic_effects)+q0] * residual_var ); clapend = clock(); sum1 += (clapend-clapstart); clapstart = clock(); p = tcdf(stat,nf-q0-n_genetic_effects); clapend = clock(); sum2 += (clapend-clapstart); /* Koni - 2014-07-02 Attempt at a cheap way to describe the percent of phenotypic variance explained by this marker. Under the simple additive quantitative genetic model, Vm = 2pq*(a + d*(q - p))^2, where Vm means genetic variance for this marker, p is the '1' allele frequency and q = 1 - p, -a is the deviation from the mean for an '00' genotype and +a is the deviation from the mean for a '11' genotype, d the deviation from the mean for a '01' or '10' genotype (a heterozygote). EMMAX assumes no dominance deviation (d = 0), and the genotype encoding I have switched to -1, 0, 1 above. Originally it was 0, 1, 2 */ double percent_variance_explained = 2.*allele_freq*(1. - allele_freq)* (betas[q0]*betas[q0])/phenotype_var*100.; /* Output the SNP id, chomosome, and position of the scan marker for this model */ fprintf(outh.fp,"%s",tped_headers[isnpid]); fprintf(outh.fp,"\t%s",tped_headers[0]); fprintf(outh.fp,"\t%s",tped_headers[3]); /* Output the percent variance explained of the whole model and PVE of genetic effects */ fprintf(outh.fp,"\t%3.1f", (1. - residual_var/phenotype_var)*100.); fprintf(outh.fp,"\t%3.1f", (1. - residual_var/null_model_residual_var)*100.); /* Output the beta, p-value, allele frequency, and PVE for the scan marker */ fprintf(outh.fp,"\t%+6.3f", betas[q0]); fprintf(outh.fp,"\t%4.2f", -log10(p)); fprintf(outh.fp,"\t%5.3f", allele_freq); fprintf(outh.fp,"\t%4.2f", percent_variance_explained); /* Output terms for covariate SNPs that were modeled along with the scan marker */ for(k=0; k < n_covariate_snps; k++) { fprintf(outh.fp,"\t%+6.3f", betas[q0+k+1]); stat = betas[q0+k+1]/ sqrt( iXDX[(q0+k+1)*(q0+n_genetic_effects)+q0+k+1]* ( yDy - mult_vec_mat_vec( XDy, iXDX, q0+n_genetic_effects ) ) / ( nf - q0 - n_genetic_effects ) ); p = tcdf(stat, nf-q0-n_genetic_effects); fprintf(outh.fp,"\t%4.2f", -log10(p)); fprintf(outh.fp,"\t%5.3f", rsq[k]); percent_variance_explained = 2*covariate_afreq[k]*(1. - covariate_afreq[k])* (betas[q0+k+1]*betas[q0+k+1])/phenotype_var*100.; fprintf(outh.fp,"\t%4.2f", percent_variance_explained); } /* If genetic interaction terms were modeled, output their betas and p-values */ if (do_genetic_interaction_tests) { for(k=0; k < n_covariate_snps; k++) { int col = q0 + n_covariate_snps +1 + k; int df = nf - q0 - n_genetic_effects; fprintf(outh.fp,"\t%+6.3f", betas[col]); stat = betas[col]/ sqrt( iXDX[(col)*(q0+n_genetic_effects)+col]* ( yDy - mult_vec_mat_vec( XDy, iXDX, q0+n_genetic_effects ) ) / df ); p = tcdf(stat, df); fprintf(outh.fp,"\t%4.2f", -log(p)); } } /* Output external covariate terms, including intercept, in columns following the genetic effects above */ for(k=0; k < q0; k++) { fprintf(outh.fp,"\t%6.3f", betas[k]); stat = betas[k]/sqrt( iXDX[k*(q0+n_genetic_effects) + k]*( yDy - mult_vec_mat_vec( XDy, iXDX, q0+n_genetic_effects ) ) / (nf - q0 - n_genetic_effects)); p = tcdf(stat, nf-q0-n_genetic_effects); fprintf(outh.fp,"\t%4.2f", -log10(p)); } fprintf(outh.fp,"\n"); //memset(snps, 0, sizeof(double)*n); nmiss = 0; clapstart = clock(); } close_file(&tpedh); close_file(&outh); free(X0t); free(x1t); free(x1); } cend = clock(); emmax_log("GLS association - elapsed CPU time is %.6lf\n",((double)(cend-cstart))/CLOCKS_PER_SEC); emmax_log("Breakdown for input file parsing : %.6lf\n",((double)sum0)/CLOCKS_PER_SEC); emmax_log(" matrix computation : %.6lf\n",((double)sum1)/CLOCKS_PER_SEC); emmax_log(" p-value computation : %.6lf\n",((double)sum2)/CLOCKS_PER_SEC); cstart = cend; if ( mphenoflag == 1 ) { free(covs); free(K); free(X0); } if ( tped_headers != NULL ) free(tped_headers); if ( covf != NULL ) free(covs_indids); if ( snps != NULL ) free(snps); if ( lbuf != NULL ) free(lbuf); if ( tfam_headers != NULL ) free(tfam_headers); if ( phenos_indids!= NULL ) free(phenos_indids); free(kins); free(phenos); free(XDX); free(iXDX); free(XDy); free(betas); free(wids); free(y); free(yt); free(eLvals); free(eLvecs); return 0; } // ** eig.L = eigen(K) // return values are stored in vp_eigL (eigenvalues) and mp_eigL (eigenvectors) int eigen_L_wo_Z(int n, double* kins, double* eLvals, double* eLvecs ) { // return eigen_decomposition(n,kins,eLvecs,eLvals); int i; double* kins_copy = (double*)malloc(sizeof(double)*n*n); memcpy(kins_copy,kins,sizeof(double)*n*n); for(i=0; i < n; ++i) { kins_copy[i*n+i] += EIGEN_ADD; } int info = eigen_decomposition(n, kins_copy, eLvecs, eLvals); for(i=0; i < n; ++i) { eLvals[i] -= EIGEN_ADD; } free(kins_copy); return info; } // ** S = I - X(X'X)^{-1}X' // ** eig = eigen(S(K+I)S) // ** ids = (eig$values-1) > 0 // ** values = eig$values[ids] // ** vectors = eig$vectors[,ids] // return values are stored in vp_eigL (size n-q) and mp_eigL (n * n-q) int eigen_R_wo_Z(int n, int q, double* kins, double* X, double* eRvals, double* eRvecs) { int i, j, k, l, info; double* kins_copy = (double*)malloc(sizeof(double)*n*n); memcpy(kins_copy,kins,sizeof(double)*n*n); for(i=0; i < n; ++i) { kins_copy[i*n+i] += EIGEN_ADD; } // first compute XtX = t(X) %*% X double* XtX = (double*)calloc(q*q, sizeof(double)); #ifdef INTEL_COMPILER dgemm(&ct,&cn,&q,&q,&n,&onef,X,&n,X,&n,&zerof,XtX,&q); #else cblas_dgemm(CblasColMajor,CblasTrans,CblasNoTrans,q,q,n,1.,X,n,X,n,0.,XtX,q); #endif // Compute iXtX = solve(XtX) double* iXtX = (double*)calloc(q*q, sizeof(double)); matrix_invert(q, XtX, iXtX); // Compute XtiXtXX X %*% solve(t(X)%*%X) %*%t(X) double* XiXtX = (double*)calloc(n*q, sizeof(double)); #ifdef INTEL_COMPILER dgemm(&cn,&cn,&n,&q,&q,&onef,X,&n,iXtX,&q,&zerof,XiXtX,&n); #else cblas_dgemm(CblasColMajor,CblasNoTrans,CblasNoTrans,n,q,q,1.,X,n,iXtX,q,0.,XiXtX,n); #endif // S = I double* S = (double*)calloc(n*n,sizeof(double)); for(i=0; i < n; ++i) { S[i+i*n] = 1.; } // S = -1*(XtiXtX %*%t(X) + 1*(S=I) #ifdef INTEL_COMPILER dgemm(&cn, &ct, &n, &n, &q, &minusonef, XiXtX, &n, X, &n, &onef, S, &n); #else cblas_dgemm(CblasColMajor,CblasNoTrans,CblasTrans,n,n,q,-1.,XiXtX,n,X,n,1.,S,n); #endif //fprintf(stderr,"S[0] = %lf, S[1] = %lf, S[n*n-1] = %lf\n",S[0],S[1],S[n*n-1]); // SKS = S %*% K %*% S double* SK = (double*)calloc(n*n,sizeof(double)); #ifdef INTEL_COMPILER dgemm(&cn, &cn, &n, &n, &n, &onef, S, &n, kins_copy, &n, &zerof, SK, &n); #else cblas_dgemm(CblasColMajor,CblasNoTrans,CblasNoTrans,n,n,n,1.,S,n,kins_copy,n,0.,SK,n); #endif //fprintf(stderr,"kins[0] = %lf, kins[1] = %lf, kins[n*n-1] = %lf\n",kins[0],kins[1],kins[n*n-1]); double* SKS = (double*)calloc(n*n,sizeof(double)); #ifdef INTEL_COMPILER dgemm(&cn, &cn, &n, &n, &n, &onef, SK, &n, S, &n, &zerof, SKS, &n); #else cblas_dgemm(CblasColMajor,CblasNoTrans,CblasNoTrans,n,n,n,1.,SK,n,S,n,0.,SKS,n); #endif //ensure_symmetry_and_relax_diag( SKS, n, TOL, TOL ); double* evals = (double*)malloc(sizeof(double)*n); double* evecs = (double*)malloc(sizeof(double)*n*n); info = eigen_decomposition(n, SKS, evecs, evals); fprintf(stderr,"evals[0] = %lf, evals[1] = %lf, evals[n-1] = %lf\n",evals[0],evals[1],evals[n-1]); // Assuming that the eigenvalues are unordered, // relocate the smallest eigenvalues at the end // relocated the corresponding eigenvectors accordingly // if negative eigenvalues < -(TOL) observed, report fatal errors // time complexity should be q*n double* minevals = (double*)malloc(sizeof(double)*q); int* minids = (int*)malloc(sizeof(int)*q); // initalize the minimum eigenvalues for(i=0; i < q; ++i) { minevals[i] = DBL_MAX; minids[i] = -1; } // scan from the first element, and compare with the q-th smallest eigenvalues for(i=0; i < n; ++i) { if ( evals[i] < 0-TOL ) { fprintf(stderr,"FATAL ERROR : Eigenvalues of SKS is %lf\n",evals[i]); } // minevals[0] is the largest one if ( evals[i] < minevals[0] ) { // find minimum j that evals[i] > minevals[j] for(j=0; (evals[i] < minevals[j]) && ( j < q ); ++j); // shift all minevals before j for(k=1; k < j-1; ++k) { minevals[k-1] = minevals[k]; minids[k-1] = minids[k]; } minevals[j-1] = evals[i]; minids[j-1] = i; } } // scan if all minevals are between -TOL and TOL for(i=0; i < q; ++i) { if ( ( minevals[i] > TOL ) || ( minevals[i] < 0-TOL ) ) { fprintf(stderr,"FATAL ERROR : Minimum q eigenvalues of SKS is supposed to be close to zero, but actually %lf\n",minevals[i]); } } /* // extract q eigenvalues closest to zero double* minabs = (double*)malloc(sizeof(double)*q); int* minids = (int*)malloc(sizeof(int)*q); for(i=0; i < q; ++i) { minabs[i] = DBL_MAX; minids[i] = -1; } for(i=0; i < n; ++i) { for(j=0; j < q; ++j) { if ( evals[i] < minabs[j] ) { for(k=q-1; k > j; --k) { minabs[k] = minabs[k-1]; minids[k] = minids[k-1]; } minabs[j] = evals[i]; minids[j] = i; break; } } }*/ // exclude minidx[0..q] to copy the eigenvalues and eigenvectors for(i=0,k=0; i < n; ++i) { for(j=0; j < q; ++j) { if ( minids[j] == i ) break; } if ( j == q ) { eRvals[k] = evals[i]-EIGEN_ADD; for(l=0; l < n; ++l) { // trying to do eRvecs(l,k) = evecs(l,i) // make sure that k < n-q // eRvecs[l*(n-q)+k] = evecs[l*n+i]; //RowMajor eRvecs[l+n*k] = evecs[l+i*n]; } ++k; } if ( k > n-q ) { fprintf(stderr,"FATAL ERROR : k = %d > n-q = %d\n", k, n-q); abort(); } } fprintf(stderr,"k = %d, n-q = %d\n", k, n-q); free(XtX); free(iXtX); free(XiXtX); free(S); free(SK); free(SKS); free(evals); free(evecs); free(minids); free(minevals); free(kins_copy); return info; } double LL_REML_wo_Z(int nq, double logdelta, double* lambdas, double* etas) { int i; double delta = exp(logdelta); long double sum1 = 0.; long double sum2 = 0.; for(i=0; i < nq; ++i) { sum1 += etas[i]*etas[i]/(lambdas[i]+delta); sum2 += log(lambdas[i]+delta); } return( 0.5*(nq*(log(nq/(2*M_PI))-1.-log(sum1))-sum2) ); } double LL_REML_wo_Z_inf_delta(int nq, double* lambdas, double* etas) { int i; long double sum1 = 0.; for(i=0; i < nq; ++i) { sum1 += etas[i]*etas[i]; } return( 0.5*(nq*(log(nq/(2*M_PI))-1.-log(sum1))) ); } double dLL_REML_wo_Z(int nq, double logdelta, double* lambdas, double* etas) { int i; double delta = exp(logdelta); long double sum1 = 0.; long double sum2 = 0.; long double sum3 = 0.; double f; for(i=0; i < nq; ++i) { f = (etas[i]*etas[i])/(lambdas[i]+delta); sum1 += f/(lambdas[i]+delta); sum2 += f; sum3 += 1./(lambdas[i]+delta); } return (0.5*(nq*sum1/sum2-sum3)); } double bis_root_REML_wo_Z(double x1, double x2, double xacc, int nq, double* lambdas, double* etas) { int j; double dx, xmid, rtb; double f = dLL_REML_wo_Z(nq,x1,lambdas,etas); double fmid = dLL_REML_wo_Z(nq,x2,lambdas,etas); //fprintf(stderr,"%lg\t%lg\n",f,fmid); if ( f*fmid > 0 ) { fprintf(stderr,"Error in bis_root_REML_wo_Z : function value has the same sign in both ends - (%lg, %lg)\n",f,fmid); abort(); } rtb = f < 0.0 ? (dx = x2-x1,x1) : (dx = x1-x2,x2); for(j=0; j < ITMAX; ++j) { fmid = dLL_REML_wo_Z(nq,xmid=rtb+(dx *= 0.5),lambdas,etas); //fprintf(stderr,"%d\t%lg\t%lg\n",j,xmid,fmid); if ( fmid <= 0.0 ) rtb = xmid; if ( fabs(dx) < xacc || fmid == 0.0 ) return rtb; } fprintf(stderr,"Too many bisections in rtbis\n"); abort(); } /* double prop_search_root_REML_wo_Z(double x1, double x2, double xacc, int nq, double* lambdas, double* etas) { int j; double dx, xmid, rtb, prop, fpos; // compute the function values at the end double f = dLL_REML_wo_Z(nq,x1,lambdas,etas); double fmid = dLL_REML_wo_Z(nq,x2,lambdas,etas); double w = 0.01; if ( f*fmid > 0 ) { fprintf(stderr,"Error in bis_root_REML_wo_Z : function value has the same sign in both ends - (%lg, %lg)\n",f,fmid); abort(); } // rtb is the negative side // prop is the (negative/positive) rtb = (f < 0.0) ? (dx = x2-x1, fpos = fmid, fmid = f, x1) : (dx = x1-x2, fpos = f, x2); for(j=0; j < ITMAX; ++j) { // fmid = dLL_REML_wo_Z(nq,xmid=rtb+(dx *= 0.5),lambdas,etas); prop = (0-fmid)/(fpos-fmid); fmid = dLL_REML_wo_Z(nq,xmid=rtb+(dx *= (w*0.5+(1.-w)*prop)),lambdas,etas); fprintf(stderr,"%d\t%lg\t%lg\n",j,xmid,fmid); if ( fmid <= 0.0 ) { rtb = xmid; } else { fpos = fmid; } if ( fabs(dx) < xacc || fmid == 0.0 ) return rtb; } fprintf(stderr,"Too many bisections in rtbis\n"); abort(); }*/ double brent_REML_wo_Z(double ax, double bx, double cx, double tol, double *xmin, int nq, double* lambdas, double* etas) { int iter; double a,b,etemp,fu,fv,fw,fx,p,q,r,tol1,tol2,u,v,w,x,xm; double d=0.0; double e=0.0; a=(ax < cx ? ax : cx); b=(ax > cx ? ax : cx); x=w=v=bx; fw=fv=fx=LL_REML_wo_Z(nq,x,lambdas,etas); for (iter=1;iter<=ITMAX;iter++) { xm=0.5*(a+b); tol2=2.0*(tol1=tol*fabs(x)+ZEPS); if (fabs(x-xm) <= (tol2-0.5*(b-a))) { *xmin=x; return fx; } if (fabs(e) > tol1) { r=(x-w)*(fx-fv); q=(x-v)*(fx-fw); p=(x-v)*q-(x-w)*r; q=2.0*(q-r); if (q > 0.0) p = -p; q=fabs(q); etemp=e; e=d; if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) d=CGOLD*(e=(x >= xm ? a-x : b-x)); else { d=p/q; u=x+d; if (u-a < tol2 || b-u < tol2) d=SIGN(tol1,xm-x); } } else { d=CGOLD*(e=(x >= xm ? a-x : b-x)); } u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); fu=LL_REML_wo_Z(nq,u,lambdas,etas); if (fu <= fx) { if (u >= x) a=x; else b=x; SHFT(v,w,x,u) SHFT(fv,fw,fx,fu) } else { if (u < x) a=u; else b=u; if (fu <= fw || w == x) { v=w; w=u; fv=fw; fw=fu; } else if (fu <= fv || v == x || v == w) { v=u; fv=fu; } } } fprintf(stderr,"Too many iterations in brent\n"); exit(-1); } double REMLE_grid_wo_Z(int n, int q, double* ys, double* xs, double* kins, int ngrids, double llim, double ulim, double* evals, double* evecs, double* optdelta, double* optvg, double* optve, double* pREML0) { int i; double tmp, tmp2; // etas = t(eigR) %*% ys double* etas = (double*)calloc(n-q,sizeof(double)); double* grids = (double*)malloc(sizeof(double)*(ngrids+1)); double* dLLs = (double*)malloc(sizeof(double)*(ngrids+1)); // etas = t(evecs) %*% ys cblas_dgemv(CblasColMajor, CblasTrans, n, n-q, 1., evecs, n, ys, 1, 0., etas, 1); for(i=0; i <= ngrids; ++i) { grids[i] = llim + (ulim-llim)/ngrids*i; dLLs[i] = dLL_REML_wo_Z(n-q, grids[i], evals, etas); } for(i=0; i < n-q; ++i) { emmax_log("etas[%d] = %lf, lambdas[%d] = %lf",i,etas[i],i,evals[i]); } //fprintf(stderr,"%lg\n",evals[0]); //fprintf(stderr,"%lg\n",evecs[0]); double maxREML = 0-DBL_MAX; double maxREMLlogdelta = 0; if ( dLLs[0] < EPS ) { tmp = LL_REML_wo_Z(n-q,llim,evals,etas); if ( tmp > maxREML ) { maxREMLlogdelta = llim; maxREML = tmp; } } if ( dLLs[1] > 0-EPS ) { tmp = LL_REML_wo_Z(n-q,ulim,evals,etas); if ( tmp > maxREML ) { maxREMLlogdelta = ulim; maxREML = tmp; } } for(i=0; i < ngrids; ++i) { if ( ( dLLs[i]*dLLs[i+1] < 0 ) && ( dLLs[i] > 0 ) && ( dLLs[i+1] < 0 ) ) { tmp2 = bis_root_REML_wo_Z(grids[i],grids[i+1],XACCU,n-q,evals,etas); tmp = LL_REML_wo_Z(n-q,tmp2,evals,etas); //fprintf(stderr,"%lg\t%lg\t%lg\n",grids[i],grids[i+1],tmp2); if ( tmp > maxREML ) { maxREMLlogdelta = tmp2; maxREML = tmp; } } emmax_log("%d\t%lf\t%lf\t%lf\n",i,dLLs[i],dLLs[i+1],LL_REML_wo_Z(n-q,grids[i],evals,etas)); } (*optdelta) = exp(maxREMLlogdelta); (*optvg) = 0; for(i=0; i < n-q; ++i) { (*optvg) += etas[i]*etas[i]/(evals[i]+(*optdelta)); } (*optvg) /= (n-q); (*optve) = (*optvg) * (*optdelta); (*pREML0) = LL_REML_wo_Z_inf_delta(n-q,evals,etas); free(etas); free(dLLs); free(grids); return(maxREML); } void close_file(struct HFILE* fhp) { if ( fhp->gzflag == 1 ) { gzclose(fhp->gzfp); fhp->gzfp = NULL; } else { fclose(fhp->fp); fhp->fp = NULL; } } // open_file() // - filename : file name to open // - gzflag : gzip flag (use gzfp if gzflag=1, otherwise use fp) // - wflag : write flag (1 if write mode otherwise read mode) struct HFILE open_file(char* filename, int gzflag, int wflag) { struct HFILE fh; fh.gzflag = gzflag; fh.wflag = wflag; fh.nheadercols = 0; fh.nvaluecols = 0; fh.nrows = 0; if ( gzflag == 1 ) { char* mode = (wflag == 1) ? "wb" : "rb"; fh.gzfp = gzopen(filename,mode); fh.fp = NULL; if ( fh.gzfp == NULL ) { emmax_error("Cannot open file %s for %s",filename,(wflag == 1) ? "writing" : "reading"); } } else { char* mode = (wflag == 1) ? "w" : "r"; fh.gzfp = (gzFile) NULL; fh.fp = fopen(filename,mode); if ( fh.fp == NULL ) { emmax_error("Cannot open file %s for %s",filename,(wflag == 1) ? "writing" : "reading"); } } return fh; } // open_file_with_suffix() // - [prefix].[suffix] : file name to open // - gzflag : gzip flag (use gzfp if gzflag=1, otherwise use fp) // - wflag : write flag (1 if write mode otherwise read mode struct HFILE open_file_with_suffix(char* prefix, char* suffix, int gzflag, int wflag) { char filename[SZBUF]; sprintf(filename,"%s.%s",prefix,suffix); return open_file(filename,gzflag,wflag); } // fill X0-only part t(X0) %*% D %*% X0 onto XDX matrix // for computing t(X) %*% D^{-1} %*%X where D is a diagnoal matrix // XDX : (q0+1)*(q0+1) matrix // X0 : n * q0 matrix (left q0 cols of X) // eLvals : size n vector // delta : double void fill_XDX_X0 ( double* X0, double* eLvals, double delta, int n, int q0, int n_genetic_effects, double* XDX) { int i, j, k; double tmp; for(i=0; i < q0; ++i) { for(j=0; j <= i; ++j) { tmp = 0; for(k=0; k < n; ++k) { tmp += ((X0[k+i*n]*X0[k+j*n])/(eLvals[k]+delta)); } XDX[i+j*(q0+n_genetic_effects)] = tmp; if ( j < i ) XDX[j+i*(q0+n_genetic_effects)] = tmp; } } } static int double_compare(const void *c, const void *d) { const double *a = (const double *) c; const double *b = (const double *) d; if (a < b) return -1; if (a > b) return 1; return 0; } // fill X1-dependent part for computing // XDX = t(X) %*% D %*% X // where X = [X0 x1], dim(X0) = (n,q), dim(x1) = (n,1) void fill_XDX_X1 ( double* X0, double* x1, double* eLvals, double delta, int n, int q0, int m, double* XDX ) { int i, j, k; double tmp[n]; for(k=0; k < m; k++) { for(i=0; i < q0; ++i) { for(j=0; j < n; ++j) { tmp[j] = ((X0[j+i*n]*x1[j + k*n])/(eLvals[j]+delta)); } qsort(tmp, n, sizeof(double), double_compare); for(j=1; j < n; j++) tmp[0] += tmp[j]; XDX[i+(q0+m)*(q0+k)] = tmp[0]; // fill the last column vector - XDX[i,q0] XDX[(q0+k)+(q0+m)*i] = tmp[0]; // fill the last row vector - XDX[q0,i] } } for(i=0; i < m; i++) { for(j=0; j <= i; j++) { for(k=0; k < n; k++) tmp[k] = x1[k + i*n]*x1[k + j*n]/(eLvals[k]+delta); qsort(tmp, n, sizeof(double), double_compare); for(k=1; k < n; k++) tmp[0] += tmp[k]; XDX[i+q0+(q0+m)*(q0+j)] = tmp[0]; XDX[j+q0+(q0+m)*(q0+i)] = tmp[0]; } } } // fill X0-dependent part (first q0 elements) for computing // XDy = t(X) %*% D %*% y // where X = [X0 x1], dim(X0) = (n,q), dim(x1) = (n,1), dim(y) = (n,1) void fill_XDy_X0 ( double* X0, double* y, double* eLvals, double delta, int n, int q0, double* XDy ) { int i, j; double tmp[n]; for(i=0; i < q0; ++i) { for(j=0; j < n; ++j) { tmp[j]= ((X0[j+n*i]*y[j])/(eLvals[j]+delta)); } qsort(tmp, n, sizeof(double), double_compare); for(j=1; j < n; j++) tmp[0] += tmp[j]; XDy[i] = tmp[0]; } } // fill X1-dependent part (the ladt element) for computing // XDX = t(X) %*% D %*% X // where X = [X0 x1], dim(X0) = (n,q), dim(x1) = (n,1) void fill_XDy_X1 ( double* x1, double* y, double* eLvals, double delta, int n, int q0, int m, double* XDy ) { int i, k; double tmp[n]; for(k=0; k < m; k++) { for(i=0; i < n; ++i) { tmp[i] = ((x1[i+(n*k)]*y[i])/(eLvals[i]+delta)); } qsort(tmp, n, sizeof(double), double_compare); for(i=1; i < n; i++) tmp[0] += tmp[i]; XDy[q0+k] = tmp[0]; } } // compute yDy = t(y) %*% D %*% y and return it double compute_yDy ( double* y, double *eLvals, double delta, int n ) { int i; double tmp[n]; for(i=0; i < n; ++i ) { tmp[i] = ((y[i]*y[i])/(eLvals[i]+delta)); } qsort(tmp, n, sizeof(double), double_compare); for(i=1; i < n; i++) tmp[0] += tmp[i]; return tmp[0]; } // compute t(vec) %*% mat %*% vec // for a general bector and symmetric matrix vec and mat double mult_vec_mat_vec ( double* vec, double* mat, int n ) { int i, j; double tmp1[n]; double tmp2[n]; for(i=0; i < n; ++i) { for(j=0; j < n; ++j) { tmp2[j] = (vec[i]*vec[j]*mat[i+j*n]); } qsort(tmp2, n, sizeof(double), double_compare); for(j=1; j < n; j++) tmp2[0] += tmp2[j]; tmp1[i] = tmp2[0]; } qsort(tmp1, n, sizeof(double), double_compare); for(i=1; i < n; i++) tmp1[0] += tmp1[i]; return tmp1[0]; } // read_matrix_with_col_headers() // - read [filename] by each line, separate by delim, and store as a row vector and return as one-dimensional array with row count and column count // - after reading the matrix in a row major order, the matrix is transposed into a column major order and returned void read_matrix_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, int zero_miss_flag, int symmetric, int* p_nmiss, double** matrix, char*** headers) { int nvalues, i, j, nmiss; double *fmat; char **fheaders; char* lbuf = (char*) malloc(sizeof(char*) * SZ_LONG_BUF); int szmat = DEFAULT_SIZE_MATRIX; int szheader = DEFAULT_SIZE_HEADER; double* cmat = (double*) malloc(sizeof(double) * szmat ); char** cheaders = (char**) malloc(sizeof(char*) * szheader ); fhp->nheadercols = nheadercols; nmiss = 0; while( tokenize_line_with_col_headers(fhp, nheadercols, delims, zero_miss_flag, lbuf, &cmat[fhp->nrows*fhp->nvaluecols], &cheaders[fhp->nrows*fhp->nheadercols], &nvalues, &nmiss) != NULL ) { if ( fhp->nrows == 1 ) { fhp->nvaluecols = nvalues; } else if ( fhp->nvaluecols != nvalues ) { emmax_error("The column size %d do not match to %d at line %d\n",nvalues,fhp->nvaluecols,fhp->nrows); } if ( (fhp->nrows+1)*(fhp->nheadercols) > szheader ) { szheader *= 2; fprintf(stderr,"Header size is doubled to %d\n",szheader); cheaders = (char**) realloc( cheaders, sizeof(char*) * szheader ); } if ( (fhp->nrows+1)*(fhp->nvaluecols) > szmat ) { szmat *= 2; fprintf(stderr,"Matrix size is doubled to %d\n",szmat); cmat = (double*) realloc( cmat, sizeof(double) * szmat ); } } free(lbuf); *p_nmiss = nmiss; fmat = (double*) malloc(sizeof(double)*fhp->nrows*fhp->nvaluecols); fheaders = (char**) malloc(sizeof(char*)*fhp->nrows*fhp->nheadercols); for(i=0; i < fhp->nrows; ++i) { for(j=0; j < fhp->nvaluecols; ++j) { fmat[i+j*fhp->nrows] = cmat[i*fhp->nvaluecols+j]; } for(j=0; j < fhp->nheadercols; ++j) { fheaders[i+j*fhp->nrows] = cheaders[i*fhp->nheadercols+j]; } } free(cmat); free(cheaders); if ( matrix != NULL ) { if ( *matrix != NULL ) { free(*matrix); } *matrix = fmat; } if ( headers != NULL ) { if ( *headers != NULL ) { free(*headers); } *headers = fheaders; } } // tokenize_line_with_col_headers() // read one line from the filestream fp, and tokenizes using delim, and store the elements to tgt with the number of elements to p_nelems. NULL is returned if EOF is reached double* tokenize_line_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, int zero_miss_flag, char* lbuf, double* values, char** headers, int* p_nvalues, int* p_nmiss ) { int j; char *token, *next; char *ret = (fhp->gzflag == 1) ? gzgets(fhp->gzfp, lbuf, SZ_LONG_BUF) : fgets( lbuf, SZ_LONG_BUF, fhp->fp ); int nmiss = 0; if ( ret == NULL ) { return NULL; } if ( fhp->nheadercols != nheadercols ) { emmax_error("# of header columns mismatch (%d vs %d) at line %d",fhp->nheadercols,nheadercols,fhp->nrows); } //fprintf(stderr,"tokenize-line called %s\n",lbuf); token = strtok(lbuf, delims); for( j=0; token != NULL; ++j ) { if ( j < nheadercols ) { headers[j] = strdup(token); } // if zero_miss_flag is set, assume the genotypes are encoded 0,1,2 // Additively encodes the two genotypes in the following way // when (j-nheadercols) is even, 0->MISSING, add 1->0, 2->1 // when (j-nheadercols) is odd, check 0-0 consistency, and add 1->0, 2->1 else if ( zero_miss_flag == 1 ) { if ( (j-nheadercols) % 2 == 0 ) { if ( strcmp(token,"0") == 0 ) { values[(j-nheadercols)/2] = DBL_MISSING; ++nmiss; } else if ( strcmp(token,"1") == 0 ) { values[(j-nheadercols)/2] = 0; } else if ( strcmp(token,"2") == 0 ) { values[(j-nheadercols)/2] = 1; } else { emmax_error("Only 0,1,2 are expected for genotypes, but %s is observed",token); } } else { if ( values[(j-nheadercols)/2] == DBL_MISSING ) { if ( strcmp(token,"0") != 0 ) { emmax_error("0 0 is expected but 0 %s is observed",token); } } else if ( strcmp(token,"0") == 0 ) { emmax_error("0 0 is expected but %s 0 is observed",token); } else if ( strcmp(token,"1") == 0 ) { //values[(j-nheadercols)/2] += 0; } else if ( strcmp(token,"2") == 0 ) { values[(j-nheadercols)/2] += 1; } } } else { values[j-nheadercols] = strtod(token, &next); if ( token == next ) { if ( ( strcmp(token,"NA") == 0 ) || ( strcmp(token,"N") == 0 ) || ( strcmp(token,"?") == 0 ) ) { values[j-nheadercols] = DBL_MISSING; ++nmiss; } else { emmax_error("Numeric value is expected at line %d and column %d, but observed %s",fhp->nrows,j,token); } } } token = strtok(NULL, delims); } //fprintf(stderr,"tokenize-line ended %d %d\n",j,nheadercols); *p_nvalues = (zero_miss_flag == 1 ) ? (j-nheadercols)/2 : (j-nheadercols); *p_nmiss = nmiss; ++(fhp->nrows); if ( j < nheadercols ) { emmax_error("Number of header columns are %d, but only %d columns were observed\n", nheadercols, j); } return values; } void ensure_symmetry_and_relax_diag( double* mat, int n, double tol, double eps ) { int i,j; /* fprintf(stderr,"%d\n",n); abort(); for(i=0; i < n; ++i) { for(j=0; j < n; ++j) { fprintf(stderr," %lf",mat[i*n+j]); } fprintf(stderr,"\n"); } */ for(i=0; i < n; ++i) { for(j=0; j < i; ++j) { if ( fabs(mat[i*n+j]-mat[j*n+i]) > tol ) { fprintf(stderr,"FATAL ERROR : Kinship matrix (%d,%d) and (%d,%d) must be the same, but actually different as %lf and %lf\n",i,j,j,i,mat[i*n+j],mat[j*n+i]); abort(); } else { mat[i*n+j] = (mat[j*n+i] = (mat[i*n+j]+mat[j*n+i])/2.); } } mat[i*n+i] += eps; } } double betacf(double a, double b, double x) { int m,m2; double aa,c,d,del,h,qab,qam,qap; qab=a+b; qap=a+1.0; qam=a-1.0; c=1.0; d=1.0-qab*x/qap; if (fabs(d) < FPMIN) d=FPMIN; d=1.0/d; h=d; for (m=1;m<=MAXIT;m++) { m2=2*m; aa=m*(b-m)*x/((qam+m2)*(a+m2)); d=1.0+aa*d; if (fabs(d) < FPMIN) d=FPMIN; c=1.0+aa/c; if (fabs(c) < FPMIN) c=FPMIN; d=1.0/d; h *= d*c; aa = -(a+m)*(qab+m)*x/((a+m2)*(qap+m2)); d=1.0+aa*d; if (fabs(d) < FPMIN) d=FPMIN; c=1.0+aa/c; if (fabs(c) < FPMIN) c=FPMIN; d=1.0/d; del=d*c; h *= del; if (fabs(del-1.0) < EPS) break; } if (m > MAXIT) { fprintf(stderr,"a or b too big, or MAXIT too small in betacf %lf %lf %lf",a,b,x); abort(); } return h; } double gammln(double xx) { double x,y,tmp,ser; static double cof[6]={76.18009172947146,-86.50532032941677,24.01409824083091,-1.231739572450155,0.1208650973866179e-2,-0.5395239384953e-5}; int j; y=x=xx; tmp=x+5.5; tmp -= (x+0.5)*log(tmp); ser=1.000000000190015; for (j=0;j<=5;j++) ser += cof[j]/++y; return -tmp+log(2.5066282746310005*ser/x); } double betai(double a, double b, double x) { double gammln(double xx); void nrerror(char error_text[]); double bt; if (x < 0.0 || x > 1.0) { fprintf(stderr,"Bad x in routine betai"); abort(); } if (x == 0.0 || x == 1.0) bt=0.0; else bt=exp((gammln(a+b)-gammln(a)-gammln(b))+(a*log(x))+(b*log(1.0-x))); if (x < (a+1.0)/(a+b+2.0)) return bt*betacf(a,b,x)/a; else return 1.0-bt*betacf(b,a,1.0-x)/b; } double tcdf(double t, double nu) { if ( isnan(t) ) return 1.; else return betai(nu/2.,0.5,nu/(nu+t*t)); } void emmax_error( const char* format, ... ) { va_list args; fprintf(g_logh.fp, "ERROR: "); va_start (args, format); vfprintf(g_logh.fp, format, args); va_end (args); fprintf(g_logh.fp,"\n"); fprintf(stderr, "ERROR: "); va_start (args, format); vfprintf(stderr, format, args); va_end (args); fprintf(stderr,"\n"); exit(-1); } void emmax_log( const char* format, ... ) { va_list args; va_start (args, format); vfprintf(g_logh.fp, format, args); va_end (args); fprintf(g_logh.fp,"\n"); if ( g_verbose ) { va_start (args, format); vfprintf(stderr, format, args); va_end (args); fprintf(stderr,"\n"); } } // for matrix S = I-11'/n, and K // compute centered trace tr(SKS) // this is equivalent to sum(diag(K))-sum(K)/nrow(K) double centered_trace(double* kin, int n) { int i,j; double dsum,asum; dsum = asum = 0; for(i=0; i < n; ++i) { for(j=0; j < n; ++j) { asum += kin[i+n*j]; if ( i == j ) { dsum += kin[i+n*j]; } } } return (dsum - asum/(double)n); } void print_help(void) { fprintf(stderr,"Usage: epi-emmax [options]\n"); fprintf(stderr,"Required parameters\n"); fprintf(stderr,"\t-t [tpedf_prefix] : prefix for tped/tfam files\n"); fprintf(stderr,"\t-o [out_prefix] : output file name prefix\n"); fprintf(stderr,"Likely essential parameters\n"); fprintf(stderr,"\t-p [phenof] : 3-column phenotype file with FAMID, INDID at the first two colmns, in the same order of .tfam file. Not required only with -K option"); fprintf(stderr,"\t-k [kinf] : n * n matrix containing kinship values in the individual order consistent to [tpedf].tfam file. [tpedf].kinf will be used if not specified\n"); fprintf(stderr,"\t-c [covf] : multi-column covariate file with FAMID, INDID at the first two colmns, in the same order of .tfam file"); fprintf(stderr,"Optional parameters\n"); fprintf(stderr,"Optional parameters\n"); fprintf(stderr,"\t-i [in_prefix] : input file name prefix including eigenvectors\n"); fprintf(stderr,"\t-d [# digits] : precision of the output values (default : 5)\n"); fprintf(stderr,"\t-s [start index of SNP] : start index of SNP (default : 0)\n"); fprintf(stderr,"\t-e [end index of SNP] : end index of SNP (default : #snps)\n"); fprintf(stderr,"\t-w : flag for writing eigenvalues/eigenvector files\n"); fprintf(stderr,"\t-D [delimiters] : delimter string in quotation marks\n"); fprintf(stderr,"\t-P [# heaer cols in tped] : # of column headers in tped file\n"); fprintf(stderr,"\t-F [# heaer cols in tfam] : # of column headers in tfam file\n"); exit(-1); } void vector_copy(int n, double* X, double* Y) { /* Copies a vector X of lenght n to vector Y */ int i; for (i=0; i<n; i++) Y[i]=X[i]; } int check_input(double* x, double*y, char* c) { int out=0; if (x==y) { printf("Error in %s: input equals output \n", c); out=1; } return out; } // Wrapper for Lapack machine precision function //static double dlamch (char CMACH) //{ // extern double dlamch_ (char *CMACHp); // return dlamch_ (&CMACH); //} // Wrapper for Lapack eigenvalue function /* int dsyevd (char JOBZ, char UPLO, int N, double *A, int LDA, double *W, double *WORK, int LWORK, int *IWORK, int LIWORK) { extern void dsyevd_ (char *JOBZp, char *UPLOp, int *Np, double *A, int *LDAp, double *W, double *WORK, int *LWORKp, int *IWORK, int *LIWORKp, int *INFOp); int INFO; dsyevd_ (&JOBZ, &UPLO, &N, A, &LDA, W, WORK, &LWORK, IWORK, &LIWORK, &INFO); return INFO; }*/ int eigen_decomposition(int n, double* X, double *eigvec, double *eigval) { /* This function calculates the eigenvalues and eigenvectors of the n*n symmetric matrix X. The matrices have to be in Fortran vector format. The eigenvectors will be put columnwise in the n*n matrix eigvec, where the corresponding eigenvalues will be put in the vector eigval (length n of course). Only the lower triangle of the matrix X is used. The content of X is not changed. This function first queries the Lapack routines for optimal workspace sizes. These memoryblocks are then allocated and the decomposition is calculated using the Lapack function "dsyevr". The allocated memory is then freed. */ double *work; int *iwork; int info, lwork, liwork; if (check_input(X, eigvec, "eigen_decomposition")) return 1; /* Use a copy of X so we don't need to change its value or use its memoryblock */ //Xc=malloc(n*n*sizeof(double)); /* The support of the eigenvectors. We will not use this but the routine needs it */ /* Allocate temporarily minimally allowed size for workspace arrays */ lwork = 2*n*n+6*n+1; liwork = 3+5*n; iwork = (int*)malloc(sizeof(int)*liwork); work = (double*)malloc(sizeof(double)*lwork); /* Check for NULL-pointers. */ if ((work==NULL)||(iwork==NULL)) { printf("malloc failed in eigen_decomposition\n"); return 2; } vector_copy(n*n, X, eigvec); #ifdef INTEL_COMPILER dsyevd(&cv,&cl, &n, eigvec, &n, eigval, work, &lwork, iwork, &liwork, &info); #else dsyevd_(&cv,&cl, &n, eigvec, &n, eigval, work, &lwork, iwork, &liwork, &info); #endif //sizeWORK = (int)WORK[0]; //sizeIWORK = IWORK[0]; /* Free previous allocation and reallocate preferable workspaces, Check result */ //free(WORK);free(IWORK); //WORK = malloc (sizeWORK*sizeof(double)); //IWORK = malloc (sizeIWORK*sizeof(int)); //if ((WORK==NULL)||(IWORK==NULL)) { // printf("malloc failed in eigen_decomposition\n"); // return 2; //} /* Now calculate the eigenvalues and vectors using optimal workspaces */ //info = dsyevd('V','L', n, eigvec, n, eigval, WORK, sizeWORK, IWORK, sizeIWORK); //eigvec = Xc; //info=dsyevr ('V', 'A', 'L', n, Xc, n, 0, 0, 0, 0, dlamch('S'), &numeig, eigval, eigvec, n, ISUPPZ, WORK, sizeWORK, IWORK, sizeIWORK); /* Cleanup and exit */ //free(WORK); free(IWORK); //free(ISUPPZ); //free(Xc); free(work); free(iwork); return info; } int matrix_invert(int n, double *X, double *Y) { /* Calculates the inverse of the n*n matrix X: Y = X^-1 Does not change the value of X, unless Y=X */ int info=0; /* When X!=Y we want to keep X unchanged. Copy to Y and use this as working variable */ if (X!=Y) vector_copy(n*n, X, Y); /* We need to store the pivot matrix obtained by the LU factorisation */ //int *ipiv; int ipiv[n]; // ipiv=malloc(n*sizeof(int)); if (ipiv==NULL) { printf("malloc failed in matrix_invert\n"); return 2; } /* Turn Y into its LU form, store pivot matrix */ //info = clapack_dgetrf (CblasColMajor, n, n, Y, n, ipiv); #ifdef INTEL_COMPILER dgetrf(&n,&n,Y,&n,ipiv,&info); #else dgetrf_(&n,&n,Y,&n,ipiv,&info); #endif /* Don't bother continuing when illegal argument (info<0) or singularity (info>0) occurs */ if (info!=0) return info; int lwork = n*16; double work[lwork]; // double* work = malloc(sizeof(double)*lwork); /* Feed this to the lapack inversion routine. */ //info = clapack_dgetri (CblasColMajor, n, Y, n, ipiv); #ifdef INTEL_COMPILER dgetri(&n,Y,&n,ipiv,work,&lwork,&info); #else dgetri_(&n,Y,&n,ipiv,work,&lwork,&info); #endif /* Cleanup and exit */ // free(ipiv); // free(work); return info; } // genotype values are encoded from 0 to 2 additively double update_kinship_IBS_mean( double* kins, double* snps, int n ) { int i,j,nv; double sum = 0; for(i=0, nv=0; i < n; ++i) { if ( snps[i] != DBL_MISSING ) { sum += snps[i]; ++nv; } } for(i=0; i < n; ++i) { if ( snps[i] == DBL_MISSING ) { snps[i] += sum/(double)nv; } } for(i=0; i < n; ++i) { for(j=0; j < i; ++j) { kins[i+j*n] += (2.-fabs(snps[i]-snps[j])); } } return 2.; } double update_kinship_IBS_rand( double* kins, double* snps, int n ) { emmax_error("Not implemented yet"); return 0; } double update_kinship_Balding_Nichols( double* kins, double* snps, int n ) { emmax_error("Not implemented yet"); return 0; } void symmetrize_and_normalize_kinship( double* kins, double sum, int n ) { int i,j; for(i=0; i < n; ++i) { for(j=0; j < i; ++j) { kins[i+j*n] /= sum; kins[j+i*n] = kins[i+j*n]; } kins[i+i*n] = 1.; } }
{ "alphanum_fraction": 0.6017150203, "avg_line_length": 31.1652209831, "ext": "c", "hexsha": "24f0ea5e354f476ca930c466965b0980c871e55d", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-06-26T15:01:39.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-26T15:01:39.000Z", "max_forks_repo_head_hexsha": "b214b602a8f7f90e13ab4b9ddeba811b67c03a19", "max_forks_repo_licenses": [ "Intel" ], "max_forks_repo_name": "slowkoni/EPI-EMMAX", "max_forks_repo_path": "epi-emmax.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "b214b602a8f7f90e13ab4b9ddeba811b67c03a19", "max_issues_repo_issues_event_max_datetime": "2021-06-23T09:15:17.000Z", "max_issues_repo_issues_event_min_datetime": "2021-06-23T09:15:17.000Z", "max_issues_repo_licenses": [ "Intel" ], "max_issues_repo_name": "slowkoni/EPI-EMMAX", "max_issues_repo_path": "epi-emmax.c", "max_line_length": 210, "max_stars_count": null, "max_stars_repo_head_hexsha": "b214b602a8f7f90e13ab4b9ddeba811b67c03a19", "max_stars_repo_licenses": [ "Intel" ], "max_stars_repo_name": "slowkoni/EPI-EMMAX", "max_stars_repo_path": "epi-emmax.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 26418, "size": 75451 }
#ifndef ALLVARSGRID_H #define ALLVARSGRID_H #include <stdio.h> #include <gsl/gsl_rng.h> #include <stdint.h> #define ABORT(sigterm) \ do { \ printf("Error in file: %s\tfunc: %s\tline: %i\n", __FILE__, __FUNCTION__, __LINE__); \ myexit(sigterm); \ } while(0) #define STEPS 10 // Number of integration intervals between two snapshots #define MAXGRIDOUT 30 #define MAXGALFAC 1 #define ALLOCPARAMETER 10.0 #define MAX_NODE_NAME_LEN 50 #define ABSOLUTEMAXSNAPS 1000 #define GRAVITY 6.672e-8 #define SOLAR_MASS 1.989e33 #define SOLAR_LUM 3.826e33 #define RAD_CONST 7.565e-15 #define AVOGADRO 6.0222e23 #define BOLTZMANN 1.3806e-16 #define GAS_CONST 8.31425e7 #define C 2.9979e10 #define PLANCK 6.6262e-27 #define CM_PER_MPC 3.085678e24 #define PROTONMASS 1.6726e-24 #define HUBBLE 3.2407789e-18 /* in h/sec */ #define SEC_PER_MEGAYEAR 3.155e13 #define SEC_PER_YEAR 3.155e7 #define CUBE(x) (x*x*x) #define MAXLEN 1024 #ifdef NDEBUG #define XASSERT(EXP, ...) do{} while(0) #else #define XASSERT(EXP, ...) \ do { if (!(EXP)) { \ printf("Error in file: %s\tfunc: %s\tline: %d with expression `"#EXP"'\n", __FILE__, __FUNCTION__, __LINE__); \ printf(__VA_ARGS__); \ fflush(stdout); \ ABORT(EXIT_FAILURE); \ } \ } while (0) #endif #ifdef NDEBUG #define XPRINT(EXP, ...) do{} while(0) #else #define XPRINT(EXP, ...) \ do { if (!(EXP)) { \ printf("Warning in file: %s\tfunc: %s\tline: %d with expression `"#EXP"'\n", __FILE__, __FUNCTION__, __LINE__); \ printf(__VA_ARGS__); \ fflush(stdout); \ } \ } while (0) #endif struct GALAXY_INPUT { int SnapNum; int Type; long long GalaxyIndex; long long CentralGalaxyIndex; int SAGEHaloIndex; int SAGETreeIndex; int SimulationFOFHaloIndex; int mergeType; //0=none; 1=minor merger; 2=major merger; 3=disk instability; 4=disrupt to ICS int mergeIntoID; int mergeIntoSnapNum; float dT; // (sub)halo properties float Pos[3]; float Vel[3]; float Spin[3]; int Len; float Mvir; float CentralMvir; float Rvir; float Vvir; float Vmax; float VelDisp; // baryonic reservoirs float ColdGas; float StellarMass; float BulgeMass; float HotGas; float EjectedMass; float BlackHoleMass; float ICS; // metals float MetalsColdGas; float MetalsStellarMass; float MetalsBulgeMass; float MetalsHotGas; float MetalsEjectedMass; float MetalsICS; // to calculate magnitudes float SfrDisk; float SfrBulge; float SfrDiskZ; float SfrBulgeZ; // misc float DiskScaleRadius; float Cooling; float Heating; float QuasarModeBHaccretionMass; float TimeOfLastMajorMerger; float TimeOfLastMinorMerger; float OutflowRate; // infall properties float infallMvir; float infallVvir; float infallVmax; // NOTE: Because the code has moved to pointers for the galaxy-grid information // They are no longer stored explicitly in the galaxy input struct. }*Gal; struct GALAXY_GRID { int TreeNr; int32_t *Type; int32_t *FoFNr; int32_t *History; // Integers that describe the grid position at every redshift. float *ColdGas; float *HotGas; float *EjectedMass; float *DustColdGas; float *DustHotGas; float *DustEjectedMass; float *BHMass; float *StellarMass; // Units of 1.0e10 Msun/h. float *SFR; // Units of Msun yr^-1 float *Z; // NOT solar metallicity, actual metallicity. float *FoFMass; // Units of 1.0e10 Msun/h. float *EjectedFraction; // Unitless (fraction). int *LenHistory; // Number of particles in FoF Halo. int *QuasarActivity; int *QuasarSubstep; float *DynamicalTime; int *LenMergerGal; float *ReionMod; float *GridNgamma_HI; float *Gridfesc; }*GalGrid; struct GRID_STRUCT { int32_t GridSize; uint64_t NumCellsTotal; int32_t NumGrids; struct GRID_PROPERTIES_STRUCT { float *SFR; float *StellarMass; float *Nion_HI; float *Nion_HeI; float *Nion_HeII; uint64_t *GalCount; // TODO: Move these to their own struct. /* These properties are per galaxy (not per grid cell) but I'm lazy. */ int32_t *SnapshotGalaxy; float *fescGalaxy; float *MvirGalaxy; float *MstarGalaxy; float *NgammaGalaxy; float *NgammafescGalaxy; }*GridProperties; }*Grid; struct halo_data { // merger tree pointers int Descendant; int FirstProgenitor; int NextProgenitor; int FirstHaloInFOFgroup; int NextHaloInFOFgroup; // properties of halo int Len; float M_Mean200, Mvir, M_TopHat; // for Millennium, Mvir=M_Crit200 float Pos[3]; float Vel[3]; float VelDisp; float Vmax; float Spin[3]; long long MostBoundID; // original position in simulation tree files int SnapNum; int FileNr; int SubhaloIndex; float SubHalfMass; } *Halo; struct meraxes_halo_data { double SFR; double StellarMass; double Mvir; double ColdGas; double HotGas; double EjectedGas; double MetalsColdGas; double Pos[3]; } *meraxes_Halo; extern double UnitLength_in_cm, UnitTime_in_s, UnitVelocity_in_cm_per_s, UnitMass_in_g, RhoCrit, UnitPressure_in_cgs, UnitDensity_in_cgs, UnitCoolingRate_in_cgs, UnitEnergy_in_cgs, UnitTime_in_Megayears, G, Hubble, a0, ar; extern int Ntrees; // Number of trees per file. extern int64_t NtotGals; // Number of galaxies per file. extern int *GalsForTree; extern int Snaplistlen; extern double ZZ[ABSOLUTEMAXSNAPS]; extern double AA[ABSOLUTEMAXSNAPS]; extern double Age[ABSOLUTEMAXSNAPS]; extern gsl_rng *random_generator; extern int MAXSNAPS; // Parameter File Variables // extern int FirstFile; // first and last file for processing extern int LastFile; extern int NumGals; // Total number of galaxies stored for current tree extern int MaxGals; // Maximum number of galaxies allowed for current tree extern int LastSnapShotNr; extern char GalaxiesInputDir[MAXLEN]; extern char GridOutputDir[512]; extern char FileNameGalaxies[512]; extern char SimulationDir[512]; extern char TreeName[512]; extern char FileWithSnapList[512]; extern int TotHalos; extern int totNHalos; // Total number of halos in a file. extern int TotGalaxies[ABSOLUTEMAXSNAPS]; extern int *TreeNgals[ABSOLUTEMAXSNAPS]; extern int *FirstHaloInSnap; extern int *TreeNHalos; extern int *TreeFirstHalo; #ifdef MPI int ThisTask, NTask, nodeNameLen; char *ThisNode; #endif extern double Omega; extern double OmegaLambda; extern double PartMass; extern double BoxSize; extern int GridSize; extern int self_consistent; extern int GridSnap; extern int NGrid; extern double Hubble_h; extern double EnergySNcode, EnergySN; extern double EtaSNcode, EtaSN; // recipe flags extern int ReionizationOn; extern int SupernovaRecipeOn; extern int DiskInstabilityOn; extern int AGNrecipeOn; extern int SFprescription; // recipe parameters extern double RecycleFraction; extern double Yield; extern double FracZleaveDisk; extern double ReIncorporationFactor; extern double ThreshMajorMerger; extern double BaryonFrac; extern double SfrEfficiency; extern double FeedbackReheatingEpsilon; extern double FeedbackEjectionEfficiency; extern double RadioModeEfficiency; extern double QuasarModeEfficiency; extern double BlackHoleGrowthRate; extern double Reionization_z0; extern double Reionization_zr; extern double ThresholdSatDisruption; extern int LowSnap; extern int HighSnap; extern int ListOutputSnaps[ABSOLUTEMAXSNAPS]; extern int ListOutputGrid[ABSOLUTEMAXSNAPS]; extern int Verbose; // Input parameters for the photon prescription // extern int PhotonPrescription; extern int fescPrescription; extern double fesc; extern double MH_low; extern double fesc_low; extern double MH_high; extern double fesc_high; extern double alpha; extern double beta; extern double quasar_baseline; extern double quasar_boosted; extern double N_dyntime; extern int HaloPartCut; extern int32_t *QuasarActivityToggle; extern int32_t *QuasarActivitySubstep; extern int32_t *QuasarSnapshot; extern float *TargetQuasarTime; extern float *QuasarBoostActiveTime; extern float *QuasarFractionalPhoton; extern int QuasarEventsAbovePartCut; extern int QuasarEventsBelowPartCut; extern float sum_photons; #endif
{ "alphanum_fraction": 0.6794685721, "avg_line_length": 23.6332453826, "ext": "h", "hexsha": "e6db968e8f8f0251af67f6ca9cb40e68c3d396b7", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jacobseiler/rsage", "max_forks_repo_path": "gridding/core_allvars_grid.h", "max_issues_count": 7, "max_issues_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_issues_repo_issues_event_max_datetime": "2019-01-16T05:40:16.000Z", "max_issues_repo_issues_event_min_datetime": "2018-08-17T05:04:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jacobseiler/rsage", "max_issues_repo_path": "gridding/core_allvars_grid.h", "max_line_length": 125, "max_stars_count": 1, "max_stars_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jacobseiler/rsage", "max_stars_repo_path": "gridding/core_allvars_grid.h", "max_stars_repo_stars_event_max_datetime": "2019-05-23T04:11:32.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-23T04:11:32.000Z", "num_tokens": 2484, "size": 8957 }
/* * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer * * Yan-Rong Li, liyanrong@mail.ihep.ac.cn * Jun 30, 2016 * */ #ifndef _MODEL3_H #define _MODEL3_H #include <stdbool.h> #include <gsl/gsl_rng.h> /* number of model parameters */ extern int num_params; extern int which_particle_update; // which particule to be updated extern int which_level_update; extern double *limits; extern int thistask, totaltask; extern DNestFptrSet *fptrset_thismodel3; /* functions */ void from_prior_thismodel3(void *model); void print_particle_thismodel3(FILE *fp, const void *model); double log_likelihoods_cal_thismodel3(const void *model); double perturb_thismodel3(void *model); void restart_action_model3(int iflag); #endif
{ "alphanum_fraction": 0.7715053763, "avg_line_length": 22.5454545455, "ext": "h", "hexsha": "67f6a5a09c1d9b9f66fad0270a2f6f288759afec", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LiyrAstroph/DNest_C", "max_forks_repo_path": "src/model3.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_issues_repo_issues_event_max_datetime": "2021-01-06T02:04:19.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-14T10:04:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LiyrAstroph/DNest_C", "max_issues_repo_path": "src/model3.h", "max_line_length": 71, "max_stars_count": 6, "max_stars_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LiyrAstroph/CDNest", "max_stars_repo_path": "src/model3.h", "max_stars_repo_stars_event_max_datetime": "2020-10-16T12:14:05.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-11T03:34:45.000Z", "num_tokens": 196, "size": 744 }
#ifndef gsl_h__ #define gsl_h__ #include <gsl/gsl_linalg.h> namespace gsl { // FIXME clean this up with C++0x rvalues struct vector { gsl_vector *p; gsl_vector_view view; vector(int n=1) { p = gsl_vector_alloc(n); view = gsl_vector_subvector_with_stride(p,0,p->stride,p->size); } ~vector() { gsl_vector_free(p); p = 0; } int length() { return p->size; } int dim(int i) { if(i==0) return p->size; throw "oops"; } void resize(int n) { gsl_vector_free(p); p = gsl_vector_alloc(n); } void operator=(double value) { gsl_vector_set_all(p,value); } double &operator()(int i) { CHECK(unsigned(i)<=unsigned(p->size)); return p->data[i*p->stride]; } operator gsl_vector_view *() { return &view; } operator gsl_vector *() { return p; } template <class T> void get(T &other) { resize(other.dim(0)); for(int i=0;i<other.dim(0);i++) operator()(i) = other(i); } template <class T> void put(T &other) { other.resize(dim(0)); for(int i=0;i<dim(0);i++) other(i) = operator()(i); } }; struct matrix { gsl_matrix *p; gsl_matrix_view view; matrix(int n=1,int m=1) { p = gsl_matrix_alloc(n,m); view = gsl_matrix_view_array_with_tda(p->data,p->size1,p->size2,p->tda); } ~matrix() { gsl_matrix_free(p); p = 0; } int dim(int i) { if(i==0) return p->size1; if(i==1) return p->size2; throw "oops"; } void resize(int n,int m) { gsl_matrix_free(p); p = gsl_matrix_alloc(n,m); view = gsl_matrix_view_array_with_tda(p->data,p->size1,p->size2,p->tda); } void operator=(double value) { gsl_matrix_set_all(p,value); } double &operator()(int i,int j) { CHECK(unsigned(i)<=unsigned(p->size1)); CHECK(unsigned(j)<=unsigned(p->size2)); return p->data[i*p->tda+j]; } operator gsl_matrix_view *() { return &view; } operator gsl_matrix *() { return p; } template <class T> void get(T &other) { resize(other.dim(0),other.dim(1)); for(int i=0;i<other.dim(0);i++) for(int j=0;j<other.dim(1);j++) operator()(i,j) = other(i,j); } template <class T> void put(T &other) { other.resize(dim(0),dim(1)); for(int i=0;i<dim(0);i++) for(int j=0;j<dim(1);j++) other(i,j) = operator()(i,j); } }; }; #endif
{ "alphanum_fraction": 0.4512195122, "avg_line_length": 27.5818181818, "ext": "h", "hexsha": "c3b6384e7e2216e4acc4f09badd8ed9d283b017c", "lang": "C", "max_forks_count": 11, "max_forks_repo_forks_event_max_datetime": "2020-12-01T21:26:43.000Z", "max_forks_repo_forks_event_min_datetime": "2016-06-24T09:35:57.000Z", "max_forks_repo_head_hexsha": "b2673354bbcfba38f7a807708f64cd33aaeb0f6d", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "michaelyin/ocropus-git", "max_forks_repo_path": "ocr-line/gsl.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b2673354bbcfba38f7a807708f64cd33aaeb0f6d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "michaelyin/ocropus-git", "max_issues_repo_path": "ocr-line/gsl.h", "max_line_length": 84, "max_stars_count": 3, "max_stars_repo_head_hexsha": "b2673354bbcfba38f7a807708f64cd33aaeb0f6d", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "michaelyin/ocropus-git", "max_stars_repo_path": "ocr-line/gsl.h", "max_stars_repo_stars_event_max_datetime": "2020-07-04T16:00:41.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-24T10:48:36.000Z", "num_tokens": 744, "size": 3034 }
/** * @file libhades.c * @author Michael Hartmann <michael.hartmann@physik.uni-augsburg.de> * @date February, 2016 * @brief library to access low-level LAPACK functions */ #include <cblas.h> #include <errno.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <strings.h> #include <libhades.h> #include <libhades/parse_npy_dict.h> /** \defgroup misc miscellaneous functions * @{ */ /** @brief malloc wrapper * * This function uses malloc to allocate size bytes of memory and returns a * pointer to the memory. If an error occures, an error message is printed to * stderr and the program is aborted. * * @param [in] size amount of memory to allocate * @retval ptr pointer to the allocated memory */ void *libhades_malloc(size_t size) { void *ptr = malloc(size); if(ptr == NULL) { const int err = errno; fprintf(stderr, "malloc can't allocate %zu bytes of memory: %s (%d)\n", size, strerror(err), err); abort(); } return ptr; } /** @brief free wrapper * * This function frees the memory allocated by \ref libhades_malloc or \ref * libhades_realloc (or malloc and realloc). If the pointer given is NULL, an error is * printed to stderr and the program is aborted. * * @param [in] ptr pointer to the memory that should be freed */ void libhades_free(void *ptr) { if(ptr == NULL) { fprintf(stderr, "Trying to free NULL pointer\n"); abort(); } free(ptr); } /** @brief realloc wrapper * * This function changes the size of the memory block pointed to by ptr to size * bytes. If ptr is NULL, this function behaves like \ref libhades_malloc. If * an error occures, an error is printed to stderr and the program is aboprted. * * @param [in] ptr pointer to the memory block * @param [in] size size of the memory block * @retval ptr_new pointer to the new memory block */ void *libhades_realloc(void *ptr, size_t size) { void *ptr_new = realloc(ptr, size); if(ptr_new == NULL) { int err = errno; fprintf(stderr, "realloc can't allocate %zu bytes of memory: %s (%d)\n", size, strerror(err), err); abort(); } return ptr_new; } static void *(*malloc_cb)(size_t) = &libhades_malloc; static void *(*realloc_cb)(void *, size_t) = &libhades_realloc; static void (*free_cb)(void *) = &libhades_free; /** macro to create functions argmin, argmax, argabsmin, argabsmax */ #define ARGXXX(FUNCTION_NAME, FUNCTION, RELATION) \ size_t FUNCTION_NAME(double list[], size_t size) \ { \ size_t index = 0; \ for(size_t i = 0; i < size; i++) \ if(FUNCTION(list[i]) RELATION FUNCTION(list[index])) \ index = i; \ return index; \ } /** @brief Return index of smallest element in list * * @param [in] list * @param [in] size elements in list * * @retval index */ ARGXXX(argmin, +, <) /** @brief Return index of largest element in list * * @param [in] list * @param [in] size elements in list * * @retval index */ ARGXXX(argmax, +, >) /** @brief Return index of element with smallest absolute value in list * * @param [in] list * @param [in] size elements in list * * @retval index */ ARGXXX(argabsmin, fabs, <) /** @brief Return index of element with largest absolute value in list * * @param [in] list * @param [in] size elements in list * * @retval index */ ARGXXX(argabsmax, fabs, >) /** @}*/ /** \defgroup create Creating, printing and freeing matrices * @{ */ static inline void _swap_int(int *a, int *b); static inline void _swap_size_t(size_t *a, size_t *b); static inline void _swap_int(int *a, int *b) { int c = *a; *a = *b; *b = c; } static inline void _swap_size_t(size_t *a, size_t *b) { size_t c = *a; *a = *b; *b = c; } #define MATRIX_SWAP(FUNCTION_NAME, MATRIX_TYPE, TYPE) \ void FUNCTION_NAME(MATRIX_TYPE *A, MATRIX_TYPE *B) \ { \ /* swap pointers */ \ TYPE *ptr = A->M; \ A->M = B->M; \ B->M = ptr; \ \ /* swap rows */ \ _swap_int(&A->rows, &B->rows); \ \ /* swap columns */ \ _swap_int(&A->columns, &B->columns); \ \ /* swap min */ \ _swap_int(&A->min, &B->min); \ \ /* swap size */ \ _swap_size_t(&A->size, &B->size); \ \ /* swap type */ \ _swap_int(&A->type, &B->type); \ \ /* swap min */ \ _swap_int(&A->min, &B->min); \ } /** @brief Swap matrices A and B * * This function swaps the matrices A and B. The former content of A will be * the content of B and vice versa. No data is copied or moved, but the * pointers are swapped. * * @param [in,out] A matrix A * @param [in,out] B matrix B */ MATRIX_SWAP(matrix_swap, matrix_t, double); /** @brief Swap matrices A and B * * See \ref matrix_swap. * * @param [in,out] A matrix A * @param [in,out] B matrix B */ MATRIX_SWAP(matrix_complex_swap, matrix_complex_t, complex_t); /** macro to create a diagnal matrix out of a vector */ #define MATRIX_DIAG(FUNCTION_NAME, MATRIX_TYPE, ZEROS) \ MATRIX_TYPE *FUNCTION_NAME(MATRIX_TYPE *v) \ { \ int dim = v->size; \ MATRIX_TYPE *A = ZEROS(dim, dim, NULL); \ if(A == NULL) \ return NULL; \ \ for(int i = 0; i < dim; i++) \ matrix_set(A, i,i, v->M[i]); \ \ return A; \ } /** @brief Construct a real diagonal matrix from a row or columns vector * * @param [in] v row or column vector * * @retval A A = diag(v) if successfull, NULL otherwise */ MATRIX_DIAG(matrix_diag, matrix_t, matrix_zeros) /** @brief Construct a complex diagonal matrix from a row or columns vector * * @param [in] v row or column vector * * @retval A A = diag(v) if successfull, NULL otherwise */ MATRIX_DIAG(matrix_complex_diag, matrix_complex_t, matrix_complex_zeros) /** @brief Set functions to allocate and free memory * * By default wrappers to malloc and free from <stdlib.h> are used to allocate * and free memory. If allocation of memory fails or a NULL pointer is freed, * the program will terminate. * * @param [in] _malloc_cb callback to a malloc-alike function * @param [in] _free_cb callback to a free-alike function */ void matrix_set_alloc(void *(*_malloc_cb)(size_t), void (*_free_cb)(void *)) { malloc_cb = _malloc_cb; free_cb = _free_cb; } /** macro for copying matrices. */ #define MATRIX_COPY(FUNCTION_NAME, MTYPE, TYPE, ALLOC) \ MTYPE *FUNCTION_NAME(MTYPE *A, MTYPE *C) \ { \ if(C == NULL) { \ C = ALLOC(A->rows, A->columns); \ if(C == NULL) \ return NULL; \ } \ \ C->rows = A->rows; \ C->columns = A->columns; \ C->min = A->min; \ C->size = A->size; \ C->type = A->type; \ C->view = 0; \ memcpy(C->M, A->M, C->size*sizeof(TYPE)); \ return C; \ } /** @brief Copy real matrix A * * Copy matrix A into C. If C is NULL, space for the matrix C will be * allocated. * * @param [in] A real matrix * @param [in,out] C real matrix * * @retval C copy of A */ MATRIX_COPY(matrix_copy, matrix_t, double, matrix_alloc) /** @brief Copy complex matrix A * * Copy matrix A into C. If C is NULL, space for the matrix C will be * allocated. * * @param [in] A complex matrix * @param [in,out] C complex matrix * * @retval C copy of A */ MATRIX_COPY(matrix_complex_copy, matrix_complex_t, complex_t, matrix_complex_alloc) /** @brief Copy a real matrix A to a complex matrix C * * Copy the matrix A to a complex matrix C. The matrix elements of A and C will * be identical. If C is NULL, memory for the matrix will be allocated. * * @param [in] A real matrix * * @retval C copy of A if successfull, NULL otherwise */ matrix_complex_t *matrix_tocomplex(matrix_t *A, matrix_complex_t *C) { if(C == NULL) { C = matrix_complex_alloc(A->rows, A->columns); if(C == NULL) return NULL; } for(size_t i = 0; i < C->size; i++) C->M[i] = A->M[i]; return C; } /** @brief Print real matrix M to stream * * Print the matrix A to the stream given by stream, e.g. stdout or stderr. * The format is given by the format string format, the separator of two * columns is sep, the separator between lines is given by sep_line. Both sep * and sep_line may be NULL. * * @param [in] stream output stream * @param [in] A real matrix * @param [in] format output format, e.g. "%lf" or "%g" * @param [in] sep separator between columns, e.g. "\t" * @param [in] sep_line separator between lines, e.g. "\n" */ void matrix_fprintf(FILE *stream, matrix_t *A, const char *format, const char *sep, const char *sep_line) { const int rows = A->rows, columns = A->columns; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { fprintf(stream, format, matrix_get(A, i,j)); if(sep != NULL) fputs(sep, stream); } if(sep_line != NULL) fputs(sep_line, stream); } } /** @brief Print complex matrix A to stream * * See matrix_fprintf. * * @param [in] stream output stream * @param [in] A complex matrix * @param [in] format output format, e.g. "%+lf%+lfi" * @param [in] sep separator between columns, e.g. "\t" * @param [in] sep_line separator between lines, e.g. "\n" */ void matrix_complex_fprintf(FILE *stream, matrix_complex_t *A, const char *format, const char *sep, const char *sep_line) { const int rows = A->rows, columns = A->columns; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { const complex_t c = matrix_get(A, i,j); fprintf(stream, format, CREAL(c), CIMAG(c)); if(sep != NULL) fputs(sep, stream); } if(sep_line != NULL) fputs(sep_line, stream); } } /** macro for matrix allocations. */ #define MATRIX_ALLOC(FUNCTION_NAME, MTYPE, TYPE) \ MTYPE *FUNCTION_NAME(int rows, int columns) \ { \ if(rows <= 0 || columns <= 0) \ return NULL; \ \ MTYPE *A = malloc_cb(sizeof(MTYPE)); \ if(A == NULL) \ return NULL; \ \ const size_t size = (size_t)rows*(size_t)columns; \ \ A->rows = rows; \ A->columns = columns; \ A->min = MIN(rows, columns); \ A->size = size; \ A->type = 0; \ A->view = 0; \ A->M = malloc_cb(size*sizeof(TYPE)); \ if(A->M == NULL) \ { \ free_cb(A); \ return NULL; \ } \ \ return A; \ } /** @brief Allocate memory for real matrix of m rows and n columns * * This function will allocate and return a matrix of m lines and n columns. * The function given by matrix_set_alloc will be used to allocate memory; by * default this is malloc from <stdlib.h>. * * The matrix elements will be undefined. To allocate a matrix initialized with * zeros, see matrix_zeros. To create a unity matrix, see matrix_eye. * * @param [in] rows rows of matrix M (rows > 0) * @param [in] columns columns of matrix M (columns > 0) * * @retval A real matrix if successful, NULL otherwise */ MATRIX_ALLOC(matrix_alloc, matrix_t, double) /** @brief Allocate memory for complex matrix of m rows and n columns * * See matrix_alloc. * * @param [in] rows rows of matrix M (rows > 0) * @param [in] columns columns of matrix M (columns > 0) * * @retval A complex matrix if successful, otherwise NULL */ MATRIX_ALLOC(matrix_complex_alloc, matrix_complex_t, complex_t) /** macro to create zero matrix */ #define MATRIX_ZEROS(FUNCTION_NAME, MTYPE, TYPE, ALLOC, SETALL) \ MTYPE *FUNCTION_NAME(int rows, int columns, MTYPE *A) \ { \ if(A == NULL) \ { \ A = ALLOC(rows,columns); \ if(A == NULL) \ return NULL; \ } \ \ SETALL(A, 0); \ \ return A; \ } /** @brief Generate a real zero matrix of m lines and n columns * * Set every element of matrix A to 0. If A is NULL, the matrix will be * created. In this case, you have to free the matrix yourself. * * @param [in] rows rows of matrix M * @param [in] columns columns of matrix M * @param [in,out] A: matrix * * @retval A real matrix 0 if successful, otherwise NULL */ MATRIX_ZEROS(matrix_zeros, matrix_t, double, matrix_alloc, matrix_setall) /** @brief Generate a complex zero matrix of m lines and n columns * * See matrix_zeros. * * @param [in] rows rows of matrix M * @param [in] columns columns of matrix M * @param [in,out] A: matrix * * @retval A complex matrix 0 if successful, otherwise NULL */ MATRIX_ZEROS(matrix_complex_zeros, matrix_complex_t, complex_t, matrix_complex_alloc, matrix_complex_setall) /** macro to create matrix x*Id */ #define MATRIX_SETALL(FUNCTION_NAME, MATRIX_TYPE, TYPE) \ void FUNCTION_NAME(MATRIX_TYPE *A, TYPE x) \ { \ const size_t size = A->size; \ TYPE *M = A->M; \ for(size_t i = 0; i < size; i++) \ *M++ = x; \ } /** @brief Set matrix elements of A to x * * @param [in,out] A real matrix * @param [in] x real number */ MATRIX_SETALL(matrix_setall, matrix_t, double) /** @brief Set matrix elements of A to x * * @param [in,out] A complex matrix * @param [in] x complex number */ MATRIX_SETALL(matrix_complex_setall, matrix_complex_t, complex_t) /** macro to create unity matrix */ #define MATRIX_EYE(FUNCTION_NAME, MTYPE, TYPE, ALLOC, SETALL) \ MTYPE *FUNCTION_NAME(int dim, MTYPE *A) \ { \ if(A == NULL) \ { \ A = ALLOC(dim,dim); \ if(A == NULL) \ return NULL; \ } \ \ const int min = A->min; \ TYPE *M = A->M; \ SETALL(A,0); \ for(int i = 0; i < min; i++) \ *(M+i*(min+1)) = 1; \ \ return A; \ } /** @brief Create real identity matrix * * If A == NULL, a identity matrix of dimension dim times dim is created and * returned. * If A != NULL, the matrix A is set to the identity matrix and the parameter * dim is ignored. More specific, for a general (e.g. not square) matrix A, the * matrix elements are set to A_ij = Delta_ij. * * @param [in] dim dimension of identity matrix (ignored for A == NULL) * @param [in,out] A real matrix * * @retval A identity matrix if successful, NULL otherwise */ MATRIX_EYE(matrix_eye, matrix_t, double, matrix_alloc, matrix_setall) /** @brief Create complex identity matrix * * See matrix_eye. * * @param [in] dim dimension of identity matrix (ignored for A == NULL) * @param [in,out] A complex matrix * * @retval A identity matrix if successful, NULL otherwise */ MATRIX_EYE(matrix_complex_eye, matrix_complex_t, complex_t, matrix_complex_alloc, matrix_complex_setall) /** macro to free matrices */ #define MATRIX_FREE(FUNCTION_NAME, MTYPE) \ void FUNCTION_NAME(MTYPE *A) \ { \ if(A != NULL) \ { \ if(!A->view && A->M != NULL) \ { \ free_cb(A->M); \ A->M = NULL; \ } \ free_cb(A); \ } \ } /** @brief Free real matrix * * This function will free the memory allocated for matrix M. If M is NULL this * function will do nothing. * * @param [in,out] A matrix to free */ MATRIX_FREE(matrix_free, matrix_t) /** @brief Free complex matrix * * See matrix_free. * * @param [in,out] A matrix to free */ MATRIX_FREE(matrix_complex_free, matrix_complex_t) /** @}*/ /** \defgroup trdet trace and determinant * @{ */ /** macro to calculate trace of matrix */ #define MATRIX_TRACE(FUNCTION_NAME, MATRIX_TYPE, TYPE) \ TYPE FUNCTION_NAME(MATRIX_TYPE *A) \ { \ const int min = A->min; \ const TYPE *M = A->M; \ TYPE trace = 0; \ for(int i = 0; i < min; i++) \ trace += *(M+i*(1+min)); \ \ return trace; \ } /** @brief Calculate Tr(A) of real matrix A * * @param [in] A complex matrix * * @retval x with x=Tr(A) */ MATRIX_TRACE(matrix_trace, matrix_t, double) /** @brief Calculate Tr(A) of complex matrix A * * @param [in] A complex matrix * * @retval z with z=Tr(A) */ MATRIX_TRACE(matrix_complex_trace, matrix_complex_t, complex_t) /** @brief Calculate Tr(A*B) * * This will calculate the trace of A*B: Tr(A*B). Matrix A and B must be square * matrices of dimension dim, dim. * * A and B must not point to the same matrix or the behaviour will be * undefined! * * @param [in] A real matrix * @param [in] B real matrix * * @retval x with x=Tr(A*B) */ double matrix_trace_AB(matrix_t *A, matrix_t *B) { const int dim = A->min; double sum = 0; double *M1 = A->M; double *M2 = B->M; for(int i = 0; i < dim; i++) sum += cblas_ddot(dim, M1+i, dim, M2+i*dim, 1); return sum; } /** @brief Calculate Tr(A*B) for A,B complex * * See matrix_trace_AB. * * @param [in] A complex matrix * @param [in] B complex matrix * * @retval z with z=Tr(A*B) */ complex_t matrix_trace_complex_AB(matrix_complex_t *A, matrix_complex_t *B) { const int dim = A->min; complex_t sum = 0; for(int i = 0; i < dim; i++) for(int k = 0; k < dim; k++) sum += matrix_get(A, i,k)*matrix_get(B, k,i); return sum; } /** @brief Calculate Re(Tr(A*B)) for A,B complex * * See matrix_trace_AB. * * @param [in] A complex matrix * @param [in] B complex matrix * * @retval x with x=Re(Tr(A*B)) */ double matrix_trace_complex_AB_real(matrix_complex_t *A, matrix_complex_t *B) { const int dim = A->rows; double sum = 0; const complex_t *M1 = A->M; const complex_t *M2 = B->M; for(int i = 0; i < dim; i++) for(int k = 0; k < dim; k++) sum += CREAL(M1[i*dim+k]*M2[k*dim+i]); return sum; } /** @}*/ /** \defgroup kron Kronecker product * @{ */ /** macro to create Kronecker product */ #define MATRIX_KRON(FUNCTION_NAME, MTYPE, TYPE, ALLOC, SETALL) \ MTYPE *FUNCTION_NAME(MTYPE *A, MTYPE *B, MTYPE *C) \ { \ const int Am = A->rows, An = A->columns; \ const int Bm = B->rows, Bn = B->columns; \ if(C == NULL) \ { \ C = ALLOC(Am*Bm, An*Bn); \ if(C == NULL) \ return NULL; \ } \ SETALL(C, 0); \ \ for(int m = 0; m < Am; m++) \ for(int n = 0; n < An; n++) \ { \ const TYPE c = matrix_get(A,m,n); \ if(c != 0) \ { \ for(int im = 0; im < Bm; im++) \ for(int in = 0; in < Bn; in++) \ matrix_set(C, m*Bm+im, n*Bn+in, c*matrix_get(B,im,in)); \ } \ } \ \ return C; \ } /** @brief Calculate Kronecker product of real matrices A and B * * Matrix A has dimension Am,An, matrix B has dimension Bm,Bn. * * If C is not NULL, the Kronecker product will be stored in C. C must have * dimension Am+Bm,An+Bn. If C is NULL, memory for the matrix will be allocated * and the matrix will be returned. You have to free the memory for the * returned matrix yourself. * * @param [in] A real matrix * @param [in] B real matrix * @param [in,out] C Kronecker product * * @retval C Kronecker product of A and B, NULL if no memory could be allocated */ MATRIX_KRON(matrix_kron, matrix_t, double, matrix_alloc, matrix_setall) /** @brief Calculate Kronecker product of complex matrices A and B * * See matrix_kron. * * @param [in] A complex matrix * @param [in] B complex matrix * @param [in,out] C Kronecker product * * @retval C Kronecker product of A and B */ MATRIX_KRON(matrix_complex_kron, matrix_complex_t, complex_t, matrix_complex_alloc, matrix_complex_setall) /** @}*/ /** \defgroup addsubmult Add, subtract and multiply matrices * @{ */ /** macro to multiply matrix with scalar factor */ #define MATRIX_MULT_SCALAR(FUNCTION_NAME, MTYPE, TYPE) \ void FUNCTION_NAME(MTYPE *A, TYPE alpha) \ { \ const size_t size = A->size; \ TYPE *M = A->M; \ for(size_t i = 0; i < size; i++) \ M[i] *= alpha; \ } /** @brief Multiply real matrix with a real scalar * * alpha*A -> A * * @param [in,out] A real matrix * @param [in] alpha real scalar * @retval A, A=alpha*A */ MATRIX_MULT_SCALAR(matrix_mult_scalar, matrix_t, double) /** @brief Multiply complex matrix with a complex scalar * * alpha*A -> A * * @param [in,out] A complex matrix * @param [in] alpha complex scalar * @retval A, A=alpha*A */ MATRIX_MULT_SCALAR(matrix_complex_mult_scalar, matrix_complex_t, complex_t) /** @brief Multiply real matrix with a complex scalar * * alpha*A -> C * * If C is NULL, memory for the matrix C will be allocated. If C is not NULL, C * must have the correct dimension. * * @param [in] A real matrix * @param [in] alpha complex scalar * @param [in,out] C complex matrix * * @retval C, C = alpha*A */ matrix_complex_t *matrix_mult_complex_scalar(matrix_t *A, complex_t alpha, matrix_complex_t *C) { const int rows = A->rows; const int columns = A->columns; const double *AM = A->M; complex_t *CM; if(C == NULL) { C = matrix_complex_alloc(rows, columns); if(C == NULL) return NULL; } CM = C->M; for(size_t i = 0; i < C->size; i++) CM[i] = alpha*AM[i]; return C; } /* compute alpha*A*B */ #define MATRIX_MULT(FUNCTION_NAME, MATRIX_TYPE, TYPE, ALLOC, BLAS_xGEMM, PTR) \ MATRIX_TYPE *FUNCTION_NAME(MATRIX_TYPE *A, MATRIX_TYPE *B, TYPE alpha, MATRIX_TYPE *C) \ { \ TYPE beta = 0; \ \ if(A->columns != B->rows) \ return NULL; \ \ if(C == NULL) \ { \ C = ALLOC(A->rows, B->columns); \ if(C == NULL) \ return NULL; \ } \ \ /* xGEMM ( TRANSA, TRANSB, M, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC) */ \ BLAS_xGEMM(CblasColMajor, /* column order */ \ CblasNoTrans, /* don't transpose/conjugate A */ \ CblasNoTrans, /* don't transpose/conjugate B */ \ A->rows, /* M: rows of A and C */ \ B->columns, /* N: columns of B and C */ \ A->columns, /* K: columns of A and rows of B */ \ PTR alpha, /* alpha: scalar */ \ A->M, /* A: matrix A */ \ A->rows, /* LDA: leading dimension of A (columns) */ \ B->M, /* B: matrix B */ \ A->columns, /* LDB: leading dimension of B (columns) */ \ PTR beta, /* beta: scalar */ \ C->M, /* C: matrix C */ \ C->rows /* LDC: leading dimension of C (columns) */ \ ); \ \ return C; \ } /** @brief Multiply real matrices * * alpha*A*B -> C * * If C is NULL, memory for the matrix C will be allocated. * * @param [in] A real matrix * @param [in] B real matrix * @param [in] alpha real scalar * @param [in,out] C real matrix * * @retval C, C = alpha*A*B */ MATRIX_MULT(matrix_mult, matrix_t, double, matrix_alloc, cblas_dgemm, +) /** @brief Multiply complex matrices * * alpha*A*B -> C * * If C is NULL, memory for the matrix C will be allocated. * * @param [in] A complex matrix * @param [in] B complex matrix * @param [in] alpha complex scalar * @param [in,out] C complex matrix * * @retval C, C = alpha*A*B */ MATRIX_MULT(matrix_complex_mult, matrix_complex_t, complex_t, matrix_complex_alloc, cblas_zgemm, &) /** macro to add two matrices */ #define MATRIX_ADD(FUNCTION_NAME, TYPE1, MTYPE1, TYPE2, MTYPE2) \ int FUNCTION_NAME(MTYPE1 *A, MTYPE2 *B, TYPE1 alpha, MTYPE1 *C) \ { \ const size_t size = A->size; \ TYPE1 *M3; \ TYPE1 *M1 = A->M; \ TYPE2 *M2 = B->M; \ \ if(C == NULL) \ M3 = A->M; \ else \ M3 = C->M; \ \ if(A->rows != B->rows || A->columns != B->columns) \ return LIBHADES_ERROR_SHAPE; \ \ for(size_t i = 0; i < size; i++) \ M3[i] = M1[i] + (alpha*M2[i]); \ \ return 0; \ } /** @brief Add real matrices A and B * * Calculate A+alpha*B -> C. * * The result will be stored in C. If C is NULL, the result is stored in A. * * @param [in,out] A real matrix * @param [in] B real matrix * @param [in] alpha real scalar * @param [in,out] C real matrix or NULL * * @retval 0 if successfull * @retval LIBHADES_ERROR_SHAPE if matrices have wrong shape */ MATRIX_ADD(matrix_add, double, matrix_t, double, matrix_t) /** @brief Add complex matrices A and B * * Calculate A+alpha*B -> C. * * The result will be stored in C. If C is NULL, the result is stored in A. * * @param [in,out] A complex matrix * @param [in] B complex matrix * @param [in] alpha complex number * @param [in,out] C complex matrix or NULL * * @retval 0 if successfull * @retval LIBHADES_ERROR_SHAPE if matrices have wrong shape */ MATRIX_ADD(matrix_complex_add, complex_t, matrix_complex_t, complex_t, matrix_complex_t) /** @brief Add complex matrix A and real matrix B * * Calculate A+alpha*B -> C. * * The result will be stored in C. If C is NULL, the result is stored in A. * * @param [in,out] A complex matrix * @param [in] B real matrix * @param [in] alpha complex scalar * @param [in,out] C complex matrix or NULL * * @retval 0 if successfull * @retval LIBHADES_ERROR_SHAPE if matrices have wrong shape */ MATRIX_ADD(matrix_complex_add_real, complex_t, matrix_complex_t, double, matrix_t) /** @}*/ /** \defgroup transconj Transpose, conjugate * @{ */ #define MATRIX_TRANSPOSE(FUNCTION_NAME, MTYPE, TYPE) \ void FUNCTION_NAME(MTYPE *A) \ { \ const int rows = A->rows; \ const int columns = A->columns; \ for(int im = 0; im < rows; im++) \ for(int in = im+1; in < columns; in++) \ { \ TYPE temp = matrix_get(A, im, in); \ matrix_set(A, im, in, matrix_get(A, in, im)); \ matrix_set(A, in, im, temp); \ } \ \ A->rows = columns; \ A->columns = rows; \ } /** @brief Transpose real matrix A * * The matrix will be transposed. * * @param [in,out] A real matrix * * @retval C with C=A^T */ MATRIX_TRANSPOSE(matrix_transpose, matrix_t, double) /** @brief Transpose complex matrix A * * The matrix will be transposed. * * @param [in,out] A complex matrix * * @retval C with C=A^T */ MATRIX_TRANSPOSE(matrix_complex_transpose, matrix_complex_t, complex_t) /** @}*/ /** \defgroup ev Eigenvalue problems * @{ */ /** @brief Compute eigenvalues and optionally eigenvectors of symmetric matrix A * * This function computes all eigenvalues and, optionally, eigenvectors of a * real symmetric matrix A. * * See dsyev. * * @param [in] A real matrix * @param [in] JOBZ 'N': only eigenvalues, 'V' eigenvalues and eigenvectors * @param [in] UPLO 'U': upper triangle part of A is stored; 'L': lower triangle part of A is stored * @param [in] w real matrix of dimension (dim,1) (i.e. a vector); the eigenvalues will be stored in w * * @retval 0 on success */ int eig_sym(matrix_t *A, char *JOBZ, char *UPLO, matrix_t *w) { int info, lwork = -1, N = A->min; double workopt; double *work; dsyev_(JOBZ, UPLO, &N, A->M, &N, w->M, &workopt, &lwork, &info); if(info != 0) return info; lwork = workopt; work = malloc_cb(lwork*sizeof(double)); if(work == NULL) return LIBHADES_ERROR_OOM; dsyev_(JOBZ, UPLO, &N, A->M, &N, w->M, work, &lwork, &info); free_cb(work); return info; } /** @brief Compute eigenvalues and optionally eigenvectors of Hermitian matrix A * * This function computes all eigenvalues and, optionally, eigenvectors of a * Hermitian symmetric matrix A. * * See zheev. * * @param [in] A complex matrix * @param [in] JOBZ 'N': only eigenvalues, 'V' eigenvalues and eigenvectors * @param [in] UPLO 'U': upper triangle part of A is stored; 'L': lower triangle part of A is stored * @param [in] w real matrix of dimension (dim,1) (i.e. a vector); the eigenvalues will be stored in w * * @retval 0 on success */ int eig_herm(matrix_complex_t *A, char *JOBZ, char *UPLO, matrix_t *w) { int info, lwork = -1, N = A->min; complex_t workopt; complex_t *work = NULL; double *rwork; rwork = malloc_cb(MAX(1, 3*N-2)*sizeof(double)); if(rwork == NULL) return LIBHADES_ERROR_OOM; zheev_(JOBZ, UPLO, &N, A->M, &N, w->M, &workopt, &lwork, rwork, &info); if(info != 0) { free_cb(rwork); return info; } lwork = CREAL(workopt); work = malloc_cb(lwork*sizeof(complex_t)); if(work == NULL) { free_cb(rwork); return LIBHADES_ERROR_OOM; } zheev_(JOBZ, UPLO, &N, A->M, &N, w->M, work, &lwork, rwork, &info); free_cb(rwork); free_cb(work); return info; } /** @brief Compute eigenvalues and optionally eigenvectors of matrix A * * Compute for an N-by-N complex nonsymmetric matrix A, the eigen- values and, * optionally, right eigenvectors * * See zgeev. * * @param [in] A real matrix * @param [in] w list containing the eigenvalues of A * @param [in] vr if vr != NULL, right eigenvectors are computed and will be stored in vr; vr must be a complex matrix of dimension (dim,dim) * @param [in] vl if vl != NULL, lefft eigenvectors are computed and will be stored in vl; vl must be a complex matrix of dimension (dim,dim) * * @retval 0 on success */ /* Parameters */ int eig_complex_generic(matrix_complex_t *A, matrix_complex_t *w, matrix_complex_t *vl, matrix_complex_t *vr) { int N = A->min; int lwork = -1; char jobvr = 'N'; char jobvl = 'N'; int info; complex_t *evr = NULL; complex_t *evl = NULL; complex_t *work = NULL; double *rwork = NULL; complex_t wopt; /* if vr is not NULL, calculate right eigenvectors */ if(vr != NULL) { jobvr = 'V'; evr = vr->M; } /* if vl is not NULL, calculate left eigenvectors */ if(vl != NULL) { jobvl = 'V'; evl = vl->M; } /* get the optimal size for workspace work */ zgeev_(&jobvl, &jobvr, &N, A->M, &N, w->M, evl, &N, evr, &N, &wopt, &lwork, rwork, &info); if(info != 0) return info; lwork = CREAL(wopt); rwork = malloc_cb(2*N*sizeof(double)); work = malloc_cb(lwork*sizeof(complex_t)); if(rwork == NULL || work == NULL) { if(rwork != NULL) free(rwork); if(work != NULL) free(work); return LIBHADES_ERROR_OOM; } /* SUBROUTINE ZGEEV( JOBVL, JOBVR, N, A, LDA, W, VL, LDVL, VR, LDVR, WORK, LWORK, RWORK, INFO ) */ zgeev_( &jobvl, /* left eigenvectors of A are not computed */ &jobvr, /* calculate/don't calculate right eigenvectors */ &N, /* order of matrix A */ A->M, /* matrix A */ &N, /* LDA - leading dimension of A */ w->M, /* eigenvalues */ evl, /* left eigenvectors */ &N, /* leading dimension of array vl */ evr, /* eigenvectors */ &N, /* leading dimension of the array VR */ work, /* COMPLEX*16 array, dimension (LWORK) */ &lwork, /* dimension of the array WORK; LWORK >= max(1,2*N) */ rwork, /* (workspace) DOUBLE PRECISION array, dimension (2*N) */ &info /* 0 == success */ ); free_cb(work); free_cb(rwork); return info; } int eig_complex_vr(matrix_complex_t *M, complex_t lambda, matrix_complex_t *vr) { matrix_complex_t *A = NULL, *b = NULL; const int rows = M->rows; const int columns = M->columns; /* lapack */ char trans = 'N'; int info, lwork; complex_t work_size, *work = NULL; int m = rows+1, n = columns, nrhs = 1; int lda = m, ldb = MAX(m,n); if((A = matrix_complex_alloc(rows+1, columns)) == NULL) return LIBHADES_ERROR_OOM; if((b = matrix_complex_zeros(rows+1,1,NULL)) == NULL) { matrix_complex_free(A); return LIBHADES_ERROR_OOM; } matrix_set(b, rows,0, 1); for(int j = 0; j < columns; j++) { for(int i = 0; i < rows; i++) matrix_set(A, i, j, matrix_get(M, i,j)); /* - lambda Id */ matrix_set(A, j,j, matrix_get(A,j,j)-lambda); /* set nomalization condition */ matrix_set(A, rows,j, 1); } /* determine work size */ lwork = -1; zgels_(&trans, &m, &n, &nrhs, A->M, &lda, b->M, &ldb, &work_size, &lwork, &info); lwork = (int)CREAL(work_size); if((work = malloc_cb(lwork*sizeof(complex_t))) == NULL) { matrix_complex_free(A); matrix_complex_free(vr); return LIBHADES_ERROR_OOM; } /* calculate eigenvector */ zgels_( &trans, /* find least squares solution of overdetermined system */ &m, /* number of rows of matrix A */ &n, /* number of columns of matrix A */ &nrhs, /* number of columns of matrix B */ A->M, /* matrix A (will be overwritten) */ &lda, /* leading dimension of A, LDA >= max(1,M) */ b->M, /* on entry: right hand side vectors, on exit: solution */ &ldb, /* leading dimension of B, LDB >= MAX(1,M,N) */ work, /* workspace */ &lwork, /* dimension of work */ &info /* status */ ); free_cb(work); matrix_complex_free(A); for(int i = 0; i < rows; i++) matrix_set(vr, i,0, matrix_get(b, i,0)); matrix_complex_free(b); return info; } /** @}*/ /** \defgroup exp Calculate matrix exponential * @{ */ /** macro to calculate matrix norm */ #define MATRIX_NORM(FUNCTION_NAME, MTYPE, LAPACK_FUNC) \ int FUNCTION_NAME(MTYPE *A, char norm_type, double *norm) \ { \ double *work = NULL; \ \ if(norm_type == 'I') \ { \ work = malloc_cb(A->rows*sizeof(double)); \ if(work == NULL) \ return LIBHADES_ERROR_OOM; \ } \ \ *norm = LAPACK_FUNC(&norm_type, &A->rows, &A->columns, A->M, &A->rows, work); \ \ if(work != NULL) \ free_cb(work); \ \ return 0; \ } /** @brief Compute matrix norm for real matrix * * See dlange. * * Returns * max(abs(A(i,j))), norm_type = 'M' or 'm' * norm1(A), norm_type = '1', 'O' or 'o' * normI(A), norm_type = 'I' or 'i' * normF(A), norm_type = 'F', 'f', 'E' or 'e' * * @param [in] A real matrix * @param [in] norm_type type of norm, e.g. 'F' for Frobenius norm * @param [out] norm value of norm * * @retval ret 0 if successfull, <0 otherwise */ MATRIX_NORM(matrix_norm, matrix_t, dlange_); /** @brief Compute matrix norm for complex matrix * * See matrix_norm. * * @param [in] A complex matrix * @param [in] norm_type type of norm, e.g. 'F' for Frobenius norm * @param [out] norm value of norm * * @retval ret 0 if successfull, <0 otherwise */ MATRIX_NORM(matrix_complex_norm, matrix_complex_t, zlange_); matrix_complex_t *matrix_complex_exp_taylor(matrix_complex_t *A, int order) { const int rows = A->min; matrix_complex_t *C = matrix_complex_alloc(rows,rows); /* B = E+A/order */ matrix_complex_t *B = matrix_complex_copy(A,NULL); matrix_complex_mult_scalar(B, 1./order); for(int i = 0; i < rows; i++) matrix_set(B, i,i, 1+matrix_get(B,i,i)); for(int k = order-1; k > 0; k--) { matrix_complex_mult(A, B, 1./order, C); /* swap */ { matrix_complex_t *temp; temp = C; C = B; B = temp; } for(int i = 0; i < rows; i++) matrix_set(B, i,i, 1+matrix_get(B,i,i)); } matrix_complex_free(C); return B; } /** @}*/ /** \defgroup LA LU decomposition, inverting * @{ */ #define LU_DECOMPOSITION(FUNCTION_NAME, MATRIX_TYPE, XGETRF) \ int FUNCTION_NAME(MATRIX_TYPE *A, int ipiv[]) \ { \ int info; \ \ XGETRF( \ &A->rows, /* M number of rows of A */ \ &A->columns, /* N number of columns of A */ \ A->M, /* matrix A to be factored */ \ &A->columns, /* LDA: leading dimension of A */ \ ipiv, /* pivot indices of dimension (min(M,N)) */ \ &info \ ); \ \ return info; \ } /** @brief Compute LU decomposition of real matrix A * * See dgetrf. * * The factorization has the form * A = P * L * U * where P is a permutation matrix, L is lower triangular with unit * diagonal elements (lower trapezoidal if rows > columns), and U is upper * triangular (upper trapezoidal if m < n). * * @param [in,out] A real matrix * @param [out] ipiv pivot indices; array of dimension MIN(rows,columns) * * @retval INFO */ LU_DECOMPOSITION(matrix_lu_decomposition, matrix_t, dgetrf_) /** @brief Compute LU decomposition of complex matrix A * * See matrix_lu_decomposition. * * @param [in,out] A complex matrix * @param [out] ipiv pivot indices; array of dimension MIN(rows,columns) * * @retval INFO */ LU_DECOMPOSITION(matrix_complex_lu_decomposition, matrix_complex_t, zgetrf_) #define MATRIX_INVERT(FUNCTION_NAME, TYPE, MATRIX_TYPE, LU_DECOMPOSITION, XGETRI) \ int FUNCTION_NAME(MATRIX_TYPE *A) \ { \ int info, lwork, dim = A->min; \ int *ipiv = NULL; \ TYPE *work = NULL; \ TYPE workopt; \ \ ipiv = malloc_cb(dim*sizeof(int)); \ if(ipiv == NULL) \ return LIBHADES_ERROR_OOM; \ \ info = LU_DECOMPOSITION(A, ipiv); \ if(info != 0) \ goto out; \ \ lwork = -1; \ XGETRI(&dim, A->M, &dim, ipiv, &workopt, &lwork, &info); \ if(info != 0) \ goto out; \ \ lwork = (int)workopt; \ work = malloc_cb(lwork*sizeof(TYPE)); \ if(work == NULL) \ { \ info = LIBHADES_ERROR_OOM; \ goto out; \ } \ \ XGETRI( \ &dim, /* order of matrix A */ \ A->M, /* factors L and U from LU decomposition */ \ &dim, /* LDA: leading dimension of A */ \ ipiv, /* pivot indices */ \ work, /* workspace of dimension LWORK */ \ &lwork, /* length of work */ \ &info \ ); \ \ out: \ free_cb(ipiv); \ if(work != NULL) \ free_cb(work); \ \ return info; \ } /** @brief Invert real matrix A * * The inverse of A is computed using the LU factorzation of A * * @param [in] A real matrix * * @retval INFO */ MATRIX_INVERT(matrix_invert, double, matrix_t, matrix_lu_decomposition, dgetri_) /** @brief Invert complex matrix A * * See matrix_invert. * * @param [in] A complex matrix * * @retval INFO */ MATRIX_INVERT(matrix_complex_invert, complex_t, matrix_complex_t, matrix_complex_lu_decomposition, zgetri_) #define MATRIX_SOLVE(FUNCTION_NAME, MATRIX_TYPE, LU_DECOMPOSITION, XGETRS) \ int FUNCTION_NAME(MATRIX_TYPE *A, MATRIX_TYPE *b) \ { \ int N = A->min; \ char trans = 'N'; \ int nrhs = b->columns; \ int info = -1; \ int *ipiv = malloc_cb(N*sizeof(int)); \ \ if(ipiv == NULL) \ return LIBHADES_ERROR_OOM; \ \ LU_DECOMPOSITION(A, ipiv); \ XGETRS(&trans, &N, &nrhs, A->M, &N, ipiv, b->M, &N, &info); \ \ free_cb(ipiv); \ \ return info; \ } /** @brief Solve system of linear equations * * Solve the system of linear equations: * A*x = b * * @param [in,out] A matrix * @param [in,out] b vector/matrix * * @retval INFO */ /** @}*/ MATRIX_SOLVE(matrix_solve, matrix_t, matrix_lu_decomposition, dgetrs_); /** @brief Solve system of linear equations * * Solve the system of complex linear equations: * A*x = b * * @param [in,out] A complex matrix * @param [in,out] b complex vector/matrix * * @retval INFO */ /** @}*/ MATRIX_SOLVE(matrix_complex_solve, matrix_complex_t, matrix_complex_lu_decomposition, zgetrs_); /* static void _cblas_zaxpy(const int N, const double alpha, const void *X, const int incX, void *Y, const int incY) { complex_t beta = alpha; cblas_zaxpy(N, &beta, X, incX, Y, incY); } */ /** @brief Calculate dot product of vectors x and y * * Calculate dot product of first column of x,y. If x and y have different * rows, the minimum is used. * * @param [in] x vector * @param [in] y vector * @retval x*y */ double vector_dot(matrix_t *x, matrix_t *y) { int incx = 1; int incy = 1; int N = MIN(x->rows, y->rows); return ddot_(&N, x->M, &incx, y->M, &incy); } /** @brief Calculate dot product of vectors x and y * * Calculate dot product of first column of x,y. If x and y have different * rows, the minimum is used. * * @param [in] x vector * @param [in] y vector * @retval x*y */ complex_t vector_complex_dot(matrix_complex_t *x, matrix_complex_t *y) { /* int incx = 1; int incy = 1; int N = MIN(x->rows, y->rows); complex_t z = 0; zdotc_(&z, &N, x->M, &incx, y->M, &incy); return z; */ int N = MIN(x->rows, y->rows); complex_t z = 0; for(int i = 0; i < N; i++) z += matrix_get(x,i,0)*matrix_get(y,i,0); return z; } #define MATRIX_GET_COLUMN(FUNCTION_NAME, TYPE, MATRIX_TYPE) \ MATRIX_TYPE *FUNCTION_NAME(MATRIX_TYPE *A, int i) \ { \ const int rows = A->rows; \ MATRIX_TYPE *v = malloc_cb(sizeof(MATRIX_TYPE)); \ if(v == NULL) \ return NULL; \ \ v->rows = rows; \ v->columns = 1; \ v->min = 1; \ v->size = rows; \ v->type = 0; \ v->view = 1; \ v->M = &A->M[i*rows]; \ \ return v; \ } /** @brief Get i-th column of matrix A * * @param [in] A matrix * @param [in] i column number * @retval x*y */ MATRIX_GET_COLUMN(matrix_get_column, double, matrix_t); /** @brief Get i-th column of matrix A * * @param [in] A matrix * @param [in] i column number * @retval x*y */ MATRIX_GET_COLUMN(matrix_complex_get_column, complex_t, matrix_complex_t); /** \defgroup sparse Functions for sparse matrices * @{ */ #ifdef SUPPORT_SPARSE /** @brief Calculate eigenvalues of a sparse complex matrix * * @param [in] N number of columns/rows of matrix * @param [in] nev number of eigenvalues to compute * @param [in] which LM (largest magnitude), SM (smallest magnitude), LR (largest real part), SR (smallest real part), LI (largest imaginary part), SI (smallest imaginary part) * @param [in] Av callback function that implements the matrix-vector operation Av; the input vector is given as in, the vector Av must be written in out * @param [in,out] d on exit d contains the Rith approximations (must be of length nev+1) * @param [in] mxiter maximum number of Arnoldi update iterations allowed * @param [in] tol relative accuracy of the Ritz value * @param [in] data pointer that is given to callback function Av * * @retval 0 if successful */ int sparse_complex_eig(int N, int nev, char *which, void (*Av)(int N, complex_t *in, complex_t *out, void *data), complex_t *d, int mxiter, double tol, void *data) { int ret = LIBHADES_ERROR_OOM; int info = 0; int ido = 0; char *bmat = "I"; /* standard eigenproblem */ int ncv = MIN(2*nev+2, N); int ishift = 1; int mode = 1; int iparam[11] = { ishift, 0, mxiter, 1, 0, 0, mode, 0, 0, 0, 0 }; int ipntr[14]; int lworkl = ncv*(3*ncv + 5); int rvec = 0; char *howmny = "P"; complex_t *workd = NULL, *workl = NULL, *resid = NULL, *v = NULL, *workev = NULL; int *select = NULL; double *rwork = NULL; /* allocate memory */ ret = LIBHADES_ERROR_OOM; workd = malloc_cb(3*N*sizeof(complex_t)); if(workd == NULL) goto out; workl = malloc_cb(lworkl*sizeof(complex_t)); if(workl == NULL) goto out; rwork = malloc_cb(ncv*sizeof(double)); if(rwork == NULL) goto out; resid = malloc_cb(N*sizeof(complex_t)); if(resid == NULL) goto out; v = malloc_cb(N*ncv*sizeof(complex_t)); if(v == NULL) goto out; select = malloc_cb(ncv*sizeof(int)); if(select == NULL) goto out; workev = malloc_cb((2*ncv)*sizeof(complex_t)); if(workev == NULL) goto out; /* loop */ while(1) { /* http://www.caam.rice.edu/software/ARPACK/UG/node138.html */ znaupd_( &ido, bmat, &N, which, &nev, &tol, resid, &ncv, v, &N, iparam, ipntr, workd, workl, &lworkl, rwork, &info, strlen(bmat), strlen(which) ); if(ido == 1 || ido == -1) Av(N, &workd[ipntr[0]-1], &workd[ipntr[1]-1], data); else if(ido == 99) break; else { ret = ido; goto out; } } if(info != 0) { ret = info; goto out; } /* http://www.mathkeisan.com/usersguide/man/zneupd.html */ zneupd_( &rvec, howmny, select, d, NULL, &N, NULL, workev, bmat, &N, which, &nev, &tol, resid, &ncv, v, &N, iparam, ipntr, workd, workl, &lworkl, rwork, &info, strlen(howmny), strlen(bmat), strlen(which) ); ret = info; out: if(resid != NULL) free_cb(resid); if(v != NULL) free_cb(v); if(workd != NULL) free_cb(workd); if(workl != NULL) free_cb(workl); if(rwork != NULL) free_cb(rwork); if(select != NULL) free_cb(select); if(workev != NULL) free_cb(workev); return ret; } #endif /** @}*/ /** \defgroup io Save/load matrices * @{ */ #define MATRIX_LOAD_FROM_STREAM(FUNCTION_NAME, MATRIX_TYPE, TYPE, ALLOC, TRANSPOSE, IS_COMPLEX) \ MATRIX_TYPE *FUNCTION_NAME(FILE *stream, int *ret) \ { \ MATRIX_TYPE *M; \ uint16_t len; \ int rows, columns, fortran_order, is_complex; \ char header[10] = { 0 }; \ char dict[2048] = { 0 }; \ \ if(ret != NULL) \ *ret = 0; \ \ /* read magic string, major and minor number */ \ fread(header, 8, 1, stream); \ if(memcmp(header, "\x93NUMPY\x01\x00", 8) != 0) \ { \ if(ret != NULL) \ *ret = LIBHADES_ERROR_HEADER; \ return NULL; \ } \ \ /* read length of dict */ \ fread(&len, sizeof(uint16_t), 1, stream); \ \ if(len >= sizeof(dict)/sizeof(dict[0])) \ { \ if(ret != NULL) \ *ret = LIBHADES_ERROR_INV_LENGTH; \ return NULL; \ } \ \ fread(dict, sizeof(char), len, stream); \ \ if(npy_dict_get_fortran_order(dict, &fortran_order) != 0) \ { \ if(ret != NULL) \ *ret = LIBHADES_ERROR_ORDER; \ return NULL; \ } \ \ if(npy_dict_get_shape(dict, &rows, &columns) != 0) \ { \ if(ret != NULL) \ *ret = LIBHADES_ERROR_SHAPE; \ return NULL; \ } \ \ if(npy_dict_get_descr(dict, &is_complex) != 0) \ { \ if(ret != NULL) \ *ret = LIBHADES_ERROR_DESCR; \ return NULL; \ } \ \ if(is_complex != IS_COMPLEX) \ { \ if(ret != NULL) \ *ret = LIBHADES_ERROR_FORMAT; \ return NULL; \ } \ \ M = ALLOC(rows,columns); \ fread(M->M, sizeof(TYPE), rows*columns, stream); \ \ if(!fortran_order) \ TRANSPOSE(M); \ \ M->min = MIN(rows,columns); \ M->size = (size_t)rows*(size_t)columns; \ M->view = 0; \ M->type = 0; \ \ return M; \ } /** @brief Load real matrix from stream * * Load real matrix A from a stream. This function will also allocate memory * for the matrix. * * If error != NULL, error will be set to: * 0 if successful * LIBHADES_ERROR_HEADER if magic or major/minor number is invalid * LIBHADES_ERROR_INV_LENGTH if length of dictionary is invalid (too long) * LIBHADES_ERROR_ORDER if order is invalid (Fortran/C order) * LIBHADES_ERROR_SHAPE if shape is invalid (rows/columns) * LIBHADES_ERROR_DESCR if dtype is wrong/not supported * LIBHADES_ERROR_FORMAT if wrong format (real instead of complex) * 0 rows/columns wrong * * @param [in] stream file handle of a opened file * @param [out] error error code * @retval A matrix * @retval NULL if an error occured */ MATRIX_LOAD_FROM_STREAM(matrix_load_from_stream, matrix_t, double, matrix_alloc, matrix_transpose, 0); /** @brief Load complex matrix from stream * * Load complex matrix A from a stream. This function will also allocate memory * for the matrix. * * If error != NULL, error will be set to: * 0 if successful * LIBHADES_ERROR_HEADER if magic or major/minor number is invalid * LIBHADES_ERROR_INV_LENGTH if length of dictionary is invalid (too long) * LIBHADES_ERROR_ORDER if order is invalid (Fortran/C order) * LIBHADES_ERROR_SHAPE if shape is invalid (rows/columns) * LIBHADES_ERROR_DESCR if dtype is wrong/not supported * LIBHADES_ERROR_FORMAT if wrong format (complex instead of real) * 0 rows/columns wrong * * @param [in] stream file handle of a opened file * @param [out] error error code * @retval A matrix * @retval NULL if an error occured */ MATRIX_LOAD_FROM_STREAM(matrix_complex_load_from_stream, matrix_complex_t, complex_t, matrix_complex_alloc, matrix_complex_transpose, 1); #define MATRIX_LOAD(FUNCTION_NAME, MATRIX_TYPE, LOAD_FUNCTION) \ MATRIX_TYPE *FUNCTION_NAME(const char *filename, int *ret) \ { \ FILE *stream; \ MATRIX_TYPE *M; \ \ if((stream = fopen(filename, "r")) == NULL) \ { \ if(ret != NULL) \ *ret = LIBHADES_ERROR_IO; \ return NULL; \ } \ \ M = LOAD_FUNCTION(stream, ret); \ \ fclose(stream); \ \ return M; \ } /** @brief Load real matrix from file * * Load real matrix A from file given by filename. This function will also * allocate memory for the matrix. See \ref matrix_load_from_stream for errors. * * @param [in] filename path to the file * @param [out] error error code * @retval A matrix * @retval NULL if an error occured */ MATRIX_LOAD(matrix_load, matrix_t, matrix_load_from_stream); /** @brief Load complex matrix from file * * Load complex matrix A from file given by filename. This function will also * allocate memory for the matrix. See \ref matrix_complex_load_from_stream for * errors. * * @param [in] filename path to the file * @param [out] error error code * @retval A matrix * @retval NULL if an error occured */ MATRIX_LOAD(matrix_complex_load, matrix_complex_t, matrix_complex_load_from_stream); #define MATRIX_SAVE_TO_STREAM(FUNCTION_NAME, TYPE, MATRIX_TYPE, DTYPE) \ void FUNCTION_NAME(MATRIX_TYPE *M, FILE *stream) \ { \ char d_str[512] = { 0 }; \ uint16_t len = 0; \ const int rows = M->rows, columns = M->columns; \ \ /* write magic string, major number and minor number */ \ fwrite("\x93NUMPY\x01\x00", sizeof(char), 8, stream); \ \ /* write length of header and header */ \ snprintf(d_str, sizeof(d_str)/sizeof(d_str[0]), "{'descr': '%s', 'fortran_order': True, 'shape': (%d, %d), }", DTYPE, rows, columns); \ \ len = strlen(d_str); \ \ fwrite(&len, sizeof(len), 1, stream); \ fwrite(d_str, sizeof(char), len, stream); \ \ /* write matrix */ \ fwrite(M->M, sizeof(TYPE), M->size, stream); \ } /** @brief Save real matrix A to stream * * Save real matrix A to a file handle given by stream. The datatype * corresponds to Numpy's npy file format. * * @param [in] A matrix to be dumped to file * @param [in] stream file handle of opened file */ MATRIX_SAVE_TO_STREAM(matrix_save_to_stream, double, matrix_t, "<f8"); /** @brief Save complex matrix A to stream * * Save complex matrix A to a file handle given by stream. The datatype * corresponds to Numpy's npy file format. * * @param [in] A matrix to be dumped to file * @param [in] stream file handle of opened file */ MATRIX_SAVE_TO_STREAM(matrix_complex_save_to_stream, complex_t, matrix_complex_t, "<c16"); #define MATRIX_SAVE(FUNCTION_NAME, MATRIX_TYPE, SAVE_FUNCTION) \ int FUNCTION_NAME(MATRIX_TYPE *M, const char *filename) \ { \ FILE *stream = fopen(filename, "w"); \ if(stream == NULL) \ return LIBHADES_ERROR_IO; \ \ SAVE_FUNCTION(M, stream); \ \ fclose(stream); \ \ return 0; \ }; /** @brief Save real matrix A to file * * Save real matrix A to file given by filename. The datatype corresponds to * Numpy's .npy file format. * * @param [in] A matrix to be dumped to file * @param [in] filename path to the file * @retval 0 if successful * @retval LIBHADES_ERROR_IO if file could not be opened */ MATRIX_SAVE(matrix_save, matrix_t, matrix_save_to_stream); /** @brief Save complex matrix A to file * * Save complex matrix A to file given by filename. The datatype corresponds to * Numpy's .npy file format. * * @param [in] A matrix to be dumped to file * @param [in] filename path to the file * @retval 0 if successful * @retval LIBHADES_ERROR_IO if file could not be opened */ MATRIX_SAVE(matrix_complex_save, matrix_complex_t, matrix_complex_save_to_stream); /** @}*/
{ "alphanum_fraction": 0.6059084251, "avg_line_length": 26.3503759398, "ext": "c", "hexsha": "7edbdeb1e6e70c973bd216748aaa683438aab435", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "81a2ab18dbf59975f8fbae0693a757b054b4501c", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "michael-hartmann/libhades", "max_forks_repo_path": "src/libhades.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "81a2ab18dbf59975f8fbae0693a757b054b4501c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "michael-hartmann/libhades", "max_issues_repo_path": "src/libhades.c", "max_line_length": 176, "max_stars_count": 4, "max_stars_repo_head_hexsha": "81a2ab18dbf59975f8fbae0693a757b054b4501c", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "michael-hartmann/libhades", "max_stars_repo_path": "src/libhades.c", "max_stars_repo_stars_event_max_datetime": "2019-08-28T20:09:32.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-03T15:07:53.000Z", "num_tokens": 15193, "size": 52569 }
#pragma once #include <algorithm> #include <array> #include <cstdint> #include <initializer_list> #include <iterator> #include <sstream> #include <string> #include <tuple> #include <gsl/gsl> #include "chainerx/axes.h" #include "chainerx/constant.h" #include "chainerx/dtype.h" #include "chainerx/error.h" #include "chainerx/macro.h" #include "chainerx/shape.h" namespace chainerx { class Strides : public Dims { using BaseVector = Dims; public: using const_iterator = BaseVector::const_iterator; using const_reverse_iterator = BaseVector::const_reverse_iterator; Strides() = default; ~Strides() = default; // Creates strides for contiguous array. Strides(const Shape& shape, Dtype dtype) : Strides{shape, GetItemSize(dtype)} {} Strides(const Shape& shape, int64_t item_size); // by iterators template <typename InputIt> Strides(InputIt first, InputIt last) { if (std::distance(first, last) > kMaxNdim) { throw DimensionError{"too many dimensions: ", std::distance(first, last)}; } insert(begin(), first, last); } // by gsl:span explicit Strides(gsl::span<const int64_t> dims) : Strides{dims.begin(), dims.end()} {} // by initializer list Strides(std::initializer_list<int64_t> dims) : Strides{dims.begin(), dims.end()} {} // copy Strides(const Strides&) = default; Strides& operator=(const Strides&) = default; // move Strides(Strides&&) = default; Strides& operator=(Strides&&) = default; std::string ToString() const; int8_t ndim() const noexcept { return gsl::narrow_cast<int8_t>(size()); } const int64_t& operator[](int8_t index) const { if (!(0 <= index && static_cast<size_t>(index) < size())) { throw DimensionError{"Stride index ", index, " out of bounds for strides with ", size(), " size."}; } return this->StackVector::operator[](index); } int64_t& operator[](int8_t index) { if (!(0 <= index && static_cast<size_t>(index) < size())) { throw DimensionError{"Stride index ", index, " out of bounds for strides with ", size(), " size."}; } return this->StackVector::operator[](index); } // span gsl::span<const int64_t> span() const { return {*this}; } // Rearranges strides in the order specified by the axes. // // The size of given axes may be fewer than the size of strides. // In that case, new strides will be composed by only given axes. // // It is the caller's responsibility to ensure validity of permutation. // If the permutation is invalid, the behavior is undefined. Strides Permute(const Axes& axes) const { CHAINERX_ASSERT(axes.size() <= size()); Strides new_strides{}; for (int8_t axe : axes) { new_strides.emplace_back(operator[](axe)); } return new_strides; } }; std::ostream& operator<<(std::ostream& os, const Strides& strides); void CheckEqual(const Strides& lhs, const Strides& rhs); // Returns a pair of lower and upper byte offsets to store the data. // This forumula always holds: lower <= 0 < item_size <= upper std::tuple<int64_t, int64_t> GetDataRange(const Shape& shape, const Strides& strides, size_t item_size); } // namespace chainerx
{ "alphanum_fraction": 0.6503918023, "avg_line_length": 30.7222222222, "ext": "h", "hexsha": "04c4dc9f73f9002a70a18ab73d9da548cdb74449", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "3029bbaa587c15b3539b55ee1fd357a4149e5aed", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "prabhatnagarajan/chainer", "max_forks_repo_path": "chainerx_cc/chainerx/strides.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3029bbaa587c15b3539b55ee1fd357a4149e5aed", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "prabhatnagarajan/chainer", "max_issues_repo_path": "chainerx_cc/chainerx/strides.h", "max_line_length": 111, "max_stars_count": null, "max_stars_repo_head_hexsha": "3029bbaa587c15b3539b55ee1fd357a4149e5aed", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "prabhatnagarajan/chainer", "max_stars_repo_path": "chainerx_cc/chainerx/strides.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 826, "size": 3318 }
// my_gsl.h is included in bayesMLR.c // Contains wrapper funtions // References: // https://www.gnu.org/software/gsl/manual/html_node/Matrices.html // https://github.com/Blei-Lab/diln/blob/master/gsl_wrapper.c #include <stdio.h> // standard input/output #include <stdlib.h> // malloc #include <math.h> // fabs, sqrt, etc. #include <time.h> // time / set seed #include <gsl/gsl_rng.h> // GNU Scientific Library #include <gsl/gsl_cdf.h> // GNU Scientific Library #include <gsl/gsl_randist.h> // GNU Scientific Library #include <gsl/gsl_linalg.h> // GNU Scientific Library #include <gsl/gsl_matrix.h> // GNU Scientific Library #include <gsl/gsl_statistics.h>// GNU Scientific Library #include <gsl/gsl_blas.h> // GSL Basic Linear Algebra #define pi 3.14159265358979323846 // Reading Matrices //////////////////////////////////////////////// int countFileRows(char* filename) { // Count number of rows in file "filename" FILE *fp; int count = 0; // Line counter (result) char c; // To store a character read from file fp = fopen(filename, "r"); // Extract characters from file and store in character c if (fp) { // check file existence for (c = getc(fp); c != EOF; c = getc(fp)) if (c == '\n') // Increment count if this character is newline count = count + 1; } fclose(fp); return count; } int countFileCols(char* filename, char delim) { // Count number of columns in file "filename" (with delimiter delim) FILE *fp = fopen(filename, "r"); char c; int count = 0; while( c=fgetc(fp) ) { if(c == EOF) { break; /* break if end of file */ } else if (c == delim) { count += 1; /* otherwise add one to the count */ } else if (c == '\n') { count += 1; break; } } fclose(fp); return count; } void read_csv(char* filename, gsl_matrix* m) { // Read a csv into matrix m FILE* f = fopen(filename, "r"); gsl_matrix_fscanf(f, m); fclose(f); } // Printing Matrix Info //////////////////////////// void print_vector(gsl_matrix* v, char* filename) { FILE* f; if (filename == "") { f = stdout; printf("\n"); } else { f = fopen(filename, "w"); } gsl_vector_fprintf(f,v,"%g"); } void print_matrix(gsl_matrix* m, char* filename) { // print matrix to filename or stdout if filename == "" FILE* f; if (filename == "") { f = stdout; printf("\n"); } else { f = fopen(filename, "w"); } int n = m->size1; int k = m->size2; for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) { fprintf (f, "%g\t", gsl_matrix_get (m, i, j)); } fprintf (f, "\n"); } if (filename == "") { printf("\n"); } else { fclose(f); } } void print_matrix_dims(gsl_matrix* m) { // print dimensions of matrix m printf("%d%s%d\n",m->size1,"x",m->size2); } // Access Matrix Elements: ////////////////////////////////// void mat_sub(gsl_matrix* X, size_t r1, size_t r2, size_t c1, size_t c2, gsl_matrix* X_new) { gsl_matrix_view x = gsl_matrix_submatrix(X,r1,c1,r2-r1+1,c2-c1+1); gsl_matrix_memcpy(X_new,&x.matrix); } // Random Number Functions: ///////////////////////////////// double runif() { // Returns a random number b/w 0 & 1 return (double) rand() / (double) RAND_MAX; } void mvrnorm(gsl_vector* m, gsl_matrix* cholS, gsl_rng* r, gsl_vector* out) { // vector addition, vector prod // m + cholS * e int n = m->size; double tmp; gsl_vector* e = gsl_vector_alloc(n); for (int i=0; i<n; i++) { tmp = 0; for (int j=0; j<n; j++) { if (i==0) gsl_vector_set(e,j,gsl_ran_gaussian(r,1.0)); tmp += gsl_matrix_get(cholS,i,j) * gsl_vector_get(e,j); } gsl_vector_set(out,i,gsl_vector_get(m,i) + tmp); } gsl_vector_free(e); } // Linear Algebra Wrappers ////////////////////////////////// // mm: matrix-matrix // mv: matrix-vector // ms: matrix-scalar // d: double real // ge: general matrix void mm_prod(gsl_matrix* A, gsl_matrix* B, double a, double b, gsl_matrix* out) { } void mm_add(gsl_matrix* A, gsl_matrix* B, double a, double b, gsl_matrix* out) { } void mv_prod(gsl_matrix* A, gsl_vector* x, double a, gsl_vector* out) { gsl_blas_dgemv(CblasNoTrans,a,A,x,0.0,out); } void vv_add(gsl_vector* x, gsl_vector* y, gsl_vector *out) { // sum two vectors if (x->size != y->size) error("Error in vv_add(): input vectors must have the same dimensionality"); else if (x->size != out->size || y->size != out->size) error("Error in vv_add(): output vector has incorrect dimensions"); double tmp; int n = x->size; for (int i=0; i<n; i++) { tmp = gsl_vector_get(x,i) + gsl_vector_get(y,i); gsl_vector_set(out,i,tmp); } } double vv_prod(gsl_vector* x, gsl_vector* y) { // dot product if (x->size != y->size) error("Error in vv_prod(): input vectors must have the same dimensionality"); double out = 0; int n = x->size; for (int i=0; i<n; i++) { out += gsl_vector_get(x,i) * gsl_vector_get(y,i); } return out; } void mat_inv(gsl_matrix * X, gsl_matrix * invX) { // invert the matrix X int signum; gsl_matrix * LU = gsl_matrix_calloc(X->size1,X->size2); gsl_permutation * p = gsl_permutation_calloc(X->size1); gsl_matrix_memcpy(LU,X); gsl_linalg_LU_decomp (LU,p,&signum); gsl_linalg_LU_invert(LU,p,invX); gsl_matrix_free(LU); gsl_permutation_free(p); } void xxi_m(gsl_matrix* X, gsl_matrix* xxi) { int n = X->size1; int k = X->size2; double dot; gsl_matrix* xx = gsl_matrix_alloc(k,k); for (int i=0; i<k; i++) { for (int j=0; j<=i; j++) { dot = 0; for (int z=0; z<n; z++) { dot += gsl_matrix_get(X,z,i) * gsl_matrix_get(X,z,j); } gsl_matrix_set(xx,j,i,dot); gsl_matrix_set(xx,i,j,dot); } } mat_inv(xx,xxi); gsl_matrix_free(xx); } int my_gsl_linalg_cholesky_decomp (gsl_matrix * A) { const size_t M = A->size1; const size_t N = A->size2; if (M != N) { GSL_ERROR("cholesky decomposition requires square matrix", GSL_ENOTSQR); } else { size_t i,j,k; int status = 0; /* Do the first 2 rows explicitly. It is simple, and faster. And * one can return if the matrix has only 1 or 2 rows. */ double A_00 = gsl_matrix_get (A, 0, 0); double L_00 = sqrt(A_00); if (A_00 <= 0) { status = GSL_EDOM ; } gsl_matrix_set (A, 0, 0, L_00); if (M > 1) { double A_10 = gsl_matrix_get (A, 1, 0); double A_11 = gsl_matrix_get (A, 1, 1); double L_10 = A_10 / L_00; double diag = A_11 - L_10 * L_10; double L_11 = sqrt(diag); if (diag <= 0) { status = GSL_EDOM; } gsl_matrix_set (A, 1, 0, L_10); gsl_matrix_set (A, 1, 1, L_11); } for (k = 2; k < M; k++) { double A_kk = gsl_matrix_get (A, k, k); for (i = 0; i < k; i++) { double sum = 0; double A_ki = gsl_matrix_get (A, k, i); double A_ii = gsl_matrix_get (A, i, i); gsl_vector_view ci = gsl_matrix_row (A, i); gsl_vector_view ck = gsl_matrix_row (A, k); if (i > 0) { gsl_vector_view di = gsl_vector_subvector(&ci.vector, 0, i); gsl_vector_view dk = gsl_vector_subvector(&ck.vector, 0, i); gsl_blas_ddot (&di.vector, &dk.vector, &sum); } A_ki = (A_ki - sum) / A_ii; gsl_matrix_set (A, k, i, A_ki); } { gsl_vector_view ck = gsl_matrix_row (A, k); gsl_vector_view dk = gsl_vector_subvector (&ck.vector, 0, k); double sum = gsl_blas_dnrm2 (&dk.vector); double diag = A_kk - sum * sum; double L_kk = sqrt(diag); if (diag <= 0) { status = GSL_EDOM; } gsl_matrix_set (A, k, k, L_kk); } } /* Now copy the transposed lower triangle to the upper triangle, * the diagonal is common. */ //for (i = 1; i < M; i++) // { // for (j = 0; j < i; j++) // { // double A_ij = 0;//gsl_matrix_get (A, i, j); // gsl_matrix_set (A, j, i, A_ij); // } // } if (status == GSL_EDOM) { GSL_ERROR ("matrix must be positive definite", GSL_EDOM); } return GSL_SUCCESS; } } void chol(gsl_matrix* X, gsl_matrix* cholS) { int n = X->size1; gsl_matrix_memcpy(cholS,X); my_gsl_linalg_cholesky_decomp(cholS); // lower tri stored in cholS. // So: mvrnorm <- function(M,S,n=nrow(S)) M + chol(S) %*% rnorm(n) }
{ "alphanum_fraction": 0.5472055222, "avg_line_length": 25.8847262248, "ext": "h", "hexsha": "69cb15d0c3d542882fe844cfd07ff035bc91f0e1", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "027f3f1ae4fea211f38ee0f37d6184700285e3cf", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "luiarthur/padawan", "max_forks_repo_path": "_posts/langcompare/code/raw.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "027f3f1ae4fea211f38ee0f37d6184700285e3cf", "max_issues_repo_issues_event_max_datetime": "2022-02-26T01:19:59.000Z", "max_issues_repo_issues_event_min_datetime": "2021-05-17T22:59:39.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "luiarthur/padawan", "max_issues_repo_path": "_posts/langcompare/code/raw.h", "max_line_length": 92, "max_stars_count": null, "max_stars_repo_head_hexsha": "027f3f1ae4fea211f38ee0f37d6184700285e3cf", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "luiarthur/padawan", "max_stars_repo_path": "_posts/langcompare/code/raw.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2690, "size": 8982 }
/** * * @file testing_zcungesv.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Emmanuel Agullo * @date 2010-11-15 * @precisions mixed zc -> ds * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> #include "testing_zmain.h" static int check_solution(int, int, PLASMA_Complex64_t*, int, PLASMA_Complex64_t*, PLASMA_Complex64_t*, int, double); int testing_zcungesv(int argc, char **argv) { /* Check for number of arguments*/ if (argc != 4){ USAGE("CUNGESV", "N LDA NRHS LDB", " - N : the size of the matrix\n" " - LDA : leading dimension of the matrix A\n" " - NRHS : number of RHS\n" " - LDB : leading dimension of the RHS B\n"); return -1; } int N = atoi(argv[0]); int LDA = atoi(argv[1]); int NRHS = atoi(argv[2]); int LDB = atoi(argv[3]); int ITER; double eps; int info, info_solution; int i,j; int LDAxN = LDA*N; int LDBxNRHS = LDB*NRHS; PLASMA_Complex64_t *A1 = (PLASMA_Complex64_t *)malloc(LDA*N *sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *A2 = (PLASMA_Complex64_t *)malloc(LDA*N *sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *B1 = (PLASMA_Complex64_t *)malloc(LDB*NRHS*sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *B2 = (PLASMA_Complex64_t *)malloc(LDB*NRHS*sizeof(PLASMA_Complex64_t)); /* Check if unable to allocate memory */ if ( (!A1) || (!A2) || (!B1) || (!B2) ) { printf("Out of Memory \n "); exit(0); } eps = LAPACKE_dlamch_work('e'); /*---------------------------------------------------------- * TESTING ZCGELS */ /* Initialize A1 and A2 */ LAPACKE_zlarnv_work(IONE, ISEED, LDAxN, A1); for (i = 0; i < N; i++) for (j = 0; j < N; j++) A2[LDA*j+i] = A1[LDA*j+i] ; /* Initialize B1 and B2 */ LAPACKE_zlarnv_work(IONE, ISEED, LDBxNRHS, B1); for (i = 0; i < N; i++) for (j = 0; j < NRHS; j++) B2[LDB*j+i] = B1[LDB*j+i] ; printf("\n"); printf("------ TESTS FOR PLASMA ZCUNGESV ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", N, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n",eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* PLASMA ZCUNGESV */ info = PLASMA_zcungesv(PlasmaNoTrans, N, NRHS, A2, LDA, B1, LDB, B2, LDB, &ITER); if (info != PLASMA_SUCCESS ) { printf("PLASMA_zcposv is not completed: info = %d\n", info); info_solution = 1; } else { printf(" Solution obtained with %d iterations\n", ITER); /* Check the orthogonality, factorization and the solution */ info_solution = check_solution(N, NRHS, A1, LDA, B1, B2, LDB, eps); } if (info_solution == 0) { printf("***************************************************\n"); printf(" ---- TESTING ZCUNGESV.................... PASSED !\n"); printf("***************************************************\n"); } else { printf("************************************************\n"); printf(" - TESTING ZCUNGESV .. FAILED !\n"); printf("************************************************\n"); } free(A1); free(A2); free(B1); free(B2); return 0; } /*-------------------------------------------------------------- * Check the solution */ static int check_solution(int N, int NRHS, PLASMA_Complex64_t *A1, int LDA, PLASMA_Complex64_t *B1, PLASMA_Complex64_t *B2, int LDB, double eps ) { int info_solution; double Rnorm, Anorm, Xnorm, Bnorm, result; PLASMA_Complex64_t alpha, beta; double *work = (double *)malloc(N*sizeof(double)); alpha = 1.0; beta = -1.0; Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, N, A1, LDA, work); Xnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, NRHS, B2, LDB, work); Bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, NRHS, B1, LDB, work); cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, N, NRHS, N, CBLAS_SADDR(alpha), A1, LDA, B2, LDB, CBLAS_SADDR(beta), B1, LDB); Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, NRHS, B1, LDB, work); if (getenv("PLASMA_TESTING_VERBOSE")) printf( "||A||_oo=%f\n||X||_oo=%f\n||B||_oo=%f\n||A X - B||_oo=%e\n", Anorm, Xnorm, Bnorm, Rnorm ); result = Rnorm / ( (Anorm*Xnorm+Bnorm)*N*eps ) ; printf("============\n"); printf("Checking the Residual of the solution \n"); printf("-- ||Ax-B||_oo/((||A||_oo||x||_oo+||B||_oo).N.eps) = %e \n", result); if ( isnan(Xnorm) || isinf(Xnorm) || isnan(result) || isinf(result) || (result > 60.0) ) { printf("-- The solution is suspicious ! \n"); info_solution = 1; } else{ printf("-- The solution is CORRECT ! \n"); info_solution = 0; } free(work); return info_solution; }
{ "alphanum_fraction": 0.5545706371, "avg_line_length": 33.84375, "ext": "c", "hexsha": "32280598a7d90d2096e1ccc4571e61e420a6e2d0", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "testing/testing_zcungesv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "testing/testing_zcungesv.c", "max_line_length": 145, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "testing/testing_zcungesv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1720, "size": 5415 }
/* specfunc/sinint.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_trig.h> #include <gsl/gsl_sf_expint.h> #include "error.h" #include "chebyshev.h" #include "cheb_eval.c" /*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/ /* based on SLATEC r9sifg.f, W. Fullerton */ /* series for f1 on the interval 2.00000e-02 to 6.25000e-02 with weighted error 2.82e-17 log weighted error 16.55 significant figures required 15.36 decimal places required 17.20 */ static double f1_data[20] = { -0.1191081969051363610, -0.0247823144996236248, 0.0011910281453357821, -0.0000927027714388562, 0.0000093373141568271, -0.0000011058287820557, 0.0000001464772071460, -0.0000000210694496288, 0.0000000032293492367, -0.0000000005206529618, 0.0000000000874878885, -0.0000000000152176187, 0.0000000000027257192, -0.0000000000005007053, 0.0000000000000940241, -0.0000000000000180014, 0.0000000000000035063, -0.0000000000000006935, 0.0000000000000001391, -0.0000000000000000282 }; static cheb_series f1_cs = { f1_data, 19, -1, 1, 10 }; /* series for f2 on the interval 0.00000e+00 to 2.00000e-02 with weighted error 4.32e-17 log weighted error 16.36 significant figures required 14.75 decimal places required 17.10 */ static double f2_data[29] = { -0.0348409253897013234, -0.0166842205677959686, 0.0006752901241237738, -0.0000535066622544701, 0.0000062693421779007, -0.0000009526638801991, 0.0000001745629224251, -0.0000000368795403065, 0.0000000087202677705, -0.0000000022601970392, 0.0000000006324624977, -0.0000000001888911889, 0.0000000000596774674, -0.0000000000198044313, 0.0000000000068641396, -0.0000000000024731020, 0.0000000000009226360, -0.0000000000003552364, 0.0000000000001407606, -0.0000000000000572623, 0.0000000000000238654, -0.0000000000000101714, 0.0000000000000044259, -0.0000000000000019634, 0.0000000000000008868, -0.0000000000000004074, 0.0000000000000001901, -0.0000000000000000900, 0.0000000000000000432 }; static cheb_series f2_cs = { f2_data, 28, -1, 1, 14 }; /* series for g1 on the interval 2.00000e-02 to 6.25000e-02 with weighted error 5.48e-17 log weighted error 16.26 significant figures required 15.47 decimal places required 16.92 */ static double g1_data[21] = { -0.3040578798253495954, -0.0566890984597120588, 0.0039046158173275644, -0.0003746075959202261, 0.0000435431556559844, -0.0000057417294453025, 0.0000008282552104503, -0.0000001278245892595, 0.0000000207978352949, -0.0000000035313205922, 0.0000000006210824236, -0.0000000001125215474, 0.0000000000209088918, -0.0000000000039715832, 0.0000000000007690431, -0.0000000000001514697, 0.0000000000000302892, -0.0000000000000061400, 0.0000000000000012601, -0.0000000000000002615, 0.0000000000000000548 }; static cheb_series g1_cs = { g1_data, 20, -1, 1, 13 }; /* series for g2 on the interval 0.00000e+00 to 2.00000e-02 with weighted error 5.01e-17 log weighted error 16.30 significant figures required 15.12 decimal places required 17.07 */ static double g2_data[34] = { -0.0967329367532432218, -0.0452077907957459871, 0.0028190005352706523, -0.0002899167740759160, 0.0000407444664601121, -0.0000071056382192354, 0.0000014534723163019, -0.0000003364116512503, 0.0000000859774367886, -0.0000000238437656302, 0.0000000070831906340, -0.0000000022318068154, 0.0000000007401087359, -0.0000000002567171162, 0.0000000000926707021, -0.0000000000346693311, 0.0000000000133950573, -0.0000000000053290754, 0.0000000000021775312, -0.0000000000009118621, 0.0000000000003905864, -0.0000000000001708459, 0.0000000000000762015, -0.0000000000000346151, 0.0000000000000159996, -0.0000000000000075213, 0.0000000000000035970, -0.0000000000000017530, 0.0000000000000008738, -0.0000000000000004487, 0.0000000000000002397, -0.0000000000000001347, 0.0000000000000000801, -0.0000000000000000501 }; static cheb_series g2_cs = { g2_data, 33, -1, 1, 20 }; /* x >= 4.0 */ static void fg_asymp(const double x, gsl_sf_result * f, gsl_sf_result * g) { /* xbig = sqrt (1.0/r1mach(3)) xmaxf = exp (amin1(-alog(r1mach(1)), alog(r1mach(2))) - 0.01) xmaxg = 1.0/sqrt(r1mach(1)) xbnd = sqrt(50.0) */ const double xbig = 1.0/GSL_SQRT_DBL_EPSILON; const double xmaxf = 1.0/GSL_DBL_MIN; const double xmaxg = 1.0/GSL_SQRT_DBL_MIN; const double xbnd = 7.07106781187; const double x2 = x*x; if(x <= xbnd) { gsl_sf_result result_c1; gsl_sf_result result_c2; cheb_eval_e(&f1_cs, (1.0/x2-0.04125)/0.02125, &result_c1); cheb_eval_e(&g1_cs, (1.0/x2-0.04125)/0.02125, &result_c2); f->val = (1.0 + result_c1.val)/x; g->val = (1.0 + result_c2.val)/x2; f->err = result_c1.err/x + 2.0 * GSL_DBL_EPSILON * fabs(f->val); g->err = result_c2.err/x2 + 2.0 * GSL_DBL_EPSILON * fabs(g->val); } else if(x <= xbig) { gsl_sf_result result_c1; gsl_sf_result result_c2; cheb_eval_e(&f2_cs, 100.0/x2-1.0, &result_c1); cheb_eval_e(&g2_cs, 100.0/x2-1.0, &result_c2); f->val = (1.0 + result_c1.val)/x; g->val = (1.0 + result_c2.val)/x2; f->err = result_c1.err/x + 2.0 * GSL_DBL_EPSILON * fabs(f->val); g->err = result_c2.err/x2 + 2.0 * GSL_DBL_EPSILON * fabs(g->val); } else { f->val = (x < xmaxf ? 1.0/x : 0.0); g->val = (x < xmaxg ? 1.0/x2 : 0.0); f->err = 2.0 * GSL_DBL_EPSILON * fabs(f->val); g->err = 2.0 * GSL_DBL_EPSILON * fabs(g->val); } return; } /* based on SLATEC si.f, W. Fullerton series for si on the interval 0.00000e+00 to 1.60000e+01 with weighted error 1.22e-17 log weighted error 16.91 significant figures required 16.37 decimal places required 17.45 */ static double si_data[12] = { -0.1315646598184841929, -0.2776578526973601892, 0.0354414054866659180, -0.0025631631447933978, 0.0001162365390497009, -0.0000035904327241606, 0.0000000802342123706, -0.0000000013562997693, 0.0000000000179440722, -0.0000000000001908387, 0.0000000000000016670, -0.0000000000000000122 }; static cheb_series si_cs = { si_data, 11, -1, 1, 9 }; /* series for ci on the interval 0.00000e+00 to 1.60000e+01 with weighted error 1.94e-18 log weighted error 17.71 significant figures required 17.74 decimal places required 18.27 */ static double ci_data[13] = { -0.34004281856055363156, -1.03302166401177456807, 0.19388222659917082877, -0.01918260436019865894, 0.00110789252584784967, -0.00004157234558247209, 0.00000109278524300229, -0.00000002123285954183, 0.00000000031733482164, -0.00000000000376141548, 0.00000000000003622653, -0.00000000000000028912, 0.00000000000000000194 }; static cheb_series ci_cs = { ci_data, 12, -1, 1, 9 }; /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_Si_e(const double x, gsl_sf_result * result) { double ax = fabs(x); /* CHECK_POINTER(result) */ if(ax < GSL_SQRT_DBL_EPSILON) { result->val = x; result->err = 0.0; return GSL_SUCCESS; } else if(ax <= 4.0) { gsl_sf_result result_c; cheb_eval_e(&si_cs, (x*x-8.0)*0.125, &result_c); result->val = x * (0.75 + result_c.val); result->err = ax * result_c.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { /* Note there is no loss of precision * here bcause of the leading constant. */ gsl_sf_result f; gsl_sf_result g; fg_asymp(ax, &f, &g); result->val = 0.5 * M_PI - f.val*cos(ax) - g.val*sin(ax); result->err = f.err + g.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); if(x < 0.0) result->val = -result->val; return GSL_SUCCESS; } } int gsl_sf_Ci_e(const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= 0.0) { DOMAIN_ERROR(result); } else if(x <= 4.0) { const double lx = log(x); const double y = (x*x-8.0)*0.125; gsl_sf_result result_c; cheb_eval_e(&ci_cs, y, &result_c); result->val = lx - 0.5 + result_c.val; result->err = 2.0 * GSL_DBL_EPSILON * (fabs(lx) + 0.5) + result_c.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { gsl_sf_result sin_result; gsl_sf_result cos_result; int stat_sin = gsl_sf_sin_e(x, &sin_result); int stat_cos = gsl_sf_cos_e(x, &cos_result); gsl_sf_result f; gsl_sf_result g; fg_asymp(x, &f, &g); result->val = f.val*sin_result.val - g.val*cos_result.val; result->err = fabs(f.err*sin_result.val); result->err += fabs(g.err*cos_result.val); result->err += fabs(f.val*sin_result.err); result->err += fabs(g.val*cos_result.err); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_sin, stat_cos); } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_Si(const double x) { EVAL_RESULT(gsl_sf_Si_e(x, &result)); } double gsl_sf_Ci(const double x) { EVAL_RESULT(gsl_sf_Ci_e(x, &result)); }
{ "alphanum_fraction": 0.6201202549, "avg_line_length": 27.6501240695, "ext": "c", "hexsha": "76a88ea00fe8b3c2ff143b4dfe467796dc285a8c", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/sinint.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/sinint.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/specfunc/sinint.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 3963, "size": 11143 }
#ifndef __GSL_SORT_H__ #define __GSL_SORT_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <gsl/gsl_sort_long_double.h> #include <gsl/gsl_sort_double.h> #include <gsl/gsl_sort_float.h> #include <gsl/gsl_sort_ulong.h> #include <gsl/gsl_sort_long.h> #include <gsl/gsl_sort_uint.h> #include <gsl/gsl_sort_int.h> #include <gsl/gsl_sort_ushort.h> #include <gsl/gsl_sort_short.h> #include <gsl/gsl_sort_uchar.h> #include <gsl/gsl_sort_char.h> #endif /* __GSL_SORT_H__ */
{ "alphanum_fraction": 0.751497006, "avg_line_length": 21.5483870968, "ext": "h", "hexsha": "2632f67efcabfafdc484c725433c49d633a2f22f", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_sort.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_sort.h", "max_line_length": 48, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_sort.h", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "num_tokens": 201, "size": 668 }
// run with OPENBLAS_NUM_THREADS=1 and OMP_NUM_THREADS=n #include <math.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <cblas.h> #include <omp.h> #include <pthread.h> #define MIN_SIZE 5 #define MAX_SIZE 60 #define NB_SIZE 10 // number of loop for a 1x1 matrix. Lower it if the test is // too slow on you computer. #define NLOOP 2e7 typedef struct { int matrix_size; int n_loop; void (* bench_func)(); void (* blas_func)(); void * (* create_matrix)(int size); } BenchParam; void * s_create_matrix(int size) { float * r = malloc(size * sizeof(double)); int i; for(i = 0; i < size; i++) r[i] = 1e3 * i / size; return r; } void * c_create_matrix(int size) { float * r = malloc(size * 2 * sizeof(double)); int i; for(i = 0; i < 2 * size; i++) r[i] = 1e3 * i / size; return r; } void * z_create_matrix(int size) { double * r = malloc(size * 2 * sizeof(double)); int i; for(i = 0; i < 2 * size; i++) r[i] = 1e3 * i / size; return r; } void * d_create_matrix(int size) { double * r = malloc(size * sizeof(double)); int i; for(i = 0; i < size; i++) r[i] = 1e3 * i / size; return r; } void trmv_bench(BenchParam * param) { int i, n; int size = param->matrix_size; n = param->n_loop / size; int one = 1; void * A = param->create_matrix(size * size); void * y = param->create_matrix(size); for(i = 0; i < n; i++) { param->blas_func("U", "N", "N", &size, A, &size, y, &one); } free(A); free(y); } void gemv_bench(BenchParam * param) { int i, n; int size = param->matrix_size; n = param->n_loop / size; double v = 1.01; int one = 1; void * A = param->create_matrix(size * size); void * y = param->create_matrix(size); for(i = 0; i < n; i++) { param->blas_func("N", &size, &size, &v, A, &size, y, &one, &v, y, &one); } free(A); free(y); } void ger_bench(BenchParam * param) { int i, n; int size = param->matrix_size; n = param->n_loop / size; double v = 1.01; int one = 1; void * A = param->create_matrix(size * size); void * y = param->create_matrix(size); for(i = 0; i < n; i++) { param->blas_func(&size, &size, &v, y, &one, y, &one, A, &size); } free(A); free(y); } #ifndef _WIN32 void * pthread_func_wrapper(void * param) { ((BenchParam *)param)->bench_func(param); pthread_exit(NULL); } #endif #define NB_TESTS 5 void * TESTS[4 * NB_TESTS] = { trmv_bench, ztrmv_, z_create_matrix, "ztrmv", gemv_bench, dgemv_, d_create_matrix, "dgemv", gemv_bench, zgemv_, z_create_matrix, "zgemv", ger_bench, dger_, d_create_matrix, "dger", ger_bench, zgerc_, z_create_matrix, "zgerc", }; inline static double delta_time(struct timespec tick) { struct timespec tock; clock_gettime(CLOCK_MONOTONIC, &tock); return (tock.tv_sec - tick.tv_sec) + (tock.tv_nsec - tick.tv_nsec) / 1e9; } double pthread_bench(BenchParam * param, int nb_threads) { #ifdef _WIN32 return 0; #else BenchParam threaded_param = *param; pthread_t threads[nb_threads]; int t, rc; struct timespec tick; threaded_param.n_loop /= nb_threads; clock_gettime(CLOCK_MONOTONIC, &tick); for(t=0; t<nb_threads; t++){ rc = pthread_create(&threads[t], NULL, pthread_func_wrapper, &threaded_param); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } for(t=0; t<nb_threads; t++){ pthread_join(threads[t], NULL); } return delta_time(tick); #endif } double seq_bench(BenchParam * param) { struct timespec tick; clock_gettime(CLOCK_MONOTONIC, &tick); param->bench_func(param); return delta_time(tick); } double omp_bench(BenchParam * param) { BenchParam threaded_param = *param; struct timespec tick; int t; int nb_threads = omp_get_max_threads(); threaded_param.n_loop /= nb_threads; clock_gettime(CLOCK_MONOTONIC, &tick); #pragma omp parallel for for(t = 0; t < nb_threads; t ++){ param->bench_func(&threaded_param); } return delta_time(tick); } int main(int argc, char * argv[]) { double inc_factor = exp(log((double)MAX_SIZE / MIN_SIZE) / NB_SIZE); BenchParam param; int test_id; printf ("Running on %d threads\n", omp_get_max_threads()); for(test_id = 0; test_id < NB_TESTS; test_id ++) { double size = MIN_SIZE; param.bench_func = TESTS[test_id * 4]; param.blas_func = TESTS[test_id * 4 + 1]; param.create_matrix = TESTS[test_id * 4 + 2]; printf("\nBenchmark of %s\n", (char*)TESTS[test_id * 4 + 3]); param.n_loop = NLOOP; while(size <= MAX_SIZE) { param.matrix_size = (int)(size + 0.5); double seq_time = seq_bench(&param); double omp_time = omp_bench(&param); double pthread_time = pthread_bench(&param, omp_get_max_threads()); printf("matrix size %d, sequential %gs, openmp %gs, speedup %g, " "pthread %gs, speedup %g\n", param.matrix_size, seq_time, omp_time, seq_time / omp_time, pthread_time, seq_time / pthread_time); size *= inc_factor; } } return(0); }
{ "alphanum_fraction": 0.5936744186, "avg_line_length": 27.1464646465, "ext": "c", "hexsha": "c5dcc58810d28a7f1e6793016e89292e4d8dbbfa", "lang": "C", "max_forks_count": 1564, "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:12:54.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-01T01:32:27.000Z", "max_forks_repo_head_hexsha": "9721b57ecfd194f1a4aaa08d715735cd9e8ad8b6", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "drhpc/OpenBLAS", "max_forks_repo_path": "benchmark/smallscaling.c", "max_issues_count": 2067, "max_issues_repo_head_hexsha": "9721b57ecfd194f1a4aaa08d715735cd9e8ad8b6", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:59:43.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-01T03:50:01.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "drhpc/OpenBLAS", "max_issues_repo_path": "benchmark/smallscaling.c", "max_line_length": 86, "max_stars_count": 4392, "max_stars_repo_head_hexsha": "9721b57ecfd194f1a4aaa08d715735cd9e8ad8b6", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "drhpc/OpenBLAS", "max_stars_repo_path": "benchmark/smallscaling.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:14:38.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-02T18:15:45.000Z", "num_tokens": 1591, "size": 5375 }
#include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "cblas.h" void cblas_zaxpy (const int N, const void *alpha, const void *X, const int incX, void *Y, const int incY) { #define BASE double #include "source_axpy_c.h" #undef BASE }
{ "alphanum_fraction": 0.6862745098, "avg_line_length": 19.6153846154, "ext": "c", "hexsha": "d6484014f0b6cedc851aeca71e4b3158456d65ad", "lang": "C", "max_forks_count": 173, "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_path": "gsl-an/cblas/zaxpy.c", "max_issues_count": 208, "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_path": "gsl-an/cblas/zaxpy.c", "max_line_length": 75, "max_stars_count": 460, "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_path": "gsl-an/cblas/zaxpy.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "num_tokens": 79, "size": 255 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <stdint.h> #include <limits.h> // for int limits etc. #include <assert.h> #include <time.h> #include <gsl/gsl_histogram.h> #include <omp.h> #include "main.h" #include "dSFMT-src-2.1/dSFMT.h" //#include "ziggurat/ziggurat.h" //#define STATS #define MULTIPLIER 1000000 // seperates the coordiantes (poor man's hash) int main (int argc, char * argv[]) { int num_particles = DSFMT_N64*4; int num_defects = 1024*4; int box_size = 128; long long nsteps = 1024*1024*2; //omp_init_lock(&omplock); //omp_set_num_threads(1); if (argc == 5) { num_particles = atoi(argv[1]); num_defects = atoi(argv[2]); box_size = atoi(argv[3]); nsteps = atoll(argv[4]); } else { printf("\n# ***** Using default values! *****\n\n"); printf("# usage: rw #particles #defects #box #steps\n"); } // Information: printf("#-------------------- Paramters --------------------\n"); printf("# Particles: %i\n", num_particles); printf("# Box size: %i\n", box_size); printf("# Defects: %i (Density: %.2e)\n", num_defects, (float) num_defects/pow(box_size,3) ); printf("# Steps: %lli\n", nsteps); printf("#---------------------------------------------------\n"); assert( (box_size & (box_size - 1)) == 0 ); // check if box_size is power of two //zigset(1); dsfmt_t dsfmt; int seed = 1; // int num_random = (num_particles < 1024) ? 1024: num_particles; // int *correlation_times = malloc(num_particles * sizeof(int)); // random distribution of correlation times // char *directions = malloc(nsteps*sizeof(char)); // directions int **particles = malloc2D_i(num_particles, 4); // 2d array for particles: x,y,z,mag int **defects = malloc2D_i(num_defects, 3); // 2d array for defect coordinates //int *particle; //int direction; // init random number generator dsfmt_init_gen_rand(&dsfmt, seed); // check if we can create the hashes //assert(box_size < MULTIPLIER); assert(num_defects < pow(box_size,3)); #ifdef STATS // statistics // histogram of diretions gsl_histogram * h = gsl_histogram_alloc (6); gsl_histogram_set_ranges_uniform (h, 0, 6); // histogram of visits gsl_histogram * hvisits = gsl_histogram_alloc (10000); gsl_histogram_set_ranges_uniform (hvisits, 0, 10000); // gsl histogram seems not to be thread safe, allow only 1 thread omp_set_num_threads(1); #endif // Start simulation // distribute particles from 0 to +box_size for (int j = 0; j < 3; j++) { for (int i=0 ;i < num_particles; i++) { particles[i][j] = (int) (dsfmt_genrand_close_open(&dsfmt)*box_size); } } // distribute defects from 0 to +box_size for (int j = 0; j < 3; j++) { for (int i=0 ; i < num_defects; i++) { int val = (int) (dsfmt_genrand_close_open(&dsfmt)*box_size); defects[i][j] = val; } } // METHOD 1: now create a hashed list to find them later // This will be a fallback to METHOD 2, in case memory is not enough int64_t *hash_list = malloc( num_defects*sizeof(int64_t) ); for (int i = 0; i < num_defects; i++) { hash_list[i] = hash(defects[i][0],defects[i][1],defects[i][2]); } qsort(hash_list, num_defects, sizeof(int64_t), int64_cmp); // METHOD 2: create lookup table for x -> lookup table for y -> lookup table for z // The smart thing is that the pointers are NULL if there is no defect in the corresponding slab, // so only the z coordinates are really arrays // // If I need more space one could use the chars as bit fields, // One needs to calculate the offset (or index of char) to get to the proper group though. // get offset: offset = coord/sizeof(char) oder coord >> log2(sizeof(char)) // set bit: array[offset] |= 1 << coord%sizeof(char) // in check_defekt_3d: // check bit: array[offset] & 1 << coord%sizeof(char) > 1 // /* int mem_size_table = 0; // first coordinate (x) will be an array of pointers to an array of pointers char ***lookup_table = malloc(box_size * sizeof(char**)); mem_size_table += box_size * sizeof(char**); // initialize the arrays to NULL pointer for (int i = 0; i < box_size; i++) { lookup_table[i]=NULL; } for (int i = 0; i < num_defects; i++) { int x_index = defects[i][0]; int y_index = defects[i][1]; int z_index = defects[i][2] / sizeof(char); // check if there is already an array at x_index ... if (lookup_table[x_index] == NULL) { // ... it's not! Create an array of pointers for the second coordinate lookup_table[x_index] = malloc(box_size * sizeof(char*)); // malloc second coordinate pointers mem_size_table += box_size * sizeof(char*); for (int i = 0; i < box_size; i++) lookup_table[x_index][i]=NULL; // initialize the second coordiante pointers to NULL } // check if there is already an array at [x_index][y_index] if (lookup_table[x_index][y_index] == NULL) { // check if third coordinate array exists lookup_table[x_index][y_index] = malloc(box_size * sizeof(char)); // malloc third coordinate array mem_size_table += box_size * sizeof(char); for (int i = 0; i < box_size; i++) lookup_table[x_index][y_index][i]=0; // initialize the third array to zero } // set the defect coordinate lookup_table[x_index][y_index][z_index] = 1; } int test_particle[4]; double start = omp_get_wtime(); for (int i = 0; i < 1024*1024*128; i++) { for (int j = 0; j < 3; j++) { test_particle[j] = (int) (dsfmt_genrand_close_open(&dsfmt)*box_size); } check_defect_3d(test_particle, lookup_table, 10); } double stop = omp_get_wtime(); printf("# Time Method 2: %.2fs\n", stop-start); printf("# Lookup table size M1: %10.1fkB %i %i\n", mem_size_table/((float) (1024)), num_defects, box_size); */ // Method 3: Using the scheme above but for x,y,z seperately int ltb_N = (int) ceil( ( (double)box_size ) / sizeof(int)); int xltb[ltb_N]; int yltb[ltb_N]; int zltb[ltb_N]; for (int i = 0; i < ltb_N; i++) { xltb[i]=0; yltb[i]=0; zltb[i]=0; } for (int i = 0; i < num_defects; i++) { int xi = defects[i][0] / sizeof(int); int xbit = defects[i][0] % sizeof(int); //printf("x %i %i %i %i\n",i, defects[i][0], xi, xbit); xltb[xi] |= 1 << xbit; int yi = defects[i][1] / sizeof(int); int ybit = defects[i][1] % sizeof(int); yltb[yi] |= 1 << ybit; //printf("y %i %i %i %i\n",i, defects[i][1], yi, ybit); int zi = defects[i][2] / sizeof(int); int zbit = defects[i][2] % sizeof(int); zltb[zi] |= 1 << zbit; //printf("z %i %i %i %i\n",i, defects[i][2], zi, zbit); } /* start = omp_get_wtime(); for (int i = 0; i < 1024*1024*128; i++) { for (int j = 0; j < 3; j++) { test_particle[j] = (int) (dsfmt_genrand_close_open(&dsfmt)*box_size); } check_defect_ltb(test_particle, xltb, yltb, zltb , 0); } stop = omp_get_wtime(); printf("Time Method 3: %.2fs\n", stop-start); */ printf("# Lookup table size M2: %10.1fkB %i %i\n", 3*ltb_N*sizeof(int) / ((float) (1024)), num_defects, box_size); // check if the lookup table is correct for (int i = 0; i < num_defects; i++) { int x = defects[i][0]; int y = defects[i][1]; int z = defects[i][2]; //printf("Test: %i\n",lookup_table[x][y][z]); /* assert(lookup_table[x][y][z] == 1); // Method 2 */ // Method 3 int xi = x/ sizeof(int); int xbit = x % sizeof(int); assert( (xltb[xi] & (1<<xbit)) != 0 ); int yi = y/ sizeof(int); int ybit = y % sizeof(int); assert( (yltb[yi] & (1<<ybit)) != 0 ); int zi = z/ sizeof(int); int zbit = z % sizeof(int); assert( (zltb[zi] & (1<<zbit)) != 0 ); } /* for (int i = 0; i < num_particles; i++) { if (particles[i][3] == 1) printf("%i\n", i); } */ /******************************* loop *********************************/ // exchange outer with inner loop printf("\n# Starting ...\n"); int *mags = malloc(nsteps * sizeof(int)); // magnetization per step for (int i = 0; i < nsteps; i++) { mags[i] = 0; } // loop over particles double calc_time=0; printf("MinSize: %i\n", DSFMT_N64); double *dir_pool = malloc(DSFMT_N64 * sizeof(double)); #pragma omp parallel for reduction(+:calc_time) firstprivate(dir_pool) for (int i = 0; i < num_particles; i+=DSFMT_N64) { // every thread gets its own RNG dsfmt_t dsfmt; dsfmt_init_gen_rand(&dsfmt, i); /* double *random_numbers_steps = malloc(nsteps * sizeof(double)); // create random numbers for the movements (directions 1..6) dsfmt_fill_array_open_close(&dsfmt, random_numbers_steps, nsteps); // scale the to 0,1,2,3,4,5 (the 6 directions) for (int i=0 ;i < nsteps; i++) { directions[i] = (short) (random_numbers_steps[i]*6); } free(random_numbers_steps); */ // distribution of correlation times, rexp,rnor are NOT thread safe! //for (int i=0 ;i < num_particles; i++) { // correlation_times[i] = (int) rexp()*30; //} // loop over steps for (int step = 0; step < nsteps; step++) { dsfmt_fill_array_open_close(&dsfmt, dir_pool, DSFMT_N64); double start = omp_get_wtime(); // doing batches of particles for (int j = 0; j < DSFMT_N64; j++) { int* particle = particles[i+j]; int direction = dir_pool[j]; //int direction = (int) (dsfmt_genrand_close_open(&dsfmt)*6); // only move particles which have not met defect yet == 0 // or see how often they met a defefct >= 0 if (particle[3] == 0) { // random step move_particle(particle, direction); // obey periodic boundary conditions, i.e. fold back check_pbc(particle, box_size); int tc = 10; // check_defect(particle, tc , hash_list, num_defects); // check_defect_tlb(particle, tc, hash_min, span, defekt_ltb); // check_defect_3d(particle, lookup_table, tc); check_defect_ltb(particle, xltb, yltb, zltb , tc); // ref_check_defect(particle, defects, num_defects); } else { // particle is trapped, decrease the residual waiting time particle[3] -= 1; } #pragma omp atomic mags[step] += particle[3]; //gsl_histogram_increment (hvisits, particle[3]); //if (magnetization == num_particles) main_loop_break = 1; //int tid = omp_get_thread_num(); //printf("Thread %i: %i %i\n", id, i, direction); /*if (step%2000 == 0) { printf("# Step: %8i (MAG: %5i)\r", step, magnetization); fflush(stdout); }*/ //printf("%8i %8i %8i %8i\n",particle[0],particle[1],particle[2],particle[3]); } // end sub particle loop double stop = omp_get_wtime(); calc_time += (stop-start); } // end steps loop /* if (i%32 == 0) { double stop = omp_get_wtime(); printf("# Particle: %8i (%8.3f s) Magnetization: %8i\r",i , (stop-start)/32 , magnetization); fflush(stdout); } */ // open the file we are writing to //#pragma omp critical //printf("# Particle: %8i (%8.3f s) \n",i , stop-start); } // end particle loop printf("Speed: %.2e s/particle \n", calc_time/num_particles); FILE *outFile; char fname[] = "binout.omp"; sprintf(fname, "binout.om%i",0); outFile = fopen(fname, "w"); // use fwrite to write binary data to the file fwrite(mags, sizeof(mags[0]), nsteps, outFile); fclose(outFile); print_array(particles, 10, 3); //print_array(particles, num_particles, 4); free(mags); free2D_i(particles); free2D_i(defects); #ifdef STATS printf("Directions drawn:\n"); gsl_histogram_fprintf (stdout, h, "%g", "%g"); printf("\n"); gsl_histogram_free (h); #endif //omp_destroy_lock(&omplock); return 0; } /***************************************************************************************************************/ /* qsort C-string comparison function */ int cstring_cmp(const void *a, const void *b) { // const char **ia = (const char **)a; // const char **ib = (const char **)b; // return strcmp(*ia, *ib); return strcmp ( (const char*)a, (const char*)b); /* strcmp functions works exactly as expected from comparison function */ } /* asm long long comparison function */ /* int asm64_comp(const void *a, const void *b) { int i=0; __asm__( "mov (%%rdi), %%rdx\n\t" // Subtract low word "sub (%%rsi), %%rdx\n\t" "mov 8(%%rdi), %%rdi\n\t" // Subtract high word "sbb 8(%%rsi), %%rdi\n\t" "sbb %%eax, %%eax\n\t" // %eax = -1 if below, zero otherwise "or %%rdx, %%rdi\n\t" // %rdi is non-zero if comparison is non-zero "neg %%rdi\n\t" // carry flag is 1 if comparison is non-zero "adc %%eax, %%eax\n\t" // Result in %eax "movl %%eax, %0\n\t" : "=a" (i) :"r" (a), "r" (b) ); return i; } */ int int64_cmp(const void *a, const void *b) { const int64_t *x = a, *y = b; if(*x > *y) return 1; else return (*x < *y) ? -1 : 0; } /* qsort int comparison function */ int int_cmp(const void *a, const void *b) { // const int *ia = (const int *)a; // casting pointer types // const int *ib = (const int *)b; //return *ia - *ib; /* integer comparison: returns negative if b > a and positive if a > b */ return ( *(int*)a - *(int*)b ); } static inline int64_t hash(int x, int y, int z) { return (int64_t) MULTIPLIER* (int64_t) MULTIPLIER * (int64_t) x + (int64_t) MULTIPLIER * (int64_t) y + (int64_t) z; } int** malloc2D_i(long nrows, long ncolumns){ int **array = malloc(nrows * sizeof(int *)); array[0] = malloc(nrows * ncolumns * sizeof(int)); if (array[0] == NULL) printf("Could not allocate memory"); for(int i = 1; i < nrows; i++) array[i] = array[0] + i * ncolumns; // set all elements to 0 for (int i = 0; i < nrows; i++) { for (int j = 0; j < ncolumns; j++) { array[i][j] = 0; } } return array; } /* char** malloc2D_char(long nrows, long ncolumns){ char **array = malloc(nrows * sizeof(char *)); array[0] = malloc(nrows * ncolumns * sizeof(char)); if (array[0] == NULL) printf("Could not allocate memory"); for(int i = 1; i < nrows; i++) array[i] = array[0] + i * ncolumns; return array; } */ char** malloc2D_char(long nrows, long ncolumns){ char **array = malloc(nrows * sizeof(char *)); for(int i = 0; i < nrows; i++) array[i] = malloc(ncolumns * sizeof(char)); return array; } void free2D_i(int** array) { //free(&array[0]); free(array); } void print_array(int **array, int nrows, int ncolumns){ for (int i = 0; i < nrows; i++) { for (int j = 0; j < ncolumns-1; j++) { printf("%i ",array[i][j]); } printf("%i\n",array[i][ncolumns-1]); } } void move_particle(int *particle, int direction){ switch (direction) { case 0: particle[0] += 1; break; case 1: particle[0] -= 1; break; case 2: particle[1] += 1; break; case 3: particle[1] -= 1; break; case 4: particle[2] += 1; break; case 5: particle[2] -= 1; break; } // end switch statement } static inline void check_pbc(int* particle, int box_size) { for (int i = 0; i < 3; i++) { // % is NOT the mod operator, but the REMAINDER, it is not working for negative numbers (of course in C only) //particle[i] = particle[i] % box_size + (particle[i]<0?box_size:0); particle[i] &= (box_size - 1); } } /* binary search */ void check_defect(int* particle, int correlation_time, int64_t* hash_list, int num_defects ){ int64_t hash_val; hash_val = hash(particle[0],particle[1],particle[2]); int * ptr; ptr = bsearch( &hash_val, hash_list, num_defects , sizeof(int64_t), int64_cmp); if (ptr != NULL) particle[3] = correlation_time; } /* lookup table 1 */ void check_defect_hash(int* particle, int correlation_time, int64_t hash_list_min, int64_t span, char* defekt_ltb){ int64_t hash_val, offset; hash_val = hash(particle[0],particle[1],particle[2]); offset = hash_val - hash_list_min; if ((offset >= 0) && (offset < span)) { if (defekt_ltb[ offset ] == 1) particle[3] = correlation_time; } } /* check Method 3 */ void check_defect_3d(int* particle, char*** lookup, int correlation_time){ int x = particle[0]; int y = particle[1]; int z = particle[2]; if (lookup[x] != NULL) { if (lookup[x][y] != NULL) { if (lookup[x][y][z] == 1) { particle[3] = correlation_time; } } } } void check_defect_ltb(int* particle, int* x, int* y, int* z, int correlation_time){ int i = particle[0] / sizeof(int); int bit = 1<< particle[0] % sizeof(int); if ( (x[i] & 1 << bit) > 0) { i = particle[1] / sizeof(int); bit = 1<< particle[1] % sizeof(int); if ( (y[i] & 1 << bit) > 0) { i = particle[2] / sizeof(int); bit = 1<< particle[2] % sizeof(int); if ( (z[i] & 1 << bit) > 0) { particle[3] = correlation_time; } } } /* switch ( (x[particle[0] / sizeof(int)]) & (1<< particle[0] % sizeof(int)) ) { case 0: break; default: switch ( (y[particle[1] / sizeof(int)]) & (1<< particle[1] % sizeof(int)) ) { case 0: break; default: switch ( (z[particle[2] / sizeof(int)]) & (1<< particle[2] % sizeof(int)) ) { case 0: break; default: particle[3] = correlation_time; } } }*/ } /* void check_defect(int* particle, int correlation_time, int64_t* hash_list, int num_defects ){ int64_t hash_val; hash_val = hash(particle[0],particle[1],particle[2]); int bsearch = 0; int left = 0; int right = num_defects-1; while (bsearch == 0 && left <= right) { // int middle = (left + right) / 2; // better: avoid integer overflow int middle = left + (right-left) / 2; if (hash_val == hash_list[middle]) { bsearch = 1; particle[3] = correlation_time; } else { if (hash_val < hash_list[middle]) right = middle - 1; if (hash_val > hash_list[middle]) left = middle + 1; } } } */ // REFERENCE METHOD void ref_check_defect(int* particle, int** defect_coords, int num_defects){ int isDefect = 0; for (int i = 0; (i < num_defects) && (isDefect == 0); i++) { for (int j=0; j<3; j++ ){ if (particle[j] != defect_coords[i][j]) { break; // coordinate mismatch, go to next particle (break loop over coordinates) } else { if (j==2) { // x,y and z ccordinate match particle[3] = (int) (rexp()*3) ; // set scalar value isDefect = 1; // break outer loop } } } } } /* void HT_check_defect(int* particle, Fnv64_t* hash_list, int num_defects ){ int* pItem; char hash_string[18]; Fnv64_t hash_val; snprintf(hash_string, sizeof(hash_string), "%5i %5i %5i", particle[0], particle[1], particle[2]); hash_val = fnv_64_str(hash_string, FNV0_64_INIT); pItem = (int*) bsearch (&hash_val, hash_list, num_defects, sizeof (Fnv64_t), fnv64_cmp); if (pItem != 0) particle[3] = 1; // set scalar value } */ /* // now create a hashed list to find them easier (hopefully) Fnv64_t hash_val; Fnv64_t *hash_list = malloc( num_defects*sizeof(Fnv64_t) ); for (int i = 0; i < num_defects; i++) { snprintf(hash_string, sizeof(hash_string), "%5i %5i %5i", defects[i][0], defects[i][1], defects[i][2]); hash_val = fnv_64_str(hash_string, FNV1_64_INIT); hash_list[i] = hash_val; } qsort(hash_list, num_defects,sizeof(Fnv64_t), fnv64_cmp); */ /* mit chars char **hash_list = malloc2D_char(num_defects, 18); //char hash_list[20][18]; for (int i = 0; i < num_defects; i++) { snprintf(hash_string, sizeof(hash_string), "%5i %5i %5i", defects[i][0], defects[i][1], defects[i][2]); hash_list[i] = hash_string; printf("%03i %s\n",i, hash_list[i]); } printf("Sorted\n"); qsort(hash_list, num_defects, sizeof(hash_list[0]), cstring_cmp);//cmpstring_up); */
{ "alphanum_fraction": 0.6133305841, "avg_line_length": 28.1552975327, "ext": "c", "hexsha": "f24d2e60b714cea428f0f33c9ea703d49730f4e3", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "199ef6bb3afe12f9b509061d867c7304a864fccd", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "mrosenstihl/projects", "max_forks_repo_path": "RW/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "199ef6bb3afe12f9b509061d867c7304a864fccd", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "mrosenstihl/projects", "max_issues_repo_path": "RW/main.c", "max_line_length": 117, "max_stars_count": 1, "max_stars_repo_head_hexsha": "199ef6bb3afe12f9b509061d867c7304a864fccd", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "mrosenstihl/projects", "max_stars_repo_path": "RW/main.c", "max_stars_repo_stars_event_max_datetime": "2016-10-03T13:02:56.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-03T13:02:56.000Z", "num_tokens": 6312, "size": 19399 }
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /* * * * Filename: hamil.c * * Description: Create an hamiltonian generator in Bloch form, from a given * vector omega * * Version: 1.0 * Created: 03/05/2014 14:16:00 * Revision: none * License: BSD * * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it * Organization: Università degli Studi di Trieste * * */ #include "funcs.h" #include <gsl/gsl_matrix.h> /* * FUNCTION * Name: ham_gen * Description: * */ int ham_gen ( gsl_matrix* h, const double* o ) { gsl_matrix_set (h, 1, 2, o[3] ) ; gsl_matrix_set (h, 1, 3, -o[2] ) ; gsl_matrix_set (h, 2, 1, -o[3] ) ; gsl_matrix_set (h, 2, 3, o[1] ) ; gsl_matrix_set (h, 3, 1, o[2] ) ; gsl_matrix_set (h, 3, 2, -o[1] ) ; /* Multiplies times -4 to obtain the Bloch matrix */ gsl_matrix_scale ( h, -4 ) ; return 0; } /* ----- end of function ham_gen ----- */
{ "alphanum_fraction": 0.6861158433, "avg_line_length": 33.0704225352, "ext": "c", "hexsha": "6b628b34998e5a42fd14206f93a720870b7eb9f2", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_path": "hamil.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_path": "hamil.c", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_path": "hamil.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 630, "size": 2348 }
#ifndef __GSLEXTRA_H__ #define __GSLEXTRA_H__ #include <iostream> #include <math.h> #include <stdio.h> #include <string.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_math.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_poly.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_sort_vector.h> typedef struct gsl_quad_tensor { int i; int j; int k; int l; gsl_matrix *** element; }gsl_quad_tensor; gsl_quad_tensor * gsl_quad_tensor_alloc(int i, int j, int k, int l); gsl_quad_tensor * gsl_quad_tensor_calloc(int i,int j, int k, int l); void gsl_quad_tensor_free(gsl_quad_tensor * q); double gsl_quad_tensor_get(gsl_quad_tensor * q, int i, int j, int k, int l); void gsl_quad_tensor_get_matrix(gsl_matrix * m, gsl_quad_tensor * q, int i, int j); void gsl_quad_tensor_set(gsl_quad_tensor * q, int i, int j, int k, int l, double x); void gsl_quad_tensor_set_matrix(gsl_quad_tensor * q, int i, int j, const gsl_matrix * m); void gsl_quad_tensor_add(gsl_quad_tensor * A, gsl_quad_tensor * b); void gsl_quad_tensor_sub(gsl_quad_tensor * A, gsl_quad_tensor * b); void gsl_quad_tensor_scale(gsl_quad_tensor * q, double x); void gsl_vector_complex_convert(gsl_vector * source, gsl_vector_complex * target, int length); void gsl_matrix_complex_convert(gsl_matrix * source, gsl_matrix_complex * target, int rows, int columns); void gsl_vector_complex_extract(gsl_vector_complex * source, gsl_vector * real, gsl_vector * imag, int length); void gsl_matrix_complex_extract(gsl_vector_complex * source, gsl_matrix * real,gsl_matrix * imag, int rows, int columns); void gsl_vector_complex_combine(gsl_vector * real, gsl_vector * imag, gsl_vector_complex * target); void gsl_matrix_complex_combine(gsl_matrix * real,gsl_matrix * imag, gsl_matrix_complex * target); void gsl_matrix_diag(gsl_matrix * target, gsl_vector * diag, int length); void gsl_matrix_complex_diag(gsl_matrix_complex * target, gsl_vector_complex * diag, int length); void gsl_matrix_mul(gsl_matrix * A, gsl_matrix *B, gsl_matrix * Result,int Acolumn,int Arow,int Bcolumn); void gsl_matrix_complex_mul(gsl_matrix_complex * A, gsl_matrix_complex *B, gsl_matrix_complex * Result,int Acolumn,int Arow,int Bcolumn); double gsl_vector_inner_product(gsl_vector * A, gsl_vector * B,int length); gsl_complex gsl_vector_complex_product(gsl_vector_complex * A, gsl_vector_complex * B, int length); gsl_complex gsl_vector_complex_inner_product(gsl_vector_complex * A, gsl_vector_complex * B, int length); void gsl_vector_transform(gsl_vector * vec,gsl_matrix * trf,int length); void gsl_vector_complex_transform(gsl_vector_complex * vec, gsl_matrix_complex * trf,int length); void gsl_matrix_unitmatrix(gsl_matrix * m,int length); void gsl_matrix_complex_unitmatrix(gsl_matrix_complex * m,int length); void gsl_vector_complex_conjugate(gsl_vector_complex * v, int length); void gsl_matrix_complex_conjugate(gsl_matrix_complex * m, int rows, int columns); void gsl_matrix_square_root(gsl_matrix * dest, gsl_matrix * src, int length); void gsl_matrix_inverse_square_root(gsl_matrix* dest, gsl_matrix * src, int length); void gsl_eigen_Lowdin_diag(gsl_matrix * m, gsl_matrix * S, gsl_vector * eigen, gsl_matrix * eigenvec, int length); void gsl_matrix_normalize(gsl_matrix * coef,int length, int columns); void gsl_matrix_flip(gsl_matrix * dest,int height,int width); #endif
{ "alphanum_fraction": 0.7906127038, "avg_line_length": 42.3571428571, "ext": "h", "hexsha": "eb404d7654c27b204c73acf9d7a808e653ff237d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "daddeb4b81bd93cd5450b1a172c8653dbbfc26d6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Walter-Feng/Overlap", "max_forks_repo_path": "include/gslextra.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "daddeb4b81bd93cd5450b1a172c8653dbbfc26d6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Walter-Feng/Overlap", "max_issues_repo_path": "include/gslextra.h", "max_line_length": 137, "max_stars_count": null, "max_stars_repo_head_hexsha": "daddeb4b81bd93cd5450b1a172c8653dbbfc26d6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Walter-Feng/Overlap", "max_stars_repo_path": "include/gslextra.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 908, "size": 3558 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_wavelet.h> #include <gsl/gsl_math.h> int main (int argc, char **argv) { int i, j, k, n = 256, nc = 20; double *data = malloc (n * sizeof (double)); double *abscoeff = malloc (n * sizeof (double)); size_t *p = malloc (n * sizeof (size_t)); FILE * f; gsl_wavelet *w; gsl_wavelet_workspace *work; w = gsl_wavelet_alloc (gsl_wavelet_daubechies, 4); work = gsl_wavelet_workspace_alloc (n); f = fopen (argv[1], "r"); for (i = 0; i < n; i++) { fscanf (f, "%lg", &data[i]); } fclose (f); gsl_wavelet_transform_forward (w, data, 1, n, work); for (i = 0; i < n; i++) { abscoeff[i] = fabs (data[i]); printf ("abscoeff[%d] = %g\n", i, abscoeff[i]); } printf ("(-1,0) = %g\n\n", abscoeff[0]); i = 1; for (j = 0; j < 8; j++) { for (k = 0; k < gsl_pow_int(2, j); k++) { printf ("(%d,%d) = %g\n", j, k, abscoeff[i]); i++; } printf("\n"); } /* ************** */ j = 0; for (i = 0; i < n; ++i) j += abscoeff[i]; for (i = 0; i < n; ++i) abscoeff[i] /= j; /* ************** */ gsl_sort_index (p, abscoeff, 1, n); for (i = 0; (i + nc) < n; i++) { printf ("p[%d] = %ld\n", i, p[i]); data[p[i]] = 0; } gsl_wavelet_transform_inverse (w, data, 1, n, work); for (i = 0; i < n; i++) { printf ("%g\n", data[i]); } gsl_wavelet_free (w); gsl_wavelet_workspace_free (work); free (data); free (abscoeff); free (p); return 0; }
{ "alphanum_fraction": 0.4131832797, "avg_line_length": 23.325, "ext": "c", "hexsha": "c698e7a8b7d86e724a5fe7b5db4be1677bb1f77b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "a1ae04c13a2209dee013284358d2d987bb0fb4fc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "klaricmn/snippets", "max_forks_repo_path": "gsl_wavelet/dwt.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "a1ae04c13a2209dee013284358d2d987bb0fb4fc", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "klaricmn/snippets", "max_issues_repo_path": "gsl_wavelet/dwt.c", "max_line_length": 59, "max_stars_count": null, "max_stars_repo_head_hexsha": "a1ae04c13a2209dee013284358d2d987bb0fb4fc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "klaricmn/snippets", "max_stars_repo_path": "gsl_wavelet/dwt.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 603, "size": 1866 }
#pragma once #include <gsl\gsl> #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include "DrawableGameComponent.h" #include "MatrixHelper.h" namespace Library { class Mesh; } namespace Rendering { class TexturedModelDemo final : public Library::DrawableGameComponent { public: TexturedModelDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); bool AnimationEnabled() const; void SetAnimationEnabled(bool enabled); virtual void Initialize() override; virtual void Update(const Library::GameTime& gameTime) override; virtual void Draw(const Library::GameTime& gameTime) override; private: struct CBufferPerObject { DirectX::XMFLOAT4X4 WorldViewProjection{ Library::MatrixHelper::Identity }; }; void CreateVertexBuffer(const Library::Mesh& mesh, gsl::not_null<ID3D11Buffer**> vertexBuffer) const; inline static const float RotationRate{ DirectX::XM_PI }; DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity }; CBufferPerObject mCBufferPerObject; winrt::com_ptr<ID3D11VertexShader> mVertexShader; winrt::com_ptr<ID3D11PixelShader> mPixelShader; winrt::com_ptr<ID3D11InputLayout> mInputLayout; winrt::com_ptr<ID3D11Buffer> mVertexBuffer; winrt::com_ptr<ID3D11Buffer> mIndexBuffer; winrt::com_ptr<ID3D11Buffer> mConstantBuffer; winrt::com_ptr<ID3D11ShaderResourceView> mColorTexture; std::uint32_t mIndexCount{ 0 }; float mRotationAngle{ 0.0f }; bool mAnimationEnabled{ true }; bool mUpdateConstantBuffer{ true }; }; }
{ "alphanum_fraction": 0.7732634338, "avg_line_length": 28.7924528302, "ext": "h", "hexsha": "680064e77a222a9f0b5362b0e2fd89f3e937876f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_path": "source/2.2_Textured_Model/TexturedModelDemo.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_path": "source/2.2_Textured_Model/TexturedModelDemo.h", "max_line_length": 103, "max_stars_count": null, "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_path": "source/2.2_Textured_Model/TexturedModelDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 415, "size": 1526 }
#ifndef MSNHINFERENCECFG_H #define MSNHINFERENCECFG_H #include <stdint.h> #include <float.h> #include <string> #include <vector> #include <chrono> #include "Msnhnet/utils/MsnhException.h" #include "Msnhnet/config/MsnhnetMacro.h" #include <math.h> #include <string.h> #ifdef USE_OMP #include <omp.h> #endif #ifdef USE_NEON #include <arm_neon.h> #endif #ifdef USE_OPEN_BLAS #include <cblas.h> #endif #ifdef USE_OPENGL #include <Msnhnet/config/MsnhnetOpenGL.h> #endif #ifndef OMP_THREAD #define OMP_THREAD omp_get_max_threads() #endif #define CUDA_THREADS 512 #define MIN_OMP_DATA 10000 #define MSNHNET_VERSION 1200 #define EFFCIENT_ALIGN 16 enum ActivationType { LOGISTIC, RELU, RELU6, RELIE, RAMP, TANH, PRELU, PLSE, LEAKY, ELU, LOGGY, STAIR, HARDTAN, LHTAN, SOFT_PLUS, SELU, SWISH, HARD_SWISH, MISH, NORM_CHAN, NORM_CHAN_SOFTMAX, NORM_CHAN_SOFTMAX_MAXVAL, NONE }; enum LayerType { CONVOLUTIONAL, DECONVOLUTIONAL, CONNECTED, MAXPOOL, LOCAL_AVGPOOL, GLOBAL_AVGPOOL, SOFTMAX, CROP, ROUTE, VARIABLE_OP, NORMALIZATION, AVGPOOL, ACTIVE, BATCHNORM, NETWORK, YOLO, YOLO_OUT, GAUSSIAN_YOLO, UPSAMPLE, L2NORM, EMPTY, VIEW, PERMUTE, PIXEL_SHUFFLE, SLICE, REDUCTION, CONFIG, RES_BLOCK, RES_2_BLOCK, CONCAT_BLOCK, ADD_BLOCK, PADDING }; enum Arithmetic { ARITH_ADD = 0, ARITH_SUB, ARITH_SUB_INV, ARITH_MUL, ARITH_DIV, ARITH_DIV_INV }; enum Scientific { SCI_ABS=0, SCI_ACOS, SCI_ASIN, SCI_ATAN, SCI_COS, SCI_COSH, SCI_SIN, SCI_SINH, SCI_TAN, SCI_TANH, SCI_EXP, SCI_POW, SCI_LOG, SCI_LOG10, SCI_SQRT }; enum ReductionType { REDUCTION_SUM, REDUCTION_MEAN }; enum WeightsType { NO_WEIGHTS, PER_FEATURE, PER_CHANNEL }; enum WeightsNorm { NO_NORM, RELU_NORM, SOFTMAX_NORM }; #endif
{ "alphanum_fraction": 0.6040515654, "avg_line_length": 14.0129032258, "ext": "h", "hexsha": "ec52943320313d83be82f9cdf607d8fa93cb0b46", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "38f8a83146c487d0e2b6053c13ddc584f7969994", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zh794390558/Msnhnet", "max_forks_repo_path": "include/Msnhnet/config/MsnhnetCfg.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "38f8a83146c487d0e2b6053c13ddc584f7969994", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zh794390558/Msnhnet", "max_issues_repo_path": "include/Msnhnet/config/MsnhnetCfg.h", "max_line_length": 42, "max_stars_count": null, "max_stars_repo_head_hexsha": "38f8a83146c487d0e2b6053c13ddc584f7969994", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zh794390558/Msnhnet", "max_stars_repo_path": "include/Msnhnet/config/MsnhnetCfg.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 641, "size": 2172 }
#define PyGSL_NUMERIC #define PyGSL_NUMARRAY #include "numeric_numarray.h" #include <gsl/gsl_errno.h> #include <pygsl/general_helpers.h> static int cp_numeric_ptrs(void) { return GSL_SUCCESS; } static int cp_numarray_ptrs(void) { return GSL_SUCCESS; } void initnumx(void) { init_pygsl(); cp_numeric_ptrs(); cp_numarray_ptrs(); }
{ "alphanum_fraction": 0.7234636872, "avg_line_length": 13.2592592593, "ext": "c", "hexsha": "5ff99b5d3ea61a7da568496478e32d7836d25872", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/numeric_numarray.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/numeric_numarray.c", "max_line_length": 34, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/numeric_numarray.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 95, "size": 358 }
#ifndef LIBTENSOR_CBLAS_H_H #define LIBTENSOR_CBLAS_H_H #ifdef USE_CBLAS extern "C" { // Fixes older cblas.h versions without extern "C" #include <cblas.h> } #endif // USE_CBLAS #ifdef USE_GSL #include <gsl/gsl_cblas.h> #endif // USE_GSL #endif // LIBTENSOR_CBLAS_H_H
{ "alphanum_fraction": 0.7527675277, "avg_line_length": 18.0666666667, "ext": "h", "hexsha": "5320c3e89bbfe40e017259da7cc17e71e73f1935", "lang": "C", "max_forks_count": 12, "max_forks_repo_forks_event_max_datetime": "2021-02-24T17:35:21.000Z", "max_forks_repo_forks_event_min_datetime": "2016-05-19T18:09:38.000Z", "max_forks_repo_head_hexsha": "f18e0e33c6c4512e4ea1dde31ed8d74fe536ed24", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "pjknowles/libtensor", "max_forks_repo_path": "libtensor/linalg/cblas/cblas_h.h", "max_issues_count": 5, "max_issues_repo_head_hexsha": "f18e0e33c6c4512e4ea1dde31ed8d74fe536ed24", "max_issues_repo_issues_event_max_datetime": "2020-12-07T08:27:20.000Z", "max_issues_repo_issues_event_min_datetime": "2016-06-14T15:54:11.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "pjknowles/libtensor", "max_issues_repo_path": "libtensor/linalg/cblas/cblas_h.h", "max_line_length": 63, "max_stars_count": 33, "max_stars_repo_head_hexsha": "f18e0e33c6c4512e4ea1dde31ed8d74fe536ed24", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "pjknowles/libtensor", "max_stars_repo_path": "libtensor/linalg/cblas/cblas_h.h", "max_stars_repo_stars_event_max_datetime": "2021-11-17T01:23:11.000Z", "max_stars_repo_stars_event_min_datetime": "2016-02-08T06:05:17.000Z", "num_tokens": 89, "size": 271 }
#ifndef _B_SYSTEM_H_ #define _B_SYSTEM_H_ #include <iostream> #include <vector> using namespace std; #include "Ode.h" #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> class B_system{ public: B_system(double ini_vx_pass, double ini_vy_pass, double ini_xx_pass, double ini_xy_pass, double t_start_pass, double t_end_pass); ~B_system(); void solve(); //solve the ODE and do the interpolation double vx(double t_now); //return velocity in x direction at t_now double vy(double t_now); //return velocity in y direction at t_now double xx(double t_now); //return location in x direction at t_now double xy(double t_now); //return location in y direction at t_now private: double ini_vx; //initial velocity in x direction double ini_vy; //initial velocity in x direction double ini_xx; //initial location in x direction double ini_xy; //initial location in x direction double t_start; //the start time double t_end; //the end time int N = 1000; //number of dots used in solving ODE ODE ode; //the initinization of the ODE class see the B_system constructor vector<double> ti_ode; //this vector stores all vector<double> vx_ode; //this vector stores all velocity in x dirction solved from ODE vector<double> vy_ode; //this vector stores all velocity in y dirction solved from ODE gsl_interp_accel *vx_acc; //workspace for interpolation loop up gsl_interp_accel *vy_acc; //workspace for interpolation loop up gsl_spline *vx_spline; //workspace for interpolation interface gsl_spline *vy_spline; //workspace for interpolation interface }; #endif
{ "alphanum_fraction": 0.6663013699, "avg_line_length": 40.5555555556, "ext": "h", "hexsha": "05f9b51401199e3d844854f6868c8e085005df69", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0614bf9813e94fa8983a03b6cc2edcd7258a8fda", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "54wedge/Electron_in_Magnetic_Field", "max_forks_repo_path": "B_system.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0614bf9813e94fa8983a03b6cc2edcd7258a8fda", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "54wedge/Electron_in_Magnetic_Field", "max_issues_repo_path": "B_system.h", "max_line_length": 98, "max_stars_count": null, "max_stars_repo_head_hexsha": "0614bf9813e94fa8983a03b6cc2edcd7258a8fda", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "54wedge/Electron_in_Magnetic_Field", "max_stars_repo_path": "B_system.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 439, "size": 1825 }
#pragma once #include <gsl\gsl> #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include "DrawableGameComponent.h" #include "MatrixHelper.h" #include "PointLight.h" namespace Rendering { class EnvironmentMappingMaterial; class EnvironmentMappingDemo final : public Library::DrawableGameComponent { public: EnvironmentMappingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); EnvironmentMappingDemo(const EnvironmentMappingDemo&) = delete; EnvironmentMappingDemo(EnvironmentMappingDemo&&) = default; EnvironmentMappingDemo& operator=(const EnvironmentMappingDemo&) = default; EnvironmentMappingDemo& operator=(EnvironmentMappingDemo&&) = default; ~EnvironmentMappingDemo(); float AmbientLightIntensity() const; void SetAmbientLightIntensity(float intensity); float EnvironmentIntensity() const; void SetEnvironmentIntensity(float intensity); float ReflectionAmount() const; void SetReflectionAmount(float amount); virtual void Initialize() override; virtual void Draw(const Library::GameTime& gameTime) override; private: inline static const float RotationRate{ DirectX::XM_PI }; std::shared_ptr<EnvironmentMappingMaterial> mMaterial; DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity }; winrt::com_ptr<ID3D11Buffer> mVertexBuffer; winrt::com_ptr<ID3D11Buffer> mIndexBuffer; std::uint32_t mIndexCount{ 0 }; bool mUpdateMaterial{ true }; }; }
{ "alphanum_fraction": 0.7866022099, "avg_line_length": 31.4782608696, "ext": "h", "hexsha": "db8194d46f1899ba13ad81ae77e27c5378efa918", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_path": "source/5.2_Environment_Mapping/EnvironmentMappingDemo.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_path": "source/5.2_Environment_Mapping/EnvironmentMappingDemo.h", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_path": "source/5.2_Environment_Mapping/EnvironmentMappingDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 336, "size": 1448 }
/* * accelerate_includes.h * * Created on: Sep 29, 2014 * Author: Tama */ #ifndef ACCELERATE_INCLUDES_H_ #define ACCELERATE_INCLUDES_H_ #ifdef __linux__ /*LINUX IMPLEMENTATION*/ /*the libraries: *liblapacke.a *liblapack.a *libcblas.a *librefblas.a are supposed to be in some standard place*/ //!!! The constant MKL_ENABLED must be defined at compile time #ifdef CUDA_ENABLED #include <cuda.h> #include <cuda_runtime_api.h> #include <cublas.h> #include <cula_lapack.h> #include <cula_lapack_device.h> #include <curand.h> #endif #ifdef MKL_ENABLED //#include <mkl_lapacke.h> #include <mkl_cblas.h> #include <mkl.h> //#include <lapacke_mangling.h> #else #include "lapacke.h" #include "cblas.h" //#include <lapacke.h> //#include <cblas.h> //#include <lapacke_mangling.h> #endif typedef lapack_int integer; typedef float __lpkreal; typedef double __lpkdoublereal; typedef lapack_complex_float __lpkcomplex; typedef lapack_complex_double __lpkdoublecomplex; template <typename T> struct constants{ // const __lpkcomplex complex_one ={1.f,0.f}; // const __lpkcomplex complex_zero = {0.f,0.f}; // const __lpkreal real_one = 1.f; // const __lpkreal real_zero = 0.f; // const __lpkreal typed_one = 1.f; // const __lpkreal typed_zero = 0.f; // const __lpkreal typed_mone = -1.f; }; template <> struct constants<__lpkreal>{ const __lpkcomplex complex_one ={1.f,0.f}; const __lpkcomplex complex_zero = {0.f,0.f}; const __lpkreal real_one = 1.f; const __lpkreal real_zero = 0.f; const __lpkreal typed_one = 1.f; const __lpkreal typed_zero = 0.f; const __lpkreal typed_mone = -1.f; const char typeCheck = 's'; }; template <> struct constants<__lpkdoublereal>{ const __lpkdoublecomplex complex_one ={1.,0.}; const __lpkdoublecomplex complex_zero = {0.,0.}; const __lpkdoublereal real_one = 1.; const __lpkdoublereal real_zero = 0.; const __lpkdoublereal typed_one = 1.; const __lpkdoublereal typed_zero = 0.; const __lpkdoublereal typed_mone = -1.; const char typeCheck = 'd'; }; template <> struct constants<__lpkcomplex>{ const __lpkcomplex complex_one ={1.f,0.f}; const __lpkcomplex complex_zero = {0.f,0.f}; const __lpkreal real_one = 1.f; const __lpkreal real_zero = 0.f; const __lpkcomplex typed_one = {1.f,0.f}; const __lpkcomplex typed_zero = {0.f,0.f}; const __lpkcomplex typed_mone = {-1.f,0.f}; const char typeCheck = 'c'; }; template <> struct constants<__lpkdoublecomplex>{ const __lpkdoublecomplex complex_one ={1.,0.}; const __lpkdoublecomplex complex_zero = {0.,0.}; const __lpkdoublereal real_one = 1.; const __lpkdoublereal real_zero = 0.; const __lpkdoublecomplex typed_one = {1.,0.}; const __lpkdoublecomplex typed_zero = {0.,0.}; const __lpkdoublecomplex typed_mone = {-1.,0.}; const char typeCheck = 'z'; }; //#ifdef SINGLEPREC //typedef float lpkreal; //typedef lapack_complex_float lpkcomplex; //const lpkcomplex complex_one = {1.f,0.f}; //const lpkcomplex complex_zero = {0.f,0.f}; //const lpkreal real_one = 1.0f; //const lpkreal real_zero = 0.0f; ////Real Norm 2 single prec //#define NORM2REAL cblas_snrm2 // //#ifdef REAL ////SINGLE PREC REAL //const lpkreal typed_one = 1.0f; //const lpkreal typed_zero = 0.0f; //const lpkreal typed_mone = -1.0f; //#define GEQRF_ sgeqrf_ //#define UNGQR_ sungqr_ //#define GEMM cblas_sgemm //#define AXPY cblas_saxpy //#define DOT cblas_sdotc //#define COPY cblas_scopy //#define GESVD_ sgesvd_ //#define DAG CblasTrans // //#else // //const lpkcomplex typed_one = {1.0f,0.f}; //const lpkcomplex typed_mone = {-1.0f,0.f}; //const lpkcomplex typed_zero = {0.0f,0.0f}; ////SINGLE PREC COMPLEX //#define GEQRF_ cgeqrf_ //#define UNGQR_ cungqr_ //#define GEMM cblas_cgemm //#define AXPY cblas_caxpy //#define DOT cblas_cdotc_sub //#define COPY cblas_ccopy //#define GESVD_ cgesvd_ //#define DAG CblasConjTrans //#endif //REAL // // //#else //DOUBLEPREC //typedef double lpkreal; //typedef lapack_complex_double lpkcomplex; //const lpkcomplex complex_one = {1.,0.}; //const lpkcomplex complex_zero = {0.,0.}; //const lpkreal real_one = 1.0; //const lpkreal real_zero = 0.0; // ////Real Norm 2 double prec //#define NORM2REAL cblas_dnrm2 //#ifdef REAL ////DOULBE PREC REAL //const lpkreal typed_one = 1.0; //const lpkreal typed_mone = -1.0; //const lpkreal typed_zero = 0.0; //#define GEQRF_ dgeqrf_ //#define UNGQR_ dungqr_ //#define GEMM cblas_dgemm //#define AXPY cblas_daxpy //#define DOT cblas_ddotc //#define COPY cblas_dcopy //#define GESVD_ dgesvd_ //#define DAG CblasTrans //#else ////DOUBLE PREC COMPLEX //const lpkcomplex typed_one = {1.0,0.}; //const lpkcomplex typed_mone = {-1.0,0.}; //const lpkcomplex typed_zero = {0.0,0.0}; // // //#define GEQRF_ zgeqrf_ //#define UNGQR_ zungqr_ //#define GEMM cblas_zgemm //#define AXPY cblas_zaxpy //#define DOT cblas_zdotc_sub //#define COPY cblas_zcopy //#define GESVD_ zgesvd_ //#define DAG CblasConjTrans //#endif // //#endif //END DOUBLE PREC #endif //LINUX #ifdef __APPLE__ #include "/System/Library/Frameworks/Accelerate.framework/Headers/Accelerate.h" //#include <Accelerate.framework/Headers/Accelerate.h> #include "/System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/Headers/clapack.h" #include "/System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/Headers/cblas.h" /******APPLE IMPLEMENTATION******/ typedef __CLPK_integer integer; typedef __CLPK_real __lpkreal; typedef __CLPK_doublereal __lpkdoublereal; typedef __CLPK_complex __lpkcomplex; typedef __CLPK_doublecomplex __lpkdoublecomplex; template <typename T> struct constants{ // const __lpkcomplex complex_one ={1.f,0.f}; // const __lpkcomplex complex_zero = {0.f,0.f}; // const __lpkreal real_one = 1.f; // const __lpkreal real_zero = 0.f; // const __lpkreal typed_one = 1.f; // const __lpkreal typed_zero = 0.f; // const __lpkreal typed_mone = -1.f; }; template <> struct constants<__lpkreal>{ const __lpkcomplex complex_one ={1.f,0.f}; const __lpkcomplex complex_zero = {0.f,0.f}; const __lpkreal real_one = 1.f; const __lpkreal real_zero = 0.f; const __lpkreal typed_one = 1.f; const __lpkreal typed_zero = 0.f; const __lpkreal typed_mone = -1.f; const char typeCheck = 's'; }; template <> struct constants<__lpkdoublereal>{ const __lpkdoublecomplex complex_one ={1.,0.}; const __lpkdoublecomplex complex_zero = {0.,0.}; const __lpkdoublereal real_one = 1.; const __lpkdoublereal real_zero = 0.; const __lpkdoublereal typed_one = 1.; const __lpkdoublereal typed_zero = 0.; const __lpkdoublereal typed_mone = -1.; const char typeCheck = 'd'; }; template <> struct constants<__lpkcomplex>{ const __lpkcomplex complex_one ={1.f,0.f}; const __lpkcomplex complex_zero = {0.f,0.f}; const __lpkreal real_one = 1.f; const __lpkreal real_zero = 0.f; const __lpkcomplex typed_one = {1.f,0.f}; const __lpkcomplex typed_zero = {0.f,0.f}; const __lpkcomplex typed_mone = {-1.f,0.f}; const char typeCheck = 'c'; }; template <> struct constants<__lpkdoublecomplex>{ const __lpkdoublecomplex complex_one ={1.,0.}; const __lpkdoublecomplex complex_zero = {0.,0.}; const __lpkdoublereal real_one = 1.; const __lpkdoublereal real_zero = 0.; const __lpkdoublecomplex typed_one = {1.,0.}; const __lpkdoublecomplex typed_zero = {0.,0.}; const __lpkdoublecomplex typed_mone = {-1.,0.}; const char typeCheck = 'z'; }; //#ifdef SINGLEPREC //typedef __CLPK_real lpkreal; //typedef __CLPK_complex lpkcomplex; //const lpkcomplex complex_one = {1.f,0.f}; //const lpkcomplex complex_zero = {0.f,0.f}; //const lpkreal real_one = 1.0f; //const lpkreal real_zero = 0.0f; ////Real Norm 2 single prec //#define NORM2REAL cblas_snrm2 // //#ifdef REAL ////SINGLE PREC REAL //const lpkreal typed_one = 1.0f; //const lpkreal typed_zero = 0.0f; //const lpkreal typed_mone = -1.0f; // //#define GEQRF_ sgeqrf_ //#define UNGQR_ sungqr_ //#define GEMM cblas_sgemm //#define AXPY cblas_saxpy //#define DOT cblas_sdotc //#define COPY cblas_scopy //#define GESVD_ sgesvd_ // //#else // //const lpkcomplex typed_one = {1.0f,0.f}; //const lpkcomplex typed_mone = {-1.0f,0.f}; //const lpkcomplex typed_zero = {0.0f,0.0f}; ////SINGLE PREC COMPLEX //#define GEQRF_ cgeqrf_ //#define UNGQR_ cungqr_ //#define GEMM cblas_cgemm //#define AXPY cblas_caxpy //#define DOT cblas_cdotc_sub //#define COPY cblas_ccopy //#define GESVD_ cgesvd_ //#endif //REAL //#else //DOUBLEPREC //typedef __CLPK_doublereal lpkreal; //typedef __CLPK_doublecomplex lpkcomplex; //const lpkcomplex complex_one = {1.,0.}; //const lpkcomplex complex_zero = {0.,0.}; //const lpkreal real_one = 1.0; //const lpkreal real_zero = 0.0; // ////Real Norm 2 double prec ////#define NORM2REAL cblas_dnrm2 ////#ifdef REAL ////DOULBE PREC REAL //template <> //struct constants<lpkreal>{ // const lpkcomplex complex_one ={1.,0.}; // const lpkcomplex complex_zero = {0.,0.}; // const lpkreal real_one = 1.; // const lpkreal real_zero = 0.; // const lpkreal typed_one = 1.; // const lpkreal typed_zero = 0.; // const lpkreal typed_mone = -1.; // const char typeCheck = 'd'; //}; //const lpkreal typed_one = 1.0; //const lpkreal typed_mone = -1.0; //const lpkreal typed_zero = 0.0; //#define GEQRF_ dgeqrf_ //#define UNGQR_ dorgqr_ //#define GEMM cblas_dgemm //#define AXPY cblas_daxpy //#define DOT cblas_ddotc //#define COPY cblas_dcopy //#define GESVD_ dgesvd_ //#else //DOUBLE PREC COMPLEX //Questa struttura dovra` essere modificata alla fine //template<> //struct constants<lpkcomplex>{ // const lpkcomplex complex_one ={1.,0.}; // const lpkcomplex complex_zero = {0.,0.}; // const lpkreal real_one = 1.; // const lpkreal real_zero = 0.; // const lpkcomplex typed_one = {1.,0.}; // const lpkcomplex typed_zero = {0.,0.}; // const lpkcomplex typed_mone = {-1.,0.}; // const char typeCheck = 'z'; //}; //const lpkcomplex typed_one = {1.0,0.}; //const lpkcomplex typed_mone = {-1.0,0.}; //const lpkcomplex typed_zero = {0.0,0.0}; //#define GEQRF_ zgeqrf_ //#define UNGQR_ zungqr_ //#define GEMM cblas_zgemm //#define AXPY cblas_zaxpy //#define DOT cblas_zdotc_sub //#define COPY cblas_zcopy //#define GESVD_ zgesvd_ //#endif //#endif //END DOUBLE PREC #endif //APPLE /******Tama's constants******/ #endif /* ACCELERATE_INCLUDES_H_ */
{ "alphanum_fraction": 0.7246931762, "avg_line_length": 26.1825192802, "ext": "h", "hexsha": "fef9d007218fc2c5de68bc4abe3ab5bfb924057b", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-08-30T08:39:14.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-05T19:42:29.000Z", "max_forks_repo_head_hexsha": "14cc92d4bf13b74afb20f917fc7cc1953ea89b92", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "kindaguy/RRSVD", "max_forks_repo_path": "RRSVD_BL_Release_20150317/RRSVD/Include/accelerate_includes.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "14cc92d4bf13b74afb20f917fc7cc1953ea89b92", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC0-1.0" ], "max_issues_repo_name": "kindaguy/RRSVD", "max_issues_repo_path": "RRSVD_BL_Release_20150317/RRSVD/Include/accelerate_includes.h", "max_line_length": 104, "max_stars_count": 3, "max_stars_repo_head_hexsha": "14cc92d4bf13b74afb20f917fc7cc1953ea89b92", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "kindaguy/RRSVD", "max_stars_repo_path": "RRSVD_BL_Release_20150317/RRSVD/Include/accelerate_includes.h", "max_stars_repo_stars_event_max_datetime": "2021-01-05T19:42:26.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-31T09:57:42.000Z", "num_tokens": 3346, "size": 10185 }
#include <config.h> #include <math.h> #include <gsl/gsl_ntuple.h> #include <gsl/gsl_histogram.h> struct data { double x; double y; double z; }; int sel_func (void *ntuple_data, void *params); double val_func (void *ntuple_data, void *params); int main (void) { struct data ntuple_row; int i; gsl_ntuple *ntuple = gsl_ntuple_open ("test.dat", &ntuple_row, sizeof (ntuple_row)); gsl_histogram *h = gsl_histogram_calloc_uniform (100, 0., 10.); gsl_ntuple_select_fn S; gsl_ntuple_value_fn V; double scale = 1.5; S.function = &sel_func; S.params = &scale; V.function = &val_func; V.params = 0; gsl_ntuple_project (h, ntuple, &V, &S); gsl_histogram_fprintf (stdout, h, "%f", "%f"); gsl_histogram_free (h); gsl_ntuple_close (ntuple); } int sel_func (void *ntuple_data, void *params) { double x, y, z, E, scale; scale = *(double *) params; x = ((struct data *) ntuple_data)->x; y = ((struct data *) ntuple_data)->y; z = ((struct data *) ntuple_data)->z; E = x * x + y * y + z * z; return E / scale > 1; } double val_func (void *ntuple_data, void *params) { double x, y, z; x = ((struct data *) ntuple_data)->x; y = ((struct data *) ntuple_data)->y; z = ((struct data *) ntuple_data)->z; return x * x + y * y + z * z; }
{ "alphanum_fraction": 0.6130728775, "avg_line_length": 18.2328767123, "ext": "c", "hexsha": "a59ef85f3f5a371e3ab5b19903829d8d05ee0948", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/ntuple/demo1.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/ntuple/demo1.c", "max_line_length": 65, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/ntuple/demo1.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 424, "size": 1331 }
#ifndef ALG_LOMV #define ALG_LOMV #include "string.h" #include "assert.h" #include <time.h> #include <stdio.h> #include <stdlib.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_linalg.h> double linf(int d, gsl_vector * a, gsl_vector * b); void psi(int p, int q, gsl_vector * theta, gsl_matrix * B, gsl_matrix * V, gsl_vector * Delta, gsl_vector * x); gsl_vector * ffp(int p, int q, gsl_vector * theta, gsl_matrix * B, gsl_matrix * V, gsl_vector * Delta); gsl_vector * lo_minvar(int p, int q, gsl_matrix * B, gsl_matrix * V, gsl_vector * Delta); double * ffp_C_interface(int p, int q, double* theta, double** B, double** V, double* Delta); double* lo_minvar_C_interface(int p, int q, double**B, double** V, double* Delta); double* psi_C_interface(int p, int q, double**B, double** V, double* Delta); #endif
{ "alphanum_fraction": 0.7059496568, "avg_line_length": 30.1379310345, "ext": "h", "hexsha": "40812b81fb5785008b94a6a17504a5afb3873493", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1ca18ea3f54583bf42ccdb79e0069b4190a0ac0e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "alexbstl/ffp_minvar", "max_forks_repo_path": "include/alg_lomv.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1ca18ea3f54583bf42ccdb79e0069b4190a0ac0e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "alexbstl/ffp_minvar", "max_issues_repo_path": "include/alg_lomv.h", "max_line_length": 111, "max_stars_count": null, "max_stars_repo_head_hexsha": "1ca18ea3f54583bf42ccdb79e0069b4190a0ac0e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "alexbstl/ffp_minvar", "max_stars_repo_path": "include/alg_lomv.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 263, "size": 874 }
/* Copyright (c) 2020 Stijn Hinterding, Utrecht University * This sofware is licensed under the MIT license (see the LICENSE file) */ #ifndef FAKECOMMUNICATOR_H #define FAKECOMMUNICATOR_H #include <phast_gui/interfaces/itimetaggercommunicator.h> #include <gsl/gsl_rng.h> #include <chrono> #include <mutex> class FakeCommunicator : public ITimeTaggerCommunicator { private: gsl_rng* r; double timeunit_seconds; double decayrate_inv_seconds; double pulse_period_seconds; double detection_probability; std::chrono::time_point<std::chrono::high_resolution_clock> prev_time; bool first_run; int64_t last_largest_time; int64_t last_pulse_time; int64_t pulse_period_timeunits; int64_t last_pulse_published; uint64_t sync_counter; uint64_t sync_divider; int64_t chan1_induced_delay; int64_t chan2_induced_delay; std::string descriptor; bool chan0_enabled; bool chan1_enabled; bool chan2_enabled; bool is_running; double sim_speedup_factor; std::mutex m; std::map<chan_id,timestamp> first_times; std::map<chan_id,timestamp> last_times; std::map<chan_id,uint64_t> n_events; int64_t n_emitters; private: void gen_pulses(std::vector<int64_t> *timestamps, std::vector<uint8_t> *channel_IDs, int64_t duration); public: FakeCommunicator(const FakeCommunicator&) = delete; FakeCommunicator& operator=(const FakeCommunicator&) = delete; ~FakeCommunicator() override; FakeCommunicator(double timeunit_seconds, double decayrate_inv_seconds, double pulse_period_seconds, double detection_probability, uint64_t sync_divider=128, int64_t chan1_induced_delay=0, int64_t chan2_induced_delay=0, int64_t n_emitters=1, double sim_speedup_factor=1); void SetSimSpeedupFactor(double value) { std::lock_guard<std::mutex> l(this->m); if (value <= 0.001) value = 0.001; this->sim_speedup_factor = value; } double GetSimSpeedupFactor() const { return this->sim_speedup_factor; } void SetDecayRate(double value) { std::lock_guard<std::mutex> l(this->m); this->decayrate_inv_seconds = value; } int64_t GetNumEmitters() const { return this->n_emitters; } double GetDecayRate() const { return this->decayrate_inv_seconds; } void SetNumEmitters(int64_t value) { std::lock_guard<std::mutex> l(this->m); if (value == 0) value = 1; this->n_emitters = value; } void SetPulsePeriod(double value) { std::lock_guard<std::mutex> l(this->m); this->pulse_period_seconds = value; this->pulse_period_timeunits = this->pulse_period_seconds/this->timeunit_seconds; } double GetPulsePeriod() const { return this->pulse_period_seconds; } void SetDetectionProbability(double value) { std::lock_guard<std::mutex> l(this->m); if (value > 1.0) value = 1.0; if (value < 0.0) value = 0.0; this->detection_probability = value; } double GetDetectionProbability() const { return this->detection_probability; } void SetSyncDivider(uint64_t value) { std::lock_guard<std::mutex> l(this->m); this->sync_divider = value; } virtual uint64_t ReceiveData(std::vector<int64_t>* timestamps, std::vector<uint8_t>* channel_IDs) override; virtual uint64_t GetSyncDivider(chan_id channel_id) override { if (channel_id == 0) return this->sync_divider; return 1; } virtual void DisableChan(uint64_t ID); virtual bool ConnectedToDevice() override { return true; } virtual const std::string& DeviceDescriptor() const override { return this->descriptor; } virtual bool TryToConnect(int64_t) override { return true; } virtual bool DataLossSinceLastCall() override { return false; } virtual double TimeUnit() const override { return this->timeunit_seconds; } virtual bool AnyDeviceAvailable() const override { return true; } virtual bool Disconnect() override { return true; } virtual uint64_t GetNumDevicesConnected() override { return 1; } virtual bool IsRealDevice() const { return false; } }; #endif // FAKECOMMUNICATOR_H
{ "alphanum_fraction": 0.6040268456, "avg_line_length": 23.9853658537, "ext": "h", "hexsha": "ecc53fb11044489c180e147f8cb55d4c39b69173", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "dad4702eb6401c1eba03ad70eff3659292636d30", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "stijnhinterding/phast", "max_forks_repo_path": "fake_timetag_device_plugin/fakecommunicator.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "dad4702eb6401c1eba03ad70eff3659292636d30", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "stijnhinterding/phast", "max_issues_repo_path": "fake_timetag_device_plugin/fakecommunicator.h", "max_line_length": 90, "max_stars_count": null, "max_stars_repo_head_hexsha": "dad4702eb6401c1eba03ad70eff3659292636d30", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "stijnhinterding/phast", "max_stars_repo_path": "fake_timetag_device_plugin/fakecommunicator.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1144, "size": 4917 }
//////////////////////////////////////////// Spin glass phase transition //////////////////////////////////////// /* Phase space of the SK model. Please cite the following paper when you use this code. [Ezaki T, Fonseca dos Reis E, Watanabe T, Sakaki M, Masuda N. Closer to critical resting-state neural dynamics in individuals with higher fluid intelligence. Commun Biol 3:1 (2020).](https://www.nature.com/articles/s42003-020-0774-y) If you find a bug in this code, please contact the authors. Author: Elohim Fonseca dos Reis Date: July 8, 2020 Parameters: ---------- This program maps the SK model phase space using the following parameters that have to be set by the user before compiling: * Total number of spins (N); * Number of time steps to calculate the averages given a fixed configuration of $J_{ij}$ (tdim); * Number of $J_{ij}$ configurations for the configurational average (conf_num); * Number of sweeps in the transient period (thermal); * Array with the mean values of $J_{ij}$ (mu). The user has to set the minimum value (mu_min), maximum value (mu_max) and the step (mu_step). The size of the array with the mean values of $J_{ij}$ is given by 1+(mu_max-mu_min)/mu_step. * Array with the standard deviation values of $J_{ij}$ (sd). The user has to set the minimum value (sd_min), the maximum value (sd_max) and the step (sd_step). The size of the array with the standard deviation values of $J_{ij}$ is given by 1+(max_sd-min_sd)/sd_step. Outputs: ------- The program outputs the following measures: * spin glass susceptibility (Xsg); * uniform susceptibility (Xuni); * spin glass order parameter (q); * magnetization (m); * specific heat (c). The outputs of the program are multiple .txt files, one for each pair of (mu, sd), and each .txt file contains one line with seven values in this order: mu, sd, Xsg, Xuni, q, m, c. For example, if the user sets *n* values for the mu array and *m* values for the sd array, the program outputs *nm* .txt files. The files are named as: file_0_0.txt, file_0_1.txt, ..., file_1_0.txt, file_1_1.txt... The reason for generating multiple .txt files is for parallelizing the program. The program has a built-in naive parallelization for the mu and sd arrays, i.e., after compiling the code, if the user runs the same program on 10 different instances, for example, the total time will decrease 10 times. So the user might be interested in running an array of jobs, each job running the same program for a given set of parameters. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <unistd.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_math.h> #include "mt19937ar.h" // Parameters #define N 264 // Total number of spins #define tdim 10000 // Thermal average dimension size #define conf_num 1000 // Number of interaction configurations #define thermal 10000 // Equilibration sweeps #define mu_min -0.002 // Minimum Average Interaction #define mu_max 0.01 // Maximum Average Interaction #define mu_step 0.0005 // Average interaction step #define sd_min 0 // Minimum interaction standard deviation #define sd_max 0.15 // Maximum interaction standard deviation #define sd_step 0.0075 // Interaction sd step // Matrix Serializations #define SSArr(SS,i,j) SS[ tdim*i + j ] // Spin series array #define JArr(J,i,j) J[ N*i + j ] // Interactions array #define CovArr(var,i,j) var[N*i + j] // Covariance array // Global Variables int *s; // Spins int *SS; // Spin series array (N x T) double *J; // Interactions (Jij) drawn from a gaussian distribution // Functions double randnum(); // Real random number [0,1) void init_randnum(); // Seed of the random number generator void sweep(); // Sweep of the system with N metropolis steps double cov(int *A, int k, int l); // Covariance cov[A(k),A(l)] void elapsed_time(); int main() { ///////////////////////////// Summary ///////////////////////////// printf("\n\nSummary:\n\n"); printf("Number of spins: %d\n", N); printf("Thermal average dimension: %d\n",tdim); printf("Number of configurations: %d\n",conf_num); printf("Equilibration sweeps: %d\n",thermal); printf("Number of parameter values: %d mean(J), %d std(J)", (int)round(((mu_max - mu_min) / mu_step + 1)), (int)round(((sd_max - sd_min) / sd_step + 1))); printf("\n\n"); ///////////////////////////// Model Parameters ///////////////////////////// /* Average interaction array (main function variable) */ int mu_size = (int)round( (mu_max - mu_min) / mu_step + 1); //printf("\n\nmu size: %d\n\n", mu_size); double *mu=malloc(mu_size*sizeof(double)); if(!mu){ printf("Out of memory.1\n"); exit(1); } for(int i=0; i<mu_size; i++){ mu[i] = (mu_min + i*mu_step); //printf("m[%d]=%f\n\n",i,mu[i]); } /* Interaction standard deviation array (main function variable) */ int sd_size = (int)round( (sd_max - sd_min) / sd_step + 1); //printf("\n\nsd size: %d\n\n", sd_size); double *sd=malloc(sd_size*sizeof(double)); if(!sd){ printf("Out of memory.2\n"); exit(1); } for(int i=0; i<sd_size; i++){ sd[i] = (sd_min + i*sd_step); //printf("sd[%d]=%f\n\n",i,sd[i]); } //////////////////////////////// Variables /////////////////////////////// /* Spin array (global) */ s=malloc(N*sizeof(int)); if(!s){ printf("Out of memory.\n"); exit(1); } /* Spin series array (global) */ SS=malloc(N*tdim*sizeof(int)); if(!SS){ printf("Out of memory.\n"); exit(1); } /* Interaction matrix (global) */ J=malloc(N*N*sizeof(double)); if(!J){ printf("Out of memory.\n"); exit(1); } /* Covariance matrix configuration average sum */ double *SumC=calloc(N*N,sizeof(double)); if(!SumC){ printf("Out of memory.\n"); exit(1); } /* Covariance matrix configuration average product sum */ double *ProdC=calloc(N*N,sizeof(double)); if(!ProdC){ printf("Out of memory.\n"); exit(1); } /* Magnetization */ double *m=malloc(mu_size*sd_size*sizeof(double)); if(!m){ printf("Out of memory.\n"); exit(1); } /* SG order parameter */ double *q=malloc(mu_size*sd_size*sizeof(double)); if(!q){ printf("Out of memory.\n"); exit(1); } /* Uniform Susceptibiliy */ double *Xuni=calloc(mu_size*sd_size,sizeof(double)); if(!Xuni){ printf("Out of memory.\n"); exit(1); } /* Spin Glass Susceptibiliy */ double *Xsg=calloc(mu_size*sd_size,sizeof(double)); if(!Xsg){ printf("Out of memory.\n"); exit(1); } /* Specific Heat */ double *c=calloc(mu_size*sd_size,sizeof(double)); if(!c){ printf("Out of memory.\n"); exit(1); } /////////////////////////////// Program /////////////////////////////// /* Initialize mt rng */ init_randnum(); /* Interaction array variables */ const gsl_rng_type * Q; gsl_rng * r; Q = gsl_rng_mt19937; r = gsl_rng_alloc (Q); ////////////////////////////////////////////////////////////////////////////////// /////////////////////////////// AVERAGE LOOP (A) ///////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// for(int A=0; A<mu_size; A++){ ////////////////////////////////////////////////////////////////////////////////// ///////////////////////// STANDARD DEVIATION LOOP (B) //////////////////////////// ////////////////////////////////////////////////////////////////////////////////// for(int B=0; B<sd_size; B++){ // Output file FILE *file; char *fname=malloc(100*sizeof(char)); snprintf(fname,100,"file_%d_%d.txt",A,B); // Check if file exists if( access( fname, F_OK ) != -1 ) { // file exists continue; } // file doesn't exist: perform calculations // Save blank file if((file = fopen(fname,"w"))==NULL){ printf("Cannot open file.\n"); exit(1); } fclose(file); printf("\nfile_%d_%d.txt mu=%f sd=%f",A,B, mu[A], sd[B]); //~~~~~~~~~ Beginning of calculations //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Initial condition for(int i=0; i<N; i++) s[i]=1; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Reset convariance array memset(SumC, 0, N*N*sizeof(*SumC)); memset(ProdC, 0, N*N*sizeof(*ProdC)); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Reset specific heat variables double ProdSumE = 0; double SumProdE = 0; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Configuration Average for(int D=0; D<conf_num; D++){ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~; // Interaction array for(int i=0; i<N; i++){ for(int j=i; j<N; j++){ JArr(J,i,j) = mu[A] + gsl_ran_gaussian_ziggurat(r,sd[B]); JArr(J,j,i) = JArr(J,i,j); JArr(J,i,i) = 0; }} //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Thermalization for(int i=0; i<thermal; i++){ sweep(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Sampling for (int j=0; j<tdim; j++){ sweep(); for (int i=0; i<N; i++){ SSArr(SS,i,j)=s[i]; } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Magnetization and SG order parameter double mag=0; double sgop=0; double aux=0; for(int i=0; i<N; i++){ aux=0; for(int t=0; t<tdim; t++){ aux += SSArr(SS,i,t); } mag += aux; sgop += aux*aux; } m[sd_size*A + B] += mag; q[sd_size*A + B] += sgop; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Covariance Matrix: configuration average sum (SumC) for Xuni and product (ProdC) for Xsg double cov_ij; for(int i=0; i<N; i++){ for(int j=i; j<N; j++){ cov_ij = cov(SS,i,j); CovArr(SumC,i,j) += cov_ij; CovArr(SumC,j,i) = CovArr(SumC,i,j); CovArr(ProdC,i,j) += cov_ij*cov_ij; CovArr(ProdC,j,i) = CovArr(ProdC,i,j); }} //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Specific heat: double sumE=0, sumE2=0, E=0; for(int t=1; t<tdim; t++){ E=0; for(int i=0; i<N; i++){ for(int j=i; j<N; j++){ E -= JArr(J,i,j) * SSArr(SS,i,t) *SSArr(SS,j,t); }} sumE += E; sumE2 += E*E; } ProdSumE += sumE*sumE; SumProdE += sumE2; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ } // End of Configuration Average m[sd_size*A+B] = fabs(m[sd_size*A+B]/(1.0*N*tdim*conf_num)); q[sd_size*A+B] = q[sd_size*A+B]/(1.0*N*tdim*tdim*conf_num); int NN=N*N; for(int i=0; i<NN; i++){ Xuni[sd_size*A+B] += SumC[i]; Xsg[sd_size*A+B] += ProdC[i]; } Xuni[sd_size*A+B] = Xuni[sd_size*A+B]/(1.0*N*conf_num); Xsg[sd_size*A+B] = Xsg[sd_size*A+B]/(1.0*N*conf_num); c[sd_size*A+B] = (SumProdE/(1.0*tdim) - ProdSumE/(1.0*tdim*tdim))/(1.0*N*conf_num); // Save file with results if((file = fopen(fname,"w"))==NULL){ printf("Cannot open file.\n"); exit(1); } fprintf(file,"%f\t%f\t%f\t%f\t%f\t%f\t%f", mu[A], sd[B], Xsg[A*sd_size+B], Xuni[A*sd_size+B], q[A*sd_size+B], m[A*sd_size+B], c[A*sd_size+B]); fclose(file); free(fname); fname = NULL; }///////////////////////////////////////////////////////////////////////////////// ///////////////////////// END OF STANDARD DEVIATION LOOP (B) ///////////////////// ////////////////////////////////////////////////////////////////////////////////// }///////////////////////////////////////////////////////////////////////////////// ////////////////////////////// END OF AVERAGE LOOP (A) ////////////////////////// ////////////////////////////////////////////////////////////////////////////////// // !!!! FREE POINTERS !!!! free(mu); mu=NULL; free(sd); sd=NULL; free(s); s=NULL; free(SS); SS=NULL; free(J); J=NULL; free(m); m=NULL; free(q); q=NULL; free(SumC); SumC=NULL; free(ProdC); ProdC=NULL; free(Xuni); Xuni=NULL; free(Xsg); Xsg=NULL; free(c); c=NULL; gsl_rng_free (r); //-------- END OF THE PROGRAM %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elapsed_time(); return 0; } // FUNCTIONS // /********************************************************************************************* Metropolis algorithm **********************************************************************************************/ void sweep() { int k; double Heff, delta; for(int i=0; i<N; i++) { /* Choose a site at random */ k = N*randnum(); /* Calculate the effective field */ Heff=0; for(int j=0; j<N; j++) Heff += JArr(J,k,j)*s[j]; /* Calculate the change in energy */ delta = s[k]*(Heff); /* Decide whether to flip the spin */ if (delta <= 0){ s[k] = -s[k]; } else if ( randnum() < exp(-2*delta) ){ s[k] = -s[k]; } } } /********************************************************************************************* Covariance: function to calculate correlations **********************************************************************************************/ double cov(int *A, int k, int l) { long long int P=0, Qk=0, Ql=0; double R=0; for(int t=0; t<tdim; t++){ P += SSArr(A,k,t) * SSArr(A,l,t); Qk += SSArr(A,k,t); Ql += SSArr(A,l,t); } R = P/(1.0*tdim) - Qk * Ql/(1.0*tdim*tdim); return R; } /********************************************************************************************* Mersenne Twister random number generator: real number in [0,1) **********************************************************************************************/ /*Seeding the MT random number generator*/ void init_randnum() { //init_genrand(time(NULL)); init_genrand(0); } /*Generates a real number "rand()" between [0,1)*/ double randnum() { double num; num=genrand_real2(); return num; } /********************************************************************************************* Execution time **********************************************************************************************/ void elapsed_time(void) { printf("\n.\n.\n.\nElapsed time: %f min\n\n", clock()/(60.0*CLOCKS_PER_SEC)); }
{ "alphanum_fraction": 0.5022947116, "avg_line_length": 28.2694610778, "ext": "c", "hexsha": "0a5476c93fc404935a98df107ed7849a0ec5881c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "7d17010e3f7a9167368e460a78f797128cfd940d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "elohimfr/sk_model", "max_forks_repo_path": "skmodel.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "7d17010e3f7a9167368e460a78f797128cfd940d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "elohimfr/sk_model", "max_issues_repo_path": "skmodel.c", "max_line_length": 329, "max_stars_count": 1, "max_stars_repo_head_hexsha": "7d17010e3f7a9167368e460a78f797128cfd940d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "elohimfr/sk_model", "max_stars_repo_path": "skmodel.c", "max_stars_repo_stars_event_max_datetime": "2021-12-09T04:09:38.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-09T04:09:38.000Z", "num_tokens": 3779, "size": 14163 }
/* ode-initval/gear1.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Gear 1 */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv.h> #include "odeiv_util.h" typedef struct { double *k; double *y0; } gear1_state_t; static void * gear1_alloc (size_t dim) { gear1_state_t *state = (gear1_state_t *) malloc (sizeof (gear1_state_t)); if (state == 0) { GSL_ERROR_NULL ("failed to allocate space for gear1_state", GSL_ENOMEM); } state->k = (double *) malloc (dim * sizeof (double)); if (state->k == 0) { free (state); GSL_ERROR_NULL ("failed to allocate space for k", GSL_ENOMEM); } state->y0 = (double *) malloc (dim * sizeof (double)); if (state->y0 == 0) { free (state->k); free (state); GSL_ERROR_NULL ("failed to allocate space for y0", GSL_ENOMEM); } return state; } static int gear1_apply(void * vstate, size_t dim, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv_system * sys) { gear1_state_t *state = (gear1_state_t *) vstate; const int iter_steps = 3; int status = 0; int nu; size_t i; double * const k = state->k; double * const y0 = state->y0; DISCARD_POINTER(dydt_in); /* prevent warning about unused parameter */ DBL_MEMCPY(y0, y, dim); /* iterative solution */ for(nu=0; nu<iter_steps; nu++) { int s = GSL_ODEIV_FN_EVAL(sys, t + h, y, k); GSL_STATUS_UPDATE(&status, s); for(i=0; i<dim; i++) { y[i] = y0[i] + h * k[i]; } } /* fudge the error estimate */ for(i=0; i<dim; i++) { yerr[i] = h * h * k[i]; } if(dydt_out != NULL) { DBL_MEMCPY(dydt_out, k, dim); } return status; } static int gear1_reset (void *vstate, size_t dim) { gear1_state_t *state = (gear1_state_t *) vstate; DBL_ZERO_MEMSET (state->k, dim); DBL_ZERO_MEMSET (state->y0, dim); return GSL_SUCCESS; } static unsigned int gear1_order (void *vstate) { gear1_state_t *state = (gear1_state_t *) vstate; state = 0; /* prevent warnings about unused parameters */ return 2; } static void gear1_free (void *vstate) { gear1_state_t *state = (gear1_state_t *) vstate; free (state->k); free (state->y0); free (state); } static const gsl_odeiv_step_type gear1_type = { "gear1", /* name */ 1, /* can use dydt_in */ 0, /* gives exact dydt_out */ &gear1_alloc, &gear1_apply, &gear1_reset, &gear1_order, &gear1_free }; const gsl_odeiv_step_type *gsl_odeiv_step_gear1 = &gear1_type;
{ "alphanum_fraction": 0.6292487861, "avg_line_length": 22.5870967742, "ext": "c", "hexsha": "3967f13d63f72157e093cdf16f61b7d32e285b0c", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_path": "gsl_subset/ode-initval/gear1.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_path": "gsl_subset/ode-initval/gear1.c", "max_line_length": 78, "max_stars_count": 30, "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_path": "gsl_subset/ode-initval/gear1.c", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "num_tokens": 1030, "size": 3501 }
#ifndef PRK_PETSC_H_ #define PRK_PETSC_H_ #define PRK_PETSC_USE_MPI 1 #ifdef PRK_PETSC_USE_MPI #include <mpi.h> #endif #include <petsc.h> #include <petscsys.h> #include <petscvec.h> #include <petscmat.h> #endif // PRK_PETSC_H_
{ "alphanum_fraction": 0.7619047619, "avg_line_length": 14.4375, "ext": "h", "hexsha": "3478c765e9d09095ab7efade4cef43eb101a8393", "lang": "C", "max_forks_count": 101, "max_forks_repo_forks_event_max_datetime": "2022-01-13T02:56:02.000Z", "max_forks_repo_forks_event_min_datetime": "2015-06-15T22:06:46.000Z", "max_forks_repo_head_hexsha": "dae34b73235ccbf150d9b0ed5fb480b924789383", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "hattom/Kernels", "max_forks_repo_path": "C1z/prk_petsc.h", "max_issues_count": 202, "max_issues_repo_head_hexsha": "dae34b73235ccbf150d9b0ed5fb480b924789383", "max_issues_repo_issues_event_max_datetime": "2022-01-06T18:26:13.000Z", "max_issues_repo_issues_event_min_datetime": "2015-06-16T15:28:05.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "hattom/Kernels", "max_issues_repo_path": "C1z/prk_petsc.h", "max_line_length": 27, "max_stars_count": 346, "max_stars_repo_head_hexsha": "dae34b73235ccbf150d9b0ed5fb480b924789383", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "hattom/Kernels", "max_stars_repo_path": "C1z/prk_petsc.h", "max_stars_repo_stars_event_max_datetime": "2022-03-18T07:55:10.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-07T19:55:15.000Z", "num_tokens": 79, "size": 231 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <malloc.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_linalg.h> #define L 1 //1 2 3 4 #define LL 2 //2^(1 2 3 4) #define LLL 4 //2^(2 3 4 5) #define N 8 #define M 1 //# of trials #define R 1 //the number of different initial conditions #define S 100 //the number of different rules #define T1 100 //transient #define T2 1000 //time window used int **mat; int component[N],cnum; void findcomponent(int node) { int i; for (i=0;i<N;i++){ if (mat[node][i]==1 && component[i]==0){ component[i]=cnum; findcomponent(i); } } } double dabs(double x) { if (x<0.0)return -x; else return x; } int main() { FILE *fp,*fq,*fe,*fg,*fh,*fc,*fa; int i,j,k,l,t,m,r,s; int flag,flag1,flag2,tmp,tmp1,tmp2,tmp3,tmp4,ttmp; double dtmp; int x[N],xx[N][L+1],y[N]; int in[N]; int **nb,**rule; int check[N],sum,check_sum; double p1[N][LL],p2[N][LLL]; double ****p3,****p4; int num1,num2,num3; double indeg[N],outdeg[N]; double p=0.5; double q; int kav=2; int **adj,**adjflag; double *llap; double **lap,**edge,**grad,**circ; double div[N],sol[N]; double diag[N]; double **uu,**vv,**lap_inv; double el2_av,gl2_av,cl2_av,cratio_av; double el2,gl2,cl2,cratio; double *curl,*vp; int trinum; int **tri; double *ccurcur; double **curcur; double *diag2; double **uu2,**vv2,**curcur_inv; double **lcirc,**gcirc; double hl2_av,lcl2_av,gcratio_av,lcratio_av; double hl2,lcl2,gcratio,lcratio; double et,gt,ht,ct; double et_av,gt_av,ht_av,ct_av; char filename[100]; gsl_matrix *v_gsl=gsl_matrix_alloc(N,N); gsl_vector *s_gsl=gsl_vector_alloc(N); gsl_vector *work=gsl_vector_alloc(N); gsl_matrix_view lap_gsl; gsl_matrix_view cur_gsl; const gsl_rng_type * TYPE; gsl_rng * ran; gsl_rng_env_setup(); TYPE=gsl_rng_default; ran=gsl_rng_alloc(TYPE); gsl_rng_set(ran,2); adj=malloc(sizeof(int*)*N); adjflag=malloc(sizeof(int*)*N); mat=malloc(sizeof(int*)*N); lap=malloc(sizeof(double*)*N); edge=malloc(sizeof(double*)*N); grad=malloc(sizeof(double*)*N); circ=malloc(sizeof(double*)*N); lcirc=malloc(sizeof(double*)*N); gcirc=malloc(sizeof(double*)*N); uu=malloc(sizeof(double*)*N); vv=malloc(sizeof(double*)*N); lap_inv=malloc(sizeof(double*)*N); llap=malloc(sizeof(double)*(N*N)); p3=malloc(sizeof(double***)*N); p4=malloc(sizeof(double***)*N); for (i=0;i<N;i++){ adj[i]=malloc(sizeof(int)*N); adjflag[i]=malloc(sizeof(int)*N); mat[i]=malloc(sizeof(int)*N); lap[i]=malloc(sizeof(double)*N); edge[i]=malloc(sizeof(double)*N); grad[i]=malloc(sizeof(double)*N); circ[i]=malloc(sizeof(double)*N); lcirc[i]=malloc(sizeof(double)*N); gcirc[i]=malloc(sizeof(double)*N); uu[i]=malloc(sizeof(double)*N); vv[i]=malloc(sizeof(double)*N); lap_inv[i]=malloc(sizeof(double)*N); p3[i]=malloc(sizeof(double**)*N); p4[i]=malloc(sizeof(double**)*N); for (j=0;j<N;j++){ p3[i][j]=malloc(sizeof(double*)*LL); p4[i][j]=malloc(sizeof(double*)*LLL); for (k=0;k<LL;k++){ p3[i][j][k]=malloc(sizeof(double)*LL); } for (k=0;k<LLL;k++){ p4[i][j][k]=malloc(sizeof(double)*LL); } } } sprintf(filename,"rtn_hodge_sw_av_n%d_k%d.txt",N,kav); fp=fopen(filename,"w"); sprintf(filename,"rtn_hodge_sw_trial_n%d_k%d.txt",N,kav); fq=fopen(filename,"w"); for (q=0.1;q<0.11;q=q+0.1){ el2_av=0.0; gl2_av=0.0; cl2_av=0.0; cratio_av=0.0; hl2_av=0.0; lcl2_av=0.0; gcratio_av=0.0; lcratio_av=0.0; et_av=0.0; gt_av=0.0; ht_av=0.0; ct_av=0.0; for (m=0;m<M;m++){ for (i=0;i<N;i++){ for (j=0;j<N;j++){ adj[i][j]=0; adjflag[i][j]=0; } } for (i=0;i<N;i++){ for (k=-kav;k<kav+1;k++){ if (k!=0){ adj[(i+k+N)%N][i]=1; adj[i][(i+k+N)%N]=1; } } } for (i=0;i<N;i++){ for (k=-kav;k<kav+1;k++){ if (k!=0 && gsl_rng_uniform(ran)<q){ adjflag[(i+k+N)%N][i]=1; adjflag[i][(i+k+N)%N]=1; } } } for (i=0;i<N;i++){ for (j=i+1;j<N;j++){ if (adjflag[i][j]==1){ if (gsl_rng_uniform(ran)<0.5){ while (1){ tmp=(int)((double)N*gsl_rng_uniform(ran)); if (j!=tmp && adj[tmp][j]==0){ adj[i][j]=0; adj[j][i]=0; adj[tmp][j]=1; adj[j][tmp]=1; break; } } } else{ while (1){ tmp=(int)((double)N*gsl_rng_uniform(ran)); if (i!=tmp && adj[i][tmp]==0){ adj[i][j]=0; adj[j][i]=0; adj[tmp][i]=1; adj[i][tmp]=1; break; } } } } } } for (i=0;i<N;i++){ for (j=i+1;j<N;j++){ if (adj[i][j]==1){ if (gsl_rng_uniform(ran)<0.5)adj[i][j]=0; else adj[j][i]=0; } } } for (i=0;i<N;i++){ in[i]=0; for (j=0;j<N;j++){ in[i]+=adj[j][i]; } } nb=malloc(sizeof(int*)*N); rule=malloc(sizeof(int*)*N); for (i=0;i<N;i++){ nb[i]=malloc(sizeof(int)*in[i]); rule[i]=malloc(sizeof(int)*in[i]); } //in-neighbors for (i=0;i<N;i++){ k=0; for (j=0;j<N;j++){ if (adj[j][i]==1){ nb[i][k]=j; k++; } } } // for (i=0;i<N;i++){ for (j=0;j<N;j++){ edge[i][j]=0.0; } } for (s=0;s<S;s++){ //random generation of rules for (i=0;i<N;i++){ for (j=0;j<in[i];j++){ // rule[i][j]=gsl_ran_gaussian(ran,sigma); if (gsl_rng_uniform(ran)<0.5)rule[i][j]=1; else rule[i][j]=-1; } } for (k=0;k<N;k++){ for (i=0;i<LL;i++){ p1[k][i]=0.0; } for (i=0;i<LLL;i++){ p2[k][i]=0.0; } for (l=0;l<in[k];l++){ for (i=0;i<LL;i++){ for (j=0;j<LL;j++){ p3[k][nb[k][l]][i][j]=0.0; } } for (i=0;i<LLL;i++){ for (j=0;j<LL;j++){ p4[k][nb[k][l]][i][j]=0.0; } } } } for (r=0;r<R;r++){ //initial state for (i=0;i<N;i++){ if (gsl_rng_uniform(ran)<p)x[i]=1; else x[i]=-1; } //transient for (t=0;t<T1;t++){ for (i=0;i<N;i++){ tmp=0; for (j=0;j<in[i];j++){ tmp+=rule[i][j]*x[nb[i][j]]; } if (tmp<0)y[i]=-1; else y[i]=1; } for (i=0;i<N;i++){ x[i]=y[i]; } } for (i=0;i<N;i++){ for (j=0;j<L;j++){ xx[i][j]=0; } xx[i][L]=x[i]; } //time window used to calculation for (t=0;t<T2+L-1;t++){ for (i=0;i<N;i++){ tmp=0; for (j=0;j<in[i];j++){ tmp+=rule[i][j]*x[nb[i][j]]; } if (tmp<0)y[i]=-1; else y[i]=1; for (j=0;j<L;j++){ xx[i][j]=xx[i][j+1]; } xx[i][L]=y[i]; } if (t>=L-1){ for (i=0;i<N;i++){ num1=0; num2=0; for (k=0;k<L;k++){ num1+=((xx[i][k]+1)/2)*(int)pow(2.0,k); num2+=((xx[i][k]+1)/2)*(int)pow(2.0,k); } num2+=((xx[i][L]+1)/2)*(int)pow(2.0,L); p1[i][num1]+=1.0; p2[i][num2]+=1.0; for (j=0;j<in[i];j++){ num3=0; for (k=0;k<L;k++){ num3+=((xx[nb[i][j]][k]+1)/2)*(int)pow(2.0,k); } p3[i][nb[i][j]][num1][num3]+=1.0; p4[i][nb[i][j]][num2][num3]+=1.0; } } } for (i=0;i<N;i++){ x[i]=y[i]; } } }//end of r-loop for (k=0;k<N;k++){ for (i=0;i<LL;i++){ p1[k][i]=p1[k][i]/(double)(T2*R); } for (i=0;i<LLL;i++){ p2[k][i]=p2[k][i]/(double)(T2*R); } for (l=0;l<in[k];l++){ for (i=0;i<LL;i++){ for (j=0;j<LL;j++){ p3[k][nb[k][l]][i][j]=p3[k][nb[k][l]][i][j]/(double)(T2*R); } } for (i=0;i<LLL;i++){ for (j=0;j<LL;j++){ p4[k][nb[k][l]][i][j]=p4[k][nb[k][l]][i][j]/(double)(T2*R); } } } } //construction of edge flow for (i=0;i<N;i++){ for (j=0;j<in[i];j++){ for (num2=0;num2<LLL;num2++){ for (num3=0;num3<LL;num3++){ if (p4[i][nb[i][j]][num2][num3]>0.0)edge[nb[i][j]][i]+=p4[i][nb[i][j]][num2][num3]*(log(p4[i][nb[i][j]][num2][num3])/log(2.0) + log(p1[i][num2%LL])/log(2.0) - log(p2[i][num2])/log(2.0) - log(p3[i][nb[i][j]][num2%LL][num3])/log(2.0)); } } } } }//end of s-loop for (i=0;i<N;i++){ for (j=0;j<N;j++){ edge[i][j]=edge[i][j]/(double)S; } } for (i=0;i<N;i++){ for (j=i+1;j<N;j++){ dtmp=edge[i][j]-edge[j][i]; edge[i][j]=dtmp; edge[j][i]=-dtmp; } } //finding the number of components for (i=0;i<N;i++){ for (j=0;j<N;j++){ mat[i][j]=0; } } for (i=0;i<N;i++){ for (j=0;j<in[i];j++){ if (i!=nb[i][j]){ mat[nb[i][j]][i]=1; mat[i][nb[i][j]]=1; } } } tmp=0; for (i=0;i<N;i++){ for (j=i+1;j<N;j++){ if (mat[i][j]==1)tmp++; } } et=(double)tmp; for (i=0;i<N;i++){ component[i]=0; } cnum=1; component[0]=cnum; findcomponent(0); for (i=1;i<N;i++){ if (component[i]==0){ cnum++; component[i]=cnum; findcomponent(i); } } gt=(double)(N-cnum); //graph Laplacian for (i=0;i<N;i++){ for (j=0;j<N;j++){ lap[i][j]=0.0; } } for (i=0;i<N;i++){ lap[i][i]=0.0; for (j=0;j<N;j++){ lap[i][i]+=(double)mat[i][j]; } } for (i=0;i<N;i++){ for (j=0;j<in[i];j++){ if (i!=nb[i][j]){ lap[nb[i][j]][i]=-1.0; lap[i][nb[i][j]]=-1.0; } } } //generalized inverse of lap for (i=0;i<N;i++){ for (j=0;j<N;j++){ llap[i*N+j]=lap[i][j]; } } lap_gsl=gsl_matrix_view_array(llap,N,N); gsl_linalg_SV_decomp(&lap_gsl.matrix,v_gsl,s_gsl,work); for (i=0;i<N-cnum;i++){ diag[i]=1.0/gsl_vector_get(s_gsl,i); } for (i=N-cnum;i<N;i++){ diag[i]=0.0; } for (i=0;i<N;i++){ for (j=0;j<N;j++){ uu[i][j]=gsl_matrix_get(&lap_gsl.matrix,i,j); vv[i][j]=gsl_matrix_get(v_gsl,i,j); } } for (i=0;i<N;i++){ for (j=0;j<N;j++){ lap_inv[i][j]=0.0; for (k=0;k<N;k++){ lap_inv[i][j]+=vv[i][k]*diag[k]*uu[j][k]; } } } // //divergence of edge flow for (i=0;i<N;i++){ div[i]=0.0; for (j=0;j<N;j++){ div[i]+=edge[i][j]; } } //solution (negative potential) for (i=0;i<N;i++){ sol[i]=0.0; for (j=0;j<N;j++){ sol[i]-=lap_inv[i][j]*div[j]; } } //gradient flow for (i=0;i<N;i++){ for (j=0;j<N;j++){ grad[i][j]=sol[j]-sol[i]; } } //circular flow for (i=0;i<N;i++){ for (j=0;j<N;j++){ circ[i][j]=edge[i][j]-grad[i][j]; } } el2=0.0; gl2=0.0; cl2=0.0; for (i=0;i<N;i++){ for (j=i+1;j<N;j++){ if (lap[i][j]<0.0){ el2+=edge[i][j]*edge[i][j]; gl2+=grad[i][j]*grad[i][j]; cl2+=circ[i][j]*circ[i][j]; } } } if (el2>0.0)cratio=cl2/el2; else cratio=0.0; el2_av+=el2/(double)M; gl2_av+=gl2/(double)M; cl2_av+=cl2/(double)M; cratio_av+=cratio/(double)M; //decomposing circular flow into harmonic and curl flows trinum=0; for (i=0;i<N;i++){ for (j=i+1;j<N;j++){ for (k=j+1;k<N;k++){ if (mat[i][j]*mat[j][k]*mat[k][i]!=0)trinum++; } } } if (trinum>0){ curl=malloc(sizeof(double)*trinum); tri=malloc(sizeof(int*)*trinum); for (i=0;i<trinum;i++){ tri[i]=malloc(sizeof(int)*3); } l=0; for (i=0;i<N;i++){ for (j=i+1;j<N;j++){ for (k=j+1;k<N;k++){ if (mat[i][j]*mat[j][k]*mat[k][i]!=0){ tri[l][0]=i; tri[l][1]=j; tri[l][2]=k; curl[l]=circ[i][j]+circ[j][k]-circ[i][k]; l++; } } } } ccurcur=malloc(sizeof(double)*trinum*trinum); diag2=malloc(sizeof(double)*trinum); vp=malloc(sizeof(double)*trinum); curcur=malloc(sizeof(double*)*trinum); uu2=malloc(sizeof(double*)*trinum); vv2=malloc(sizeof(double*)*trinum); curcur_inv=malloc(sizeof(double*)*trinum); for (i=0;i<trinum;i++){ curcur[i]=malloc(sizeof(double)*trinum); uu2[i]=malloc(sizeof(double)*trinum); vv2[i]=malloc(sizeof(double)*trinum); curcur_inv[i]=malloc(sizeof(double)*trinum); } for (i=0;i<trinum;i++){ for (j=0;j<trinum;j++){ curcur[i][j]=0.0; if (tri[i][0]==tri[j][0] && tri[i][1]==tri[j][1])curcur[i][j]+=1.0; if (tri[i][0]==tri[j][0] && tri[i][1]==tri[j][2])curcur[i][j]-=1.0; if (tri[i][0]==tri[j][1] && tri[i][1]==tri[j][2])curcur[i][j]+=1.0; if (tri[i][1]==tri[j][0] && tri[i][2]==tri[j][1])curcur[i][j]+=1.0; if (tri[i][1]==tri[j][0] && tri[i][2]==tri[j][2])curcur[i][j]-=1.0; if (tri[i][1]==tri[j][1] && tri[i][2]==tri[j][2])curcur[i][j]+=1.0; if (tri[i][0]==tri[j][0] && tri[i][2]==tri[j][1])curcur[i][j]-=1.0; if (tri[i][0]==tri[j][0] && tri[i][2]==tri[j][2])curcur[i][j]+=1.0; if (tri[i][0]==tri[j][1] && tri[i][2]==tri[j][2])curcur[i][j]-=1.0; } } gsl_matrix *v_gsl2=gsl_matrix_alloc(trinum,trinum); gsl_vector *s_gsl2=gsl_vector_alloc(trinum); gsl_vector *work2=gsl_vector_alloc(trinum); //generalized inverse of curcur for (i=0;i<trinum;i++){ for (j=0;j<trinum;j++){ ccurcur[i*trinum+j]=curcur[i][j]; } } cur_gsl=gsl_matrix_view_array(ccurcur,trinum,trinum); gsl_linalg_SV_decomp(&cur_gsl.matrix,v_gsl2,s_gsl2,work2); tmp=0; for (i=0;i<trinum;i++){ dtmp=gsl_vector_get(s_gsl2,i); if (dtmp>1e-8)diag2[i]=1.0/dtmp; else { diag2[i]=0.0; tmp++; } } ct=(double)(trinum-tmp); ht=et-gt-ct; for (i=0;i<trinum;i++){ for (j=0;j<trinum;j++){ uu2[i][j]=gsl_matrix_get(&cur_gsl.matrix,i,j); vv2[i][j]=gsl_matrix_get(v_gsl2,i,j); } } for (i=0;i<trinum;i++){ for (j=0;j<trinum;j++){ curcur_inv[i][j]=0.0; for (k=0;k<trinum;k++){ curcur_inv[i][j]+=vv2[i][k]*diag2[k]*uu2[j][k]; } } } for (i=0;i<trinum;i++){ vp[i]=0.0; for (j=0;j<trinum;j++){ vp[i]+=curcur_inv[i][j]*curl[j]; } } for (i=0;i<N;i++){ lcirc[i][i]=0.0; for (j=i+1;j<N;j++){ lcirc[i][j]=0.0; if (mat[i][j]!=0){ for (k=0;k<trinum;k++){ if (tri[k][0]==i && tri[k][1]==j)lcirc[i][j]+=vp[k]; if (tri[k][0]==i && tri[k][2]==j)lcirc[i][j]-=vp[k]; if (tri[k][1]==i && tri[k][2]==j)lcirc[i][j]+=vp[k]; } } } } for (i=0;i<N;i++){ for (j=0;j<i;j++){ lcirc[i][j]=-lcirc[j][i]; } } for (i=0;i<N;i++){ for (j=0;j<N;j++){ gcirc[i][j]=circ[i][j]-lcirc[i][j]; } } hl2=0.0; lcl2=0.0; for (i=0;i<N;i++){ for (j=i+1;j<N;j++){ if (lap[i][j]<0.0){ hl2+=gcirc[i][j]*gcirc[i][j]; lcl2+=lcirc[i][j]*lcirc[i][j]; } } } fe=fopen("edgeflow.txt","w"); fg=fopen("gradientflow.txt","w"); fh=fopen("harmonicflow.txt","w"); fc=fopen("curlflow.txt","w"); fa=fopen("adjmatrix.txt","w"); for (i=0;i<N;i++){ for (j=0;j<N;j++){ if (adj[i][j]==1)fprintf(fa,"1 "); else fprintf(fa,"0 "); if (lap[i][j]<0.0){ fprintf(fe,"%lf ",edge[i][j]); fprintf(fg,"%lf ",grad[i][j]); fprintf(fh,"%lf ",gcirc[i][j]); fprintf(fc,"%lf ",lcirc[i][j]); } else{ fprintf(fe,"%lf ",0.0); fprintf(fg,"%lf ",0.0); fprintf(fh,"%lf ",0.0); fprintf(fc,"%lf ",0.0); } } fprintf(fe,"\n"); fprintf(fg,"\n"); fprintf(fh,"\n"); fprintf(fc,"\n"); fprintf(fa,"\n"); } fclose(fe); fclose(fg); fclose(fh); fclose(fc); fclose(fa); gsl_matrix_free(v_gsl2); gsl_vector_free(s_gsl2); gsl_vector_free(work2); free(ccurcur); free(diag2); free(vp); if (curcur){ for (i=0;i<trinum;i++){ free(curcur[i]); } } if (uu2){ for (i=0;i<trinum;i++){ free(uu2[i]); } } if (vv2){ for (i=0;i<trinum;i++){ free(vv2[i]); } } if (curcur_inv){ for (i=0;i<trinum;i++){ free(curcur_inv[i]); } } } else{ ct=0.0; ht=et-gt-ct; for (i=0;i<N;i++){ for (j=0;j<N;j++){ gcirc[i][j]=circ[i][j]; } } hl2=0.0; lcl2=0.0; for (i=0;i<N;i++){ for (j=i+1;j<N;j++){ if (lap[i][j]<0.0){ hl2+=gcirc[i][j]*gcirc[i][j]; } } } } if (cl2>0.0)gcratio=hl2/el2; else gcratio=0.0; hl2_av+=hl2/(double)M; lcl2_av+=lcl2/(double)M; gcratio_av+=gcratio/(double)M; lcratio=cratio-gcratio; lcratio_av+=lcratio/(double)M; et_av+=et/(double)M; gt_av+=gt/(double)M; ht_av+=ht/(double)M; ct_av+=ct/(double)M; if (m%1==0)printf("%lf %d %d %lf %lf %lf %lf %lf %lf\n",q,m,cnum,el2,gl2,hl2,lcl2,gcratio,lcratio); fprintf(fq,"%lf %d %d %.15lf %.15lf %.15lf %.15lf %.15lf %.15lf %.15lf %.15lf %.15lf %.15lf\n",q,m,cnum,el2,gl2,hl2,lcl2,gcratio,lcratio,et,gt,ht,ct); if (nb){ for (i=0;i<N;i++){ if (nb[i])free(nb[i]); } free(nb); } if (rule){ for (i=0;i<N;i++){ if (rule[i])free(rule[i]); } free(rule); } }//end of m-loop fprintf(fp,"%lf %.15lf %.15lf %.15lf %.15lf %.15lf %.15lf %.15lf %.15lf %.15lf %.15lf\n",q,el2_av,gl2_av,hl2_av,lcl2_av,gcratio_av,lcratio_av,et_av,gt_av,ht_av,ct_av); }//end of q-loop fclose(fp); fclose(fq); return 0; }
{ "alphanum_fraction": 0.443108332, "avg_line_length": 21.7823050058, "ext": "c", "hexsha": "38c941bcf17722f5538b7d97ae09c149fe46f0a7", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "dd744537927e1c98e64d9f5853e0f897bf649a5d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "taichiharuna/rtn_hodge_sw", "max_forks_repo_path": "rtn_hodge_sw_demo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "dd744537927e1c98e64d9f5853e0f897bf649a5d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "taichiharuna/rtn_hodge_sw", "max_issues_repo_path": "rtn_hodge_sw_demo.c", "max_line_length": 242, "max_stars_count": null, "max_stars_repo_head_hexsha": "dd744537927e1c98e64d9f5853e0f897bf649a5d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "taichiharuna/rtn_hodge_sw", "max_stars_repo_path": "rtn_hodge_sw_demo.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7132, "size": 18711 }