static void alloc_and_assign_internal_structures(struct s_net **original_net, struct s_block **original_block, int *original_num_nets, int *original_num_blocks) { /*allocate new data structures to hold net, and block info */ *original_net = clb_net; *original_num_nets = num_nets; num_nets = NET_COUNT; alloc_net(); *original_block = block; *original_num_blocks = num_blocks; num_blocks = BLOCK_COUNT; alloc_block(); /* [0..num_nets-1][1..num_pins-1] */ net_delay = (float **)alloc_matrix(0, NET_COUNT - 1, 1, BLOCK_COUNT - 1, sizeof(float)); net_slack = (float **)alloc_matrix(0, NET_COUNT - 1, 1, BLOCK_COUNT - 1, sizeof(float)); reset_placement(); }
static void alloc_delta_arrays(void) { int id_x, id_y; delta_clb_to_clb = (float **) alloc_matrix(0, nx - 1, 0, ny - 1, sizeof(float)); delta_inpad_to_clb = (float **) alloc_matrix(0, nx, 0, ny, sizeof(float)); delta_clb_to_outpad = (float **) alloc_matrix(0, nx, 0, ny, sizeof(float)); delta_inpad_to_outpad = (float **) alloc_matrix(0, nx + 1, 0, ny + 1, sizeof(float)); /*initialize all of the array locations to -1*/ for (id_x = 0; id_x <= nx; id_x++) { for (id_y = 0; id_y <= ny; id_y++) { delta_inpad_to_clb[id_x][id_y] = IMPOSSIBLE; } } for (id_x = 0; id_x <= nx - 1; id_x++) { for (id_y = 0; id_y <= ny - 1; id_y++) { delta_clb_to_clb[id_x][id_y] = IMPOSSIBLE; } } for (id_x = 0; id_x <= nx; id_x++) { for (id_y = 0; id_y <= ny; id_y++) { delta_clb_to_outpad[id_x][id_y] = IMPOSSIBLE; } } for (id_x = 0; id_x <= nx + 1; id_x++) { for (id_y = 0; id_y <= ny + 1; id_y++) { delta_inpad_to_outpad[id_x][id_y] = IMPOSSIBLE; } } }
int main(int argc, char** argv) { arg_size = 1024; if(argc > 1) arg_size = atoi(argv[1]); arg_cutoff_value = 64; if(argc > 2) arg_cutoff_value = atoi(argv[2]); if((arg_size & (arg_size - 1)) != 0 || (arg_size % 16) != 0) inncabs::error("Error: matrix size must be a power of 2 and a multiple of 16\n"); REAL *A = alloc_matrix(arg_size); REAL *B = alloc_matrix(arg_size); REAL *C = alloc_matrix(arg_size); REAL *D = alloc_matrix(arg_size); std::stringstream ss; ss << "Strassen Algorithm (" << arg_size << " x " << arg_size << " matrix with cutoff " << arg_cutoff_value << ") "; init_matrix(arg_size, A, arg_size); init_matrix(arg_size, B, arg_size); OptimizedStrassenMultiply_seq(D, A, B, arg_size, arg_size, arg_size, arg_size, 1); inncabs::run_all( [&](const std::launch l) { OptimizedStrassenMultiply_par(l, C, A, B, arg_size, arg_size, arg_size, arg_size, 1); return 1; }, [&](int result) { return compare_matrix(arg_size, C, arg_size, D, arg_size); }, ss.str() ); }
int main(int argc, char** argv) { int i, j, size, k, step, pos, res; pthread_t threads[THR_NUM]; pthread_attr_t attr; if(argc > 1) size = atoi(argv[1]); else size = SIZE; printf("Выделение памяти\n"); int *m1 = alloc_matrix(size); int *m2 = alloc_matrix(size); int *ans = alloc_matrix(size); for(i=0; i<size; i++) for(j=0; j<size; j++) { m1[i + j * size] = 1;//i* size +j; m2[i + j * size] = 1;//i* 1000 +j; } printf("Умножение\n"); double t0 = dtime(); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); step = (int)((double)size/(double)THR_NUM); pos = 0; for(k = 0; k < THR_NUM; k++) { ARG[k].m1 = m1; ARG[k].m2 = m2; ARG[k].ans = ans; ARG[k].size = size; ARG[k].start = pos; pos += step; ARG[k].end = (k == THR_NUM - 1) ? size : pos; res = pthread_create(&threads[k], &attr, multiply_matrix, (void *)&ARG[k]); if (res) { fprintf(stderr, "Поток не создан!\n"); exit(1); } } pthread_attr_destroy(&attr); for(k = 0; k < THR_NUM; k++) pthread_join(threads[k], NULL); printf("Время выполнениея программы: %f\n", dtime() - t0); FILE *f = fopen("out", "w"); printf("Вычисление\n"); for(i=0; i<size; i++) { for(j=0; j<size; j++) fprintf(f, "%d\t", ans[i*size + j]); fprintf(f, "\n"); } fclose(f); del_matrix(m1); del_matrix(m2); del_matrix(ans); pthread_exit(NULL); }
double multi_regression(FILE *fp, int nrow, double *y, int ncol, double **xx, double *a0) { int row, niter, i, j; double ax, chi2, **a, **at, **ata, *atx; a = alloc_matrix(nrow, ncol); at = alloc_matrix(ncol, nrow); ata = alloc_matrix(ncol, ncol); for (i = 0; (i < nrow); i++) { for (j = 0; (j < ncol); j++) { at[j][i] = a[i][j] = xx[j][i]; } } matrix_multiply(fp, nrow, ncol, a, at, ata); if ((row = matrix_invert(fp, ncol, ata)) != 0) { gmx_fatal(FARGS, "Matrix inversion failed. Incorrect row = %d.\nThis probably indicates that you do not have sufficient data points, or that some parameters are linearly dependent.", row); } snew(atx, ncol); for (i = 0; (i < ncol); i++) { atx[i] = 0; for (j = 0; (j < nrow); j++) { atx[i] += at[i][j]*y[j]; } } for (i = 0; (i < ncol); i++) { a0[i] = 0; for (j = 0; (j < ncol); j++) { a0[i] += ata[i][j]*atx[j]; } } chi2 = 0; for (j = 0; (j < nrow); j++) { ax = 0; for (i = 0; (i < ncol); i++) { ax += a0[i]*a[j][i]; } chi2 += sqr(y[j]-ax); } sfree(atx); free_matrix(a); free_matrix(at); free_matrix(ata); return chi2; }
void ksampleEtest(double *x, int *byrow, int *nsamples, int *sizes, int *dim, int *R, double *e0, double *e, double *pval) { /* exported for R energy package: E test for equal distributions x the pooled sample (or distances) *byrow logical, TRUE if x is stored by row pass x=as.double(t(x)) if *byrow==TRUE *nsamples number of samples *sizes vector of sample sizes *dim dimension of data in x (0 if x is distance matrix) *R number of replicates for permutation test *e0 observed E test statistic e vector of replicates of E statistic *pval approximate p-value */ int b, ek, i, k; int B = (*R), K = (*nsamples), d=(*dim), N; int *perm; double **data, **D; N = 0; for (k=0; k<K; k++) N += sizes[k]; perm = Calloc(N, int); for (i=0; i<N; i++) perm[i] = i; D = alloc_matrix(N, N); /* distance matrix */ if (d > 0) { data = alloc_matrix(N, d); /* sample matrix */ vector2matrix(x, data, N, d, *byrow); distance(data, D, N, d); free_matrix(data, N, d); } else vector2matrix(x, D, N, N, *byrow); *e0 = multisampleE(D, K, sizes, perm); /* bootstrap */ if (B > 0) { ek = 0; GetRNGstate(); for (b=0; b<B; b++) { permute(perm, N); e[b] = multisampleE(D, K, sizes, perm); if ((*e0) < e[b]) ek++; } PutRNGstate(); (*pval) = ((double) (ek + 1)) / ((double) (B + 1)); } free_matrix(D, N, N); Free(perm); }
int main(int argc, char* argv[]) { int dim = 0; int **mat=NULL, **ps=NULL, **outmat=NULL; FILE* input_file; if(argc != 2) { usage(argv[0]); } /* open files */ input_file = fopen(argv[1], "r"); if(input_file == NULL) { usage(argv[0]); } /* read matrix dimension */ dim = get_mat_dim(input_file); /* init matrices */ mat = alloc_matrix(dim, dim); ps = alloc_matrix(dim, dim); /* read matrix */ read_matrix(mat, dim, dim, input_file); #ifdef _PRINT_INFO /* Print the matrix */ printf("[INFO] Input matrix [%d]\n", dim); print_matrix(mat, dim, dim); #endif printf("Evaluation:\n"); printf("===========\n"); double avg_time = 0; /* compute an average value of the time needed to run the program */ for(int i=0; i<NUM_ROUNDS; i++) { max_sub_arr(mat, ps, outmat, dim); /* runtime of the algorithm is modified by the algorithm itself */ avg_time += runtime; } avg_time /= NUM_ROUNDS; /* print stats */ printf("[STAT] Runtime=%f sec\n\n", avg_time); /* release resources */ fclose(input_file); free_matrix(mat, dim); free_matrix(ps, dim); return EXIT_SUCCESS; }
struct ClassData *I_AllocClassData(struct SigSet *S, struct ClassSig *C, int npixels) { struct ClassData *Data; Data = &(C->ClassData); Data->npixels = npixels; Data->count = 0; Data->x = alloc_matrix(npixels, S->nbands); Data->p = alloc_matrix(npixels, C->nsubclasses); return Data; }
int main(int argc, char** argv) { if(argc != 3) { printf("Usage: ./gram_schmidt vector_length number_of_vectors\n"); exit(EXIT_FAILURE); } double** v; double **q; double temp_norm, sigma; int row = atoi(argv[1]); //int col = row; int col = atoi(argv[2]); if(row < col) { printf("It is not possible to create an orthogonal base with such values. \n"); exit(-1); } int k,i,j,ttime; v = alloc_matrix(row, col); q = alloc_matrix(row, col); // initializes v with random values srand(time(NULL)); init(v, row, col); // compute ttime=timer(); for(i=0; i<row; i++) { temp_norm = vecNorm(v[i],col); for (k=0; k<col; k++) q[i][k] = v[i][k]/temp_norm; #pragma omp parallel for private(temp_norm, k, j, sigma) schedule(dynamic) for(j=i+1; j<row; j++) { sigma = scalarProd(q[i], v[j], col); for(k=0; k<col; k++) v[j][k] -=sigma*q[i][k]; } } ttime=timer()-ttime; printf("Time: %f \n",ttime/1000000.0); printf("Check orthogonality: %e \n",scalarProd(q[col/2], q[col/3], row)); }
int main(int argc, char *argv[]){ double bestcost; int bestroot; int high; int low; int n; int r; double rcost; int **root; double **cost; double *p; // probability of each key scanf("%d", &n); p = (double *) malloc (n * sizeof(double)); for (int i = 0; i < n; ++i) scanf("%lf",&p[i]); /* Find Optimal Binary Search Tree */ alloc_matrix((void ***) &cost, n + 1, n + 1, sizeof(double)); alloc_matrix((void ***) &root, n + 1, n + 1, sizeof(int)); for (int low = n; low >= 0; --low) { cost[low][low] = 0.0; root[low][low] = low; for (int high = low + 1; high <= n; ++high) { bestcost = INF; double fcost = 0; for (int j = low; j < high; ++j) fcost += p[j]; for (int r = low; r < high; ++r) { rcost = cost[low][r] + cost[r + 1][high] + fcost; if (rcost < bestcost) { bestcost = rcost; bestroot = r; } } cost[low][high] = bestcost; root[low][high] = bestroot; } } /* Print structure of binary search tree */ //print_root(root, 0, n - 1); printf("Optimal solution cost = %lf\n", cost[0][n]); return 0; }
/* * Reads matrix from file */ struct matrix_t* read_matrix(FILE *f) { struct matrix_t* matrix; msize_t n_rows, n_cols; assert (f != NULL); fscanf(f, "%d %d ", &n_rows, &n_cols); /* XXX */ assert ((n_rows >= 0) && (n_cols >= 0)); if ((matrix = alloc_matrix(n_rows, n_cols)) == NULL) { return NULL; } /* Read matrix elements */ { msize_t row, col; elem_t * restrict * restrict data = matrix->data; for (row = 0; row < n_rows; row++) { for (col = 0; col < n_cols; col++) { fscanf(f, "%lf", &data[row][col]); /* XXX */ } } } return matrix; }
static struct matrix_t* transpose(struct matrix_t* m) { struct matrix_t* t; if ((t = alloc_matrix(m->n_cols, m->n_rows)) == NULL) { return NULL; } /* Copying may look sloow, but it's not the bottleneck */ { msize_t row, col; elem_t * restrict * restrict src; elem_t * restrict * restrict dst; src = m->data; dst = t->data; for (row = 0; row < m->n_rows; row++) { for (col = 0; col < m->n_cols; col++) { dst[col][row] = src[row][col]; } } } return t; }
int main(int argc, char *argv[]) { int n = 3; //rows int m = 3; //cols double **matrix; FILE *fp; //Det could be computed only from square matrix if (n != m && n > 1) error(2); fp = fopen("matrix.txt", "r"); if (!fp) error(0); matrix = alloc_matrix(n, m); parse_file(fp, matrix, n, m); print_matrix(matrix, n, m); printf("Det: %f\n", compute_det(matrix, n)); dealloc_matrix(matrix, n); fclose(fp); getchar(); return 0; }
static ERL_NIF_TERM add(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { /* add(Matrix_A, Matrix_B) -> Matrix_Sum */ unsigned i, j; ERL_NIF_TERM ret; mx_t mxA, mxB, mxS; mxA.p = NULL; mxB.p = NULL; mxS.p = NULL; if (!enif_get_resource(env, argv[0], resource_type, &mxA.vp) || !enif_get_resource(env, argv[1], resource_type, &mxB.vp) || mxA.p->nrows != mxB.p->nrows || mxB.p->ncols != mxB.p->ncols) { return enif_make_badarg(env); } mxS.p = alloc_matrix(env, mxA.p->nrows, mxA.p->ncols); for (i = 0; i < mxA.p->nrows; i++) { for (j = 0; j < mxA.p->ncols; j++) { POS(mxS.p, i, j) = POS(mxA.p, i, j) + POS(mxB.p, i, j); } } ret = enif_make_resource(env, mxS.p); enif_release_resource(mxS.p); return ret; }
int main(int argc, char* argv[]) { int dim = 0; int **mat, **ps, **outmat; FILE* input_file; if(argc < 2) { usage(argv[0]); } for(int i=1; i<argc; i++) { /* open files */ input_file = fopen(argv[i], "r"); if(input_file == NULL) { usage(argv[0]); } /* read matrix dimension */ dim = get_mat_dim(input_file); /* init matrices */ mat = alloc_matrix(dim, dim); ps = alloc_matrix(dim, dim); /* read matrix */ read_matrix(mat, dim, dim, input_file); precomp_matrix(mat, ps, dim, NUM_THREADS); maxarray_thread_ret ret = maxarray_pthread(ps, mat, dim, NUM_THREADS); printf("%d %d %d %d\n",ret.left,ret.top,ret.right,ret.bottom); /* release resources */ fclose(input_file); free_matrix(mat, dim); free_matrix(ps, dim); } return EXIT_SUCCESS; }
static matrix *transpose(matrix a) { matrix *result = alloc_matrix(a.n, a.m); for (int i=0; i<result->m; i++) { for (int j=0; j<result->n; j++) result->entries[i][j] = a.entries[j][i]; } return result; }
void lindiff (long nx, /* image dimension in x direction */ long ny, /* image dimension in y direction */ float ht, /* time step size, 0 < ht <= 0.25 */ float hx, /* pixel size in x direction */ float hy, /* pixel size in y direction */ float **u) /* input: original image; output: smoothed */ /* linear diffusion subroutine for du/dt = div(grad(u)) */ { long i, j; /* loop variables */ float rx, ry; /* mesh ratios */ float **f; /* copy of input image u */ /* ---- allocate storage for f ---- */ alloc_matrix (&f, nx+2, ny+2); /* ---- copy u into f ---- */ for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) f[i][j] = u[i][j]; /* ---- create dummy boundaries for f by mirroring ---- */ dummies (f, nx, ny); /* ---- diffusive averaging ---- */ rx = ht / (hx * hx); ry = ht / (hy * hy); for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) { /* SUPPLEMENT CODE */ u[i][j] = (1 - 2 * rx - 2 * ry) * f[i][j] + rx * f[i + 1][j] + rx * f[i - 1][j] + ry * f[i][j + 1] + ry * f[i][j - 1]; } /* ---- disallocate storage for f ---- */ disalloc_matrix (f, nx+2, ny+2); return; } /* lindiff */
/* Gera o arquivo de saida */ void gera_csv_reduzido(char fnamein[], char fnameout[]) { FILE *in, *out; int n, *campos; int columns, lines; int i, j; char **values; /* Abrindo os arquivos de entrada e saida */ in = fopen(fnamein, "r"); out = fopen(fnameout, "w"); /* Se nao conseguir abrir, retorna */ if ((in == NULL) || (out == NULL)) { return; } /* Quantidade de colunas */ columns = columns_file(in); /* Quantidade de linhas */ lines = lines_file(in); /* Alocacao da matriz que armazenara os campos em cada linha */ values = alloc_matrix(columns, MAX_CAMP); /* Quantidade de colunas que serao impressas no arquivo de saida */ scanf("%d", &n); /* Alocacao do vetor que armazenara quais colunas serao impressas */ campos = malloc(n * sizeof(int)); /* Leitura dos numeros das colunas a serem impressas */ for (i = 0; i < n; i++) scanf("%d", &campos[i]); /* Leitura das linhas do arquivo de entrada */ for (i = 0; i < lines; i++) { read_lines(in, columns, values); /* Impressao dessas linhas no arquivo de saida */ for (j = 0; j < n; j++) { fprintf(out, "%s", values[campos[j]-1]); if (j != n-1) fprintf(out, ","); } fprintf(out, "\n"); } /* Fechando os arquivos abertos pelo programa */ if (in) fclose(in); if (out) fclose(out); /* Liberando a memoria alocada pela matriz */ free_matrix(values, columns); }
matrix_t* getGamma(const mxArray* array, size_t L) { if (mxGetN(array) != L || mxGetM(array) != L) { mexErrMsgTxt("Invalid dimension of gamma matrix."); } matrix_t* gamma = alloc_matrix(L, L); copyMatrix(gamma, array); return gamma; }
static void load_simplified_device(void) { int i, j; /* Backup original globals */ EMPTY_TYPE_BACKUP = EMPTY_TYPE; IO_TYPE_BACKUP = IO_TYPE; FILL_TYPE_BACKUP = FILL_TYPE; type_descriptors_backup = type_descriptors; num_types_backup = num_types; num_types = NUM_TYPES_USED; /* Fill in homogeneous core type info */ dummy_type_descriptors[0] = *EMPTY_TYPE; dummy_type_descriptors[0].index = 0; dummy_type_descriptors[1] = *IO_TYPE; dummy_type_descriptors[1].index = 1; dummy_type_descriptors[2] = *FILL_TYPE; dummy_type_descriptors[2].index = 2; type_descriptors = dummy_type_descriptors; EMPTY_TYPE = &dummy_type_descriptors[0]; IO_TYPE = &dummy_type_descriptors[1]; FILL_TYPE = &dummy_type_descriptors[2]; /* Fill in homogeneous core grid info */ grid_backup = grid; grid = (struct s_grid_tile **)alloc_matrix(0, nx + 1, 0, ny + 1, sizeof(struct s_grid_tile)); for(i = 0; i < nx + 2; i++) { for(j = 0; j < ny + 2; j++) { if((i == 0 && j == 0) || (i == nx + 1 && j == 0) || (i == 0 && j == ny + 1) || (i == nx + 1 && j == ny + 1)) { grid[i][j].type = EMPTY_TYPE; } else if(i == 0 || i == nx + 1 || j == 0 || j == ny + 1) { grid[i][j].type = IO_TYPE; } else { grid[i][j].type = FILL_TYPE; } grid[i][j].blocks = my_malloc(grid[i][j].type->capacity * sizeof(int)); grid[i][j].offset = 0; } } }
int main(int argc, char const* argv[]) { int dimension; int **A, **B, **C; int runtimesec, runtimenano; struct timeval pretime, pasttime; srand(time(0)); /* init random number generator */ if (argc != 2) { printf("Bitte die größe der Matrix angeben\n"); exit(1); } dimension = atoi(argv[1]); if (dimension < 2) { printf("Zu klein\n"); exit(1); } A = alloc_matrix(dimension); B = alloc_matrix(dimension); /* fill C with rand values, even if it doesn't make sense */ C = alloc_matrix(dimension); gettimeofday(&pretime, NULL); serial_mx_mult(A, B, C, dimension); gettimeofday(&pasttime, NULL); print_matrix(C, dimension); //runtimesec = difftime(pasttime.tv_sec, pretime.tv_sec); runtimesec = pasttime.tv_sec - pretime.tv_sec; //runtimenano = difftime(pasttime.tv_usec, pretime.tv_usec); runtimenano = pasttime.tv_usec - pretime.tv_usec; printf("Sekunden %d, Mikrosekunden: %d\n", runtimesec, runtimenano); return 0; }
// runtime: O(a.m*a.n*b.n) matrix *matrix_mult(matrix a, matrix b) { assert(a.n == b.m); // otherwise product is not defined matrix *result = alloc_matrix(a.m, b.n); for (int i=0; i<result->m; i++) { for (int j=0; j<result->n; j++) { result->entries[i][j] = 0; for (int k=0; k<a.n; k++) result->entries[i][j] += a.entries[i][k] * b.entries[k][j]; } } return result; }
void null_matrix(matrix_t *mat, int r) { int i = 0, j = 0; mat->m = r; mat->n = r; alloc_matrix(mat); for (i = 0; i<mat->m; i++) { for (j = 0; j<mat->n; j++) { set_mat(*mat, i, j, (float)0); } } }
int test_gaussian () { FILE *out = fopen("gaussian.dat", "w"); size_t i; double **samples, **interp_samples; gsl_rng *rng = gsl_rng_alloc(gsl_rng_ranlxd2); const size_t nsamples = 1000000; const size_t ndim = 2; double low[ndim], high[ndim]; tree *tr; double mu[ndim], std[ndim]; int status = 0; /* Success unless proved otherwise. */ FILE *gaussian_out = fopen("gaussian_interp.dat", "w"); assert(gaussian_out != 0); assert(rng != 0); randomize(rng); samples = alloc_gaussian_samples(rng, nsamples, ndim); bounds_of_points(ndim, nsamples, samples, low, high); col_mean_std(samples, nsamples, ndim, mu, std); tr = make_interp_tree(ndim, nsamples, samples, low, high); interp_samples = alloc_matrix(nsamples, ndim); for (i = 0; i < nsamples; i++) { sample_density(ndim, nsamples, samples, tr, (uniform_random) gsl_rng_uniform, rng, interp_samples[i]); } col_mean_std(interp_samples, nsamples, ndim, mu, std); for (i = 0; i < nsamples; i++) { fprintf(gaussian_out, "%g %g\n", interp_samples[i][0], interp_samples[i][1]); } fclose(gaussian_out); if (fabs(mu[0]) > 5e-2) status = 1; if (fabs(mu[1]) > 5e-2) status = 2; if (fabs(std[0] - 1.0) > 5e-2) status = 3; if (fabs(std[1] - 1.0) > 5e-2) status = 4; gsl_rng_free(rng); fclose(out); free_matrix(samples, nsamples, ndim); free_matrix(interp_samples, nsamples, ndim); return status; }
int main(void) { srand(time(NULL)); TYPE **a = alloc_matrix(N); TYPE **b = alloc_matrix(N); TYPE **c = alloc_matrix(N); randomize_matrix(a, N); randomize_matrix(b, N); clock_t start = clock(); mul_matrix(c, a, b, N); double working_time = (double)(clock() - start) / CLOCKS_PER_SEC; printf("Working time: %g s\n", working_time); free_matrix(a, N); free_matrix(b, N); free_matrix(c, N); return 0; }
void random_matrix(matrix_t *mat, int r) { int i = 0, j = 0; mat->m = r; mat->n = r; alloc_matrix(mat); for (i = 0; i<mat->m; i++) { for (j = 0; j<mat->n; j++) { set_mat(*mat, i, j, ((float)(((float)(rand()%100))/(float)(rand()%50))) ); } } }
void read_pgm_and_allocate_memory (const char *file_name, /* name of pgm file */ long *nx, /* image size in x direction, output */ long *ny, /* image size in y direction, output */ float ***u) /* image, output */ /* reads a greyscale image that has been encoded in pgm format P5; allocates memory for the image u; adds boundary layers of size 1 such that - the relevant image pixels in x direction use the indices 1,...,nx - the relevant image pixels in y direction use the indices 1,...,ny */ { FILE *inimage; /* input file */ char row[80]; /* for reading data */ long i, j; /* loop variables */ /* open file */ inimage = fopen (file_name, "rb"); if (NULL == inimage) { printf ("could not open file '%s' for reading, aborting.\n", file_name); exit (1); } /* read header */ fgets (row, 80, inimage); /* skip format definition */ fgets (row, 80, inimage); while (row[0]=='#') /* skip comments */ fgets (row, 80, inimage); sscanf (row, "%ld %ld", nx, ny); /* read image size */ fgets (row, 80, inimage); /* read maximum grey value */ /* allocate memory */ alloc_matrix (u, (*nx)+2, (*ny)+2); /* read image data row by row */ for (j=1; j<=(*ny); j++) for (i=1; i<=(*nx); i++) (*u)[i][j] = (float) getc(inimage); /* close file */ fclose(inimage); return; } /* read_pgm_and_allocate_memory */
// returns a minus the zeroth row and nth column static matrix *matrix_minor(matrix a, int n) { matrix *result = alloc_matrix(a.m - 1, a.n - 1); for (int i=0; i<result->m; i++) { for (int j=0; j<result->n; j++) { if (j < n) { result->entries[i][j] = a.entries[i+1][j]; } else { result->entries[i][j] = a.entries[i+1][j+1]; } } } return result; }
// returns the n-by-n identity matrix matrix *identity_matrix(int n) { matrix *result = alloc_matrix(n, n); for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { if (i == j) { result->entries[i][j] = 1.0; } else { result->entries[i][j] = 0.0; } } } return result; }
double * amoeba(Search_settings *sett, Aux_arrays *aux, double *point, double *nS, double *res_max, int dim, double tol, double *pc2, double **sigaa, double **sigbb){ int ihi, ilo, inhi; // ihi = ih[0], ilo = ih[1], inhi = ih[2]; int *ih; int j, i; static double NM_out[11]; double ** fx = alloc_matrix(dim + 1, 11); double * midpoint = alloc_vector(dim); double * line = alloc_vector(dim); double ** simplex = make_simplex(point, dim, pc2); evaluate_simplex(simplex, dim, fx, sett, aux, nS, sigaa, sigbb); while (true) { ih = simplex_extremes(fx, dim); ihi = ih[0]; ilo = ih[1]; inhi = ih[2]; simplex_bearings(simplex, dim, midpoint, line, ihi); if(check_tol(fx[ihi][5], fx[ilo][5], tol)) break; update_simplex(simplex, dim, fx[ihi][5], fx, ihi, midpoint, line, -1.0, sett, aux, nS, sigaa, sigbb); if (fx[ihi][5] < fx[ilo][5]){ update_simplex(simplex, dim, fx[ihi][5], fx, ihi, midpoint, line, -2.0, sett, aux, nS, sigaa, sigbb); } else if (fx[ihi][5] > fx[inhi][5]){ if (!update_simplex(simplex, dim, fx[ihi][5], fx, ihi, midpoint, line, 0.5, sett, aux, nS, sigaa, sigbb)){ contract_simplex(simplex, dim, fx, ilo, ihi, sett, aux, nS, sigaa, sigbb); } } } for (j = 0; j < dim; j++) point[j] = simplex[ilo][j]; for (j = 0; j < 11; j++) NM_out[j] = fx[ilo][j]; free_matrix(fx, dim + 1, 10); free_vector(midpoint, dim); free_vector(line, dim); free_matrix(simplex, dim + 1, dim); /* free(fx); free(midpoint); free(line); free(simplex); */ return NM_out; }