Grid::Grid(Grid *Orig){ int i; domainname = strdup(Orig->domainname); domainfile = Orig->domainfile; totverts = Orig->totverts; xcoords = dvector(0, totverts-1); ycoords = dvector(0, totverts-1); zcoords = dvector(0, totverts-1); dcopy(totverts, Orig->xcoords, 1, xcoords, 1); dcopy(totverts, Orig->ycoords, 1, ycoords, 1); dcopy(totverts, Orig->zcoords, 1, zcoords, 1); nel = Orig->nel; nverts = ivector(0, nel-1); icopy(nel, Orig->nverts, 1, nverts, 1); vertids = imatrix(0, nel-1, 0, Max_Nverts-1); icopy(nel*Max_Nverts, Orig->vertids[0], 1, vertids[0], 1); elmtids = ivector(0, nel-1); icopy(nel, Orig->elmtids, 1, elmtids, 1); vertexmap = imatrix(0, nel-1, 0, Max_Nverts-1); icopy(nel*Max_Nverts, Orig->vertexmap[0], 1, vertexmap[0], 1); }
/* count the number of nodal domains in grid precondition: grid must be ny x nx inputs: grid - function values sampled at grid points counted - array to store nodal domain numbers in. mask should be applied to this already sizefile - file to write size of nodal domains to output: return value - count of nodal domains */ int countNodalDomains(bit_array_t *signs, bit_array_t *counted, FILE *sizefile) { int i, j; int rc; int nx, ny; nx = signs->nx; ny = signs->ny; #ifdef DEBUG bit_array2file(signs, "../data/signs.dat"); domain_numbers = imatrix(ny, nx); #endif int nd = 0; // count of nodal domains int size; // area of last nodal domain (in pixels) i = 0; j = 0; while (findNextUnseen(counted, &i, &j, ny, nx)) { nd++; size = findDomain(signs, counted, i, j, nd, ny, nx); if (sizefile) { fprintf(sizefile, "%d ", size); } } #ifdef DEBUG intArray2file(domain_numbers, ny, nx, "../data/counted.dat"); #endif return nd; }
int main(int argc, char* argv[]) { FILE *in; int **image; double **image_i; double **image_d; int c; int N; int coeff_start = 5000, wm_length = 10000; double wm_alpha = 0.2; int width, height; pgm_init(&argc, argv); wm_init2(); while ((c = getopt(argc, argv, "a:s:l:")) != EOF) { switch (c) { case 'a': wm_alpha = atof(optarg); break; case 's': coeff_start = atoi(optarg); break; case 'l': wm_length = atoi(optarg); break; } } argc -= optind; argv += optind; in = stdin; open_image(in, &width, &height); image = imatrix(height, width); load_image(image, in, width, height); if (height == width) N = height; else { fprintf(stderr, "Cannot Proccess non-square images!\n"); exit( -11); } image_i = dmatrix(height, width); image_d = dmatrix(height, width); if (image_d == NULL) { fprintf(stderr, "Unable to allocate the double array\n"); exit(1); } matrix_i2d(image, image_i, N); hartley(image_i, image_d, N); read_watermark(image_d, N, coeff_start, wm_length, wm_alpha); freematrix_d(image_i, height); freematrix_d(image_d, height); fclose(in); exit(EXIT_SUCCESS); }
/* * ASSEMBLE_K - assemble global stiffness matrix from individual elements 23feb94 */ void assemble_K( double **K, int DoF, int nE, vec3 *xyz, float *r, double *L, double *Le, int *N1, int *N2, float *Ax, float *Asy, float *Asz, float *Jx, float *Iy, float *Iz, float *E, float *G, float *p, int shear, int geom, double **Q, int debug ){ double **k; /* element stiffness matrix in global coord */ int **ind, /* member-structure DoF index table */ res=0, i, j, ii, jj, l, ll; char stiffness_fn[FILENMAX]; for (i=1; i<=DoF; i++) for (j=1; j<=DoF; j++) K[i][j] = 0.0; k = dmatrix(1,12,1,12); ind = imatrix(1,12,1,nE); for ( i=1; i<= nE; i++ ) { ind[1][i] = 6*N1[i] - 5; ind[7][i] = 6*N2[i] - 5; ind[2][i] = ind[1][i] + 1; ind[8][i] = ind[7][i] + 1; ind[3][i] = ind[1][i] + 2; ind[9][i] = ind[7][i] + 2; ind[4][i] = ind[1][i] + 3; ind[10][i] = ind[7][i] + 3; ind[5][i] = ind[1][i] + 4; ind[11][i] = ind[7][i] + 4; ind[6][i] = ind[1][i] + 5; ind[12][i] = ind[7][i] + 5; } for ( i = 1; i <= nE; i++ ) { elastic_K ( k, xyz, r, L[i], Le[i], N1[i], N2[i], Ax[i],Asy[i],Asz[i], Jx[i],Iy[i],Iz[i], E[i],G[i], p[i], shear); if (geom) geometric_K( k, xyz, r, L[i], Le[i], N1[i], N2[i], Ax[i], Asy[i],Asz[i], Jx[i], Iy[i], Iz[i], E[i],G[i], p[i], -Q[i][1], shear); if (debug) { res = sprintf(stiffness_fn,"k_%03d",i); save_dmatrix(stiffness_fn,k,1,12,1,12,0, "w"); } for ( l=1; l <= 12; l++ ) { ii = ind[l][i]; for ( ll=1; ll <= 12; ll++ ) { jj = ind[ll][i]; K[ii][jj] += k[l][ll]; } } } free_dmatrix ( k,1,12,1,12); free_imatrix(ind,1,12,1,nE); return; }
int main(int argc, char** argv) { long nrh, nrl, nch, ncl; byte** I; byte** binary; byte** droits; int theta, roMax, ro; int** tableRT; I = LoadPGM_bmatrix("route0.pgm", &nrl, &nrh, &ncl, &nch); binary = bmatrix(nrl, nrh, ncl, nch); roMax = sqrt(nrh * nrh + nch * nch); tableRT = imatrix(0, 179, 0, roMax); droits = bmatrix(0, 179, 0, roMax); int i, j; for (i = nrl; i < nrh; i++) { for (j = ncl; j < nch; j++) { if (I[i][j] >= 180) binary[i][j] = 255; else binary[i][j] = 0; } } for (theta = 0; theta < 180; theta++) { for (ro = 0; ro < roMax; ro++) { tableRT[theta][ro] = 0; } } for (theta = 0; theta < 180; theta++) { for (i = nrl; i < nrh; i++) { for (j = ncl; j < nch; j++) { if (I[i][j] >= 180) { ro = i * cos(rad(theta)) + j * sin(rad(theta)); tableRT[theta][abs(ro)]++; } } } } int max = 0; for (theta = 0; theta < 180; theta++) { for (ro = 0; ro < roMax; ro++) { if (tableRT[theta][ro] > max) { max = tableRT[theta][ro]; } } } SavePGM_bmatrix(binary, nrl, nrh, ncl, nch, "route_binary.pgm"); free_bmatrix(I, nrl, nrh, ncl, nch); free_bmatrix(binary, nrl, nrh, ncl, nch); return 0; }
int main(int argc, char* argv[]) { FILE *in; int **image_i; double *image_f = NULL; int N; int c; int coeff_start = 5000, wm_length = 10000; double wm_alpha = 0.2; pgm_init(&argc, argv); wm_init2(); while ((c = getopt(argc, argv, "a:s:l:")) != EOF) { switch (c) { case 'a': wm_alpha = atof(optarg); break; case 's': coeff_start = atoi(optarg); break; case 'l': wm_length = atoi(optarg); break; } } argc -= optind; argv += optind; in = stdin; open_image(in, &width, &height); image_i = imatrix(height, width); load_image(image_i, in, width, height); if (height == width) N = height; else { fprintf(stderr, "Cannot Proccess non-square images!\n"); exit( -11); } initialize_constants(); image_f = (double *)calloc(N * N, sizeof(double)); if (image_f == NULL) { printf("Unable to allocate the float array\n"); exit(1); } put_image_from_int_2_double(image_i, image_f, N); fct2d(image_f, N, N); read_watermark(image_f, N, coeff_start, wm_length, wm_alpha); fclose(in); freematrix(image_i, height); free(image_f); exit(EXIT_SUCCESS); }
AffineTransform AffineTransform::inverse() const { double determinant = det(); if (determinant == 0.0) return AffineTransform(); else { double dinv = 1.0 / determinant; AffineTransform imatrix((m_m22 * dinv), (-m_m12 * dinv), (-m_m21 * dinv), (m_m11 * dinv), ((m_m21 * m_dy - m_m22 * m_dx) * dinv), ((m_m12 * m_dx - m_m11 * m_dy) * dinv)); return imatrix; } }
INTMATRIX *new_intmatrix(long nrh,long nch) { INTMATRIX *m; m=(INTMATRIX *)malloc(sizeof(INTMATRIX)); if (!m) t_error("allocation failure in INTMATRIX()"); m->isdynamic=isDynamic; m->nrl=NL; m->nrh=nrh; m->ncl=NL; m->nch=nch; m->co=imatrix(1,nrh,1,nch); return m; }
QWMatrix QWMatrix::invert( bool *invertible ) const { double det = _m11*_m22 - _m12*_m21; if ( QABS(det) < 0.000001 ) { // very close to zero if ( invertible ) // (whatever that means...) *invertible = FALSE; // singular matrix QWMatrix defaultMatrix; return defaultMatrix; } else { // invertible matrix if ( invertible ) *invertible = TRUE; double dinv = 1.0/det; QWMatrix imatrix( (float)(_m22*dinv), (float)(-_m12*dinv), (float)(-_m21*dinv), (float)( _m11*dinv), (float)((_m21*_dy - _m22*_dx)*dinv), (float)((_m12*_dx - _m11*_dy)*dinv) ); return imatrix; } }
QWMatrix QWMatrix::invert( bool *invertible ) const { double det = _m11*_m22 - _m12*_m21; if ( det == 0.0 ) { if ( invertible ) *invertible = FALSE; // singular matrix QWMatrix defaultMatrix; return defaultMatrix; } else { // invertible matrix if ( invertible ) *invertible = TRUE; double dinv = 1.0/det; QWMatrix imatrix( (_m22*dinv), (-_m12*dinv), (-_m21*dinv), ( _m11*dinv), ((_m21*_dy - _m22*_dx)*dinv), ((_m12*_dx - _m11*_dy)*dinv) ); return imatrix; } }
int main(void) { int i,j,**nmbr; float ccc,chisq,cramrv,df,prob; char dummy[MAXSTR],fate[NDAT+1][16],mon[NMON+1][6],txt[16]; FILE *fp; nmbr=imatrix(1,NDAT,1,NMON); if ((fp = fopen("table1.dat","r")) == NULL) nrerror("Data file table1.dat not found\n"); fgets(dummy,MAXSTR,fp); fgets(dummy,MAXSTR,fp); fscanf(fp,"%16c",txt); txt[15]='\0'; for (i=1;i<=12;i++) fscanf(fp," %s",mon[i]); fgets(dummy,MAXSTR,fp); fgets(dummy,MAXSTR,fp); for (i=1;i<=NDAT;i++) { fscanf(fp,"%16[^0123456789]",fate[i]); fate[i][15]='\0'; for (j=1;j<=12;j++) fscanf(fp,"%d ",&nmbr[i][j]); } fclose(fp); printf("\n%s",txt); for (i=1;i<=12;i++) printf("%5s",mon[i]); printf("\n\n"); for (i=1;i<=NDAT;i++) { printf("%s",fate[i]); for (j=1;j<=12;j++) printf("%5d",nmbr[i][j]); printf("\n"); } cntab1(nmbr,NDAT,NMON,&chisq,&df,&prob,&cramrv,&ccc); printf("\n%15s chi-squared %20.2f\n"," ",chisq); printf("%15s degrees of freedom%20.2f\n"," ",df); printf("%15s probability %20.4f\n"," ",prob); printf("%15s cramer-v %20.4f\n"," ",cramrv); printf("%15s contingency coeff.%20.4f\n"," ",ccc); free_imatrix(nmbr,1,NDAT,1,NMON); return 0; }
/* * allocate memory for the matrices. placeholder can be an empty * floorplan frame with only the names of the functional units */ block_model_t *alloc_block_model(thermal_config_t *config, flp_t *placeholder) { /* shortcuts */ int n = placeholder->n_units; int m = NL*n+EXTRA; block_model_t *model = (block_model_t *) calloc (1, sizeof(block_model_t)); if (!model) fatal("memory allocation error\n"); model->config = *config; model->n_units = model->base_n_units = n; model->n_nodes = m; model->border = imatrix(n, 4); model->len = dmatrix(n, n); /* len[i][j] = length of shared edge bet. i & j */ model->g = dmatrix(m, m); /* g[i][j] = conductance bet. nodes i & j */ model->gx = dvector(n); /* lumped conductances in x direction */ model->gy = dvector(n); /* lumped conductances in y direction */ model->gx_int = dvector(n); /* lateral conductances in the interface layer */ model->gy_int = dvector(n); model->gx_sp = dvector(n); /* lateral conductances in the spreader layer */ model->gy_sp = dvector(n); model->gx_hs = dvector(n); /* lateral conductances in the heatsink layer */ model->gy_hs = dvector(n); /* vertical conductances to ambient */ model->g_amb = dvector(n+EXTRA); model->t_vector = dvector(m);/* scratch pad */ model->p = ivector(m); /* permutation vector for b's LUP decomposition */ model->a = dvector(m); /* vertical Cs - diagonal matrix stored as a 1-d vector */ model->inva = dvector(m); /* inverse of the above */ /* B, C and LU are (NL*n+EXTRA)x(NL*n+EXTRA) matrices */ model->b = dmatrix(m, m); model->c = dmatrix(m, m); model->lu = dmatrix(m, m); model->flp = placeholder; return model; }
void trexR(int *threshold, // input, threshold count of rare variants int *tablevec, // input, vector to fill 3x2 obsTable double *chistatObs, double *chi2sided, double *chi1sided, int *chistatSign, double *fisher2sided, double *fisher1sided, int *fisherSign, double *probExcluded) { // DECLARE OBJECTS FOR INPUT AND OUTPUT FROM PROGRAM static int verbose=0; // PREPARE DATA FOR TREX DRIVER int nrow=3; int ncol=2; int **obsTable = imatrix(1,nrow, 1,ncol); if(!obsTable) errmsg("Memory allocation failure for obsTable\n"); fillTable(tablevec, obsTable, nrow, ncol); // CALL TREX DRIVER trexDriver(*threshold, obsTable, chistatObs, chi2sided, chi1sided, chistatSign, fisher2sided, fisher1sided, fisherSign, probExcluded, verbose); // CLEAN MEMORY AND RETURN free_imatrix(obsTable, 1, nrow, 1, ncol); return; }
double calc_misfit(float **sectiondata, float **section, int ntr, int ns, int LNORM, float L2, int itest, int sws, int swstestshot,int ntr_glob, int **recpos_loc, int nsrc_glob, int ishot){ /* declaration of variables */ extern float DT; extern int MYID; extern int TRKILL; extern char TRKILL_FILE[STRING_SIZE]; float intseis, intseis_data, intseis_synthetics, abs_synthetics, abs_data; int i,j; float l2; float L2_dummy; int umax=0, h; /* declaration of variables for trace killing */ int ** kill_tmp, *kill_vector; char trace_kill_file[STRING_SIZE]; FILE *ftracekill; if(TRKILL){ kill_tmp = imatrix(1,ntr_glob,1,nsrc_glob); kill_vector = ivector(1,ntr); ftracekill=fopen(TRKILL_FILE,"r"); if (ftracekill==NULL) err(" Trace kill file could not be opened!"); for(i=1;i<=ntr_glob;i++){ for(j=1;j<=nsrc_glob;j++){ fscanf(ftracekill,"%d",&kill_tmp[i][j]); } } fclose(ftracekill); h=1; for(i=1;i<=ntr;i++){ kill_vector[h] = kill_tmp[recpos_loc[3][i]][ishot]; h++; } } /* end if(TRKILL)*/ /* calculate misfit */ for(i=1;i<=ntr;i++){ if((TRKILL==1)&&(kill_vector[i]==1)) continue; intseis = 0.0; intseis_data = 0.0; intseis_synthetics = 0.0; abs_data = 0.0; abs_synthetics = 0.0; L2_dummy=0.0; for(j=1;j<=ns;j++){ /*printf("%d \t %d \t %e \t %e \n",i,j,sectionpdata[i][j],sectionp[i][j]);*/ /* calculate L2 residuals */ if((LNORM==2) ||(LNORM==6)){ intseis += section[i][j]-sectiondata[i][j];} if(LNORM==5){ intseis_data += sectiondata[i][j]*DT; intseis_synthetics += section[i][j]*DT; abs_data += intseis_data*intseis_data; abs_synthetics += intseis_synthetics*intseis_synthetics; L2_dummy+=(intseis_data*intseis_synthetics);} /* calculate norm */ /*if((sws==1)&&(swstestshot==1)){*/ if(((LNORM==2) ||(LNORM==6)) &&(swstestshot==1)){ /*L2+=sectiondiff[i][invtime]*sectiondiff[i][invtime];*/ L2+=intseis*intseis*DT*DT; } } if(LNORM==5){ L2 -= L2_dummy/(sqrt(abs_data)*sqrt(abs_synthetics));} } l2=L2; return l2; /* free memory for trace killing */ if(TRKILL){ free_imatrix(kill_tmp,1,ntr_glob,1,nsrc_glob); free_ivector(kill_vector,1,ntr); } }
int main(int argn, char** args){ if (argn !=2 ) { printf("When running the simulation, please give a valid scenario file name!\n"); return 1; } //set the scenario char *filename = NULL; filename = args[1]; //initialize variables double t = 0; /*time start*/ int it, n = 0; /*iteration and time step counter*/ double res; /*residual for SOR*/ /*arrays*/ double **U, **V, **P; double **RS, **F, **G; int **Flag; //additional data structure for arbitrary geometry /*those to be read in from the input file*/ double Re, UI, VI, PI, GX, GY, t_end, xlength, ylength, dt, dx, dy, alpha, omg, tau, eps, dt_value; int imax, jmax, itermax; double presLeft, presRight, presDelta; //for pressure stuff int wl, wr, wt, wb; char problem[32]; double vel; //in case of a given inflow or wall velocity //read the parameters, using problem.dat, including wl, wr, wt, wb read_parameters(filename, &Re, &UI, &VI, &PI, &GX, &GY, &t_end, &xlength, &ylength, &dt, &dx, &dy, &imax, &jmax, &alpha, &omg, &tau, &itermax, &eps, &dt_value, &wl, &wr, &wt, &wb, problem, &presLeft, &presRight, &presDelta, &vel); int pics = dt_value/dt; //just a helping variable for outputing vtk //allocate memory, including Flag U = matrix(0, imax+1, 0, jmax+1); V = matrix(0, imax+1, 0, jmax+1); P = matrix(0, imax+1, 0, jmax+1); RS = matrix(1, imax, 1, jmax); F = matrix(0, imax, 1, jmax); G = matrix(1, imax, 0, jmax); Flag = imatrix(0, imax+1, 0, jmax+1); // or Flag = imatrix(1, imax, 1, jmax); int kmax = 20; //test no slip boundary value function double ***U3d = (double ***) malloc((size_t)((imax+1)*(jmax+1)*(kmax+1) * sizeof(double*)) ); //test no slip boundary value function double ***V3d = (double ***) malloc((size_t)((imax+1)*(jmax+1)*(kmax+1) * sizeof(double*)) ); //test no slip boundary value function double ***W3d = (double ***) malloc((size_t)((imax+1)*(jmax+1)*(kmax+1) * sizeof(double*)) ); //test no slip boundary value function int ***Flag3d = (int ***) malloc((size_t)((imax+1)*(jmax+1)*(kmax+1) * sizeof(int*)) ); //test no slip boundary value function //initialisation, including **Flag init_flag(problem, imax, jmax, presDelta, Flag); init_uvp(UI, VI, PI, imax, jmax, U, V, P, problem); //going through all time steps while(t < t_end){ //adaptive time stepping calculate_dt(Re, tau, &dt, dx, dy, imax, jmax, U, V); //setting bound.values boundaryvalues(imax, jmax, U, V, P, wl, wr, wt, wb, F, G, problem, Flag, vel); //including P, wl, wr, wt, wb, F, G, problem //test no slip boundary value function for(int i=1; i<=imax; i++){ for(int j=1; j<=jmax; j++){ for(int k=1; k<=kmax; k++){ boundaryvalues_no_slip(i, j, k, U3d, V3d, W3d, Flag3d); //test no slip boundary value function } } } //computing F, G and right hand side of pressue eq. calculate_fg(Re, GX, GY, alpha, dt, dx, dy, imax, jmax, U, V, F, G, Flag); calculate_rs(dt, dx, dy, imax, jmax, F, G, RS); //iteration counter it = 0; do{ // //perform SOR iteration, at same time set bound.values for P and new residual value sor(omg, dx, dy, imax, jmax, P, RS, &res, Flag, presLeft, presRight); it++; }while(it<itermax && res>eps); /* if (it == itermax) { printf("Warning: sor while loop exits because it reaches the itermax. res = %f, time =%f\n", res, t); } */ //calculate U and V of this time step calculate_uv(dt, dx, dy, imax, jmax, U, V, F, G, P, Flag); //indent time and number of time steps n++; t += dt; //output of pics for animation if (n%pics==0 ){ write_vtkFile(filename, n, xlength, ylength, imax, jmax, dx, dy, U, V, P); } } //output of U, V, P at the end for visualization //write_vtkFile("DrivenCavity", n, xlength, ylength, imax, jmax, dx, dy, U, V, P); //free memory free_matrix(U, 0, imax+1, 0, jmax+1); free_matrix(V, 0, imax+1, 0, jmax+1); free_matrix(P, 0, imax+1, 0, jmax+1); free_matrix(RS, 1, imax, 1, jmax); free_matrix(F, 0, imax, 1, jmax); free_matrix(G, 1, imax, 0, jmax); free_imatrix(Flag, 0, imax+1, 0, jmax+1); free(U3d); free(V3d); free(W3d); free(Flag3d); return -1; }
void Load_HO_Surface(char *name) { register int i,j; int np,nface,ntot,info; FILE *infile; char buf[BUFSIZ],*p; double *Rpts, *Spts; if(Loaded_Surf_File) return; // allow for multiple calls // check for .hsf file first sprintf(buf,"%s.hsf",strtok(name,".")); if(!(infile = fopen(buf,"r"))) { fprintf(stderr,"unable to open file %s or %s\n" "Run homesh on the .fro file to generate " "high order surface file \n",name,buf); exit(1); } // read header fgets(buf,BUFSIZ,infile); p = strchr(buf,'='); sscanf(++p,"%d",&np); p = strchr(p,'='); sscanf(++p,"%d",&nface); Snp = np; Snface = nface; ntot = np*(np+1)/2; Rpts = dvector(0,ntot-1); Spts = dvector(0,ntot-1); // read in point distribution in standard region fgets(buf,BUFSIZ,infile); fscanf(infile,"# %lf",Rpts); for(i = 1; i < ntot; ++i) fscanf(infile,"%lf",Rpts+i); fgets(buf,BUFSIZ,infile); fscanf(infile,"# %lf",Spts); for(i = 1; i < ntot; ++i) fscanf(infile,"%lf",Spts+i); fgets(buf,BUFSIZ,infile); fgets(buf,BUFSIZ,infile); SurXpts = dmatrix(0,nface-1,0,ntot-1); SurYpts = dmatrix(0,nface-1,0,ntot-1); SurZpts = dmatrix(0,nface-1,0,ntot-1); // read surface points for(i = 0; i < nface; ++i) { fgets(buf,BUFSIZ,infile); for(j = 0; j < ntot; ++j) { fgets(buf,BUFSIZ,infile); sscanf(buf,"%lf%lf%lf",SurXpts[i]+j,SurYpts[i]+j,SurZpts[i]+j); } // read input connectivity data for(j = 0; j < (np-1)*(np-1); ++j) fgets(buf,BUFSIZ,infile); } fgets(buf,BUFSIZ,infile); // read Vertids to match with .rea file surfids = imatrix(0,nface,0,4); for(i = 0; i < nface; ++i) { fgets(buf,BUFSIZ,infile); sscanf(buf,"# %*d%d%d%d",surfids[i],surfids[i]+1,surfids[i]+2); surfids[i][0]--; surfids[i][1]--; surfids[i][2]--; surfids[i][3] = surfids[i][0] + surfids[i][1] + surfids[i][2]; } Tri T; T.qa = Snp+1; T.qb = Snp; T.lmax = Snp; Basis *B = Tri_addbase(Snp,Snp+1,Snp,Snp); double av,bv,*hr,*hs,v1,v2; hr = dvector(0,Snp); hs = dvector(0,Snp); // setup collocation interpolation matrix CollMat = dmatrix(0,ntot-1,0,ntot-1); for(i = 0; i < ntot; ++i) { av = (fabs(1.0-Spts[i]) > FPTOL)? 2*(1+Rpts[i])/(1-Spts[i])-1: 0; bv = Spts[i]; Tri_get_point_shape(&T,av,bv,hr,hs); for(j =0; j < ntot; ++j) { v1 = ddot(Snp+1,hr,1,B->vert[j].a,1); v2 = ddot(Snp,hs,1,B->vert[j].b,1); CollMat[i][j] = v1*v2; } } Tri_reset_basis(B); CollMatIpiv = ivector(0,ntot-1); // invert matrix dgetrf(ntot,ntot,*CollMat,ntot,CollMatIpiv,info); if(info) fprintf(stderr,"Trouble factoring collocation matrix\n"); Loaded_Surf_File = 1; free(hr); free(hs); free(Rpts); free(Spts); }
void laplace_fourier_res(float **sectionvy_obs, float **sectionvy, float **sectiondiff, int ntr, int ntr_glob, int ns, int ishot, int nshots, int iter, int **recpos, int **recpos_loc, float **srcpos){ /* declaration of global variables */ extern float DT, DH, OFFSETC; extern int SEIS_FORMAT, MYID, NT, TIMEWIN; extern char SEIS_FILE_VY[STRING_SIZE], PARA[STRING_SIZE], DATA_DIR[STRING_SIZE]; extern int TRKILL, OFFSET_MUTE, GRAD_FORM; extern char TRKILL_FILE[STRING_SIZE]; /* declaration of variables for trace killing */ int ** kill_tmp, *kill_vector, h, j, i, Npad; char trace_kill_file[STRING_SIZE]; FILE *ftracekill; /* declaration of variables for offset-muting */ float offset, xr, yr, xs, ys; /* complex variables for source wavelet estimation */ fftw_complex *D_ss, *D_ss_fd; /* parameters for STA/LTA first arrival picking */ float *picked_times=NULL; /* variables for data integration */ int invtime; float **integrated_section=NULL, **integrated_sectiondata=NULL; float EPS_NORM; integrated_section = matrix(1,ntr,1,ns); integrated_sectiondata = matrix(1,ntr,1,ns); Npad = 2.0 * ns; Npad = (int)(pow(2.0, ceil(log((double)(Npad))/log(2.0))+2.0) ); EPS_NORM=1e0; /* Allocate memory */ D_ss = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * Npad); D_ss_fd = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * Npad); /* reverse time direction integrate data if GRAD_FORM=1 */ for(i=1;i<=ntr;i++){ invtime = ns; for(j=1;j<=ns;j++){ if(GRAD_FORM==1){ integrated_section[i][invtime] += DT*sectionvy[i][j]; integrated_sectiondata[i][invtime] += DT*sectionvy_obs[i][j]; } if(GRAD_FORM==2){ integrated_section[i][invtime] = sectionvy[i][j]; integrated_sectiondata[i][invtime] = sectionvy_obs[i][j]; } invtime--; } } /* pick first arrivals in the synthetic data with STA/LTA-picker and apply time window to field data before stf inversion */ /*if(TIMEWIN==3){ picked_times = vector(1,ntr); stalta(sectionvy, ntr, ns, picked_times, ishot); time_window_stf(sectionvy_obs, iter, ntr, ns, ishot); }*/ TIMEWIN=2; /* apply time damping to field and model data */ picked_times = vector(1,ntr); time_window(integrated_sectiondata,picked_times,iter,ntr_glob,recpos_loc,ntr,ns,ishot); time_window(integrated_section,picked_times,iter,ntr_glob,recpos_loc,ntr,ns,ishot); /* TRKILL==1 - trace killing is applied */ if(TRKILL){ kill_tmp = imatrix(1,nshots,1,ntr); kill_vector = ivector(1,ntr); ftracekill=fopen(TRKILL_FILE,"r"); if (ftracekill==NULL) err(" Trace kill file could not be opened!"); for(i=1;i<=nshots;i++){ for(j=1;j<=ntr;j++){ fscanf(ftracekill,"%d",&kill_tmp[i][j]); } } fclose(ftracekill); for(i=1;i<=ntr;i++){ kill_vector[i] = kill_tmp[ishot][i]; } for(i=1;i<=ntr;i++){ if(kill_vector[i]==1){ for(j=1;j<=ns;j++){ integrated_section[i][j]=0.0; integrated_sectiondata[i][j]=0.0; } } } } /* trace killing ends here */ /* apply offset mute */ if(OFFSET_MUTE){ /*printf("OFFSETC = %f \n",OFFSETC); printf("OFFSET_MUTE = %d \n",OFFSET_MUTE); */ for (i=1;i<=ntr;i++){ /* calculate source and receiver positions */ xr = recpos[1][recpos_loc[3][i]]*DH; xs = srcpos[1][ishot]; yr = recpos[2][recpos_loc[3][i]]*DH; ys = srcpos[2][ishot]; /* calculate absolute offset */ offset = sqrt(((xs-xr)*(xs-xr))+((ys-yr)*(ys-yr))); /* mute far-offset data*/ if((OFFSET_MUTE==1)&&(offset>=OFFSETC)){ for(j=1;j<=ns;j++){ integrated_section[i][j]=0.0; integrated_sectiondata[i][j]=0.0; } } /* mute near-offset data*/ if((OFFSET_MUTE==2)&&(offset<=OFFSETC)){ for(j=1;j<=ns;j++){ integrated_section[i][j]=0.0; integrated_sectiondata[i][j]=0.0; } } } } /* end of OFFSET_MUTE */ /* FFT of each data and model trace and calculation of nominator and denominator of Wiener deconvolution */ for(i=1;i<=ntr;i++){ /* allocate memory for complex variables */ fftw_complex *in_data, *out_data, *in_model, *out_model, *res_td, *res; fftw_plan p_data,p_model; in_data = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * Npad); out_data = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * Npad); in_model = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * Npad); out_model = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * Npad); res_td = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * Npad); res = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * Npad); /* define real and imaginary parts of data vectors and apply zero-padding */ for(j=0;j<Npad;j++){ if(j<ns){ in_model[j] = (integrated_section[i][j+1]) + 0.0*I; in_data[j] = (integrated_sectiondata[i][j+1]) + 0.0*I; } else{ in_model[j] = 0.0 + 0.0*I; in_data[j] = 0.0 + 0.0*I; } } /* apply FFTW */ p_data = fftw_plan_dft_1d(Npad, in_data, out_data, 1, FFTW_ESTIMATE); p_model = fftw_plan_dft_1d(Npad, in_model, out_model, 1, FFTW_ESTIMATE); fftw_execute(p_data); fftw_execute(p_model); /* calculate data residuals in the Laplace-Fourier domain (Jun etal., 2014)*/ for(j=0;j<Npad;j++){ /* real parts of the nominator and denominator */ res[j] = (1.0/out_model[j]+EPS_NORM)*conj(log(out_model[j]+EPS_NORM)-log(out_data[j]+EPS_NORM)); } /* inverse FFTW of data residuals */ fftw_plan p_stf; p_stf = fftw_plan_dft_1d(Npad, res, res_td, -1, FFTW_ESTIMATE); fftw_execute(p_stf); /* extract real part and write data to sectiondiff */ /*h=1; for(j=Npad;j>Npad-ns;j--){ sectiondiff[i][h]=creal(res_td[h])/Npad; h=h+1; }*/ for(j=1;j<=ns;j++){ sectiondiff[i][j] = integrated_section[i][j] - integrated_sectiondata[i][j]; } fftw_destroy_plan(p_data); fftw_free(in_data); fftw_free(out_data); fftw_destroy_plan(p_model); fftw_destroy_plan(p_stf); fftw_free(in_model); fftw_free(out_model); fftw_free(res); fftw_free(res_td); } /* free memory for trace killing and FFTW */ if(TRKILL){ free_imatrix(kill_tmp,1,nshots,1,ntr); free_ivector(kill_vector,1,ntr); } fftw_free(D_ss); fftw_free(D_ss_fd); free_vector(picked_times,1,ntr); free_matrix(integrated_section,1,ntr,1,ns); free_matrix(integrated_sectiondata,1,ntr,1,ns); }
void create_RC_matrices(flp_t *flp, int omit_lateral) { int i, j, k = 0, n = flp->n_units; int **border; double **len, *gx, *gy, **g, *c_ver, **t, *gx_sp, *gy_sp; double r_sp1, r_sp2, r_hs; /* lateral resistances to spreader and heatsink */ /* NOTE: *_mid - the vertical R/C from CENTER nodes of spreader * and heatsink. *_per - the vertical R/C from PERIPHERAL (n,s,e,w) nodes */ double r_sp_per, r_hs_mid, r_hs_per, c_sp_per, c_hs_mid, c_hs_per; double gn_sp=0, gs_sp=0, ge_sp=0, gw_sp=0; double w_chip = get_total_width (flp); /* x-axis */ double l_chip = get_total_height (flp); /* y-axis */ border = imatrix(n, 4); len = matrix(n, n); /* len[i][j] = length of shared edge bet. i & j */ gx = vector(n); /* lumped conductances in x direction */ gy = vector(n); /* lumped conductances in y direction */ gx_sp = vector(n); /* lateral conductances in the spreader layer */ gy_sp = vector(n); g = matrix(NL*n+EXTRA, NL*n+EXTRA); /* g[i][j] = conductance bet. nodes i & j */ c_ver = vector(NL*n+EXTRA); /* vertical capacitance */ b = matrix(NL*n+EXTRA, NL*n+EXTRA); /* B, C, INVA and INVB are (NL*n+EXTRA)x(NL*n+EXTRA) matrices */ c = matrix(NL*n+EXTRA, NL*n+EXTRA); inva = matrix(NL*n+EXTRA, NL*n+EXTRA); invb = matrix(NL*n+EXTRA, NL*n+EXTRA); t = matrix (NL*n+EXTRA, NL*n+EXTRA); /* copy of B */ /* compute the silicon fitting factor - see pg 10 of the UVA CS tech report - CS-TR-2003-08 */ factor_chip = C_FACTOR * ((SPEC_HEAT_INT / SPEC_HEAT_SI) * (w_chip + 0.88 * t_interface) \ * (l_chip + 0.88 * t_interface) * t_interface / ( w_chip * l_chip * t_chip) + 1); /* fitting factor for interface - same rationale as above */ factor_int = C_FACTOR * ((SPEC_HEAT_CU / SPEC_HEAT_INT) * (w_chip + 0.88 * t_spreader) \ * (l_chip + 0.88 * t_spreader) * t_spreader / ( w_chip * l_chip * t_interface) + 1); /*printf("fitting factors : %lf, %lf\n", factor_chip, factor_int); */ /* gx's and gy's of blocks */ for (i = 0; i < n; i++) { /* at the silicon layer */ if (omit_lateral) { gx[i] = gy[i] = 0; } else { gx[i] = 1.0/getr(K_SI, flp->units[i].height, flp->units[i].width, l_chip, t_chip); gy[i] = 1.0/getr(K_SI, flp->units[i].width, flp->units[i].height, w_chip, t_chip); } /* at the spreader layer */ gx_sp[i] = 1.0/getr(K_CU, flp->units[i].height, flp->units[i].width, l_chip, t_spreader); gy_sp[i] = 1.0/getr(K_CU, flp->units[i].width, flp->units[i].height, w_chip, t_spreader); } /* shared lengths between blocks */ for (i = 0; i < n; i++) for (j = i; j < n; j++) len[i][j] = len[j][i] = get_shared_len(flp, i, j); /* lateral R's of spreader and sink */ r_sp1 = getr(K_CU, (s_spreader+3*w_chip)/4.0, (s_spreader-w_chip)/4.0, w_chip, t_spreader); r_sp2 = getr(K_CU, (3*s_spreader+w_chip)/4.0, (s_spreader-w_chip)/4.0, (s_spreader+3*w_chip)/4.0, t_spreader); r_hs = getr(K_CU, (s_sink+3*s_spreader)/4.0, (s_sink-s_spreader)/4.0, s_spreader, t_sink); /* vertical R's and C's of spreader and sink */ r_sp_per = RHO_CU * t_spreader * 4.0 / (s_spreader * s_spreader - w_chip*l_chip); c_sp_per = factor_pack * SPEC_HEAT_CU * t_spreader * (s_spreader * s_spreader - w_chip*l_chip) / 4.0; r_hs_mid = RHO_CU * t_sink / (s_spreader*s_spreader); c_hs_mid = factor_pack * SPEC_HEAT_CU * t_sink * (s_spreader * s_spreader); r_hs_per = RHO_CU * t_sink * 4.0 / (s_sink * s_sink - s_spreader*s_spreader); c_hs_per = factor_pack * SPEC_HEAT_CU * t_sink * (s_sink * s_sink - s_spreader*s_spreader) / 4.0; /* short the R's from block centers to a particular chip edge */ for (i = 0; i < n; i++) { if (eq(flp->units[i].bottomy + flp->units[i].height, l_chip)) { gn_sp += gy_sp[i]; border[i][2] = 1; /* block is on northern border */ } if (eq(flp->units[i].bottomy, 0)) { gs_sp += gy_sp[i]; border[i][3] = 1; /* block is on southern border */ } if (eq(flp->units[i].leftx + flp->units[i].width, w_chip)) { ge_sp += gx_sp[i]; border[i][1] = 1; /* block is on eastern border */ } if (eq(flp->units[i].leftx, 0)) { gw_sp += gx_sp[i]; border[i][0] = 1; /* block is on western border */ } } /* overall R and C between nodes */ for (i = 0; i < n; i++) { double area = (flp->units[i].height * flp->units[i].width); /* * amongst functional units in the various layers * resistances in the interface layer are assumed * to be infinite */ for (j = 0; j < n; j++) { double part = 0, part_sp = 0; if (is_horiz_adj(flp, i, j)) { part = gx[i] / flp->units[i].height; part_sp = gx_sp[i] / flp->units[i].height; } else if (is_vert_adj(flp, i,j)) { part = gy[i] / flp->units[i].width; part_sp = gy_sp[i] / flp->units[i].width; } g[i][j] = part * len[i][j]; g[HSP*n+i][HSP*n+j] = part_sp * len[i][j]; } /* vertical g's in the silicon layer */ g[i][IFACE*n+i]=g[IFACE*n+i][i]=2.0/(RHO_SI * t_chip / area); /* vertical g's in the interface layer */ g[IFACE*n+i][HSP*n+i]=g[HSP*n+i][IFACE*n+i]=2.0/(RHO_INT * t_interface / area); /* vertical g's in the spreader layer */ g[HSP*n+i][NL*n+SP_B]=g[NL*n+SP_B][HSP*n+i]=2.0/(RHO_CU * t_spreader / area); /* C's from functional units to ground */ c_ver[i] = factor_chip * SPEC_HEAT_SI * t_chip * area; /* C's from interface portion of the functional units to ground */ c_ver[IFACE*n+i] = factor_int * SPEC_HEAT_INT * t_interface * area; /* C's from spreader portion of the functional units to ground */ c_ver[HSP*n+i] = factor_pack * SPEC_HEAT_CU * t_spreader * area; /* lateral g's from block center (spreader layer) to peripheral (n,s,e,w) spreader nodes */ g[HSP*n+i][NL*n+SP_N]=g[NL*n+SP_N][HSP*n+i]=2.0*border[i][2]/((1.0/gy_sp[i])+r_sp1*gn_sp/gy_sp[i]); g[HSP*n+i][NL*n+SP_S]=g[NL*n+SP_S][HSP*n+i]=2.0*border[i][3]/((1.0/gy_sp[i])+r_sp1*gs_sp/gy_sp[i]); g[HSP*n+i][NL*n+SP_E]=g[NL*n+SP_E][HSP*n+i]=2.0*border[i][1]/((1.0/gx_sp[i])+r_sp1*ge_sp/gx_sp[i]); g[HSP*n+i][NL*n+SP_W]=g[NL*n+SP_W][HSP*n+i]=2.0*border[i][0]/((1.0/gx_sp[i])+r_sp1*gw_sp/gx_sp[i]); } /* max slope (max_power * max_vertical_R / vertical RC time constant) for silicon */ max_slope = MAX_PD / (factor_chip * t_chip * SPEC_HEAT_SI); /* vertical g's and C's between central nodes */ /* between spreader bottom and sink bottom */ g[NL*n+SINK_B][NL*n+SP_B]=g[NL*n+SP_B][NL*n+SINK_B]=2.0/r_hs_mid; /* from spreader bottom to ground */ c_ver[NL*n+SP_B]=c_hs_mid; /* from sink bottom to ground */ c_ver[NL*n+SINK_B] = factor_pack * c_convec; /* g's and C's from peripheral(n,s,e,w) nodes */ for (i = 1; i <= 4; i++) { /* vertical g's between peripheral spreader nodes and spreader bottom */ g[NL*n+SP_B-i][NL*n+SP_B]=g[NL*n+SP_B][NL*n+SP_B-i]=2.0/r_sp_per; /* lateral g's between peripheral spreader nodes and peripheral sink nodes */ g[NL*n+SP_B-i][NL*n+SINK_B-i]=g[NL*n+SINK_B-i][NL*n+SP_B-i]=2.0/(r_hs + r_sp2); /* vertical g's between peripheral sink nodes and sink bottom */ g[NL*n+SINK_B-i][NL*n+SINK_B]=g[NL*n+SINK_B][NL*n+SINK_B-i]=2.0/r_hs_per; /* from peripheral spreader nodes to ground */ c_ver[NL*n+SP_B-i]=c_sp_per; /* from peripheral sink nodes to ground */ c_ver[NL*n+SINK_B-i]=c_hs_per; } /* calculate matrices A, B such that A(dT) + BT = POWER */ for (i = 0; i < NL*n+EXTRA; i++) { for (j = 0; j < NL*n+EXTRA; j++) { if (i==j) { inva[i][j] = 1.0/c_ver[i]; if (i == NL*n+SINK_B) /* sink bottom */ b[i][j] += 1.0 / r_convec; for (k = 0; k < NL*n+EXTRA; k++) { if ((g[i][k]==0.0)||(g[k][i])==0.0) continue; else /* here is why the 2.0 factor comes when calculating g[][] */ b[i][j] += 1.0/((1.0/g[i][k])+(1.0/g[k][i])); } } else { inva[i][j]=0.0; if ((g[i][j]==0.0)||(g[j][i])==0.0) b[i][j]=0.0; else b[i][j]=-1.0/((1.0/g[i][j])+(1.0/g[j][i])); } } } /* we are always going to use the eqn dT + A^-1 * B T = A^-1 * POWER. so, store C = A^-1 * B */ matmult(c, inva, b, NL*n+EXTRA); /* we will also be needing INVB so store it too */ copy_matrix(t, b, NL*n+EXTRA, NL*n+EXTRA); matinv(invb, t, NL*n+EXTRA); /* dump_vector(c_ver, NL*n+EXTRA); */ /* dump_matrix(g, NL*n+EXTRA, NL*n+EXTRA); */ /* dump_matrix(c, NL*n+EXTRA, NL*n+EXTRA); */ /* cleanup */ free_matrix(t, NL*n+EXTRA); free_matrix(g, NL*n+EXTRA); free_matrix(len, n); free_imatrix(border, n); free_vector(c_ver); free_vector(gx); free_vector(gy); free_vector(gx_sp); free_vector(gy_sp); }
static Gdinfo *ReadGridFile(FileList *f) { register int i,j,k; char buf[BUFSIZ]; int nel,npt,nbnd,vid,vid1,eid,eid1,**bndpts,trip; Gdinfo *ginfo = (Gdinfo *)malloc(sizeof(Gdinfo)); Cinfo *con,*c,*c1; FILE *fp = f->in.fp; /* read boundary condition file */ if(f->mesh.name) ReadBcond(f->mesh.fp,ginfo); fgets(buf,BUFSIZ,fp); fgets(buf,BUFSIZ,fp); sscanf(buf,"%d%d%d%*d",&nel,&npt,&nbnd); ginfo->nel = nel; ginfo->npt = npt; ginfo->nbnd = nbnd; ginfo->elmtpts = imatrix(0,nel-1,0,2); ginfo->x = dvector(0,npt-1); ginfo->y = dvector(0,npt-1); bndpts = imatrix(0,nel-1,0,2); ginfo->elmtcon = (Cinfo**)malloc(nel*sizeof(Cinfo *)); ginfo->elmtcon[0] = (Cinfo *)calloc(3*nel,sizeof(Cinfo) ); for(k = 1; k < nel; ++k) ginfo->elmtcon[k] = ginfo->elmtcon[k-1]+3; con = (Cinfo *)calloc(npt,sizeof(Cinfo)); /* read element vertex co-ordinate indices */ fgets(buf,BUFSIZ,fp); for(k = 0; k < nel; ++k) { fgets (buf,BUFSIZ,fp); sscanf(buf,"%*d%d%d%d",ginfo->elmtpts[k], ginfo->elmtpts[k]+1,ginfo->elmtpts[k]+2); } /* read co-ordinates */ fgets(buf,BUFSIZ,fp); for(k = 0; k < npt; ++k) { fgets (buf,BUFSIZ,fp); sscanf(buf,"%*d%lf%lf",ginfo->x+k,ginfo->y+k); } /* read boundary info */ fgets(buf,BUFSIZ,fp); for(k = 0; k < nbnd; ++k) { fgets (buf,BUFSIZ,fp); sscanf(buf,"%d%d%*d%d",bndpts[k],bndpts[k]+1,bndpts[k]+2); } /* sort out connectivity */ /* get list of all elements at a vertex */ for(k = 0; k < nel; ++k) for(i = 0; i < 3; ++i) addcon(con+ginfo->elmtpts[k][i]-1,k+1,i); /* search through element list and fill out element connectivity */ for(i = 0; i < npt; ++i) { for(c = con[i].next; c; c = c->next) { vid = (c->vsid+1)%3; eid = c->elmtid; for(c1 = con[i].next; c1; c1 = c1->next) { vid1 = (c1->vsid+2)%3; eid1 = c1->elmtid; if(ginfo->elmtpts[eid-1][vid] == ginfo->elmtpts[eid1-1][vid1]) { ginfo->elmtcon[eid -1][c->vsid].type = 'E'; ginfo->elmtcon[eid -1][c->vsid].elmtid = eid1; ginfo->elmtcon[eid -1][c->vsid].vsid = vid1; ginfo->elmtcon[eid1-1][vid1 ].type = 'E'; ginfo->elmtcon[eid1-1][vid1 ].elmtid = eid; ginfo->elmtcon[eid1-1][vid1 ].vsid = c->vsid; } } } } /* check through list and match any missing element with boundary values */ for(k = 0; k < nel; ++k) for(i = 0; i < 3; ++i) if(!ginfo->elmtcon[k][i].elmtid) { vid = ginfo->elmtpts[k][i]; vid1 = ginfo->elmtpts[k][(i+1)%3]; /* check to see that this side is a boundary */ for(j = 0,trip=1; j < nbnd; ++j) if(vid == bndpts[j][0] && vid1 == bndpts[j][1]) { /* set boundary condition from given values if present */ if(f->mesh.name) { register int i1; Bndinfo *b; Curinfo *c; for(b=ginfo->bnd; b; b = b->next) if(b->region == bndpts[j][2]) { ginfo->elmtcon[k][i].type = b->type; switch(b->type) { case 'W': case 'O': case 'S': case 'B': case 'M': case 'I': case 'Z': break; case 'V': case 'F': dcopy(b->nbcs,b->data.val,1,ginfo->elmtcon[k][i].f,1); break; case 'v': case 'f': case 'm': for(i1=0; i1 < b->nbcs; ++i1) ginfo->elmtcon[k][i].str[i1] = b->data.str[i1]; break; } } for(c=ginfo->curve; c; c = c->next) { if(c->region == bndpts[j][2]) { /* reset co-ordinates */ switch(c->type) { case 'C': /* arc */ { double theta; theta = atan2(ginfo->y[vid-1]-c->info.arc.yc, ginfo->x[vid-1]-c->info.arc.xc); ginfo->x[vid-1] = fabs(c->info.arc.radius)*cos(theta) + c->info.arc.xc; ginfo->y[vid-1] = fabs(c->info.arc.radius)*sin(theta) + c->info.arc.yc; theta = atan2(ginfo->y[vid1-1]-c->info.arc.yc, ginfo->x[vid1-1]-c->info.arc.xc); ginfo->x[vid1-1] = fabs(c->info.arc.radius)*cos(theta) + c->info.arc.xc; ginfo->y[vid1-1] = fabs(c->info.arc.radius)*sin(theta) + c->info.arc.yc; break; } } /* add curved information about element to ginfo */ addcurve(ginfo,k+1,i,c->idtype); } } } else ginfo->elmtcon[k][i].type = 'W'; trip=0; } if(trip) fprintf(stderr,"side %d of element %d using coordinate indices" " (%d,%d) is not a boundary\n",i+1,k+1,vid,vid1); } /* free the con list */ for(k = 0; k < npt; ++k) { c = con[k].next; while(c) { c1 = c->next; free(c); c = c1; } } free(con); free_imatrix(bndpts,0,0); return ginfo; }
Grid::Grid(char *fname){ register int i,j; char buf[BUFSIZ]; if(option("REAFILE")){ register int k,l; int dim; double **xloc, **yloc, **zloc; int **locvid; sprintf(buf, "%s.rea",strtok(fname,"\n")); domainname = strdup(buf); domainfile = fopen(domainname,"r"); if(!findSection("MESH",buf,domainfile)) {fputs("Grid_rea: Section not found\n", stderr); exit(-1);} get_next_line(domainfile, buf); sscanf(buf,"%d%d",&nel,&dim); if(dim != 3){ fputs("Grid_rea: Mesh is not 3D\n",stderr); exit(-1);} xloc = dmatrix(0,nel-1,0,Max_Nverts-1); yloc = dmatrix(0,nel-1,0,Max_Nverts-1); zloc = dmatrix(0,nel-1,0,Max_Nverts-1); nverts = ivector(0, nel-1); /* read local mesh */ for(k = 0; k < nel; k++) { get_next_line(domainfile, buf); /* element header */ if(strstr(buf,"Hex") || strstr(buf,"hex")){ fscanf(domainfile,"%lf%lf%lf%lf%lf%lf%lf%lf", xloc[k],xloc[k]+1,xloc[k]+2,xloc[k]+3,xloc[k]+4, xloc[k]+5,xloc[k]+6,xloc[k]+7); fscanf(domainfile,"%lf%lf%lf%lf%lf%lf%lf%lf", yloc[k],yloc[k]+1,yloc[k]+2,yloc[k]+3,yloc[k]+4, yloc[k]+5,yloc[k]+6,yloc[k]+7); fscanf(domainfile,"%lf%lf%lf%lf%lf%lf%lf%lf", zloc[k],zloc[k]+1,zloc[k]+2,zloc[k]+3,zloc[k]+4, zloc[k]+5,zloc[k]+6,zloc[k]+7); get_next_line(domainfile, buf); /* get remainder of line */ nverts[k] = 8; } else if(strstr(buf,"Prism") || strstr(buf,"prism")){ fscanf(domainfile,"%lf%lf%lf%lf%lf%lf", xloc[k],xloc[k]+1,xloc[k]+2,xloc[k]+3,xloc[k]+4,xloc[k]+5); fscanf(domainfile,"%lf%lf%lf%lf%lf%lf", yloc[k],yloc[k]+1,yloc[k]+2,yloc[k]+3,yloc[k]+4,yloc[k]+5); fscanf(domainfile,"%lf%lf%lf%lf%lf%lf", zloc[k],zloc[k]+1,zloc[k]+2,zloc[k]+3,zloc[k]+4,zloc[k]+5); get_next_line(domainfile, buf); /* get remainder of line */ nverts[k] = 6; } else if(strstr(buf,"Pyr") || strstr(buf,"pyr")){ fscanf(domainfile,"%lf%lf%lf%lf%lf", xloc[k],xloc[k]+1,xloc[k]+2,xloc[k]+3,xloc[k]+4); fscanf(domainfile,"%lf%lf%lf%lf%lf", yloc[k],yloc[k]+1,yloc[k]+2,yloc[k]+3,yloc[k]+4); fscanf(domainfile,"%lf%lf%lf%lf%lf", zloc[k],zloc[k]+1,zloc[k]+2,zloc[k]+3,zloc[k]+4); get_next_line(domainfile, buf); /* get remainder of line */ nverts[k] = 5; } else{ /* assume it is a tet */ fscanf(domainfile,"%lf%lf%lf%lf",xloc[k],xloc[k]+1,xloc[k]+2,xloc[k]+3); fscanf(domainfile,"%lf%lf%lf%lf",yloc[k],yloc[k]+1,yloc[k]+2,yloc[k]+3); fscanf(domainfile,"%lf%lf%lf%lf",zloc[k],zloc[k]+1,zloc[k]+2,zloc[k]+3); get_next_line(domainfile, buf); /* get remainder of line */ nverts[k] = 4; } } /* search through elements and search for similar elements */ vertids = imatrix(0,nel-1,0,Max_Nverts-1); ifill(nel*Max_Nverts,-1,vertids[0],1); totverts=0; for(k = 0; k < nel; ++k) for(i= 0; i < nverts[k]; ++i) if(vertids[k][i] == -1){ vertids[k][i] = totverts++; for(l = k+1; l < nel; ++l) for(j = 0; j < nverts[l]; ++j) if(vertids[l][j] == -1){ if(same(xloc[l][j],xloc[k][i]) && same(yloc[l][j],yloc[k][i]) && same(zloc[l][j],zloc[k][i])) vertids[l][j] = vertids[k][i]; } } xcoords = dvector(0, totverts-1); ycoords = dvector(0, totverts-1); zcoords = dvector(0, totverts-1); for(k = 0; k < nel; ++k) for(i= 0; i < nverts[k]; ++i){ xcoords[vertids[k][i]] = xloc[k][i]; ycoords[vertids[k][i]] = yloc[k][i]; zcoords[vertids[k][i]] = zloc[k][i]; } free_dmatrix(xloc,0,0); free_dmatrix(yloc,0,0); free_dmatrix(zloc,0,0); } else{ char language; sprintf(buf, strtok(fname, "\n")); domainname = strdup(buf); domainfile = fopen(domainname, "r"); get_next_line(domainfile, buf); sscanf(buf, "%c", &language); get_next_line(domainfile, buf); sscanf(buf, "%d", &totverts); xcoords = dvector(0, totverts-1); ycoords = dvector(0, totverts-1); zcoords = dvector(0, totverts-1); for(i=0;i<totverts;++i){ get_next_line(domainfile, buf); sscanf(buf, "%lf %lf %lf", xcoords+i, ycoords+i, zcoords+i); } get_next_line(domainfile, buf); sscanf(buf, "%d", &nel); nverts = ivector(0, nel-1); vertids = imatrix(0, nel-1, 0, Max_Nverts-1); ifill(nel*Max_Nverts, -1, vertids[0], 1); for(i=0;i<nel;++i){ get_next_line(domainfile, buf); sscanf(buf, "%d", nverts+i); switch(nverts[i]){ case 4: sscanf(buf, "%*d %d %d %d %d", vertids[i], vertids[i]+1, vertids[i]+2, vertids[i]+3); break; case 5: sscanf(buf, "%*d %d %d %d %d %d", vertids[i], vertids[i]+1, vertids[i]+2, vertids[i]+3, vertids[i]+4); break; case 6: sscanf(buf, "%*d %d %d %d %d %d %d", vertids[i], vertids[i]+1, vertids[i]+2, vertids[i]+3, vertids[i]+4, vertids[i]+5); break; case 8: sscanf(buf, "%*d %d %d %d %d %d %d %d %d", vertids[i], vertids[i]+1, vertids[i]+2, vertids[i]+3, vertids[i]+4, vertids[i]+5, vertids[i]+6, vertids[i]+7); break; } if(language == 'F'){ for(j=0;j<nverts[i];++j) vertids[i][j] -=1; } } } elmtids = ivector(0, nel-1); for(i=0;i<nel;++i) elmtids[i] = i; vertexmap = imatrix(0, nel-1, 0, Max_Nverts-1); ifill(nel*Max_Nverts, -1, vertexmap[0], 1); for(i=0;i<nel;++i) for(j=0;j<nverts[i];++j) vertexmap[i][j] = j; }
/* * Function to be called from Python */ static PyObject* py_smith_waterman_context(PyObject* self, PyObject* args) { char *seq1 = NULL; char *seq2 = NULL; char retstr[100] = {'\0'}; int len1, len2; int i, j; int gap_opening, gap_extension; static int ** similarity = NULL; PyArg_ParseTuple(args, "s#s#ii", &seq1, &len1, &seq2, &len2, &gap_opening, &gap_extension); if (!seq1 || !seq2) { sprintf (retstr, "no seq in py_smith_waterman_context"); return Py_BuildValue("s", retstr); } /* passing a matrix this way is all to painful, so we'll elegantyly hardcode it: */ if ( !similarity) { similarity = imatrix(ASCII_SIZE, ASCII_SIZE); if (!similarity) { sprintf (retstr, "error alloc matrix space"); return Py_BuildValue("s", retstr); } load_sim_matrix (similarity); } /**********************************************************************************/ //int gap_opening = -5; // used in 15_make_maps //int gap_extension = -3; //char gap_character = '-' //int gap_opening = -3; // used in 25_db_migration/06_make_alignments //int gap_extension = 0; char gap_character = '#'; int endgap = 0; int use_endgap = 0; int far_away = -1; int max_i = len1; int max_j = len2; // allocation, initialization int **F = NULL; char **direction = NULL; int *map_i2j = NULL; int *map_j2i = NULL; if ( ! (F= imatrix (max_i+1, max_j+1)) ) { sprintf (retstr, "error alloc matrix space"); return Py_BuildValue("s", retstr); } if ( ! (direction = cmatrix (max_i+1, max_j+1)) ) { sprintf (retstr, "error alloc matrix space"); return Py_BuildValue("s", retstr); } if (! (map_i2j = emalloc( (max_i+1)*sizeof(int))) ) { sprintf (retstr, "error alloc matrix space"); return Py_BuildValue("s", retstr); } if (! (map_j2i = emalloc( (max_j+1)*sizeof(int))) ) { sprintf (retstr, "error alloc matrix space"); return Py_BuildValue("s", retstr); } for (i=0; i<=max_i; i++) map_i2j[i]=far_away; for (j=0; j<=max_j; j++) map_j2i[j]=far_away; int F_max = far_away; int F_max_i = 0; int F_max_j = 0; int penalty = 0; int i_sim, j_sim, diag_sim, max_sim; int i_between_exons = 1; int j_between_exons = 1; // for (i=0; i<=max_i; i++) { if (i > 0) { if (seq1[i-1] == 'B') { i_between_exons = 0; } else if ( seq1[i-1] == 'Z'){ i_between_exons = 1; } } for (j=0; j<=max_j; j++) { if (j > 0) { if (seq2[j-1] == 'B') { j_between_exons = 0; } else if (seq2[j-1] == 'Z') { j_between_exons = 1; } } if ( !i && !j ){ F[0][0] = 0; direction[i][j] = 'd'; continue; } if ( i && j ){ /**********************************/ penalty = 0; if ( direction[i-1][j] == 'i' ) { // gap extension if (j_between_exons) { penalty = 0; } else { if (use_endgap && j==max_j){ penalty = endgap; } else { penalty = gap_extension; } } } else { // gap opening */ if (j_between_exons) { penalty = 0; } else { if (use_endgap && j==max_j){ penalty = endgap; } else{ penalty = gap_opening; } } } i_sim = F[i-1][j] + penalty; /**********************************/ penalty = 0; if ( direction[i][j-1] == 'j' ) { // gap extension if (i_between_exons) { penalty = 0; } else { if (use_endgap && i==max_i){ penalty = endgap; } else{ penalty = gap_extension; } } } else { // gap opening */ if (i_between_exons) { penalty = 0; } else { if (use_endgap && i==max_i){ penalty = endgap; } else { penalty = gap_opening; } } } j_sim = F[i][j-1] + penalty; /**********************************/ diag_sim = F[i-1][j-1] + similarity [seq1[i-1]][seq2[j-1]]; /**********************************/ max_sim = diag_sim; direction[i][j] = 'd'; if ( i_sim > max_sim ){ max_sim = i_sim; direction[i][j] = 'i'; } if ( j_sim > max_sim ) { max_sim = j_sim; direction[i][j] = 'j'; } } else if (j) { penalty = 0; if (j_between_exons) { penalty = 0; } else { if (use_endgap) { penalty = endgap; } else { if ( direction[i][j-1] =='j' ) { penalty = gap_extension; } else { penalty = gap_opening; } } } j_sim = F[i][j-1] + penalty; max_sim = j_sim; direction[i][j] = 'j'; } else if (i) { penalty = 0; if (i_between_exons) { penalty = 0; } else { if ( use_endgap) { penalty = endgap; } else { if ( direction[i-1][j] == 'i' ) { penalty = gap_extension; } else { penalty = gap_opening; } } } i_sim = F[i-1][j] + penalty; max_sim = i_sim; direction[i][j] = 'i'; } if (max_sim < 0.0 ) max_sim = 0.0; F[i][j] = max_sim; if ( F_max < max_sim ) { // TODO{ tie break here */ F_max = max_sim; F_max_i = i; F_max_j = j; } } } i = F_max_i; j = F_max_j; // aln_score = F[i][j] ; while ( i>0 || j >0 ){ if ( i<0 || j<0 ){ sprintf (retstr, "Retracing error"); return Py_BuildValue("s", retstr); } if (direction[i][j] == 'd'){ map_i2j [i-1] = j-1; map_j2i [j-1] = i-1; i-= 1; j-= 1; } else if (direction[i][j] == 'i') { map_i2j [i-1] = far_away; i-= 1 ; } else if (direction[i][j] == 'j') { map_j2i [j-1] = far_away; j-= 1 ; } else{ sprintf (retstr, "Retracing error"); return Py_BuildValue("s", retstr); } } char * aligned_seq_1 = NULL; char * aligned_seq_2 = NULL; /* (lets hope it gets properly freed in the main program */ if (! (aligned_seq_1 = emalloc( (len1+len2)*sizeof(char))) ) { sprintf (retstr, "error alloc array space"); return Py_BuildValue("s", retstr); } if (! (aligned_seq_2 = emalloc( (len1+len2)*sizeof(char))) ) { sprintf (retstr, "error alloc array space"); return Py_BuildValue("s", retstr); } i = 0; j = 0; int done = 0; int pos = 0; while (!done) { if (j>=max_j && i>=max_i){ done = 1; } else if (j<max_j && i<max_i){ if (map_i2j[i] == j){ aligned_seq_1[pos] = seq1[i]; aligned_seq_2[pos] = seq2[j]; i += 1; j += 1; } else if (map_i2j[i] < 0){ aligned_seq_1[pos] = seq1[i]; aligned_seq_2[pos] = gap_character; i += 1; } else if (map_j2i[j] < 0){ aligned_seq_1[pos] = gap_character; aligned_seq_2[pos] = seq2[j]; j += 1; } } else if (j<max_j){ aligned_seq_1[pos] = gap_character; aligned_seq_2[pos] = seq2[j]; j += 1; } else { aligned_seq_1[pos] = seq1[i]; aligned_seq_2[pos] = gap_character; i += 1; } pos ++; } free_imatrix(F); free_cmatrix(direction); free(map_i2j); free(map_j2i); return Py_BuildValue("ss", aligned_seq_1, aligned_seq_2 ); }
/* "buildhessian" constructs a block Hessian and associated projection matrix by application of the ANM. Atomic coordinates and block definitions are provided in 'coords' and 'blocks'; ANM parameters are provided in 'cutoff' and 'gamma'. On successful termination, the block Hessian is stored in 'hessian', and the projection matrix between block and all-atom spaces is in 'projection'. */ static PyObject *buildhessian(PyObject *self, PyObject *args, PyObject *kwargs) { PDB_File PDB; dSparse_Matrix PP,HH; PyArrayObject *coords, *blocks, *hessian, *projection; double *XYZ,*hess,*proj; long *BLK; double **HB; double cutoff = 15., gamma = 1., scl=1., mlo=1., mhi=-1.; int natm, nblx, bmx; int hsize,elm,bdim,i,j; static char *kwlist[] = {"coords", "blocks", "hessian", "projection", "natoms", "nblocks", "maxsize", "cutoff", "gamma", "scale", "memlo", "memhi", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOOOiii|ddddd", kwlist, &coords, &blocks, &hessian, &projection, &natm, &nblx, &bmx, &cutoff, &gamma, &scl, &mlo, &mhi)) return NULL; XYZ = (double *) PyArray_DATA(coords); BLK = (long *) PyArray_DATA(blocks); hess = (double *) PyArray_DATA(hessian); proj = (double *) PyArray_DATA(projection); /* First allocate a PDB_File object to hold the coordinates and block indices of the atoms. This wastes a bit of memory, but it prevents the need to re-write all of the RTB functions that are used in standalone C code. */ PDB.atom=malloc((size_t)((natm+2)*sizeof(Atom_Line))); if(!PDB.atom) return PyErr_NoMemory(); for(i=1;i<=natm;i++){ PDB.atom[i].model=BLK[i-1]; for(j=0;j<3;j++) PDB.atom[i].X[j]=XYZ[j*natm+i-1]; } /* Find the projection matrix */ hsize = 18*bmx*nblx > 12*natm ? 12*natm : 18*bmx*nblx; HH.IDX=imatrix(1,hsize,1,2); HH.X=dvector(1,hsize); elm=dblock_projections2(&HH,&PDB,natm,nblx,bmx); PP.IDX=imatrix(1,elm,1,2); PP.X=dvector(1,elm); for(i=1;i<=elm;i++){ PP.IDX[i][1]=HH.IDX[i][1]; PP.IDX[i][2]=HH.IDX[i][2]; PP.X[i]=HH.X[i]; } free_imatrix(HH.IDX,1,hsize,1,2); free_dvector(HH.X,1,hsize); dsort_PP2(&PP,elm,1); /* Calculate the block Hessian */ HB=dmatrix(1,6*nblx,1,6*nblx); bdim=calc_blessian_mem(&PDB,&PP,natm,nblx,elm,HB,cutoff,gamma,scl,mlo,mhi); /* Cast the block Hessian and projection matrix into 1D arrays. */ copy_prj_ofst(&PP,proj,elm,bdim); for(i=1;i<=bdim;i++) for(j=1;j<=bdim;j++) hess[bdim*(i-1)+j-1]=HB[i][j]; free(PDB.atom); free_imatrix(PP.IDX,1,elm,1,2); free_dvector(PP.X,1,elm); free_dmatrix(HB,1,6*nblx,1,6*nblx); Py_RETURN_NONE; }
int main(int argc, char** args){ double Re, UI, VI, PI, GX, GY, t_end, xlength, ylength, dt, dx, dy, alpha, omg, tau, eps, dt_value, t, res, dp, nu; double **U, **V, **P, **F, **G, **RS; double **K, **E; /* turbulent kinetic energy k, dissipation rate epsilon*/ double Fu, Fv; /* force integration variables */ double KI, EI, cn, ce, c1, c2; /* K and E: Initial values for k and epsilon */ int n, it, imax, jmax, itermax, pb, boundaries[4]; int fluid_cells; /* Number of fluid cells in our geometry */ int **Flag; /* Flagflield matrix */ char vtkname[200]; char pgm[200]; char problem[10]; /* Problem name */ char fname[200]; if(argc<2){ printf("No parameter file specified. Terminating...\n"); exit(1); } sprintf(fname, "%s%s", CONFIGS_FOLDER, args[1]); printf("%s\n",fname); read_parameters(fname, &Re, &UI, &VI, &PI, &GX, &GY, &t_end, &xlength, &ylength, &dt, &dx, &dy, &imax, &jmax, &alpha, &omg, &itermax, &eps, boundaries, &dp, &pb, &KI, &EI, &cn, &ce, &c1, &c2, pgm, &nu, problem); /* Allocate Flag matrix */ Flag = imatrix( 0, imax+1, 0, jmax+1 ); U = matrix ( 0 , imax+1 , 0 , jmax+1 ); V = matrix ( 0 , imax+1 , 0 , jmax+1 ); P = matrix ( 0 , imax+1 , 0 , jmax+1 ); F = matrix ( 0 , imax , 0 , jmax ); G = matrix ( 0 , imax , 0 , jmax ); RS = matrix ( 0 , imax , 0 , jmax ); K = matrix ( 0 , imax+1 , 0 , jmax+1 ); E = matrix ( 0 , imax+1 , 0 , jmax+1 ); /* Initialize values to the Flag, u, v and p */ init_flag(CONFIGS_FOLDER,pgm, imax, jmax, &fluid_cells, Flag ); init_uvp(UI, VI, PI, KI, EI, imax, jmax, U, V, P, K, E, Flag, problem ); printf("Problem: %s\n", problem ); printf( "xlength = %f, ylength = %f\n", xlength, ylength ); printf( "imax = %d, jmax = %d\n", imax, jmax ); printf( "dt = %f, dx = %f, dy = %f\n", dt, dx, dy); printf( "Number of fluid cells = %d\n", fluid_cells ); printf( "Reynolds number: %f\n\n", Re); t=.0; n=0; while( t <= t_end ){ boundaryvalues( imax, jmax, U, V, K, E, boundaries, Flag ); /* special inflow boundaries, including k and eps */ spec_boundary_val( problem, imax, jmax, U, V, K, E, Re, dp, cn, ylength); /* calculate new values for k and eps */ comp_KAEP(Re, nu, cn, ce, c1, c2, alpha, dt, dx, dy, imax, jmax, U, V, K, E, GX, GY, Flag); /* calculate new values for F and G */ calculate_fg( Re, GX, GY, alpha, dt, dx, dy, imax, jmax, U, V, F, G, K, E, nu, cn, Flag ); /* calculate right hand side */ calculate_rs( dt, dx, dy, imax, jmax, F, G, RS, Flag ); it = 0; res = 10000.0; while( it < itermax && fabs(res) > eps ){ sor( omg, dx, dy, imax, jmax, fluid_cells, P, RS, Flag, &res, problem, dp ); it++; } printf("[%5d: %f] dt: %f, sor iterations: %4d \n", n, t, dt, it); /* calculate new values for u and v */ calculate_uv( dt, dx, dy, imax, jmax, U, V, F, G, P, Flag ); t += dt; n++; } sprintf(vtkname, "%s%s", VISUA_FOLDER, args[1]); write_vtkFile( vtkname, 1, xlength, ylength, imax, jmax, dx, dy, U, V, P, K, E, Flag); comp_surface_force( Re, dx, dy, imax, jmax, U, V, P, Flag, &Fu, &Fv); printf( "\nProblem: %s\n", problem ); printf( "xlength = %f, ylength = %f\n", xlength, ylength ); printf( "imax = %d, jmax = %d\n", imax, jmax ); printf( "dt = %f, dx = %f, dy = %f\n", dt, dx, dy); printf( "Number of fluid cells = %d\n", fluid_cells ); printf( "Reynolds number: %f\n", Re); printf( "Drag force = %f Lift force = %f\n", Fu, Fv); /* free memory */ free_matrix(U,0,imax+1,0,jmax+1); free_matrix(V,0,imax+1,0,jmax+1); free_matrix(P,0,imax+1,0,jmax+1); free_matrix(K,0,imax+1,0,jmax+1); free_matrix(E,0,imax+1,0,jmax+1); free_matrix(F,0,imax,0,jmax); free_matrix(G,0,imax,0,jmax); free_matrix(RS,0,imax,0,jmax); free_imatrix(Flag,0,imax+1,0,jmax+1); return 0; }
main (int argc, char *argv[]){ int i,j,k; manager_init(); parse_util_args(argc, argv); iparam_set("LQUAD",3); iparam_set("MQUAD",3); iparam_set("NQUAD",3); iparam_set("MODES",iparam("LQUAD")-1); char *buf = (char*) calloc(BUFSIZ, sizeof(char)); char *fname = (char*) calloc(BUFSIZ, sizeof(char)); get_string("Enter name of input file", buf); sprintf(fname, strtok(buf, "\n")); Grid *grid = new Grid(fname); Grid *grida = new Grid(grid); grida->RenumberPrisms(); grida->FixPrismOrientation(); grid->ImportPrismOrientation(grida); grida->RemovePrisms(); grida->RemoveHexes(); grida->FixTetOrientation(); grid->ImportTetOrientation(grida); Element_List *U = grid->gen_aux_field(); int nel = U->nel; get_string("Enter name of output file", buf); sprintf(fname, strtok(buf, "\n")); FILE *fout = fopen(fname, "w"); int Nfields, Nbdry; get_int ("Enter number of fields", &Nfields); get_int ("Enter number of boundaries (including default)", &Nbdry); char **eqn = (char**) calloc(Nfields, sizeof(char*)); for(i=0;i<Nfields;++i){ eqn[i] = (char*)calloc(BUFSIZ, sizeof(char)); } Bndry *Bc; Bndry **Vbc = (Bndry**) calloc(Nfields, sizeof(Bndry*)); char *bndryeqn = (char*) calloc(BUFSIZ, sizeof(char)); int **bcmatrix = imatrix(0, U->nel-1, 0, Max_Nfaces-1); izero(U->nel*Max_Nfaces, bcmatrix[0], 1); int nb; char type; char curved, curvetype; Curve *cur; int curveid = 0; for(nb=0;nb<Nbdry;++nb){ if(nb != Nbdry-1){ fprintf(stderr, "#\nBoundary: %d\n#\n", nb+1); get_string("Enter function which has roots at boundary", bndryeqn); fprintf(stderr, "#\n"); } else{ fprintf(stderr, "#\nDefault Boundary:\n#\n"); } get_char("Enter character type\n(v=velocity)\n" "(W=wall)\n(O=outflow)\n(s=flux (Compressible only))\n", &type); fprintf(stderr, "#\n"); switch(type){ case 'W': case 'O': break; case 'v': case 's': for(i=0;i<Nfields;++i){ get_string("Enter function definition", eqn[i]); fprintf(stderr, "\n"); } } get_char("Is this boundary curved (y/n)?", &curved); if(curved == 'y'){ ++curveid; get_char("Enter curve type\n(S=sphere)\n(C=cylinder)\n(T=taurus)\n", &curvetype); switch(curvetype){ case 'S':{ double cx, cy, cz, cr; get_double("Enter center x-coord", &cx); get_double("Enter center y-coord", &cy); get_double("Enter center z-coord", &cz); get_double("Enter radius", &cr); cur = (Curve*) calloc(1, sizeof(Curve)); cur->type = T_Sphere; cur->info.sph.xc = cx; cur->info.sph.yc = cy; cur->info.sph.zc = cz; cur->info.sph.radius = cr; cur->id = curveid; break; } case 'C':{ double cx, cy, cz, cr; double ax, ay, az; get_double("Enter point on axis x-coord", &cx); get_double("Enter point on axis y-coord", &cy); get_double("Enter point on axis z-coord", &cz); get_double("Enter axis vector x-coord", &ax); get_double("Enter axis vector y-coord", &ay); get_double("Enter axis vector z-coord", &az); get_double("Enter radius", &cr); cur = (Curve*) calloc(1, sizeof(Curve)); cur->type = T_Cylinder; cur->info.cyl.xc = cx; cur->info.cyl.yc = cy; cur->info.cyl.zc = cz; cur->info.cyl.ax = ax; cur->info.cyl.ay = ay; cur->info.cyl.az = az; cur->info.cyl.radius = cr; cur->id = curveid; break; } } } if(nb == Nbdry-1) break; double res; Element *E; for(E=U->fhead;E;E=E->next){ for(i=0;i<E->Nfaces;++i){ for(j=0;j<E->Nfverts(i);++j){ vector_def("x y z",bndryeqn); vector_set(1, &(E->vert[E->fnum(i,j)].x), &(E->vert[E->fnum(i,j)].y), &(E->vert[E->fnum(i,j)].z), &res); if(fabs(res)> TOL) break; } if(j==E->Nfverts(i)){ if(curved == 'y'){ E->curve = (Curve*) calloc(1, sizeof(Curve)); memcpy(E->curve, cur, sizeof(Curve)); E->curve->face = i; } switch(type){ case 'W': case 'O': for(j=0;j<Nfields;++j){ Bc = E->gen_bndry(type, i, 0.); Bc->type = type; add_bc(&Vbc[j], Bc); } bcmatrix[E->id][i] = 1; break; case 'v': case 's': for(j=0;j<Nfields;++j){ Bc = E->gen_bndry(type, i, eqn[j]); Bc->type = type; add_bc(&Vbc[j], Bc); } bcmatrix[E->id][i] = 1; break; } } } } } char is_periodic; get_char("Is there periodicity in the x-direction (y/n)?", &is_periodic); if(is_periodic == 'y') get_double("Enter periodic length",&XPERIOD); get_char("Is there periodicity in the y-direction (y/n)?", &is_periodic); if(is_periodic == 'y') get_double("Enter periodic length",&YPERIOD); get_char("Is there periodicity in the z-direction (y/n)?", &is_periodic); if(is_periodic == 'y') get_double("Enter periodic length",&ZPERIOD); // Do remaining connections Element *E, *F; for(E=U->fhead;E;E=E->next) for(i=0;i<E->Nfaces;++i) if(!bcmatrix[E->id][i]) for(F=E;F;F=F->next) for(j=0;j<F->Nfaces;++j) if(!bcmatrix[F->id][j]) if(neighbourtest(E,i,F,j) && !(E->id == F->id && i==j)){ bcmatrix[E->id][i] = 2; bcmatrix[F->id][j] = 2; set_link(E,i,F,j); break; } // if the default bc is curved the make default bndries curved if(curved == 'y'){ for(E=U->fhead;E;E=E->next) for(i=0;i<E->Nfaces;++i) if(!bcmatrix[E->id][i]){ E->curve = (Curve*) calloc(1, sizeof(Curve)); memcpy(E->curve, cur, sizeof(Curve)); E->curve->face = i; } } fprintf(fout, "****** PARAMETERS *****\n"); fprintf(fout, " SolidMes \n"); fprintf(fout, " 3 DIMENSIONAL RUN\n"); fprintf(fout, " 0 PARAMETERS FOLLOW\n"); fprintf(fout, "0 Lines of passive scalar data follows2 CONDUCT; 2RHOCP\n"); fprintf(fout, " 0 LOGICAL SWITCHES FOLLOW\n"); fprintf(fout, "Dummy line from old nekton file\n"); fprintf(fout, "**MESH DATA** x,y,z, values of vertices 1,2,3,4.\n"); fprintf(fout, "%d 3 1 NEL NDIM NLEVEL\n", U->nel); for(E=U->fhead;E;E=E->next){ switch(E->identify()){ case Nek_Tet: fprintf(fout, "Element %d Tet\n", E->id+1); break; case Nek_Pyr: fprintf(fout, "Element %d Pyr\n", E->id+1); break; case Nek_Prism: fprintf(fout, "Element %d Prism\n", E->id+1); break; case Nek_Hex: fprintf(fout, "Element %d Hex\n", E->id+1); break; } for(i=0;i<E->Nverts;++i) fprintf(fout, "%lf ", E->vert[i].x); fprintf(fout, "\n"); for(i=0;i<E->Nverts;++i) fprintf(fout, "%lf ", E->vert[i].y); fprintf(fout, "\n"); for(i=0;i<E->Nverts;++i) fprintf(fout, "%lf ", E->vert[i].z); fprintf(fout, "\n"); } fprintf(fout, "***** CURVED SIDE DATA ***** \n"); fprintf(fout, "%d Number of curve types\n", curveid); for(i=0;i<curveid;++i){ int flag = 0; for(E=U->fhead;!flag && E;E=E->next){ if(E->curve && E->curve->type != T_Straight){ if(E->curve->id == i+1){ switch(E->curve->type){ case T_Sphere: fprintf(fout, "Sphere\n"); fprintf(fout, "%lf %lf %lf %lf %c\n", E->curve->info.sph.xc, E->curve->info.sph.yc, E->curve->info.sph.zc, E->curve->info.sph.radius, 'a'+i+1); flag = 1; break; case T_Cylinder: fprintf(fout, "Cylinder\n"); fprintf(fout, "%lf %lf %lf %lf %lf %lf %lf %c\n", E->curve->info.cyl.xc, E->curve->info.cyl.yc, E->curve->info.cyl.zc, E->curve->info.cyl.ax, E->curve->info.cyl.ay, E->curve->info.cyl.az, E->curve->info.cyl.radius, 'a'+i+1); flag = 1; break; } } } } } int ncurvedsides = 0; for(E=U->fhead;E;E=E->next){ if(E->curve && E->curve->type != T_Straight) ++ncurvedsides; } fprintf(fout, "%d Curved sides follow\n", ncurvedsides); for(E=U->fhead;E;E=E->next) if(E->curve && E->curve->type != T_Straight) fprintf(fout, "%d %d %c\n", E->curve->face+1, E->id+1, 'a'+E->curve->id); fprintf(fout, "***** BOUNDARY CONDITIONS ***** \n"); fprintf(fout, "***** FLUID BOUNDARY CONDITIONS ***** \n"); for(E=U->fhead;E;E=E->next){ for(j=0;j<E->Nfaces;++j){ if(bcmatrix[E->id][j] == 2){ fprintf(fout, "E %d %d %d %d\n", E->id+1, j+1, E->face[j].link->eid+1, E->face[j].link->id+1); } else if(bcmatrix[E->id][j] == 1){ for(i=0;i<Nfields;++i) for(Bc=Vbc[i];Bc;Bc=Bc->next){ if(Bc->elmt == E && Bc->face == j){ if(i==0) switch(Bc->type){ case 'W': fprintf(fout, "W %d %d 0. 0. 0.\n", E->id+1, j+1); break; case 'O': fprintf(fout, "O %d %d 0. 0. 0.\n", E->id+1, j+1); break; case 'v': fprintf(fout, "v %d %d 0. 0. 0.\n", E->id+1, j+1); break; case 's': fprintf(fout, "s %d %d 0. 0. 0.\n", E->id+1, j+1); break; } if(Bc->type == 's' || Bc->type == 'v') fprintf(fout, "%c=%s\n", 'u'+i,Bc->bstring); break; } } } else{ switch(type){ case 'W': fprintf(fout, "W %d %d 0. 0. 0.\n", E->id+1, j+1); break; case 'O': fprintf(fout, "O %d %d 0. 0. 0.\n", E->id+1, j+1); break; case 'v': fprintf(fout, "v %d %d 0. 0. 0.\n", E->id+1, j+1); break; case 's': fprintf(fout, "s %d %d 0. 0. 0.\n", E->id+1, j+1); break; } if(type == 's' || type == 'v') for(i=0;i<Nfields;++i) fprintf(fout, "%c=%s\n", 'u'+i,eqn[i]); } } } char bufa[BUFSIZ]; fprintf(fout, "***** NO THERMAL BOUNDARY CONDITIONS *****\n"); get_char("Are you using a field file restart (y/n)?", &type); if(type == 'y'){ fprintf(fout, "%d INITIAL CONDITIONS *****\n",1); get_string("Enter name of restart file:", buf); fprintf(fout, "Restart\n"); fprintf(fout, "%s\n", buf); } else{ fprintf(fout, "%d INITIAL CONDITIONS *****\n",1+Nfields); fprintf(fout, "Given\n"); for(i=0;i<Nfields;++i){ sprintf(bufa, "Field %d ", i+1); get_string(bufa, buf); fprintf(fout, "%s\n", buf); } } fprintf(fout, "***** DRIVE FORCE DATA ***** PRESSURE GRAD, FLOW, Q\n"); get_char("Are you using a forcing function (y/n)?", &type); if(type == 'y'){ fprintf(fout, "%d Lines of Drive force data follow\n", Nfields); for(i=0;i<Nfields;++i){ sprintf(bufa, "FF%c = ", 'X'+i); get_string(bufa,buf); fprintf(fout, "FF%c = %s\n",'X'+i, buf); } } else{ fprintf(fout, "0 Lines of Drive force data follow\n"); } fprintf(fout, "***** Variable Property Data ***** Overrrides Parameter data.\n"); fprintf(fout, " 1 Lines follow.\n"); fprintf(fout, " 0 PACKETS OF DATA FOLLOW\n"); fprintf(fout, "***** HISTORY AND INTEGRAL DATA *****\n"); get_char("Are you using history points (y/n)?", &type); if(type == 'y'){ int npoints; get_int ("Enter number of points", &npoints); fprintf(fout, " %d POINTS. Hcode, I,J,H,IEL\n", npoints); for(i=0;i<npoints;++i){ sprintf(bufa, "Enter element number for point %d", i+1); get_int(bufa,&j); sprintf(bufa, "Enter vertex number for point %d", i+1); get_int(bufa, &k); fprintf(fout, "UVWP H %d 1 1 %d\n", k, j); } } else{ fprintf(fout, " 0 POINTS. Hcode, I,J,H,IEL\n"); } fprintf(fout, " ***** OUTPUT FIELD SPECIFICATION *****\n"); fprintf(fout, " 0 SPECIFICATIONS FOLLOW\n"); return 0; }
int main(int argn, char** args){ double **U, **V, **P, **F, **G, **RS; const char *szFileName = "dam_break.dat"; double Re, UI, VI, PI, GX, GY, t_end, xlength, ylength, dt, dx, dy, alpha, omg, tau, eps, dt_value; double res = 0, t = 0, n = 0; int imax, jmax, itermax, it; /* Additional data structures for VOF */ double **fluidFraction; double **fluidFraction_alt; int **flagField; double **dFdx, **dFdy; int **pic; char output_dirname[60]; double epsilon = 1e-10; /* Read the program configuration file using read_parameters() */ read_parameters(szFileName, &Re, &UI, &VI, &PI, &GX, &GY, &t_end, &xlength, &ylength, &dt, &dx, &dy, &imax, &jmax, &alpha, &omg, &tau, &itermax, &eps, &dt_value); /* Set up the matrices (arrays) needed using the matrix() command */ U = matrix(0, imax , 0, jmax+1); V = matrix(0, imax+1, 0, jmax ); P = matrix(0, imax+1, 0, jmax+1); F = matrix(0, imax , 0, jmax+1); G = matrix(0, imax+1, 0, jmax ); RS= matrix(0, imax+1, 0, jmax+1); flagField = imatrix(0, imax+1, 0, jmax+1); fluidFraction = matrix(0, imax+1, 0, jmax+1); fluidFraction_alt = matrix(0, imax+1, 0, jmax+1); dFdx = matrix(0, imax+1, 0, jmax+1); dFdy = matrix(0, imax+1, 0, jmax+1); /*create a directory*/ strcpy(output_dirname, "dam_break/dam_break"); mkdir("dam_break", 0777); /* Read pgm file with domain and initial setting */ pic = read_pgm("dam_break.pgm"); init_fluidFraction(pic, fluidFraction,fluidFraction_alt, imax, jmax); /* Assign initial values to u, v, p */ init_uvp(UI, VI, PI, imax, jmax, U, V, P); /* Set valid values for the fluid fraction */ adjust_fluidFraction(fluidFraction, flagField, epsilon, imax, jmax); while(t <= t_end){ /*Select δt*/ calculate_dt(Re, tau, &dt, dx, dy, imax, jmax, U, V); /* Set boundary values for u and v */ /* boundaryvalues(imax, jmax, U, V, flagField, dx, dy); */ /* Compute F(n) and G(n) */ calculate_fg(Re, GX, GY, alpha, dt, dx, dy, imax, jmax, U, V, F, G, flagField); /* Compute the right-hand side rs of the pressure equation */ calculate_rs(dt, dx, dy, imax, jmax, F, G, RS, flagField); /* Determine the orientation of the free surfaces */ calculate_freeSurfaceOrientation(fluidFraction, flagField, dFdx, dFdy, dx, dy, imax, jmax); /* Perform SOR iterations */ it=0; res = 1e6; while(it < itermax && res > eps){ sor(omg, dx, dy, imax, jmax, P, RS, fluidFraction, flagField, dFdx, dFdy, &res); it++; } /* Compute u(n+1) and v(n+1) */ calculate_uv(dt, dx, dy, imax, jmax, U, V, F, G, P, flagField); boundaryvalues(imax, jmax, U, V, flagField, dx, dy); /* Compute fluidFraction(n+1) */ calculate_fluidFraction(fluidFraction,fluidFraction_alt, flagField, U, V, dFdx, dFdy, imax, jmax, dx, dy, dt); boundaryvalues(imax, jmax, U, V, flagField, dx, dy); /* Set valid values for the fluid fraction */ adjust_fluidFraction(fluidFraction, flagField, epsilon, imax, jmax); boundaryvalues(imax, jmax, U, V, flagField, dx, dy); if((int)n % 10 == 0) { write_vtkFile(output_dirname, n, xlength, ylength, imax, jmax, dx, dy, U, V, P, fluidFraction, flagField); } /* Print out simulation time and whether SOR converged */ printf("Time: %.4f", t); if(res > eps) {printf("\t*** Did not converge (res=%f, eps=%f)", res, eps);return -1;} printf("\n"); t = t + dt; n++; } free_matrix(U , 0, imax , 0, jmax+1); free_matrix(V , 0, imax+1, 0, jmax ); free_matrix(P , 0, imax+1, 0, jmax+1); free_matrix(F , 0, imax , 0, jmax+1); free_matrix(G , 0, imax+1, 0, jmax ); free_matrix(RS, 0, imax+1, 0, jmax+1); return -1; }
int main(int argc,char *argv[]) { Centroid *SYS,*ENV; Sprngmtx *Gamma; char *sysfile,*envfile,*massfile,*ctfile,*spgfile; double **GG; double *CUT,**HS,**HE,**HX,**PH,*P; double dd,x,y; int **CT,**PIX,nss,nen,nn,ntp,nse,r1,c1,r2,c2,i,j,k; int ptmd,rprm,pprm; /* Formalities */ read_command_line(argc,argv,&pprm,&rprm,&ptmd,&MSCL); /* Read coordinate and mass data */ sysfile=get_param(argv[pprm],"syscoords"); envfile=get_param(argv[pprm],"envcoords"); massfile=get_param(argv[pprm],"massfile"); SYS=read_centroids1(sysfile,massfile,&nss); ENV=read_centroids1(envfile,massfile,&nen); nn=nss+nen; fprintf(stderr,"System read from %s: %d centroids\n",sysfile,nss); fprintf(stderr,"Environment read from %s: %d centroids\n",envfile,nen); fprintf(stderr,"Masses read from %s\n",massfile); CT=imatrix(1,nn,1,nn); /* Find extent of membrane */ membounds(ENV,nen,&MHI,&MLO); /* Print masses, if called for */ if(ptmd==2){ for(i=1;i<=nss;i++) for(j=-2;j<=0;j++){ k=3*i+j; printf("%8d%8d% 25.15e\n",k,k,SYS[i].mass); } for(i=1;i<=nen;i++) for(j=-2;j<=0;j++){ k=3*nss+3*i+j; printf("%8d%8d% 25.15e\n",k,k,ENV[i].mass); } return 0; } /* ---------------- Assign contacts... ----------------- */ /* From a contact file... */ if((ctfile=get_param(argv[pprm],"contactfile"))!=NULL){ read_contacts(ctfile,CT,nn); fprintf(stderr,"Contacts read from %s\n",ctfile); } /* ...or from a cutoff file... */ else if((ctfile=get_param(argv[pprm],"cutfile"))!=NULL){ fprintf(stderr,"Cutoff values read from %s\n",ctfile); CUT=read_cutfile2(ctfile,SYS,ENV,nss,nen); radius_contact_sysenv(CT,SYS,ENV,nss,nen,CUT); } /* ...or from default values */ else{ CUT=dvector(1,nn); for(i=1;i<=nn;i++) CUT[i]=DEFCUT; fprintf(stderr,"All cutoff values set to %.3f\n",DEFCUT); radius_contact_sysenv(CT,SYS,ENV,nss,nen,CUT); } fprintf(stderr,"%d clusters\n",num_clusters(CT,nn)); if(ptmd==1){ fprintf(stderr,"Printing contacts\n"); for(i=1;i<=nn;i++) for(j=i+1;j<=nn;j++) if(CT[i][j]!=0) printf("%d\t%d\n",i,j); return 0; } /* ------- Construct the matrix of force constants -------*/ GG=dmatrix(1,nn,1,nn); /* Read force constants from file... */ if((spgfile=get_param(argv[pprm],"springfile"))!=NULL){ fprintf(stderr,"Reading spring constants from %s\n",spgfile); Gamma=read_springfile_sysenv(spgfile,SYS,ENV,nss,nen,&ntp); spring_constants_sysenv(SYS,ENV,GG,CT,Gamma,nss,nen,ntp); } /* ...or else assign the default value to all springs */ else for(i=1;i<=nn;i++) for(j=i;j<=nn;j++) if(CT[i][j]!=0) GG[i][j]=GG[j][i]=DEFGAM; /* Construct the mass-weighted Hessian from coordinates, masses, and potential matrix */ fprintf(stderr,"Calculating Hessian...\n"); HS=dmatrix(1,3*nss,1,3*nss); HE=dmatrix(1,3*nen,1,3*nen); HX=dmatrix(1,3*nss,1,3*nen); mwhess_sysenv(HS,HE,HX,SYS,ENV,GG,nss,nen); /* PRINT THE ENVIRONMENT-ENVIRONMENT SUB-HESSIAN IN SPARSE FORMAT */ if(ptmd==0 && rprm==-1){ fprintf(stderr,"\nPrinting env-env sub-hessian...\n\n"); for(i=1;i<=3*nen;i++) for(j=i;j<=3*nen;j++) if(fabs(HE[i][j])>1.0e-10) printf("%8d%8d% 25.15e\n",i,j,HE[i][j]); return 0; } /* PRINT THE FULL HESSIAN IN SPARSE FORMAT */ if(ptmd==3){ for(i=1;i<=3*nss;i++){ for(j=i;j<=3*nss;j++) if(fabs(HS[i][j])>1.0e-10) printf("%8d%8d% 20.10e\n",i,j,HS[i][j]); for(j=1;j<=3*nen;j++) if(fabs(HX[i][j])>1.0e-10) printf("%8d%8d% 20.10e\n",i,j+3*nss,HX[i][j]); } for(i=1;i<=3*nen;i++) for(j=i;j<=3*nen;j++) if(fabs(HE[i][j])>1.0e-10) printf("%8d%8d% 20.10e\n",i+3*nss,j+3*nss,HE[i][j]); return 0; } /* READ INVERSE OF ENVIRONMENTAL HESSIAN, OR INVERT HE */ free_imatrix(CT,1,nn,1,nn); free_dmatrix(GG,1,nn,1,nn); if(rprm!=-1){ fprintf(stderr,"Reading matrix from %s...\n",argv[rprm]); read_sparsemtx(argv[rprm],HE,3*nen,3*nen); } else{ fprintf(stderr,"\nWell...How did I get here?\n\n"); exit(1);} /* ---------------- CALCULATE AND PRINT THE PSEUDOHESSIAN ---------------- */ /* COUNT THE NUMBER OF NON-ZERO TERMS IN THE PROJECTION MATRIX */ nse=0; for(i=1;i<=3*nss;i++) for(j=1;j<=3*nen;j++) if(fabs(HX[i][j])>1.0e-9) nse++; fprintf(stderr,"%d non-zero projection elements\n",nse); P=dvector(1,nse); PIX=imatrix(1,nse,1,2); k=1; for(i=1;i<=3*nss;i++) for(j=1;j<=3*nen;j++) if(fabs(HX[i][j])>1.0e-9){ PIX[k][1]=i; PIX[k][2]=j; P[k]=HX[i][j]; k++; } free_dmatrix(HX,1,3*nss,1,3*nen); PH=dmatrix(1,3*nss,1,3*nss); for(i=1;i<=3*nss;i++) for(j=i;j<=3*nss;j++) PH[i][j]=PH[j][i]=0.0; for(i=1;i<=nse;i++){ r1=PIX[i][1]; c1=PIX[i][2]; x=P[i]; for(j=i;j<=nse;j++){ r2=PIX[j][1]; c2=PIX[j][2]; y=HE[c1][c2]*P[j]*x; PH[r1][r2]+=y; if(r1==r2 && c1!=c2) PH[r1][r2]+=y; } } for(i=1;i<=3*nss;i++) for(j=i;j<=3*nss;j++){ dd=HS[i][j]-PH[i][j]; if(fabs(dd)>1.0e-10) printf("%8d%8d% 25.15e\n",i,j,dd); } return 0; }
/* "calc_blessian_mem" calculates the block Hessian. */ int calc_blessian_mem(PDB_File *PDB,dSparse_Matrix *PP1,int nres,int nblx, int elm,double **HB,double cut,double gam,double scl, double mlo,double mhi) { dSparse_Matrix *PP2; double **HR,***HT; int **CT,*BST1,*BST2; int ii,i,j,k,p,q,q1,q2,ti,tj,bi,bj,sb,nc,out; /* ------------------- INITIALIZE LOCAL VARIABLES ------------------- */ /* HR holde three rows (corresponding to 1 residue) of the full Hessian */ HR=zero_dmatrix(1,3*nres,1,3); /* CT is an array of contacts between blocks */ CT=unit_imatrix(0,nblx); /* Copy PP1 to PP2 and sort by second element */ PP2=(dSparse_Matrix *)malloc((size_t)sizeof(dSparse_Matrix)); PP2->IDX=imatrix(1,elm,1,2); PP2->X=dvector(1,elm); copy_dsparse(PP1,PP2,1,elm); dsort_PP2(PP2,elm,2); /* BST1: for all j: BST1[i]<=j<BST[i+1], PP1->IDX[j][1]=i */ /* BST2: for all j: BST2[i]<=j<BST2[i+1], PP2->IDX[j][2]=i */ BST1=ivector(1,3*nres+1); BST2=ivector(1,6*nblx+1); init_bst(BST1,PP1,elm,3*nres+1,1); init_bst(BST2,PP2,elm,6*nblx+1,2); /* ------------------- LOCAL VARIABLES INITIALIZED ------------------ */ /* ------------- FIND WHICH BLOCKS ARE IN CONTACT --------------- */ nc=find_contacts1(CT,PDB,nres,nblx,cut); /* Allocate a tensor for the block Hessian */ HT=zero_d3tensor(1,nc,1,6,1,6); /* Calculate each super-row of the full Hessian */ for(ii=1;ii<=nres;ii++){ if(PDB->atom[ii].model!=0){ /* ----------------- FIND SUPER-ROW OF FULL HESSIAN --------------- */ hess_superrow_mem(HR,CT,PDB,nres,ii,cut,gam,scl,mlo,mhi); /* Update elements of block hessian */ q1=BST1[3*(ii-1)+2]; q2=BST1[3*(ii-1)+3]; /* Sum over elements of projection matrix corresponding to residue ii: for each k in the following loop, PP1->IDX[k][1]==3*ii + 0,1,2 */ for(k=BST1[3*ii-2];k<BST1[3*ii+1];k++){ if(k<q1) q=1; else if(k<q2) q=2; else q=3; i=PP1->IDX[k][2]; bi=(i-1)/6+1; ti=i-6*(bi-1); /* Sum over all elements of projection matrix with column j>=i */ for(p=BST2[i];p<=elm;p++){ j=PP2->IDX[p][2]; bj=(j-1)/6+1; sb=CT[bi][bj]; if(i<=j && sb!=0){ /* the first condition should ALWAYS hold */ tj=j-6*(bj-1); HT[sb][ti][tj]+=(PP1->X[k]*PP2->X[p]*HR[PP2->IDX[p][1]][q]); } } } } } /* Print the block Hessian in sparse format */ out=bless_from_tensor(HB,HT,CT,nblx); /* Free up memory */ free_dmatrix(HR,1,3*nres,1,3); free_d3tensor(HT,1,nc,1,6,1,6); free_imatrix(CT,0,nblx,0,nblx); free_ivector(BST1,1,3*nres+1); free_ivector(BST2,1,6*nblx+1); free_imatrix(PP2->IDX,1,elm,1,2); free_dvector(PP2->X,1,elm); return out; }
static int compute_tree_adaboost(ETree *etree,int n,int d,double *x[],int y[], int nmodels,int stumps, int minsize) { int i,b; int *samples; double **trx; int *try; double *prob; double *prob_copy; double sumalpha; double eps; int *pred; double *margin; double sumprob; if(nmodels<1){ fprintf(stderr,"compute_tree_adaboost: nmodels must be greater than 0\n"); return 1; } if(stumps != 0 && stumps != 1){ fprintf(stderr,"compute_tree_bagging: parameter stumps must be 0 or 1\n"); return 1; } if(minsize < 0){ fprintf(stderr,"compute_tree_bagging: parameter minsize must be >= 0\n"); return 1; } etree->nclasses=iunique(y,n, &(etree->classes)); if(etree->nclasses<=0){ fprintf(stderr,"compute_tree_adaboost: iunique error\n"); return 1; } if(etree->nclasses==1){ fprintf(stderr,"compute_tree_adaboost: only 1 class recognized\n"); return 1; } if(etree->nclasses==2) if(etree->classes[0] != -1 || etree->classes[1] != 1){ fprintf(stderr,"compute_tree_adaboost: for binary classification classes must be -1,1\n"); return 1; } if(etree->nclasses>2){ fprintf(stderr,"compute_tree_adaboost: multiclass classification not allowed\n"); return 1; } if(!(etree->tree=(Tree *)calloc(nmodels,sizeof(Tree)))){ fprintf(stderr,"compute_tree_adaboost: out of memory\n"); return 1; } if(!(etree->weights=dvector(nmodels))){ fprintf(stderr,"compute_tree_adaboost: out of memory\n"); return 1; } if(!(trx=(double **)calloc(n,sizeof(double*)))){ fprintf(stderr,"compute_tree_adaboost: out of memory\n"); return 1; } if(!(try=ivector(n))){ fprintf(stderr,"compute_tree_adaboost: out of memory\n"); return 1; } if(!(prob_copy=dvector(n))){ fprintf(stderr,"compute_tree_adaboost: out of memory\n"); return 1; } if(!(prob=dvector(n))){ fprintf(stderr,"compute_tree_adaboost: out of memory\n"); return 1; } if(!(pred=ivector(n))){ fprintf(stderr,"compute_tree_adaboost: out of memory\n"); return 1; } for(i =0;i<n;i++) prob[i]=1.0/(double)n; etree->nmodels=nmodels; sumalpha=0.0; for(b=0;b<nmodels;b++){ for(i =0;i<n;i++) prob_copy[i]=prob[i]; if(sample(n, prob_copy, n, &samples, TRUE,b)!=0){ fprintf(stderr,"compute_tree_adaboost: sample error\n"); return 1; } for(i=0;i<n;i++){ trx[i] = x[samples[i]]; try[i] = y[samples[i]]; } if(compute_tree(&(etree->tree[b]),n,d,trx,try,stumps,minsize)!=0){ fprintf(stderr,"compute_tree_adaboost: compute_tree error\n"); return 1; } free_ivector(samples); eps=0.0; for(i=0;i<n;i++){ pred[i]=predict_tree(&(etree->tree[b]),x[i],&margin); if(pred[i] < -1 ){ fprintf(stderr,"compute_tree_adaboost: predict_tree error\n"); return 1; } if(pred[i]==0 || pred[i] != y[i]) eps += prob[i]; free_dvector(margin); } if(eps > 0.0 && eps < 0.5){ etree->weights[b]=0.5 *log((1.0-eps)/eps); sumalpha+=etree->weights[b]; }else{ etree->nmodels=b; break; } sumprob=0.0; for(i=0;i<n;i++){ prob[i]=prob[i]*exp(-etree->weights[b]*y[i]*pred[i]); sumprob+=prob[i]; } if(sumprob <=0.0){ fprintf(stderr,"compute_tree_adaboost: sumprob = 0\n"); return 1; } for(i=0;i<n;i++) prob[i] /= sumprob; } if(etree->nmodels<=0){ fprintf(stderr,"compute_tree_adaboost: no models produced\n"); return 1; } if(sumalpha <=0){ fprintf(stderr,"compute_tree_adaboost: sumalpha = 0\n"); return 1; } for(b=0;b<etree->nmodels;b++) etree->weights[b] /= sumalpha; free(trx); free_ivector(try); free_ivector(pred); free_dvector(prob); free_dvector(prob_copy); return 0; } static void split_node(Node *node,Node *nodeL,Node *nodeR,int classes[], int nclasses) { int **indx; double *tmpvar; int i,j,k; int **npL , **npR; double **prL , **prR; int totL,totR; double a,b; double *decrease_in_inpurity; double max_decrease=0; int splitvar; int splitvalue; int morenumerous; nodeL->priors=dvector(nclasses); nodeR->priors=dvector(nclasses); nodeL->npoints_for_class=ivector(nclasses); nodeR->npoints_for_class=ivector(nclasses); indx=imatrix(node->nvar,node->npoints); tmpvar=dvector(node->npoints); decrease_in_inpurity=dvector(node->npoints-1); npL=imatrix(node->npoints,nclasses); npR=imatrix(node->npoints,nclasses); prL=dmatrix(node->npoints,nclasses); prR=dmatrix(node->npoints,nclasses); splitvar=0; splitvalue=0; max_decrease=0; for(i=0;i<node->nvar;i++){ for(j=0;j<node->npoints;j++) tmpvar[j]=node->data[j][i]; for(j=0;j<node->npoints;j++) indx[i][j]=j; dsort(tmpvar,indx[i],node->npoints,SORT_ASCENDING); for(k=0;k<nclasses;k++) if(node->classes[indx[i][0]]==classes[k]){ npL[0][k] = 1; npR[0][k] = node->npoints_for_class[k]-npL[0][k]; } else{ npL[0][k] = 0; npR[0][k] = node->npoints_for_class[k]; } for(j=1;j<node->npoints-1;j++) for(k=0;k<nclasses;k++) if(node->classes[indx[i][j]]==classes[k]){ npL[j][k] = npL[j-1][k] +1; npR[j][k] = node->npoints_for_class[k] - npL[j][k]; } else { npL[j][k] = npL[j-1][k]; npR[j][k] = node->npoints_for_class[k] - npL[j][k]; } for(j=0;j<node->npoints-1;j++){ if(node->data[indx[i][j]][i] != node->data[indx[i][j+1]][i]){ totL = totR = 0; for(k=0;k<nclasses;k++) totL += npL[j][k]; for(k=0;k<nclasses;k++) prL[j][k] = (double) npL[j][k] / (double) totL; for(k=0;k<nclasses;k++) totR += npR[j][k]; for(k=0;k<nclasses;k++) prR[j][k] = (double) npR[j][k] /(double) totR; a = (double) totL / (double) node->npoints; b = (double) totR / (double) node->npoints ; decrease_in_inpurity[j] = gini_index(node->priors,nclasses) - a * gini_index(prL[j],nclasses) - b * gini_index(prR[j],nclasses); } } for(j=0;j<node->npoints-1;j++) if(decrease_in_inpurity[j] > max_decrease){ max_decrease = decrease_in_inpurity[j]; splitvar=i; splitvalue=j; for(k=0;k<nclasses;k++){ nodeL->priors[k]=prL[splitvalue][k]; nodeR->priors[k]=prR[splitvalue][k]; nodeL->npoints_for_class[k]=npL[splitvalue][k]; nodeR->npoints_for_class[k]=npR[splitvalue][k]; } } } node->var=splitvar; node->value=(node->data[indx[splitvar][splitvalue]][node->var]+ node->data[indx[splitvar][splitvalue+1]][node->var])/2.; nodeL->nvar=node->nvar; nodeL->nclasses=node->nclasses; nodeL->npoints=splitvalue+1; nodeL->terminal=TRUE; if(gini_index(nodeL->priors,nclasses) >0) nodeL->terminal=FALSE; nodeL->data=(double **) calloc(nodeL->npoints,sizeof(double *)); nodeL->classes=ivector(nodeL->npoints); for(i=0;i<nodeL->npoints;i++){ nodeL->data[i] = node->data[indx[splitvar][i]]; nodeL->classes[i] = node->classes[indx[splitvar][i]]; } morenumerous=0; for(k=0;k<nclasses;k++) if(nodeL->npoints_for_class[k] > morenumerous){ morenumerous = nodeL->npoints_for_class[k]; nodeL->node_class=classes[k]; } nodeR->nvar=node->nvar; nodeR->nclasses=node->nclasses; nodeR->npoints=node->npoints-nodeL->npoints; nodeR->terminal=TRUE; if(gini_index(nodeR->priors,nclasses) >0) nodeR->terminal=FALSE; nodeR->data=(double **) calloc(nodeR->npoints,sizeof(double *)); nodeR->classes=ivector(nodeR->npoints); for(i=0;i<nodeR->npoints;i++){ nodeR->data[i] = node->data[indx[splitvar][nodeL->npoints+i]]; nodeR->classes[i] = node->classes[indx[splitvar][nodeL->npoints+i]]; } morenumerous=0; for(k=0;k<nclasses;k++) if(nodeR->npoints_for_class[k] > morenumerous){ morenumerous = nodeR->npoints_for_class[k]; nodeR->node_class=classes[k]; } free_imatrix(indx, node->nvar,node->npoints); free_imatrix(npL, node->npoints,nclasses); free_imatrix(npR, node->npoints,nclasses); free_dmatrix(prL, node->npoints,nclasses); free_dmatrix(prR, node->npoints,nclasses); free_dvector(tmpvar); free_dvector(decrease_in_inpurity); }
void Comnode(phylo t1, phylo t2) { int i, j, xnode, depth, common, matches1, matches2, p, q; int matchcode = 0; int t1md = 0; int t2md = 0; int *active_n; int *matched1; int *matched2; int **comlist1; // contents: node number of a term taxon (use to lookup name) // indexed by node, and then an index 0... int *comlist1n; // the number of items in *comlist int **comlist2; // contents: node number of a term taxon (use to lookup name) // indexed by node, and then an index 0... int *comlist2n; // the number of items in *comlist char tmp[50]; phylo Out[1]; strcpy(t1.phyname, "Tree1"); // t1.arenotes = 1; // t1.notes = cmatrix(0, t1.nnodes-1, 0, 49); strcpy(t2.phyname, "Tree2"); // t2.arenotes = 1; // t2.notes = cmatrix(0, t2.nnodes-1, 0, 49); comlist1 = imatrix(0, t1.nnodes-1, 0, t1.termtaxa); comlist1n = ivector(0, t1.nnodes-1); comlist2 = imatrix(0, t2.nnodes-1, 0, t2.termtaxa); comlist2n = ivector(0, t2.nnodes-1); matched1 = ivector(0, t1.termtaxa-1); matched2 = ivector(0, t2.termtaxa-1); // printf("t1: nnodes: %d taxa1: %s\n", t1.nnodes, t1.taxalist[0]); // printf("t2: nnodes: %d taxa1: %s\n", t2.nnodes, t2.taxalist[0]); // make a full list of term taxa from each node: // tree1: for (i = 0; i < t1.nnodes; i++) { if (t1.depth[i] > t1md) t1md = t1.depth[i]; // need to clear the node names - they could cause confusion // when bladjing, beacause the default names are the same for both // trees if (t1.noat[i] > 0) strcpy(t1.taxon[i], "."); // these will get unmaned: see fy2new } active_n = ivector(0, t1.nnodes-1); for (i = 0; i < t1.nnodes; i++) { active_n[i] = 1; comlist1n[i] = 0; for (depth = t1.depth[i]; depth <= t1md; depth++) { for (xnode = 0; xnode < t1.nnodes; xnode++) { if ( (t1.depth[xnode] == depth) && (active_n[xnode] == 1) ) { // first we check to see if we have reached a tip if (t1.noat[xnode] == 0) { // test to see that it is a common spp to tree 2 common = 0; for (j = 0; j < t2.termtaxa; j++) { if (strcmp(t1.taxon[xnode], t2.taxalist[j]) == 0)\ common = 1; } if (common ==1) { comlist1[i][comlist1n[i]] = xnode; comlist1n[i]++; //printf("1 dependent to node %d is %s\n", // i, t1.taxon[comlist1[i][comlist1n[i]-1]]); } active_n[xnode] = 0; } else { for (j = 0; j < t1.noat[xnode]; j++) { active_n[t1.down[xnode][j]] = 1; } active_n[xnode] = 0; } } } } } // make a full list of term taxa from each node: // tree2: for (i = 0; i < t2.nnodes; i++) { if (t2.depth[i] > t2md) t2md = t2.depth[i]; // need to clear the node names - they could cause confusion // when bladjing, beacause the default names are the same for both // trees if (t2.noat[i] > 0) strcpy(t2.taxon[i], "."); // these will get unmaned: see fy2new } active_n = ivector(0, t2.nnodes-1); for (i = 0; i < t2.nnodes; i++) { active_n[i] = 1; comlist2n[i] = 0; for (depth = t2.depth[i]; depth <= t2md; depth++) { for (xnode = 0; xnode < t2.nnodes; xnode++) { if ( (t2.depth[xnode] == depth) && (active_n[xnode] == 1) ) { // first we check to see if we have reached a tip if (t2.noat[xnode] == 0) { // test to see that it is a common spp to tree 2 common = 0; for (j = 0; j < t1.termtaxa; j++) { if (strcmp(t2.taxon[xnode], t1.taxalist[j]) == 0)\ common = 1; } if (common ==1) { comlist2[i][comlist2n[i]] = xnode; comlist2n[i]++; //printf("2 dependent to node %d is %s\n", // i, t2.taxon[comlist2[i][comlist2n[i]-1]]); } active_n[xnode] = 0; } else { for (j = 0; j < t2.noat[xnode]; j++) { active_n[t2.down[xnode][j]] = 1; } active_n[xnode] = 0; } } } } } // Now, compare the nodes (once only for each pair) for (i = 0; i < t1.nnodes; i++) { for (j = 0; j < t2.nnodes; j++) { // initialize: for (p = 0; p < comlist1n[i]; p++) matched1[p] = 0; for (q = 0; q < comlist2n[j]; q++) matched2[q] = 0; // here's the crux - each one must have the same sublist to be valid for (p = 0; p < comlist1n[i]; p++) { for(q= 0; q < comlist2n[j]; q++) { if (strcmp(t1.taxon[comlist1[i][p]], t2.taxon[comlist2[j][q]] ) ==0 ) { matched1[p] = 1; matched2[q] = 1; } } } // check matches matches1 = 0; matches2 = 0; for (p = 0; p < comlist1n[i]; p++) { if (matched1[p] == 1) matches1++; } for (q = 0; q < comlist2n[j]; q++) { if (matched2[q] == 1) matches2++; } if ( (matches1 == comlist1n[i]) && (matches2 == comlist2n[j]) && \ (matches1 > 1) && (matches2 > 1)) { sprintf(tmp, "match%d", matchcode++); //printf("tree1node%d matches with tree2node%d\n", i, j); // more correct, but need to just use nodenames for r8s: // strcat(t1.notes[i], tmp); strcat(t1.notes[i], " "); // strcat(t2.notes[j], tmp); strcat(t2.notes[j], " "); // for bladj (note the last one overrides the previous - this // will general be correct strcpy(t1.taxon[i], tmp); strcpy(t2.taxon[j], tmp); } } } // Unname the "." node names (a hack) for (i = 0; i < t1.nnodes; i++) { if (!strcmp(t1.taxon[i], ".")) strcpy(t1.taxon[i], ""); } for (i = 0; i < t2.nnodes; i++) { if (!strcmp(t2.taxon[i], ".")) strcpy(t2.taxon[i], ""); } printf("#NEXUS\n\nBEGIN TREES;\nTREE tree1 = "); Fy2newRec(t1); printf("TREE tree2 = "); Fy2newRec(t2); printf("END;\n"); Out[0] = t1; //WriteNexus(Out, 1, InS, 0 , InC, 0 ); Out[0] = t2; //WriteNexus(Out, 1, InS, 0 , InC, 0 ); }
int main ( int argc, char * argv[]) { char pdbname[150] = {'\0'}; char selection_file[150] = {'\0'}; Residue * sequence; int no_res, res_ctr; int * selected; double cutoff_dist, score; double **distmat; int ** cluster; int c; char chain_id = '\0'; FILE * fclust = NULL; if ( argc < 5 ) { fprintf (stderr, "Usage: %s <pdbfile> <chain id>|'-' <selection file> <cutoff dist> \n" "where selection file is of the format (for example) \n" "F 3 \n" "K 48 \n" "R 50 \n" "D 59 \n" "E 82 \n" "G 91 \n" "A 97 \n" "C 100 \n" "etc \n" "and the cutoff distance is given in Angstroms\n", argv[0]); exit (1); } sprintf ( pdbname, "%s", argv[1]); chain_id = argv[2][0]=='-' ? '\0' : argv[2][0]; sprintf ( selection_file, "%s", argv[3]); cutoff_dist = atof ( argv[4]); printf ("cutoff distance: %5.2lf Angstroms\n", cutoff_dist); /* input the structure */ if ( read_pdb ( pdbname, &chain_id, &sequence, &no_res) ) exit (1); printf ("there are %d residues in %s, chain %c.\n", no_res, pdbname, chain_id); /* input selection */ selected = emalloc (no_res*sizeof(int)); if (! selected) { fprintf (stderr, "error allocating selection array\n"); exit(1); // leaky, leaky } if ( read_selection (sequence, no_res, selection_file, selected) ) exit (1); /* allocate space for dist matrix */ distmat = (double**) dmatrix (0, no_res-1, 0, no_res-1); /* calculate dist */ if ( determine_dist_matrix(distmat, sequence, no_res) ) exit(1); /* cluster counting ... */ int no_of_clusters, max_size, secnd_max_size; int * cluster_count; int ** neighbors; int res1, res2; cluster_count = (int *) emalloc ( (no_res+1)*sizeof(int)); cluster = imatrix (0, no_res, 0, no_res); neighbors = imatrix (0, no_res-1, 0, no_res-1); for (res1=0; res1 < no_res; res1++ ) { neighbors [res1][res1] = 1; for (res2= res1+1; res2 < no_res; res2++ ) { neighbors[res1][res2] = ( distmat[res1][res2] < cutoff_dist); neighbors[res2][res1] = neighbors[res1][res2]; } } cluster_counter (no_res, neighbors, selected, cluster_count, & no_of_clusters, &max_size, &secnd_max_size , cluster); clustering_z_score ( no_res, neighbors, selected, &score); if (0) { printf ("runnning simulation ...\n"); int cluster_score (int no_of_res, int *seq, int ** adj_matrix,double *score); int i, n; int no_selected = 0; for (i=0; i<no_res; i++) no_selected += selected[i]; cluster_score (no_res, selected, neighbors, &score); printf (" selected %4d original cluster score = %8.2e\n", no_selected, score); double frac = (double)no_selected/no_res; double score = 0; for (n=0; n<100; n++) { // number of reps memset (selected, 0, no_res*sizeof(int)); for (i=0; i<no_res; i++) { if (drand48() < frac) selected[i] = 1; } cluster_score (no_res, selected, neighbors, &score); no_selected = 0; for (i=0; i<no_res; i++) no_selected += selected[i]; printf (" selected %4d random score = %8.2e\n", no_selected, score); } } /* output */ fclust = stdout; for ( c=0; c <= no_res; c++) { if ( ! cluster[c][0] ) { continue; } if ( !c ) { fprintf ( fclust,"\t isolated:\n"); } else { fprintf ( fclust,"\t cluster size: %3d \n", cluster[c][0]); } for ( res_ctr=1; res_ctr <= cluster[c][0]; res_ctr++) { fprintf ( fclust, "%s \n", sequence[ cluster[c][res_ctr] ].pdb_id ); } } fprintf (fclust, "\nclustering z-score: %8.3f\n", score); return 0; }