code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#include <stdio.h> #include <time.h> main() { time_t t0, t1; clock_t t; clock_t ct0, ct1; time( &t0); ct0 = clock(); printf("t0 = %d\n", t0); t = clock() + 3.1415926535*CLK_TCK; while( clock() < t){} time( &t1); ct1 = clock(); printf("t1 = %d\n", t1); printf(" t1- t0 = %f seconds\n", difftime( t1, t0)); printf("(ct1-ct0 = %f)/CLK_TCK = %f seconds\n", ((double)ct1 - (double)ct0), ((double)ct1 - (double)ct0)/(double)CLK_TCK); }
111pjb-one
src/ctimer.c
C
gpl3
469
#ifndef FLAGS_H #define FLAGS_H //############################################################################## // // flags.h // // - Preprocessor flags for lb2d_prime. // // Set VERBOSITY_LEVEL to correspond to how deep into nested loops to // print debug and related output. Stuff will be printed down to // loops nested VERBOSITY_LEVEL-1 deep. For example, // // VERBOSITY_LEVEL 0 ==> Nothing is printed, even outside of loops. // VERBOSITY_LEVEL 1 ==> Only stuff outside of loops is printed. // VERBOSITY_LEVEL 2 ==> Stuff inside the first level of loops is printed. // VERBOSITY_LEVEL 3 ==> Stuff inside the second level of loops is printed. // // Flag: VERBOSITY_LEVEL #define VERBOSITY_LEVEL 1 // If SAY_HI is on, some routines will display "hi" and "bye" messages // to stdout. // Flag: SAY_HI #define SAY_HI 0 // NUM_FLUID_COMPONENTS specifies the number of fluid components. // Flag: NUM_FLUID_COMPONENTS #define NUM_FLUID_COMPONENTS 1 // If NUM_FLUID_COMPONENTS is 2, the second component can be the sigma // component for solute (or thermal) transport as in Inamuro & Yoshino // by turning on INAMURO_SIGMA_COMPONENT . // Flag: INAMURO_SIGMA_COMPONENT #define INAMURO_SIGMA_COMPONENT ( 0 && NUM_FLUID_COMPONENTS==2) // Toggle Zhang & Chen energy transport method, PRE 67, 0066711 (2003). // Supposed to give thermodynamic consistency unlike old Shan & Chen method. // And supports general equation of state P = P(rho,T). // Utilizes the Inamuro component for evolution of the energy transport // equation. Employs modified compute_phase_force routine to compute // body force term representing non-local interaction potential U among // particles. // Flag: ZHANG_AND_CHEN_ENERGY_TRANSPORT #define ZHANG_AND_CHEN_ENERGY_TRANSPORT ( 0 && (INAMURO_SIGMA_COMPONENT)) // Simulate POROUS_MEDIA via a solid density parameter // as proposed by Dardis and McCloskey, // Phys Rev E, 57, 4, 4834-4837, 1998 // Flag: POROUS_MEDIA #define POROUS_MEDIA 0 // When there are two (or more) fluid components, a single velocity is // sometimes (always?) used to compute the equilibrium distribution // function. This single velocity will be called upr, and the // STORE_U_COMPOSITE flag will toggle its use. // Flag: STORE_U_COMPOSITE #define STORE_U_COMPOSITE ( 1 && ( (NUM_FLUID_COMPONENTS)==2 \ &&!((INAMURO_SIGMA_COMPONENT)))) // If DO_NOT_STORE_SOLIDS is on, then only the nodes necessary to flow are // stored. In this case, extra storage is needed for geometry information // (e.g. node neighbors). If the ratio of fluid nodes to solid nodes is // small (<~.7), this results in lower storage requirements. // Flag: DO_NOT_STORE_SOLIDS #define DO_NOT_STORE_SOLIDS 0 // NON_LOCAL_FORCES toggles any mechanisms for computing and storing // non-local (interaction) forces. // Flag: NON_LOCAL_FORCES #define NON_LOCAL_FORCES ( 1 && !(INAMURO_SIGMA_COMPONENT&&!ZHANG_AND_CHEN_ENERGY_TRANSPORT)) // The phase force weighting factors: // WM = weights in the direction of major axes // WD = weights in the direction of diagonals // According to Raskinmaki, it should be WM=2 and WD=1. // According to Chen (via correspondence) it should be WM=4 and WD=1. // According to Sukop and Thorne, it should be WM=1/9 and WD=1/36. // The corresonding G values (a.k.a. G, as in params.in) for the usual // equation of state that we like are -5, -10/3, and -120, respectively. // Flag: WM #define WM (1./ 9.) // Flag: WD #define WD (1./36.) // Toggle manage_body_force call at beginning of time loop for // gradually increasing/decreasing gravity. // Flag: MANAGE_BODY_FORCE #define MANAGE_BODY_FORCE 0 // Toggle break through curve (BTC) mechanism for sigma component. // Flag: STORE_BTC #define STORE_BTC ( 1 && INAMURO_SIGMA_COMPONENT) // // Toggle DETERMINE_FLOW_DIRECTION to attempt to determine the direction of // flow. // // Assigns FlowDir = { 0, 1, 2} = { indeterminate, vertical, horizontal} // // NOTE: This determination informs the breakthrough curve mechanism which // should be used in a simple situation with either pressure/velocity // boundaries driving the flow in one direction or gravity driving the flow // in one direction. If the direction of flow cannot be determined, FlowDir // will be set to indeterminate (=0) and a BTC will not be stored. // // NOTE: This determination also informs the sigma slip boundary which // should only be used in the simple situation of flow through a channel // where the geometry is trivial and the direction of flow is obvious. // // Flag: DETERMINE_FLOW_DIRECTION #define DETERMINE_FLOW_DIRECTION 1 // Toggle mechanism to initialize domain with ux_in or uy_in. This is // useful for setting a velocity in a periodic domain without using // fluid boundary conditions. // Flag: INITIALIZE_WITH_UX_IN #define INITIALIZE_WITH_UX_IN 0 // Flag: INITIALIZE_WITH_UY_IN #define INITIALIZE_WITH_UY_IN 1 // Dumping the density and velocity data to files can be time consuming and // take up a lot of disk space. If all that is needed is the BMP files, then // turn WRITE_MACRO_VAR_DAT_FILES off to save time and space. // Flag: WRITE_MACRO_VAR_DAT_FILES #define WRITE_MACRO_VAR_DAT_FILES 0 // Usually the density and velocity are written only for the active nodes // and in a way designed for post-processing. Additional files with the // variables written in a readable grid of all lattice nodes will be // generated when WRITE_RHO_AND_U_TO_TXT is on. This is done in an // inefficient way and is intended only for debugging purposes on tiny // lattices. Note that if WRITE_MACRO_VAR_DAT_FILES is off, this flag // has no effect. // Flag: WRITE_RHO_AND_U_TO_TXT #define WRITE_RHO_AND_U_TO_TXT 0 // WRITE_PDF_DAT_FILES is analogous to WRITE_MACRO_VAR_DAT_FILES. // Flag: WRITE_PDF_DAT_FILES #define WRITE_PDF_DAT_FILES 0 // WRITE_PDF_TO_TXT is analogous to WRITE_RHO_AND_U_TO_TXT. // Flag: WRITE_PDF_TO_TXT #define WRITE_PDF_TO_TXT 0 // Value used to represent an INACTIVE_NODE . This is used in the list // of neighbors ( struct node_struct::nn). It is also used in the // map from (i,j) space onto n index space in rho2bmp() and u2bmp(). // Flag: INACTIVE_NODE #define INACTIVE_NODE -1 // Negative densities (f_a) generally signify impending doom. The code // will die "gracefully" when this happens if PUKE_NEGATIVE_DENSITIES is on. // Might want to turn this off to boost performance on big, long runs that // are expected to survive without such instabilities. // Flag: PUKE_NEGATIVE_DENSITIES #define PUKE_NEGATIVE_DENSITIES 0 // Turn one of these on for coloring of the solids in bmp files. // Flag: SOLID_COLOR_IS_CHECKERBOARD #define SOLID_COLOR_IS_CHECKERBOARD 0 // Flag: SOLID_COLOR_IS_BLACK #define SOLID_COLOR_IS_BLACK 1 // Flag: DELAY #define DELAY 0 // Flag: END_GRAV #define END_GRAV 2000 // A single white pixel will be placed in at the (0,0) lattice node if // MARK_ORIGIN_FOR_REFERENCE is turned on. This is good for assisting with the // problem of tracking orientation of the results between regimes (e.g. C, BMP, // Matlab...). // Flag: MARK_ORIGIN_FOR_REFERENCE #define MARK_ORIGIN_FOR_REFERENCE 0 // Flag: PERTURBATIONS #define PERTURBATIONS 0 // If WRITE_CHEN_DAT_FILES is on, the code will output old style chen_*.dat // files to be processed by the old lb_rho_v*.m matlab scripts. // Flag: WRITE_CHEN_DAT_FILES #define WRITE_CHEN_DAT_FILES 0 #endif /* FLAGS_H */
111pjb-one
src/flags_scmp.h
C
gpl3
7,416
#include <studio.h> main() { FILE *in; in = fopen(); }
111pjb-one
src/area.c
C
gpl3
61
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // collide.c // #if POROUS_MEDIA //############################################################################## // // void collide( lattice_ptr lattice) // void collide( lattice_ptr lattice) { double *f; double omega; int bc_type; int n, a; int subs; double ns; double *ftemp, *feq; double *nsterm; int i, j; int ip, jp, in, jn; int LX = lattice->param.LX, LY = lattice->param.LY; #if SAY_HI printf("collide() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { for( n=0; n<lattice->NumNodes; n++) { feq = lattice->pdf[subs][n].feq; f = lattice->pdf[subs][n].f; ftemp = lattice->pdf[subs][n].ftemp; bc_type = lattice->bc[subs][n].bc_type; #if ZHANG_AND_CHEN_ENERGY_TRANSPORT force = lattice->force[subs][n].force; #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ if( !( bc_type & BC_SOLID_NODE)) { // C O L L I D E // f = ftemp - (1/tau[subs])( ftemp - feq) for( a=0; a<=8; a++) { #if 1 f[a] = ftemp[a] - ( ( ftemp[a] / lattice->param.tau[subs] ) - ( feq[a] / lattice->param.tau[subs] ) ); #else f[a] = ftemp[a] - ( ( ftemp[a] ) - ( feq[a] ) ) / lattice->param.tau[subs]; #endif } /* for( a=0; a<=8; a++) */ #if ZHANG_AND_CHEN_ENERGY_TRANSPORT if( subs==0) { // // Add the body force term, equation (8), // // f_i = f_i + \Delta f_i // // = f_i + \frac{w_i}{T_0} c_i \dot F // // Assuming the weights, w_i, are the ones from compute_feq. // // Zhang & Chen state T_0 to be 1/3 for D3Q19. The same in D2Q9. // f[1] += .00032*(vx[1]*3.*2.*force[0]); f[2] += .00032*(vy[2]*3.*2.*force[1]); f[3] += .00032*(vx[3]*3.*2.*force[0]); f[4] += .00032*(vy[4]*3.*2.*force[1]); f[5] += .00032*( 3.*( vx[5]*force[0] + vy[5]*force[1])); f[6] += .00032*( 3.*( vx[6]*force[0] + vy[6]*force[1])); f[7] += .00032*( 3.*( vx[7]*force[0] + vy[7]*force[1])); f[8] += .00032*( 3.*( vx[8]*force[0] + vy[8]*force[1])); } #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ #if PUKE_NEGATIVE_DENSITIES for( a=0; a<=8; a++) { if( *f < 0.) { printf("\n"); printf( "collide() -- Node %d (%d,%d), subs %d, " "has negative density %20.17f " "in direction %d " "at timestep %d. Exiting!\n", n, n%lattice->param.LX, n/lattice->param.LX, subs, f[a], a, lattice->time ); printf("\n"); process_exit(1); } } /* for( a=0; a<=8; a++) */ #endif /* PUKE_NEGATIVE_DENSITIES */ } /* if( !( bc_type & BC_SOLID_NODE)) */ else // bc_type & BC_SOLID_NODE { // B O U N C E B A C K if( lattice->param.bc_slip_north && n >= lattice->NumNodes - lattice->param.LX) { // Slip condition on north boundary. /* // A B C // \|/ \|/ // D-o-E --> D-o-E // /|\ /|\ // A B C */ f[1] = ftemp[1]; f[2] = ftemp[4]; f[3] = ftemp[3]; f[4] = ftemp[2]; f[5] = ftemp[8]; f[6] = ftemp[7]; f[7] = ftemp[6]; f[8] = ftemp[5]; } /* if( lattice->param.bc_slip_north && ... ) */ else { if( subs==0) { // Usual non-slip bounce-back condition. /* // A B C H G F // \|/ \|/ // D-o-E --> E-o-D // /|\ /|\ // F G H C B A */ f[1] = ftemp[3]; f[2] = ftemp[4]; f[3] = ftemp[1]; f[4] = ftemp[2]; f[5] = ftemp[7]; f[6] = ftemp[8]; f[7] = ftemp[5]; f[8] = ftemp[6]; } /* if( subs==0) */ #if NUM_FLUID_COMPONENTS==2 else // subs==1 { #if INAMURO_SIGMA_COMPONENT if( lattice->param.bc_sigma_slip) { // // Slip BC for solute on side walls. // Will this make a difference on Taylor dispersion? // if( lattice->FlowDir == /*Vertical*/2) { if( /*west*/(n )%lattice->param.LX == 0 || /*east*/(n+1)%lattice->param.LX == 0) { // Slip condition on east/west boundary. /* // A B C C B A // \|/ \|/ // D-o-E --> E-o-D // /|\ /|\ // F G H H G F */ f[1] = ftemp[3]; f[2] = ftemp[2]; f[3] = ftemp[1]; f[4] = ftemp[4]; f[5] = ftemp[6]; f[6] = ftemp[5]; f[7] = ftemp[8]; f[8] = ftemp[7]; } } else if( lattice->FlowDir == /*Horizontal*/1) { if( /*north*/ n >= lattice->NumNodes - lattice->param.LX || /*south*/ n < lattice->param.LX ) { // Slip condition on north/south boundary. /* // A B C F G H // \|/ \|/ // D-o-E --> D-o-E // /|\ /|\ // F G H A B C */ f[1] = ftemp[1]; f[2] = ftemp[4]; f[3] = ftemp[3]; f[4] = ftemp[2]; f[5] = ftemp[8]; f[6] = ftemp[7]; f[7] = ftemp[6]; f[8] = ftemp[5]; } else { // ERROR: Solid exists somewhere other than as side walls. printf("%s (%d) >> " "ERROR: " "bc_sigma_slip is on. " "FlowDir is determined to be horizontal. " "Encountered solid node somewhere other than side walls. " "That situation is not supported. " "Exiting!", __FILE__, __LINE__); process_exit(1); } } else { printf("%s (%d) >> " "FlowDir is indeterminate. " "Cannot apply slip BC (bc_sigma_slip). " "Exiting!", __FILE__, __LINE__); process_exit(1); } } /* if( lattice->param.bc_sigma_slip) */ else { #endif /* INAMURO_SIGMA_COMPONENT */ // Usual non-slip bounce-back condition. /* // A B C H G F // \|/ \|/ // D-o-E --> E-o-D // /|\ /|\ // F G H C B A */ f[1] = ftemp[3]; f[2] = ftemp[4]; f[3] = ftemp[1]; f[4] = ftemp[2]; f[5] = ftemp[7]; f[6] = ftemp[8]; f[7] = ftemp[5]; f[8] = ftemp[6]; #if INAMURO_SIGMA_COMPONENT } /* if( lattice->param.bc_sigma_slip) else */ #endif /* INAMURO_SIGMA_COMPONENT */ } /* if( subs==0) else*/ #endif /* NUM_FLUID_COMPONENTS==2 */ } /* if( lattice->param.bc_slip_north && ... ) else */ } /* if( !( bc_type & BC_SOLID_NODE)) else */ } /* for( n=0; n<lattice_NumNodes; n++) */ if( INAMURO_SIGMA_COMPONENT!=0 || subs==0) { // Need separate temp space for this? nsterm = (double*)malloc( 9*lattice->NumNodes*sizeof(double)); // Compute the solid density term for fluid component. for( n=0; n<lattice->NumNodes; n++) { bc_type = lattice->bc [subs][n].bc_type; i = n%LX; j = n/LX; jp = ( j<LY-1)?( j+1):( 0 ); jn = ( j>0 )?( j-1):( LY-1); ip = ( i<LX-1)?( i+1):( 0 ); in = ( i>0 )?( i-1):( LX-1); if( !( bc_type & BC_SOLID_NODE)) { if( lattice->param.ns_flag == 0) { ns = lattice->param.ns; /* 1 */ nsterm[9*n+1] = ns*( lattice->pdf[subs][ j *LX + ip].f[3] - lattice->pdf[subs][ j *LX + i ].f[1]); /* 2 */ nsterm[9*n+2] = ns*( lattice->pdf[subs][ jp*LX + i ].f[4] - lattice->pdf[subs][ j *LX + i ].f[2]); /* 3 */ nsterm[9*n+3] = ns*( lattice->pdf[subs][ j *LX + in].f[1] - lattice->pdf[subs][ j *LX + i ].f[3]); /* 4 */ nsterm[9*n+4] = ns*( lattice->pdf[subs][ jn*LX + i ].f[2] - lattice->pdf[subs][ j *LX + i ].f[4]); /* 5 */ nsterm[9*n+5] = ns*( lattice->pdf[subs][ jp*LX + ip].f[7] - lattice->pdf[subs][ j *LX + i ].f[5]); /* 6 */ nsterm[9*n+6] = ns*( lattice->pdf[subs][ jp*LX + in].f[8] - lattice->pdf[subs][ j *LX + i ].f[6]); /* 7 */ nsterm[9*n+7] = ns*( lattice->pdf[subs][ jn*LX + in].f[5] - lattice->pdf[subs][ j *LX + i ].f[7]); /* 8 */ nsterm[9*n+8] = ns*( lattice->pdf[subs][ jn*LX + ip].f[6] - lattice->pdf[subs][ j *LX + i ].f[8]); } else /* ns_flag==1 || ns_flag==2 */ { // Variable solid density. ns = lattice->ns[n].ns; //printf("%s %d >> ns = %f\n",__FILE__,__LINE__,ns); /* 1 */ nsterm[9*n+1] = ns*( lattice->pdf[subs][ j *LX + ip].f[3] - lattice->pdf[subs][ j *LX + i ].f[1]); /* 2 */ nsterm[9*n+2] = ns*( lattice->pdf[subs][ jp*LX + i ].f[4] - lattice->pdf[subs][ j *LX + i ].f[2]); /* 3 */ nsterm[9*n+3] = ns*( lattice->pdf[subs][ j *LX + in].f[1] - lattice->pdf[subs][ j *LX + i ].f[3]); /* 4 */ nsterm[9*n+4] = ns*( lattice->pdf[subs][ jn*LX + i ].f[2] - lattice->pdf[subs][ j *LX + i ].f[4]); /* 5 */ nsterm[9*n+5] = ns*( lattice->pdf[subs][ jp*LX + ip].f[7] - lattice->pdf[subs][ j *LX + i ].f[5]); /* 6 */ nsterm[9*n+6] = ns*( lattice->pdf[subs][ jp*LX + in].f[8] - lattice->pdf[subs][ j *LX + i ].f[6]); /* 7 */ nsterm[9*n+7] = ns*( lattice->pdf[subs][ jn*LX + in].f[5] - lattice->pdf[subs][ j *LX + i ].f[7]); /* 8 */ nsterm[9*n+8] = ns*( lattice->pdf[subs][ jn*LX + ip].f[6] - lattice->pdf[subs][ j *LX + i ].f[8]); } } /* if( !( *bc_type++ & BC_SOLID_NODE)) */ } /* for( n=0; n<lattice_NumNodes; n++) */ for( n=0; n<lattice->NumNodes; n++) { f = lattice->pdf[subs][n].f; bc_type = lattice->bc [subs][n].bc_type; if( !( bc_type & BC_SOLID_NODE)) { for( a=1; a<9; a++) { lattice->pdf[subs][n].ftemp[a] = f[a]; f[a] += nsterm[9*n+a]; } /* for( a=1; a<9; a++) */ } /* if( !( bc_type & BC_SOLID_NODE)) */ } /* for( n=0; n<lattice->NumNodes; n++, f+=18) */ free( nsterm); } /* if( INAMURO_SIGMA_COMPONENT!=0 || subs==0) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("collide() -- Bye!\n"); #endif /* SAY_HI */ } /* void collide( lattice_ptr lattice) */ #else /* !( POROUS_MEDIA) */ //############################################################################## // // void collide( lattice_ptr lattice) // void collide( lattice_ptr lattice) { double *feq; double *f; double *ftemp; #if ZHANG_AND_CHEN_ENERGY_TRANSPORT double *force; #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ double omega; int bc_type; int n, a; int subs; #if SAY_HI printf("collide() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { for( n=0; n<lattice->NumNodes; n++) { feq = lattice->pdf[subs][n].feq; f = lattice->pdf[subs][n].f; ftemp = lattice->pdf[subs][n].ftemp; bc_type = lattice->bc[subs][n].bc_type; #if ZHANG_AND_CHEN_ENERGY_TRANSPORT force = lattice->force[subs][n].force; #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ #if INAMURO_SIGMA_COMPONENT if( ( get_bc_sigma_walls(lattice) && subs==1) || !( bc_type & BC_SOLID_NODE)) #else /* !(INAMURO_SIGMA_COMPONENT) */ if( !( bc_type & BC_SOLID_NODE)) #endif /* (INAMURO_SIGMA_COMPONENT) */ { // C O L L I D E // f = ftemp - (1/tau[subs])( ftemp - feq) for( a=0; a<=8; a++) { #if 1 f[a] = ftemp[a] - ( ( ftemp[a] / lattice->param.tau[subs] ) - ( feq[a] / lattice->param.tau[subs] ) ); #else f[a] = ftemp[a] - ( ( ftemp[a] ) - ( feq[a] ) ) / lattice->param.tau[subs]; #endif } /* for( a=0; a<=8; a++) */ #if ZHANG_AND_CHEN_ENERGY_TRANSPORT if( subs==0) { // // Add the body force term, equation (8), // // f_i = f_i + \Delta f_i // // = f_i + \frac{w_i}{T_0} c_i \dot F // // Assuming the weights, w_i, are the ones from compute_feq. // // Zhang & Chen state T_0 to be 1/3 for D3Q19. The same in D2Q9. // f[1] += .00032*(vx[1]*3.*2.*force[0]); f[2] += .00032*(vy[2]*3.*2.*force[1]); f[3] += .00032*(vx[3]*3.*2.*force[0]); f[4] += .00032*(vy[4]*3.*2.*force[1]); f[5] += .00032*( 3.*( vx[5]*force[0] + vy[5]*force[1])); f[6] += .00032*( 3.*( vx[6]*force[0] + vy[6]*force[1])); f[7] += .00032*( 3.*( vx[7]*force[0] + vy[7]*force[1])); f[8] += .00032*( 3.*( vx[8]*force[0] + vy[8]*force[1])); } #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ #if PUKE_NEGATIVE_DENSITIES for( a=0; a<=8; a++) { if( *f < 0.) { printf("\n"); printf( "collide() -- Node %d (%d,%d), subs %d, " "has negative density %20.17f " "in direction %d " "at timestep %d. Exiting!\n", n, n%lattice->param.LX, n/lattice->param.LX, subs, f[a], a, lattice->time ); printf("\n"); process_exit(1); } } /* for( a=0; a<=8; a++) */ #endif /* PUKE_NEGATIVE_DENSITIES */ } /* if( !( bc_type & BC_SOLID_NODE)) */ else // bc_type & BC_SOLID_NODE { // B O U N C E B A C K if( lattice->param.bc_slip_north && n >= lattice->NumNodes - lattice->param.LX) { // Slip condition on north boundary. /* // A B C // \|/ \|/ // D-o-E --> D-o-E // /|\ /|\ // A B C */ f[1] = ftemp[1]; f[2] = ftemp[4]; f[3] = ftemp[3]; f[4] = ftemp[2]; f[5] = ftemp[8]; f[6] = ftemp[7]; f[7] = ftemp[6]; f[8] = ftemp[5]; } /* if( lattice->param.bc_slip_north && ... ) */ else { if( subs==0) { // Usual non-slip bounce-back condition. /* // A B C H G F // \|/ \|/ // D-o-E --> E-o-D // /|\ /|\ // F G H C B A */ f[1] = ftemp[3]; f[2] = ftemp[4]; f[3] = ftemp[1]; f[4] = ftemp[2]; f[5] = ftemp[7]; f[6] = ftemp[8]; f[7] = ftemp[5]; f[8] = ftemp[6]; } /* if( subs==0) */ #if NUM_FLUID_COMPONENTS==2 else // subs==1 { #if INAMURO_SIGMA_COMPONENT if( lattice->param.bc_sigma_slip) { // // Slip BC for solute on side walls. // Will this make a difference on Taylor dispersion? // if( lattice->FlowDir == /*Vertical*/2) { if( /*west*/(n )%lattice->param.LX == 0 || /*east*/(n+1)%lattice->param.LX == 0) { // Slip condition on east/west boundary. /* // A B C C B A // \|/ \|/ // D-o-E --> E-o-D // /|\ /|\ // F G H H G F */ f[1] = ftemp[3]; f[2] = ftemp[2]; f[3] = ftemp[1]; f[4] = ftemp[4]; f[5] = ftemp[6]; f[6] = ftemp[5]; f[7] = ftemp[8]; f[8] = ftemp[7]; } } else if( lattice->FlowDir == /*Horizontal*/1) { if( /*north*/ n >= lattice->NumNodes - lattice->param.LX || /*south*/ n < lattice->param.LX ) { // Slip condition on north/south boundary. /* // A B C F G H // \|/ \|/ // D-o-E --> D-o-E // /|\ /|\ // F G H A B C */ f[1] = ftemp[1]; f[2] = ftemp[4]; f[3] = ftemp[3]; f[4] = ftemp[2]; f[5] = ftemp[8]; f[6] = ftemp[7]; f[7] = ftemp[6]; f[8] = ftemp[5]; } else { // ERROR: Solid exists somewhere other than as side walls. printf("%s (%d) >> " "ERROR: " "bc_sigma_slip is on. " "FlowDir is determined to be horizontal. " "Encountered solid node somewhere other than side walls. " "That situation is not supported. " "Exiting!", __FILE__, __LINE__); process_exit(1); } } else { printf("%s (%d) >> " "FlowDir is indeterminate. " "Cannot apply slip BC (bc_sigma_slip). " "Exiting!", __FILE__, __LINE__); process_exit(1); } } /* if( lattice->param.bc_sigma_slip) */ else { #endif /* INAMURO_SIGMA_COMPONENT */ // Usual non-slip bounce-back condition. /* // A B C H G F // \|/ \|/ // D-o-E --> E-o-D // /|\ /|\ // F G H C B A */ f[1] = ftemp[3]; f[2] = ftemp[4]; f[3] = ftemp[1]; f[4] = ftemp[2]; f[5] = ftemp[7]; f[6] = ftemp[8]; f[7] = ftemp[5]; f[8] = ftemp[6]; #if INAMURO_SIGMA_COMPONENT } /* if( lattice->param.bc_sigma_slip) else */ #endif /* INAMURO_SIGMA_COMPONENT */ } /* if( subs==0) else*/ #endif /* NUM_FLUID_COMPONENTS==2 */ } /* if( lattice->param.bc_slip_north && ... ) else */ } /* if( !( bc_type & BC_SOLID_NODE)) else */ } /* for( n=0; n<lattice_NumNodes; n++) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("collide() -- Bye!\n"); #endif /* SAY_HI */ } /* void collide( lattice_ptr lattice) */ #endif /* POROUS_MEDIA */
111pjb-one
src/collide_bak08102005_01.c
C
gpl3
19,990
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // all_nodes_latman.c // // - Lattice Manager. // // - Routines for managing a lattice: // // - construct // - init // - destruct // // - This file, with prefix "all_nodes_", is for the version of the code // that stores all nodes of the domain even if they are interior solid // nodes that are not involved in any computations. This is more // efficient, in spite of storing unused nodes, if the ratio of // interior solid nodes to total nodes is sufficiently low. How // low is sufficient? is a difficult question. If storage is the // only consideration, then the two approaches balance at somewhere // around .75 . But more observations need to be made to characterize // the trade-off in terms of computational efficiency. // // void process_matrix( struct lattice_struct *lattice, int **matrix) //############################################################################## // // P R O C E S S M A T R I X // // - Process the soil matrix. // // - Convert the full matrix representation into sparse lattice form. // // - This routine is useful when the domain is read from a BMP file // representing the full lattice. If more general mechanisms // are developed (e.g., reading parameterized fracture information), // then determining the sparse lattice data structure will require a // corresponding mechanism (and storing the full lattice, even for // pre-/post-processing, may become undesirable if not impossible). // void process_matrix( struct lattice_struct *lattice, int **matrix, int subs) { // Variable declarations. int i, j; int in, jn; int ip, jp; int ei, ej; int n; int NumActiveNodes; // Ending indices. ei = get_LX(lattice)-1; ej = get_LY(lattice)-1; // Mark solid nodes that have fluid nodes as neighbors and // count the total number of nodes requiring storage. NumActiveNodes = 0; if( lattice->periodic_y[subs]) { for( j=0; j<=ej; j++) { jp = ( j<ej) ? ( j+1) : ( 0 ); jn = ( j>0 ) ? ( j-1) : ( ej); for( i=0; i<=ei; i++) { ip = ( i<ei) ? ( i+1) : ( 0 ); in = ( i>0 ) ? ( i-1) : ( ei); if( matrix[j ][i ] == 0) { NumActiveNodes++; if( matrix[j ][ip] == 1) { matrix[j ][ip] = 2; NumActiveNodes++;} if( matrix[jp][i ] == 1) { matrix[jp][i ] = 2; NumActiveNodes++;} if( matrix[j ][in] == 1) { matrix[j ][in] = 2; NumActiveNodes++;} if( matrix[jn][i ] == 1) { matrix[jn][i ] = 2; NumActiveNodes++;} if( matrix[jp][ip] == 1) { matrix[jp][ip] = 2; NumActiveNodes++;} if( matrix[jp][in] == 1) { matrix[jp][in] = 2; NumActiveNodes++;} if( matrix[jn][in] == 1) { matrix[jn][in] = 2; NumActiveNodes++;} if( matrix[jn][ip] == 1) { matrix[jn][ip] = 2; NumActiveNodes++;} } } /* for( i=0; i<=ei; i++) */ } /* for( j=0; j<=ej; j++) */ } /* if( lattice->periodic_y[subs]) */ else /* !lattice->periodic_y[subs] */ { j = 0; jp = 1; for( i=0; i<=ei; i++) { ip = ( i<ei) ? ( i+1) : ( 0 ); in = ( i>0 ) ? ( i-1) : ( ei); if( matrix[j ][i ] == 0) { NumActiveNodes++; if( matrix[j ][ip] == 1) { matrix[j ][ip] = 2; NumActiveNodes++;} if( matrix[jp][i ] == 1) { matrix[jp][i ] = 2; NumActiveNodes++;} if( matrix[j ][in] == 1) { matrix[j ][in] = 2; NumActiveNodes++;} //if( matrix[jn][i ] == 1) { matrix[jn][i ] = 2; NumActiveNodes++;} if( matrix[jp][ip] == 1) { matrix[jp][ip] = 2; NumActiveNodes++;} if( matrix[jp][in] == 1) { matrix[jp][in] = 2; NumActiveNodes++;} //if( matrix[jn][in] == 1) { matrix[jn][in] = 2; NumActiveNodes++;} //if( matrix[jn][ip] == 1) { matrix[jn][ip] = 2; NumActiveNodes++;} } } /* for( i=0; i<=ei; i++) */ for( j=1; j<ej; j++) { jp = j+1; jn = j-1; for( i=0; i<=ei; i++) { ip = ( i<ei) ? ( i+1) : ( 0 ); in = ( i>0 ) ? ( i-1) : ( ei); if( matrix[j ][i ] == 0) { NumActiveNodes++; if( matrix[j ][ip] == 1) { matrix[j ][ip] = 2; NumActiveNodes++;} if( matrix[jp][i ] == 1) { matrix[jp][i ] = 2; NumActiveNodes++;} if( matrix[j ][in] == 1) { matrix[j ][in] = 2; NumActiveNodes++;} if( matrix[jn][i ] == 1) { matrix[jn][i ] = 2; NumActiveNodes++;} if( matrix[jp][ip] == 1) { matrix[jp][ip] = 2; NumActiveNodes++;} if( matrix[jp][in] == 1) { matrix[jp][in] = 2; NumActiveNodes++;} if( matrix[jn][in] == 1) { matrix[jn][in] = 2; NumActiveNodes++;} if( matrix[jn][ip] == 1) { matrix[jn][ip] = 2; NumActiveNodes++;} } } /* for( i=0; i<=ei; i++) */ } /* for( j=0; j<=ej; j++) */ j = ej; jn = ej-1; for( i=0; i<=ei; i++) { ip = ( i<ei) ? ( i+1) : ( 0 ); in = ( i>0 ) ? ( i-1) : ( ei); if( matrix[j ][i ] == 0) { NumActiveNodes++; if( matrix[j ][ip] == 1) { matrix[j ][ip] = 2; NumActiveNodes++;} //if( matrix[jp][i ] == 1) { matrix[jp][i ] = 2; NumActiveNodes++;} if( matrix[j ][in] == 1) { matrix[j ][in] = 2; NumActiveNodes++;} if( matrix[jn][i ] == 1) { matrix[jn][i ] = 2; NumActiveNodes++;} //if( matrix[jp][ip] == 1) { matrix[jp][ip] = 2; NumActiveNodes++;} //if( matrix[jp][in] == 1) { matrix[jp][in] = 2; NumActiveNodes++;} if( matrix[jn][in] == 1) { matrix[jn][in] = 2; NumActiveNodes++;} if( matrix[jn][ip] == 1) { matrix[jn][ip] = 2; NumActiveNodes++;} } } /* for( i=0; i<=ei; i++) */ } /* if( lattice->periodic_y[subs]) else */ #if VERBOSITY_LEVEL > 0 printf( "[%s,%d] process_matrix() -- NumActiveNodes = %d\n", __FILE__, __LINE__, NumActiveNodes); #endif /* VERBOSITY_LEVEL > 0 */ #if 0 // Dump the matrix contents to the screen. for( j=0; j<=ej; j++) { for( i=0; i<=ei; i++) { printf(" %d", matrix[j][i]); } printf("\n"); } //process_exit(1); #endif // Set lattice->NumNodes in the lattice. lattice->NumNodes = get_LX(lattice) * get_LY(lattice); #if VERBOSITY_LEVEL > 0 printf("[%s,%d] process_matrix() -- NumNodes = %d\n", __FILE__,__LINE__, lattice->NumNodes); #endif /* VERBOSITY_LEVEL > 0 */ // Allocate memory for lattice->NumNodes boundary conditions. lattice->bc[subs]= ( struct bc_struct*)malloc( lattice->NumNodes*sizeof( struct bc_struct)); assert( lattice->bc[subs]!=NULL); // Set coordinates and index of lattice nodes. // Use matrix entries to store pointers to associated nodes to // facilitate finding neighbors on a following traversal. for( j=0; j<=ej; j++) { n = j*get_LX(lattice); for( i=0; i<=ei; i++, n++) { switch( matrix[j][i]) { case 0: lattice->bc[subs][n].bc_type = 0; break; case 1: lattice->bc[subs][n].bc_type = INACTIVE_NODE; break; case 2: lattice->bc[subs][n].bc_type = BC_SOLID_NODE; break; default: printf("%s %d >> process_matrix() -- " "Unhandled case matrix[%d][%d]=%d. Exiting!\n", __FILE__,__LINE__, j, i, matrix[j][i] ); process_exit(1); break; } } /* for( i=0; i<=ei; i++) */ } /* for( j=0; j<=ej; j++) */ #if 0 // Dump the matrix contents to the screen. for( j=0; j<=ej; j++) { for( i=0; i<=ei; i++) { printf(" %d", matrix[j][i]); } printf("\n"); } #endif #if 0 // Dump BCs to screen. for( n=0; n<lattice->NumNodes; n++) { printf("%d (%d,%d), %d\n", n, n%get_LX(lattice), n/get_LX(lattice), lattice->bc[subs][n].bc_type); } printf("\n"); for( n=0, j=0; j<=ej; j++) { for( i=0; i<=ei; i++, n++) { printf(" %d", lattice->bc[subs][n].bc_type); } printf("\n"); } #endif } /* void process_matrix( struct lattice_struct *lattice, int **matrix) */ // void construct_lattice( struct lattice_struct *lattice) //############################################################################## // // C O N S T R U C T L A T T I C E // // - Construct lattice. // void construct_lattice( lattice_ptr *lattice, int argc, char **argv) { // Variable declarations int **matrix; int i, j; int n; int subs; int width, height; char filename[1024]; #if POROUS_MEDIA || FREED_POROUS_MEDIA FILE *in; char r, g, b; struct bitmap_info_header bmih; #endif /* POROUS_MEDIA */ assert(*lattice!=NULL); process_init( *lattice, argc, argv); if( argc == 2) { printf("argv = \"%s\"\n", argv[1]); strcpy( filename, argv[1]); printf("filename = \"%s\"\n", filename); } else if( argc == 1) { sprintf(filename, "./in/%s", "params.in"); printf("filename = \"%s\"\n", filename); } else { printf("\n\nusage: ./lb2d [infile]\n\n\n"); process_exit(1); } // Read problem parameters read_params( *lattice, filename); process_compute_local_params( *lattice); // Allocate matrix for storing information from bmp file. matrix = (int**)malloc( get_LY(*lattice)*sizeof(int*)); for( j=0; j<get_LY(*lattice); j++) { matrix[j] = (int*)malloc( get_LX(*lattice)*sizeof(int)); } // Initialize matrix[][]. for( j=0; j<get_LY(*lattice); j++) { for( i=0; i<get_LX(*lattice); i++) { matrix[j][i] = 0; } } for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { // Default periodicity. This will be adjusted in read_bcs() // or process_bcs() depending on flow boundaries. (*lattice)->periodic_x[subs] = 1; (*lattice)->periodic_y[subs] = 1; // Get solids. sprintf( filename, "./in/%dx%d.bmp", get_g_LX(*lattice), get_g_LY(*lattice)); spy_bmp( filename, *lattice, matrix); // Determine active nodes. process_matrix( *lattice, matrix, subs); assert( (*lattice)->bc[subs]!=NULL); #if 0 // Read boundary conditions from BMP files. // Eventually this mechanism will be very general to handle // (somewhat?) arbitrary arrangements of boundary conditions. read_bcs( *lattice, matrix); #else // Process boundary conditions based on flags read from params.in . // This will only support standard inflow and outflow boundaries along // entire sides of the lattice. process_bcs( *lattice, subs); #endif } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ // Deallocate memory used for storing the full matrix. #if VERBOSITY_LEVEL > 0 printf("latman.c: contruct_lattice() -- Free the matrix.\n"); #endif /* VERBOSITY_LEVEL > 0 */ for( n=0; n<get_LY(*lattice); n++) { free( matrix[n]); } free( matrix); #if VERBOSITY_LEVEL > 0 printf("latman.c: contruct_lattice() -- Matrix is free.\n"); #endif /* VERBOSITY_LEVEL > 0 */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { // Allocate NumNodes particle distribution functions. (*lattice)->pdf[subs] = ( struct pdf_struct*)malloc( (*lattice)->NumNodes*sizeof( struct pdf_struct)); if( (*lattice)->pdf[subs] == NULL) { printf( "construct_lattice() -- ERROR: " "Attempt to allocate %d struct pdf_struct types failed. " "Exiting!\n", (*lattice)->NumNodes ); process_exit(1); } // Allocate NumNodes macroscopic variables. (*lattice)->macro_vars[subs] = ( struct macro_vars_struct*)malloc( (*lattice)->NumNodes*sizeof( struct macro_vars_struct)); if( (*lattice)->macro_vars[subs]==NULL) { printf( "construct_lattice() -- ERROR: " "Attempt to allocate %d struct macro_vars_struct types failed. " "Exiting!\n", (*lattice)->NumNodes ); process_exit(1); } #if NON_LOCAL_FORCES // Allocate NumNodes elements for force. (*lattice)->force[subs] = ( struct force_struct*)malloc( (*lattice)->NumNodes*sizeof( struct force_struct)); if( (*lattice)->force[subs]==NULL) { printf( "construct_lattice() -- ERROR: " "Attempt to allocate %d struct force_struct types failed. " "Exiting!\n", (*lattice)->NumNodes ); process_exit(1); } #endif /* NON_LOCAL_FORCES */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if STORE_U_COMPOSITE // Allocate NumNodes elements for upr. (*lattice)->upr = ( struct upr_struct*)malloc( (*lattice)->NumNodes*sizeof( struct upr_struct)); if( (*lattice)->upr==NULL) { printf( "construct_lattice() -- ERROR: " "Attempt to allocate %d struct upr_struct types failed. " "Exiting!\n", (*lattice)->NumNodes ); process_exit(1); } #endif /* STORE_U_COMPOSITE */ #if TAU_ZHANG_ANISOTROPIC_DISPERSION (*lattice)->tau_zhang = (double*)malloc( 9*sizeof(double)); #endif #if POROUS_MEDIA || FREED_POROUS_MEDIA switch( (*lattice)->param.ns_flag) { case 0: { if( (*lattice)->param.ns > 1.) { printf( "latman.c: construct_lattice() -- " "ERROR: ns = %f. " "Should have 0 <= ns <=1. " "Exiting!\n", (*lattice)->param.ns ); process_exit(1); } break; } case 1: { // Allocate space for ns values. (*lattice)->ns = (struct ns_struct*)malloc( (*lattice)->NumNodes*sizeof(struct ns_struct)); if( (*lattice)->ns==NULL) { printf( "construct_lattice() -- ERROR: " "Attempt to allocate %d struct ns_struct types failed. " "Exiting!\n", (*lattice)->NumNodes ); process_exit(1); } // Try to read ns<LX>x<LY>.bmp file. #if PARALLEL sprintf( filename, "./in/ns%dx%d_proc%04d.bmp", get_LX(*lattice), get_LY(*lattice), get_proc_id(*lattice)); #else sprintf( filename, "./in/ns%dx%d.bmp", get_LX(*lattice), get_LY(*lattice)); #endif if( in = fopen( filename, "r+")) { printf("%s %d >> Reading file \"%s\".\n",__FILE__,__LINE__,filename); bmp_read_header( in, &bmih); for( n=0; n<(*lattice)->NumNodes; n++) { bmp_read_entry( in, &bmih, &r, &g, &b); // Verify grayscale. if( (double)r != (double)g || (double)g != (double)b || (double)r != (double)b) { printf( "%s %d >> latman.c: construct_lattice() -- " "n=%d: [ r g b] = [ %3u %3u %3u]\n",__FILE__,__LINE__, n, (unsigned int)r%256, (unsigned int)g%256, (unsigned int)b%256); printf( "%s %d >> latman.c: construct_lattice() -- " "ERROR: File %s needs to be grayscale. " "Exiting!\n",__FILE__,__LINE__, filename); process_exit(1); } // Assign ns value. (*lattice)->ns[n].ns = ((double)((unsigned int)r%256))/255.; #if 0 && VERBOSITY_LEVEL>0 printf("%s %d >> n=%d, ns=%f\n", __FILE__, __LINE__, n, (*lattice)->ns[n].ns); #endif /* 1 && VERBOSITY_LEVEL>0 */ } /* for( n=0; n<(*lattice)->NumNodes; n++) */ fclose( in); } /* if( in = fopen( filename, "r+")) */ else /* !( in = fopen( filename, "r+")) */ { // Can't read ns.bmp file, so use default values. printf("%s %d >> WARNING: Can't read \"%s\". " "Using default ns values.\n",__FILE__,__LINE__,filename); } /* if( in = fopen( filename, "r+")) else */ break; } case 2: { // Allocate space for ns values. (*lattice)->ns = (struct ns_struct*)malloc( (*lattice)->NumNodes*sizeof(struct ns_struct)); if( (*lattice)->ns==NULL) { printf( "construct_lattice() -- ERROR: " "Attempt to allocate %d struct ns_struct types failed. " "Exiting!\n", (*lattice)->NumNodes ); process_exit(1); } // Try to read ns<LX>x<LY>.bmp file. #if PARALLEL sprintf( filename, "./in/ns%dx%d_proc%04d.bmp", get_LX(*lattice), get_LY(*lattice), get_proc_id(*lattice)); #else sprintf( filename, "./in/ns%dx%d.bmp", get_LX(*lattice), get_LY(*lattice)); #endif if( in = fopen( filename, "r+")) { printf("%s %d >> Reading file \"%s\".\n",__FILE__,__LINE__,filename); bmp_read_header( in, &bmih); for( n=0; n<(*lattice)->NumNodes; n++) { bmp_read_entry( in, &bmih, &r, &g, &b); // Verify grayscale. if( (double)r != (double)g || (double)g != (double)b || (double)r != (double)b) { printf( "%s %d >> latman.c: construct_lattice() -- " "n=%d: [ r g b] = [ %3u %3u %3u]\n",__FILE__,__LINE__, n, (unsigned int)r%256, (unsigned int)g%256, (unsigned int)b%256); printf( "%s %d >> latman.c: construct_lattice() -- " "ERROR: File %s needs to be grayscale. " "Exiting!\n",__FILE__,__LINE__, filename); process_exit(1); } if( ((unsigned int)r%256) != 0 && ((unsigned int)r%256) != 255 ) { printf( "%s %d >> latman.c: construct_lattice() -- " "ERROR: File %s needs to be black and white. " "Exiting!\n",__FILE__,__LINE__, filename); process_exit(1); } // Assign ns value. if( ((unsigned int)r%256) == 0) { (*lattice)->ns[n].ns = (*lattice)->param.ns; } else { (*lattice)->ns[n].ns = 0.; } #if 0 && VERBOSITY_LEVEL>0 printf("%s %d >> n=%d, ns=%f\n", __FILE__, __LINE__, n, (*lattice)->ns[n].ns); #endif /* 1 && VERBOSITY_LEVEL>0 */ } /* for( n=0; n<(*lattice)->NumNodes; n++) */ fclose( in); } /* if( in = fopen( filename, "r+")) */ else /* !( in = fopen( filename, "r+")) */ { // Can't read ns.bmp file, so use default values. printf("%s %d >> WARNING: Can't read \"%s\". " "Using default ns values.\n",__FILE__,__LINE__,filename); } /* if( in = fopen( filename, "r+")) else */ break; } default: { printf("%s %d >> construct_lattice() -- Unhandled case: " "ns_flag = %d . (Exiting!)\n", __FILE__,__LINE__,(*lattice)->param.ns_flag < 0.); process_exit(1); break; } } /* switch( (*lattice)->param.ns_flag) */ #endif /* POROUS_MEDIA */ #if INAMURO_SIGMA_COMPONENT && DETERMINE_FLOW_DIRECTION // // Try to determine the direction of flow. // // NOTE: This determination informs the breakthrough curve mechanism which // should be used in a simple situation with either pressure/velocity // boundaries driving the flow in one direction or gravity driving the flow // in one direction. If the direction of flow cannot be determined, FlowDir // will be set to indeterminate (=0) and a BTC will not be stored. // // NOTE: This determination also informs the sigma slip boundary which // should only be used in the simple situation of flow through a channel // where geometry is trivial and the direction of flow is obvious. // int north_bcs = (*lattice)->param.pressure_n_in[0] || (*lattice)->param.pressure_n_out[0] || (*lattice)->param.velocity_n_in[0] || (*lattice)->param.velocity_n_out[0]; int south_bcs = (*lattice)->param.pressure_s_out[0] || (*lattice)->param.pressure_s_in[0] || (*lattice)->param.velocity_s_out[0] || (*lattice)->param.velocity_s_in[0]; int east_bcs = (*lattice)->param.pressure_e_in[0] || (*lattice)->param.pressure_e_out[0] || (*lattice)->param.velocity_e_in[0] || (*lattice)->param.velocity_e_out[0]; int west_bcs = (*lattice)->param.pressure_w_out[0] || (*lattice)->param.pressure_w_in[0] || (*lattice)->param.velocity_w_out[0] || (*lattice)->param.velocity_w_in[0]; if( // Pressure/Velocity boundaries moving the flow vertically. ( north_bcs || south_bcs ) && !( east_bcs || west_bcs)) { (*lattice)->FlowDir = /*Vertical*/2; } else if( // Pressure/Velocity boundaries moving the flow horizontally. !( north_bcs || south_bcs ) && ( east_bcs || west_bcs)) { (*lattice)->FlowDir = /*Horizontal*/1; } else { if( // Gravity driving flow vertically. (*lattice)->param.gval[0][1] != 0. && (*lattice)->param.gval[0][0] == 0. ) { (*lattice)->FlowDir = /*Vertical*/2; } else if( // Gravity driving flow horizontally. (*lattice)->param.gval[0][0] != 0. && (*lattice)->param.gval[0][1] == 0. ) { (*lattice)->FlowDir = /*Horizontal*/1; } else // Cannot determine direction of flow. { (*lattice)->FlowDir = /*Indeterminate*/0; } } // INITIALIZE_WITH_UX_IN or INITIALIZE_WITH_UY_IN can override // the flow direction calculations. #if INITIALIZE_WITH_UX_IN (*lattice)->FlowDir = /*Horizontal*/1; #endif /* INITIALIZE_WITH_UX_IN */ #if INITIALIZE_WITH_UY_IN (*lattice)->FlowDir = /*Vertical*/2; #endif /* INITIALIZE_WITH_UY_IN */ #endif /* INAMURO_SIGMA_COMPONENT && DETERMINE_FLOW_DIRECTION */ #if INAMURO_SIGMA_COMPONENT && STORE_BTC // Allocate space for a break through curve if necessary. if( (*lattice)->param.sigma_btc_rate > 0 && (*lattice)->FlowDir!=0) { // Compute "size" of break through curve: number of readings // to store. (*lattice)->SizeBTC = (int)ceil((double)( ( (*lattice)->NumTimeSteps - (((*lattice)->param.sigma_start>0) ?((*lattice)->param.sigma_start) :(0)) ) / (*lattice)->param.sigma_btc_rate))+1; // // Allocate 4*SizeBTC elements. // // Readings will come in groups of four (r1,r2,r3,r4): // // r0: Timestep. // // r1: Concentration at sigma_spot-1 // // r2: Concentration at sigma_spot-0 // // r3: Concentration at sigma_spot+1 // // r4: Velocity in direction of flow. // // Then // // Cf = ( C*v - D*dCdx)/v = ( (r2+r3)/(2*r4) - D*(r3-r2)) / r4 // (*lattice)->param.sigma_btc = ( double*)malloc( 5*(*lattice)->SizeBTC*sizeof(double)); } /* if( sigma_btc_rate > 0) */ #endif /* INAMURO_SIGMA_COMPONENT && STORE_BTC */ //for reading north boundary pressure from file ./in/pressure_n_in0.in //and assigning it to the appropriate variable if( (*lattice)->param.pressure_n_in[0] == 2) { sprintf(filename,"./in/pressure_n_in0.in"); printf("[%s,%d] construct_lattice() -- Reading %s\n", __FILE__, __LINE__ , filename); FILE *in; in = fopen(filename,"r"); if( !( in = fopen(filename,"r+"))) { printf("%s %d >> WARNING: Can't load \"%s\".\n", __FILE__,__LINE__,filename); return; } *(num_pressure_n_in0_ptr(*lattice,0)) = 0; double temp; fscanf(in,"%lf",&temp); while( !feof(in)) { (*(num_pressure_n_in0_ptr(*lattice,0)))++; fscanf(in,"%lf",&temp); } printf("num_pressure_n_in0_ptr = %d\n", num_pressure_n_in0(*lattice,0)); *pressure_n_in0_ptr(*lattice,0) = (double*)malloc( num_pressure_n_in0(*lattice,0)*sizeof(double)); rewind(in); int i; for( i=0; i<num_pressure_n_in0(*lattice,0); i++) { fscanf(in,"%lf", pressure_n_in0(*lattice,0) + i); } fclose(in); //for( i=0; i<num_pressure_n_in0(*lattice,0); i++) //{ // printf("%f\n",*( pressure_n_in0(*lattice,0) + i)); //} } //for reading south boundary pressure from file ./in/pressure_s_in0.in //and assigning it to the appropriate variable if( (*lattice)->param.pressure_s_in[0] == 2) { sprintf(filename,"./in/pressure_s_in0.in"); printf("[%s,%d] construct_lattice() -- Reading %s\n", __FILE__, __LINE__ , filename); FILE *in; in = fopen(filename,"r"); if( !( in = fopen(filename,"r+"))) { printf("%s %d >> WARNING: Can't load \"%s\".\n", __FILE__,__LINE__,filename); return; } *(num_pressure_s_in0_ptr(*lattice,0)) = 0; double temp; fscanf(in,"%lf",&temp); while( !feof(in)) { (*(num_pressure_s_in0_ptr(*lattice,0)))++; fscanf(in,"%lf",&temp); } printf("num_pressure_s_in0_ptr = %d\n", num_pressure_s_in0(*lattice,0)); *pressure_s_in0_ptr(*lattice,0) = (double*)malloc( num_pressure_s_in0(*lattice,0)*sizeof(double)); rewind(in); int i; for( i=0; i<num_pressure_s_in0(*lattice,0); i++) { fscanf(in,"%lf", pressure_s_in0(*lattice,0) + i); } fclose(in); //for( i=0; i<num_pressure_n_in0(*lattice,0); i++) //{ // printf("%f\n",*( pressure_n_in0(*lattice,0) + i)); //} } if( do_user_stuff((*lattice))) { (*lattice)->user_stuff = (user_stuff_ptr)malloc( sizeof(struct user_stuff_struct)); } dump_params( *lattice); } /* void construct_lattice( struct lattice_struct **lattice) */ // void read_PEST_in_files( lattice_ptr *lattice, int argc, char **argv) //############################################################################## // // READ PEST IN FILES // // - Read the files timestep_file.in, x_coord_file.in and y_coord_file.in // // - The function write_PEST_out_data will then save fluid 1 rho values // (concentration) to an output file. // void read_PEST_in_files( lattice_ptr *lattice, int argc, char **argv) { #if PEST_OUTPUT_ON //for reading concentration data from files in ./in/ //for use with PEST char filename[1024]; FILE *in; int i; //begin with timesteps sprintf(filename,"./in/timestep_file.in"); printf("[%s,%d] construct_lattice() -- Reading %s\n", __FILE__, __LINE__ , filename); in = fopen(filename,"r"); if( !( in = fopen(filename,"r+"))) { printf("%s %d >> WARNING: Can't load \"%s\".\n", __FILE__,__LINE__,filename); return; } double temp; (*lattice)->conc_array_size = 0; fscanf(in,"%lf",&temp); while( !feof(in)) { (*lattice)->conc_array_size++; fscanf(in,"%lf",&temp); } printf("Number of PEST points = %d\n", (*lattice)->conc_array_size); (*lattice)->concentration_data = ( struct conc_data_struct*)malloc( (*lattice)->conc_array_size*sizeof( struct conc_data_struct)); rewind(in); for( i=0; i<(*lattice)->conc_array_size; i++) { (*lattice)->concentration_data[i].countervar = i; fscanf(in,"%d", &((*lattice)->concentration_data[i].timestep)); } fclose(in); for( i=1; i<(*lattice)->conc_array_size; i++) { if((*lattice)->concentration_data[i].timestep < (*lattice)->concentration_data[i-1].timestep) { printf("[%s,%d] PEST Failure - Concentration data not in time order\n", __FILE__, __LINE__); exit (1); } } //now do the space coordinates, starting with x sprintf(filename,"./in/x_coord_file.in"); printf("[%s,%d] construct_lattice() -- Reading %s\n", __FILE__, __LINE__ , filename); in = fopen(filename,"r"); if( !( in = fopen(filename,"r+"))) { printf("%s %d >> WARNING: Can't load \"%s\".\n", __FILE__,__LINE__,filename); return; } for( i=0; i<(*lattice)->conc_array_size; i++) { fscanf(in,"%d", &((*lattice)->concentration_data[i].x_coord)); } fclose(in); //now do y sprintf(filename,"./in/y_coord_file.in"); printf("[%s,%d] construct_lattice() -- Reading %s\n", __FILE__, __LINE__ , filename); in = fopen(filename,"r"); if( !( in = fopen(filename,"r+"))) { printf("%s %d >> WARNING: Can't load \"%s\".\n", __FILE__,__LINE__,filename); return; } for( i=0; i<(*lattice)->conc_array_size; i++) { fscanf(in,"%d", &((*lattice)->concentration_data[i].y_coord)); } fclose(in); //Now we must reduce our arrays so that they only contain concs valid for the local domain int tempint; for( i=0; i<(*lattice)->conc_array_size; i++) { if((*lattice)->concentration_data[i].y_coord < get_g_SY(*lattice) || (*lattice)->concentration_data[i].y_coord > get_g_EY(*lattice) || (*lattice)->concentration_data[i].x_coord < get_g_SX(*lattice) || (*lattice)->concentration_data[i].x_coord > get_g_EX(*lattice)) { (*lattice)->concentration_data[i].timestep = -1; } else { tempint = g2ly(*lattice, (*lattice)->concentration_data[i].y_coord); (*lattice)->concentration_data[i].y_coord = tempint; } } int newcount = 0; for( i=0; i<(*lattice)->conc_array_size; i++) { tempint = (*lattice)->concentration_data[i].timestep; if(tempint > -1) { (*lattice)->concentration_data[newcount].countervar = (*lattice)->concentration_data[i].countervar; (*lattice)->concentration_data[newcount].timestep = (*lattice)->concentration_data[i].timestep; (*lattice)->concentration_data[newcount].x_coord = (*lattice)->concentration_data[i].x_coord; (*lattice)->concentration_data[newcount].y_coord = (*lattice)->concentration_data[i].y_coord; newcount++; } } (*lattice)->conc_array_size = newcount; printf("Concentration array size for processor %d is %d. \n", get_proc_id(*lattice), (*lattice)->conc_array_size); (*lattice)->array_position = 0; #endif } /* void read_PEST_in_files */ // void write_PEST_out_data( lattice_ptr *lattice, int argc, char **argv) //############################################################################## // // WRITE_PEST_OUT_DATA // // - Write pest data to (*lattice)->concentration_data[0].norm_conc // // - The function write_PEST_out_data will then save fluid 1 rho values // (concentration) to an output file. // void write_PEST_out_data( lattice_ptr *lattice, int argc, char **argv) { #if PEST_OUTPUT_ON //problem with not allocating space for time_array_position? while((*lattice)->concentration_data[(*lattice)->array_position].timestep == (*lattice)->time - 1) { printf("Process %d has found a match between time %d and conc data timestep %d. \n", get_proc_id(*lattice), (*lattice)->time-1, (*lattice)->concentration_data[(*lattice)->array_position].timestep); printf("Process %d is recording concentration at %d x %d. \n", get_proc_id(*lattice), (*lattice)->concentration_data[(*lattice)->array_position].x_coord, (*lattice)->concentration_data[(*lattice)->array_position].y_coord); (*lattice)->concentration_data[(*lattice)->array_position].norm_conc = *(&((*lattice)->macro_vars[1][0].rho) + 3 * (*lattice)->concentration_data[(*lattice)->array_position].y_coord * get_LX(*lattice) + 3 * (*lattice)->concentration_data[(*lattice)->array_position].x_coord); (*lattice)->array_position++; } #endif } // void write_PEST_out_file( lattice_ptr *lattice, int argc, char **argv) //############################################################################## // // WRITE_PEST_OUT_FILE // // - Write pest data to (*lattice)->concentration_data[0].norm_conc // // - The function write_PEST_out_file will then save fluid 1 rho values // (concentration) to an output file. // void write_PEST_out_file( lattice_ptr *lattice, int argc, char **argv) { #if PEST_OUTPUT_ON FILE *fp; char filename[1024]; int aa; sprintf( filename, "./out/conc_data_proc%04d.dat", (*lattice)->process.id); fp=fopen(filename, "w+"); if( !( fp = fopen(filename,"w+"))) { printf("%s %d >> WARNING: Can't load \"%s\".\n", __FILE__,__LINE__,filename); return; } for( aa = 0; aa < (*lattice)->conc_array_size; aa++) { fprintf(fp,"%20.17f\n", (*lattice)->concentration_data[aa].norm_conc); } fclose(fp); sprintf( filename, "./out/conc_order_proc%04d.dat", (*lattice)->process.id); fp=fopen(filename, "w+"); if( !( fp = fopen(filename,"w+"))) { printf("%s %d >> WARNING: Can't load \"%s\".\n", __FILE__,__LINE__,filename); return; } for( aa = 0; aa < (*lattice)->conc_array_size; aa++) { fprintf(fp,"%d\n", (*lattice)->concentration_data[aa].countervar); } fclose(fp); #endif } // void init_problem( struct lattice_struct *lattice) //############################################################################## // // I N I T P R O B L E M // // - Initialize the problem on the lattice. // // - Set the initial density and velocity. // // - Compute the initial feq. // void init_problem( struct lattice_struct *lattice) { #if WRITE_CHEN_DAT_FILES FILE *o; char filename[1024]; #endif /* WRITE_CHEN_DAT_FILES */ int n, i, j; double a, x, u_max, K, drho, m; double *macro_var_ptr; double *f, *feq, *ftemp; #if STORE_U_COMPOSITE double *upr; #endif /* STORE_U_COMPOSITE */ #if NON_LOCAL_FORCES double *force; #endif /* NON_LOCAL_FORCES */ bc_ptr bc; int subs; double kappa; double ti; double y; FILE *ic_in; char ic_filename[1024]; struct bitmap_info_header bmih; char r, g, b; if( lattice->param.initial_condition == IC_WOLF_GLADROW_DIFFUSION) { kappa = 1.*( lattice->param.tau[1] - .5); ti = 15./kappa; printf("IC_WOLF_GLADROW_DIFFUSION\n"); printf(" ti = 15./kappa = 15./%f = %f\n", kappa, ti); printf(" tf = 75./kappa = 75./%f = %f\n", kappa, 75./kappa); printf(" tf-ti = (75.-15.)/kappa = 60./%f = %f\n", kappa, 60./kappa); printf("\n"); } #if VERBOSITY_LEVEL > 0 printf("init_problem() -- Initilizing problem...\n"); #endif /* VERBOSITY_LEVEL > 0 */ #if WRITE_CHEN_DAT_FILES // // Create empty chen_*.dat files. // sprintf( filename, "%s", "./out/chen_xyrho.dat"); if( !( o = fopen( filename,"w+"))) { printf("Error creating \"%s\". Exiting!\n", filename); process_exit(1); } fclose( o); sprintf( filename, "%s", "./out/chen_xy_ux_uy.dat"); if( !( o = fopen( filename,"w+"))) { printf("Error creating \"%s\". Exiting!\n", filename); process_exit(1); } fclose( o); sprintf( filename, "%s", "./out/chen_time.dat"); if( !( o = fopen( filename,"w+"))) { printf("Error creating \"%s\". Exiting!\n", filename); process_exit(1); } fclose( o); #endif /* WRITE_CHEN_DAT_FILES */ #if 0 // Want to allow mix of velocity and pressure boundaries. if( lattice->param.ic_poiseuille) { if( lattice->param.uy_in != lattice->param.uy_out) { printf("\n"); printf("\n"); printf("%s (%d) -- ERROR: " "Need uy_in == uy_out to initialize with poiseuille profile. " "Exiting.\n", __FILE__,__LINE__); printf("\n"); printf("\n"); process_exit(1); } /* if( lattice->param.uy_in != lattice->param.uy_out) */ } /* if( lattice->param.ic_poiseuille) */ #endif for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { macro_var_ptr = &( lattice->macro_vars[subs][0].rho); bc = lattice->bc[subs]; #if STORE_U_COMPOSITE upr = lattice->upr[0].u; #endif /* STORE_U_COMPOSITE */ if( lattice->param.initial_condition == IC_READ_FROM_FILE) { // Try to read <LX>x<LY>ic.bmp file. sprintf( ic_filename, "./in/%dx%dic.bmp", get_LX(lattice), get_LY(lattice)); if( ic_in = fopen( ic_filename, "r+")) { printf("%s %d >> Reading file \"%s\".\n",__FILE__,__LINE__,ic_filename); bmp_read_header( ic_in, &bmih); } /* if( ic_in = fopen( ic_filename, "r+")) */ else /* !( ic_in = fopen( ic_filename, "r+")) */ { // Can't read ic file. printf("%s %d >> ERROR: Can't read \"%s\". " "Exiting!\n",__FILE__,__LINE__,ic_filename); process_exit(1); } /* if( ic_in = fopen( ic_filename, "r+")) else */ } /* if( lattice->param.initial_condition == IC_READ_FROM_FILE) */ for( n=0; n<lattice->NumNodes; n++) { i = n%get_LX(lattice); j = n/get_LX(lattice); // Set initial density. if( ( 1 || !( bc->bc_type & BC_SOLID_NODE)) ) { switch( lattice->param.initial_condition) { case IC_UNIFORM_RHO_A: { #if INAMURO_SIGMA_COMPONENT if( subs==0) { if( 1 && lattice->param.ic_poiseuille) { if( !lattice->periodic_x[subs]) { // Density gradient corresponding to the desired velocity. // Based on formula for poiseuille velocity profile // // u(x) = K*( a^2 - x^2) // // where, in terms of the density/pressure gradient, // // K = dP/(2 L rho0 nu) ==> drho = 6 L rho0 nu K // // using the equation of state rho = 3 P. // // u_max = (3/2)ux_in u_max = 1.5*(lattice->param.ux_in); // a = .5*(LY-2) . a = .5*(get_LY(lattice)-2); // u(y) = K(a^2-y^2) // ==> u_max = Ka^2 // ==> K = u_max/a^2 K = u_max/(a*a); drho = 6.*get_LX(lattice) *lattice->param.rho_A[subs] *((1./3.)*(lattice->param.tau[subs]-.5)) *K; if( lattice->param.incompressible) { drho = drho/lattice->param.rho_A[subs]; } //drho = .0188121666666667; //drho = .62680456666658; //drho = 6.2680456666658; //printf("%s (%d) -- drho = %f\n",__FILE__,__LINE__,drho); m = drho/(get_LX(lattice)-1); *macro_var_ptr++ = ( lattice->param.rho_A[subs] + drho/2.) - m*i; #if 0 ( 1.5*( lattice->param.ux_in) /( .25*(get_LY(lattice)-2)*(get_LY(lattice)-2)) ) *( .25*( get_LY(lattice)-2)*( get_LY(lattice)-2) - (i-.5*( get_LY(lattice)-2)-.5) *(i-.5*( get_LY(lattice)-2)-.5) ) ; #endif //printf("%s (%d) -- %d %f\n", __FILE__, __LINE__, i, *(macro_var_ptr-1)); } else if( !lattice->periodic_y[subs]) { // Density gradient corresponding to the desired velocity. // Based on formula for poiseuille velocity profile // // u(x) = K*( a^2 - x^2) // // where, in terms of the density/pressure gradient, // // K = dP/(2 L rho0 nu) ==> drho = 6 L rho0 nu K // // using the equation of state rho = 3 P. // // u_max = (3/2)uy_in u_max = 1.5*(lattice->param.uy_in); // a = .5*(LX-2) . a = .5*(get_LX(lattice)-2); // u(x) = K(a^2-x^2) // ==> u_max = Ka^2 // ==> K = u_max/a^2 K = u_max/(a*a); drho = 6.*get_LY(lattice) *lattice->param.rho_A[subs] *((1./3.)*(lattice->param.tau[subs]-.5)) *K; if( lattice->param.incompressible) { drho = drho/lattice->param.rho_A[subs]; } //drho = .0188121666666667; //drho = .62680456666658; //drho = 6.2680456666658; //printf("%s (%d) -- drho = %f\n",__FILE__,__LINE__,drho); m = drho/(get_LY(lattice)-1); *macro_var_ptr++ = ( lattice->param.rho_A[subs] + drho/2.) - m*j; #if 0 ( 1.5*( lattice->param.uy_in) /( .25*(get_LX(lattice)-2)*(get_LX(lattice)-2)) ) *( .25*( get_LX(lattice)-2)*( get_LX(lattice)-2) - (i-.5*( get_LX(lattice)-2)-.5) *(i-.5*( get_LX(lattice)-2)-.5) ) ; #endif //printf("%s (%d) -- %d %f\n", __FILE__, __LINE__, i, *(macro_var_ptr-1)); } else { } } /* if( lattice->param.ic_poiseuille) */ else // !lattice->param.ic_poiseuille { if( hydrostatic( lattice)) { //*macro_var_ptr++ = ( 1.00216 - (j-1)*.00054); if( hydrostatic_compressible( lattice)) { if( hydrostatic_compute_rho_ref(lattice)) { // Reference density computed in terms of average density lattice->param.rho_out = #if 0 ( 3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C(lattice)-get_C0(lattice)) ) #endif *(get_LY(lattice)-2) *lattice->param.rho_A[0]) / ( 1. - exp( -3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *(get_LY(lattice)-2))); #else ( 3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C(lattice)-get_C0(lattice)) ) #endif *(get_LY(lattice)-2) *lattice->param.rho_A[0]) / ( 1. - exp( -3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *(get_LY(lattice)-2))); #endif //printf("rho_ref = %20.17f\n", lattice->param.rho_out); } *macro_var_ptr++ = #if 0 lattice->param.rho_out *exp( -3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT //*(1.+(get_buoyancy(lattice))*lattice->param.rho_sigma) *(1. + (get_buoyancy(lattice)) *get_beta(lattice) *( get_C(lattice) - get_C0(lattice))) #endif //*(0.5*(get_LY(lattice)-1.)-1.)) *( (get_LY(lattice)-1.)-0.)) *exp( 3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT //*(1.+(get_buoyancy(lattice))*lattice->param.rho_sigma) *(1. + (get_buoyancy(lattice)) *get_beta(lattice) *( get_C(lattice) - get_C0(lattice))) #endif *(j+1.0)); #else 3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT //*(1.+(get_buoyancy(lattice))*lattice->param.rho_sigma) *(1. + (get_buoyancy(lattice)) *get_beta(lattice) *( get_C(lattice) - get_C0(lattice))) #endif *(get_LY(lattice)-2) *lattice->param.rho_A[0] *exp( -3.*lattice->param.gval[0][1] *( ( get_LY(lattice)-2.) - (j-.5)) ) / ( 1. - exp( -3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT //*(1.+(get_buoyancy(lattice))*lattice->param.rho_sigma) *(1. + (get_buoyancy(lattice)) *get_beta(lattice) *( get_C(lattice) - get_C0(lattice))) #endif *(get_LY(lattice)-2))); #endif } else { *macro_var_ptr++ = lattice->param.rho_out * ( 1. - 3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT //*(1.+(get_buoyancy(lattice))*lattice->param.rho_sigma) *(1. + (get_buoyancy(lattice)) *get_beta(lattice) *( get_C(lattice) - get_C0(lattice))) #endif *( ( get_LY(lattice) + ((get_LY(lattice)%2)?(-1.):(1.)))/2. - j ) ); } } else { *macro_var_ptr++ = lattice->param.rho_A[subs]; } } /* if( lattice->param.ic_poiseuille) else */ } else // subs==1 { *macro_var_ptr++ = lattice->param.rho_sigma; } #else /* !( INAMURO_SIGMA_COMPONENT) */ if( hydrostatic( lattice)) { if( hydrostatic_compressible( lattice)) { if( hydrostatic_compute_rho_ref(lattice)) { // Reference density computed in terms of average density lattice->param.rho_out = ( 3.*lattice->param.gval[0][1] *(get_LY(lattice)-2) *lattice->param.rho_A[0]) / ( 1. - exp( -3.*lattice->param.gval[0][1] *(get_LY(lattice)-2))); } *macro_var_ptr++ = #if 0 lattice->param.rho_out *exp( -3.*lattice->param.gval[0][1] *( (get_LY(lattice)-1.)-0.)) *exp( 3.*lattice->param.gval[0][1] *(j+1.0)); #else 3.*lattice->param.gval[0][1] *(get_LY(lattice)-2) *lattice->param.rho_A[0] *exp( -3.*lattice->param.gval[0][1] *( ( get_LY(lattice)-2.) - (j-.5)) ) / ( 1. - exp( -3.*lattice->param.gval[0][1] *(get_LY(lattice)-2))); #endif } else { *macro_var_ptr++ = lattice->param.rho_out * ( 1. - 3.*lattice->param.gval[0][1] *( ( get_LY(lattice) + ((get_LY(lattice)%2)?(-1.):(1.)))/2. - j ) ); } } else { *macro_var_ptr++ = lattice->param.rho_A[subs]; } #endif /* INAMURO_SIGMA_COMPONENT */ break; } case IC_UNIFORM_RHO_B: { #if INAMURO_SIGMA_COMPONENT if( subs==0) { if( 1 && lattice->param.ic_poiseuille) { if( !lattice->periodic_x[subs]) { // Density gradient corresponding to the desired velocity. // Based on formula for poiseuille velocity profile // // u(x) = K*( a^2 - x^2) // // where, in terms of the density/pressure gradient, // // K = dP/(2 L rho0 nu) ==> drho = 6 L rho0 nu K // // using the equation of state rho = 3 P. // // u_max = (3/2)ux_in u_max = 1.5*(lattice->param.ux_in); // a = .5*(LY-2) . a = .5*(get_LY(lattice)-2); // u(y) = K(a^2-y^2) // ==> u_max = Ka^2 // ==> K = u_max/a^2 K = u_max/(a*a); drho = 6.*get_LX(lattice) *lattice->param.rho_B[subs] *((1./3.)*(lattice->param.tau[subs]-.5)) *K; if( lattice->param.incompressible) { drho = drho/lattice->param.rho_B[subs]; } //drho = .0188121666666667; //drho = .62680456666658; //drho = 6.2680456666658; //printf("%s (%d) -- drho = %f\n",__FILE__,__LINE__,drho); m = drho/(get_LX(lattice)-1); *macro_var_ptr++ = ( lattice->param.rho_B[subs] + drho/2.) - m*i; #if 0 ( 1.5*( lattice->param.ux_in) /( .25*(get_LY(lattice)-2)*(get_LY(lattice)-2)) ) *( .25*( get_LY(lattice)-2)*( get_LY(lattice)-2) - (i-.5*( get_LY(lattice)-2)-.5) *(i-.5*( get_LY(lattice)-2)-.5) ) ; #endif //printf("%s (%d) -- %d %f\n", __FILE__, __LINE__, i, *(macro_var_ptr-1)); } else if( !lattice->periodic_y[subs]) { // Density gradient corresponding to the desired velocity. // Based on formula for poiseuille velocity profile // // u(x) = K*( a^2 - x^2) // // where, in terms of the density/pressure gradient, // // K = dP/(2 L rho0 nu) ==> drho = 6 L rho0 nu K // // using the equation of state rho = 3 P. // // u_max = (3/2)uy_in u_max = 1.5*(lattice->param.uy_in); // a = .5*(LX-2) . a = .5*(get_LX(lattice)-2); // u(x) = K(a^2-x^2) // ==> u_max = Ka^2 // ==> K = u_max/a^2 K = u_max/(a*a); drho = 6.*get_LY(lattice) *lattice->param.rho_B[subs] *((1./3.)*(lattice->param.tau[subs]-.5)) *K; if( lattice->param.incompressible) { drho = drho/lattice->param.rho_B[subs]; } //drho = .0188121666666667; //drho = .62680456666658; //drho = 6.2680456666658; //printf("%s (%d) -- drho = %f\n",__FILE__,__LINE__,drho); m = drho/(get_LY(lattice)-1); *macro_var_ptr++ = ( lattice->param.rho_B[subs] + drho/2.) - m*j; if( lattice->param.pressure_n_out[0] == 1 && lattice->param.velocity_s_in[0] == 1) { lattice->param.rho_out = ( lattice->param.rho_B[subs] + drho/2.) - m*( get_LY(lattice)-1); } #if 0 ( 1.5*( lattice->param.uy_in) /( .25*(get_LX(lattice)-2)*(get_LX(lattice)-2)) ) *( .25*( get_LX(lattice)-2)*( get_LX(lattice)-2) - (i-.5*( get_LX(lattice)-2)-.5) *(i-.5*( get_LX(lattice)-2)-.5) ) ; #endif //printf("%s (%d) -- %d %f\n", __FILE__, __LINE__, i, *(macro_var_ptr-1)); } else { } } /* if( lattice->param.ic_poiseuille) */ else // !lattice->param.ic_poiseuille { #if 0 *macro_var_ptr++ = lattice->param.rho_B[subs]; #else if( 0)//i<get_LX(lattice)-1) { *macro_var_ptr++ = ( lattice->param.rho_B[subs] * ( 1. - 3. *((get_LY(lattice)-2. + 1.*((get_LY(lattice)%2)?(-1.):(1.)))/2.+1.-j) *lattice->param.gval[0][1] ) ); } else { *macro_var_ptr++ = ( lattice->param.rho_B[subs] * ( 1. - 3. *((get_LY(lattice)-2. + 1.*((get_LY(lattice)%2)?(-1.):(1.)) )/2.+1.-j) *(1.+lattice->param.rho_sigma_out) *lattice->param.gval[0][1] ) ); } #endif } /* if( lattice->param.ic_poiseuille) else */ } else // subs==1 { //*macro_var_ptr++ = 0.; if( 0)//i==get_LX(lattice)-1)//j>5 && j<get_LY(lattice)-1 && i!=5) { *macro_var_ptr++ = lattice->param.rho_sigma_out; } else { *macro_var_ptr++ = 0.; } } #else /* !( INAMURO_SIGMA_COMPONENT) */ if( 0)//hydrostatic( lattice)) { *macro_var_ptr++ = ( lattice->param.rho_B[subs] * ( 1. - 3. *((get_LY(lattice)-2. + 1.*((get_LY(lattice)%2)?(-1.):(1.)) )/2.+1.-j) *lattice->param.gval[0][1] ) ); } else { *macro_var_ptr++ = lattice->param.rho_B[subs]; } #endif /* INAMURO_SIGMA_COMPONENT */ break; } case IC_UNIFORM_RHO_IN: { #if INAMURO_SIGMA_COMPONENT if( subs==0) { *macro_var_ptr++ = lattice->param.rho_in; } else // subs==1 { *macro_var_ptr++ = lattice->param.rho_in; } #else /* !( INAMURO_SIGMA_COMPONENT) */ *macro_var_ptr++ = lattice->param.rho_in; #endif /* INAMURO_SIGMA_COMPONENT */ break; } case IC_BUBBLE: { #if INAMURO_SIGMA_COMPONENT if( subs==0) { *macro_var_ptr++ = lattice->param.rho_A[subs]; } else { if( (i-lattice->param.x0)*(i-lattice->param.x0) + (get_g_SY(lattice) + j-lattice->param.y0)*(get_g_SY(lattice) + j-lattice->param.y0) < lattice->param.r0*lattice->param.r0) { *macro_var_ptr++ = lattice->param.rho_sigma; } else { *macro_var_ptr++ = 0.; } } #else /* !( INAMURO_SIGMA_COMPONENT) */ if( (i-lattice->param.x0)*(i-lattice->param.x0) + (get_g_SY(lattice) + j-lattice->param.y0)*(get_g_SY(lattice) + j-lattice->param.y0) < lattice->param.r0*lattice->param.r0) { *macro_var_ptr++ = lattice->param.rho_A[subs]; } else { *macro_var_ptr++ = lattice->param.rho_B[subs]; } #endif /* INAMURO_SIGMA_COMPONENT */ break; } case IC_YIN_YANG: { if( i < get_LX(lattice)/2) { if( (i-lattice->param.x0/2.)*(i-lattice->param.x0/2.) + (j-lattice->param.y0)*(j-lattice->param.y0) < lattice->param.r0*lattice->param.r0/4.) { *macro_var_ptr++ = lattice->param.rho_A[subs]; } else { *macro_var_ptr++ = lattice->param.rho_B[subs]; } } else { if( (i-3.*lattice->param.x0/2.)*(i-3.*lattice->param.x0/2.) + (j-lattice->param.y0)*(j-lattice->param.y0) < lattice->param.r0*lattice->param.r0/4.) { *macro_var_ptr++ = lattice->param.rho_B[subs]; } else { *macro_var_ptr++ = lattice->param.rho_A[subs]; } } break; } case IC_DIAGONAL: { if( i+j < get_LX(lattice)) { *macro_var_ptr++ = lattice->param.rho_A[subs]; } else { *macro_var_ptr++ = lattice->param.rho_B[subs]; } break; } case IC_2X2_CHECKERS: { if( ( ( i < get_LX(lattice)/2) && ( j < get_LX(lattice)/2)) || ( ( i >= get_LX(lattice)/2) && ( j >= get_LX(lattice)/2)) ) { *macro_var_ptr++ = lattice->param.rho_A[subs]; } else { *macro_var_ptr++ = lattice->param.rho_B[subs]; } break; } case IC_STATIC: { if( NUM_FLUID_COMPONENTS==2) { if( ((double)rand()/(double)RAND_MAX) < lattice->param.cut) { *macro_var_ptr++ = lattice->param.rho_A[subs]; } else { *macro_var_ptr++ = lattice->param.rho_B[subs]; } } else if( NUM_FLUID_COMPONENTS==1) { *macro_var_ptr++ = lattice->param.rho_in + ((double)rand()/(double)RAND_MAX); } else { printf( "%s %d >> " "init_lattice() -- " "Unhandled case NUM_FLUID_COMPONENTS = %d . " "Exiting!\n",__FILE__,__LINE__, NUM_FLUID_COMPONENTS); process_exit(1); } break; } case IC_RECTANGLE: { #if INAMURO_SIGMA_COMPONENT #if ZHANG_AND_CHEN_ENERGY_TRANSPORT if( subs==0) { if( ( i >= lattice->param.x1) && ( get_g_SY(lattice) + j >= lattice->param.y1) && ( i <= lattice->param.x2) && ( get_g_SY(lattice) + j <= lattice->param.y2)) { *macro_var_ptr++ = lattice->param.rho_A[subs]; } else { *macro_var_ptr++ = lattice->param.rho_B[subs]; } } else // subs==1 { if( ( i >= lattice->param.x1) && ( get_g_SY(lattice) + j >= lattice->param.y1) && ( i <= lattice->param.x2) && ( get_g_SY(lattice) + j <= lattice->param.y2)) { *macro_var_ptr++ = lattice->param.rho_sigma; } else { *macro_var_ptr++ = lattice->param.rho_sigma; } } #else /* !( ZHANG_AND_CHEN_ENERGY_TRANSPORT) */ if( subs==0) { *macro_var_ptr++ = lattice->param.rho_A[subs]; } else { if( ( i >= g2lx( lattice, lattice->param.x1)) && ( j >= g2ly( lattice, lattice->param.y1)) && ( i <= g2lx( lattice, lattice->param.x2)) && ( j <= g2ly( lattice, lattice->param.y2)) ) { *macro_var_ptr++ = lattice->param.rho_sigma; } else { //*macro_var_ptr++ = 0.; *macro_var_ptr++ = lattice->param.rho_A[subs]; } } #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ #else /* !( INAMURO_SIGMA_COMPONENT) */ if( ( i >= lattice->param.x1) && ( get_g_SY(lattice) + j >= lattice->param.y1) && ( i <= lattice->param.x2) && ( get_g_SY(lattice) + j <= lattice->param.y2)) { *macro_var_ptr++ = lattice->param.rho_A[subs]; } else { *macro_var_ptr++ = lattice->param.rho_B[subs]; } #endif /* INAMURO_SIGMA_COMPONENT */ break; } case IC_DOT: { if( i == lattice->param.x0 && get_g_SY(lattice) + j == lattice->param.y0) { *macro_var_ptr++ = lattice->param.rho_A[subs]; } else { *macro_var_ptr++ = lattice->param.rho_B[subs]; } break; } case IC_WOLF_GLADROW_DIFFUSION: { #if INAMURO_SIGMA_COMPONENT if( subs==0) { *macro_var_ptr++ = lattice->param.rho_A[subs]; } else // subs==1 { y = (j - ( get_LY(lattice)-1)/2.)/((get_LY(lattice)-1)/200.); *macro_var_ptr++ = (1./(2.*sqrt(PI*15.)))*exp(-y*y/(4.*15.)); } #else /* !( INAMURO_SIGMA_COMPONENT) */ printf("%s %d >> Unhandled case. Exiting!\n", __FILE__, __LINE__); process_exit(1); #endif /* INAMURO_SIGMA_COMPONENT */ break; } case IC_HYDROSTATIC: { #if INAMURO_SIGMA_COMPONENT if( subs==0) { *macro_var_ptr++ = lattice->param.rho_A[subs] - j*( lattice->param.rho_A[subs] - lattice->param.rho_B[subs] ) / get_LY(lattice); } else // subs==1 { *macro_var_ptr++ = 0.; } #else /* !( INAMURO_SIGMA_COMPONENT) */ printf("%s %d >> Unhandled case. Exiting!\n", __FILE__, __LINE__); process_exit(1); #endif /* INAMURO_SIGMA_COMPONENT */ break; } case IC_READ_FROM_FILE: { bmp_read_entry( ic_in, &bmih, &r, &g, &b); printf("%s %d >> %d: rgb = (%d,%d,%d)\n",__FILE__,__LINE__, subs, (unsigned int)r%256, (unsigned int)g%256, (unsigned int)b%256 ); if( NUM_FLUID_COMPONENTS==1) { // Verify grayscale. if( (double)r != (double)g || (double)g != (double)b || (double)r != (double)b) { //printf( // "%s %d >> latman.c: construct_lattice() -- " // "n=%d: [ r g b] = [ %3u %3u %3u]\n",__FILE__,__LINE__, // n, (unsigned int)r%256, // (unsigned int)g%256, (unsigned int)b%256); //printf( // "%s %d >> latman.c: construct_lattice() -- " // "WARNING: File %s is not grayscale. " // "Using the blue channel as the initial condition.\n", // __FILE__,__LINE__, ic_filename); } *macro_var_ptr++ = get_rho_A(lattice,subs)*((double)((unsigned int)b%256))/255.; } else if( NUM_FLUID_COMPONENTS==2) { #if INAMURO_SIGMA_COMPONENT if(subs==0) { *macro_var_ptr++ = get_rho_A(lattice,subs); } else { // Verify grayscale. if( (double)r != (double)g || (double)g != (double)b || (double)r != (double)b) { //printf( // "%s %d >> latman.c: construct_lattice() -- " // "n=%d: [ r g b] = [ %3u %3u %3u]\n",__FILE__,__LINE__, // n, (unsigned int)r%256, // (unsigned int)g%256, (unsigned int)b%256); //printf( // "%s %d >> latman.c: construct_lattice() -- " // "WARNING: File %s is not grayscale. " // "Using the red channel as the initial condition.\n", // __FILE__,__LINE__, ic_filename); } *macro_var_ptr++ = get_rho_sigma(lattice)*(1.-(((double)((unsigned int)b%256))/255.)); } #else /* !( INAMURO_SIGMA_COMPONENT) */ // Use blue channel for subs 0 and red channel for subs 1. if(subs==0) { *macro_var_ptr++ = get_rho_A(lattice,subs)*((double)((unsigned int)b%256))/255.; //printf("%s %d >> subs 0, b=%d, rho = %f\n",__FILE__,__LINE__, (unsigned int)b%256, *(macro_var_ptr-1)); } else if( subs==1) { *macro_var_ptr++ = get_rho_B(lattice,subs)*((double)((unsigned int)r%256))/255.; //printf("%s %d >> subs 1, r=%d, rho = %f\n",__FILE__,__LINE__, (unsigned int)r%256, *(macro_var_ptr-1)); } else { printf("%s %d >> ERROR: Unhandled case! Exiting!\n", __FILE__,__LINE__); process_exit(1); } #endif /* INAMURO_SIGMA_COMPONENT */ } else { printf("%s %d >> ERROR: Unhandled case! Exiting!\n", __FILE__,__LINE__); process_exit(1); } break; } default: { printf( "%s %d >> init_problem() -- Unhandled case " "lattice->param.initial_condition = %d. " "Exiting!\n", __FILE__, __LINE__, lattice->param.initial_condition ); process_exit(1); break; } } /* switch( lattice->param.initial_condition) */ } /* if( ( 1 || !( bc->bc_type & BC_SOLID_NODE)) ) */ else { //if( bc->bc_type & BC_SOLID_NODE) //{ // //*macro_var_ptr++ = lattice->param.rho_A[subs]; // *macro_var_ptr++ = lattice->param.rho_in; //} //else //{ *macro_var_ptr++ = 0.; //} } /* if( ( 1 || !( bc->bc_type & BC_SOLID_NODE)) ) else */ // Set initial velocty. if( ( 0 || !( bc->bc_type & BC_SOLID_NODE)) ) { #if 1 // u_x if( lattice->param.ic_poiseuille && !lattice->periodic_x[subs]) { // Poiseuille flow profile in the x- direction. Assuming // one-lattice-unit walls on both sides. // a = .5*(LY-2) . a = .5*(get_LY(lattice)-2); // u_max = (3/2)ux_in u_max = 1.5*(lattice->param.ux_in); // u(x) = K(a^2-x^2) ==> u_max = Ka^2 ==> K = u_max/a^2 K = u_max/(a*a); // u(x) = K(a^2-x^2) x = (j-.5) - a; *macro_var_ptr++ = K * ( a*a - x*x); #if 0 ( 1.5*( lattice->param.ux_in) /( .25*(get_LY(lattice)-2)*(get_LY(lattice)-2)) ) *( .25*( get_LY(lattice)-2)*( get_LY(lattice)-2) - (j-.5*( get_LY(lattice)-2)-.5) *(j-.5*( get_LY(lattice)-2)-.5) ) ; #endif //printf("%s (%d) -- %d %f\n", __FILE__, __LINE__, j, *(macro_var_ptr-1)); } else { #if INITIALIZE_WITH_UX_IN *macro_var_ptr++ = lattice->param.ux_in; #else /* !( INITIALIZE_WITH_UX_IN) */ *macro_var_ptr++ = 0.; #endif /* INITIALIZE_WITH_UX_IN */ } // u_y if( lattice->param.ic_poiseuille && !lattice->periodic_y[subs]) { // Poiseuille flow profile in the vertical/y- direction. Assuming // one-lattice-unit walls on both sides. // a = .5*(LX-2) . a = .5*(get_LX(lattice)-2); // u_max = (3/2)uy_in u_max = 1.5*(lattice->param.uy_in); // u(x) = K(a^2-x^2) ==> u_max = Ka^2 ==> K = u_max/a^2 K = u_max/(a*a); // u(x) = K(a^2-x^2) x = (i-.5) - a; *macro_var_ptr++ = K * ( a*a - x*x); #if 0 ( 1.5*( lattice->param.uy_in) /( .25*(get_LX(lattice)-2)*(get_LX(lattice)-2)) ) *( .25*( get_LX(lattice)-2)*( get_LX(lattice)-2) - (i-.5*( get_LX(lattice)-2)-.5) *(i-.5*( get_LX(lattice)-2)-.5) ) ; #endif //printf("%s (%d) -- %d %f\n", __FILE__, __LINE__, i, *(macro_var_ptr-1)); } /* if( lattice->param.ic_poiseuille) */ else // !lattice->param.ic_poiseuille { #if INITIALIZE_WITH_UY_IN *macro_var_ptr++ = lattice->param.uy_in; #else /* !( INITIALIZE_WITH_UY_IN) */ *macro_var_ptr++ = 0.; #endif /* INITIALIZE_WITH_UY_IN */ } /* if( lattice->param.ic_poiseuille) else */ #else *macro_var_ptr++ = ( lattice->param.ux_in + lattice->param.ux_out)/2.; *macro_var_ptr++ = ( lattice->param.uy_in + lattice->param.uy_out)/2.; #endif } else { *macro_var_ptr++ = 0.; *macro_var_ptr++ = 0.; } bc++; #if STORE_U_COMPOSITE *upr++ = 0.; *upr++ = 0.; #endif /* STORE_U_COMPOSITE */ } /* for( n=0; n<lattice->NumNodes; n++) */ if( lattice->param.initial_condition == IC_READ_FROM_FILE) { fclose( ic_in); } } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ // Compute initial feq. compute_feq( lattice, 0); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { for( n=0; n<lattice->NumNodes; n++) { f = &(lattice->pdf[subs][n].f[0]); feq = &(lattice->pdf[subs][n].feq[0]); ftemp = &(lattice->pdf[subs][n].ftemp[0]); if( 1 || !( bc[n].bc_type & BC_SOLID_NODE)) { #if 1 // Copy feq to f. f[0]= feq[0]; f[1]= feq[1]; f[2]= feq[2]; f[3]= feq[3]; f[4]= feq[4]; f[5]= feq[5]; f[6]= feq[6]; f[7]= feq[7]; f[8]= feq[8]; // Initialize ftemp. ftemp[0]= 0.; //*(f-9); ftemp[1]= 0.; //*(f-9); ftemp[2]= 0.; //*(f-9); ftemp[3]= 0.; //*(f-9); ftemp[4]= 0.; //*(f-9); ftemp[5]= 0.; //*(f-9); ftemp[6]= 0.; //*(f-9); ftemp[7]= 0.; //*(f-9); ftemp[8]= 0.; //*(f-9); #else // Debug info. To track during the streaming step. // f f[0] = (double)n + 0./10.;// *(f-9); f[1] = (double)n + 1./10.;// *(f-9); f[2] = (double)n + 2./10.;// *(f-9); f[3] = (double)n + 3./10.;// *(f-9); f[4] = (double)n + 4./10.;// *(f-9); f[5] = (double)n + 5./10.;// *(f-9); f[6] = (double)n + 6./10.;// *(f-9); f[7] = (double)n + 7./10.;// *(f-9); f[8] = (double)n + 8./10.;// *(f-9); // ftemp ftemp[0] = (double)n;// *(f-9); ftemp[1] = (double)n;// *(f-9); ftemp[2] = (double)n;// *(f-9); ftemp[3] = (double)n;// *(f-9); ftemp[4] = (double)n;// *(f-9); ftemp[5] = (double)n;// *(f-9); ftemp[6] = (double)n;// *(f-9); ftemp[7] = (double)n;// *(f-9); ftemp[8] = (double)n;// *(f-9); #endif } else { // f = 0. f[0] = 0.; f[1] = 0.; f[2] = 0.; f[3] = 0.; f[4] = 0.; f[5] = 0.; f[6] = 0.; f[7] = 0.; f[8] = 0.; // ftemp = 0. ftemp[0] = 0.; ftemp[1] = 0.; ftemp[2] = 0.; ftemp[3] = 0.; ftemp[4] = 0.; ftemp[5] = 0.; ftemp[6] = 0.; ftemp[7] = 0.; ftemp[8] = 0.; } } /* for( n=0; n<lattice->NumNodes; n++) */ #if NON_LOCAL_FORCES force = lattice->force[subs][0].force; for( n=0; n<lattice->NumNodes; n++) { *force++ = 0.; *force++ = 0.; *force++ = 0.; *force++ = 0.; } #endif /* NON_LOCAL_FORCES */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if NON_LOCAL_FORCES if( NUM_FLUID_COMPONENTS == 2) { if( lattice->param.Gads[0] != 0. || lattice->param.Gads[1] != 0.) { compute_double_fluid_solid_force( lattice); } } else if( NUM_FLUID_COMPONENTS == 1) { } else { printf( "%s %d >> " "compute_feq() -- " "Unhandled case NUM_FLUID_COMPONENTS = %d . " "Exiting!\n",__FILE__,__LINE__, NUM_FLUID_COMPONENTS); process_exit(1); } #endif /* NON_LOCAL_FORCES */ //dump_pdf( lattice, /*time=*/ 9000*lattice->param.FrameRate); //compute_macro_vars( lattice); //dump_macro_vars( lattice, /*time=*/ 0); #if VERBOSITY_LEVEL > 0 printf("init_problem() -- Problem initialized.\n"); #endif /* VERBOSITY_LEVEL > 0 */ } /* void init_problem( struct lattice_struct *lattice) */ // void destruct_lattice( struct lattice_struct *lattice) //############################################################################## // // D E S T R U C T L A T T I C E // // - Destruct lattice. // void destruct_lattice( struct lattice_struct *lattice) { int subs; assert( lattice!=NULL); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { assert( lattice->pdf[subs]!=NULL); free( lattice->pdf[subs]); assert( lattice->macro_vars[subs]!=NULL); free( lattice->macro_vars[subs]); assert( lattice->bc[subs]!=NULL); free( lattice->bc[subs]); #if NON_LOCAL_FORCES assert( lattice->force[subs]!=NULL); free( lattice->force[subs]); #endif /* NON_LOCAL_FORCES */ } #if STORE_U_COMPOSITE free( lattice->upr); #endif /* STORE_U_COMPOSITE */ process_finalize(); free( lattice); } /* void destruct_lattice( struct lattice_struct *lattice) */ #if INAMURO_SIGMA_COMPONENT && STORE_BTC #if 0 void sigma_stuff( lattice_ptr lattice) { int btc_time; int i, j, n; double btc_val01, btc_val02, btc_val03, btc_val04; int width01, width02, width03, width04; // Turn off concentration boundaries when time is up. if( lattice->param.sigma_stop >= 0 && lattice->time > lattice->param.sigma_stop) { lattice->param.rho_sigma_in = 0.; lattice->param.rho_sigma_out = 0.; } /* if( lattice->param.sigma_stop >= 0 && ... */ // Accumulate break through curve. if( !( lattice->param.sigma_btc_rate <= 0 || lattice->FlowDir==0)) { if( lattice->param.sigma_start <= lattice->time && ( lattice->param.sigma_stop < 0 || lattice->param.sigma_stop >= lattice->time ) && !( lattice->time % lattice->param.sigma_btc_rate)) { btc_time = ( lattice->time - ((lattice->param.sigma_start>0) ?(lattice->param.sigma_start) :(0)) ) / lattice->param.sigma_btc_rate; //printf("%s (%d) >> btc_time = %d (%d)\n", // __FILE__,__LINE__,btc_time,lattice->SizeBTC); btc_val01 = 0.; btc_val02 = 0.; btc_val03 = 0.; btc_val04 = 0.; if( lattice->FlowDir == /*Horizontal*/1) { i = ( (lattice->param.sigma_btc_spot >= 0) ? (lattice->param.sigma_btc_spot) : (get_LX(lattice)-2)); width01 = 0; width02 = 0; width03 = 0; width04 = 0; for( j=0; j<get_LY(lattice); j++) { // // Concentration at sigma_spot-1 // n = i-1 + j*get_LX(lattice); if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) { btc_val01 += lattice->macro_vars[1][n].rho; width01++; } /* if( !( lattice->bc[n].bc_type & BC_SOLID_NODE)) */ // // Concentration at sigma_spot // n = i + j*get_LX(lattice); if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) { btc_val02 += lattice->macro_vars[1][n].rho; width02++; } /* if( !( lattice->bc[n].bc_type & BC_SOLID_NODE)) */ // // Concentration at sigma_spot+1 // n = i+1 + j*get_LX(lattice); if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) { btc_val03 += lattice->macro_vars[1][n].rho; width03++; } /* if( !( lattice->bc[n].bc_type & BC_SOLID_NODE)) */ // // Velocity at sigma_spot // n = i + j*get_LX(lattice); if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) { btc_val04 += lattice->macro_vars[1][n].u[0]; width04++; } /* if( !( lattice->bc[n].bc_type & BC_SOLID_NODE)) */ } /* for( j=0; j<get_LY(lattice); j++) */ btc_val01 /= width01; btc_val02 /= width02; btc_val03 /= width03; btc_val04 /= width04; } /* if( lattice->FlowDir == 1) */ else if( lattice->FlowDir == /*Vertical*/2) { j = ( (lattice->param.sigma_btc_spot >= 0) ? (lattice->param.sigma_btc_spot) : (get_LY(lattice)-2)); width01 = 0; width02 = 0; width03 = 0; width04 = 0; for( i=0; i<get_LX(lattice); i++) { // // Concentration at sigma_spot-1 // n = i + (j-1)*get_LX(lattice); if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) { btc_val01 += lattice->macro_vars[1][n].rho; width01++; } /* if( !( lattice->bc[n].bc_type & BC_SOLID_NODE)) */ // // Concentration at sigma_spot // n = i + (j )*get_LX(lattice); if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) { btc_val02 += lattice->macro_vars[1][n].rho; width02++; } /* if( !( lattice->bc[n].bc_type & BC_SOLID_NODE)) */ // // Concentration at sigma_spot+1 // n = i + (j+1)*get_LX(lattice); if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) { btc_val03 += lattice->macro_vars[1][n].rho; width03++; } /* if( !( lattice->bc[n].bc_type & BC_SOLID_NODE)) */ // // Velocity at sigma_spot // n = i + j*get_LX(lattice); if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) { btc_val04 += lattice->macro_vars[1][n].u[1]; width04++; } /* if( !( lattice->bc[n].bc_type & BC_SOLID_NODE)) */ } /* for( i=0; i<get_LX(lattice); i++) */ btc_val01 /= width01; btc_val02 /= width02; btc_val03 /= width03; btc_val04 /= width04; } /* else if( lattice->FlowDir == 2) */ else // Flow direction is undetermined. { // Unhandled case. // TODO: Warning message? } /* if( lattice->FlowDir == ?) else */ //printf("%s (%d) >> btc_val01 = %f\n",__FILE__,__LINE__,btc_val01); lattice->param.sigma_btc[5*btc_time+0] = lattice->time; lattice->param.sigma_btc[5*btc_time+1] = btc_val01; lattice->param.sigma_btc[5*btc_time+2] = btc_val02; lattice->param.sigma_btc[5*btc_time+3] = btc_val03; lattice->param.sigma_btc[5*btc_time+4] = btc_val04; } /* if( !( lattice->time % lattice->param.sigma_btc_rate)) */ } /* if( lattice->param.sigma_start <= lattice->time) */ } /* void sigma_stuff( lattice_ptr lattice) */ #else void sigma_stuff( lattice_ptr lattice) { int btc_time; int i, j, n, nm, np; double btc_val01, btc_val02, btc_val03, btc_val04; int width; #if 0 // Turn off concentration boundaries when time is up. if( lattice->param.sigma_stop >= 0 && lattice->time > lattice->param.sigma_stop) { lattice->param.rho_sigma_in = 0.; lattice->param.rho_sigma_out = 0.; } /* if( lattice->param.sigma_stop >= 0 && ... */ #endif // Accumulate break through curve. if( !( lattice->param.sigma_btc_rate <= 0 || lattice->FlowDir==0)) { if( lattice->param.sigma_start <= lattice->time // && ( // lattice->param.sigma_stop < 0 // || // lattice->param.sigma_stop >= lattice->time // ) && !( lattice->time % lattice->param.sigma_btc_rate)) { btc_time = ( lattice->time - ((lattice->param.sigma_start>0) ?(lattice->param.sigma_start) :(0)) ) / lattice->param.sigma_btc_rate; //printf("%s (%d) >> btc_time = %d (%d)\n", // __FILE__,__LINE__,btc_time,lattice->SizeBTC); btc_val01 = 0.; btc_val02 = 0.; btc_val03 = 0.; btc_val04 = 0.; if( lattice->FlowDir == /*Horizontal*/1) { i = ( (lattice->param.sigma_btc_spot >= 0) ? (lattice->param.sigma_btc_spot) : (get_LX(lattice)-2)); width = 0; for( j=0; j<get_LY(lattice); j++) { nm = i-1 + j*get_LX(lattice); n = i + j*get_LX(lattice); np = i+1 + j*get_LX(lattice); if( !( lattice->bc[0][nm].bc_type & BC_SOLID_NODE || lattice->bc[0][n ].bc_type & BC_SOLID_NODE || lattice->bc[0][np].bc_type & BC_SOLID_NODE ) ) { // Concentration at sigma_spot-1 btc_val01 += lattice->macro_vars[1][nm].rho; // Concentration at sigma_spot btc_val02 += lattice->macro_vars[1][n ].rho; // Concentration at sigma_spot+1 btc_val03 += lattice->macro_vars[1][np].rho; // Velocity at sigma_spot btc_val04 += lattice->macro_vars[1][n ].u[0]; width++; } /* if( !( lattice->bc[n].bc_type & BC_SOLID_NODE)) */ } /* for( j=0; j<get_LY(lattice); j++) */ btc_val01 /= width; btc_val02 /= width; btc_val03 /= width; btc_val04 /= width; } /* if( lattice->FlowDir == 1) */ else if( lattice->FlowDir == /*Vertical*/2) { j = ( (lattice->param.sigma_btc_spot >= 0) ? (lattice->param.sigma_btc_spot) : (get_LY(lattice)-2)); width = 0; for( i=0; i<get_LX(lattice); i++) { nm = i + (j-1)*get_LX(lattice); n = i + (j )*get_LX(lattice); np = i + (j+1)*get_LX(lattice); if( !( lattice->bc[0][nm].bc_type & BC_SOLID_NODE || lattice->bc[0][n ].bc_type & BC_SOLID_NODE || lattice->bc[0][np].bc_type & BC_SOLID_NODE ) ) { // Concentration at sigma_spot-1 btc_val01 += lattice->macro_vars[1][nm].rho; // Concentration at sigma_spot btc_val02 += lattice->macro_vars[1][n ].rho; // Concentration at sigma_spot+1 btc_val03 += lattice->macro_vars[1][np].rho; // Velocity at sigma_spot btc_val04 += lattice->macro_vars[1][n ].u[1]; width++; } /* if( !( lattice->bc[n].bc_type & BC_SOLID_NODE)) */ } /* for( i=0; i<get_LX(lattice); i++) */ btc_val01 /= width; btc_val02 /= width; btc_val03 /= width; btc_val04 /= width; } /* else if( lattice->FlowDir == 2) */ else // Flow direction is undetermined. { // Unhandled case. // TODO: Warning message? } /* if( lattice->FlowDir == ?) else */ //printf("%s (%d) >> btc_val01 = %f\n",__FILE__,__LINE__,btc_val01); lattice->param.sigma_btc[5*btc_time+0] = lattice->time; lattice->param.sigma_btc[5*btc_time+1] = btc_val01; lattice->param.sigma_btc[5*btc_time+2] = btc_val02; lattice->param.sigma_btc[5*btc_time+3] = btc_val03; lattice->param.sigma_btc[5*btc_time+4] = btc_val04; } /* if( !( lattice->time % lattice->param.sigma_btc_rate)) */ } /* if( lattice->param.sigma_start <= lattice->time) */ } /* void sigma_stuff( lattice_ptr lattice) */ #endif #endif /* INAMURO_SIGMA_COMPONENT && STORE_BTC */ // int get_sizeof_lattice_structure( lattice_ptr lattice) //############################################################################## // // G E T _ S I Z E O F _ L A T T I C E _ S T R U C T U R E // // - Return size of struct lattice_struct in bytes. // int get_sizeof_lattice_structure( lattice_ptr lattice) { return sizeof( struct lattice_struct); } /* int get_sizeof_lattice_structure( lattice_ptr lattice) */ // int get_sizeof_lattice( lattice_ptr lattice) //############################################################################## // // G E T _ S I Z E O F _ L A T T I C E // // - Return size of lattice in bytes. // int get_sizeof_lattice( lattice_ptr lattice) { return sizeof(int) // NumNodes + sizeof(int) // NumTimeSteps + sizeof(int) // time + sizeof(int) // frame + sizeof(int)*NUM_FLUID_COMPONENTS // periodic_x + sizeof(int)*NUM_FLUID_COMPONENTS // periodic_y #if INAMURO_SIGMA_COMPONENT + sizeof(int) // SizeBTC + sizeof(int) // FlowDir #endif + sizeof(struct param_struct) + lattice->NumNodes * ( NUM_FLUID_COMPONENTS*sizeof(struct pdf_struct) + NUM_FLUID_COMPONENTS*sizeof(struct macro_vars_struct) + NUM_FLUID_COMPONENTS*sizeof(struct bc_struct) #if NON_LOCAL_FORCES + NUM_FLUID_COMPONENTS*sizeof(struct force_struct) #endif /* NON_LOCAL_FORCES */ #if STORE_U_COMPOSITE + sizeof(struct upr_struct) #endif /* STORE_U_COMPOSITE */ #if POROUS_MEDIA || FREED_POROUS_MEDIA + sizeof(struct ns_struct) #endif /* POROUS_MEDIA */ ) // Include lbmpi_ptr ? // Include user_stuff_struct ? ; } /* int get_sizeof_lattice( lattice_ptr lattice) */ // int get_num_active_nodes( lattice_ptr lattice) //############################################################################## // // G E T _ N U M B E R _ A C T I V E _ N O D E S // // - Return number of active nodes. // int get_num_active_nodes( lattice_ptr lattice) { int n, k; k = 0; for( n=0; n<lattice->NumNodes; n++) { if( lattice->bc[0][n].bc_type != INACTIVE_NODE) { k++; } } return k; } /* int get_num_active_nodes( lattice_ptr lattice) */ // void check_point_save( lattice_ptr lattice) void check_point_save( lattice_ptr lattice) { FILE *o; char filename[1024]; int n, a; printf("############################################################\n"); printf(" \n"); printf("%s %d >> Saving check point.\n",__FILE__,__LINE__); printf(" \n"); printf("############################################################\n"); printf(" \n"); printf(" #### ### ### ####### #### ### ## ###### ### ##### ## ### #######\n"); printf(" # # # # # # # # # # # # # # # # # # # #\n"); printf(" # # # # # # # # # # # # ## # # \n"); printf(" # # # # # # # # # # # # # ## # # \n"); printf(" # ##### #### # # # ##### # # # # # # # \n"); printf(" # # # # # # ### # # # # # ## # \n"); printf(" # # # # # # # # # # # # ## # \n"); printf(" # # # # # # # # # # # # # # # # # \n"); printf(" #### ### ### ####### #### ### ## #### ### ##### ### # ### \n"); printf(" \n"); printf("############################################################\n"); sprintf(filename, "./%s/checkpoint_%dx%d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice)); if( !( o = fopen(filename,"w+"))) { printf("%s %d >> ERROR: Can't save checkpoint file \"%s\".\n", __FILE__,__LINE__,filename); return; } // Write check point information. fprintf( o, "%d\n", lattice->frame); fprintf( o, "%d\n", get_LX(lattice)); fprintf( o, "%d\n", get_LY(lattice)); for( n=0; n<get_NumNodes(lattice); n++) { for( a=0; a<9; a++) { fprintf( o, "%20.17f\n",lattice->pdf[0][n].feq[a]); } for( a=0; a<9; a++) { fprintf( o, "%20.17f\n",lattice->pdf[0][n].f[a]); } for( a=0; a<9; a++) { fprintf( o, "%20.17f\n",lattice->pdf[0][n].ftemp[a]); } if(NUM_FLUID_COMPONENTS==2) { for( a=0; a<9; a++) { fprintf( o, "%20.17f\n",lattice->pdf[1][n].feq[a]); } for( a=0; a<9; a++) { fprintf( o, "%20.17f\n",lattice->pdf[1][n].f[a]); } for( a=0; a<9; a++) { fprintf( o, "%20.17f\n",lattice->pdf[1][n].ftemp[a]); } } /* if(NUM_FLUID_COMPONENTS==2) */ } /* for( n=0; n<get_NumNodes(lattice); n++) */ #if INAMURO_SIGMA_COMPONENT && STORE_BTC fprintf( o, "%d\n", lattice->SizeBTC); for( n=0; n<5*lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", lattice->param.sigma_btc[n]); } #endif /* INAMURO_SIGMA_COMPONENT && STORE_BTC */ fclose(o); printf("%s %d >> Saving check point done.\n",__FILE__,__LINE__); } /* void check_point_save( lattice_ptr lattice) */ // void check_point_load( lattice_ptr lattice) void check_point_load( lattice_ptr lattice) { FILE *in; char filename[1024]; int n, a; int LX_in, LY_in; int SizeBTC; printf("############################################################\n"); printf(" \n"); printf("%s %d >> Loading check point.\n",__FILE__,__LINE__); printf(" \n"); printf("############################################################\n"); printf(" \n"); printf(" #### ### ### ####### #### ### ## ###### ### ##### ## ### #######\n"); printf(" # # # # # # # # # # # # # # # # # # # #\n"); printf(" # # # # # # # # # # # # ## # # \n"); printf(" # # # # # # # # # # # # # ## # # \n"); printf(" # ##### #### # # # ##### # # # # # # # \n"); printf(" # # # # # # ### # # # # # ## # \n"); printf(" # # # # # # # # # # # # ## # \n"); printf(" # # # # # # # # # # # # # # # # # \n"); printf(" #### ### ### ####### #### ### ## #### ### ##### ### # ### \n"); printf(" \n"); printf("############################################################\n"); sprintf(filename, "./%s/checkpoint.dat", get_out_path(lattice)); if( !( in = fopen(filename,"r+"))) { printf("%s %d >> WARNING: Can't load checkpoint \"%s\".\n", __FILE__,__LINE__,filename); return; } // Read check point information. fscanf( in, "%d", &(lattice->frame)); fscanf( in, "%d", &LX_in); fscanf( in, "%d", &LY_in); if( LX_in != get_LX(lattice)) { printf( "%s %d >> ERROR: " "Checkpoint LX %d does not match current domain LX %d.\n", __FILE__,__LINE__, LX_in, get_LX(lattice)); if( LY_in != get_LY(lattice)) { printf( "%s %d >> ERROR: " "Checkpoint LY %d does not match current domain LY %d.\n", __FILE__,__LINE__, LY_in, get_LY(lattice)); } process_exit(1); } if( LY_in != get_LY(lattice)) { printf( "%s %d >> ERROR: " "Checkpoint LY %d does not match current domain LY %d.\n", __FILE__,__LINE__, LY_in, get_LY(lattice)); process_exit(1); } for( n=0; n<get_NumNodes(lattice); n++) { for( a=0; a<9; a++) { fscanf( in, "%lf",lattice->pdf[0][n].feq+a); } for( a=0; a<9; a++) { fscanf( in, "%lf",lattice->pdf[0][n].f+a); } for( a=0; a<9; a++) { fscanf( in, "%lf",lattice->pdf[0][n].ftemp+a); } if(NUM_FLUID_COMPONENTS==2) { for( a=0; a<9; a++) { fscanf( in, "%lf",lattice->pdf[1][n].feq+a); } for( a=0; a<9; a++) { fscanf( in, "%lf",lattice->pdf[1][n].f+a); } for( a=0; a<9; a++) { fscanf( in, "%lf",lattice->pdf[1][n].ftemp+a); } } /* if(NUM_FLUID_COMPONENTS==2) */ } /* for( n=0; n<get_NumNodes(lattice); n++) */ #if INAMURO_SIGMA_COMPONENT && STORE_BTC fscanf( in, "%d", &SizeBTC); for( n=0; n<5*SizeBTC; n++) { fscanf( in, "%lf", lattice->param.sigma_btc+n); } #endif /* INAMURO_SIGMA_COMPONENT && STORE_BTC */ fclose(in); printf("%s %d >> Loading check point done.\n",__FILE__,__LINE__); } /* void check_point_load( lattice_ptr lattice) */ // vim: foldmethod=syntax
111pjb-one
src/latman.c
C
gpl3
89,837
#ifndef FLAGS_H #define FLAGS_H //############################################################################## // // flags.h // // - Preprocessor flags for lb2d_prime. // // Set VERBOSITY_LEVEL to correspond to how deep into nested loops to // print debug and related output. Stuff will be printed down to // loops nested VERBOSITY_LEVEL-1 deep. For example, // // VERBOSITY_LEVEL 0 ==> Nothing is printed, even outside of loops. // VERBOSITY_LEVEL 1 ==> Only stuff outside of loops is printed. // VERBOSITY_LEVEL 2 ==> Stuff inside the first level of loops is printed. // VERBOSITY_LEVEL 3 ==> Stuff inside the second level of loops is printed. // // Flag: VERBOSITY_LEVEL #define VERBOSITY_LEVEL 1 // If SAY_HI is on, some routines will display "hi" and "bye" messages // to stdout. // Flag: SAY_HI #define SAY_HI 0 // NUM_FLUID_COMPONENTS specifies the number of fluid components. // Flag: NUM_FLUID_COMPONENTS #define NUM_FLUID_COMPONENTS 2 // If NUM_FLUID_COMPONENTS is 2, the second component can be the sigma // component for solute (or thermal) transport as in Inamuro & Yoshino // by turning on INAMURO_SIGMA_COMPONENT . // Flag: INAMURO_SIGMA_COMPONENT #define INAMURO_SIGMA_COMPONENT ( 0 && NUM_FLUID_COMPONENTS==2) // Toggle Zhang & Chen energy transport method, PRE 67, 0066711 (2003). // Supposed to give thermodynamic consistency unlike old Shan & Chen method. // And supports general equation of state P = P(rho,T). // Utilizes the Inamuro component for evolution of the energy transport // equation. Employs modified compute_phase_force routine to compute // body force term representing non-local interaction potential U among // particles. // Flag: ZHANG_AND_CHEN_ENERGY_TRANSPORT #define ZHANG_AND_CHEN_ENERGY_TRANSPORT ( 0 && (INAMURO_SIGMA_COMPONENT)) // Simulate POROUS_MEDIA via a solid density parameter // as proposed by Dardis and McCloskey, // Phys Rev E, 57, 4, 4834-4837, 1998 // Flag: POROUS_MEDIA #define POROUS_MEDIA 0 // When there are two (or more) fluid components, a single velocity is // sometimes (always?) used to compute the equilibrium distribution // function. This single velocity will be called upr, and the // STORE_U_COMPOSITE flag will toggle its use. // Flag: STORE_U_COMPOSITE #define STORE_U_COMPOSITE ( 1 && ( (NUM_FLUID_COMPONENTS)==2 \ &&!((INAMURO_SIGMA_COMPONENT)))) // If DO_NOT_STORE_SOLIDS is on, then only the nodes necessary to flow are // stored. In this case, extra storage is needed for geometry information // (e.g. node neighbors). If the ratio of fluid nodes to solid nodes is // small (<~.7), this results in lower storage requirements. // Flag: DO_NOT_STORE_SOLIDS #define DO_NOT_STORE_SOLIDS 0 // NON_LOCAL_FORCES toggles any mechanisms for computing and storing // non-local (interaction) forces. // Flag: NON_LOCAL_FORCES #define NON_LOCAL_FORCES ( 1 && !(INAMURO_SIGMA_COMPONENT&&!ZHANG_AND_CHEN_ENERGY_TRANSPORT)) // The phase force weighting factors: // WM = weights in the direction of major axes // WD = weights in the direction of diagonals // According to Raskinmaki, it should be WM=2 and WD=1. // According to Chen (via correspondence) it should be WM=4 and WD=1. // According to Sukop and Thorne, it should be WM=1/9 and WD=1/36. // The corresonding G values (a.k.a. G, as in params.in) for the usual // equation of state that we like are -5, -10/3, and -120, respectively. // Flag: WM #define WM (1./ 9.) // Flag: WD #define WD (1./36.) // Toggle manage_body_force call at beginning of time loop for // gradually increasing/decreasing gravity. // Flag: MANAGE_BODY_FORCE #define MANAGE_BODY_FORCE 0 // Toggle break through curve (BTC) mechanism for sigma component. // Flag: STORE_BTC #define STORE_BTC ( 1 && INAMURO_SIGMA_COMPONENT) // // Toggle DETERMINE_FLOW_DIRECTION to attempt to determine the direction of // flow. // // Assigns FlowDir = { 0, 1, 2} = { indeterminate, vertical, horizontal} // // NOTE: This determination informs the breakthrough curve mechanism which // should be used in a simple situation with either pressure/velocity // boundaries driving the flow in one direction or gravity driving the flow // in one direction. If the direction of flow cannot be determined, FlowDir // will be set to indeterminate (=0) and a BTC will not be stored. // // NOTE: This determination also informs the sigma slip boundary which // should only be used in the simple situation of flow through a channel // where the geometry is trivial and the direction of flow is obvious. // // Flag: DETERMINE_FLOW_DIRECTION #define DETERMINE_FLOW_DIRECTION 1 // Toggle mechanism to initialize domain with ux_in or uy_in. This is // useful for setting a velocity in a periodic domain without using // fluid boundary conditions. // Flag: INITIALIZE_WITH_UX_IN #define INITIALIZE_WITH_UX_IN 0 // Flag: INITIALIZE_WITH_UY_IN #define INITIALIZE_WITH_UY_IN 1 // Dumping the density and velocity data to files can be time consuming and // take up a lot of disk space. If all that is needed is the BMP files, then // turn WRITE_MACRO_VAR_DAT_FILES off to save time and space. // Flag: WRITE_MACRO_VAR_DAT_FILES #define WRITE_MACRO_VAR_DAT_FILES 0 // Usually the density and velocity are written only for the active nodes // and in a way designed for post-processing. Additional files with the // variables written in a readable grid of all lattice nodes will be // generated when WRITE_RHO_AND_U_TO_TXT is on. This is done in an // inefficient way and is intended only for debugging purposes on tiny // lattices. Note that if WRITE_MACRO_VAR_DAT_FILES is off, this flag // has no effect. // Flag: WRITE_RHO_AND_U_TO_TXT #define WRITE_RHO_AND_U_TO_TXT 0 // WRITE_PDF_DAT_FILES is analogous to WRITE_MACRO_VAR_DAT_FILES. // Flag: WRITE_PDF_DAT_FILES #define WRITE_PDF_DAT_FILES 0 // WRITE_PDF_TO_TXT is analogous to WRITE_RHO_AND_U_TO_TXT. // Flag: WRITE_PDF_TO_TXT #define WRITE_PDF_TO_TXT 0 // Value used to represent an INACTIVE_NODE . This is used in the list // of neighbors ( struct node_struct::nn). It is also used in the // map from (i,j) space onto n index space in rho2bmp() and u2bmp(). // Flag: INACTIVE_NODE #define INACTIVE_NODE -1 // Negative densities (f_a) generally signify impending doom. The code // will die "gracefully" when this happens if PUKE_NEGATIVE_DENSITIES is on. // Might want to turn this off to boost performance on big, long runs that // are expected to survive without such instabilities. // Flag: PUKE_NEGATIVE_DENSITIES #define PUKE_NEGATIVE_DENSITIES 0 // Turn one of these on for coloring of the solids in bmp files. // Flag: SOLID_COLOR_IS_CHECKERBOARD #define SOLID_COLOR_IS_CHECKERBOARD 0 // Flag: SOLID_COLOR_IS_BLACK #define SOLID_COLOR_IS_BLACK 1 // Flag: DELAY #define DELAY 0 // Flag: END_GRAV #define END_GRAV 2000 // A single white pixel will be placed in at the (0,0) lattice node if // MARK_ORIGIN_FOR_REFERENCE is turned on. This is good for assisting with the // problem of tracking orientation of the results between regimes (e.g. C, BMP, // Matlab...). // Flag: MARK_ORIGIN_FOR_REFERENCE #define MARK_ORIGIN_FOR_REFERENCE 0 // Flag: PERTURBATIONS #define PERTURBATIONS 0 // If WRITE_CHEN_DAT_FILES is on, the code will output old style chen_*.dat // files to be processed by the old lb_rho_v*.m matlab scripts. // Flag: WRITE_CHEN_DAT_FILES #define WRITE_CHEN_DAT_FILES 0 #endif /* FLAGS_H */
111pjb-one
src/flags_what.h
C
gpl3
7,416
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // flags.h // // - Preprocessor flags for lb2d_prime. // #ifndef FLAGS_H #define FLAGS_H // Set VERBOSITY_LEVEL to correspond to how deep into nested loops to // print debug and related output. Stuff will be printed down to // loops nested VERBOSITY_LEVEL-1 deep. For example, // // VERBOSITY_LEVEL 0 ==> Nothing is printed, even outside of loops. // VERBOSITY_LEVEL 1 ==> Only stuff outside of loops is printed. // VERBOSITY_LEVEL 2 ==> Stuff inside the first level of loops is printed. // VERBOSITY_LEVEL 3 ==> Stuff inside the second level of loops is printed. // // Flag: VERBOSITY_LEVEL #define VERBOSITY_LEVEL 1 // If SAY_HI is on, some routines will display "hi" and "bye" messages // to stdout. // Flag: SAY_HI #define SAY_HI 0 // NUM_FLUID_COMPONENTS specifies the number of fluid components. // Flag: NUM_FLUID_COMPONENTS #define NUM_FLUID_COMPONENTS 2 // If NUM_FLUID_COMPONENTS is 2, the second component can be the sigma // component for solute (or thermal) transport as in Inamuro & Yoshino // by turning on INAMURO_SIGMA_COMPONENT . // Flag: INAMURO_SIGMA_COMPONENT #define INAMURO_SIGMA_COMPONENT ( 0 && NUM_FLUID_COMPONENTS==2) // Toggle Zhang & Chen energy transport method, PRE 67, 0066711 (2003). // Supposed to give thermodynamic consistency unlike old Shan & Chen method. // And supports general equation of state P = P(rho,T). // Utilizes the Inamuro component for evolution of the energy transport // equation. Employs modified compute_phase_force routine to compute // body force term representing non-local interaction potential U among // particles. // Flag: ZHANG_AND_CHEN_ENERGY_TRANSPORT #define ZHANG_AND_CHEN_ENERGY_TRANSPORT ( 0 && (INAMURO_SIGMA_COMPONENT)) // Simulate POROUS_MEDIA via a solid density parameter // as proposed by Dardis and McCloskey, // Phys Rev E, 57, 4, 4834-4837, 1998 // Flag: POROUS_MEDIA #define POROUS_MEDIA 0 // When there are two (or more) fluid components, a single velocity is // sometimes (always?) used to compute the equilibrium distribution // function. This single velocity will be called upr, and the // STORE_U_COMPOSITE flag will toggle its use. // Flag: STORE_U_COMPOSITE #define STORE_U_COMPOSITE ( 1 && ( (NUM_FLUID_COMPONENTS)==2 \ &&!((INAMURO_SIGMA_COMPONENT)))) // If DO_NOT_STORE_SOLIDS is on, then only the nodes necessary to flow are // stored. In this case, extra storage is needed for geometry information // (e.g. node neighbors). If the ratio of fluid nodes to solid nodes is // small (<~.7), this results in lower storage requirements. // Flag: DO_NOT_STORE_SOLIDS #define DO_NOT_STORE_SOLIDS 0 // If COMPUTE_ON_SOLIDS is on, macroscopic variables and feq will be computed // on solid nodes, even though they are not conceptually meaningful there. // This can be helpful for debugging purposes. #define COMPUTE_ON_SOLIDS 1 // NON_LOCAL_FORCES toggles any mechanisms for computing and storing // non-local (interaction) forces. // Flag: NON_LOCAL_FORCES #define NON_LOCAL_FORCES ( 1 && !(INAMURO_SIGMA_COMPONENT&&!ZHANG_AND_CHEN_ENERGY_TRANSPORT)) // The phase force weighting factors: // WM = weights in the direction of major axes // WD = weights in the direction of diagonals // According to Raskinmaki, it should be WM=2 and WD=1. // According to Chen (via correspondence) it should be WM=4 and WD=1. // According to Sukop and Thorne, it should be WM=1/9 and WD=1/36. // The corresonding G values (a.k.a. G, as in params.in) for the usual // equation of state that we like are -5, -10/3, and -120, respectively. // Flag: WM #define WM (1./ 9.) // Flag: WD #define WD (1./36.) // Toggle manage_body_force call at beginning of time loop for // gradually increasing/decreasing gravity. // Flag: MANAGE_BODY_FORCE #define MANAGE_BODY_FORCE 0 // Toggle break through curve (BTC) mechanism for sigma component. // Flag: STORE_BTC #define STORE_BTC ( 1 && INAMURO_SIGMA_COMPONENT) // // Toggle DETERMINE_FLOW_DIRECTION to attempt to determine the direction of // flow. // // Assigns FlowDir = { 0, 1, 2} = { indeterminate, vertical, horizontal} // // NOTE: This determination informs the breakthrough curve mechanism which // should be used in a simple situation with either pressure/velocity // boundaries driving the flow in one direction or gravity driving the flow // in one direction. If the direction of flow cannot be determined, FlowDir // will be set to indeterminate (=0) and a BTC will not be stored. // // NOTE: This determination also informs the sigma slip boundary which // should only be used in the simple situation of flow through a channel // where the geometry is trivial and the direction of flow is obvious. // // Flag: DETERMINE_FLOW_DIRECTION #define DETERMINE_FLOW_DIRECTION 1 // Toggle mechanism to initialize domain with ux_in or uy_in. This is // useful for setting a velocity in a periodic domain without using // fluid boundary conditions. // Flag: INITIALIZE_WITH_UX_IN #define INITIALIZE_WITH_UX_IN 0 // Flag: INITIALIZE_WITH_UY_IN #define INITIALIZE_WITH_UY_IN 0 // Dumping the density and velocity data to files can be time consuming and // take up a lot of disk space. If all that is needed is the BMP files, then // turn WRITE_MACRO_VAR_DAT_FILES off to save time and space. // Flag: WRITE_MACRO_VAR_DAT_FILES #define WRITE_MACRO_VAR_DAT_FILES 0 // Usually the density and velocity are written only for the active nodes // and in a way designed for post-processing. Additional files with the // variables written in a readable grid of all lattice nodes will be // generated when WRITE_RHO_AND_U_TO_TXT is on. This is done in an // inefficient way and is intended only for debugging purposes on tiny // lattices. Note that if WRITE_MACRO_VAR_DAT_FILES is off, this flag // has no effect. // Flag: WRITE_RHO_AND_U_TO_TXT #define WRITE_RHO_AND_U_TO_TXT 0 // WRITE_PDF_DAT_FILES is analogous to WRITE_MACRO_VAR_DAT_FILES. // Flag: WRITE_PDF_DAT_FILES #define WRITE_PDF_DAT_FILES 0 // WRITE_PDF_TO_TXT is analogous to WRITE_RHO_AND_U_TO_TXT. // Flag: WRITE_PDF_TO_TXT #define WRITE_PDF_TO_TXT 0 // Value used to represent an INACTIVE_NODE . This is used in the list // of neighbors ( struct node_struct::nn). It is also used in the // map from (i,j) space onto n index space in rho2bmp() and u2bmp(). // Flag: INACTIVE_NODE #define INACTIVE_NODE -1 // Negative densities (f_a) generally signify impending doom. The code // will die "gracefully" when this happens if PUKE_NEGATIVE_DENSITIES is on. // Might want to turn this off to boost performance on big, long runs that // are expected to survive without such instabilities. // Flag: PUKE_NEGATIVE_DENSITIES #define PUKE_NEGATIVE_DENSITIES 0 // Turn one of these on for coloring of the solids in bmp files. // Flag: SOLID_COLOR_IS_CHECKERBOARD #define SOLID_COLOR_IS_CHECKERBOARD 0 // Flag: SOLID_COLOR_IS_BLACK #define SOLID_COLOR_IS_BLACK 1 // Flag: DELAY #define DELAY 0 // Flag: END_GRAV #define END_GRAV 2000 // A single white pixel will be placed in at the (0,0) lattice node if // MARK_ORIGIN_FOR_REFERENCE is turned on. This is good for assisting with the // problem of tracking orientation of the results between regimes (e.g. C, BMP, // Matlab...). // Flag: MARK_ORIGIN_FOR_REFERENCE #define MARK_ORIGIN_FOR_REFERENCE 0 // Flag: PERTURBATIONS #define PERTURBATIONS 0 // If WRITE_CHEN_DAT_FILES is on, the code will output old style chen_*.dat // files to be processed by the old lb_rho_v*.m matlab scripts. // Flag: WRITE_CHEN_DAT_FILES #define WRITE_CHEN_DAT_FILES 0 // NEW_PARAMS_INPUT_ROUTINE is a temporary flag to switch between the old // params input routine and the new one under development. When the new // one is ready, it should be used exclusively. #define NEW_PARAMS_INPUT_ROUTINE 1 #endif /* FLAGS_H */
111pjb-one
src/flags_bak20061115.h
C
gpl3
7,934
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // flags.h // // - Preprocessor flags for lb2d_prime. // #ifndef FLAGS_H #define FLAGS_H // Set VERBOSITY_LEVEL to correspond to how deep into nested loops to // print debug and related output. Stuff will be printed down to // loops nested VERBOSITY_LEVEL-1 deep. For example, // // VERBOSITY_LEVEL 0 ==> Nothing is printed, even outside of loops. // VERBOSITY_LEVEL 1 ==> Only stuff outside of loops is printed. // VERBOSITY_LEVEL 2 ==> Stuff inside the first level of loops is printed. // VERBOSITY_LEVEL 3 ==> Stuff inside the second level of loops is printed. // // Flag: VERBOSITY_LEVEL #define VERBOSITY_LEVEL 1 // If SAY_HI is on, some routines will display "hi" and "bye" messages // to stdout. // Flag: SAY_HI #define SAY_HI 0 // NUM_FLUID_COMPONENTS specifies the number of fluid components. // Flag: NUM_FLUID_COMPONENTS #define NUM_FLUID_COMPONENTS 1 // If NUM_FLUID_COMPONENTS is 2, the second component can be the sigma // component for solute (or thermal) transport as in Inamuro & Yoshino // by turning on INAMURO_SIGMA_COMPONENT . // Flag: INAMURO_SIGMA_COMPONENT #define INAMURO_SIGMA_COMPONENT ( 1 && NUM_FLUID_COMPONENTS==2) // Toggle Zhang & Chen energy transport method, PRE 67, 0066711 (2003). // Supposed to give thermodynamic consistency unlike old Shan & Chen method. // And supports general equation of state P = P(rho,T). // Utilizes the Inamuro component for evolution of the energy transport // equation. Employs modified compute_phase_force routine to compute // body force term representing non-local interaction potential U among // particles. // Flag: ZHANG_AND_CHEN_ENERGY_TRANSPORT #define ZHANG_AND_CHEN_ENERGY_TRANSPORT ( 0 && (INAMURO_SIGMA_COMPONENT)) // Simulate POROUS_MEDIA via a solid density parameter // as proposed by Dardis and McCloskey, // Phys Rev E, 57, 4, 4834-4837, 1998 // Flag: POROUS_MEDIA #define POROUS_MEDIA 0 // Simulate porous media as a body force. #define FREED_POROUS_MEDIA 0 // Toggle Tau & Zhang anisotropic dispersion. #define TAU_ZHANG_ANISOTROPIC_DISPERSION ( 1 \ && INAMURO_SIGMA_COMPONENT \ && POROUS_MEDIA ) // Guo, Zheng & Shi: PRE 65 2002, Body force #define GUO_ZHENG_SHI_BODY_FORCE 0 // Body force macros #if GUO_ZHENG_SHI_BODY_FORCE #if INAMURO_SIGMA_COMPONENT #define F(dir_,rho_,conc_) \ ( lattice->param.gval[0][(dir_)] \ /*+ lattice->param.gval[subs][(dir_)] */\ /* *(rho_) */\ *( 1. + get_buoyancy(lattice) \ *( get_beta(lattice)) \ *( (conc_) - get_C0(lattice))) \ ) #else #define F(dir_) lattice->param.gval[subs][(dir_)] #endif #else #if INAMURO_SIGMA_COMPONENT #define F(dir_,rho_,conc_) \ ( lattice->param.gval[0][(dir_)] \ /*+ lattice->param.gval[1][(dir_)] */\ /* *(rho_) */\ *( 1. + ( get_buoyancy(lattice)) \ *( get_beta(lattice)) \ *( (conc_) - get_C0(lattice))) ) #else #define F(dir_,rho_) \ lattice->param.gval[subs][(dir_)] \ *((lattice->param.incompressible)?(rho_):(1.)) #endif #endif // When there are two (or more) fluid components, a single velocity is // sometimes (always?) used to compute the equilibrium distribution // function. This single velocity will be called upr, and the // STORE_U_COMPOSITE flag will toggle its use. // Flag: STORE_U_COMPOSITE #define STORE_U_COMPOSITE ( 1 && ( (NUM_FLUID_COMPONENTS)==2 \ &&!((INAMURO_SIGMA_COMPONENT)))) // If DO_NOT_STORE_SOLIDS is on, then only the nodes necessary to flow are // stored. In this case, extra storage is needed for geometry information // (e.g. node neighbors). If the ratio of fluid nodes to solid nodes is // small (<~.7), this results in lower storage requirements. // Flag: DO_NOT_STORE_SOLIDS #define DO_NOT_STORE_SOLIDS 0 // If COMPUTE_ON_SOLIDS is on, macroscopic variables and feq will be computed // on solid nodes, even though they are not conceptually meaningful there. // This can be helpful for debugging purposes. #define COMPUTE_ON_SOLIDS 1 // NON_LOCAL_FORCES toggles any mechanisms for computing and storing // non-local (interaction) forces. // Flag: NON_LOCAL_FORCES #define NON_LOCAL_FORCES ( 0 && !(INAMURO_SIGMA_COMPONENT&&!ZHANG_AND_CHEN_ENERGY_TRANSPORT)) // The phase force weighting factors: // WM = weights in the direction of major axes // WD = weights in the direction of diagonals // According to Raskinmaki, it should be WM=2 and WD=1. // According to Chen (via correspondence) it should be WM=4 and WD=1. // According to Sukop and Thorne, it should be WM=1/9 and WD=1/36. // The corresonding G values (a.k.a. G, as in params.in) for the usual // equation of state that we like are -5, -10/3, and -120, respectively. // Flag: WM #define WM (1./ 9.) // Flag: WD #define WD (1./36.) #define Q 9 // Toggle manage_body_force call at beginning of time loop for // gradually increasing/decreasing gravity. // Flag: MANAGE_BODY_FORCE #define MANAGE_BODY_FORCE 0 // Toggle break through curve (BTC) mechanism for sigma component. // Flag: STORE_BTC #define STORE_BTC ( 1 && INAMURO_SIGMA_COMPONENT) // // Toggle DETERMINE_FLOW_DIRECTION to attempt to determine the direction of // flow. // // Assigns FlowDir = { 0, 1, 2} = { indeterminate, vertical, horizontal} // // NOTE: This determination informs the breakthrough curve mechanism which // should be used in a simple situation with either pressure/velocity // boundaries driving the flow in one direction or gravity driving the flow // in one direction. If the direction of flow cannot be determined, FlowDir // will be set to indeterminate (=0) and a BTC will not be stored. // // NOTE: This determination also informs the sigma slip boundary which // should only be used in the simple situation of flow through a channel // where the geometry is trivial and the direction of flow is obvious. // // Flag: DETERMINE_FLOW_DIRECTION #define DETERMINE_FLOW_DIRECTION 1 // Toggle mechanism to initialize domain with ux_in or uy_in. This is // useful for setting a velocity in a periodic domain without using // fluid boundary conditions. // Flag: INITIALIZE_WITH_UX_IN #define INITIALIZE_WITH_UX_IN 0 // Flag: INITIALIZE_WITH_UY_IN #define INITIALIZE_WITH_UY_IN 0 // Dumping the density and velocity data to files can be time consuming and // take up a lot of disk space. If all that is needed is the BMP files, then // turn WRITE_MACRO_VAR_DAT_FILES off to save time and space. // Flag: WRITE_MACRO_VAR_DAT_FILES #define WRITE_MACRO_VAR_DAT_FILES 1 // Usually the density and velocity are written only for the active nodes // and in a way designed for post-processing. Additional files with the // variables written in a readable grid of all lattice nodes will be // generated when WRITE_RHO_AND_U_TO_TXT is on. This is done in an // inefficient way and is intended only for debugging purposes on tiny // lattices. Note that if WRITE_MACRO_VAR_DAT_FILES is off, this flag // has no effect. // Flag: WRITE_RHO_AND_U_TO_TXT #define WRITE_RHO_AND_U_TO_TXT 0 // WRITE_PDF_DAT_FILES is analogous to WRITE_MACRO_VAR_DAT_FILES. // Flag: WRITE_PDF_DAT_FILES #define WRITE_PDF_DAT_FILES 0 // WRITE_PDF_TO_TXT is analogous to WRITE_RHO_AND_U_TO_TXT. // Flag: WRITE_PDF_TO_TXT #define WRITE_PDF_TO_TXT 0 // Value used to represent an INACTIVE_NODE . This is used in the list // of neighbors ( struct node_struct::nn). It is also used in the // map from (i,j) space onto n index space in rho2bmp() and u2bmp(). // Flag: INACTIVE_NODE #define INACTIVE_NODE -1 // Negative densities (f_a) generally signify impending doom. The code // will die "gracefully" when this happens if PUKE_NEGATIVE_DENSITIES is on. // Might want to turn this off to boost performance on big, long runs that // are expected to survive without such instabilities. // Flag: PUKE_NEGATIVE_DENSITIES #define PUKE_NEGATIVE_DENSITIES 0 // Turn one of these on for coloring of the solids in bmp files. // Flag: SOLID_COLOR_IS_CHECKERBOARD #define SOLID_COLOR_IS_CHECKERBOARD 0 // Flag: SOLID_COLOR_IS_BLACK #define SOLID_COLOR_IS_BLACK 1 // Flag: DELAY #define DELAY 0 // Flag: END_GRAV #define END_GRAV 2000 // A single white pixel will be placed in at the (0,0) lattice node if // MARK_ORIGIN_FOR_REFERENCE is turned on. This is good for assisting with the // problem of tracking orientation of the results between regimes (e.g. C, BMP, // Matlab...). // Flag: MARK_ORIGIN_FOR_REFERENCE #define MARK_ORIGIN_FOR_REFERENCE 0 // Flag: PERTURBATIONS #define PERTURBATIONS 0 // If WRITE_CHEN_DAT_FILES is on, the code will output old style chen_*.dat // files to be processed by the old lb_rho_v*.m matlab scripts. // Flag: WRITE_CHEN_DAT_FILES #define WRITE_CHEN_DAT_FILES 0 // NEW_PARAMS_INPUT_ROUTINE is a temporary flag to switch between the old // params input routine and the new one under development. When the new // one is ready, it should be used exclusively. #define NEW_PARAMS_INPUT_ROUTINE 1 #endif /* FLAGS_H */
111pjb-one
src/flags_poiseuille_gravity_x.h
C
gpl3
9,094
//############################################################################## // // user_stuff.c // // - This file has function definitions of functions that will be called // at specified times (see individual function documentation) if the // lattice->param.do_user_stuff flag is on. // // - The user can fill these routines with whatever they want. // double theta_of_height_width( const double height, const double width) { double theta; if( height > width/2.) { // TODO: Need to double check this formula: theta = PI/2. + atan( ((double)height/(double)width) - ((double)width/(4.*(double)height))); } else if( height < width/2.) { // TODO: Need to double check this formula: theta = atan( 1./( ((double)width/(4.*(double)height)) - ((double)height/(double)width) )); } else if( height == width/2.) { theta = PI/2.; } else { printf("%s %d >> Unhandled case: height=%f, width=%f\n", __FILE__, __LINE__, height, width); theta = 999.; // Bogus value instead of process_exiting. } return theta; } // double theta_of_height_width( const double height, const double width) void ascii_display_of_the_drop( lattice_ptr lattice, int j, int rho_cut, int rho_min) { double rho; const double rho_v=85.7042; const double rho_l=524.3905; int i, max_i = 80; max_i = (max_i > get_LX(lattice))?( get_LX(lattice)):(max_i); for( i=0; i<max_i; i++) { if( is_solid_node( lattice, /*subs=*/0, IJ2N(i,j))) { printf("%2d",i%100); if( j!=0) { printf("%s %d >> WARNING: " "Function compute_drop() is designed to compute the " "width and height of a drop forming on a " "surface at the bottom of the domain. " "Solid detected at (%d,%d) does not conform to that " "configuration.\n", __FILE__, __LINE__, i, j ); } } else { rho = get_rho(lattice,i,j,/*subs=*/0); if( rho > rho_l) { printf("++"); } else if( rho > rho_cut) { printf("Xx"); } else if( rho > rho_min) { printf("o "); } else if( rho < rho_v) { printf("--"); } else { printf(". "); } } } printf("%3d\n",j); } // void ascii_display_of_the_drop( lattice_ptr lattice, int j, ... // void compute_drop( lattice_ptr lattice) // // Compute the width and height of the drop. (SCMP) // void compute_drop( lattice_ptr lattice, int output_to_file, int jbase, double rho_cut, int header) { int i, j; double rho; const double rho_v=85.7042; const double rho_l=524.3905; const double psi_v = 4.*exp(-200./(rho_v)); const double psi_l = 4.*exp(-200./(rho_l)); const double psi_cut=(psi_v+psi_l)/2.; //const double rho_cut=(rho_v+rho_l)/2.; //const double rho_cut= -200./log(.25*psi_cut); //const double rho_cut=450.; //const double rho_cut=100.; double i1, i2, icut_left, icut_right; double j1, j2, jcut; double rho1, rho2; // INPUTE PARAM NOW: const int jbase = 4; // jbase frame_rate theta_low theta theta_high // ----- ---------- ---------- ---------- ---------- // 1 100 91.909683 93.327450 94.732496 // 1 1000 90.947016 92.357518 93.755755 // 2 100 90.962932 92.396963 93.818305 // 2 1000 90.000000 91.426377 92.840531 // 3 100 89.037068 90.479460 91.909683 // 3 1000 89.037068 90.479460 91.909683 // 4 100 88.057956 89.516494 90.962932 // 4 1000 88.057956 89.516494 90.962932 const double rho_min=100.; //const double rho_min=rho_v; //psi(rho_l)=4.*exp(-200/524.3905) //psi(rho_v)=4.*exp(-200/85.7042) int width=0, width_temp=0, max_width=0, max_width_j=0; int height=0; double theta; double max_rho=0.; int imax; int imax1; int imax2; double G = get_G( lattice); double Gads = get_Gads( lattice, /*subs*/0); jcut = -1.; // Flag value. // Start at about 3/4 the height of the domain to skip over any condensing // blobs on the ceiling. Main drop being measured should not be that high. for( j=(int)floor((3./4.)*get_LY(lattice)); j>0; j--) { max_rho=0.; for( i=0; i<get_LX( lattice); i++) { rho = get_rho(lattice,i,/*j=*/j,/*subs=*/0); if( max_rho < fabs(rho)) { max_rho = fabs(rho); imax = i; } } if( /*row j crosses the drop*/ max_rho > rho_min) { if( max_rho > rho_cut && jcut < 0.) { // rho1 was assigned max_rho from row j-1. // j1 was assigned max_rho from row j-1. rho2 = max_rho; imax2 = imax; j2 = j; // Linear interpolation of jcut: jcut = j1 + ((j2-j1)/(rho2-rho1))*( rho_cut - rho1); } if( j>=jbase) { if( max_rho >= rho_cut){ height++;} width_temp=0; icut_left = -1; icut_right = -1; for( i=0; i<get_LX(lattice); i++) { rho = get_rho(lattice,i,j,/*subs=*/0); if( rho > rho_cut) { if( icut_left < 0. ) { // i1 and rho1 were set at i-1. rho2 = rho; i2 = i; // Linear interpolation of icut_left: icut_left = i1 + ((i2-i1)/(rho2-rho1))*( rho_cut - rho1); } else { rho1 = rho; i1 = i; /*save for interp of icut_right*/} width_temp++; } else { if( icut_left < 0.) { i1 = i; rho1 = rho; /*save for interp of icut_left*/ } else { if( icut_right < 0.) { // i1 and rho1 were set at i-1. rho2 = rho; i2 = i; // Linear interpolation of icut_right: icut_right = i1 + ((i2-i1)/(rho2-rho1))*( rho_cut - rho1); } } } } if( width_temp > 0) { width = width_temp; if( max_width < width) { max_width = width; max_width_j = j;} } } } else { rho1 = max_rho; // save rho1 to use for interpolation of jcut. imax1 = imax; j1 = j; } } //for( i=0; i<get_LX( lattice); i++) //{ // printf("%f ",get_rho(lattice,i,/*j=*/max_width_j,/*subs=*/0)); //} if(/*verbose*/0) { printf("\n"); printf("jbase = %d\n", jbase); printf("width=%d, height=%d, ", width, height); printf("width/height=%f, ", (double)width/(double)height); printf("max_width=%d at j=%d, ", max_width, max_width_j); theta = theta_of_height_width( jcut-jbase, icut_right-icut_left); printf("%f = %f^o ", theta, theta*(180./PI)); theta = theta_of_height_width( height-1, width+1); printf("theta_low = %f = %f^o, ", theta, theta*(180./PI)); theta = theta_of_height_width( height, width); printf("theta = %f = %f^o, ", theta, theta*(180./PI)); theta = theta_of_height_width( height+1, width-1); printf("theta_high = %f = %f^o, ", theta, theta*(180./PI)); theta = acos( ( ( psi_v - Gads/G) - ( Gads/G - psi_l) )/(psi_v-psi_l)); printf("theta_predicted_youngs = %f = %f^o ", theta, theta*(180./PI)); //theta = PI*( ( Gads/G - psi_l) / ( psi_v - psi_l)); //printf("theta_predicted_combination = %f = %f^o ", theta, theta*(180./PI)); printf("\n"); printf("rho_cut = %f\n", rho_cut); printf("(icut_left,icut_right,jcut) = ( %9.6f, %9.6f, %9.6f); " "(imax1,imax2)=(%d,%d); (icut_left+icut_right)/2 = %9.6f\n", icut_left, icut_right, jcut, imax1, imax2,(icut_left+icut_right)/2.); printf("psi(rho_cut) = %f\n", 4.*exp(-200./rho_cut)); printf("psi(rho_v) = %f\n", 4.*exp(-200./85.7042)); printf("psi(rho_l) = %f\n", 4.*exp(-200./524.3905)); printf("psi((rho_l+rho_v)/2.) = %f\n", 4.*exp(-200./((85.7042+524.3905)/2.))); printf("(psi(rho_v)+psi(rho_l))/2. = %f\n", (4.*exp(-200./85.7042)+4.*exp(-200./524.3905))/2.); rho = 212.36; printf("psi(%f) = %f\n", rho, 4.*exp(-200./rho)); } else { if( header) { printf("\n"); printf( " DROP " " jbase" " rho_cut" " width" " height" " theta pixelated" " theta interpolated" " theta predicted" "\n"); printf( " DROP " " ---------------------" " ---------------------" " ---------------------" " ---------------------" " ---------------------" " ---------------------" " ---------------------" "\n"); } printf(" DROP "); printf(" %21.17f", (double)jbase); printf(" %21.17f", rho_cut); printf(" %21.17f", icut_right-icut_left); printf(" %21.17f", jcut - jbase); theta = theta_of_height_width( height, width); printf(" %21.17f", theta*(180/PI)); theta = theta_of_height_width( jcut-jbase, icut_right-icut_left); printf(" %21.17f", theta*(180/PI)); theta = acos( ( ( psi_v - Gads/G) - ( Gads/G - psi_l) )/(psi_v-psi_l)); printf(" %21.17f", theta*(180/PI)); printf("\n"); } if( output_to_file) { FILE *o; o = fopen( "compute_drop.dat", "a+"); fprintf( o, "%d ", get_NumFrames( lattice)); fprintf( o, "%d ", get_FrameRate( lattice)); fprintf( o, "%8.4f ", get_G( lattice)); fprintf( o, "%8.4f ", get_Gads( lattice, /*subs*/0)); fprintf( o, "%d ", jbase); fprintf( o, "%d ", width); fprintf( o, "%d ", height); theta = theta_of_height_width( jcut-jbase, icut_right-icut_left); fprintf( o, "%20.17f ", theta*(180./PI)); theta = theta_of_height_width( height-1, width+1); fprintf( o, "%20.17f ", theta*(180./PI)); theta = theta_of_height_width( height, width); fprintf( o, "%20.17f ", theta*(180./PI)); theta = theta_of_height_width( height+1, width-1); fprintf( o, "%20.17f ", theta*(180./PI)); theta = acos( ( ( psi_v - Gads/G) - ( Gads/G - psi_l) )/(psi_v-psi_l)); //fprintf( o, "acos(%20.17f) = ", ( ( psi_v - Gads/G) - ( Gads/G - psi_l) )/(psi_v-psi_l)); fprintf( o, "%20.17f ", theta*(180./PI)); //theta = PI*( ( Gads/G - psi_l) / ( psi_v - psi_l)); //fprintf( o, "%20.17f ", theta*(180./PI)); fprintf( o, "\n"); fclose(o); } //4.*exp(-200/524.3905) //4.*exp(-200/85.7042) } /* void compute_drop( lattice_ptr lattice, bool output_to_file) */ void compute_sequence_of_drops( lattice_ptr lattice, int fileio) { double rho_v=85.7042; double rho_l=524.3905; const double psi_v = 4.*exp(-200./(rho_v)); const double psi_l = 4.*exp(-200./(rho_l)); const double psi_mid = (psi_v+psi_l)/2.; double psi_range = psi_l - psi_v; int num_psi_intervals = 4; int half_psi_intervals = num_psi_intervals/2; double dpsi = psi_range / num_psi_intervals; double rho_cut; double psi_cut; int jbase; int min_jbase = 2; int max_jbase = 6; for( psi_cut = psi_mid - half_psi_intervals*dpsi; psi_cut <= psi_mid + half_psi_intervals*dpsi; psi_cut += dpsi) { for( jbase = min_jbase; jbase <= max_jbase; jbase++) { rho_cut = -200./log(.25*psi_cut); compute_drop( lattice, fileio, jbase, rho_cut, /*display header?*/( psi_cut == psi_mid-half_psi_intervals*dpsi && jbase == min_jbase )); } } } // void user_stuff_pre_frames( lattice_ptr lattice) // // This function is called before the frame loop in lb2d_prime.c. // void user_stuff_pre_frames( lattice_ptr lattice) { #if 0 compute_drop( lattice, /*ascii*/1, /*file-io*/0, /*jbase*/1); compute_drop( lattice, /*ascii*/0, /*file-io*/0, /*jbase*/2); compute_drop( lattice, /*ascii*/0, /*file-io*/0, /*jbase*/3); compute_drop( lattice, /*ascii*/0, /*file-io*/0, /*jbase*/4); compute_drop( lattice, /*ascii*/0, /*file-io*/0, /*jbase*/5); compute_drop( lattice, /*ascii*/0, /*file-io*/0, /*jbase*/6); #else //ascii_display_of_the_drop( lattice, j, rho_cut, rho_min); compute_sequence_of_drops( lattice, /*file-io*/0); #endif } /* void user_stuff_pre_frames( lattice_ptr lattice) */ // void user_stuff_frame( lattice_ptr lattice) // // If lattice->param.do_user_stuff is on, this function is called at the // end of each frame in lb2d_prime.c. // void user_stuff_frame( lattice_ptr lattice) { } /* void user_stuff_frame( lattice_ptr lattice) */ // void user_stuff_post_frames( lattice_ptr lattice) // // If lattice->param.do_user_stuff is on, this function is called after // the frame loop in lb2d_prime.c. // void user_stuff_post_frames( lattice_ptr lattice) { #if 0 compute_drop( lattice, /*ascii*/1, /*file-io*/1, /*jbase*/1); compute_drop( lattice, /*ascii*/0, /*file-io*/1, /*jbase*/2); compute_drop( lattice, /*ascii*/0, /*file-io*/1, /*jbase*/3); compute_drop( lattice, /*ascii*/0, /*file-io*/1, /*jbase*/4); compute_drop( lattice, /*ascii*/0, /*file-io*/1, /*jbase*/5); compute_drop( lattice, /*ascii*/0, /*file-io*/1, /*jbase*/6); #else //ascii_display_of_the_drop( lattice, j, rho_cut, rho_min); compute_sequence_of_drops( lattice, /*file-io*/1); #endif } /* void user_stuff_post_frames( lattice_ptr lattice) */ // void user_stuff_pre_times( lattice_ptr lattice) // // If lattice->param.do_user_stuff is on, this function is called before // the time loop in lb2d_prime.c. // void user_stuff_pre_times( lattice_ptr lattice) { } /* void user_stuff_pre_times( lattice_ptr lattice) */ // void user_stuff_time( lattice_ptr lattice) // // If lattice->param.do_user_stuff is on, this function is called at the // end of each time loop in lb2d_prime.c. // void user_stuff_time( lattice_ptr lattice) { } /* void user_stuff_time( lattice_ptr lattice) */ // void user_stuff_post_times( lattice_ptr lattice) // // If lattice->param.do_user_stuff is on, this function is called after // the time loop in lb2d_prime.c. // void user_stuff_post_times( lattice_ptr lattice) { #if 0 compute_drop( lattice, /*ascii*/1, /*file-io*/0, /*jbase*/1); compute_drop( lattice, /*ascii*/0, /*file-io*/0, /*jbase*/2); compute_drop( lattice, /*ascii*/0, /*file-io*/0, /*jbase*/3); compute_drop( lattice, /*ascii*/0, /*file-io*/0, /*jbase*/4); compute_drop( lattice, /*ascii*/0, /*file-io*/0, /*jbase*/5); compute_drop( lattice, /*ascii*/0, /*file-io*/0, /*jbase*/6); #else //ascii_display_of_the_drop( lattice, j, rho_cut, rho_min); compute_sequence_of_drops( lattice, /*file-io*/0); #endif } /* void user_stuff_post_times( lattice_ptr lattice) */
111pjb-one
src/user_stuff.c
C
gpl3
14,764
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // flags.h // // - Preprocessor flags for lb2d_prime. // #ifndef FLAGS_H #define FLAGS_H // Set VERBOSITY_LEVEL to correspond to how deep into nested loops to // print debug and related output. Stuff will be printed down to // loops nested VERBOSITY_LEVEL-1 deep. For example, // // VERBOSITY_LEVEL 0 ==> Nothing is printed, even outside of loops. // VERBOSITY_LEVEL 1 ==> Only stuff outside of loops is printed. // VERBOSITY_LEVEL 2 ==> Stuff inside the first level of loops is printed. // VERBOSITY_LEVEL 3 ==> Stuff inside the second level of loops is printed. // // Flag: VERBOSITY_LEVEL #define VERBOSITY_LEVEL 1 // If SAY_HI is on, some routines will display "hi" and "bye" messages // to stdout. // Flag: SAY_HI #define SAY_HI 0 // NUM_FLUID_COMPONENTS specifies the number of fluid components. // Flag: NUM_FLUID_COMPONENTS #define NUM_FLUID_COMPONENTS 1 // If NUM_FLUID_COMPONENTS is 2, the second component can be the sigma // component for solute (or thermal) transport as in Inamuro & Yoshino // by turning on INAMURO_SIGMA_COMPONENT . // Flag: INAMURO_SIGMA_COMPONENT #define INAMURO_SIGMA_COMPONENT ( 0 && NUM_FLUID_COMPONENTS==2) // Toggle Zhang & Chen energy transport method, PRE 67, 0066711 (2003). // Supposed to give thermodynamic consistency unlike old Shan & Chen method. // And supports general equation of state P = P(rho,T). // Utilizes the Inamuro component for evolution of the energy transport // equation. Employs modified compute_phase_force routine to compute // body force term representing non-local interaction potential U among // particles. // Flag: ZHANG_AND_CHEN_ENERGY_TRANSPORT #define ZHANG_AND_CHEN_ENERGY_TRANSPORT ( 0 && (INAMURO_SIGMA_COMPONENT)) // Simulate POROUS_MEDIA via a solid density parameter // as proposed by Dardis and McCloskey, // Phys Rev E, 57, 4, 4834-4837, 1998 // Flag: POROUS_MEDIA #define POROUS_MEDIA 0 // When there are two (or more) fluid components, a single velocity is // sometimes (always?) used to compute the equilibrium distribution // function. This single velocity will be called upr, and the // STORE_U_COMPOSITE flag will toggle its use. // Flag: STORE_U_COMPOSITE #define STORE_U_COMPOSITE ( 1 && ( (NUM_FLUID_COMPONENTS)==2 \ &&!((INAMURO_SIGMA_COMPONENT)))) // If DO_NOT_STORE_SOLIDS is on, then only the nodes necessary to flow are // stored. In this case, extra storage is needed for geometry information // (e.g. node neighbors). If the ratio of fluid nodes to solid nodes is // small (<~.7), this results in lower storage requirements. // Flag: DO_NOT_STORE_SOLIDS #define DO_NOT_STORE_SOLIDS 0 // If COMPUTE_ON_SOLIDS is on, macroscopic variables and feq will be computed // on solid nodes, even though they are not conceptually meaningful there. // This can be helpful for debugging purposes. #define COMPUTE_ON_SOLIDS 1 // NON_LOCAL_FORCES toggles any mechanisms for computing and storing // non-local (interaction) forces. // Flag: NON_LOCAL_FORCES #define NON_LOCAL_FORCES ( 1 && !(INAMURO_SIGMA_COMPONENT&&!ZHANG_AND_CHEN_ENERGY_TRANSPORT)) // The phase force weighting factors: // WM = weights in the direction of major axes // WD = weights in the direction of diagonals // According to Raskinmaki, it should be WM=2 and WD=1. // According to Chen (via correspondence) it should be WM=4 and WD=1. // According to Sukop and Thorne, it should be WM=1/9 and WD=1/36. // The corresonding G values (a.k.a. G, as in params.in) for the usual // equation of state that we like are -5, -10/3, and -120, respectively. // Flag: WM #define WM (1./ 9.) // Flag: WD #define WD (1./36.) // Toggle manage_body_force call at beginning of time loop for // gradually increasing/decreasing gravity. // Flag: MANAGE_BODY_FORCE #define MANAGE_BODY_FORCE 0 // Toggle break through curve (BTC) mechanism for sigma component. // Flag: STORE_BTC #define STORE_BTC ( 1 && INAMURO_SIGMA_COMPONENT) // // Toggle DETERMINE_FLOW_DIRECTION to attempt to determine the direction of // flow. // // Assigns FlowDir = { 0, 1, 2} = { indeterminate, vertical, horizontal} // // NOTE: This determination informs the breakthrough curve mechanism which // should be used in a simple situation with either pressure/velocity // boundaries driving the flow in one direction or gravity driving the flow // in one direction. If the direction of flow cannot be determined, FlowDir // will be set to indeterminate (=0) and a BTC will not be stored. // // NOTE: This determination also informs the sigma slip boundary which // should only be used in the simple situation of flow through a channel // where the geometry is trivial and the direction of flow is obvious. // // Flag: DETERMINE_FLOW_DIRECTION #define DETERMINE_FLOW_DIRECTION 0 // Toggle mechanism to initialize domain with ux_in or uy_in. This is // useful for setting a velocity in a periodic domain without using // fluid boundary conditions. // Flag: INITIALIZE_WITH_UX_IN #define INITIALIZE_WITH_UX_IN 0 // Flag: INITIALIZE_WITH_UY_IN #define INITIALIZE_WITH_UY_IN 0 // Dumping the density and velocity data to files can be time consuming and // take up a lot of disk space. If all that is needed is the BMP files, then // turn WRITE_MACRO_VAR_DAT_FILES off to save time and space. // Flag: WRITE_MACRO_VAR_DAT_FILES #define WRITE_MACRO_VAR_DAT_FILES 1 // Usually the density and velocity are written only for the active nodes // and in a way designed for post-processing. Additional files with the // variables written in a readable grid of all lattice nodes will be // generated when WRITE_RHO_AND_U_TO_TXT is on. This is done in an // inefficient way and is intended only for debugging purposes on tiny // lattices. Note that if WRITE_MACRO_VAR_DAT_FILES is off, this flag // has no effect. // Flag: WRITE_RHO_AND_U_TO_TXT #define WRITE_RHO_AND_U_TO_TXT 0 // WRITE_PDF_DAT_FILES is analogous to WRITE_MACRO_VAR_DAT_FILES. // Flag: WRITE_PDF_DAT_FILES #define WRITE_PDF_DAT_FILES 0 // WRITE_PDF_TO_TXT is analogous to WRITE_RHO_AND_U_TO_TXT. // Flag: WRITE_PDF_TO_TXT #define WRITE_PDF_TO_TXT 0 // Value used to represent an INACTIVE_NODE . This is used in the list // of neighbors ( struct node_struct::nn). It is also used in the // map from (i,j) space onto n index space in rho2bmp() and u2bmp(). // Flag: INACTIVE_NODE #define INACTIVE_NODE -1 // Negative densities (f_a) generally signify impending doom. The code // will die "gracefully" when this happens if PUKE_NEGATIVE_DENSITIES is on. // Might want to turn this off to boost performance on big, long runs that // are expected to survive without such instabilities. // Flag: PUKE_NEGATIVE_DENSITIES #define PUKE_NEGATIVE_DENSITIES 0 // Turn one of these on for coloring of the solids in bmp files. // Flag: SOLID_COLOR_IS_CHECKERBOARD #define SOLID_COLOR_IS_CHECKERBOARD 0 // Flag: SOLID_COLOR_IS_BLACK #define SOLID_COLOR_IS_BLACK 1 // Flag: DELAY #define DELAY 0 // Flag: END_GRAV #define END_GRAV 2000 // A single white pixel will be placed in at the (0,0) lattice node if // MARK_ORIGIN_FOR_REFERENCE is turned on. This is good for assisting with the // problem of tracking orientation of the results between regimes (e.g. C, BMP, // Matlab...). // Flag: MARK_ORIGIN_FOR_REFERENCE #define MARK_ORIGIN_FOR_REFERENCE 0 // Flag: PERTURBATIONS #define PERTURBATIONS 0 // If WRITE_CHEN_DAT_FILES is on, the code will output old style chen_*.dat // files to be processed by the old lb_rho_v*.m matlab scripts. // Flag: WRITE_CHEN_DAT_FILES #define WRITE_CHEN_DAT_FILES 0 // NEW_PARAMS_INPUT_ROUTINE is a temporary flag to switch between the old // params input routine and the new one under development. When the new // one is ready, it should be used exclusively. #define NEW_PARAMS_INPUT_ROUTINE 1 #endif /* FLAGS_H */
111pjb-one
src/flags_scmp_drops.h
C
gpl3
7,934
#include <stdio.h> #include <stdlib.h> #include <memory.h> #define TWO_SUBS 0 int ni=100; int nj=100; int nf=23; #define ij2n(i_,j_) ((j_)*ni+(i_)) void alloc_rho( double **rho_a, double ***rho_a2d); void read_rho_file( char *filename, double **rho, double *max, double *min); void display_density_plot( FILE *o, double *rho_a, int max_width); void write_rho_profile( FILE *o, double *rho_a, int i); int main( int argc, char **argv) { FILE *o; char filename[1024]; double **rho_a2d; double *rho_a; double **rho_b2d; double *rho_b; double rho_a_max; double rho_a_min; double rho_b_max; double rho_b_min; int i, j; int iprof; int max_width; switch( argc) { case 2: nf = atoi( argv[1]); iprof = ni/2; max_width = 85; break; case 3: nf = atoi( argv[1]); iprof = atoi( argv[2]); max_width = 85; break; case 4: ni = atoi( argv[1]); nj = atoi( argv[2]); nf = atoi( argv[3]); iprof = ni/2; max_width = 85; break; case 5: ni = atoi( argv[1]); nj = atoi( argv[2]); max_width = atoi( argv[3]); nf = atoi( argv[4]); iprof = ni/2; break; case 6: ni = atoi( argv[1]); nj = atoi( argv[2]); max_width = atoi( argv[3]); nf = atoi( argv[4]); iprof = atoi( argv[5]); break; default: printf("ERROR: Unhandled case: argc = %d. Exiting\n", argc); process_exit(1); break; } alloc_rho( &rho_a, &rho_a2d); #if TWO_SUBS alloc_rho( &rho_b, &rho_b2d); #endif sprintf(filename,"./out/rho%dx%d_frame%04d_subs00.dat",ni,nj,nf); read_rho_file( filename, &rho_a, &rho_a_max, &rho_a_min); #if TWO_SUBS sprintf(filename,"./out/rho%dx%d_frame%04d_subs01.dat",ni,nj,nf); read_rho_file( filename, &rho_b, &rho_b_max, &rho_b_min); #endif #if TWO_SUBS display_density_plot( stdout, rho_b, max_width); printf("\n"); #endif display_density_plot( stdout, rho_a, max_width); printf("\n"); sprintf(filename,"./out/rho%dx%d_frame%04d_subs00_profile%04d.dat", ni,nj,nf,iprof); o = fopen(filename,"w+"); write_rho_profile( o, rho_a, iprof); fclose(o); #if TWO_SUBS sprintf(filename,"./out/rho%dx%d_frame%04d_subs01_profile%04d.dat", ni,nj,nf,iprof); o = fopen(filename,"w+"); write_rho_profile( o, rho_b, iprof); fclose(o); #endif printf("rho_a_max = %f, ", rho_a_max); printf("rho_a_min = %f, ", rho_a_min); #if TWO_SUBS printf("rho_b_max = %f, ", rho_b_max); printf("rho_b_min = %f, ", rho_b_min); #endif printf("Wrote profile at i = %d.\n", iprof); free( rho_a); #if TWO_SUBS free( rho_b); #endif return 0; } void alloc_rho( double **rho, double ***rho2d) { int j; *rho = (double*)malloc( ni*nj*sizeof(double)); *rho2d = (double**)malloc( nj*sizeof(double*)); for( j=0; j<nj; j++) { (*rho2d)[j] = &((*rho)[j*ni]); } } void read_rho_file( char *filename, double **rho, double *max, double *min) { FILE *in; int i, j; if( !( in = fopen(filename,"r"))) { printf("ERROR: Error opening file \"%s\". Exiting.\n",filename); process_exit(1); } j = 0; i = 0; fscanf( in, "%lf ", ((*rho + ij2n(i,j)))); *max = *(*rho + ij2n(i,j)); *min = *(*rho + ij2n(i,j)); for( i=1; i<ni; i++) { fscanf( in, "%lf ", ((*rho + ij2n(i,j)))); if( *max < *(*rho + ij2n(i,j))) { *max = *(*rho + ij2n(i,j));} if( *min > *(*rho + ij2n(i,j))) { *min = *(*rho + ij2n(i,j));} } for( j=1; j<nj; j++) { for( i=0; i<ni; i++) { fscanf( in, "%lf ", ((*rho + ij2n(i,j)))); if( *max < *(*rho + ij2n(i,j))) { *max = *(*rho + ij2n(i,j));} if( *min > *(*rho + ij2n(i,j))) { *min = *(*rho + ij2n(i,j));} } } fclose( in); } void display_density_plot( FILE *o, double *rho_a, int max_width) { int i, j; for( j=nj-1; j>=0; j--) { for( i=0; i<((ni<=max_width)?(ni):(max_width)); i++) { fprintf( o, " %c", (char)(((rho_a[ij2n(i,j)]-85.)/(524.-85.)>1./5.) ?(((rho_a[ij2n(i,j)]-85.)/(524.-85.)>2./5.) ?(((rho_a[ij2n(i,j)]-85.)/(524.-85.)>3./5.) ?(((rho_a[ij2n(i,j)]-85.)/(524.-85.)>4./5.) ?('#') :('X')) :('O')) :('+')) :('.'))); //printf("%.1f ", rho_a2d[ij2n(i,j)]); } printf("\n"); } for( i=0; i<((ni<=max_width)?(ni):(max_width)); i++) { fprintf( o, "%2d", i%100); } } void write_rho_profile( FILE *o, double *rho_a, int i) { int j; for( j=0; j<nj; j++) { fprintf( o, "%f\n", rho_a[ ij2n(i,j)]); } }
111pjb-one
src/ascii_view_density.c
C
gpl3
4,595
//############################################################################## // // user_stuff.h // // - This file includes a definition of the struct user_struct, which the // user should fill in with whatever they want. It will be accessed // from the lattice structure as lattice->user_stuff->whatever // // - This file also has forward declarations for the user_stuff functions. // These functions are defined in user_stuff.c. The user should put in // them whatever they want. See user_stuff.c for more information. // // struct user_stuff_struct { double rho_c; double rho_c_start; double rho_c_inc; double rho_c_reverse; double rho_ave; double rho_ave_prev; double u_ave[2]; double u_ave_prev[2]; double tol; FILE *o; }; typedef struct user_stuff_struct *user_stuff_ptr; void user_stuff_pre_frames( lattice_ptr lattice); void user_stuff_frame( lattice_ptr lattice); void user_stuff_post_frames( lattice_ptr lattice); void user_stuff_pre_times( lattice_ptr lattice); void user_stuff_time( lattice_ptr lattice); void user_stuff_post_times( lattice_ptr lattice);
111pjb-one
src/user_stuff_20070320_contact_angles.h
C
gpl3
1,116
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // collide.c // #if POROUS_MEDIA void collide( lattice_ptr lattice) { double *f; double omega; int *bc_type; int n, a; int subs; double ns; double *ftemp; int i, j; int ip, jp, in, jn; int ni = lattice->param.LX, nj = lattice->param.LY; #if SAY_HI printf("collide() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { //dump_pdf( lattice, 998); f = lattice->pdf[subs][0].f; bc_type = &( lattice->bc[subs][0].bc_type); for( n=0; n<lattice->NumNodes; n++, f+=18, bc_type++) { if( !( *bc_type & BC_SOLID_NODE)) { // if( *bc_type == 0) // { // C O L L I D E for( a=0; a<=8; a++, f++) { // f = f - (1/tau[subs])( ftemp - feq) //printf("collide() -- (Before): n = %2d, a = %d, " // "*f = %10.7f, *(f+9) = %10.7f, *(f-9) = %10.7f\n", // n, a, *(f), *(f+9), *(f-9)); #if 1 *f = *(f+9) - ( ( *(f+9) / lattice->param.tau[subs] ) - ( *(f-9) / lattice->param.tau[subs] ) ); #else *f = *(f+9) - ( ( *(f+9) ) - ( *(f-9) ) ) / lattice->param.tau[subs]; #endif #if 0//PERTURBATIONS //if( n%lattice->NumNodes == n/lattice->NumNodes && a==5) //if( n/lattice->NumNodes == lattice->param.LY/2 && a==1) if( a==1) { //*f+=.0001*(n%lattice->NumNodes)*( rand()/(double)RAND_MAX - .5); *f+=.000001*(n%lattice->NumNodes)*( rand()/(double)RAND_MAX); } #endif /* PERTURBATIONS */ #if PUKE_NEGATIVE_DENSITIES if( *f < 0.) { printf("\n"); printf( "collide() -- Node %d (%d,%d), subs %d, " "has negative density %20.17f " "in direction %d " "at timestep %d. Exiting!\n", n, n%lattice->param.LX, n/lattice->param.LX, subs, *f, a, lattice->time ); printf("\n"); process_exit(1); } #endif /* PUKE_NEGATIVE_DENSITIES */ //printf("collide() -- (After ): n = %2d, a = %d, " // "*f = %10.7f, *(f+9) = %10.7f, *(f-9) = %10.7f\n", // n, a, *(f-1), *(f-1+9), *(f-1-9)); } /* for( a=0; a<=8; a++) */ // } // else // { //printf("collide() -- Skipping bc %d at n = %d\n", *bc_type, n); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // } } /* if( !( *bc_type++ & BC_SOLID_NODE)) */ else // *bc_type++ & BC_SOLID_NODE { // B O U N C E B A C K f++; // Skip rest particle. *f++ = *( f + 9 + 2); //f++; // f[1] = ftemp[3] *f++ = *( f + 9 + 2); //f++; // f[2] = ftemp[4] *f++ = *( f + 9 - 2); //f++; // f[3] = ftemp[1] *f++ = *( f + 9 - 2); //f++; // f[4] = ftemp[2] *f++ = *( f + 9 + 2); //f++; // f[5] = ftemp[7] *f++ = *( f + 9 + 2); //f++; // f[6] = ftemp[8] *f++ = *( f + 9 - 2); //f++; // f[7] = ftemp[5] *f++ = *( f + 9 - 2); //f++; // f[8] = ftemp[6] //printf("collide() -- Bncback: n = %2d\n", n); } /* if( !( *bc_type++ & BC_SOLID_NODE)) else */ } /* for( n=0; n<lattice_NumNodes; n++) */ if( subs==0) { // Compute the solid density term for fluid component. ftemp = lattice->pdf[subs][0].ftemp; bc_type = &( lattice->bc[subs][0].bc_type); for( n=0; n<lattice->NumNodes; n++, ftemp+=18, bc_type++) { i = n%ni; j = n/ni; jp = ( j<nj-1)?( j+1):( 0 ); jn = ( j>0 )?( j-1):( nj-1); ip = ( i<ni-1)?( i+1):( 0 ); in = ( i>0 )?( i-1):( ni-1); if( !( *bc_type & BC_SOLID_NODE)) { if( lattice->param.ns >= 0.) { ns = lattice->param.ns; /* 0 */ ftemp++; /* 1 */ *ftemp++ = ns*( lattice->pdf[subs][ j *ni + ip].f[3] - lattice->pdf[subs][ j *ni + i ].f[1]); /* 2 */ *ftemp++ = ns*( lattice->pdf[subs][ jp*ni + i ].f[4] - lattice->pdf[subs][ j *ni + i ].f[2]); /* 3 */ *ftemp++ = ns*( lattice->pdf[subs][ j *ni + in].f[1] - lattice->pdf[subs][ j *ni + i ].f[3]); /* 4 */ *ftemp++ = ns*( lattice->pdf[subs][ jn*ni + i ].f[2] - lattice->pdf[subs][ j *ni + i ].f[4]); /* 5 */ *ftemp++ = ns*( lattice->pdf[subs][ jp*ni + ip].f[7] - lattice->pdf[subs][ j *ni + i ].f[5]); /* 6 */ *ftemp++ = ns*( lattice->pdf[subs][ jp*ni + in].f[8] - lattice->pdf[subs][ j *ni + i ].f[6]); /* 7 */ *ftemp++ = ns*( lattice->pdf[subs][ jn*ni + in].f[5] - lattice->pdf[subs][ j *ni + i ].f[7]); /* 8 */ *ftemp++ = ns*( lattice->pdf[subs][ jn*ni + ip].f[6] - lattice->pdf[subs][ j *ni + i ].f[8]); } else { // TODO: Variable solid density. } } /* if( !( *bc_type++ & BC_SOLID_NODE)) */ else { ftemp+=9; } } /* for( n=0; n<lattice_NumNodes; n++) */ f = lattice->pdf[subs][0].f; bc_type = &( lattice->bc[subs][0].bc_type); for( n=0; n<lattice->NumNodes; n++, f+=18, bc_type++) { if( !( *bc_type & BC_SOLID_NODE)) { f++; for( a=1; a<9; a++, f++) { *f += *(f+9); } /* for( a=1; a<9; a++) */ } else { f+=9; } } /* for( n=0; n<lattice->NumNodes; n++, f+=18) */ } /* if( subs==0) */ //dump_pdf( lattice, 999); } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("collide() -- Bye!\n"); #endif /* SAY_HI */ } /* void collide( lattice_ptr lattice) */ #else /* !( POROUS_MEDIA) */ void collide( lattice_ptr lattice) { double *feq; double *f; double *ftemp; #if ZHANG_AND_CHEN_ENERGY_TRANSPORT double *force; #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ double omega; int bc_type; int n, a; int subs; #if SAY_HI printf("collide() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { for( n=0; n<lattice->NumNodes; n++) { feq = lattice->pdf[subs][n].feq; f = lattice->pdf[subs][n].f; ftemp = lattice->pdf[subs][n].ftemp; bc_type = lattice->bc[subs][n].bc_type; #if ZHANG_AND_CHEN_ENERGY_TRANSPORT force = lattice->force[subs][n].force; #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ if( !( bc_type & BC_SOLID_NODE)) { // C O L L I D E // f = ftemp - (1/tau[subs])( ftemp - feq) for( a=0; a<=8; a++) { #if 1 f[a] = ftemp[a] - ( ( f[a] / lattice->param.tau[subs] ) - ( feq[a] / lattice->param.tau[subs] ) ); #else f[a] = ftemp[a] - ( ( ftemp[a] ) - ( feq[a] ) ) / lattice->param.tau[subs]; #endif } /* for( a=0; a<=8; a++) */ #if ZHANG_AND_CHEN_ENERGY_TRANSPORT // // Add the body force term, equation (8), // // f_i = f_i + \Delta f_i // // = f_i + \frac{w_i}{T_0} c_i \dot F // // Assuming the weights, w_i, are the ones from compute_feq. // // Zhang & Chen state T_0 to be 1/3 for D3Q19. The same in D2Q9. // f[1] += feq[1]*( 3.*2.*force[0]); f[2] += feq[2]*( 3.*2.*force[1]); f[3] += feq[3]*( 3.*2.*force[0]); f[4] += feq[4]*( 3.*2.*force[1]); f[5] += feq[5]*( 3.*( force[0] + force[1])); f[6] += feq[6]*( 3.*( force[0] + force[1])); f[7] += feq[7]*( 3.*( force[0] + force[1])); f[8] += feq[8]*( 3.*( force[0] + force[1])); #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ #if PUKE_NEGATIVE_DENSITIES for( a=0; a<=8; a++) { if( *f < 0.) { printf("\n"); printf( "collide() -- Node %d (%d,%d), subs %d, " "has negative density %20.17f " "in direction %d " "at timestep %d. Exiting!\n", n, n%lattice->param.LX, n/lattice->param.LX, subs, f[a], a, lattice->time ); printf("\n"); process_exit(1); } } /* for( a=0; a<=8; a++) */ #endif /* PUKE_NEGATIVE_DENSITIES */ } /* if( !( bc_type & BC_SOLID_NODE)) */ else // bc_type & BC_SOLID_NODE { // B O U N C E B A C K if( lattice->param.bc_slip_north && n >= lattice->NumNodes - lattice->param.LX) { // Slip condition on north boundary. f[1] = ftemp[1]; f[2] = ftemp[4]; f[3] = ftemp[3]; f[4] = ftemp[2]; f[5] = ftemp[8]; f[6] = ftemp[7]; f[7] = ftemp[6]; f[8] = ftemp[5]; } else { // Usual non-slip bounce-back condition. f[1] = ftemp[3]; f[2] = ftemp[4]; f[3] = ftemp[1]; f[4] = ftemp[2]; f[5] = ftemp[7]; f[6] = ftemp[8]; f[7] = ftemp[5]; f[8] = ftemp[6]; } } /* if( !( bc_type & BC_SOLID_NODE)) else */ } /* for( n=0; n<lattice_NumNodes; n++) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("collide() -- Bye!\n"); #endif /* SAY_HI */ } /* void collide( lattice_ptr lattice) */ #endif /* POROUS_MEDIA */
111pjb-one
src/collide_new.c
C
gpl3
9,701
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // lb2d_prime.c // // - Lattice Boltzmann // #include "lb2d_prime.h" int main( int argc, char **argv) { int n; double k; int time, frame; clock_t tic, ticf; double t0, t1, tf; int start_frame; struct lattice_struct *lattice; struct report_struct report; //LBMPI #if PARALLEL //LBMPI lbmpi_ptr lbmpi; //LBMPI #endif /* (PARALLEL) */ setbuf( stdout, (char*)NULL); // Don't buffer screen output. // TODO: OSTYPE is not defined...? //#if OSTYPE==darwin // printf("%s %d >> Darwin \n",__FILE__,__LINE__); //#endif /* (OSTYPE=="DARWIN") */ // Allocate the lattice structure. lattice = ( struct lattice_struct*)malloc( sizeof(struct lattice_struct)); //LBMPI #if PARALLEL //LBMPI // Allocate the lbmpi structure. //LBMPI lbmpi = ( struct lbmpi_struct*)malloc( sizeof(struct lbmpi_struct)); //LBMPI //LBMPI // Give the lattice a pointer to the lbmpi structure. //LBMPI lattice->lbmpi = lbmpi; //LBMPI #endif /* (PARALLEL) */ tic = clock(); construct_lattice( &lattice, argc, argv); report_flags(lattice); //LBMPI #if PARALLEL //LBMPI lbmpi_construct( lbmpi, lattice, argc, argv); //LBMPI #endif /* (PARALLEL) */ lattice->time = 0; lattice->frame = 0; init_problem( lattice); output_frame( lattice); printf("\n"); t0 = ((double)clock() - (double)tic)/(double)CLK_TCK; printf("Overhead time: %f seconds\n", t0); tic = clock(); ticf = clock(); if( do_check_point_load( lattice)){ check_point_load( lattice);} start_frame=lattice->frame; if( do_user_stuff(lattice)) { user_stuff_pre_frames(lattice);} read_PEST_in_files( &lattice, argc, argv); for( frame = start_frame+1; frame<=get_NumFrames( lattice); frame++) { lattice->frame = frame; if( do_user_stuff(lattice)) { user_stuff_pre_times(lattice); } for( time = (frame-1)*get_FrameRate(lattice)+1; time<= frame*get_FrameRate(lattice); time++) { lattice->time = time; run_man( lattice); write_PEST_out_data( &lattice, argc, argv); stream( lattice); /* ftemp <- f */ dump( lattice, 1); //LBMPI #if PARALLEL //LBMPI lbmpi_communicate( lbmpi, lattice); //LBMPI #endif /* (PARALLEL) */ bcs( lattice); dump( lattice, 2); compute_macro_vars( lattice, /*which_f=*/ 1); // solute/buoyancy/grav //compute_macro_vars( lattice, /*which_f=*/ 1); compute_feq( lattice, 1); dump( lattice, 3); collide( lattice); /* f <- ftemp */ if( do_user_stuff(lattice)) { user_stuff_time(lattice); } } /* for( time=frame*get_FrameRate(lattice); ... */ if( do_user_stuff(lattice)) { user_stuff_post_times(lattice); } #if POROUS_MEDIA || FREED_POROUS_MEDIA // Before application of the ns term, f after collision is stored in ftemp // so which_f=1. compute_macro_vars( lattice, /*which_f=*/ 2); #else /* !( POROUS_MEDIA) */ // After collision so use f (which_f=0). #if GUO_ZHENG_SHI_BODY_FORCE compute_macro_vars( lattice, /*which_f=*/ 2); // solute/buoyancy/grav #else compute_macro_vars( lattice, /*which_f=*/ 2); // solute/buoyancy/grav #endif //compute_macro_vars( lattice, /*which_f=*/ 0); #endif /* POROUS_MEDIA */ output_frame( lattice); if( do_check_point_save( lattice)){ check_point_save( lattice);} tf = ((double)clock() - (double)ticf)/(double)CLK_TCK; ticf = clock(); if( do_user_stuff(lattice)) { user_stuff_frame(lattice); } printf("Time for frame: %f\n", tf); } /* for( frame = 0; frame<get_NumFrames( lattice); time++) */ write_PEST_out_file( &lattice, argc, argv); if( do_user_stuff(lattice)) { user_stuff_post_frames(lattice);} t1 = ((double)clock() - (double)tic)/(double)CLK_TCK; report_open( &report, "./out/report"); report_ratio_entry( &report,"Overhead time", t0, 1., "seconds"); report_ratio_entry( &report,"Time in loop", t1, 1., "seconds"); report_ratio_entry( &report,"Time in loop", t1, 60., "minutes"); report_ratio_entry( &report,"Relative overhead time", 100.*t0, t1, "%"); report_integer_entry( &report,"Number of frames", frame, ""); report_ratio_entry( &report,"Average time per frame", t1, (double)frame , "seconds"); report_integer_entry( &report,"Number of timesteps", --time, ""); report_ratio_entry( &report,"Average time per timestep", t1, (double)time, "seconds"); report_partition( &report); report_integer_entry( &report,"Size of lattice structure", get_sizeof_lattice_structure( lattice), "bytes"); report_integer_entry( &report,"Size of lattice", get_sizeof_lattice( lattice), "bytes"); report_ratio_entry( &report,"Size of lattice", get_sizeof_lattice( lattice), pow(2.,20.), "MB"); report_ratio_entry( &report,"Percentage of active nodes", 100.*(double)get_num_active_nodes( lattice), (double)lattice->NumNodes, "%"); report_close( &report); #if INAMURO_SIGMA_COMPONENT dump_sigma_btc( lattice); #endif /* INAMURO_SIGMA_COMPONENT */ destruct_lattice( lattice); #if VERBOSITY_LEVEL > 0 printf("\n"); printf("lb2d_prime.c: main() -- Terminating normally.\n"); printf("\n"); #endif /* VERBOSITY_LEVEL > 0 */ return 0; } /* int main( int argc, char **argv) */
111pjb-one
src/lb2d_prime.c
C
gpl3
5,673
//############################################################################## // // process.c // //############################################################################## void process_init( lattice_ptr lattice, int argc, char **argv) { #if PARALLEL // Routine inititialization calls. MPI_Init( &argc, &argv); MPI_Comm_size( MPI_COMM_WORLD, &(lattice->process.num_procs)); MPI_Comm_rank( MPI_COMM_WORLD, &(lattice->process.id)); #else lattice->process.id = 0; lattice->process.num_procs = 1; #endif #if VERBOSITY_LEVEL > 0 // Say hi. printf("Hello >> ProcID = %d, NumProcs = %d.\n", get_proc_id( lattice), get_num_procs( lattice) ); #endif } /* void process_init( lattice_ptr lattice, int argc, char **argv) */ //############################################################################## void process_compute_local_params( lattice_ptr lattice) { #if PARALLEL int NumLayersOnRoot; int NumLayersPerProc; // Save a copy of global dimensions. set_g_LX( lattice, get_LX( lattice)); set_g_LY( lattice, get_LY( lattice)); //3D set_g_LZ( lattice, get_LZ( lattice)); set_g_SX( lattice, 0); set_g_SY( lattice, 0); //3D set_g_SZ( lattice, 0); set_g_EX( lattice, get_LX( lattice) - 1); set_g_EY( lattice, get_LY( lattice) - 1); //3D set_g_EZ( lattice, get_LZ( lattice) - 1); set_g_NumNodes( lattice, get_NumNodes( lattice)); // Adjust local y-dimension according to local subdomain. // NOTE: Currently only supports partitioning in y-direction. NumLayersOnRoot = get_g_LY( lattice) % get_num_procs( lattice); if( NumLayersOnRoot != 0) { NumLayersPerProc = ( get_g_LY( lattice) - NumLayersOnRoot) / (get_num_procs(lattice)-1); } else { NumLayersPerProc = ( get_g_LY( lattice) - NumLayersOnRoot) / (get_num_procs(lattice)); NumLayersOnRoot = NumLayersPerProc; } if( is_on_root_proc( lattice)) { // Assign the left-over (modulus) layers. set_LY( lattice, NumLayersOnRoot); set_g_SY( lattice, 0); set_g_EY( lattice, 0 + NumLayersOnRoot - 1); set_g_StartNode( lattice, 0); } else { set_LY( lattice, NumLayersPerProc); set_g_SY( lattice, NumLayersOnRoot + NumLayersPerProc*(get_proc_id(lattice)-1) ); set_g_EY( lattice, NumLayersOnRoot + NumLayersPerProc*(get_proc_id(lattice)-1) + NumLayersPerProc - 1); set_g_StartNode( lattice, get_g_SY( lattice)*( get_LX(lattice)) ); } set_NumNodes( lattice); lattice->process.y_pos_pdf_to_send = (double*)malloc( 3*(get_LX(lattice))*sizeof(double)); lattice->process.y_pos_pdf_to_recv = (double*)malloc( 3*(get_LX(lattice))*sizeof(double)); lattice->process.y_neg_pdf_to_send = (double*)malloc( 3*(get_LX(lattice))*sizeof(double)); lattice->process.y_neg_pdf_to_recv = (double*)malloc( 3*(get_LX(lattice))*sizeof(double)); #endif #if VERBOSITY_LEVEL > 0 #if PARALLEL printf( "Proc %04d" ", g_SX = %d" ", g_EX = %d" ", g_LX = %d" ", g_SY = %d" ", g_EY = %d" ", g_LY = %d" ", LX = %d" ", LY = %d" //3D ", g_SZ = %d" //3D ", g_EZ = %d" //3D ", g_LZ = %d" ", g_StartNode = %d" ", g_NumNodes = %d" ", NumNodes = %d" ".\n" ,get_proc_id( lattice) ,get_g_SX( lattice) ,get_g_EX( lattice) ,get_g_LX( lattice) ,get_g_SY( lattice) ,get_g_EY( lattice) ,get_g_LY( lattice) ,get_LX( lattice) ,get_LY( lattice) //3D ,get_g_SZ( lattice) //3D ,get_g_EZ( lattice) //3D ,get_g_LZ( lattice) ,get_g_StartNode( lattice) ,get_g_NumNodes( lattice) ,get_NumNodes( lattice) ); #endif #endif } /* void process_compute_local_params( lattice_ptr lattice) */ //############################################################################## void process_send_recv_begin( lattice_ptr lattice, const int subs) { #if PARALLEL int n; int i, j, k; int ni = get_LX( lattice), nj = get_LY( lattice); int mpierr; // A C C U M U L A T E P D F S T O S E N D //######################################################################### n = 0; j = get_LY(lattice)-1; //3D for( j=0; j<nj; j++) //3D { for( i=0; i<ni; i++) { lattice->process.y_pos_pdf_to_send[n] = lattice->pdf[subs][ XY2N( i , j , ni)].f[ N]; lattice->process.y_neg_pdf_to_send[n] = lattice->pdf[subs][ XY2N( i , 0 , ni)].f[ S]; n++; lattice->process.y_pos_pdf_to_send[n] = lattice->pdf[subs][ XY2N( i , j , ni)].f[NW]; lattice->process.y_neg_pdf_to_send[n] = lattice->pdf[subs][ XY2N( i , 0 , ni)].f[SW]; n++; lattice->process.y_pos_pdf_to_send[n] = lattice->pdf[subs][ XY2N( i , j , ni)].f[NE]; lattice->process.y_neg_pdf_to_send[n] = lattice->pdf[subs][ XY2N( i , 0 , ni)].f[SE]; n++; //3D lattice->process.y_pos_pdf_to_send[n] = //3D lattice->pdf[subs][ XY2N( i , j , ni)].f[TN]; //3D lattice->process.y_neg_pdf_to_send[n] = //3D lattice->pdf[subs][ XY2N( i , j , ni)].f[BN]; //3D n++; //3D lattice->process.y_pos_pdf_to_send[n] = //3D lattice->pdf[subs][ XY2N( i , j , ni)].f[TS]; //3D lattice->process.y_neg_pdf_to_send[n] = //3D lattice->pdf[subs][ XY2N( i , j , ni)].f[BS]; //3D n++; } /* if( i=0; i<ni; i++) */ //3D } /* if( j=0; j<nj; j++) */ #if 0 // Contrived debug data... display_warning_about_contrived_data( lattice); n = 0; j = 1; for( i=0; i<ni; i++) { #if 0 lattice->process.y_pos_pdf_to_send[n] = 1; lattice->process.y_neg_pdf_to_send[n] = 1; n++; lattice->process.y_pos_pdf_to_send[n] = 2; lattice->process.y_neg_pdf_to_send[n] = 2; n++; lattice->process.y_pos_pdf_to_send[n] = 3; lattice->process.y_neg_pdf_to_send[n] = 3; n++; #endif #if 1 lattice->process.y_pos_pdf_to_send[n] = j; lattice->process.y_neg_pdf_to_send[n] = j; n++; lattice->process.y_pos_pdf_to_send[n] = j; lattice->process.y_neg_pdf_to_send[n] = j; n++; lattice->process.y_pos_pdf_to_send[n] = j; lattice->process.y_neg_pdf_to_send[n] = j; n++; j++; #endif } /* if( j=0; j<nj; j++) */ #endif //process_dump_pdfs_to_send( lattice, "Before Send/Recv"); // S E N D I N P O S I T I V E D I R E C T I O N //######################################################################### #if VERBOSITY_LEVEL > 1 printf( "%s %d %04d >> " "MPI_Isend( %04d)" "\n", __FILE__,__LINE__,get_proc_id(lattice), (get_proc_id(lattice)+get_num_procs(lattice)+1)%get_num_procs(lattice)); #endif mpierr = MPI_Isend( /*void *buf*/ lattice->process.y_pos_pdf_to_send, /*int count*/ 3*(get_LX(lattice)), /*MPI_Datatype dtype*/ MPI_DOUBLE, /*int dest*/ ( get_proc_id(lattice) + get_num_procs(lattice)+1) % get_num_procs(lattice), /*int tag*/ 0, /*MPI_Comm comm*/ MPI_COMM_WORLD, /*MPI_Request *req*/ &(lattice->process.send_req_0) ); if( mpierr != MPI_SUCCESS) { printf( "%s %d %04d >> " "ERROR: %d <-- MPI_Isend( %04d)" "\n", __FILE__,__LINE__,get_proc_id(lattice), mpierr, (get_proc_id(lattice)+get_num_procs(lattice)+1)%get_num_procs(lattice)); process_exit(1); } // R E C V F R O M N E G A T I V E D I R E C T I O N //######################################################################### #if VERBOSITY_LEVEL > 1 printf( "%s %d %04d >> " "MPI_Irecv( %04d)" "\n", __FILE__,__LINE__,get_proc_id(lattice), (get_proc_id(lattice)+get_num_procs(lattice)-1)%get_num_procs(lattice)); #endif mpierr = MPI_Irecv( /*void *buf*/ lattice->process.y_pos_pdf_to_recv, /*int count*/ 3*(get_LX(lattice)), /*MPI_Datatype dtype*/ MPI_DOUBLE, /*int src*/ ( get_proc_id(lattice) + get_num_procs(lattice)-1) % get_num_procs(lattice), /*int tag*/ 0, /*MPI_Comm comm*/ MPI_COMM_WORLD, /*MPI_Request *req*/ &(lattice->process.recv_req_0) ); if( mpierr != MPI_SUCCESS) { printf( "%s %d %04d >> " "ERROR: %d <-- MPI_Irecv( %04d)" "\n", __FILE__,__LINE__,get_proc_id(lattice), mpierr, (get_proc_id(lattice)+get_num_procs(lattice)-1)%get_num_procs(lattice)); process_exit(1); } // S E N D I N N E G A T I V E D I R E C T I O N //######################################################################### #if VERBOSITY_LEVEL > 1 printf( "%s %d %04d >> " "MPI_Isend( %04d)" "\n", __FILE__,__LINE__,get_proc_id(lattice), (get_proc_id(lattice)+get_num_procs(lattice)-1)%get_num_procs(lattice)); #endif mpierr = MPI_Isend( /*void *buf*/ lattice->process.y_neg_pdf_to_send, /*int count*/ 3*(get_LX(lattice)), /*MPI_Datatype dtype*/ MPI_DOUBLE, /*int dest*/ ( get_proc_id(lattice) + get_num_procs(lattice)-1) % get_num_procs(lattice), /*int tag*/ 1, /*MPI_Comm comm*/ MPI_COMM_WORLD, /*MPI_Request *req*/ &(lattice->process.send_req_1) ); if( mpierr != MPI_SUCCESS) { printf( "%s %d %04d >> " "ERROR: %d <-- MPI_Isend( %04d)" "\n", __FILE__,__LINE__,get_proc_id(lattice), mpierr, (get_proc_id(lattice)+get_num_procs(lattice)-1)%get_num_procs(lattice)); process_exit(1); } // R E C V F R O M P O S I T I V E D I R E C T I O N //######################################################################### #if VERBOSITY_LEVEL > 1 printf( "%s %d %04d >> " "MPI_Irecv( %04d)" "\n", __FILE__,__LINE__,get_proc_id(lattice), (get_proc_id(lattice)+get_num_procs(lattice)+1)%get_num_procs(lattice)); #endif mpierr = MPI_Irecv( /*void *buf*/ lattice->process.y_neg_pdf_to_recv, /*int count*/ 3*(get_LX(lattice)), /*MPI_Datatype dtype*/ MPI_DOUBLE, /*int src*/ ( get_proc_id(lattice) + get_num_procs(lattice)+1) % get_num_procs(lattice), /*int tag*/ 1, /*MPI_Comm comm*/ MPI_COMM_WORLD, /*MPI_Request *req*/ &(lattice->process.recv_req_1) ); if( mpierr != MPI_SUCCESS) { printf( "%s %d %04d >> " "ERROR: %d <-- MPI_Irecv( %04d)" "\n", __FILE__,__LINE__,get_proc_id(lattice), mpierr, (get_proc_id(lattice)+get_num_procs(lattice)+1)%get_num_procs(lattice)); process_exit(1); } #endif } /* void process_send_recv_begin( lattice_ptr lattice, const int subs) */ //############################################################################## void process_send_recv_end( lattice_ptr lattice, const int subs) { #if PARALLEL int n; int i, j; //3D , k; int ni = get_LX( lattice), nj = get_LY( lattice); int ip, in; int jp, jn; int mpierr; mpierr = MPI_Wait( /* MPI_Request *req */&(lattice->process.send_req_0), /* MPI_Status *stat */&(lattice->process.mpi_status)); mpierr = MPI_Wait( /* MPI_Request *req */&(lattice->process.recv_req_0), /* MPI_Status *stat */&(lattice->process.mpi_status)); mpierr = MPI_Wait( /* MPI_Request *req */&(lattice->process.send_req_1), /* MPI_Status *stat */&(lattice->process.mpi_status)); mpierr = MPI_Wait( /* MPI_Request *req */&(lattice->process.recv_req_1), /* MPI_Status *stat */&(lattice->process.mpi_status)); //process_dump_pdfs_to_recv( lattice, "After Send/Recv, Before Stream"); //dump_north_pointing_pdfs( lattice, subs, -1, // "After Send/Recv, Before Stream", 2); //dump_south_pointing_pdfs( lattice, subs, -1, // "After Send/Recv, Before Stream", 2); // S T R E A M I N T H E B O U N D A R I E S //########################################################################### n = 0; j = get_LY(lattice)-1; //3D for( j=0; j<nj; j++) //3D { //3D jp = ( j<nj-1)?( j+1):( 0 ); //3D jn = ( j>0 )?( j-1):( nj-1); for( i=0; i<ni; i++) { ip = ( i<ni-1)?( i+1):( 0 ); in = ( i>0 )?( i-1):( ni-1); lattice->pdf[subs][ XY2N( i , 0 , ni)].ftemp[ N] = lattice->process.y_pos_pdf_to_recv[n]; lattice->pdf[subs][ XY2N( i , j , ni)].ftemp[ S] = lattice->process.y_neg_pdf_to_recv[n]; n++; lattice->pdf[subs][ XY2N( in, 0 , ni)].ftemp[NW] = lattice->process.y_pos_pdf_to_recv[n]; lattice->pdf[subs][ XY2N( in, j , ni)].ftemp[SW] = lattice->process.y_neg_pdf_to_recv[n]; n++; lattice->pdf[subs][ XY2N( ip, 0 , ni)].ftemp[NE] = lattice->process.y_pos_pdf_to_recv[n]; lattice->pdf[subs][ XY2N( ip, j , ni)].ftemp[SE] = lattice->process.y_neg_pdf_to_recv[n]; n++; //3D lattice->pdf[subs][ XY2N( i , jp, ni)].ftemp[TN] = //3D lattice->process.y_pos_pdf_to_recv[n]; //3D lattice->pdf[subs][ XY2N( i , jp, ni)].ftemp[BN] = //3D lattice->process.y_neg_pdf_to_recv[n]; //3D n++; //3D lattice->pdf[subs][ XY2N( i , jn, ni)].ftemp[TS] = //3D lattice->process.y_pos_pdf_to_recv[n]; //3D lattice->pdf[subs][ XY2N( i , jn, ni)].ftemp[BS] = //3D lattice->process.y_neg_pdf_to_recv[n]; //3D n++; } /* if( i=0; i<ni; i++) */ //3D } /* if( j=0; j<nj; j++) */ #if 0 // Copy back to check with a call to process_dump_pdfs... #if 0 n = 0; j = get_LY(lattice)-1; //3D for( j=0; j<nj; j++) //3D { for( i=0; i<ni; i++) { lattice->process.y_pos_pdf_to_recv[n] = lattice->pdf[subs][ XY2N( i , j , ni)].ftemp[ N]; lattice->process.y_neg_pdf_to_recv[n] = lattice->pdf[subs][ XY2N( i , j , ni)].ftemp[ S]; n++; lattice->process.y_pos_pdf_to_recv[n] = lattice->pdf[subs][ XY2N( i , j , ni)].ftemp[NW]; lattice->process.y_neg_pdf_to_recv[n] = lattice->pdf[subs][ XY2N( i , j , ni)].ftemp[SW]; n++; lattice->process.y_pos_pdf_to_recv[n] = lattice->pdf[subs][ XY2N( i , j , ni)].ftemp[NE]; lattice->process.y_neg_pdf_to_recv[n] = lattice->pdf[subs][ XY2N( i , j , ni)].ftemp[SE]; n++; //3D lattice->process.y_pos_pdf_to_recv[n] = //3D lattice->pdf[subs][ XY2N( i , j , ni)].ftemp[TN]; //3D lattice->process.y_neg_pdf_to_recv[n] = //3D lattice->pdf[subs][ XY2N( i , j , ni)].ftemp[BN]; //3D n++; //3D lattice->process.y_pos_pdf_to_recv[n] = //3D lattice->pdf[subs][ XY2N( i , j , ni)].ftemp[TS]; //3D lattice->process.y_neg_pdf_to_recv[n] = //3D lattice->pdf[subs][ XY2N( i , j , ni)].ftemp[BS]; //3D n++; } /* if( i=0; i<ni; i++) */ //3D } /* if( j=0; j<nj; j++) */ #else gather_north_pointing_pdfs( lattice, lattice->process.y_pos_pdf_to_recv, subs, get_LY(lattice)-1, 2); gather_south_pointing_pdfs( lattice, lattice->process.y_neg_pdf_to_recv, subs, 0, 2); #endif //process_dump_pdfs_to_recv( lattice, "After Stream"); #endif #endif } /* void process_send_recv_end( lattice_ptr lattice, const int subs) */ //############################################################################## void process_dump_pdfs_to_recv( lattice_ptr lattice, char *comment_str) { #if PARALLEL char new_comment[1024]; sprintf( new_comment, "pos pdfs to recv, %s", comment_str); process_dump_pdfs( lattice, new_comment, lattice->process.y_pos_pdf_to_recv); sprintf( new_comment, "neg pdfs to recv, %s", comment_str); process_dump_pdfs( lattice, new_comment, lattice->process.y_neg_pdf_to_recv); #endif } /* void process_dump_pdfs_to_recv( lattice_ptr lattice) */ //############################################################################## void process_dump_pdfs_to_send( lattice_ptr lattice, char *comment_str) { #if PARALLEL char new_comment[1024]; sprintf( new_comment, "pos pdfs to send, %s", comment_str); process_dump_pdfs( lattice, new_comment, lattice->process.y_pos_pdf_to_send); sprintf( new_comment, "neg pdfs to send, %s", comment_str); process_dump_pdfs( lattice, new_comment, lattice->process.y_neg_pdf_to_send); #endif } /* void process_dump_pdfs_to_send( lattice_ptr lattice) */ //############################################################################## void process_dump_pdfs( lattice_ptr lattice, char *comment_str, double *pdfs) { #if PARALLEL int n, p; int i, j, k; int ni = get_LX( lattice), nj = get_LY( lattice); int mpierr; for( p=0; p<get_num_procs( lattice); p++) { MPI_Barrier( MPI_COMM_WORLD); if( p == get_proc_id(lattice)) { printf("\n\n// Proc %d, \"%s\".", get_proc_id( lattice), comment_str); printf("\n "); for( i=0; i<ni; i++) { printf("+"); printf("---"); printf("---"); printf("---"); printf("-"); } printf("+"); //3D for( j=0; j<nj; j++) //3D { // 0 1 2 3 4 // O W E N S // South //3D n = 5*j*ni + 4; //3D printf("\n "); //3D for( i=0; i<ni; i++) //3D { //3D printf("|"); //3D printf(" "); //3D printf(" %2.0f", pdfs[n]); //3D printf(" "); //3D printf(" "); //3D n+=5; //3D } //3D printf("|"); // West/O/East n = 0; printf("\n "); for( i=0; i<ni; i++) { printf("|"); printf(" %2.0f", pdfs[n+1]); printf(" %2.0f", pdfs[n]); printf(" %2.0f", pdfs[n+2]); printf(" "); n+=3; } printf("|"); // North //3D n = 5*j*ni + 3; //3D printf("\n "); //3D for( i=0; i<ni; i++) //3D { //3D printf("|"); //3D printf(" "); //3D printf(" %2.0f", pdfs[n]); //3D printf(" "); //3D printf(" "); //3D n+=5; //3D } //3D printf("|"); printf("\n "); for( i=0; i<ni; i++) { printf("+"); printf("---"); printf("---"); printf("---"); printf("-"); } printf("+"); //3D } /* if( j=0; j<nj; j++) */ } /* if( p == get_proc_id(lattice)) */ } /* for( p=0; p<get_num_procs( lattice); p++) */ MPI_Barrier( MPI_COMM_WORLD); #endif } /* void process_dump_pdfs_to_recv( lattice_ptr lattice) */ //############################################################################## void gather_north_pointing_pdfs( lattice_ptr lattice, double *north, const int subs, const int k, const int which_pdf) { int i, j, n; int ni = get_LX( lattice), nj = get_LY( lattice); switch(which_pdf) { case 0: n = 0; //3D for( j=0; j<nj; j++) //3D { for( i=0; i<ni; i++) { north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].feq[ N]; n++; north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].feq[NW]; n++; north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].feq[NE]; n++; //3D north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].feq[TN]; n++; //3D north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].feq[TS]; n++; } /* if( i=0; i<ni; i++) */ //3D } /* if( j=0; j<nj; j++) */ break; case 1: n = 0; //3D for( j=0; j<nj; j++) //3D { for( i=0; i<ni; i++) { north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].f[ N]; n++; north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].f[NW]; n++; north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].f[NE]; n++; //3D north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].f[TN]; n++; //3D north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].f[TS]; n++; } /* if( i=0; i<ni; i++) */ //3D } /* if( j=0; j<nj; j++) */ break; case 2: n = 0; //3D for( j=0; j<nj; j++) //3D { for( i=0; i<ni; i++) { north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].ftemp[ N]; n++; north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].ftemp[NW]; n++; north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].ftemp[NE]; n++; //3D north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].ftemp[TN]; n++; //3D north[n] = lattice->pdf[subs][ XY2N(i,j, ni)].ftemp[TS]; n++; } /* if( i=0; i<ni; i++) */ //3D } /* if( j=0; j<nj; j++) */ break; default: printf("%s %d %04d >> ERROR: Unhandled case which_pdf=%d. Exiting!", __FILE__,__LINE__,get_proc_id(lattice), which_pdf); process_exit(1); break; } /* switch(which_pdf) */ } /* void gather_north_pointing_pdfs( lattice_ptr lattice, double *north) */ //############################################################################## void gather_south_pointing_pdfs( lattice_ptr lattice, double *south, const int subs, const int k, const int which_pdf) { int i, j, n; int ni = get_LX( lattice), nj = get_LY( lattice); switch(which_pdf) { case 0: n = 0; //3D for( j=0; j<nj; j++) //3D { for( i=0; i<ni; i++) { south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].feq[ S]; n++; south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].feq[SW]; n++; south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].feq[SE]; n++; //3D south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].feq[BN]; n++; //3D south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].feq[BS]; n++; } /* if( i=0; i<ni; i++) */ //3D } /* if( j=0; j<nj; j++) */ break; case 1: n = 0; //3D for( j=0; j<nj; j++) //3D { for( i=0; i<ni; i++) { south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].f[ S]; n++; south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].f[SW]; n++; south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].f[SE]; n++; //3D south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].f[BN]; n++; //3D south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].f[BS]; n++; } /* if( i=0; i<ni; i++) */ //3D } /* if( j=0; j<nj; j++) */ break; case 2: n = 0; //3D for( j=0; j<nj; j++) //3D { for( i=0; i<ni; i++) { south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].ftemp[ S]; n++; south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].ftemp[SW]; n++; south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].ftemp[SE]; n++; //3D south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].ftemp[BN]; n++; //3D south[n] = lattice->pdf[subs][ XY2N(i,j, ni)].ftemp[BS]; n++; } /* if( i=0; i<ni; i++) */ //3D } /* if( j=0; j<nj; j++) */ break; default: printf("%s %d %04d >> ERROR: Unhandled case which_pdf=%d. Exiting!", __FILE__,__LINE__,get_proc_id(lattice), which_pdf); process_exit(1); break; } } /* void gather_south_pointing_pdfs( lattice_ptr lattice, double *south) */ void process_reduce_double_sum( lattice_ptr lattice, double *arg_x) { #if PARALLEL double sum_x; int mpierr; // // INPUT PARAMETERS // sbuf - address of send buffer (choice) // count - number of elements in send buffer (integer) // dtype - data type of elements of send buffer (handle) // op - reduce operation (handle) // root - rank of root process (integer) // comm - communicator (handle) // // OUTPUT PARAMETER // rbuf - address of receive buffer (choice, sig't only at root ) // mpierr = MPI_Allreduce( /*void *sbuf*/ arg_x, /*void* rbuf*/ &sum_x, /*int count*/ 1, /*MPI_Datatype dtype*/ MPI_DOUBLE, /*MPI_Op op*/ MPI_SUM, /*MPI_Comm comm*/ MPI_COMM_WORLD ); if( mpierr != MPI_SUCCESS) { printf( "%s %d %04d >> " "ERROR: %d <-- MPI_Reduce( ave_rho, MPI_DOUBLE, MPI_SUM)" "\n", __FILE__,__LINE__,get_proc_id(lattice), mpierr); process_exit(1); } #if 0 if( is_on_root_proc( lattice)) { *arg_x = sum_x; } mpierr = MPI_Bcast( /*void *buffer*/ arg_x, /*int count*/ 1, /*MPI_Datatype datatype*/ MPI_DOUBLE, /*int root*/ 0, /*MPI_Comm comm*/ MPI_COMM_WORLD ); if( mpierr != MPI_SUCCESS) { printf( "%s %d %04d >> " "ERROR: %d <-- MPI_Reduce( ave_rho, MPI_DOUBLE, MPI_SUM)" "\n", __FILE__,__LINE__,get_proc_id(lattice), mpierr); process_exit(1); } #endif #endif } /* void process_reduce_double_sum( lattice_ptr lattice, double &arg_x) */ void process_reduce_int_sum( lattice_ptr lattice, int *arg_n) { #if PARALLEL double sum_n; int mpierr; // // INPUT PARAMETERS // sbuf - address of send buffer (choice) // count - number of elements in send buffer (integer) // dtype - data type of elements of send buffer (handle) // op - reduce operation (handle) // root - rank of root process (integer) // comm - communicator (handle) // // OUTPUT PARAMETER // rbuf - address of receive buffer (choice, sig't only at root ) // mpierr = MPI_Allreduce( /*void *sbuf*/ arg_n, /*void* rbuf*/ &sum_n, /*int count*/ 1, /*MPI_Datatype dtype*/ MPI_INT, /*MPI_Op op*/ MPI_SUM, /*MPI_Comm comm*/ MPI_COMM_WORLD ); if( mpierr != MPI_SUCCESS) { printf( "%s %d %04d >> " "ERROR: %d <-- MPI_Reduce( ave_rho, MPI_DOUBLE, MPI_SUM)" "\n", __FILE__,__LINE__,get_proc_id(lattice), mpierr); process_exit(1); } #if 0 if( is_on_root_proc( lattice)) { *arg_n = sum_n; } mpierr = MPI_Bcast( /*void *buffer*/ arg_n, /*int count*/ 1, /*MPI_Datatype datatype*/ MPI_DOUBLE, /*int root*/ 0, /*MPI_Comm comm*/ MPI_COMM_WORLD ); if( mpierr != MPI_SUCCESS) { printf( "%s %d %04d >> " "ERROR: %d <-- MPI_Reduce( ave_rho, MPI_DOUBLE, MPI_SUM)" "\n", __FILE__,__LINE__,get_proc_id(lattice), mpierr); process_exit(1); } #endif #endif } /* void process_reduce_int_sum( lattice_ptr lattice, int *arg_n) */ void process_reduce_double_max( lattice_ptr lattice, double *arg_x) { #if PARALLEL double max_x; int mpierr; // // INPUT PARAMETERS // sbuf - address of send buffer (choice) // count - number of elements in send buffer (integer) // dtype - data type of elements of send buffer (handle) // op - reduce operation (handle) // root - rank of root process (integer) // comm - communicator (handle) // // OUTPUT PARAMETER // rbuf - address of receive buffer (choice, sig't only at root ) // mpierr = MPI_Allreduce( /*void *sbuf*/ arg_x, /*void* rbuf*/ &max_x, /*int count*/ 1, /*MPI_Datatype dtype*/ MPI_DOUBLE, /*MPI_Op op*/ MPI_MAX, /*MPI_Comm comm*/ MPI_COMM_WORLD ); if( mpierr != MPI_SUCCESS) { printf( "%s %d %04d >> " "ERROR: %d <-- MPI_Reduce( ave_rho, MPI_DOUBLE, MPI_SUM)" "\n", __FILE__,__LINE__,get_proc_id(lattice), mpierr); process_exit(1); } #if 0 if( is_on_root_proc( lattice)) { *arg_x = max_x; } mpierr = MPI_Bcast( /*void *buffer*/ arg_x, /*int count*/ 1, /*MPI_Datatype datatype*/ MPI_DOUBLE, /*int root*/ 0, /*MPI_Comm comm*/ MPI_COMM_WORLD ); if( mpierr != MPI_SUCCESS) { printf( "%s %d %04d >> " "ERROR: %d <-- MPI_Reduce( ave_rho, MPI_DOUBLE, MPI_SUM)" "\n", __FILE__,__LINE__,get_proc_id(lattice), mpierr); process_exit(1); } #endif #endif } /* void process_reduce_double_sum( lattice_ptr lattice, double &arg_x) */ void process_reduce_double_min( lattice_ptr lattice, double *arg_x) { #if PARALLEL double min_x; int mpierr; // // INPUT PARAMETERS // sbuf - address of send buffer (choice) // count - number of elements in send buffer (integer) // dtype - data type of elements of send buffer (handle) // op - reduce operation (handle) // root - rank of root process (integer) // comm - communicator (handle) // // OUTPUT PARAMETER // rbuf - address of receive buffer (choice, sig't only at root ) // mpierr = MPI_Allreduce( /*void *sbuf*/ arg_x, /*void* rbuf*/ &min_x, /*int count*/ 1, /*MPI_Datatype dtype*/ MPI_DOUBLE, /*MPI_Op op*/ MPI_MIN, /*MPI_Comm comm*/ MPI_COMM_WORLD ); if( mpierr != MPI_SUCCESS) { printf( "%s %d %04d >> " "ERROR: %d <-- MPI_Reduce( ave_rho, MPI_DOUBLE, MPI_SUM)" "\n", __FILE__,__LINE__,get_proc_id(lattice), mpierr); process_exit(1); } #if 0 if( is_on_root_proc( lattice)) { *arg_x = min_x; } mpierr = MPI_Bcast( /*void *buffer*/ arg_x, /*int count*/ 1, /*MPI_Datatype datatype*/ MPI_DOUBLE, /*int root*/ 0, /*MPI_Comm comm*/ MPI_COMM_WORLD ); if( mpierr != MPI_SUCCESS) { printf( "%s %d %04d >> " "ERROR: %d <-- MPI_Reduce( ave_rho, MPI_DOUBLE, MPI_SUM)" "\n", __FILE__,__LINE__,get_proc_id(lattice), mpierr); process_exit(1); } #endif #endif } /* void process_reduce_double_sum( lattice_ptr lattice, double &arg_x) */ //############################################################################## void process_barrier() { #if PARALLEL MPI_Barrier( MPI_COMM_WORLD); #endif } //############################################################################## void process_finalize() { #if PARALLEL MPI_Finalize(); #endif } //############################################################################## void process_exit( int exit_val) { process_finalize(); exit( exit_val); } //############################################################################## // // Accessor methods for the process struct. // int get_proc_id( lattice_ptr lattice) { return lattice->process.id;} int get_num_procs( lattice_ptr lattice) { return lattice->process.num_procs;} int is_on_root_proc( lattice_ptr lattice) { return !(lattice->process.id);} #if PARALLEL int get_g_LX( lattice_ptr lattice) { return lattice->process.g_LX;} int get_g_LY( lattice_ptr lattice) { return lattice->process.g_LY;} //3D int get_g_LZ( lattice_ptr lattice) { return lattice->process.g_LZ;} int get_g_SX( lattice_ptr lattice) { return lattice->process.g_SX;} int get_g_SY( lattice_ptr lattice) { return lattice->process.g_SY;} //3D int get_g_SZ( lattice_ptr lattice) { return lattice->process.g_SZ;} int get_g_EX( lattice_ptr lattice) { return lattice->process.g_EX;} int get_g_EY( lattice_ptr lattice) { return lattice->process.g_EY;} //3D int get_g_EZ( lattice_ptr lattice) { return lattice->process.g_EZ;} void set_g_LX( lattice_ptr lattice, const int arg_LX) { lattice->process.g_LX = arg_LX; } void set_g_LY( lattice_ptr lattice, const int arg_LY) { lattice->process.g_LY = arg_LY; } //3D void set_g_LZ( lattice_ptr lattice, const int arg_LZ) //3D { //3D lattice->process.g_LZ = arg_LZ; //3D } void set_g_SX( lattice_ptr lattice, const int arg_SX) { lattice->process.g_SX = arg_SX; } void set_g_SY( lattice_ptr lattice, const int arg_SY) { lattice->process.g_SY = arg_SY; } //3D void set_g_SZ( lattice_ptr lattice, const int arg_SZ) //3D { //3D lattice->process.g_SZ = arg_SZ; //3D } void set_g_EX( lattice_ptr lattice, const int arg_EX) { lattice->process.g_EX = arg_EX; } void set_g_EY( lattice_ptr lattice, const int arg_EY) { lattice->process.g_EY = arg_EY; } //3D void set_g_EZ( lattice_ptr lattice, const int arg_EZ) //3D { //3D lattice->process.g_EZ = arg_EZ; //3D } int get_g_NumNodes( lattice_ptr lattice) { return lattice->process.g_NumNodes;} void set_g_NumNodes( lattice_ptr lattice, const int arg_NumNodes) { lattice->process.g_NumNodes = arg_NumNodes; } void set_g_StartNode( lattice_ptr lattice, const int arg_n) { lattice->process.g_StartNode = arg_n; } int get_g_StartNode( lattice_ptr lattice) { return lattice->process.g_StartNode; } double g2lx( lattice_ptr lattice, double g_x) { // 1 g_ey=7 -o // g_y =6 o- y = g_y - g_sy = 6 - 4 = 2 // o // 1 g_sy=4 -o // 0 g_ey=3 -o // o // o // 0 g_sy=0 -o return g_x - get_g_SX(lattice); } double g2ly( lattice_ptr lattice, double g_y) { return g_y - get_g_SY(lattice); } #else // Defaults for non-parallel runs. int get_g_LX( lattice_ptr lattice) { return get_LX( lattice);} int get_g_LY( lattice_ptr lattice) { return get_LY( lattice);} //3D int get_g_LZ( lattice_ptr lattice) { return get_LZ( lattice);} int get_g_SX( lattice_ptr lattice) { return 0;} int get_g_SY( lattice_ptr lattice) { return 0;} //3D int get_g_SZ( lattice_ptr lattice) { return 0;} int get_g_EX( lattice_ptr lattice) { return get_LX( lattice)-1;} int get_g_EY( lattice_ptr lattice) { return get_LY( lattice)-1;} //3D int get_g_EZ( lattice_ptr lattice) { return get_LZ( lattice)-1;} int get_g_NumNodes( lattice_ptr lattice) { return get_NumNodes( lattice);} int get_g_StartNode( lattice_ptr lattice) { return 0;} double g2lx( lattice_ptr lattice, double g_x) { return g_x;} double g2ly( lattice_ptr lattice, double g_y) { return g_y;} #endif // vim: foldmethod=syntax
111pjb-one
src/process.c
C
gpl3
34,172
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // collide.c // #if POROUS_MEDIA void collide( lattice_ptr lattice) { double *f; double omega; int *bc_type; int n, a; int subs; double ns; double *ftemp; int i, j; int ip, jp, in, jn; int ni = lattice->param.LX, nj = lattice->param.LY; #if SAY_HI printf("collide() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { //dump_pdf( lattice, 998); f = lattice->pdf[subs][0].f; bc_type = &( lattice->bc[subs][0].bc_type); for( n=0; n<lattice->NumNodes; n++, f+=18, bc_type++) { if( !( *bc_type & BC_SOLID_NODE)) { // if( *bc_type == 0) // { // C O L L I D E for( a=0; a<=8; a++, f++) { // f = f - (1/tau[subs])( ftemp - feq) //printf("collide() -- (Before): n = %2d, a = %d, " // "*f = %10.7f, *(f+9) = %10.7f, *(f-9) = %10.7f\n", // n, a, *(f), *(f+9), *(f-9)); #if 1 *f = *(f+9) - ( ( *(f+9) / lattice->param.tau[subs] ) - ( *(f-9) / lattice->param.tau[subs] ) ); #else *f = *(f+9) - ( ( *(f+9) ) - ( *(f-9) ) ) / lattice->param.tau[subs]; #endif #if 0//PERTURBATIONS //if( n%lattice->NumNodes == n/lattice->NumNodes && a==5) //if( n/lattice->NumNodes == lattice->param.LY/2 && a==1) if( a==1) { //*f+=.0001*(n%lattice->NumNodes)*( rand()/(double)RAND_MAX - .5); *f+=.000001*(n%lattice->NumNodes)*( rand()/(double)RAND_MAX); } #endif /* PERTURBATIONS */ #if PUKE_NEGATIVE_DENSITIES if( *f < 0.) { printf("\n"); printf( "collide() -- Node %d (%d,%d), subs %d, " "has negative density %20.17f " "in direction %d " "at timestep %d. Exiting!\n", n, n%lattice->param.LX, n/lattice->param.LX, subs, *f, a, lattice->time ); printf("\n"); process_exit(1); } #endif /* PUKE_NEGATIVE_DENSITIES */ //printf("collide() -- (After ): n = %2d, a = %d, " // "*f = %10.7f, *(f+9) = %10.7f, *(f-9) = %10.7f\n", // n, a, *(f-1), *(f-1+9), *(f-1-9)); } /* for( a=0; a<=8; a++) */ // } // else // { //printf("collide() -- Skipping bc %d at n = %d\n", *bc_type, n); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // *f++ = *( f + 9); // } } /* if( !( *bc_type++ & BC_SOLID_NODE)) */ else // *bc_type++ & BC_SOLID_NODE { // B O U N C E B A C K f++; // Skip rest particle. *f++ = *( f + 9 + 2); //f++; // f[1] = ftemp[3] *f++ = *( f + 9 + 2); //f++; // f[2] = ftemp[4] *f++ = *( f + 9 - 2); //f++; // f[3] = ftemp[1] *f++ = *( f + 9 - 2); //f++; // f[4] = ftemp[2] *f++ = *( f + 9 + 2); //f++; // f[5] = ftemp[7] *f++ = *( f + 9 + 2); //f++; // f[6] = ftemp[8] *f++ = *( f + 9 - 2); //f++; // f[7] = ftemp[5] *f++ = *( f + 9 - 2); //f++; // f[8] = ftemp[6] //printf("collide() -- Bncback: n = %2d\n", n); } /* if( !( *bc_type++ & BC_SOLID_NODE)) else */ } /* for( n=0; n<lattice_NumNodes; n++) */ if( subs==0) { // Compute the solid density term for fluid component. ftemp = lattice->pdf[subs][0].ftemp; bc_type = &( lattice->bc[subs][0].bc_type); for( n=0; n<lattice->NumNodes; n++, ftemp+=18, bc_type++) { i = n%ni; j = n/ni; jp = ( j<nj-1)?( j+1):( 0 ); jn = ( j>0 )?( j-1):( nj-1); ip = ( i<ni-1)?( i+1):( 0 ); in = ( i>0 )?( i-1):( ni-1); if( !( *bc_type & BC_SOLID_NODE)) { if( lattice->param.ns >= 0.) { ns = lattice->param.ns; /* 0 */ ftemp++; /* 1 */ *ftemp++ = ns*( lattice->pdf[subs][ j *ni + ip].f[3] - lattice->pdf[subs][ j *ni + i ].f[1]); /* 2 */ *ftemp++ = ns*( lattice->pdf[subs][ jp*ni + i ].f[4] - lattice->pdf[subs][ j *ni + i ].f[2]); /* 3 */ *ftemp++ = ns*( lattice->pdf[subs][ j *ni + in].f[1] - lattice->pdf[subs][ j *ni + i ].f[3]); /* 4 */ *ftemp++ = ns*( lattice->pdf[subs][ jn*ni + i ].f[2] - lattice->pdf[subs][ j *ni + i ].f[4]); /* 5 */ *ftemp++ = ns*( lattice->pdf[subs][ jp*ni + ip].f[7] - lattice->pdf[subs][ j *ni + i ].f[5]); /* 6 */ *ftemp++ = ns*( lattice->pdf[subs][ jp*ni + in].f[8] - lattice->pdf[subs][ j *ni + i ].f[6]); /* 7 */ *ftemp++ = ns*( lattice->pdf[subs][ jn*ni + in].f[5] - lattice->pdf[subs][ j *ni + i ].f[7]); /* 8 */ *ftemp++ = ns*( lattice->pdf[subs][ jn*ni + ip].f[6] - lattice->pdf[subs][ j *ni + i ].f[8]); } else { // TODO: Variable solid density. } } /* if( !( *bc_type++ & BC_SOLID_NODE)) */ else { ftemp+=9; } } /* for( n=0; n<lattice_NumNodes; n++) */ f = lattice->pdf[subs][0].f; bc_type = &( lattice->bc[subs][0].bc_type); for( n=0; n<lattice->NumNodes; n++, f+=18, bc_type++) { if( !( *bc_type & BC_SOLID_NODE)) { f++; for( a=1; a<9; a++, f++) { *f += *(f+9); } /* for( a=1; a<9; a++) */ } else { f+=9; } } /* for( n=0; n<lattice->NumNodes; n++, f+=18) */ } /* if( subs==0) */ //dump_pdf( lattice, 999); } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("collide() -- Bye!\n"); #endif /* SAY_HI */ } /* void collide( lattice_ptr lattice) */ #else /* !( POROUS_MEDIA) */ void collide( lattice_ptr lattice) { double *feq; double *f; double *ftemp; #if ZHANG_AND_CHEN_ENERGY_TRANSPORT double *force; #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ double omega; int bc_type; int n, a; int subs; #if SAY_HI printf("collide() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { for( n=0; n<lattice->NumNodes; n++) { feq = lattice->pdf[subs][n].feq; f = lattice->pdf[subs][n].f; ftemp = lattice->pdf[subs][n].ftemp; bc_type = lattice->bc[subs][n].bc_type; #if ZHANG_AND_CHEN_ENERGY_TRANSPORT force = lattice->force[subs][n].force; #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ if( !( bc_type & BC_SOLID_NODE)) { // C O L L I D E // f = ftemp - (1/tau[subs])( ftemp - feq) for( a=0; a<=8; a++) { #if 1 f[a] = ftemp[a] - ( ( ftemp[a] / lattice->param.tau[subs] ) - ( feq[a] / lattice->param.tau[subs] ) ); #else f[a] = ftemp[a] - ( ( ftemp[a] ) - ( feq[a] ) ) / lattice->param.tau[subs]; #endif } /* for( a=0; a<=8; a++) */ #if ZHANG_AND_CHEN_ENERGY_TRANSPORT if( subs==0) { // // Add the body force term, equation (8), // // f_i = f_i + \Delta f_i // // = f_i + \frac{w_i}{T_0} c_i \dot F // // Assuming the weights, w_i, are the ones from compute_feq. // // Zhang & Chen state T_0 to be 1/3 for D3Q19. The same in D2Q9. // f[1] += .00032*(vx[1]*3.*2.*force[0]); f[2] += .00032*(vy[2]*3.*2.*force[1]); f[3] += .00032*(vx[3]*3.*2.*force[0]); f[4] += .00032*(vy[4]*3.*2.*force[1]); f[5] += .00032*( 3.*( vx[5]*force[0] + vy[5]*force[1])); f[6] += .00032*( 3.*( vx[6]*force[0] + vy[6]*force[1])); f[7] += .00032*( 3.*( vx[7]*force[0] + vy[7]*force[1])); f[8] += .00032*( 3.*( vx[8]*force[0] + vy[8]*force[1])); } #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ #if PUKE_NEGATIVE_DENSITIES for( a=0; a<=8; a++) { if( *f < 0.) { printf("\n"); printf( "collide() -- Node %d (%d,%d), subs %d, " "has negative density %20.17f " "in direction %d " "at timestep %d. Exiting!\n", n, n%lattice->param.LX, n/lattice->param.LX, subs, f[a], a, lattice->time ); printf("\n"); process_exit(1); } } /* for( a=0; a<=8; a++) */ #endif /* PUKE_NEGATIVE_DENSITIES */ } /* if( !( bc_type & BC_SOLID_NODE)) */ else // bc_type & BC_SOLID_NODE { // B O U N C E B A C K if( lattice->param.bc_slip_north && n >= lattice->NumNodes - lattice->param.LX) { // Slip condition on north boundary. /* // A B C // \|/ \|/ // D-o-E --> D-o-E // /|\ /|\ // A B C */ f[1] = ftemp[1]; f[2] = ftemp[4]; f[3] = ftemp[3]; f[4] = ftemp[2]; f[5] = ftemp[8]; f[6] = ftemp[7]; f[7] = ftemp[6]; f[8] = ftemp[5]; } /* if( lattice->param.bc_slip_north && ... ) */ else { if( subs==0) { // Usual non-slip bounce-back condition. /* // A B C H G F // \|/ \|/ // D-o-E --> E-o-D // /|\ /|\ // F G H C B A */ f[1] = ftemp[3]; f[2] = ftemp[4]; f[3] = ftemp[1]; f[4] = ftemp[2]; f[5] = ftemp[7]; f[6] = ftemp[8]; f[7] = ftemp[5]; f[8] = ftemp[6]; } /* if( subs==0) */ #if NUM_FLUID_COMPONENTS==2 else // subs==1 { #if INAMURO_SIGMA_COMPONENT if( lattice->param.bc_sigma_slip) { // // Slip BC for solute on side walls. // Will this make a difference on Taylor dispersion? // if( lattice->FlowDir == /*Vertical*/2) { if( /*west*/(n )%lattice->param.LX == 0 || /*east*/(n+1)%lattice->param.LX == 0) { // Slip condition on east/west boundary. /* // A B C C B A // \|/ \|/ // D-o-E --> E-o-D // /|\ /|\ // F G H H G F */ f[1] = ftemp[3]; f[2] = ftemp[2]; f[3] = ftemp[1]; f[4] = ftemp[4]; f[5] = ftemp[6]; f[6] = ftemp[5]; f[7] = ftemp[8]; f[8] = ftemp[7]; } } else if( lattice->FlowDir == /*Horizontal*/1) { if( /*north*/ n >= lattice->NumNodes - lattice->param.LX || /*south*/ n < lattice->param.LX ) { // Slip condition on north/south boundary. /* // A B C F G H // \|/ \|/ // D-o-E --> D-o-E // /|\ /|\ // F G H A B C */ f[1] = ftemp[1]; f[2] = ftemp[4]; f[3] = ftemp[3]; f[4] = ftemp[2]; f[5] = ftemp[8]; f[6] = ftemp[7]; f[7] = ftemp[6]; f[8] = ftemp[5]; } else { // ERROR: Solid exists somewhere other than as side walls. printf("%s (%d) >> " "ERROR: " "bc_sigma_slip is on. " "FlowDir is determined to be horizontal. " "Encountered solid node somewhere other than side walls. " "That situation is not supported. " "Exiting!", __FILE__, __LINE__); process_exit(1); } } else { printf("%s (%d) >> " "FlowDir is indeterminate. " "Cannot apply slip BC (bc_sigma_slip). " "Exiting!", __FILE__, __LINE__); process_exit(1); } } /* if( lattice->param.bc_sigma_slip) */ else { #endif /* INAMURO_SIGMA_COMPONENT */ // Usual non-slip bounce-back condition. /* // A B C H G F // \|/ \|/ // D-o-E --> E-o-D // /|\ /|\ // F G H C B A */ f[1] = ftemp[3]; f[2] = ftemp[4]; f[3] = ftemp[1]; f[4] = ftemp[2]; f[5] = ftemp[7]; f[6] = ftemp[8]; f[7] = ftemp[5]; f[8] = ftemp[6]; #if INAMURO_SIGMA_COMPONENT } /* if( lattice->param.bc_sigma_slip) else */ #endif /* INAMURO_SIGMA_COMPONENT */ } /* if( subs==0) else*/ #endif /* NUM_FLUID_COMPONENTS==2 */ } /* if( lattice->param.bc_slip_north && ... ) else */ } /* if( !( bc_type & BC_SOLID_NODE)) else */ } /* for( n=0; n<lattice_NumNodes; n++) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("collide() -- Bye!\n"); #endif /* SAY_HI */ } /* void collide( lattice_ptr lattice) */ #endif /* POROUS_MEDIA */
111pjb-one
src/collide_bak02032005.c
C
gpl3
13,873
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // flags.h // // - Preprocessor flags for lb2d_prime. // #ifndef FLAGS_H #define FLAGS_H // Set VERBOSITY_LEVEL to correspond to how deep into nested loops to // print debug and related output. Stuff will be printed down to // loops nested VERBOSITY_LEVEL-1 deep. For example, // // VERBOSITY_LEVEL 0 ==> Nothing is printed, even outside of loops. // VERBOSITY_LEVEL 1 ==> Only stuff outside of loops is printed. // VERBOSITY_LEVEL 2 ==> Stuff inside the first level of loops is printed. // VERBOSITY_LEVEL 3 ==> Stuff inside the second level of loops is printed. // // Flag: VERBOSITY_LEVEL #define VERBOSITY_LEVEL 1 // If SAY_HI is on, some routines will display "hi" and "bye" messages // to stdout. // Flag: SAY_HI #define SAY_HI 0 // NUM_FLUID_COMPONENTS specifies the number of fluid components. // Flag: NUM_FLUID_COMPONENTS #define NUM_FLUID_COMPONENTS 1 // If NUM_FLUID_COMPONENTS is 2, the second component can be the sigma // component for solute (or thermal) transport as in Inamuro & Yoshino // by turning on INAMURO_SIGMA_COMPONENT . // Flag: INAMURO_SIGMA_COMPONENT #define INAMURO_SIGMA_COMPONENT ( 1 && NUM_FLUID_COMPONENTS==2) // Toggle Zhang & Chen energy transport method, PRE 67, 0066711 (2003). // Supposed to give thermodynamic consistency unlike old Shan & Chen method. // And supports general equation of state P = P(rho,T). // Utilizes the Inamuro component for evolution of the energy transport // equation. Employs modified compute_phase_force routine to compute // body force term representing non-local interaction potential U among // particles. // Flag: ZHANG_AND_CHEN_ENERGY_TRANSPORT #define ZHANG_AND_CHEN_ENERGY_TRANSPORT ( 0 && (INAMURO_SIGMA_COMPONENT)) // Simulate POROUS_MEDIA via a solid density parameter // as proposed by Dardis and McCloskey, // Phys Rev E, 57, 4, 4834-4837, 1998 // Flag: POROUS_MEDIA #define POROUS_MEDIA 0 // Simulate porous media as a body force. #define FREED_POROUS_MEDIA 0 // Toggle Tau & Zhang anisotropic dispersion. #define TAU_ZHANG_ANISOTROPIC_DISPERSION ( 1 \ && INAMURO_SIGMA_COMPONENT \ && POROUS_MEDIA ) // Guo, Zheng & Shi: PRE 65 2002, Body force #define GUO_ZHENG_SHI_BODY_FORCE 0 // Body force macros #if GUO_ZHENG_SHI_BODY_FORCE #if INAMURO_SIGMA_COMPONENT #define F(dir_,rho_,conc_) \ ( lattice->param.gval[0][(dir_)] \ /*+ lattice->param.gval[subs][(dir_)] */\ /* *(rho_) */\ *( 1. + get_buoyancy(lattice) \ *( get_beta(lattice)) \ *( (conc_) - get_C0(lattice))) \ ) #else #define F(dir_) lattice->param.gval[subs][(dir_)] #endif #else #if INAMURO_SIGMA_COMPONENT #define F(dir_,rho_,conc_) \ ( lattice->param.gval[0][(dir_)] \ /*+ lattice->param.gval[1][(dir_)] */\ /* *(rho_) */\ *( 1. + ( get_buoyancy(lattice)) \ *( get_beta(lattice)) \ *( (conc_) - get_C0(lattice))) ) #else #define F(dir_,rho_) \ lattice->param.gval[subs][(dir_)] \ *((lattice->param.incompressible)?(rho_):(1.)) #endif #endif // When there are two (or more) fluid components, a single velocity is // sometimes (always?) used to compute the equilibrium distribution // function. This single velocity will be called upr, and the // STORE_U_COMPOSITE flag will toggle its use. // Flag: STORE_U_COMPOSITE #define STORE_U_COMPOSITE ( 1 && ( (NUM_FLUID_COMPONENTS)==2 \ &&!((INAMURO_SIGMA_COMPONENT)))) // If DO_NOT_STORE_SOLIDS is on, then only the nodes necessary to flow are // stored. In this case, extra storage is needed for geometry information // (e.g. node neighbors). If the ratio of fluid nodes to solid nodes is // small (<~.7), this results in lower storage requirements. // Flag: DO_NOT_STORE_SOLIDS #define DO_NOT_STORE_SOLIDS 0 // If COMPUTE_ON_SOLIDS is on, macroscopic variables and feq will be computed // on solid nodes, even though they are not conceptually meaningful there. // This can be helpful for debugging purposes. #define COMPUTE_ON_SOLIDS 1 // NON_LOCAL_FORCES toggles any mechanisms for computing and storing // non-local (interaction) forces. // Flag: NON_LOCAL_FORCES #define NON_LOCAL_FORCES ( 0 && !(INAMURO_SIGMA_COMPONENT&&!ZHANG_AND_CHEN_ENERGY_TRANSPORT)) // The phase force weighting factors: // WM = weights in the direction of major axes // WD = weights in the direction of diagonals // According to Raskinmaki, it should be WM=2 and WD=1. // According to Chen (via correspondence) it should be WM=4 and WD=1. // According to Sukop and Thorne, it should be WM=1/9 and WD=1/36. // The corresonding G values (a.k.a. G, as in params.in) for the usual // equation of state that we like are -5, -10/3, and -120, respectively. // Flag: WM #define WM (1./ 9.) // Flag: WD #define WD (1./36.) #define Q 9 // Toggle manage_body_force call at beginning of time loop for // gradually increasing/decreasing gravity. // Flag: MANAGE_BODY_FORCE #define MANAGE_BODY_FORCE 0 // Toggle break through curve (BTC) mechanism for sigma component. // Flag: STORE_BTC #define STORE_BTC ( 1 && INAMURO_SIGMA_COMPONENT) // // Toggle DETERMINE_FLOW_DIRECTION to attempt to determine the direction of // flow. // // Assigns FlowDir = { 0, 1, 2} = { indeterminate, vertical, horizontal} // // NOTE: This determination informs the breakthrough curve mechanism which // should be used in a simple situation with either pressure/velocity // boundaries driving the flow in one direction or gravity driving the flow // in one direction. If the direction of flow cannot be determined, FlowDir // will be set to indeterminate (=0) and a BTC will not be stored. // // NOTE: This determination also informs the sigma slip boundary which // should only be used in the simple situation of flow through a channel // where the geometry is trivial and the direction of flow is obvious. // // Flag: DETERMINE_FLOW_DIRECTION #define DETERMINE_FLOW_DIRECTION 1 // Toggle mechanism to initialize domain with ux_in or uy_in. This is // useful for setting a velocity in a periodic domain without using // fluid boundary conditions. // Flag: INITIALIZE_WITH_UX_IN #define INITIALIZE_WITH_UX_IN 0 // Flag: INITIALIZE_WITH_UY_IN #define INITIALIZE_WITH_UY_IN 0 // Dumping the density and velocity data to files can be time consuming and // take up a lot of disk space. If all that is needed is the BMP files, then // turn WRITE_MACRO_VAR_DAT_FILES off to save time and space. // Flag: WRITE_MACRO_VAR_DAT_FILES #define WRITE_MACRO_VAR_DAT_FILES 1 // Usually the density and velocity are written only for the active nodes // and in a way designed for post-processing. Additional files with the // variables written in a readable grid of all lattice nodes will be // generated when WRITE_RHO_AND_U_TO_TXT is on. This is done in an // inefficient way and is intended only for debugging purposes on tiny // lattices. Note that if WRITE_MACRO_VAR_DAT_FILES is off, this flag // has no effect. // Flag: WRITE_RHO_AND_U_TO_TXT #define WRITE_RHO_AND_U_TO_TXT 0 // WRITE_PDF_DAT_FILES is analogous to WRITE_MACRO_VAR_DAT_FILES. // Flag: WRITE_PDF_DAT_FILES #define WRITE_PDF_DAT_FILES 0 // WRITE_PDF_TO_TXT is analogous to WRITE_RHO_AND_U_TO_TXT. // Flag: WRITE_PDF_TO_TXT #define WRITE_PDF_TO_TXT 0 // Value used to represent an INACTIVE_NODE . This is used in the list // of neighbors ( struct node_struct::nn). It is also used in the // map from (i,j) space onto n index space in rho2bmp() and u2bmp(). // Flag: INACTIVE_NODE #define INACTIVE_NODE -1 // Negative densities (f_a) generally signify impending doom. The code // will die "gracefully" when this happens if PUKE_NEGATIVE_DENSITIES is on. // Might want to turn this off to boost performance on big, long runs that // are expected to survive without such instabilities. // Flag: PUKE_NEGATIVE_DENSITIES #define PUKE_NEGATIVE_DENSITIES 0 // Turn one of these on for coloring of the solids in bmp files. // Flag: SOLID_COLOR_IS_CHECKERBOARD #define SOLID_COLOR_IS_CHECKERBOARD 0 // Flag: SOLID_COLOR_IS_BLACK #define SOLID_COLOR_IS_BLACK 1 // Flag: DELAY #define DELAY 0 // Flag: END_GRAV #define END_GRAV 2000 // A single white pixel will be placed in at the (0,0) lattice node if // MARK_ORIGIN_FOR_REFERENCE is turned on. This is good for assisting with the // problem of tracking orientation of the results between regimes (e.g. C, BMP, // Matlab...). // Flag: MARK_ORIGIN_FOR_REFERENCE #define MARK_ORIGIN_FOR_REFERENCE 0 // Flag: PERTURBATIONS #define PERTURBATIONS 0 // If WRITE_CHEN_DAT_FILES is on, the code will output old style chen_*.dat // files to be processed by the old lb_rho_v*.m matlab scripts. // Flag: WRITE_CHEN_DAT_FILES #define WRITE_CHEN_DAT_FILES 0 // NEW_PARAMS_INPUT_ROUTINE is a temporary flag to switch between the old // params input routine and the new one under development. When the new // one is ready, it should be used exclusively. #define NEW_PARAMS_INPUT_ROUTINE 1 #endif /* FLAGS_H */
111pjb-one
src/flags_poiseuille_gravity_y.h
C
gpl3
9,094
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // flags.h // // - Preprocessor flags for lb2d_prime. // // Set VERBOSITY_LEVEL to correspond to how deep into nested loops to // print debug and related output. Stuff will be printed down to // loops nested VERBOSITY_LEVEL-1 deep. For example, // // VERBOSITY_LEVEL 0 ==> Nothing is printed, even outside of loops. // VERBOSITY_LEVEL 1 ==> Only stuff outside of loops is printed. // VERBOSITY_LEVEL 2 ==> Stuff inside the first level of loops is printed. // VERBOSITY_LEVEL 3 ==> Stuff inside the second level of loops is printed. // #define VERBOSITY_LEVEL 1 // If SAY_HI is on, some routines will display "hi" and "bye" messages // to stdout. #define SAY_HI 0 // NUM_FLUID_COMPONENTS specifies the number of fluid components. #define NUM_FLUID_COMPONENTS 2 // If NUM_FLUID_COMPONENTS is 2, the second component can be the sigma // component for solute (or thermal) transport as in Inamuro & Yoshino // by turning on INAMURO_SIGMA_COMPONENT . #define INAMURO_SIGMA_COMPONENT 0 // Simulate POROUS_MEDIA via a solid density parameter // as proposed by Dardis and McCloskey, // Phys Rev E, 57, 4, 4834-4837, 1998 #define POROUS_MEDIA 0 // When there are two (or more) fluid components, a single velocity is // sometimes (always?) used to compute the equilibrium distribution // function. This single velocity will be called upr, and the // STORE_U_COMPOSITE flag will toggle its use. #define STORE_U_COMPOSITE 1 && NUM_FLUID_COMPONENTS==2 && !INAMURO_SIGMA_COMPONENT // If DO_NOT_STORE_SOLIDS is on, then only the nodes necessary to flow are // stored. In this case, extra storage is needed for geometry information // (e.g. node neighbors). If the ratio of fluid nodes to solid nodes is // small (<~.7), this results in lower storage requirements. #define DO_NOT_STORE_SOLIDS 0 // NON_LOCAL_FORCES toggles any mechanisms for computing and storing // non-local (interaction) forces. #define NON_LOCAL_FORCES 1 // BC_XXX flags are for boundary conditions. // Used to set struct bc_struct::bc_type. // Should be powers of two so that multiple boundary types can be // checked easily via bitwise and (&). // For instance, bc_type & BC_SOLID_NODE & BC_CONSTANT_CONCENTRATION. #define BC_SOLID_NODE 0x00000001 #define BC_FLUID_NODE 0x00000000 #define BC_FILM_NODE 0x40000000 #define BC_PRESSURE_N_IN 0x00000010 #define BC_PRESSURE_S_IN 0x00000020 #define BC_PRESSURE_E_IN 0x00000040 #define BC_PRESSURE_W_IN 0x00000080 #define BC_PRESSURE_N_OUT 0x00000100 #define BC_PRESSURE_S_OUT 0x00000200 #define BC_PRESSURE_E_OUT 0x00000400 #define BC_PRESSURE_W_OUT 0x00000800 #define BC_VELOCITY_N_IN 0x00001000 #define BC_VELOCITY_S_IN 0x00002000 #define BC_VELOCITY_E_IN 0x00004000 #define BC_VELOCITY_W_IN 0x00008000 #define BC_VELOCITY_N_OUT 0x00010000 #define BC_VELOCITY_S_OUT 0x00020000 #define BC_VELOCITY_E_OUT 0x00040000 #define BC_VELOCITY_W_OUT 0x00080000 // Dumping the density and velocity data to files can be time consuming and // take up a lot of disk space. If all that is needed is the BMP files, then // turn WRITE_MACRO_VAR_DAT_FILES off to save time and space. #define WRITE_MACRO_VAR_DAT_FILES 1 // Usually the density and velocity are written only for the active nodes // and in a way designed for post-processing. Additional files with the // variables written in a readable grid of all lattice nodes will be // generated when WRITE_RHO_AND_U_TO_TXT is on. This is done in an // inefficient way and is intended only for debugging purposes on tiny // lattices. Note that if WRITE_MACRO_VAR_DAT_FILES is off, this flag // has no effect. #define WRITE_RHO_AND_U_TO_TXT 0 // WRITE_PDF_DAT_FILES is analogous to WRITE_MACRO_VAR_DAT_FILES. #define WRITE_PDF_DAT_FILES 0 // WRITE_PDF_TO_TXT is analogous to WRITE_RHO_AND_U_TO_TXT. #define WRITE_PDF_TO_TXT 0 // Value used to represent an INACTIVE_NODE . This is used in the list // of neighbors ( struct node_struct::nn). It is also used in the // map from (i,j) space onto n index space in rho2bmp() and u2bmp(). #define INACTIVE_NODE -1 // Negative densities (f_a) generally signify impending doom. The code // will die "gracefully" when this happens if PUKE_NEGATIVE_DENSITIES is on. // Might want to turn this off to boost performance on big, long runs that // are expected to survive without such instabilities. #define PUKE_NEGATIVE_DENSITIES 0 // Turn one of these on for coloring of the solids in bmp files. #define SOLID_COLOR_IS_CHECKERBOARD 0 #define SOLID_COLOR_IS_BLACK 1 #define DELAY 0 #define END_GRAV 2000 // A single white pixel will be placed in at the (0,0) lattice node if // MARK_ORIGIN_FOR_REFERENCE is turned on. This is good for assisting with the // problem of tracking orientation of the results between regimes (e.g. C, BMP, // Matlab...). #define MARK_ORIGIN_FOR_REFERENCE 0 #define PERTURBATIONS 0 // If WRITE_CHEN_DAT_FILES is on, the code will output old style chen_*.dat // files to be processed by the old lb_rho_v*.m matlab scripts. #define WRITE_CHEN_DAT_FILES 0 // IC_* flags are for initial conditions. Used in switch statement in // init_problem() in latmat.c . Set the initial_condition parameter // in params.in . #define IC_UNIFORM_RHO_A 1 #define IC_UNIFORM_RHO_IN 2 #define IC_BUBBLE 3 #define IC_YIN_YANG 4 #define IC_DIAGONAL 5 #define IC_2X2_CHECKERS 6 #define IC_STATIC 7 #define IC_RECTANGLE 8 #define IC_DOT 9 #define IC_WOLF_GLADROW_DIFFUSION 10
111pjb-one
src/flags_laplace.h
C
gpl3
5,687
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // lb2d_prime.h // // - Header file for lb2d_prime. // #ifndef MCMP_PRIME_H #define MCMP_PRIME_H #include <stdio.h> #include <stdlib.h> //#include <malloc.h> #include <memory.h> #include <assert.h> #include <math.h> #include <string.h> #include <time.h> #ifndef CLK_TCK // Temporary fix for compiling on macbooks... //#define CLK_TCK __DARWIN_CLK_TCK #define CLK_TCK CLOCKS_PER_SEC #endif #define IJ2N(_i_,_j_) (_j_)*get_LX(lattice) + (_i_) // Following for compatibility with process mechanism imported from LB3D. #define XY2N(_i_,_j_,_ni_) (_j_)*(_ni_) + (_i_) #define N2I(_n_) (_n_)%get_LX(lattice) #define N2J(_n_) (_n_)/get_LX(lattice) double vx[9] = { 0., 1., 0.,-1., 0., 1.,-1.,-1., 1.}; double vy[9] = { 0., 0., 1., 0.,-1., 1., 1.,-1.,-1.}; // C E N W S NE NW SW SE #define C 0 #define E 1 #define N 2 #define W 3 #define S 4 #define NE 5 #define NW 6 #define SW 7 #define SE 8 #define EPS .0000000000001 #define PI 3.1415926535 #ifdef PARALLEL #include <mpi.h> #endif /* (PARALLEL) */ #include "flags.h" #include "bc_flags.h" #include "ic_flags.h" #include "forward_declarations.h" #include "process.h" #include "lattice.h" #include "user_stuff.h" //LBMPI #ifdef PARALLEL //LBMPI #include "lbmpi.h" //LBMPI #endif /* PARALLEL */ //LBMPI #ifdef PARALLEL //LBMPI #include "lbmpi.c" //LBMPI #endif /* PARALLEL */ #include "user_stuff.c" #include "params.h" #define HRULE0 "- - - - - - - - - - - - - - - - - - - - " \ "- - - - - - - - - - - - - - - - - - - - " #define HRULE1 "----------------------------------------" \ "----------------------------------------" #define HRULE2 "========================================" \ "========================================" #if DO_NOT_STORE_SOLIDS // TODO: Incorporate version that omits storage of interior solids (which // are not involved in flow). //#include "min_nodes/compute.c" //#include "min_nodes/stream.c" //#include "min_nodes/bcs.c" //#include "min_nodes/collide.c" //#include "min_nodes/lbio.c" //#include "min_nodes/latman.c" #else /* !( DO_NOT_STORE_SOLIDS) */ #include "process.c" #include "compute.c" #include "stream.c" #include "collide.c" #include "bcs.c" #include "lbio.h" #include "lbio.c" #include "latman.c" #include "runman.c" #endif /* DO_NOT_STORE_SOLIDS */ void report_flags( lattice_ptr lattice) { struct report_struct flags; char filename[1024]; sprintf( filename, "%s/flags", get_out_path(lattice)); report_open( &flags, filename); report_integer_entry( &flags, "VERBOSITY_LEVEL", VERBOSITY_LEVEL, ""); report_integer_entry( &flags, "SAY_HI", SAY_HI, ""); report_integer_entry( &flags, "NUM_FLUID_COMPONENTS", NUM_FLUID_COMPONENTS, ""); report_integer_entry( &flags, "INAMURO_SIGMA_COMPONENT", INAMURO_SIGMA_COMPONENT, ""); report_integer_entry( &flags, "ZHANG_AND_CHEN_ENERGY_TRANSPORT", ZHANG_AND_CHEN_ENERGY_TRANSPORT, ""); report_integer_entry( &flags, "POROUS_MEDIA", POROUS_MEDIA, ""); report_integer_entry( &flags, "STORE_U_COMPOSITE", STORE_U_COMPOSITE, ""); report_integer_entry( &flags, "DO_NOT_STORE_SOLIDS", DO_NOT_STORE_SOLIDS, ""); report_integer_entry( &flags, "NON_LOCAL_FORCES", NON_LOCAL_FORCES, ""); report_integer_entry( &flags, "MANAGE_BODY_FORCE", MANAGE_BODY_FORCE, ""); report_integer_entry( &flags, "STORE_BTC", STORE_BTC, ""); report_integer_entry( &flags, "DETERMINE_FLOW_DIRECTION", DETERMINE_FLOW_DIRECTION, ""); report_integer_entry( &flags, "BC_SOLID_NODE", BC_SOLID_NODE, ""); report_integer_entry( &flags, "BC_FLUID_NODE", BC_FLUID_NODE, ""); report_integer_entry( &flags, "BC_SLIP_NODE", BC_SLIP_NODE, ""); report_integer_entry( &flags, "BC_FILM_NODE", BC_FILM_NODE, ""); report_integer_entry( &flags, "BC_PRESSURE_N_IN", BC_PRESSURE_N_IN, ""); report_integer_entry( &flags, "BC_PRESSURE_S_IN", BC_PRESSURE_S_IN, ""); report_integer_entry( &flags, "BC_PRESSURE_E_IN", BC_PRESSURE_E_IN, ""); report_integer_entry( &flags, "BC_PRESSURE_W_IN", BC_PRESSURE_W_IN, ""); report_integer_entry( &flags, "BC_PRESSURE_N_OUT", BC_PRESSURE_N_OUT, ""); report_integer_entry( &flags, "BC_PRESSURE_S_OUT", BC_PRESSURE_S_OUT, ""); report_integer_entry( &flags, "BC_PRESSURE_E_OUT", BC_PRESSURE_E_OUT, ""); report_integer_entry( &flags, "BC_PRESSURE_W_OUT", BC_PRESSURE_W_OUT, ""); report_integer_entry( &flags, "BC_VELOCITY_N_IN", BC_VELOCITY_N_IN, ""); report_integer_entry( &flags, "BC_VELOCITY_S_IN", BC_VELOCITY_S_IN, ""); report_integer_entry( &flags, "BC_VELOCITY_E_IN", BC_VELOCITY_E_IN, ""); report_integer_entry( &flags, "BC_VELOCITY_W_IN", BC_VELOCITY_W_IN, ""); report_integer_entry( &flags, "BC_VELOCITY_N_OUT", BC_VELOCITY_N_OUT, ""); report_integer_entry( &flags, "BC_VELOCITY_S_OUT", BC_VELOCITY_S_OUT, ""); report_integer_entry( &flags, "BC_VELOCITY_E_OUT", BC_VELOCITY_E_OUT, ""); report_integer_entry( &flags, "BC_VELOCITY_W_OUT", BC_VELOCITY_W_OUT, ""); report_integer_entry( &flags, "WRITE_MACRO_VAR_DAT_FILES", WRITE_MACRO_VAR_DAT_FILES, ""); report_integer_entry( &flags, "WRITE_RHO_AND_U_TO_TXT", WRITE_RHO_AND_U_TO_TXT, ""); report_integer_entry( &flags, "WRITE_PDF_DAT_FILES", WRITE_PDF_DAT_FILES, ""); report_integer_entry( &flags, "WRITE_PDF_TO_TXT", WRITE_PDF_TO_TXT, ""); report_integer_entry( &flags, "INACTIVE_NODE", INACTIVE_NODE, ""); report_integer_entry( &flags, "PUKE_NEGATIVE_DENSITIES", PUKE_NEGATIVE_DENSITIES, ""); report_integer_entry( &flags, "SOLID_COLOR_IS_CHECKERBOARD", SOLID_COLOR_IS_CHECKERBOARD, ""); report_integer_entry( &flags, "SOLID_COLOR_IS_BLACK", SOLID_COLOR_IS_BLACK, ""); report_integer_entry( &flags, "DELAY", DELAY, ""); report_integer_entry( &flags, "END_GRAV", END_GRAV, ""); report_integer_entry( &flags, "MARK_ORIGIN_FOR_REFERENCE", MARK_ORIGIN_FOR_REFERENCE, ""); report_integer_entry( &flags, "PERTURBATIONS", PERTURBATIONS, ""); report_integer_entry( &flags, "WRITE_CHEN_DAT_FILES", WRITE_CHEN_DAT_FILES, ""); report_integer_entry( &flags, "IC_UNIFORM_RHO_A", IC_UNIFORM_RHO_A, ""); report_integer_entry( &flags, "IC_UNIFORM_RHO_B", IC_UNIFORM_RHO_B, ""); report_integer_entry( &flags, "IC_UNIFORM_RHO_IN", IC_UNIFORM_RHO_IN, ""); report_integer_entry( &flags, "IC_BUBBLE", IC_BUBBLE, ""); report_integer_entry( &flags, "IC_DIAGONAL", IC_DIAGONAL, ""); report_integer_entry( &flags, "IC_2X2_CHECKERS", IC_2X2_CHECKERS, ""); report_integer_entry( &flags, "IC_STATIC", IC_STATIC, ""); report_integer_entry( &flags, "IC_RECTANGLE", IC_RECTANGLE, ""); report_integer_entry( &flags, "IC_DOT", IC_DOT, ""); report_integer_entry( &flags, "IC_WOLF_GLADROW_DIFFUSION", IC_WOLF_GLADROW_DIFFUSION, ""); report_integer_entry( &flags, "IC_YIN_YANG", IC_YIN_YANG, ""); report_integer_entry( &flags, "IC_HYDROSTATIC", IC_HYDROSTATIC, ""); report_close( &flags); } #endif /* MCMP_PRIME_H */
111pjb-one
src/lb2d_prime.h
C
gpl3
7,022
#ifndef FLAGS_H #define FLAGS_H //############################################################################## // // flags.h // // - Preprocessor flags for lb2d_prime. // // Set VERBOSITY_LEVEL to correspond to how deep into nested loops to // print debug and related output. Stuff will be printed down to // loops nested VERBOSITY_LEVEL-1 deep. For example, // // VERBOSITY_LEVEL 0 ==> Nothing is printed, even outside of loops. // VERBOSITY_LEVEL 1 ==> Only stuff outside of loops is printed. // VERBOSITY_LEVEL 2 ==> Stuff inside the first level of loops is printed. // VERBOSITY_LEVEL 3 ==> Stuff inside the second level of loops is printed. // // Flag: VERBOSITY_LEVEL #define VERBOSITY_LEVEL 1 // If SAY_HI is on, some routines will display "hi" and "bye" messages // to stdout. // Flag: SAY_HI #define SAY_HI 0 // NUM_FLUID_COMPONENTS specifies the number of fluid components. // Flag: NUM_FLUID_COMPONENTS #define NUM_FLUID_COMPONENTS 1 // If NUM_FLUID_COMPONENTS is 2, the second component can be the sigma // component for solute (or thermal) transport as in Inamuro & Yoshino // by turning on INAMURO_SIGMA_COMPONENT . // Flag: INAMURO_SIGMA_COMPONENT #define INAMURO_SIGMA_COMPONENT ( 0 && NUM_FLUID_COMPONENTS==2) // Toggle Zhang & Chen energy transport method, PRE 67, 0066711 (2003). // Supposed to give thermodynamic consistency unlike old Shan & Chen method. // And supports general equation of state P = P(rho,T). // Utilizes the Inamuro component for evolution of the energy transport // equation. Employs modified compute_phase_force routine to compute // body force term representing non-local interaction potential U among // particles. // Flag: ZHANG_AND_CHEN_ENERGY_TRANSPORT #define ZHANG_AND_CHEN_ENERGY_TRANSPORT ( 0 && (INAMURO_SIGMA_COMPONENT)) // Simulate POROUS_MEDIA via a solid density parameter // as proposed by Dardis and McCloskey, // Phys Rev E, 57, 4, 4834-4837, 1998 // Flag: POROUS_MEDIA #define POROUS_MEDIA 0 // When there are two (or more) fluid components, a single velocity is // sometimes (always?) used to compute the equilibrium distribution // function. This single velocity will be called upr, and the // STORE_U_COMPOSITE flag will toggle its use. // Flag: STORE_U_COMPOSITE #define STORE_U_COMPOSITE ( 1 && ( (NUM_FLUID_COMPONENTS)==2 \ &&!((INAMURO_SIGMA_COMPONENT)))) // If DO_NOT_STORE_SOLIDS is on, then only the nodes necessary to flow are // stored. In this case, extra storage is needed for geometry information // (e.g. node neighbors). If the ratio of fluid nodes to solid nodes is // small (<~.7), this results in lower storage requirements. // Flag: DO_NOT_STORE_SOLIDS #define DO_NOT_STORE_SOLIDS 0 // If COMPUTE_ON_SOLIDS is on, macroscopic variables and feq will be computed // on solid nodes, even though they are not conceptually meaningful there. // This can be helpful for debugging purposes. #define COMPUTE_ON_SOLIDS 1 // NON_LOCAL_FORCES toggles any mechanisms for computing and storing // non-local (interaction) forces. // Flag: NON_LOCAL_FORCES #define NON_LOCAL_FORCES ( 1 && !(INAMURO_SIGMA_COMPONENT&&!ZHANG_AND_CHEN_ENERGY_TRANSPORT)) // The phase force weighting factors: // WM = weights in the direction of major axes // WD = weights in the direction of diagonals // According to Raskinmaki, it should be WM=2 and WD=1. // According to Chen (via correspondence) it should be WM=4 and WD=1. // According to Sukop and Thorne, it should be WM=1/9 and WD=1/36. // The corresonding G values (a.k.a. G, as in params.in) for the usual // equation of state that we like are -5, -10/3, and -120, respectively. // Flag: WM #define WM (1./ 9.) // Flag: WD #define WD (1./36.) // Toggle manage_body_force call at beginning of time loop for // gradually increasing/decreasing gravity. // Flag: MANAGE_BODY_FORCE #define MANAGE_BODY_FORCE 0 // Toggle break through curve (BTC) mechanism for sigma component. // Flag: STORE_BTC #define STORE_BTC ( 1 && INAMURO_SIGMA_COMPONENT) // // Toggle DETERMINE_FLOW_DIRECTION to attempt to determine the direction of // flow. // // Assigns FlowDir = { 0, 1, 2} = { indeterminate, vertical, horizontal} // // NOTE: This determination informs the breakthrough curve mechanism which // should be used in a simple situation with either pressure/velocity // boundaries driving the flow in one direction or gravity driving the flow // in one direction. If the direction of flow cannot be determined, FlowDir // will be set to indeterminate (=0) and a BTC will not be stored. // // NOTE: This determination also informs the sigma slip boundary which // should only be used in the simple situation of flow through a channel // where the geometry is trivial and the direction of flow is obvious. // // Flag: DETERMINE_FLOW_DIRECTION #define DETERMINE_FLOW_DIRECTION 0 // Toggle mechanism to initialize domain with ux_in or uy_in. This is // useful for setting a velocity in a periodic domain without using // fluid boundary conditions. // Flag: INITIALIZE_WITH_UX_IN #define INITIALIZE_WITH_UX_IN 0 // Flag: INITIALIZE_WITH_UY_IN #define INITIALIZE_WITH_UY_IN 0 // Dumping the density and velocity data to files can be time consuming and // take up a lot of disk space. If all that is needed is the BMP files, then // turn WRITE_MACRO_VAR_DAT_FILES off to save time and space. // Flag: WRITE_MACRO_VAR_DAT_FILES #define WRITE_MACRO_VAR_DAT_FILES 1 // Usually the density and velocity are written only for the active nodes // and in a way designed for post-processing. Additional files with the // variables written in a readable grid of all lattice nodes will be // generated when WRITE_RHO_AND_U_TO_TXT is on. This is done in an // inefficient way and is intended only for debugging purposes on tiny // lattices. Note that if WRITE_MACRO_VAR_DAT_FILES is off, this flag // has no effect. // Flag: WRITE_RHO_AND_U_TO_TXT #define WRITE_RHO_AND_U_TO_TXT 0 // WRITE_PDF_DAT_FILES is analogous to WRITE_MACRO_VAR_DAT_FILES. // Flag: WRITE_PDF_DAT_FILES #define WRITE_PDF_DAT_FILES 0 // WRITE_PDF_TO_TXT is analogous to WRITE_RHO_AND_U_TO_TXT. // Flag: WRITE_PDF_TO_TXT #define WRITE_PDF_TO_TXT 0 // Value used to represent an INACTIVE_NODE . This is used in the list // of neighbors ( struct node_struct::nn). It is also used in the // map from (i,j) space onto n index space in rho2bmp() and u2bmp(). // Flag: INACTIVE_NODE #define INACTIVE_NODE -1 // Negative densities (f_a) generally signify impending doom. The code // will die "gracefully" when this happens if PUKE_NEGATIVE_DENSITIES is on. // Might want to turn this off to boost performance on big, long runs that // are expected to survive without such instabilities. // Flag: PUKE_NEGATIVE_DENSITIES #define PUKE_NEGATIVE_DENSITIES 0 // Turn one of these on for coloring of the solids in bmp files. // Flag: SOLID_COLOR_IS_CHECKERBOARD #define SOLID_COLOR_IS_CHECKERBOARD 0 // Flag: SOLID_COLOR_IS_BLACK #define SOLID_COLOR_IS_BLACK 1 // Flag: DELAY #define DELAY 0 // Flag: END_GRAV #define END_GRAV 2000 // A single white pixel will be placed in at the (0,0) lattice node if // MARK_ORIGIN_FOR_REFERENCE is turned on. This is good for assisting with the // problem of tracking orientation of the results between regimes (e.g. C, BMP, // Matlab...). // Flag: MARK_ORIGIN_FOR_REFERENCE #define MARK_ORIGIN_FOR_REFERENCE 0 // Flag: PERTURBATIONS #define PERTURBATIONS 0 // If WRITE_CHEN_DAT_FILES is on, the code will output old style chen_*.dat // files to be processed by the old lb_rho_v*.m matlab scripts. // Flag: WRITE_CHEN_DAT_FILES #define WRITE_CHEN_DAT_FILES 0 #endif /* FLAGS_H */
111pjb-one
src/flags_bak20070317.h
C
gpl3
7,644
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // flags.h // // - Preprocessor flags for lb2d_prime. // // Set VERBOSITY_LEVEL to correspond to how deep into nested loops to // print debug and related output. Stuff will be printed down to // loops nested VERBOSITY_LEVEL-1 deep. For example, // // VERBOSITY_LEVEL 0 ==> Nothing is printed, even outside of loops. // VERBOSITY_LEVEL 1 ==> Only stuff outside of loops is printed. // VERBOSITY_LEVEL 2 ==> Stuff inside the first level of loops is printed. // VERBOSITY_LEVEL 3 ==> Stuff inside the second level of loops is printed. // #define VERBOSITY_LEVEL 1 // If SAY_HI is on, some routines will display "hi" and "bye" messages // to stdout. #define SAY_HI 0 // NUM_FLUID_COMPONENTS specifies the number of fluid components. #define NUM_FLUID_COMPONENTS 2 // If NUM_FLUID_COMPONENTS is 2, the second component can be the sigma // component for solute (or thermal) transport as in Inamuro & Yoshino // by turning on INAMURO_SIGMA_COMPONENT . #define INAMURO_SIGMA_COMPONENT 1 // Simulate POROUS_MEDIA via a solid density parameter // as proposed by Dardis and McCloskey, // Phys Rev E, 57, 4, 4834-4837, 1998 #define POROUS_MEDIA 0 // When there are two (or more) fluid components, a single velocity is // sometimes (always?) used to compute the equilibrium distribution // function. This single velocity will be called ueq, and the // STORE_UEQ flag will toggle its use. #define STORE_UEQ 1 && NUM_FLUID_COMPONENTS==2 && !INAMURO_SIGMA_COMPONENT // If DO_NOT_STORE_SOLIDS is on, then only the nodes necessary to flow are // stored. In this case, extra storage is needed for geometry information // (e.g. node neighbors). If the ratio of fluid nodes to solid nodes is // small (<~.7), this results in lower storage requirements. #define DO_NOT_STORE_SOLIDS 0 // NON_LOCAL_FORCES toggles any mechanisms for computing and storing // non-local (interaction) forces. #define NON_LOCAL_FORCES 0 // BC_XXX flags are for boundary conditions. // Used to set struct bc_struct::bc_type. // Should be powers of two so that multiple boundary types can be // checked easily via bitwise and (&). // For instance, bc_type & BC_SOLID_NODE & BC_CONSTANT_CONCENTRATION. #define BC_SOLID_NODE 0x00000001 #define BC_FLUID_NODE 0x00000000 #define BC_FILM_NODE 0x40000000 #define BC_PRESSURE_N_IN 0x00000010 #define BC_PRESSURE_S_IN 0x00000020 #define BC_PRESSURE_E_IN 0x00000040 #define BC_PRESSURE_W_IN 0x00000080 #define BC_PRESSURE_N_OUT 0x00000100 #define BC_PRESSURE_S_OUT 0x00000200 #define BC_PRESSURE_E_OUT 0x00000400 #define BC_PRESSURE_W_OUT 0x00000800 #define BC_VELOCITY_N_IN 0x00001000 #define BC_VELOCITY_S_IN 0x00002000 #define BC_VELOCITY_E_IN 0x00004000 #define BC_VELOCITY_W_IN 0x00008000 #define BC_VELOCITY_N_OUT 0x00010000 #define BC_VELOCITY_S_OUT 0x00020000 #define BC_VELOCITY_E_OUT 0x00040000 #define BC_VELOCITY_W_OUT 0x00080000 // Dumping the density and velocity data to files can be time consuming and // take up a lot of disk space. If all that is needed is the BMP files, then // turn WRITE_MACRO_VAR_DAT_FILES off to save time and space. #define WRITE_MACRO_VAR_DAT_FILES 1 // Usually the density and velocity are written only for the active nodes // and in a way designed for post-processing. Additional files with the // variables written in a readable grid of all lattice nodes will be // generated when WRITE_RHO_AND_U_TO_TXT is on. This is done in an // inefficient way and is intended only for debugging purposes on tiny // lattices. Note that if WRITE_MACRO_VAR_DAT_FILES is off, this flag // has no effect. #define WRITE_RHO_AND_U_TO_TXT 1 // WRITE_PDF_DAT_FILES is analogous to WRITE_MACRO_VAR_DAT_FILES. #define WRITE_PDF_DAT_FILES 0 // WRITE_PDF_TO_TXT is analogous to WRITE_RHO_AND_U_TO_TXT. #define WRITE_PDF_TO_TXT 0 // Value used to represent an INACTIVE_NODE . This is used in the list // of neighbors ( struct node_struct::nn). It is also used in the // map from (i,j) space onto n index space in rho2bmp() and u2bmp(). #define INACTIVE_NODE -1 // Negative densities (f_a) generally signify impending doom. The code // will die "gracefully" when this happens if PUKE_NEGATIVE_DENSITIES is on. // Might want to turn this off to boost performance on big, long runs that // are expected to survive without such instabilities. #define PUKE_NEGATIVE_DENSITIES 0 // Turn one of these on for coloring of the solids in bmp files. #define SOLID_COLOR_IS_CHECKERBOARD 0 #define SOLID_COLOR_IS_BLACK 1 #define DELAY 0 #define END_GRAV 2000 // A single white pixel will be placed in at the (0,0) lattice node if // MARK_ORIGIN_FOR_REFERENCE is turned on. This is good for assisting with the // problem of tracking orientation of the results between regimes (e.g. C, BMP, // Matlab...). #define MARK_ORIGIN_FOR_REFERENCE 0 #define PERTURBATIONS 0 // If WRITE_CHEN_DAT_FILES is on, the code will output old style chen_*.dat // files to be processed by the old lb_rho_v*.m matlab scripts. #define WRITE_CHEN_DAT_FILES 0 // IC_* flags are for initial conditions. Used in switch statement in // init_problem() in latmat.c . Set the initial_condition parameter // in params.in . #define IC_UNIFORM_RHO_A 1 #define IC_UNIFORM_RHO_IN 2 #define IC_BUBBLE 3 #define IC_YIN_YANG 4 #define IC_DIAGONAL 5 #define IC_2X2_CHECKERS 6 #define IC_STATIC 7 #define IC_RECTANGLE 8 #define IC_DOT 9 #define IC_WOLF_GLADROW_DIFFUSION 10
111pjb-one
src/flags_bak09262004.h
C
gpl3
5,671
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // compute.c // // - Routines for computing on the lattice: // // - compute_rho_and_u // - compute_feq // - compute_big_u // - compute_gval // - compute_fluid_fluid_force // - etc... // // P R E P R O C E S S O R M A C R O S #if NON_LOCAL_FORCES #if ZHANG_AND_CHEN_ENERGY_TRANSPORT #define BIG_U_X( u_) \ (u_) \ + lattice->param.tau[subs] \ * lattice->param.gval[subs][0] #define BIG_U_Y( u_) \ (u_) \ + lattice->param.tau[subs] \ * lattice->param.gval[subs][1] #define BIG_U_X_BUOY( u_, rho1_, rho2_) 1. #define BIG_U_Y( u_, rho1_, rho2_) 1. #else /* !( ZHANG_AND_CHEN_ENERGY_TRANSPORT) */ #if NUM_FLUID_COMPONENTS == 2 #define BIG_U_X( u_, rho_) \ (u_) \ + lattice->param.tau[subs] \ * lattice->force[subs][n].force[0]/(rho_) \ + lattice->param.tau[subs] \ * lattice->force[subs][n].sforce[0] \ + lattice->param.tau[subs] \ * lattice->param.gval[subs][0] #define BIG_U_Y( u_, rho_) \ (u_) \ + lattice->param.tau[subs] \ * lattice->force[subs][n].force[1]/(rho_) \ + lattice->param.tau[subs] \ * lattice->force[subs][n].sforce[1] \ + lattice->param.tau[subs] \ * lattice->param.gval[subs][1] #else #define BIG_U_X( u_, rho_) \ (u_) \ + lattice->param.tau[subs] \ * lattice->force[subs][n].force[0]/(rho_) \ + lattice->param.tau[subs] \ * lattice->force[subs][n].sforce[0]/(rho_) \ + lattice->param.tau[subs] \ * lattice->param.gval[subs][0] #define BIG_U_Y( u_, rho_) \ (u_) \ + lattice->param.tau[subs] \ * lattice->force[subs][n].force[1]/(rho_) \ + lattice->param.tau[subs] \ * lattice->force[subs][n].sforce[1]/(rho_) \ + lattice->param.tau[subs] \ * lattice->param.gval[subs][1] #endif /* NUM_FLUID_COMPONENTS == 2 */ #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ #else /* !( NON_LOCAL_FORCES) */ #if INAMURO_SIGMA_COMPONENT #if GUO_ZHENG_SHI_BODY_FORCE #define BIG_U_X( u_, rho1_, rho2_) (u_) + .5*F(0,rho1_,rho2_) #define BIG_U_Y( u_, rho1_, rho2_) (u_) + .5*F(1,rho1_,rho2_) #else #define BIG_U_X( u_, rho1_, rho2_) \ (u_) + get_tau(lattice,subs) * F(0,rho1_,rho2_) #define BIG_U_Y( u_, rho1_, rho2_) \ (u_) + get_tau(lattice,subs) * F(1,rho1_,rho2_) #endif #else /* !( INAMURO_SIGMA_COMPONENT) */ #if GUO_ZHENG_SHI_BODY_FORCE #define BIG_U_X( u_, rho_) (u_) + .5*F(0) #define BIG_U_Y( u_, rho_) (u_) + .5*F(1) #else #define BIG_U_X( u_, rho_) (u_) + get_tau(lattice,subs) * F(0,rho_) #define BIG_U_Y( u_, rho_) (u_) + get_tau(lattice,subs) * F(1,rho_) #endif #endif /* INAMURO_SIGMA_COMPONENT */ #endif /* NON_LOCAL_FORCES */ #if INAMURO_SIGMA_COMPONENT // C O M P U T E _ M A C R O _ V A R S {{{1 void compute_macro_vars( struct lattice_struct *lattice, int which_f) { int n, a; double *rho[ NUM_FLUID_COMPONENTS], *u_x[ NUM_FLUID_COMPONENTS], *u_y[ NUM_FLUID_COMPONENTS]; double *f, *ftemp; bc_ptr bc; int subs; double c; #if TAU_ZHANG_ANISOTROPIC_DISPERSION double Dxx, Dyy, Dxy, Dl, Dt, ns; double factor=0.0, lamdax, lamday; double wt[9]={4./9.,WM,WM,WM,WM,WD,WD,WD,WD}; #endif #if GUO_ZHENG_SHI_BODY_FORCE double conc; // For computing concentration to use in body force. #endif //############################################################################ // // For first component, compute rho and u. // subs=0; rho[subs] = &( lattice->macro_vars[subs][0].rho); u_x[subs] = lattice->macro_vars[subs][0].u; u_y[subs] = lattice->macro_vars[subs][0].u + 1; switch(which_f) { case 0: // Compute from post-collision f. ftemp = lattice->pdf[subs][0].f; break; case 1: // Compute from pre-collision f. ftemp = lattice->pdf[subs][0].ftemp; break; case 2: // Compute average from pre- and post-collision f. f = lattice->pdf[subs][0].f; ftemp = lattice->pdf[subs][0].ftemp; break; default: break; } bc = lattice->bc[subs]; for( n=0; n<lattice->NumNodes; n++) { *rho[subs] = 0.; *u_x[subs] = 0.; *u_y[subs] = 0.; if( COMPUTE_ON_SOLIDS || is_not_solid_node( lattice, subs, n)) { for( a=0; a<9; a++) { (*rho[subs]) += (*ftemp); (*u_x[subs]) += vx[a]*(*ftemp); (*u_y[subs]) += vy[a]*(*ftemp); ftemp++; if( which_f == 2) { (*rho[subs]) += (*f); (*u_x[subs]) += vx[a]*(*f); (*u_y[subs]) += vy[a]*(*f); f++; } } /* for( a=0; a<9; a++) */ #if SOURCE_ON (*rho[subs]) += lattice->param.source_strength * lattice->param.tau[0]; if(which_f == 2) { (*rho[subs]) += lattice->param.source_strength * lattice->param.tau[0]; } #endif /*if SOURCE_ON*/ if( which_f == 2) { (*rho[subs]) /= 2.; (*u_x[subs]) /= 2.; (*u_y[subs]) /= 2.; } else { #if GUO_ZHENG_SHI_BODY_FORCE //conc = lattice->pdf[/*sigma*/ 1 ][n].f[0] // + lattice->pdf[/*sigma*/ 1 ][n].f[1] // + lattice->pdf[/*sigma*/ 1 ][n].f[2] // + lattice->pdf[/*sigma*/ 1 ][n].f[3] // + lattice->pdf[/*sigma*/ 1 ][n].f[4] // + lattice->pdf[/*sigma*/ 1 ][n].f[5] // + lattice->pdf[/*sigma*/ 1 ][n].f[6] // + lattice->pdf[/*sigma*/ 1 ][n].f[7] // + lattice->pdf[/*sigma*/ 1 ][n].f[8] // + lattice->pdf[/*sigma*/ 1 ][n].f[9]; conc = lattice->macro_vars[1][n].rho; *u_x[subs] += .5*lattice->param.gval[subs][0] *(*rho[subs]) #if 1 *( 1. + ( get_buoyancy(lattice)) *( get_beta(lattice)) *( conc - get_C0(lattice))) #endif ; *u_y[subs] += .5*lattice->param.gval[subs][1] *(*rho[subs]) #if 1 *( 1. + ( get_buoyancy(lattice)) *( get_beta(lattice)) *( conc - get_C0(lattice))) #endif ; #endif } #if PUKE_NEGATIVE_DENSITIES if( *rho[subs] < 0.) { printf("\n"); printf( "compute_macro_vars() -- " "Node %d (%d,%d) has negative density %20.17f " "at timestep %d. Exiting!\n", n, n%lattice->param.LX, n/lattice->param.LX, *rho[subs], lattice->time ); printf("\n"); process_exit(1); } #endif /* PUKE_NEGATIVE_DENSITIES */ if( 0)//*rho[subs] == 0) { printf("\n"); printf("\n"); printf("%s (%d) -- " "ERROR: rho[subs=%d][j=%d][i=%d] = 0. " "at timestep %d. " "Exiting!\n", __FILE__,__LINE__, subs, n/lattice->param.LX, n%lattice->param.LX, lattice->time ); printf("\n"); printf("\n"); process_exit(1); } } /* if( !( bc++->bc_type & BC_SOLID_NODE)) */ else // bc++->bc_type & BC_SOLID_NODE { //printf("RHO: n=%d, Solid node.\n", n); ftemp+=9; if( which_f) { f+=9; } } /* if( !( bc++->bc_type & BC_SOLID_NODE)) else */ rho[subs]+=3; u_x[subs]+=3; u_y[subs]+=3; ftemp+=18; if( which_f == 2) { f+=18; } } /* for( n=0; n<lattice->NumNodes; n++) */ //############################################################################ // // For second component, compute just rho. // subs=1; //#if SIGMA_BULK_FLAG // if(lattice->time > lattice->param.sigma_bulk_on) // { //#endif rho[subs] = &( lattice->macro_vars[subs][0].rho); switch(which_f) { case 0: // Compute from pre-collision f. ftemp = lattice->pdf[subs][0].ftemp; break; case 1: // Compute from pre-collision f. ftemp = lattice->pdf[subs][0].ftemp; break; case 2: // Compute from pre-collision f. ftemp = lattice->pdf[subs][0].ftemp; break; default: break; } bc = lattice->bc[subs]; #if TAU_ZHANG_ANISOTROPIC_DISPERSION if( (lattice->param.ns_flag == 0)){ ns = lattice->param.ns;} #endif for( n=0; n<lattice->NumNodes; n++) { #if TAU_ZHANG_ANISOTROPIC_DISPERSION //Dl=.81;Dt=0.21; //*u_x[0] = (*u_x[0] < 1e-12 ? 0. : *u_x[0]); //*u_y[0] = (*u_y[0] < 1e-12 ? 0. : *u_y[0]); Dxx = lattice->param.Dt *sqrt(pow((*u_x[0]),2) + pow((*u_y[0]),2) ) + ( lattice->param.Dl - lattice->param.Dt)*(*u_x[0] * (*u_x[0]))/sqrt(pow((*u_x[0]),2) + pow((*u_y[0]),2)); Dyy= lattice->param.Dt *sqrt(pow((*u_x[0]),2) + pow((*u_y[0]),2) ) + ( lattice->param.Dl - lattice->param.Dt)*(*u_y[0] * (*u_y[0]))/sqrt(pow((*u_x[0]),2) + pow((*u_y[0]),2)); Dxy= ( lattice->param.Dl - lattice->param.Dt )*(*u_x[0] * (*u_y[0]))/sqrt(pow((*u_x[0]),2) + pow((*u_y[0]),2)); //printf("Dl=%f\n",lattice->param.Dl); lattice->tau_zhang [0] = 1.; lamdax = (18. * Dxx + 3. - 18. * Dxy)/ 6.; lamday = (18. * Dyy + 3. - 18. * Dxy)/ 6.; if(lamdax <0.5 | lamday <0.5) { printf("%s (%d)\n""lamda<0.5 lamdax=%f lamday=%f at n=%d, time=%d",__FILE__,__LINE__,lamdax,lamday,n,lattice->time); printf("\nux=%f uy=%f Dxx=%f Dxy=%f Dyy=%f \n",*u_x[0],*u_y[0],Dxx,Dxy,Dyy); exit(1); } if (Dxy > 1e-12) { if (lamdax < lamday) lattice->tau_zhang [6] = lattice->tau_zhang [8] = lamdax; else lattice->tau_zhang [6] = lattice->tau_zhang [8] = lamday; lattice->tau_zhang [5] = lattice->tau_zhang [7] = ( 18.* Dxy + lattice->tau_zhang [6]); lattice->tau_zhang [2] = lattice->tau_zhang [4] = ( 18.* Dyy + 3. - (lattice->tau_zhang [5]+lattice->tau_zhang [6]) )/4.; lattice->tau_zhang [1] = lattice->tau_zhang [3] = ( 18.* Dxx + 3. - (lattice->tau_zhang [5]+lattice->tau_zhang [6]) )/4.; } else if (Dxy < 1e-12) { if (lamdax < lamday) lattice->tau_zhang [6] = lattice->tau_zhang [8] = lamday; else lattice->tau_zhang [6] = lattice->tau_zhang [8] = lamdax; lattice->tau_zhang [5] = lattice->tau_zhang [7] = 0.5001; lattice->tau_zhang [6] = lattice->tau_zhang [8] = ( 18.* Dxy + lattice->tau_zhang [5]); lattice->tau_zhang [2] = lattice->tau_zhang [4] = ( 18.* Dyy + 3. - (lattice->tau_zhang [5]+lattice->tau_zhang [6]) )/4.; lattice->tau_zhang [1] = lattice->tau_zhang [3] = ( 18.* Dxx + 3. - (lattice->tau_zhang [5]+lattice->tau_zhang [6]) )/4.; } else if ( Dxy == 0.) { lattice->tau_zhang [6] = lattice->tau_zhang [8] = 0.5001; lattice->tau_zhang [5] = lattice->tau_zhang [7] = ( 18.* Dxy + lattice->tau_zhang [6]); lattice->tau_zhang [2] = lattice->tau_zhang [4] = ( 18.* Dyy + 3. - (lattice->tau_zhang [5]+lattice->tau_zhang [6]) )/4.; lattice->tau_zhang [1] = lattice->tau_zhang [3] = ( 18.* Dxx + 3. - (lattice->tau_zhang [5]+lattice->tau_zhang [6]) )/4.; } else { printf("%s (%d)""at Dxy = %f n=%d, time=%d",__FILE__,__LINE__,Dxy,n,lattice->time); printf("\nux=%f uy=%f Dxx=%f Dxy=%f Dyy=%f \n",*u_x[0],*u_y[0],Dxx,Dxy,Dyy); printf("\n%s (%d)\n""lamda<0.5 lamdax=%f lamday=%f at n=%d, time=%d",__FILE__,__LINE__,lamdax,lamday,n,lattice->time); exit(1); } factor=0.; for(a=0;a<9;a++) { factor=factor+wt[a]/lattice->tau_zhang [a]; } factor=1./factor; #endif *rho[subs] = 0.; if( COMPUTE_ON_SOLIDS || is_not_solid_node( lattice, subs, n)) { #if TAU_ZHANG_ANISOTROPIC_DISPERSION if( lattice->param.ns_flag >= 1 ) { ns = lattice->ns[n].ns;} for( a=0; a<9; a++) { (*rho[subs]) += (*ftemp)*((ns>1e-12) ?(factor/lattice->tau_zhang[a]) :(1.)); ftemp++; } /* for( a=0; a<9; a++) */ #else for( a=0; a<9; a++) { (*rho[subs]) += (*ftemp); ftemp++; } /* for( a=0; a<9; a++) */ #endif #if SINK_ON (*rho[subs]) *= (1. - lattice->param.sink_strength * lattice->param.tau[1]); #endif #if PUKE_NEGATIVE_CONCENTRATIONS if( *rho[subs] < 0.) { printf("\n"); printf( "compute_macro_vars() -- " "Node %d (%d,%d) has negative density %20.17f " "at timestep %d. Exiting!\n", n, n%lattice->param.LX, n/lattice->param.LX, *rho[subs], lattice->time ); printf("\n"); process_exit(1); } #endif /* PUKE_NEGATIVE_CONCENTRATIONS */ //assert( *rho[subs] != 0); } /* if( !( bc++->bc_type & BC_SOLID_NODE)) */ else // bc++->bc_type & BC_SOLID_NODE { //printf("RHO: n=%d, Solid node.\n", n); ftemp+=9; } /* if( !( bc++->bc_type & BC_SOLID_NODE)) else */ rho[subs]+=3; ftemp+=18; } /* for( n=0; n<lattice->NumNodes; n++) */ rho[0] = &( lattice->macro_vars[0][0].rho); u_x[0] = lattice->macro_vars[0][0].u; u_x[1] = lattice->macro_vars[1][0].u; u_y[0] = lattice->macro_vars[0][0].u + 1; u_y[1] = lattice->macro_vars[1][0].u + 1; for( n=0; n<lattice->NumNodes; n++) { if( COMPUTE_ON_SOLIDS || is_not_solid_node( lattice, subs, n)) { if( 0)//*rho[0] == 0) { printf("\n"); printf("\n"); printf("%s (%d) -- " "ERROR: rho[subs=%d][j=%d][i=%d] = 0. " "at timestep %d. " "Exiting!\n", __FILE__,__LINE__, 0, n/lattice->param.LX, n%lattice->param.LX, lattice->time ); printf("\n"); printf("\n"); process_exit(1); } if( lattice->param.incompressible) { c = 1.; } else { c = *rho[0]; } if( c!=0&&*u_x[0]!=0.) { *u_x[0] /= c;} else { *u_x[0] = 0.;} if( c!=0&&*u_y[0]!=0.) { *u_y[0] /= c;} else { *u_y[0] = 0.;} *u_x[1] = *u_x[0]; *u_y[1] = *u_y[0]; } /* if( 1 || !( bc[n].bc_type & BC_SOLID_NODE)) */ rho[0]+=3; u_x[0]+=3; u_x[1]+=3; u_y[0]+=3; u_y[1]+=3; } /* for( n=0; n<lattice->NumNodes; n++) */ //#if SIGMA_BULK_FLAG // } //#endif } /* void compute_macro_vars( struct lattice_struct *lattice) */ // }}} #else /* !( INAMURO_SIGMA_COMPONENT) */ // C O M P U T E _ M A C R O _ V A R S {{{1 void compute_macro_vars( struct lattice_struct *lattice, int which_f) { int n, a; double *rho[ NUM_FLUID_COMPONENTS], *u_x[ NUM_FLUID_COMPONENTS], *u_y[ NUM_FLUID_COMPONENTS]; double ux_sum, uy_sum; double *upr; double *f, *ftemp; bc_ptr bc; int subs; double tau0, tau1; double c; // // Compute for substance 0: // subs = 0; rho[subs] = &( lattice->macro_vars[subs][0].rho); u_x[subs] = lattice->macro_vars[subs][0].u; u_y[subs] = lattice->macro_vars[subs][0].u + 1; bc = lattice->bc[subs]; switch(which_f) { case 0: // Compute from post-collision f. ftemp = lattice->pdf[subs][0].f; break; case 1: // Compute from pre-collision f. ftemp = lattice->pdf[subs][0].ftemp; break; case 2: // Compute average from pre- and post-collision f. f = lattice->pdf[subs][0].f; ftemp = lattice->pdf[subs][0].ftemp; break; default: break; } for( n=0; n<lattice->NumNodes; n++) { *rho[subs] = 0.; *u_x[subs] = 0.; *u_y[subs] = 0.; if( COMPUTE_ON_SOLIDS || is_not_solid_node( lattice, subs, n)) { for( a=0; a<9; a++) { (*rho[subs]) += (*ftemp); (*u_x[subs]) += vx[a]*(*ftemp); (*u_y[subs]) += vy[a]*(*ftemp); ftemp++; if( which_f == 2) { (*rho[subs]) += (*f); (*u_x[subs]) += vx[a]*(*f); (*u_y[subs]) += vy[a]*(*f); f++; } } /* for( a=0; a<9; a++) */ #if SOURCE_ON (*rho[subs]) += lattice->param.source_strength * lattice->param.tau[0]; if( which_f == 2) { (*rho[subs]) += lattice->param.source_strength * lattice->param.tau[0]; } #endif /*if SOURCE_ON*/ if( which_f == 2) { (*rho[subs]) /= 2.; (*u_x[subs]) /= 2.; (*u_y[subs]) /= 2.; } else { #if GUO_ZHENG_SHI_BODY_FORCE *u_x[subs] += .5*lattice->param.gval[subs][0]*(*rho[subs]); *u_y[subs] += .5*lattice->param.gval[subs][1]*(*rho[subs]); #endif } // PUKE_NEGATIVE_DENSITIES {{{ #if PUKE_NEGATIVE_DENSITIES if( *rho[subs] < 0.) { printf("\n"); printf( "compute_macro_vars() -- " "Node %d (%d,%d) has negative density %20.17f " "at timestep %d. Exiting!\n", n, n%lattice->param.LX, n/lattice->param.LX, *rho[subs], lattice->time ); printf("\n"); process_exit(1); } #endif // PUKE_NEGATIVE_DENSITIES }}} //assert( *rho[subs] != 0); } /* if( !( bc++->bc_type & BC_SOLID_NODE)) */ else // bc++->bc_type & BC_SOLID_NODE {{{ { //printf("RHO: n=%d, Solid node.\n", n); ftemp+=9; if( which_f) { f+=9; } } /* if( !( bc++->bc_type & BC_SOLID_NODE)) else }}} */ rho[subs]+=3; u_x[subs]+=3; u_y[subs]+=3; ftemp+=18; if( which_f==2) { f+=18; } } /* for( n=0; n<lattice->NumNodes; n++) */ // // Compute for substance 1: // #if NUM_FLUID_COMPONENTS==2 subs = 1; rho[subs] = &( lattice->macro_vars[subs][0].rho); u_x[subs] = lattice->macro_vars[subs][0].u; u_y[subs] = lattice->macro_vars[subs][0].u + 1; bc = lattice->bc[subs]; switch(which_f) { case 0: // Compute from post-collision f. ftemp = lattice->pdf[subs][0].f; break; case 1: // Compute from pre-collision f. ftemp = lattice->pdf[subs][0].ftemp; break; case 2: // Compute average from pre- and post-collision f. f = lattice->pdf[subs][0].f; ftemp = lattice->pdf[subs][0].ftemp; break; default: break; } for( n=0; n<lattice->NumNodes; n++) { *rho[subs] = 0.; *u_x[subs] = 0.; *u_y[subs] = 0.; if( COMPUTE_ON_SOLIDS || is_not_solid_node( lattice, subs, n)) { for( a=0; a<9; a++) { (*rho[subs]) += (*ftemp); (*u_x[subs]) += vx[a]*(*ftemp); (*u_y[subs]) += vy[a]*(*ftemp); ftemp++; if( which_f == 2) { (*rho[subs]) += (*f); (*u_x[subs]) += vx[a]*(*f); (*u_y[subs]) += vy[a]*(*f); f++; } } /* for( a=0; a<9; a++) */ if( which_f == 2) { (*rho[subs]) /= 2.; (*u_x[subs]) /= 2.; (*u_y[subs]) /= 2.; } else { #if GUO_ZHENG_SHI_BODY_FORCE *u_x[subs] += .5*lattice->param.gval[subs][0]*(*rho[subs]); *u_y[subs] += .5*lattice->param.gval[subs][1]*(*rho[subs]); #endif } // PUKE_NEGATIVE_DENSITIES {{{ #if PUKE_NEGATIVE_DENSITIES if( *rho[subs] < 0.) { printf("\n"); printf( "compute_macro_vars() -- " "Node %d (%d,%d) has negative density %20.17f " "at timestep %d. Exiting!\n", n, n%lattice->param.LX, n/lattice->param.LX, *rho[subs], lattice->time ); printf("\n"); process_exit(1); } #endif // PUKE_NEGATIVE_DENSITIES }}} //assert( *rho[subs] != 0); } /* if( !( bc++->bc_type & BC_SOLID_NODE)) */ else // bc++->bc_type & BC_SOLID_NODE {{{ { //printf("RHO: n=%d, Solid node.\n", n); ftemp+=9; if( which_f) { f+=9; } } /* if( !( bc++->bc_type & BC_SOLID_NODE)) else }}} */ rho[subs]+=3; u_x[subs]+=3; u_y[subs]+=3; ftemp+=18; if( which_f==2) { f+=18; } } /* for( n=0; n<lattice->NumNodes; n++) */ #endif /*NUM_FLUID_COMPONENTS==2*/ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { rho[subs] = &( lattice->macro_vars[subs][0].rho); u_x[subs] = lattice->macro_vars[subs][0].u; u_y[subs] = lattice->macro_vars[subs][0].u + 1; } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if STORE_U_COMPOSITE upr = lattice->upr[0].u; #endif /* STORE_U_COMPOSITE */ if( NUM_FLUID_COMPONENTS==2) // {{{ { tau0 = lattice->param.tau[0]; tau1 = lattice->param.tau[1]; for( n=0; n<lattice->NumNodes; n++) { if( COMPUTE_ON_SOLIDS || is_not_solid_node( lattice, subs, n)) { ux_sum = *u_x[0]/tau0 + *u_x[1]/tau1; uy_sum = *u_y[0]/tau0 + *u_y[1]/tau1; #if STORE_U_COMPOSITE //assert( *rho[0] + *rho[1] != 0.); if( *rho[0] + *rho[1] != 0) { *upr++ = ( ux_sum) / ( *rho[0]/tau0 + *rho[1]/tau1); *upr++ = ( uy_sum) / ( *rho[0]/tau0 + *rho[1]/tau1); } else { *upr++ = 0.; *upr++ = 0.; } #endif /* STORE_U_COMPOSITE */ //assert( *rho[0] != 0.); //assert( *rho[1] != 0.); if( ux_sum != 0.) { if( *rho[0] != 0) { *u_x[0] = ux_sum / *rho[0]; } else { *u_x[0] = 0.; } if( *rho[1] != 0) { *u_x[1] = ux_sum / *rho[1]; } else { *u_x[1] = 0.; } } else { *u_x[0] = 0.; *u_x[1] = 0.; } if( uy_sum != 0.) { if( *rho[0] != 0) { *u_y[0] = uy_sum / *rho[0]; } else { *u_y[0] = 0.; } if( *rho[1] != 0) { *u_y[1] = uy_sum / *rho[1]; } else { *u_y[1] = 0.; } } else { *u_y[0] = 0.; *u_y[1] = 0.; } } /* if( 1 || !( bc[n].bc_type & BC_SOLID_NODE)) */ #if STORE_U_COMPOSITE else { upr+=2; } /* if( 1 || !( bc[n].bc_type & BC_SOLID_NODE)) else */ #endif /* STORE_U_COMPOSITE */ rho[0]+=3; u_x[0]+=3; u_y[0]+=3; rho[1]+=3; u_x[1]+=3; u_y[1]+=3; } /* for( n=0; n<lattice->NumNodes; n++) */ } // }}} else if( NUM_FLUID_COMPONENTS == 1) // {{{ { for( n=0; n<lattice->NumNodes; n++) { if( COMPUTE_ON_SOLIDS || is_not_solid_node( lattice, /*subs*/0, n)) { //assert( *rho[0] != 0.); if( lattice->param.incompressible) { c = 1.;} else { c = *rho[0];} if( c!=0&&*u_x[0]!=0.) { *u_x[0] /= c;} else { *u_x[0] = 0.;} if( c!=0&&*u_y[0]!=0.) { *u_y[0] /= c;} else { *u_y[0] = 0.;} } /* if( 1 || !( bc[n].bc_type & BC_SOLID_NODE)) */ rho[0]+=3; u_x[0]+=3; u_y[0]+=3; } /* for( n=0; n<lattice->NumNodes; n++) */ } // }}} else // {{{ { printf( "compute_macro_vars() -- " "Unhandled case " "NUM_FLUID_COMPONENTS = %d . " "Exiting!\n", NUM_FLUID_COMPONENTS); process_exit(1); } // }}} } /* void compute_macro_vars( struct lattice_struct *lattice) */ // }}} #endif /* INAMURO_SIGMA_COMPONENT */ // C O M P U T E _ F E Q {{{1 //############################################################################## // // void compute_feq( struct lattice_struct *lattice) // // - Compute equilibrium distribution function, feq. // void compute_feq( struct lattice_struct *lattice, int skip_sigma) { int n, a; double rt0, rt1, rt2; double f1, f2, f3; double ux, uy, uxsq, uysq, usq; double c; double *macro_var; #if INAMURO_SIGMA_COMPONENT double *rho, *u, *u0, *u1; #endif /* INAMURO_SIGMA_COMPONENT */ double *feq; #if STORE_U_COMPOSITE double *upr; #endif /* STORE_U_COMPOSITE */ bc_ptr bc; int subs; #if FREED_POROUS_MEDIA double Rx, Ry; double Gx, Gy; double u_x_p, u_y_p; double u_x_m, u_y_m; double edotu; double edotu_sq; double tau0 = lattice->param.tau[0]; double nu = (1./3.)*(tau0-.5); double rho0; double wt[9]={4./9.,1./9.,1./9.,1./9.,1./9.,1./36.,1./36.,1./36.,1./36.}; #endif #if NON_LOCAL_FORCES if( NUM_FLUID_COMPONENTS == 2) { #if ZHANG_AND_CHEN_ENERGY_TRANSPORT compute_phase_force( lattice, 0); #else /* !( ZHANG_AND_CHEN_ENERGY_TRANSPORT) */ if( lattice->param.G != 0.) { compute_fluid_fluid_force( lattice); } // NOTE: fluid/solid force is computed once in latman.c. #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ } else if( NUM_FLUID_COMPONENTS == 1) { if( lattice->param.G != 0.) { compute_phase_force( lattice, 0); } if( lattice->param.Gads[0] != 0.) { compute_single_fluid_solid_force( lattice, 0); } } else { printf( "compute_feq() -- " "Unhandled case NUM_FLUID_COMPONENTS = %d . " "Exiting!\n", NUM_FLUID_COMPONENTS); process_exit(1); } //dump_forces( lattice); //force2bmp( lattice); //printf("%s %d >> rand() = %f\n", __FILE__, __LINE__, // .00001*(double)rand()/(double)RAND_MAX); #endif f1 = 3.; f2 = 9./2.; f3 = 3./2.; for( subs=0; subs<(NUM_FLUID_COMPONENTS)-(INAMURO_SIGMA_COMPONENT); subs++) { macro_var = &( lattice->macro_vars[subs][0].rho); #if INAMURO_SIGMA_COMPONENT u0 = lattice->macro_vars[0][0].u; u1 = lattice->macro_vars[1][0].u; #endif /* INAMURO_SIGMA_COMPONENT */ feq = lattice->pdf[subs][0].feq; #if STORE_U_COMPOSITE upr = lattice->upr[0].u; #endif /* STORE_U_COMPOSITE */ bc = lattice->bc[subs]; for( n=0; n<lattice->NumNodes; n++) { if( COMPUTE_ON_SOLIDS || is_not_solid_node( lattice, subs, n)) { rt0 = *macro_var++; // Preserve raw density until after BIG_U. if( COMPUTE_ON_SOLIDS || is_not_solid_node( lattice, subs, n)) { #if STORE_U_COMPOSITE ux = BIG_U_X( *upr, ((rt0!=0)?(rt0):(1))); *upr++;// = ux; uy = BIG_U_Y( *upr, ((rt0!=0)?(rt0):(1))); *upr++;// = uy; macro_var+=2; #else /* !( STORE_U_COMPOSITE) */ #if INAMURO_SIGMA_COMPONENT ux = BIG_U_X( *macro_var, rt0, lattice->macro_vars[1][n].rho); macro_var++; *u1++ = *u0++; #else /* !( INAMURO_SIGMA_COMPONENT) */ ux = BIG_U_X( *macro_var, rt0); macro_var++; #endif /* INAMURO_SIGMA_COMPONENT */ #if INAMURO_SIGMA_COMPONENT #if 0 if( //gravitationally_adjacent_to_a_solid( lattice, subs, n, 1) || //on_the_east_or_west( lattice, n) on_the_east( lattice, n) //0 ) { // Preliminary, experimental mechanism to skip applying the // gravity term when adjacent to a solid and/or on a node that // has a boundary condition enforced. uy = *macro_var; } #else uy = BIG_U_Y( *macro_var, rt0, lattice->macro_vars[1][n].rho); #endif macro_var++; *u1++ = *u0++; #else /* !( INAMURO_SIGMA_COMPONENT) */ #if 0 if( //gravitationally_adjacent_to_a_solid( lattice, subs, n, 1) //|| on_the_east_or_west( lattice, n) //on_the_east( lattice, n) //0 ) { // Preliminary, experimental mechanism to skip applying the // gravity term when adjacent to a solid and/or on a node that // has a boundary condition enforced. uy = *macro_var; } #else uy = BIG_U_Y( *macro_var, rt0); #endif macro_var++; #endif /* INAMURO_SIGMA_COMPONENT */ #endif /* STORE_U_COMPOSITE */ } else { #if STORE_U_COMPOSITE ux = *upr++; uy = *upr++; macro_var+=2; #else /* !( STORE_U_COMPOSITE) */ ux = *macro_var++; #if INAMURO_SIGMA_COMPONENT *u1++ = *u0++; #endif /* INAMURO_SIGMA_COMPONENT */ uy = *macro_var++; #if INAMURO_SIGMA_COMPONENT *u1++ = *u0++; #endif /* INAMURO_SIGMA_COMPONENT */ #endif /* STORE_U_COMPOSITE */ } #if FREED_POROUS_MEDIA if( lattice->param.incompressible) { printf("ERROR: Can't have incompressible with Freed PM!"); process_exit(1); c = rt0; // rt0 == rho rt1 = 1./9.; rt2 = 1./36.; rt0 = 4./9.; // Overwrite rt0. } else // compressible { rho0 = rt0; c = 1.; rt1 = rt0/(9.); // rt0 == rho rt2 = rt0/(36.);// rt0 == rho rt0 *= (4./9.); // Update rt0 now that raw density is no longer needed. } Rx = lattice->param.ns; Ry = Rx; Gx = (1. - 3.*nu*Rx)/(1. + 0.5*Rx); Gy = (1. - 3.*nu*Ry)/(1. + 0.5*Ry); u_x_p = Gx*ux //u_x_p is post-collision velocity, + lattice->param.gval[subs][0]*tau0/rho0; u_y_p = Gy*uy // u_x is pre-collision velocity + lattice->param.gval[subs][1]*tau0/rho0; u_x_m = (1. - 0.5/tau0)*ux + 0.5*u_x_p/tau0; // u_x_m is mean velocity u_y_m = (1. - 0.5/tau0)*uy + 0.5*u_y_p/tau0; usq = pow(u_x_m, 2) + pow(u_y_m, 2); // printf("ux =%12.10f ux_p= %12.10f ux_m=%12.10f \n", u_x, u_x_p, u_x_m); for(a=0; a<9; a++) { edotu = *(vx + a)*u_x_p + *(vy +a)*u_y_p; edotu_sq = pow( ( *(vx + a)*u_x_m + *(vy +a)*u_y_m ), 2.); *feq++ = *(wt +a)*rho0 *(1. + 3.*edotu + (9./2.)*edotu_sq - (3./2.)*usq ); } ux = u_x_m; uy = u_y_m; lattice->macro_vars[subs][n].u[0] = ux; lattice->macro_vars[subs][n].u[1] = uy; #else if( lattice->param.incompressible) { c = rt0; // rt0 == rho rt1 = 1./9.; rt2 = 1./36.; rt0 = 4./9.; // Overwrite rt0. } else // compressible { c = 1.; rt1 = rt0/(9.); // rt0 == rho rt2 = rt0/(36.);// rt0 == rho rt0 *= (4./9.); // Update rt0 now that raw density is no longer needed. } uxsq = ux*ux; uysq = uy*uy; usq = uxsq + uysq; *feq++ = rt0 * (c - f3*usq); *feq++ = rt1 * (c + f1*ux + f2*uxsq - f3*usq); *feq++ = rt1 * (c + f1*uy + f2*uysq - f3*usq); *feq++ = rt1 * (c - f1*ux + f2*uxsq - f3*usq); *feq++ = rt1 * (c - f1*uy + f2*uysq - f3*usq); *feq++ = rt2*(c+f1*( ux+uy)+f2*( ux+uy)*( ux+uy)-f3*usq); *feq++ = rt2*(c+f1*(-ux+uy)+f2*(-ux+uy)*(-ux+uy)-f3*usq); *feq++ = rt2*(c+f1*(-ux-uy)+f2*(-ux-uy)*(-ux-uy)-f3*usq); *feq++ = rt2*(c+f1*( ux-uy)+f2*( ux-uy)*( ux-uy)-f3*usq); #endif feq+=18; #if INAMURO_SIGMA_COMPONENT u0++; u1++; #endif /* INAMURO_SIGMA_COMPONENT */ } else { #if 1 *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; feq+=18; #else feq+=27; #endif macro_var+=3; #if INAMURO_SIGMA_COMPONENT u0+=3; u1+=3; #endif /* INAMURO_SIGMA_COMPONENT */ #if STORE_U_COMPOSITE upr+=2; #endif /* STORE_U_COMPOSITE */ } } /* for( n=0; n<lattice->NumNodes; n++) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if INAMURO_SIGMA_COMPONENT if( !skip_sigma) { subs=1; c = 1.; #if ZHANG_AND_CHEN_ENERGY_TRANSPORT f1 = 3.; f2 = 9./2.; f3 = 3./2.; #else /* !( ZHANG_AND_CHEN_ENERGY_TRANSPORT) */ f1 = 3.; f2 = 0.; f3 = 0.; #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ rho = &( lattice->macro_vars[subs][0].rho); u = lattice->macro_vars[subs][0].u; feq = lattice->pdf[subs][0].feq; bc = lattice->bc[subs]; for( n=0; n<lattice->NumNodes; n++) { if( COMPUTE_ON_SOLIDS || is_not_solid_node( lattice, subs, n)) { rt0 = *rho; // Preserve raw density until after BIG_U. rho+=3; ux = *u++; uy = *u++; if( lattice->param.simple_diffusion) { rt1 = rt0/(8.); // rt0 == rho rt0 *= (1./2.); // Update rt0 now that raw density is no longer needed. *feq++ = rt0 * ( 1. ); *feq++ = rt1 * ( c + f1*ux ); *feq++ = rt1 * ( c + f1*uy ); *feq++ = rt1 * ( c - f1*ux ); *feq++ = rt1 * ( c - f1*uy ); *feq++ = 0.; //rt2 * ( c + f1*( ux+uy)); *feq++ = 0.; //rt2 * ( c + f1*(-ux+uy)); *feq++ = 0.; //rt2 * ( c + f1*(-ux-uy)); *feq++ = 0.; //rt2 * ( c + f1*( ux-uy)); } else { rt1 = rt0/(9.); // rt0 == rho rt2 = rt0/(36.);// rt0 == rho rt0 *= (4./9.); // Update rt0 now that raw density is no longer needed. #if ZHANG_AND_CHEN_ENERGY_TRANSPORT uxsq = ux*ux; uysq = uy*uy; usq = uxsq + uysq; *feq++ = rt0 * (c - f3*usq); *feq++ = rt1 * (c + f1*ux + f2*uxsq - f3*usq); *feq++ = rt1 * (c + f1*uy + f2*uysq - f3*usq); *feq++ = rt1 * (c - f1*ux + f2*uxsq - f3*usq); *feq++ = rt1 * (c - f1*uy + f2*uysq - f3*usq); *feq++ = rt2*(c+f1*( ux+uy)+f2*( ux+uy)*( ux+uy)-f3*usq); *feq++ = rt2*(c+f1*(-ux+uy)+f2*(-ux+uy)*(-ux+uy)-f3*usq); *feq++ = rt2*(c+f1*(-ux-uy)+f2*(-ux-uy)*(-ux-uy)-f3*usq); *feq++ = rt2*(c+f1*( ux-uy)+f2*( ux-uy)*( ux-uy)-f3*usq); #else /* !( ZHANG_AND_CHEN_ENERGY_TRANSPORT) */ *feq++ = rt0 * ( 1. ); *feq++ = rt1 * ( c + f1*ux ); *feq++ = rt1 * ( c + f1*uy ); *feq++ = rt1 * ( c - f1*ux ); *feq++ = rt1 * ( c - f1*uy ); *feq++ = rt2 * ( c + f1*( ux+uy)); *feq++ = rt2 * ( c + f1*(-ux+uy)); *feq++ = rt2 * ( c + f1*(-ux-uy)); *feq++ = rt2 * ( c + f1*( ux-uy)); #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ } feq+=18; u++; } else { #if 1 *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; *feq++ = 0.; feq+=18; #else feq+=27; #endif rho+=1; u+=3; } } /* for( n=0; n<lattice->NumNodes; n++) */ } #endif /* INAMURO_SIGMA_COMPONENT */ //dump_pdf( lattice, lattice->time); } /* void compute_feq( struct lattice_struct *lattice) */ // }}} #if NON_LOCAL_FORCES #if 1 // C O M P U T E _ F L U I D _ F L U I D _ F O R C E {{{1 void compute_fluid_fluid_force( lattice_ptr lattice) { printf("BING: compute_fluid_fluid_force()\n"); double ***psi; //psi[ NUM_FLUID_COMPONENTS][LX][LY]; double psi_temp; double *rho; double *force[2]; int i, j, in, jn, ip, jp; int n, LX, LY; int sj, ej; int subs; LX = lattice->param.LX; LY = lattice->param.LY; psi = ( double***)malloc( (NUM_FLUID_COMPONENTS)*sizeof(double**)); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { psi[subs] = ( double**)malloc( LY*sizeof(double*)); } for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { for( j=0; j<LY; j++) { psi[subs][j] = ( double*)malloc( LX*sizeof(double)); } } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ // Initialize psi. for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { for( j=0; j<LY; j++) { for( i=0; i<LX; i++, n++) { psi[subs][j][i] = 0.; } } if( lattice->periodic_y[subs]) { sj = 0; ej = LY-1; rho = &( lattice->macro_vars[subs][0].rho); } else { sj = 1; ej = LY-2; rho = &( lattice->macro_vars[subs][LX].rho); } if( !lattice->periodic_x[subs]) { printf("%s %d >> Need to be periodic in x-direction to use " "NON_LOCAL_FORCES for now. Exiting!\n", __FILE__, __LINE__); process_exit(1); } for( j=sj; j<=ej; j++) { n = j*LX; for( i=0; i<LX; i++, n++) { if( is_not_solid_node( lattice, subs, n)) { psi[subs][j][i] = *rho; } rho+=3; } /* for( i=0; i<LX; i++) */ } /* for( j=0; j<LY; j++) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ //printf("sizeof( struct force_struct) = %d\n", sizeof( struct force_struct)); //printf("NumNodes*sizeof( struct force_struct) = %d\n", // lattice->NumNodes*sizeof( struct force_struct)); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { if( lattice->periodic_y[subs]) { sj = 0; ej = LY-1; force[subs] = lattice->force[subs][0].force; } else { sj = 1; ej = LY-2; force[subs] = lattice->force[subs][LX].force; } for( j=sj; j<=ej; j++) { jp = ( j<LY-1)?( j+1):( 0 ); jn = ( j>0 )?( j-1):( LY-1); for( i=0; i<LX; i++) { ip = ( i<LX-1)?( i+1):( 0 ); in = ( i>0 )?( i-1):( LX-1); //printf("compute_fluid_fluid_force() -- " // "subs %d, ( i, j) = ( %2d, %2d), | f - f0| = %d\n", // subs, i, j, // force[subs] - lattice->force[subs][0].force ); *( force[subs] ) = 0.; *( force[subs]+1) = 0.; if( !( lattice->bc[subs][ j*LX+i].bc_type & BC_SOLID_NODE)) { /* 1 */ if( !( lattice->bc[subs][ j *LX+ip].bc_type & BC_SOLID_NODE)) { *( force[subs] ) += WM*vx[1]*psi[subs][j ][ip]; *( force[subs]+1) += WM*vy[1]*psi[subs][j ][ip]; } /* 2 */ if( !( lattice->bc[subs][ jp*LX+i ].bc_type & BC_SOLID_NODE)) { *( force[subs] ) += WM*vx[2]*psi[subs][jp][i ]; *( force[subs]+1) += WM*vy[2]*psi[subs][jp][i ]; } /* 3 */ if( !( lattice->bc[subs][ j *LX+in].bc_type & BC_SOLID_NODE)) { *( force[subs] ) += WM*vx[3]*psi[subs][j ][in]; *( force[subs]+1) += WM*vy[3]*psi[subs][j ][in]; } /* 4 */ if( !( lattice->bc[subs][ jn*LX+i ].bc_type & BC_SOLID_NODE)) { *( force[subs] ) += WM*vx[4]*psi[subs][jn][i ]; *( force[subs]+1) += WM*vy[4]*psi[subs][jn][i ]; } /* 5 */ if( !( lattice->bc[subs][ jp*LX+ip].bc_type & BC_SOLID_NODE)) { *( force[subs] ) += WD*vx[5]*psi[subs][jp][ip]; *( force[subs]+1) += WD*vy[5]*psi[subs][jp][ip]; } /* 6 */ if( !( lattice->bc[subs][ jp*LX+in].bc_type & BC_SOLID_NODE)) { *( force[subs] ) += WD*vx[6]*psi[subs][jp][in]; *( force[subs]+1) += WD*vy[6]*psi[subs][jp][in]; } /* 7 */ if( !( lattice->bc[subs][ jn*LX+in].bc_type & BC_SOLID_NODE)) { *( force[subs] ) += WD*vx[7]*psi[subs][jn][in]; *( force[subs]+1) += WD*vy[7]*psi[subs][jn][in]; } /* 8 */ if( !( lattice->bc[subs][ jn*LX+ip].bc_type & BC_SOLID_NODE)) { *( force[subs] ) += WD*vx[8]*psi[subs][jn][ip]; *( force[subs]+1) += WD*vy[8]*psi[subs][jn][ip]; } } /* if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) */ force[subs] += ( sizeof( struct force_struct)/8); } /* for( i=0; i<LX; i++) */ } /* for( j=0; j<LY; j++) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ force[0] = lattice->force[0][0].force; force[1] = lattice->force[1][0].force; for( j=0; j<LY; j++) { for( i=0; i<LX; i++) { if( !( lattice->bc[0][ j*LX+i].bc_type & BC_SOLID_NODE)) { psi_temp = *( force[1] ); *( force[1] ) = -lattice->param.G*psi[1][j][i]*( *(force[0] )); *( force[0] ) = -lattice->param.G*psi[0][j][i]*( psi_temp ); psi_temp = *( force[1]+1); *( force[1]+1) = -lattice->param.G*psi[1][j][i]*( *(force[0]+1)); *( force[0]+1) = -lattice->param.G*psi[0][j][i]*( psi_temp ); } /* if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) */ force[0] += ( sizeof( struct force_struct)/8); force[1] += ( sizeof( struct force_struct)/8); } /* for( i=0; i<LX; i++) */ } /* for( j=0; j<LY; j++) */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { for( j=0; j<LY; j++) { free( psi[subs][j]); } } for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { free( psi[subs]); } free( psi); } /* void compute_fluid_fluid_force( lattice_ptr lattice) */ // }}} #else // C O M P U T E _ F L U I D _ F L U I D _ F O R C E {{{1 void compute_fluid_fluid_force( lattice_ptr lattice) { double ***psi; //psi[ NUM_FLUID_COMPONENTS][LX][LY]; double psi_x[2]; double psi_y[2]; double *rho; double *force[2]; int i, j, in, jn, ip, jp; int n, LX, LY; int subs; LX = lattice->param.LX; LY = lattice->param.LY; psi = ( double***)malloc( (NUM_FLUID_COMPONENTS)*sizeof(double**)); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { psi[subs] = ( double**)malloc( LY*sizeof(double*)); } for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { for( j=0; j<LY; j++) { psi[subs][j] = ( double*)malloc( LY*sizeof(double)); } } // Initialize psi. for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { rho = &( lattice->macro_vars[subs][0].rho); if( !lattice->periodic_x[subs] || !lattice->periodic_y[subs]) { printf("%s %d >> Need to be fully periodic to use " "NON_LOCAL_FORCES for now. Exiting!\n" __FILE__, __LINE__); process_exit(1); } for( j=0; j<LY; j++) { n = j*LX; for( i=0; i<LX; i++, n++) { if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { psi[subs][j][i] = *rho; } else // lattice->bc[subs][n].bc_type & BC_SOLID_NODE { psi[subs][j][i] = 0.; } rho+=3; } /* for( i=0; i<LX; i++) */ } /* for( j=0; j<LY; j++) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ //printf("sizeof( struct force_struct) = %d\n", sizeof( struct force_struct)); //printf("NumNodes*sizeof( struct force_struct) = %d\n", // lattice->NumNodes*sizeof( struct force_struct)); for( j=0; j<LY; j++) { jp = ( j<LY-1)?( j+1):( 0 ); jn = ( j>0 )?( j-1):( LY-1); for( i=0; i<LX; i++) { ip = ( i<LX-1)?( i+1):( 0 ); in = ( i>0 )?( i-1):( LX-1); if( !( lattice->bc[0][ j*LX+i].bc_type & BC_SOLID_NODE)) { for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { force[subs] = lattice->force[subs][j*LX+i].force; psi_x[subs] = 0.; psi_y[subs] = 0.; /* 1 */ if( !( lattice->bc[subs][ j *LX+ip].bc_type & BC_SOLID_NODE)) { psi_x[subs] += 2.*vx[1]*psi[subs][j ][ip]; psi_y[subs] += 2.*vy[1]*psi[subs][j ][ip]; } /* 2 */ if( !( lattice->bc[subs][ jp*LX+i ].bc_type & BC_SOLID_NODE)) { psi_x[subs] += 2.*vx[2]*psi[subs][jp][i ]; psi_y[subs] += 2.*vy[2]*psi[subs][jp][i ]; } /* 3 */ if( !( lattice->bc[subs][ j *LX+in].bc_type & BC_SOLID_NODE)) { psi_x[subs] += 2.*vx[3]*psi[subs][j ][in]; psi_y[subs] += 2.*vy[3]*psi[subs][j ][in]; } /* 4 */ if( !( lattice->bc[subs][ jn*LX+i ].bc_type & BC_SOLID_NODE)) { psi_x[subs] += 2.*vx[4]*psi[subs][jn][i ]; psi_y[subs] += 2.*vy[4]*psi[subs][jn][i ]; } /* 5 */ if( !( lattice->bc[subs][ jp*LX+ip].bc_type & BC_SOLID_NODE)) { psi_x[subs] += vx[5]*psi[subs][jp][ip]; psi_y[subs] += vy[5]*psi[subs][jp][ip]; } /* 6 */ if( !( lattice->bc[subs][ jp*LX+in].bc_type & BC_SOLID_NODE)) { psi_x[subs] += vx[6]*psi[subs][jp][in]; psi_y[subs] += vy[6]*psi[subs][jp][in]; } /* 7 */ if( !( lattice->bc[subs][ jn*LX+in].bc_type & BC_SOLID_NODE)) { psi_x[subs] += vx[7]*psi[subs][jn][in]; psi_y[subs] += vy[7]*psi[subs][jn][in]; } /* 8 */ if( !( lattice->bc[subs][ jn*LX+ip].bc_type & BC_SOLID_NODE)) { psi_x[subs] += vx[8]*psi[subs][jn][ip]; psi_y[subs] += vy[8]*psi[subs][jn][ip]; } } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ lattice->force[0][j*LX+i].force[0] = -lattice->param.G*psi[0][j][i]*( psi_x[1]); lattice->force[0][j*LX+i].force[1] = -lattice->param.G*psi[0][j][i]*( psi_y[1]); lattice->force[1][j*LX+i].force[0] = -lattice->param.G*psi[1][j][i]*( psi_x[0]); lattice->force[1][j*LX+i].force[1] = -lattice->param.G*psi[1][j][i]*( psi_y[0]); } else { lattice->force[0][j*LX+i].force[0] = 0.; lattice->force[0][j*LX+i].force[1] = 0.; lattice->force[1][j*LX+i].force[0] = 0.; lattice->force[1][j*LX+i].force[1] = 0.; } } /* for( i=0; i<LX; i++) */ } /* for( j=0; j<LY; j++) */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { for( j=0; j<LY; j++) { free( psi[subs][j]); } } for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { free( psi[subs]); } free( psi); } /* void compute_fluid_fluid_force( lattice_ptr lattice) */ // }}} #endif #if ZHANG_AND_CHEN_ENERGY_TRANSPORT // C O M P U T E _ P H A S E _ F O R C E {{{1 // // Based on Zhang & Chen, PRE 67, 0066711 (2003) // // Supposed to give thermodynamic consistency unlike old Shan & Chen method. // And supports general equation of state P = P(rho,T). // Utilizes the Inamuro component for evolution of the energy transport // equation. Employs modified compute_phase_force routine to compute // body force term representing non-local interaction potential U among // particles. // void compute_phase_force( lattice_ptr lattice, int subs) { double **U; double *rho; double *T; double *force; double a, b, R; int i, j, in, jn, ip, jp; int n, LX, LY; int sj, ej; double y; LX = lattice->param.LX; LY = lattice->param.LY; U = ( double**)malloc( LY*sizeof(double*)); for( j=0; j<LY; j++) { U[j] = ( double*)malloc( LX*sizeof(double)); } // Initialize U. for( j=0; j<LY; j++) { for( i=0; i<LX; i++, n++) { U[j][i] = 0.; } } if( !lattice->periodic_x[0] || !lattice->periodic_y[0]) { printf("%s %d >> Need to be fully periodic to use " "ZHANG_AND_CHEN_ENERGY_TRANSPORT for now. Exiting!\n" __FILE__, __LINE__); process_exit(1); } /* if( !lattice->periodic_x[0] || !lattice->periodic_y[0]) */ sj = 0; ej = LY-1; //############################################################################ // // Set U = P(rho,T) - rho*T0 // // = R*T*( rho/(1-rho*b)) - a*rho^2 // // Maxwell ==> rho_l = 10.8657, rho_v = 4.98648 // a = 3.592; b = 0.04267; R = 0.082057; rho = &( lattice->macro_vars[/*subs*/0][0].rho); T = &( lattice->macro_vars[/*subs*/1][0].rho); for( j=sj; j<=ej; j++) { n = j*LX; for( i=0; i<LX; i++, n++) { if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) { #if 0 // Van der Walls U[j][i] = R*(*T)*( (*rho)/( 1. - (*rho)*b)) - a*(*rho)*(*rho); #else // Carnahan-Starling y = (*rho)*b/4.; U[j][i] = R*(*T)*(*rho)*( ( 1. + y + y*y - y*y*y) / ( (1.-y)*(1.-y)*(1.-y))) - a*(*rho)*(*rho); //printf("%s (%d) >> U[%d][%d](rho=%f,T=%f) = %20.17f\n", // __FILE__, __LINE__, j, i, *rho, *T, U[j][i]); #endif } /* if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) */ rho+=3; T +=3; } /* for( i=0; i<LX; i++) */ } /* for( j=0; j<LY; j++) */ //printf("sizeof( struct force_struct) = %d\n", sizeof( struct force_struct)); //printf("NumNodes*sizeof( struct force_struct) = %d\n", // lattice->NumNodes*sizeof( struct force_struct)); //############################################################################ // // Compute F(x,t) = -\sum_i ( D/(b*c_i^2)) e_i U( x+e_i,t) // sj = 0; ej = LY-1; force = ( lattice->force[/*subs*/0][0].force); for( j=sj; j<=ej; j++) { jp = ( j<LY-1)?( j+1):( 0 ); jn = ( j>0 )?( j-1):( LY-1); for( i=0; i<LX; i++) { ip = ( i<LX-1)?( i+1):( 0 ); in = ( i>0 )?( i-1):( LX-1); *( force ) = 0.; *( force+1) = 0.; if( !( lattice->bc[0][ j*LX+i].bc_type & BC_SOLID_NODE)) { /* 1 */ if( !( lattice->bc[0][ j *LX+ip].bc_type & BC_SOLID_NODE)) { *( force ) += 1.*vx[1]*U[j ][ip]; *( force+1) += 1.*vy[1]*U[j ][ip]; } /* 2 */ if( !( lattice->bc[0][ jp*LX+i ].bc_type & BC_SOLID_NODE)) { *( force ) += 1.*vx[2]*U[jp][i ]; *( force+1) += 1.*vy[2]*U[jp][i ]; } /* 3 */ if( !( lattice->bc[0][ j *LX+in].bc_type & BC_SOLID_NODE)) { *( force ) += 1.*vx[3]*U[j ][in]; *( force+1) += 1.*vy[3]*U[j ][in]; } /* 4 */ if( !( lattice->bc[0][ jn*LX+i ].bc_type & BC_SOLID_NODE)) { *( force ) += 1.*vx[4]*U[jn][i ]; *( force+1) += 1.*vy[4]*U[jn][i ]; } /* 5 */ if( !( lattice->bc[0][ jp*LX+ip].bc_type & BC_SOLID_NODE)) { *( force ) += vx[5]*U[jp][ip]; *( force+1) += vy[5]*U[jp][ip]; } /* 6 */ if( !( lattice->bc[0][ jp*LX+in].bc_type & BC_SOLID_NODE)) { *( force ) += vx[6]*U[jp][in]; *( force+1) += vy[6]*U[jp][in]; } /* 7 */ if( !( lattice->bc[0][ jn*LX+in].bc_type & BC_SOLID_NODE)) { *( force ) += vx[7]*U[jn][in]; *( force+1) += vy[7]*U[jn][in]; } /* 8 */ if( !( lattice->bc[0][ jn*LX+ip].bc_type & BC_SOLID_NODE)) { *( force ) += vx[8]*U[jn][ip]; *( force+1) += vy[8]*U[jn][ip]; } *( force ) = -(1./8.)*( *(force )); *( force+1) = -(1./8.)*( *(force+1)); //printf("%s (%d) >> Fx = %20.17f\n", __FILE__, __LINE__, *(force )); //printf("%s (%d) >> Fy = %20.17f\n", __FILE__, __LINE__, *(force+1)); } /* if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) */ else { *( force ) = 0.; *( force+1) = 0.; //printf("%s (%d) >> Fx = ZERO\n", __FILE__, __LINE__); //printf("%s (%d) >> Fy = ZERO\n", __FILE__, __LINE__); } force += ( sizeof( struct force_struct)/8); } /* for( i=0; i<LX; i++) */ } /* for( j=0; j<LY; j++) */ for( j=0; j<LY; j++) { free( U[j]); } free( U); } /* void compute_phase_force( lattice_ptr lattice, int subs) */ // }}} #else /* !( ZHANG_AND_CHEN_ENERGY_TRANSPORT) */ // C O M P U T E _ P H A S E _ F O R C E {{{1 void compute_phase_force( lattice_ptr lattice, int subs) { double **psi; //psi[ NUM_FLUID_COMPONENTS][LX][LY]; double psi_temp; double *rho; double *force; int i, j, in, jn, ip, jp; int n, LX, LY; int sj, ej; LX = lattice->param.LX; LY = lattice->param.LY; psi = ( double**)malloc( LY*sizeof(double**)); for( j=0; j<LY; j++) { psi[j] = ( double*)malloc( LX*sizeof(double)); } // Initialize psi. for( j=0; j<LY; j++) { for( i=0; i<LX; i++, n++) { psi[j][i] = 0.; } } //if( lattice->periodic_y[subs]) //{ sj = 0; ej = LY-1; rho = &( lattice->macro_vars[subs][0].rho); //} //else //{ // sj = 1; // ej = LY-2; // rho = &( lattice->macro_vars[subs][LX].rho); //} for( j=sj; j<=ej; j++) { n = j*LX; for( i=0; i<LX; i++, n++) { if( *rho!=0 && !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { psi[j][i] = 4.*exp(-200./(*rho)); } else { psi[j][i] = 0.; } rho+=3; } /* for( i=0; i<LX; i++) */ } /* for( j=0; j<LY; j++) */ if( is_periodic_in_y(lattice,subs)) { sj = 0; ej = LY-1; force = lattice->force[subs][0].force; } /* if( is_periodic_in_y(lattice,subs)) */ else //{ // sj = 1; // ej = LY-2; // force = lattice->force[subs][LX].force; //} { j = 0; jp = j+1; force = lattice->force[subs][0].force; for( i=0; i<LX; i++) { ip = ( i<LX-1)?( i+1):( 0 ); in = ( i>0 )?( i-1):( LX-1); *( force ) = 0.; *( force+1) = 0.; if( !( lattice->bc[subs][ j*LX+i].bc_type & BC_SOLID_NODE)) { if( !( lattice->bc[subs][ j *LX+ip].bc_type & BC_SOLID_NODE)) { *( force ) += WM*vx[1]*psi[j ][ip]; *( force+1) += WM*vy[1]*psi[j ][ip]; } if( !( lattice->bc[subs][ jp*LX+i ].bc_type & BC_SOLID_NODE)) { *( force ) += WM*vx[2]*psi[jp][i ]; *( force+1) += WM*vy[2]*psi[jp][i ]; } if( !( lattice->bc[subs][ j *LX+in].bc_type & BC_SOLID_NODE)) { *( force ) += WM*vx[3]*psi[j ][in]; *( force+1) += WM*vy[3]*psi[j ][in]; } /**/ if( !( lattice->bc[subs][ j *LX+i ].bc_type & BC_SOLID_NODE)) { /**/ *( force ) += WM*vx[4]*psi[j ][i ]; /**/ *( force+1) += WM*vy[4]*psi[j ][i ]; } if( !( lattice->bc[subs][ jp*LX+ip].bc_type & BC_SOLID_NODE)) { *( force ) += WD*vx[5]*psi[jp][ip]; *( force+1) += WD*vy[5]*psi[jp][ip]; } if( !( lattice->bc[subs][ jp*LX+in].bc_type & BC_SOLID_NODE)) { *( force ) += WD*vx[6]*psi[jp][in]; *( force+1) += WD*vy[6]*psi[jp][in]; } /**/ if( !( lattice->bc[subs][ j *LX+in].bc_type & BC_SOLID_NODE)) { /**/ *( force ) += WD*vx[7]*psi[j ][in]; /**/ *( force+1) += WD*vy[7]*psi[j ][in]; } /**/ if( !( lattice->bc[subs][ j *LX+ip].bc_type & BC_SOLID_NODE)) { /**/ *( force ) += WD*vx[8]*psi[j ][ip]; /**/ *( force+1) += WD*vy[8]*psi[j ][ip]; } *( force ) = -lattice->param.G*psi[j][i]*( *(force )); *( force+1) = -lattice->param.G*psi[j][i]*( *(force+1)); } /* if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) */ else { *( force ) = 0.; *( force+1) = 0.; } force += ( sizeof( struct force_struct)/8); } /* for( i=0; i<LX; i++) */ j = LY-1; jn = j-1; force = lattice->force[subs][j*LX].force; for( i=0; i<LX; i++) { ip = ( i<LX-1)?( i+1):( 0 ); in = ( i>0 )?( i-1):( LX-1); *( force ) = 0.; *( force+1) = 0.; if( !( lattice->bc[subs][ j*LX+i].bc_type & BC_SOLID_NODE)) { if( !( lattice->bc[subs][ j *LX+ip].bc_type & BC_SOLID_NODE)) { *( force ) += WM*vx[1]*psi[j ][ip]; *( force+1) += WM*vy[1]*psi[j ][ip]; } /**/ if( !( lattice->bc[subs][ j *LX+i ].bc_type & BC_SOLID_NODE)) { /**/ *( force ) += WM*vx[2]*psi[j ][i ]; /**/ *( force+1) += WM*vy[2]*psi[j ][i ]; } if( !( lattice->bc[subs][ j *LX+in].bc_type & BC_SOLID_NODE)) { *( force ) += WM*vx[3]*psi[j ][in]; *( force+1) += WM*vy[3]*psi[j ][in]; } if( !( lattice->bc[subs][ jn*LX+i ].bc_type & BC_SOLID_NODE)) { *( force ) += WM*vx[4]*psi[jn][i ]; *( force+1) += WM*vy[4]*psi[jn][i ]; } /**/ if( !( lattice->bc[subs][ j *LX+ip].bc_type & BC_SOLID_NODE)) { /**/ *( force ) += WD*vx[5]*psi[j ][ip]; /**/ *( force+1) += WD*vy[5]*psi[j ][ip]; } /**/ if( !( lattice->bc[subs][ j *LX+in].bc_type & BC_SOLID_NODE)) { /**/ *( force ) += WD*vx[6]*psi[j ][in]; /**/ *( force+1) += WD*vy[6]*psi[j ][in]; } if( !( lattice->bc[subs][ jn*LX+in].bc_type & BC_SOLID_NODE)) { *( force ) += WD*vx[7]*psi[jn][in]; *( force+1) += WD*vy[7]*psi[jn][in]; } if( !( lattice->bc[subs][ jn*LX+ip].bc_type & BC_SOLID_NODE)) { *( force ) += WD*vx[8]*psi[jn][ip]; *( force+1) += WD*vy[8]*psi[jn][ip]; } *( force ) = -lattice->param.G*psi[j][i]*( *(force )); *( force+1) = -lattice->param.G*psi[j][i]*( *(force+1)); } /* if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) */ else { *( force ) = 0.; *( force+1) = 0.; } force += ( sizeof( struct force_struct)/8); } /* for( i=0; i<LX; i++) */ sj = 1; ej = LY-2; force = lattice->force[subs][LX].force; } /* if( is_periodic_in_y(lattice,subs)) else */ for( j=sj; j<=ej; j++) { jp = ( j<LY-1)?( j+1):( 0 ); jn = ( j>0 )?( j-1):( LY-1); for( i=0; i<LX; i++) { ip = ( i<LX-1)?( i+1):( 0 ); in = ( i>0 )?( i-1):( LX-1); *( force ) = 0.; *( force+1) = 0.; if( !( lattice->bc[subs][ j*LX+i].bc_type & BC_SOLID_NODE)) { /* 1 */ if( !( lattice->bc[subs][ j *LX+ip].bc_type & BC_SOLID_NODE)) { *( force ) += WM*vx[1]*psi[j ][ip]; *( force+1) += WM*vy[1]*psi[j ][ip]; } /* 2 */ if( !( lattice->bc[subs][ jp*LX+i ].bc_type & BC_SOLID_NODE)) { *( force ) += WM*vx[2]*psi[jp][i ]; *( force+1) += WM*vy[2]*psi[jp][i ]; } /* 3 */ if( !( lattice->bc[subs][ j *LX+in].bc_type & BC_SOLID_NODE)) { *( force ) += WM*vx[3]*psi[j ][in]; *( force+1) += WM*vy[3]*psi[j ][in]; } /* 4 */ if( !( lattice->bc[subs][ jn*LX+i ].bc_type & BC_SOLID_NODE)) { *( force ) += WM*vx[4]*psi[jn][i ]; *( force+1) += WM*vy[4]*psi[jn][i ]; } /* 5 */ if( !( lattice->bc[subs][ jp*LX+ip].bc_type & BC_SOLID_NODE)) { *( force ) += WD*vx[5]*psi[jp][ip]; *( force+1) += WD*vy[5]*psi[jp][ip]; } /* 6 */ if( !( lattice->bc[subs][ jp*LX+in].bc_type & BC_SOLID_NODE)) { *( force ) += WD*vx[6]*psi[jp][in]; *( force+1) += WD*vy[6]*psi[jp][in]; } /* 7 */ if( !( lattice->bc[subs][ jn*LX+in].bc_type & BC_SOLID_NODE)) { *( force ) += WD*vx[7]*psi[jn][in]; *( force+1) += WD*vy[7]*psi[jn][in]; } /* 8 */ if( !( lattice->bc[subs][ jn*LX+ip].bc_type & BC_SOLID_NODE)) { *( force ) += WD*vx[8]*psi[jn][ip]; *( force+1) += WD*vy[8]*psi[jn][ip]; } *( force ) = -lattice->param.G*psi[j][i]*( *(force )); *( force+1) = -lattice->param.G*psi[j][i]*( *(force+1)); } /* if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) */ else { *( force ) = 0.; *( force+1) = 0.; } force += ( sizeof( struct force_struct)/8); } /* for( i=0; i<LX; i++) */ } /* for( j=0; j<LY; j++) */ for( j=0; j<LY; j++) { free( psi[j]); } free( psi); } /* void compute_phase_force( lattice_ptr lattice) */ // }}} #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ // C O M P U T E _ D O U B L E _ F L U I D _ S O L I D _ F O R C E {{{ //############################################################################## // Eq. 20 of Martys and Chen, 1996 void compute_double_fluid_solid_force( lattice_ptr lattice) { // Declare local variables. double sum_x, sum_y; int x, y, xn, yn, xp, yp; int subs; int LX = lattice->param.LX; int LY = lattice->param.LY; //printf("BING: compute_double_fluid_solid_force()\n"); //printf("SFORCE: %f %f \n", // lattice->param.Gads[0], // lattice->param.Gads[1] ); for( y = 0; y < LY; y++) { yp = ( y<LY-1)?( y+1):( 0 ); yn = ( y>0 )?( y-1):( LY-1); for( x = 0; x < LX; x++) { xp = ( x<LX-1)?( x+1):( 0 ); xn = ( x>0 )?( x-1):( LX-1); //if( !( lattice->bc[0][ y*LX + x].bc_type & BC_SOLID_NODE)) if( is_not_solid_node( lattice, /*subs*/0, IJ2N( x, y))) { sum_x=0.; sum_y=0.; // neighbor 1 //if( b[y][xp]) //if( lattice->bc[0][ y*LX + xp].bc_type & BC_SOLID_NODE) if( is_solid_node( lattice, /*subs*/0, IJ2N( xp, y))) { sum_x = sum_x + WM*vx[1] ; sum_y = sum_y + WM*vy[1] ; //printf("SFORCE 1: sum_x sum_y %f %f\n", sum_x, sum_y); } // neighbor 2 //if( b[yp][x]) //if( lattice->bc[0][ yp*LX + x].bc_type & BC_SOLID_NODE) if( is_solid_node( lattice, /*subs*/0, IJ2N( x, yp))) { sum_x = sum_x + WM*vx[2] ; sum_y = sum_y + WM*vy[2] ; //printf("SFORCE 2: sum_x sum_y %f %f\n", sum_x, sum_y); } // neighbor 3 //if( b[y][xn]) //if( lattice->bc[0][ y*LX + xn].bc_type & BC_SOLID_NODE) if( is_solid_node( lattice, /*subs*/0, IJ2N( xn, y))) { sum_x = sum_x + WM*vx[3] ; sum_y = sum_y + WM*vy[3] ; //printf("SFORCE 3: sum_x sum_y %f %f\n", sum_x, sum_y); } // neighbor 4 //if( b[yn][x]) //if( lattice->bc[0][ yn*LX + x].bc_type & BC_SOLID_NODE) if( is_solid_node( lattice, /*subs*/0, IJ2N( x, yn))) { sum_x = sum_x + WM*vx[4] ; sum_y = sum_y + WM*vy[4] ; //printf("SFORCE 4: sum_x sum_y %f %f\n", sum_x, sum_y); } // neighbor 5 //if( b[yp][xp]) //if( lattice->bc[0][ yp*LX + xp].bc_type & BC_SOLID_NODE) if( is_solid_node( lattice, /*subs*/0, IJ2N( xp, yp))) { sum_x = sum_x + WD*vx[5] ; sum_y = sum_y + WD*vy[5] ; //printf("SFORCE 5: sum_x sum_y %f %f\n", sum_x, sum_y); } // neighbor 6 //if( b[yp][xn]) //if( lattice->bc[0][ yp*LX + xn].bc_type & BC_SOLID_NODE) if( is_solid_node( lattice, /*subs*/0, IJ2N( xn, yp))) { sum_x = sum_x + WD*vx[6] ; sum_y = sum_y + WD*vy[6] ; //printf("SFORCE 6: sum_x sum_y %f %f\n", sum_x, sum_y); } // neighbor 7 //if( b[yn][xn]) //if( lattice->bc[0][ yn*LX + xn].bc_type & BC_SOLID_NODE) if( is_solid_node( lattice, /*subs*/0, IJ2N( xn, yn))) { sum_x = sum_x + WD*vx[7] ; sum_y = sum_y + WD*vy[7] ; //printf("SFORCE 7: sum_x sum_y %f %f\n", sum_x, sum_y); } // neighbor 8 //if( b[yn][xp]) //if( lattice->bc[0][ yn*LX + xp].bc_type & BC_SOLID_NODE) if( is_solid_node( lattice, /*subs*/0, IJ2N( xp, yn))) { sum_x = sum_x + WD*vx[8] ; sum_y = sum_y + WD*vy[8] ; //printf("SFORCE 8: sum_x sum_y %f %f\n", sum_x, sum_y); } for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { if( lattice->macro_vars[subs][IJ2N(x,y)].rho != 0.) { lattice->force[ subs][ IJ2N(x,y)].sforce[0] = -lattice->param.Gads[subs]*sum_x; lattice->force[ subs][ IJ2N(x,y)].sforce[1] = -lattice->param.Gads[subs]*sum_y; if( 0 &&( lattice->force[subs][ IJ2N(x,y)].sforce[0]!=0. ||lattice->force[subs][ IJ2N(x,y)].sforce[1]!=0. ) ) { printf("SFORCE: %f %f\n", lattice->force[subs][ IJ2N(x,y)].sforce[0], lattice->force[subs][ IJ2N(x,y)].sforce[1] ); } } else { lattice->force[ subs][ IJ2N(x,y)].sforce[0] = 0.; lattice->force[ subs][ IJ2N(x,y)].sforce[1] = 0.; } } } /* if( !obst[y][x]) */ if( 0 &&( lattice->force[ 0][ IJ2N(x,y)].sforce[0]!=0. ||lattice->force[ 0][ IJ2N(x,y)].sforce[1]!=0. ||lattice->force[ 1][ IJ2N(x,y)].sforce[0]!=0. ||lattice->force[ 1][ IJ2N(x,y)].sforce[1]!=0. ) ) { printf("SFORCE (%d,%d): %f %f %f %f\n", x,y, lattice->force[ 0][ IJ2N(x,y)].sforce[0], lattice->force[ 0][ IJ2N(x,y)].sforce[1], lattice->force[ 1][ IJ2N(x,y)].sforce[0], lattice->force[ 1][ IJ2N(x,y)].sforce[1] ); } } /* for( x = 1; x <= LX; x++) */ } /* for( y = 1; y <= LY; y++) */ } /* void compute_double_fluid_solid_force( lattice_ptr lattice) */ // }}} // C O M P U T E _ S I N G L E _ F L U I D _ S O L I D _ F O R C E {{{ //############################################################################## // Eq. 20 of Martys and Chen, 1996 void compute_single_fluid_solid_force( lattice_ptr lattice, int subs) { // Declare local variables. double sum_x, sum_y; int x, y, xn, yn, xp, yp; int LX = lattice->param.LX; int LY = lattice->param.LY; int i, j, si, sj, ei, ej; int n; double **psi; double *rho; psi = ( double**)malloc( LY*sizeof(double*)); for( j=0; j<LY; j++) { psi[j] = ( double*)malloc( LX*sizeof(double)); } // Initialize psi. for( j=0; j<LY; j++) { for( i=0; i<LX; i++) { psi[j][i] = 0.; } } if( lattice->periodic_y[subs]) { sj = 0; ej = LY-1; rho = &( lattice->macro_vars[subs][0].rho); } else { sj = 1; ej = LY-2; rho = &( lattice->macro_vars[subs][LX].rho); } for( j=sj; j<=ej; j++) { n = j*LX; for( i=0; i<LX; i++, n++) { if( *rho != 0 && !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { psi[j][i] = 4.*exp(-200./(*rho)); } else { psi[j][i] = 0.; } rho+=3; } /* for( i=0; i<LX; i++) */ } /* for( j=0; j<LY; j++) */ //(MOSIX) write(6,*) "Sforce", LX,LY //rho = &( lattice->macro_vars[subs][0].rho); for( y = 0; y < LY; y++) { yp = ( y<LY-1)?( y+1):( 0 ); yn = ( y>0 )?( y-1):( LY-1); for( x = 0; x < LX; x++)//, rho+=3) { xp = ( x<LX-1)?( x+1):( 0 ); xn = ( x>0 )?( x-1):( LX-1); if( !( lattice->bc[0][ y*LX + x].bc_type & BC_SOLID_NODE)) { sum_x=0.; sum_y=0.; // neighbor 1 //if( b[y][xp]) if( lattice->bc[0][ y*LX + xp].bc_type & BC_SOLID_NODE) { sum_x = WM*vx[1] ; sum_y = WM*vy[1] ; } // neighbor 2 //if( b[yp][x]) if( lattice->bc[0][ yp*LX + x].bc_type & BC_SOLID_NODE) { sum_x = sum_x + WM*vx[2] ; sum_y = sum_y + WM*vy[2] ; } // neighbor 3 //if( b[y][xn]) if( lattice->bc[0][ y*LX + xn].bc_type & BC_SOLID_NODE) { sum_x = sum_x + WM*vx[3] ; sum_y = sum_y + WM*vy[3] ; } // neighbor 4 //if( b[yn][x]) if( lattice->bc[0][ yn*LX + x].bc_type & BC_SOLID_NODE) { sum_x = sum_x + WM*vx[4] ; sum_y = sum_y + WM*vy[4] ; } // neighbor 5 //if( b[yp][xp]) if( lattice->bc[0][ yp*LX + xp].bc_type & BC_SOLID_NODE) { sum_x = sum_x + WD*vx[5] ; sum_y = sum_y + WD*vy[5] ; } // neighbor 6 //if( b[yp][xn]) if( lattice->bc[0][ yp*LX + xn].bc_type & BC_SOLID_NODE) { sum_x = sum_x + WD*vx[6] ; sum_y = sum_y + WD*vy[6] ; } // neighbor 7 //if( b[yn][xn]) if( lattice->bc[0][ yn*LX + xn].bc_type & BC_SOLID_NODE) { sum_x = sum_x + WD*vx[7] ; sum_y = sum_y + WD*vy[7] ; } // neighbor 8 //if( b[yn][xp]) if( lattice->bc[0][ yn*LX + xp].bc_type & BC_SOLID_NODE) { sum_x = sum_x + WD*vx[8] ; sum_y = sum_y + WD*vy[8] ; } if( lattice->macro_vars[subs][y*LX+x].rho != 0) { lattice->force[ subs][ y*LX+x].sforce[0] = -lattice->param.Gads[subs]*psi[y][x]*sum_x;///(*rho); lattice->force[ subs][ y*LX+x].sforce[1] = -lattice->param.Gads[subs]*psi[y][x]*sum_y;///(*rho); } else { lattice->force[ subs][ y*LX+x].sforce[0] = 0.; lattice->force[ subs][ y*LX+x].sforce[1] = 0.; } } /* if( !obst[y][x]) */ } /* for( x = 1; x <= LX; x++) */ } /* for( y = 1; y <= LY; y++) */ for( j=0; j<LY; j++) { free( psi[j]); } free( psi); } /* void compute_single_fluid_solid_force( lattice_ptr lattice) */ // }}} #endif /* NON_LOCAL_FORCES */ //COMPUTE_MAX_F {{{1 void compute_max_f( lattice_ptr lattice, double *fptr, double *max_f, int subs) { int n, a; *max_f = 0.; for( n=0; n<lattice->NumNodes; n++) { if( 1)//is_not_solid_node( lattice, subs, n)) { for( a=0; a<9; a++) { if( fptr[a] > *max_f) { *max_f = fptr[a]; } } } fptr += ( sizeof(struct pdf_struct)/8); } } /* void compute_max_f( lattice_ptr lattice, double *fptr, double *max_f) */ // }}} // COMPUTE_MAX_F0 {{{1 void compute_max_f0( lattice_ptr lattice, double *fptr, double *max_f, int subs) { int n, a; *max_f = 0.; for( n=0; n<lattice->NumNodes; n++) { if( 1)//is_not_solid_node( lattice, subs, n)) { if( fptr[a] > *max_f) { *max_f = fptr[a]; } } fptr += ( sizeof(struct pdf_struct)/8); } } /* void compute_max_f0( lattice_ptr lattice, double *fptr, double *max_f) */ // }}} // COMPUTE_MIN_F0 {{{1 void compute_min_f0( lattice_ptr lattice, double *fptr, double *min_f, int subs) { int n, a; compute_max_f0( lattice, fptr, min_f, subs); for( n=0; n<lattice->NumNodes; n++) { if( 1)//is_not_solid_node( lattice, subs, n)) { if( fptr[a] < *min_f) { *min_f = fptr[a]; } } fptr += ( sizeof(struct pdf_struct)/8); } } /* void compute_min_f0( lattice_ptr lattice, double *fptr, double *min_f) */ // }}} // COMPUTE_MAX_F1234 {{{1 void compute_max_f1234( lattice_ptr lattice, double *fptr, double *max_f, int subs) { int n, a; *max_f = 0.; for( n=0; n<lattice->NumNodes; n++) { if( 1)//is_not_solid_node( lattice, subs, n)) { for( a=1; a<=4; a++) { if( fptr[a] > *max_f) { *max_f = fptr[a]; } } } fptr += ( sizeof(struct pdf_struct)/8); } } /* void compute_max_f1234( lattice_ptr lattice, double *fptr, ...) */ // }}} // COMPUTE_MAX_F5678 {{{1 void compute_max_f5678( lattice_ptr lattice, double *fptr, double *max_f, int subs) { int n, a; *max_f = 0.; for( n=0; n<lattice->NumNodes; n++) { if( 1)//is_not_solid_node( lattice, subs, n)) { for( a=5; a<=8; a++) { if( fptr[a] > *max_f) { *max_f = fptr[a]; } } } fptr += ( sizeof(struct pdf_struct)/8); } } /* void compute_max_f5678( lattice_ptr lattice, double *fptr, ...) */ // }}} // COMPUTE_MAX_RHO {{{1 void compute_max_rho( lattice_ptr lattice, double *max_rho, int subs) { int n; *max_rho = 0.; for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { if( ( lattice->macro_vars[subs][n].rho) > *max_rho) { *max_rho = ( lattice->macro_vars[subs][n].rho); } } } process_reduce_double_max( lattice, max_rho); } /* void compute_max_rho( lattice_ptr lattice, double *max_rho, int subs) */ // }}} // COMPUTE_MIN_RHO {{{1 void compute_min_rho( lattice_ptr lattice, double *min_rho, int subs) { int n; compute_max_rho( lattice, min_rho, subs); for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { if( ( lattice->macro_vars[subs][n].rho) < *min_rho) { *min_rho = ( lattice->macro_vars[subs][n].rho); } } } process_reduce_double_min( lattice, min_rho); } /* void compute_min_rho( lattice_ptr lattice, double *min_rho, int subs) */ // }}} // COMPUTE_AVE_RHO {{{1 void compute_ave_rho( lattice_ptr lattice, double *ave_rho, int subs) { int n, nn; *ave_rho = 0.; nn = 0; for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { *ave_rho += ( lattice->macro_vars[subs][n].rho); nn++; } } process_reduce_double_sum( lattice, ave_rho); process_reduce_int_sum( lattice, &nn); if( nn != 0) { *ave_rho = (*ave_rho) / nn;} } /* void compute_ave_rho( lattice_ptr lattice, double *ave_rho, int subs) */ // }}} // COMPUTE_MAX_U {{{1 void compute_max_u( lattice_ptr lattice, double *max_u, int subs) { int n; *max_u = 0.; *(max_u+1) = 0.; for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { if( fabs( lattice->macro_vars[subs][n].u[0]) > *(max_u)) { *max_u = fabs( lattice->macro_vars[subs][n].u[0]); } if( fabs( lattice->macro_vars[subs][n].u[1]) > *(max_u+1)) { *(max_u+1) = fabs( lattice->macro_vars[subs][n].u[1]); } } } process_reduce_double_max( lattice, max_u+0); process_reduce_double_max( lattice, max_u+1); } /* void compute_max_u( lattice_ptr lattice, double *max_u, int subs) */ // }}} // COMPUTE_MAX_U_ALL {{{1 void compute_max_u_all( lattice_ptr lattice, double *max_u, int subs) { int n; double rho, u, u_x, u_y; *(max_u+0) = 0.; *(max_u+1) = 0.; *(max_u+2) = 0.; *(max_u+3) = 0.; *(max_u+4) = 0.; for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { rho = lattice->macro_vars[subs][n].rho; u_x = lattice->macro_vars[subs][n].u[0]; u_y = lattice->macro_vars[subs][n].u[1]; u = sqrt(u_x*u_x+u_y*u_y); if( u > *(max_u+0)) { *(max_u+0) = u; } if( fabs( u_x) > *(max_u+1)) { *(max_u+1) = fabs( u_x); } if( fabs( u_y) > *(max_u+2)) { *(max_u+2) = fabs( u_y); } if( ( u_x) > *(max_u+3)) { *(max_u+3) = ( u_x); } if( ( u_y) > *(max_u+4)) { *(max_u+4) = ( u_y); } } } } /* void compute_max_u_all( lattice_ptr lattice, double *max_u, int subs) */ // }}} // COMPUTE_MIN_U {{{1 void compute_min_u( lattice_ptr lattice, double *min_u, int subs) { int n; compute_max_u( lattice, min_u, subs); //compute_max_u( lattice, min_u+1, subs); for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { if( fabs( lattice->macro_vars[subs][n].u[0]) < *(min_u)) { *min_u = fabs( lattice->macro_vars[subs][n].u[0]); } if( fabs( lattice->macro_vars[subs][n].u[1]) < *(min_u+1)) { *(min_u+1) = fabs( lattice->macro_vars[subs][n].u[1]); } } } process_reduce_double_min( lattice, min_u+0); process_reduce_double_min( lattice, min_u+1); } /* void compute_min_u( lattice_ptr lattice, double *min_u) */ // }}} // COMPUTE_MIN_U_ALL {{{1 void compute_min_u_all( lattice_ptr lattice, double *min_u, int subs) { int n; double rho, u, u_x, u_y; compute_max_u_all( lattice, min_u, subs); for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { rho = lattice->macro_vars[subs][n].rho; u_x = lattice->macro_vars[subs][n].u[0]; u_y = lattice->macro_vars[subs][n].u[1]; u = sqrt(u_x*u_x+u_y*u_y); if( u < *(min_u+0)) { *(min_u+0) = u; } if( fabs( u_x) < *(min_u+1)) { *(min_u+1) = fabs( u_x); } if( fabs( u_y) < *(min_u+2)) { *(min_u+2) = fabs( u_y); } if( ( u_x) < *(min_u+3)) { *(min_u+3) = ( u_x); } if( ( u_y) < *(min_u+4)) { *(min_u+4) = ( u_y); } } } } /* void compute_min_u_all( lattice_ptr lattice, double *min_u) */ // }}} // COMPUTE_AVE_U {{{1 void compute_ave_u( lattice_ptr lattice, double *ave_u, int subs) { int n, nn; *(ave_u+0) = 0.; *(ave_u+1) = 0.; nn = 0; for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { *(ave_u+0) += lattice->macro_vars[subs][n].u[0]; *(ave_u+1) += lattice->macro_vars[subs][n].u[1]; nn++; } } process_reduce_double_sum( lattice, ave_u+0); process_reduce_double_sum( lattice, ave_u+1); process_reduce_int_sum( lattice, &nn); if( nn != 0) { *(ave_u+0) = (*(ave_u+0))/nn; *(ave_u+1) = (*(ave_u+1))/nn; } } /* void compute_ave_u( lattice_ptr lattice, double *ave_u, int subs) */ // }}} // COMPUTE_AVE_U_ALL {{{1 void compute_ave_u_all( lattice_ptr lattice, double *ave_u, int subs) { int n, nn; double rho, u_x, u_y; *(ave_u+0) = 0.; *(ave_u+1) = 0.; *(ave_u+2) = 0.; *(ave_u+3) = 0.; *(ave_u+4) = 0.; nn = 0; for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { rho = lattice->macro_vars[subs][n].rho; u_x = lattice->macro_vars[subs][n].u[0]; u_y = lattice->macro_vars[subs][n].u[1]; *(ave_u+0) += sqrt(u_x*u_x+u_y*u_y); *(ave_u+1) += fabs(u_x); *(ave_u+2) += fabs(u_y); *(ave_u+3) += u_x; *(ave_u+4) += u_y; nn++; } } if( nn != 0) { *(ave_u+0) = (*(ave_u+0))/nn; *(ave_u+1) = (*(ave_u+1))/nn; *(ave_u+2) = (*(ave_u+2))/nn; *(ave_u+3) = (*(ave_u+3))/nn; *(ave_u+4) = (*(ave_u+4))/nn; } } /* void compute_ave_u( lattice_ptr lattice, double *ave_u, int subs) */ // }}} // COMPUTE_FLUX {{{1 void compute_flux( lattice_ptr lattice, double *flux, int subs) { int n, nn; double rho, u_x, u_y; *(flux+0) = 0.; *(flux+1) = 0.; *(flux+2) = 0.; nn = 0; for( n=0; n<lattice->NumNodes; n++) { rho = lattice->macro_vars[subs][n].rho; u_x = lattice->macro_vars[subs][n].u[0]; u_y = lattice->macro_vars[subs][n].u[1]; if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { *(flux+0) += rho*sqrt(u_x*u_x+u_y*u_y); *(flux+1) += rho*u_x; *(flux+2) += rho*u_y; nn++; } } if( nn != 0) { *(flux+0) = (*(flux+0))/nn; *(flux+1) = (*(flux+1))/nn; *(flux+2) = (*(flux+2))/nn; } } /* void compute_flux( lattice_ptr lattice, double *flux, int subs) */ // }}} #if NON_LOCAL_FORCES // COMPUTE_MAX_SFORCE {{{1 void compute_max_force( lattice_ptr lattice, double *max_force, int subs) { int n; *max_force = 0.; *(max_force+1) = 0.; for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { if( fabs( lattice->force[subs][ n].force[0]) > *(max_force)) { *max_force = fabs( lattice->macro_vars[subs][n].u[0]); } if( fabs( lattice->force[subs][ n].force[1]) > *(max_force+1)) { *(max_force+1) = fabs( lattice->macro_vars[subs][n].u[1]); } } } } /* void compute_max_u( lattice_ptr lattice, double *max_u, int subs) */ // }}} // COMPUTE_MAX_SFORCE {{{1 void compute_max_sforce( lattice_ptr lattice, double *max_sforce, int subs) { int n; *max_sforce = 0.; *(max_sforce+1) = 0.; for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[subs][n].bc_type & BC_SOLID_NODE)) { if( fabs( lattice->force[subs][ n].sforce[0]) > *(max_sforce)) { *max_sforce = fabs( lattice->macro_vars[subs][n].u[0]); } if( fabs( lattice->force[subs][ n].sforce[1]) > *(max_sforce+1)) { *(max_sforce+1) = fabs( lattice->macro_vars[subs][n].u[1]); } } } } /* void compute_max_u( lattice_ptr lattice, double *max_u, int subs) */ // }}} #endif #if STORE_U_COMPOSITE // COMPUTE_MAX_UPR {{{1 void compute_max_upr( lattice_ptr lattice, double *max_u) { int n; *max_u = 0.; *(max_u+1) = 0.; for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) { if( fabs( lattice->upr[n].u[0]) > *(max_u)) { *max_u = fabs( lattice->upr[n].u[0]); } if( fabs( lattice->upr[n].u[1]) > *(max_u+1)) { *(max_u+1) = fabs( lattice->upr[n].u[1]); } } } } /* void compute_max_upr( lattice_ptr lattice, double *max_u) */ // }}} // COMPUTE_MIN_UPR {{{1 void compute_min_upr( lattice_ptr lattice, double *min_u) { int n; compute_max_upr( lattice, min_u); for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) { if( fabs( lattice->upr[n].u[0]) < *(min_u)) { *min_u = fabs( lattice->upr[n].u[0]); } if( fabs( lattice->upr[n].u[1]) < *(min_u+1)) { *(min_u+1) = fabs( lattice->upr[n].u[1]); } } } } /* void compute_min_upr( lattice_ptr lattice, double *min_u) */ // }}} // COMPUTE_AVE_UPR {{{1 void compute_ave_upr( lattice_ptr lattice, double *ave_u) { int n, nn; *ave_u = 0.; *(ave_u+1) = 0.; nn = 0; for( n=0; n<lattice->NumNodes; n++) { if( !( lattice->bc[0][n].bc_type & BC_SOLID_NODE)) { *ave_u += fabs( lattice->upr[n].u[0]); *(ave_u+1) += fabs( lattice->upr[n].u[1]); nn++; } } if( nn != 0) { *ave_u = (*ave_u)/nn; *(ave_u+1) = (*(ave_u+1))/nn; } } /* void compute_ave_upr( lattice_ptr lattice, double *ave_u) */ // }}} #endif /* STORE_U_COMPOSITE */ // COMPUTE_VORTICITY {{{1 void compute_vorticity( lattice_ptr lattice, int i, int j, int n, double *vor, int subs) { double duyx, duxy; int nn[5]; // Indices of neighbors; int LX=lattice->param.LX, LY=lattice->param.LY; int ip, in, jp, jn; ip = ( i<LX-1)?(i+1):(0 ); in = ( i>0 )?(i-1):(LX-1); jp = ( j<LY-1)?(j+1):(0 ); jn = ( j>0 )?(j-1):(LY-1); nn[1] = j *LX + ip; nn[2] = jp*LX + i ; nn[3] = j *LX + in; nn[4] = jn*LX + i ; // NOTE: Assuming dx=1 . TODO: Generalize dx? // Derivative of uy wrt x. if( lattice->bc[subs][nn[1]].bc_type == BC_FLUID_NODE && lattice->bc[subs][nn[3]].bc_type == BC_FLUID_NODE) { // Forward difference. duyx = lattice->macro_vars[subs][nn[1]].u[1] - lattice->macro_vars[subs][n].u[1]; } //else if( lattice->bc[subs][nn[3]].bc_type == BC_FLUID_NODE) //{ // // Backward difference. // duyx = lattice->macro_vars[subs][n].u[1] // - lattice->macro_vars[subs][nn[3]].u[1]; //} else { duyx = 0.; } //printf("compute_vorticity() -- " // "n=%d, (i,j)=(%d,%d), duyx=%f, " // "nn1 = %d, nn3 = %d," // "bc1 = %d, bc3 = %d" // "\n", // n, i, j, duyx, // nn[1], nn[3], // lattice->bc[subs][nn[1]].bc_type, // lattice->bc[subs][nn[3]].bc_type); // Derivative of ux wrt y. if( lattice->bc[subs][nn[2]].bc_type == BC_FLUID_NODE && lattice->bc[subs][nn[4]].bc_type == BC_FLUID_NODE) { // Forward difference. duxy = lattice->macro_vars[subs][nn[2]].u[0] - lattice->macro_vars[subs][n].u[0]; } //else if( lattice->bc[subs][nn[4]].bc_type == BC_FLUID_NODE) //{ // // Backward difference. // duxy = lattice->macro_vars[subs][n].u[0] // - lattice->macro_vars[subs][nn[4]].u[0]; //} else { duxy = 0.; } if( duxy*duyx != 0.) { *vor = duyx - duxy; } else { *vor = 0.; } } /* void compute_vorticity( lattice_ptr lattice, int i, int j, int n, ... */ // }}} // COMPUTE_MAX_VOR {{{1 void compute_max_vor( lattice_ptr lattice, double *max_vor_p, double *max_vor_n, int subs) { int n; double vor; int nnz; *max_vor_p = 0.; *max_vor_n = 0.; nnz = 0; for( n=0; n<=lattice->NumNodes; n++) { if( lattice->bc[subs][n].bc_type == BC_FLUID_NODE) { compute_vorticity( lattice, n%lattice->param.LX, n/lattice->param.LX, n, &vor, subs ); if( vor != 0.) { nnz++;} if( vor > *max_vor_p) { *max_vor_p = vor; } /* if( vor > *max_vor_p) */ else if( vor < *max_vor_n) { *max_vor_n = vor; } /* if( vor > *max_vor_p) */ } /* if( lattice->bc[subs][n].bc_type == 0) */ } /* for( n=0; n<=lattice->NumNodes; n++) */ #if 0 && VERBOSITY_LEVEL > 0 printf("compute_max_vor() -- nnz = %d. nnz/NumNodes = %f\n", nnz, (double)nnz/(double)lattice->NumNodes); #endif /* 0 && VERBOSITY_LEVEL > 0 */ } /* void compute_max_vor( lattice_ptr lattice, double *max_vor_p, ... */ // }}} // COMPUTE_AVE_VOR {{{1 void compute_ave_vor( lattice_ptr lattice, double *ave_vor_p, double *ave_vor_n, int subs) { int n; double vor; int nnz; int num_p; int num_n; *ave_vor_p = 0.; *ave_vor_n = 0.; nnz = 0; num_p = 0; num_n = 0; for( n=0; n<=lattice->NumNodes; n++) { if( lattice->bc[subs][n].bc_type == BC_FLUID_NODE) { compute_vorticity( lattice, n%lattice->param.LX, n/lattice->param.LX, n, &vor, subs ); if( vor != 0.) { nnz++;} if( vor > *ave_vor_p) { *ave_vor_p += vor; num_p++; } /* if( vor > *ave_vor_p) */ else if( vor < *ave_vor_n) { *ave_vor_n += vor; num_n++; } /* if( vor > *ave_vor_p) */ } /* if( lattice->bc[subs][n].bc_type == 0) */ } /* for( n=0; n<=lattice->NumNodes; n++) */ if( num_p > 0) { *ave_vor_p /= num_p;} if( num_n > 0) { *ave_vor_n /= num_n;} #if 0 && VERBOSITY_LEVEL > 0 printf("compute_ave_vor() -- nnz = %d. nnz/NumNodes = %f\n", nnz, (double)nnz/(double)lattice->NumNodes); #endif /* VERBOSITY_LEVEL > 0 */ } /* void compute_ave_vor( lattice_ptr lattice, double *ave_vor_p, ... */ // }}} //############################################################################## // vim: foldmethod=syntax:foldlevel=0
111pjb-one
src/compute.c
C
gpl3
86,515
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // lbmpi.c // // - Note that this is adapted from a previous implementation in an // old mcmp code from last summer (2004). // void lbmpi_construct( lbmpi_ptr lbmpi, lattice_ptr lattice, int argc, char **argv) { int i, j; int ierr; // Routine inititialization calls. MPI_Init( &argc, &argv); MPI_Comm_size( MPI_COMM_WORLD, &lbmpi->NumProcs); MPI_Comm_rank( MPI_COMM_WORLD, &lbmpi->ProcID); // Determine coordinates (PX,PY) of subdomain in // PX-by-PY array of subdomains. lbmpi->PX = lbmpi->ProcID%lbmpi->NPX; lbmpi->PY = (int)floor((double)lbmpi->ProcID/(double)lbmpi->NPX); // Determine ID of processes with adjacent subdomains. lbmpi->NorthID = lbmpi->NPX*((lbmpi->PY+1)%lbmpi->NPY) + (lbmpi->PX); lbmpi->SouthID = lbmpi->NPX*((lbmpi->PY-1+lbmpi->NPY)%lbmpi->NPY) + (lbmpi->PX); lbmpi->EastID = lbmpi->NPX*((lbmpi->PY)) + (lbmpi->PX+1)%lbmpi->NPX; lbmpi->WestID = lbmpi->NPX*((lbmpi->PY)) + (lbmpi->PX-1+lbmpi->NPX)%lbmpi->NPX; // Say "hi". printf( "Proc %d (%d,%d) of %d (%d-by-%d) says, \"Hi!\" " "// (N,S,E,W) = (%d,%d,%d,%d)\n", lbmpi->ProcID, lbmpi->PX, lbmpi->PY, lbmpi->NumProcs, lbmpi->NPX, lbmpi->NPY, lbmpi->NorthID, lbmpi->SouthID, lbmpi->EastID, lbmpi->WestID ); // Allocate space for datatypes. lbmpi_allocate_datatypes( lbmpi, lattice); // Create data type structure MPI_South2North. // // - This will be used in the communication step after // streaming to send/recv elements from north subdomains // to south subdomains. // printf("\n%d: Making MPI_South2North... \n", lbmpi_get_ProcID(lbmpi)); MPI_Address( get_ftemp_ptr( lattice, /*subs*/0, /*j*/get_sj(lattice), /*i*/get_si(lattice), /*a*/0), (MPI_Aint *)lbmpi_get_Index0_ptr(lbmpi)); // Acquire memory addresses of all the elements. With these // we will compute the indices needed by MPI_Type_struct // below. for(i=get_si(lattice); i<=get_ei(lattice); i++) { MPI_Address( get_ftemp_ptr(lattice,0,get_sj(lattice),i,2), &( lbmpi->AddrsNS[ 3*(i-0)+0]) ); MPI_Address( get_ftemp_ptr(lattice,0,get_sj(lattice),i,5), &( lbmpi->AddrsNS[ 3*(i-0)+1]) ); MPI_Address( get_ftemp_ptr(lattice,0,get_sj(lattice),i,6), &( lbmpi->AddrsNS[ 3*(i-0)+2]) ); } /* for(i=1; i<=get_LX(lattice); i++) */ // Stuff needed by MPI_Type_struct. for(i=1; i<=get_LX(lattice); i++) { // All the block lengths are one (1). lbmpi->BlockLengthsNS[ 3*(i-1)+0] = 1; lbmpi->BlockLengthsNS[ 3*(i-1)+1] = 1; lbmpi->BlockLengthsNS[ 3*(i-1)+2] = 1; // Compute offsets from the first element. lbmpi->IndicesNS[ 3*(i-1)+0] = lbmpi->AddrsNS[ 3*(i-1)+0]-lbmpi->AddrsNS[0]; lbmpi->IndicesNS[ 3*(i-1)+1] = lbmpi->AddrsNS[ 3*(i-1)+1]-lbmpi->AddrsNS[0]; lbmpi->IndicesNS[ 3*(i-1)+2] = lbmpi->AddrsNS[ 3*(i-1)+2]-lbmpi->AddrsNS[0]; // All the types are doubles. lbmpi->TypesNS[ 3*(i-1)+0] = MPI_DOUBLE; lbmpi->TypesNS[ 3*(i-1)+1] = MPI_DOUBLE; lbmpi->TypesNS[ 3*(i-1)+2] = MPI_DOUBLE; } /* for(i=1; i<=get_LX(lattice); i++) */ ierr = MPI_Type_struct( /* int count */ 3*get_LX(lattice), /* int blocklens[] */ lbmpi->BlockLengthsNS, /* MPI_Aint indices[] */ lbmpi->IndicesNS, /* MPI_Datatype old_types[] */ lbmpi->TypesNS, /* MPI_Datatype *newtype */ &lbmpi->MPI_South2North ); ierr = MPI_Type_commit( /* MPI_Datatype *datatype */ &lbmpi->MPI_South2North ); printf("\n%d: Done making MPI_South2North\n", lbmpi_get_ProcID(lbmpi)); #if 1 // Output the indices for inspection... sprintf( lbmpi->iobuf, " "); for(i=1; i<=get_LX(lattice); i++) { sprintf( lbmpi->iobuf, "%s%d %d %d ", lbmpi->iobuf, lbmpi->IndicesNS[ 3*(i-1)+0], lbmpi->IndicesNS[ 3*(i-1)+1], lbmpi->IndicesNS[ 3*(i-1)+2] ); } printf("\n%d: MPI_South2North { %s }\n", lbmpi_get_ProcID(lbmpi), lbmpi->iobuf); #endif // Create data type structure MPI_North2South. // // - This will be used in the communication step after // streaming to send/recv elements from south subdomains // to north subdomains. // printf("\n%d: Making MPI_North2South... \n", lbmpi_get_ProcID(lbmpi)); MPI_Address( get_ftemp_ptr( lattice, /*subs*/0, /*j*/get_ej(lattice), /*i*/get_si(lattice), /*a*/4), (MPI_Aint *)lbmpi_get_Index0_ptr(lbmpi)); // Acquire memory addresses of all the elements. With these // we will compute the indices needed by MPI_Type_struct // below. for(i=get_si(lattice); i<=get_ei(lattice); i++) { MPI_Address( get_ftemp_ptr(lattice,0,get_ej(lattice),i,4), &( lbmpi->AddrsNS[ 3*(i-0)+0])); MPI_Address( get_ftemp_ptr(lattice,0,get_ej(lattice),i,7), &( lbmpi->AddrsNS[ 3*(i-0)+1])); MPI_Address( get_ftemp_ptr(lattice,0,get_ej(lattice),i,8), &( lbmpi->AddrsNS[ 3*(i-0)+2])); } /* for(i=1; i<=get_LX(lattice); i++) */ // Stuff needed by MPI_Type_struct. for(i=1; i<=get_LX(lattice); i++) { // All the block lengths are one (1). lbmpi->BlockLengthsNS[ 3*(i-1)+0] = 1; lbmpi->BlockLengthsNS[ 3*(i-1)+1] = 1; lbmpi->BlockLengthsNS[ 3*(i-1)+2] = 1; // Compute offsets from the first element. lbmpi->IndicesNS[ 3*(i-1)+0] = lbmpi->AddrsNS[ 3*(i-1)+0]-lbmpi->AddrsNS[0]; lbmpi->IndicesNS[ 3*(i-1)+1] = lbmpi->AddrsNS[ 3*(i-1)+1]-lbmpi->AddrsNS[0]; lbmpi->IndicesNS[ 3*(i-1)+2] = lbmpi->AddrsNS[ 3*(i-1)+2]-lbmpi->AddrsNS[0]; // All the types are doubles. lbmpi->TypesNS[ 3*(i-1)+0] = MPI_DOUBLE; lbmpi->TypesNS[ 3*(i-1)+1] = MPI_DOUBLE; lbmpi->TypesNS[ 3*(i-1)+2] = MPI_DOUBLE; } /* for(i=1; i<=get_LX(lattice); i++) */ ierr = MPI_Type_struct( /* int count */ 3*get_LX(lattice), /* int blocklens[] */ lbmpi->BlockLengthsNS, /* MPI_Aint indices[] */ lbmpi->IndicesNS, /* MPI_Datatype old_types[] */ lbmpi->TypesNS, /* MPI_Datatype *newtype */ &lbmpi->MPI_North2South ); ierr = MPI_Type_commit( /* MPI_Datatype *datatype */ &lbmpi->MPI_North2South ); printf("\n%d: Done making MPI_North2South\n", lbmpi->ProcID); #if 1 // Output the indices for inspection... sprintf( lbmpi->iobuf, " "); for(i=1; i<=get_LX(lattice); i++) { sprintf( lbmpi->iobuf, "%s%d %d %d ", lbmpi->iobuf, lbmpi->IndicesNS[ 3*(i-1)+0], lbmpi->IndicesNS[ 3*(i-1)+1], lbmpi->IndicesNS[ 3*(i-1)+2] ); } printf("\n%d: MPI_North2South { %s }\n", lbmpi_get_ProcID(lbmpi), lbmpi->iobuf); #endif // Create data type structure MPI_East2West. // // - This will be used in the communication step after // streaming to send/recv elements from east subdomains // to west subdomains. // printf("\n%d: Making MPI_East2West... \n", lbmpi_get_ProcID(lbmpi)); //MPI_Address( &( ftemp[1][1][get_LX(lattice)][3]), &Index0); MPI_Address( get_ftemp_ptr( lattice, /*subs*/0, /*j*/get_sj(lattice), /*i*/get_ei(lattice), /*a*/3), (MPI_Aint *)lbmpi_get_Index0_ptr(lbmpi)); // Acquire memory addresses of all the elements. With these // we will compute the indices needed by MPI_Type_struct // below. for(j=get_sj(lattice); j<=get_ej(lattice); j++) { MPI_Address( get_ftemp_ptr(lattice,0,j,get_ei(lattice),3), &( lbmpi->AddrsEW[ 3*(j-0)+0])); MPI_Address( get_ftemp_ptr(lattice,0,j,get_ei(lattice),6), &( lbmpi->AddrsEW[ 3*(j-0)+1])); MPI_Address( get_ftemp_ptr(lattice,0,j,get_ei(lattice),7), &( lbmpi->AddrsEW[ 3*(j-0)+2])); } /* for(j=1; j<=get_LY(lattice); j++) */ // Stuff needed by MPI_Type_struct. for(j=get_sj(lattice); j<=get_ej(lattice); j++) { // All the block lengths are one (1). lbmpi->BlockLengthsEW[ 3*j+0] = 1; lbmpi->BlockLengthsEW[ 3*j+1] = 1; lbmpi->BlockLengthsEW[ 3*j+2] = 1; // Compute offsets from the first element. lbmpi->IndicesEW[ 3*j+0] = lbmpi->AddrsEW[ 3*j+0]-lbmpi->AddrsEW[0]; lbmpi->IndicesEW[ 3*j+1] = lbmpi->AddrsEW[ 3*j+1]-lbmpi->AddrsEW[0]; lbmpi->IndicesEW[ 3*j+2] = lbmpi->AddrsEW[ 3*j+2]-lbmpi->AddrsEW[0]; // All the types are doubles. lbmpi->TypesEW[ 3*j+0] = MPI_DOUBLE; lbmpi->TypesEW[ 3*j+1] = MPI_DOUBLE; lbmpi->TypesEW[ 3*j+2] = MPI_DOUBLE; } /* for(j=1; j<=get_LY(lattice); j++) */ ierr = MPI_Type_struct( /* int count */ 3*get_LY(lattice), /* int blocklens[] */ lbmpi->BlockLengthsEW, /* MPI_Aint indices[] */ lbmpi->IndicesEW, /* MPI_Datatype old_types[] */ lbmpi->TypesEW, /* MPI_Datatype *newtype */ &lbmpi->MPI_East2West ); ierr = MPI_Type_commit( /* MPI_Datatype *datatype */ &lbmpi->MPI_East2West ); printf("\n%d: Done making MPI_East2West\n", lbmpi_get_ProcID(lbmpi)); #if 1 // Output the indices for inspection... sprintf( lbmpi->iobuf, " "); for(j=1; j<=get_LY(lattice); j++) { sprintf( lbmpi->iobuf, "%s%d %d %d ", lbmpi->iobuf, lbmpi->IndicesEW[ 3*(j-1)+0], lbmpi->IndicesEW[ 3*(j-1)+1], lbmpi->IndicesEW[ 3*(j-1)+2] ); } printf("\n%d: MPI_East2West { %s }\n", lbmpi_get_ProcID(lbmpi), lbmpi->iobuf); #endif // Create data type structure MPI_West2East. // // - This will be used in the communication step after // streaming to send/recv elements from west subdomains // to east subdomains. // printf("\n%d: Making MPI_West2East... \n", lbmpi_get_ProcID(lbmpi)); //MPI_Address( &( ftemp[1][1][1][1]), &Index0); MPI_Address( get_ftemp_ptr( lattice, /*subs*/0, /*j*/get_sj(lattice), /*i*/get_si(lattice), /*a*/1), (MPI_Aint *)lbmpi_get_Index0_ptr(lbmpi)); // Acquire memory addresses of all the elements. With these // we will compute the indices needed by MPI_Type_struct // below. for(j=get_sj(lattice); j<=get_ej(lattice); j++) { MPI_Address( get_ftemp_ptr(lattice,0,j,get_si(lattice),1), &( lbmpi->AddrsEW[ 3*(j-1)+0])); MPI_Address( get_ftemp_ptr(lattice,0,j,get_si(lattice),5), &( lbmpi->AddrsEW[ 3*(j-1)+1])); MPI_Address( get_ftemp_ptr(lattice,0,j,get_si(lattice),8), &( lbmpi->AddrsEW[ 3*(j-1)+2])); } /* for(j=1; j<=get_LY(lattice); j++) */ // Stuff needed by MPI_Type_struct. for(j=get_sj(lattice); j<=get_ej(lattice); j++) { // All the block lengths are one (1). lbmpi->BlockLengthsEW[ 3*j+0] = 1; lbmpi->BlockLengthsEW[ 3*j+1] = 1; lbmpi->BlockLengthsEW[ 3*j+2] = 1; // Compute offsets from the first element. lbmpi->IndicesEW[ 3*j+0] = lbmpi->AddrsEW[ 3*j+0]-lbmpi->AddrsEW[0]; lbmpi->IndicesEW[ 3*j+1] = lbmpi->AddrsEW[ 3*j+1]-lbmpi->AddrsEW[0]; lbmpi->IndicesEW[ 3*j+2] = lbmpi->AddrsEW[ 3*j+2]-lbmpi->AddrsEW[0]; // All the types are doubles. lbmpi->TypesEW[ 3*j+0] = MPI_DOUBLE; lbmpi->TypesEW[ 3*j+1] = MPI_DOUBLE; lbmpi->TypesEW[ 3*j+2] = MPI_DOUBLE; } /* for(j=1; j<=get_LY(lattice); j++) */ ierr = MPI_Type_struct( /* int count */ 3*get_LY(lattice), /* int blocklens[] */ lbmpi->BlockLengthsEW, /* MPI_Aint indices[] */ lbmpi->IndicesEW, /* MPI_Datatype old_types[] */ lbmpi->TypesEW, /* MPI_Datatype *newtype */ &lbmpi->MPI_West2East ); ierr = MPI_Type_commit( /* MPI_Datatype *datatype */ &lbmpi->MPI_West2East ); printf("\n%d: Done making MPI_West2East\n", lbmpi_get_ProcID(lbmpi)); #if 1 // Output the indices for inspection... sprintf( lbmpi->iobuf, " "); //for(j=get_sj(lattice); j<=get_ej(lattice); j++) for(j=1; j<=get_LY(lattice); j++) { sprintf( lbmpi->iobuf, "%s%d %d %d ", lbmpi->iobuf, lbmpi->IndicesEW[ 3*(j-1)+0], lbmpi->IndicesEW[ 3*(j-1)+1], lbmpi->IndicesEW[ 3*(j-1)+2] ); } printf("\n%d: MPI_West2East { %s }\n", lbmpi_get_ProcID(lbmpi), lbmpi->iobuf); #endif } /* void lbmpi_construct( lbmpi_ptr lbmpi, lattice_ptr lattice, argc, argv) */ // void lbmpi_communicate( lbmpi_ptr lbmpi, lattice_ptr lattice) // // Communicate data between processes. // void lbmpi_communicate( lbmpi_ptr lbmpi, lattice_ptr lattice) { } /* void lbmpi_communicate( lbmpi_ptr lbmpi, lattice_ptr lattice) */ // void lbmpi_allocate_data_structures( lbmpi, lattice) // // Allocate datatypes for void lbmpi_allocate_datatypes( lbmpi_ptr lbmpi, lattice_ptr lattice) { //int BlockLengthsEW[3*LY]; lbmpi->BlockLengthsEW = (int*)malloc( 3*get_LY(lattice)*sizeof(int)); //MPI_Aint AddrsEW[3*LY]; lbmpi->AddrsEW = (MPI_Aint*)malloc( 3*get_LY(lattice)*sizeof(MPI_Aint)); //MPI_Aint IndicesEW[3*LY]; lbmpi->IndicesEW = (MPI_Aint*)malloc( 3*get_LY(lattice)*sizeof(MPI_Aint)); //MPI_Datatype TypesEW[3*LY]; lbmpi->TypesEW = (MPI_Datatype*)malloc( 3*get_LY(lattice)*sizeof(MPI_Datatype)); //int BlockLengthsNS[3*LX]; lbmpi->BlockLengthsNS = (int*)malloc( 3*get_LX(lattice)*sizeof(int)); //MPI_Aint AddrsNS[3*LX]; lbmpi->AddrsNS = (MPI_Aint*)malloc( 3*get_LX(lattice)*sizeof(MPI_Aint)); //MPI_Aint IndicesNS[3*LX]; lbmpi->IndicesNS = (MPI_Aint*)malloc( 3*get_LX(lattice)*sizeof(MPI_Aint)); //MPI_Datatype TypesNS[3*LX]; lbmpi->TypesNS = (MPI_Datatype*)malloc( 3*get_LX(lattice)*sizeof(MPI_Datatype)); #if DUMP_AFTER_COMM || DUMP_BEFORE_COMM //double fmat[3*LY][3*LX]; fmat = (double**)malloc(3*get_LY(lattice)*sizeof(double*)) for(j=1;j<=get_LY(lattice);j++) { lbmpi->fmat[j] = (double*)malloc(3*get_LX(lattice)*sizeof(double)); } #endif /* DUMP_AFTER_COMM || DUMP_BEFORE_COMM */ } /* void lbmpi_allocate_datatypes( lbmpi, lattice) */ int lbmpi_get_ProcID( lbmpi_ptr lbmpi) { return lbmpi->ProcID; } MPI_Aint *lbmpi_get_Index0_ptr( lbmpi_ptr lbmpi) { return (MPI_Aint *)(&(lbmpi->Index0)); } int get_NumProcs( lbmpi_ptr lbmpi) { return lbmpi->NumProcs;} int get_ProcID( lbmpi_ptr lbmpi) { return lbmpi->ProcID;} int get_NPX( lbmpi_ptr lbmpi) { return lbmpi->NPX;} int get_NPY( lbmpi_ptr lbmpi) { return lbmpi->NPY;} int get_PX( lbmpi_ptr lbmpi) { return lbmpi->PX;} int get_PY( lbmpi_ptr lbmpi) { return lbmpi->PY;} int set_GLX( lbmpi_ptr lbmpi, int arg_GLX) { lbmpi->GLX = arg_GLX;} int set_GLY( lbmpi_ptr lbmpi, int arg_GLY) { lbmpi->GLY = arg_GLY;} int get_GLX( lbmpi_ptr lbmpi) { return lbmpi->GLX;} int get_GLY( lbmpi_ptr lbmpi) { return lbmpi->GLY;} int get_GSX( lbmpi_ptr lbmpi) { return lbmpi->GSX;} int get_GSY( lbmpi_ptr lbmpi) { return lbmpi->GSY;} int get_GEX( lbmpi_ptr lbmpi) { return lbmpi->GEX;} int get_GEY( lbmpi_ptr lbmpi) { return lbmpi->GEY;} void compute_LX( lattice_ptr lattice, lbmpi_ptr lbmpi) { // First store the global domain size in (GLX,GLY). set_GLX( lbmpi, get_LX( lattice)); set_GLY( lbmpi, get_LY( lattice)); if( get_GLX(lbmpi) % get_NPX(lbmpi) != 0) { printf("%s %d >> ERROR: Currently require global domain size" "to be divisible by number of processes." "LX %% NPX = %d %% %d = %d\n", __FILE__,__LINE__, get_GLX(lbmpi), get_NPX(lbmpi), get_GLX(lbmpi) % get_NPX(lbmpi) ); process_exit(1); } set_LX( lattice, get_GLX(lbmpi) / get_NPX(lbmpi)); } /* void compute_LX( lattice_ptr lattice) */ void compute_LY( lattice_ptr lattice, lbmpi_ptr lbmpi) { if( get_GLY(lbmpi) % get_NPY(lbmpi) != 0) { printf("%s %d >> ERROR: Currently require global domain size" "to be divisible by number of processes." "GLY %% NPY = %d %% %d = %d\n", __FILE__,__LINE__, get_GLY(lbmpi), get_NPY(lbmpi), get_GLY(lbmpi) % get_NPY(lbmpi) ); process_exit(1); } set_LY( lattice, get_GLY(lbmpi) / get_NPY(lbmpi)); } /* void compute_LX( lattice_ptr lattice) */ // void compute_global_coords( lattice_ptr lattice) void compute_global_coords( lattice_ptr lattice) { lbmpi_ptr lbmpi; lbmpi = lattice->lbmpi; printf("%s %d >> \n",__FILE__,__LINE__); printf("%s %d >> (PX,PY) = (%d,%d)\n",__FILE__,__LINE__,lbmpi->PX,lbmpi->PY); printf("%s %d >> \n",__FILE__,__LINE__); lbmpi->GSX = lbmpi->PX*get_LX(lattice); lbmpi->GEX = lbmpi->GSX + get_LX(lattice)-1; lbmpi->GSY = lbmpi->PY*get_LY(lattice); lbmpi->GEY = lbmpi->GEY + get_LY(lattice)-1; printf("%s %d >> (GSX,GSY)..(GEX,GEY) = (%d,%d)..(%d,%d)\n", __FILE__,__LINE__, get_GSX(lbmpi), get_GSY(lbmpi), get_GEX(lbmpi), get_GEY(lbmpi) ); } /* void compute_global_coords( lattice_ptr lattice) */ // void lbmpi_distribute_domain( lattice_ptr lattice) //############################################################################## // // When this subroutine is called, sub_matrix_ptr points to the global // matrix representing solids and pores in the domain. // // This routine makes a temporary copy of this global information and // then reallocates sub_matrix_ptr to point to space for solids/pores // information for just this process' portion of the domain and // copies that local info out of the temporary global copy. // void lbmpi_distribute_domain( lattice_ptr lattice, int ***sub_matrix_ptr) { lbmpi_ptr lbmpi; lbmpi = lattice->lbmpi; int **matrix; int i, j; int ii, jj; // Allocate space for temporary copy of global matrix. matrix = (int**)malloc( get_GLY(lbmpi)*sizeof(int*)); for( j=0; j<get_GLY(lbmpi); j++) { matrix[j] = (int*)malloc( get_GLX(lbmpi)*sizeof(int)); } // Make temporary copy of global matrix. for( j=0; j<get_GLY( lbmpi); j++) { for( i=0; i<get_GLX( lbmpi); i++) { matrix[j][i] = (*sub_matrix_ptr)[j][i]; printf(" %d",matrix[j][i]); } printf("\n"); } // Free the sub_matrix and reallocate at local dimensions. for( j=0; j<get_GLY(lbmpi); j++) { free( (*sub_matrix_ptr)[j]); } free( (*sub_matrix_ptr)); (*sub_matrix_ptr) = (int**)malloc( get_GLY(lbmpi)*sizeof(int*)); for( j=0; j<get_GLY(lbmpi); j++) { (*sub_matrix_ptr)[j] = (int*)malloc( get_GLX(lbmpi)*sizeof(int)); } // Copy the local data out of the global matrix. printf("%s %d >> jj=%d..%d\n", __FILE__,__LINE__, get_GSY(lbmpi), get_GEY(lbmpi)); printf("%s %d >> ii=%d..%d\n", __FILE__,__LINE__, get_GSX(lbmpi), get_GEX(lbmpi)); j = 0; for( jj=get_GSY(lbmpi); jj<=get_GEY(lbmpi); jj++) { i = 0; for( ii=get_GSX(lbmpi); ii<=get_GEX(lbmpi); ii++) { printf("%s %d >> %d: (i,j)<--(ii,jj), (%d,%d)<--(%d,%d)\n", __FILE__,__LINE__,lbmpi->ProcID,i,j,ii,jj); (*sub_matrix_ptr)[j][i] = matrix[jj][ii]; i++; } j++; } // Print the newly constructed submatrix. printf("\n"); for( j=0; j<get_LY( lattice); j++) { for( i=0; i<get_LX( lattice); i++) { printf(" %d",(*sub_matrix_ptr)[j][i]); } printf("\n"); } } /* void lbmpi_distribute_domain( lattice_ptr lattice) */ // void lbmpi_write_local_bmp( lattice_ptr lattice, int **sub_matrix) void lbmpi_write_local_bmp( lattice_ptr lattice, int **sub_matrix) { lbmpi_ptr lbmpi; bmp_hdr_ptr bmp_hdr; char b, g, r; int n; char filename[1024]; FILE *bmp; printf("lbmpi_write_local_bmp() -- hi!\n"); lbmpi = lattice->lbmpi; // TODO: Create bmp file for this process' piece of the domain. printf("\nTODOTODOTODOTODOTODOTODOTODOTODOTODOTODOTODOTODOTODOTODOTODO\n\n"); printf("%s %d >> TODO: Implement lbmpi_write_local_bmp\n",__FILE__,__LINE__); printf("\n\nTODOTODOTODOTODOTODOTODOTODOTODOTODOTODOTODOTODOTODOTODOTODO\n"); bmp_hdr = (bmp_hdr_ptr)malloc( sizeof(struct bmp_hdr_struct)); sprintf( filename, "./in/%dx%d_id%05d_px%05d_py%05d.bmp", get_LX(lattice), get_LY(lattice), get_NumProcs(lbmpi), get_PX(lbmpi), get_PY(lbmpi) ); bmp = fopen(filename,"w+"); bmp_write_header( bmp, bmp_hdr, get_LX(lattice), get_LY(lattice), /*bits*/24); printf("lbmpi_write_local_bmp() -- nn = %d.\n", get_NumNodes(lattice)); for( n=0; n<get_NumNodes(lattice); n++) { printf("lbmpi_write_local_bmp() -- n = %d.\n", n); if( *(*sub_matrix+n) == 1) { r = 0; g = 0; b = 0; } else { r = 255; g = 255; b = 255; } bmp_write_entry( bmp, bmp_hdr, n, r, g, b); } fclose(bmp); printf("lbmpi_write_local_bmp() -- bye!\n"); } /* void lbmpi_write_local_bmp( lattice_ptr lattice, int **sub_matrix) */ // vim: foldmethod=syntax
111pjb-one
src/lbmpi.c
C
gpl3
20,839
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // flags.h // // - Preprocessor flags for lb2d_prime. // #ifndef FLAGS_H #define FLAGS_H // Set VERBOSITY_LEVEL to correspond to how deep into nested loops to // print debug and related output. Stuff will be printed down to // loops nested VERBOSITY_LEVEL-1 deep. For example, // // VERBOSITY_LEVEL 0 ==> Nothing is printed, even outside of loops. // VERBOSITY_LEVEL 1 ==> Only stuff outside of loops is printed. // VERBOSITY_LEVEL 2 ==> Stuff inside the first level of loops is printed. // VERBOSITY_LEVEL 3 ==> Stuff inside the second level of loops is printed. // // Flag: VERBOSITY_LEVEL #define VERBOSITY_LEVEL 1 // If SAY_HI is on, some routines will display "hi" and "bye" messages // to stdout. // Flag: SAY_HI #define SAY_HI 0 // NUM_FLUID_COMPONENTS specifies the number of fluid components. // Flag: NUM_FLUID_COMPONENTS #define NUM_FLUID_COMPONENTS 2 // If NUM_FLUID_COMPONENTS is 2, the second component can be the sigma // component for solute (or thermal) transport as in Inamuro & Yoshino // by turning on INAMURO_SIGMA_COMPONENT . // Flag: INAMURO_SIGMA_COMPONENT #define INAMURO_SIGMA_COMPONENT ( 1 && NUM_FLUID_COMPONENTS==2) // Toggle Zhang & Chen energy transport method, PRE 67, 0066711 (2003). // Supposed to give thermodynamic consistency unlike old Shan & Chen method. // And supports general equation of state P = P(rho,T). // Utilizes the Inamuro component for evolution of the energy transport // equation. Employs modified compute_phase_force routine to compute // body force term representing non-local interaction potential U among // particles. // Flag: ZHANG_AND_CHEN_ENERGY_TRANSPORT #define ZHANG_AND_CHEN_ENERGY_TRANSPORT ( 0 && (INAMURO_SIGMA_COMPONENT)) // Simulate POROUS_MEDIA via a solid density parameter // as proposed by Dardis and McCloskey, // Phys Rev E, 57, 4, 4834-4837, 1998 // Flag: POROUS_MEDIA #define POROUS_MEDIA 0 // Simulate porous media as a body force. #define FREED_POROUS_MEDIA 0 // Toggle Tau & Zhang anisotropic dispersion. #define TAU_ZHANG_ANISOTROPIC_DISPERSION ( 1 \ && INAMURO_SIGMA_COMPONENT \ && POROUS_MEDIA ) // Guo, Zheng & Shi: PRE 65 2002, Body force #define GUO_ZHENG_SHI_BODY_FORCE 0 // Body force macros #if GUO_ZHENG_SHI_BODY_FORCE #if INAMURO_SIGMA_COMPONENT #define F(dir_,rho_,conc_) \ ( lattice->param.gval[0][(dir_)] \ /*+ lattice->param.gval[subs][(dir_)] */\ /* *(rho_) */\ *( 1. + get_buoyancy(lattice) \ *( get_beta(lattice)) \ *( (conc_) - get_C0(lattice))) \ ) #else #define F(dir_) lattice->param.gval[subs][(dir_)] #endif #else #if INAMURO_SIGMA_COMPONENT #define F(dir_,rho_,conc_) \ ( lattice->param.gval[0][(dir_)] \ /*+ lattice->param.gval[1][(dir_)] */\ /* *(rho_) */\ *( 1. + ( get_buoyancy(lattice)) \ *( get_beta(lattice)) \ *( (conc_) - get_C0(lattice))) ) #else #define F(dir_,rho_) \ lattice->param.gval[subs][(dir_)] \ *((lattice->param.incompressible)?(rho_):(1.)) #endif #endif // When there are two (or more) fluid components, a single velocity is // sometimes (always?) used to compute the equilibrium distribution // function. This single velocity will be called upr, and the // STORE_U_COMPOSITE flag will toggle its use. // Flag: STORE_U_COMPOSITE #define STORE_U_COMPOSITE ( 1 && ( (NUM_FLUID_COMPONENTS)==2 \ &&!((INAMURO_SIGMA_COMPONENT)))) // If DO_NOT_STORE_SOLIDS is on, then only the nodes necessary to flow are // stored. In this case, extra storage is needed for geometry information // (e.g. node neighbors). If the ratio of fluid nodes to solid nodes is // small (<~.7), this results in lower storage requirements. // Flag: DO_NOT_STORE_SOLIDS #define DO_NOT_STORE_SOLIDS 0 // If COMPUTE_ON_SOLIDS is on, macroscopic variables and feq will be computed // on solid nodes, even though they are not conceptually meaningful there. // This can be helpful for debugging purposes. #define COMPUTE_ON_SOLIDS 1 // NON_LOCAL_FORCES toggles any mechanisms for computing and storing // non-local (interaction) forces. // Flag: NON_LOCAL_FORCES #define NON_LOCAL_FORCES ( 0 && !(INAMURO_SIGMA_COMPONENT&&!ZHANG_AND_CHEN_ENERGY_TRANSPORT)) // The phase force weighting factors: // WM = weights in the direction of major axes // WD = weights in the direction of diagonals // According to Raskinmaki, it should be WM=2 and WD=1. // According to Chen (via correspondence) it should be WM=4 and WD=1. // According to Sukop and Thorne, it should be WM=1/9 and WD=1/36. // The corresonding G values (a.k.a. G, as in params.in) for the usual // equation of state that we like are -5, -10/3, and -120, respectively. // Flag: WM #define WM (1./ 9.) // Flag: WD #define WD (1./36.) #define Q 9 // Toggle manage_body_force call at beginning of time loop for // gradually increasing/decreasing gravity. // Flag: MANAGE_BODY_FORCE #define MANAGE_BODY_FORCE 0 // Toggle break through curve (BTC) mechanism for sigma component. // Flag: STORE_BTC #define STORE_BTC ( 1 && INAMURO_SIGMA_COMPONENT) // // Toggle DETERMINE_FLOW_DIRECTION to attempt to determine the direction of // flow. // // Assigns FlowDir = { 0, 1, 2} = { indeterminate, vertical, horizontal} // // NOTE: This determination informs the breakthrough curve mechanism which // should be used in a simple situation with either pressure/velocity // boundaries driving the flow in one direction or gravity driving the flow // in one direction. If the direction of flow cannot be determined, FlowDir // will be set to indeterminate (=0) and a BTC will not be stored. // // NOTE: This determination also informs the sigma slip boundary which // should only be used in the simple situation of flow through a channel // where the geometry is trivial and the direction of flow is obvious. // // Flag: DETERMINE_FLOW_DIRECTION #define DETERMINE_FLOW_DIRECTION 1 // Toggle mechanism to initialize domain with ux_in or uy_in. This is // useful for setting a velocity in a periodic domain without using // fluid boundary conditions. // Flag: INITIALIZE_WITH_UX_IN #define INITIALIZE_WITH_UX_IN 0 // Flag: INITIALIZE_WITH_UY_IN #define INITIALIZE_WITH_UY_IN 0 // Dumping the density and velocity data to files can be time consuming and // take up a lot of disk space. If all that is needed is the BMP files, then // turn WRITE_MACRO_VAR_DAT_FILES off to save time and space. // Flag: WRITE_MACRO_VAR_DAT_FILES #define WRITE_MACRO_VAR_DAT_FILES 1 // Usually the density and velocity are written only for the active nodes // and in a way designed for post-processing. Additional files with the // variables written in a readable grid of all lattice nodes will be // generated when WRITE_RHO_AND_U_TO_TXT is on. This is done in an // inefficient way and is intended only for debugging purposes on tiny // lattices. Note that if WRITE_MACRO_VAR_DAT_FILES is off, this flag // has no effect. // Flag: WRITE_RHO_AND_U_TO_TXT #define WRITE_RHO_AND_U_TO_TXT 0 // WRITE_PDF_DAT_FILES is analogous to WRITE_MACRO_VAR_DAT_FILES. // Flag: WRITE_PDF_DAT_FILES #define WRITE_PDF_DAT_FILES 0 // WRITE_PDF_TO_TXT is analogous to WRITE_RHO_AND_U_TO_TXT. // Flag: WRITE_PDF_TO_TXT #define WRITE_PDF_TO_TXT 0 // Value used to represent an INACTIVE_NODE . This is used in the list // of neighbors ( struct node_struct::nn). It is also used in the // map from (i,j) space onto n index space in rho2bmp() and u2bmp(). // Flag: INACTIVE_NODE #define INACTIVE_NODE -1 // Negative densities (f_a) generally signify impending doom. The code // will die "gracefully" when this happens if PUKE_NEGATIVE_DENSITIES is on. // Might want to turn this off to boost performance on big, long runs that // are expected to survive without such instabilities. // Flag: PUKE_NEGATIVE_DENSITIES #define PUKE_NEGATIVE_DENSITIES 0 // Turn one of these on for coloring of the solids in bmp files. // Flag: SOLID_COLOR_IS_CHECKERBOARD #define SOLID_COLOR_IS_CHECKERBOARD 0 // Flag: SOLID_COLOR_IS_BLACK #define SOLID_COLOR_IS_BLACK 1 // Flag: DELAY #define DELAY 0 // Flag: END_GRAV #define END_GRAV 2000 // A single white pixel will be placed in at the (0,0) lattice node if // MARK_ORIGIN_FOR_REFERENCE is turned on. This is good for assisting with the // problem of tracking orientation of the results between regimes (e.g. C, BMP, // Matlab...). // Flag: MARK_ORIGIN_FOR_REFERENCE #define MARK_ORIGIN_FOR_REFERENCE 0 // Flag: PERTURBATIONS #define PERTURBATIONS 0 // If WRITE_CHEN_DAT_FILES is on, the code will output old style chen_*.dat // files to be processed by the old lb_rho_v*.m matlab scripts. // Flag: WRITE_CHEN_DAT_FILES #define WRITE_CHEN_DAT_FILES 0 // NEW_PARAMS_INPUT_ROUTINE is a temporary flag to switch between the old // params input routine and the new one under development. When the new // one is ready, it should be used exclusively. #define NEW_PARAMS_INPUT_ROUTINE 1 #endif /* FLAGS_H */
111pjb-one
src/flags_taylor_pressure.h
C
gpl3
9,094
#ifndef FLAGS_H #define FLAGS_H //############################################################################## // // flags.h // // - Preprocessor flags for lb2d_prime. // // Set VERBOSITY_LEVEL to correspond to how deep into nested loops to // print debug and related output. Stuff will be printed down to // loops nested VERBOSITY_LEVEL-1 deep. For example, // // VERBOSITY_LEVEL 0 ==> Nothing is printed, even outside of loops. // VERBOSITY_LEVEL 1 ==> Only stuff outside of loops is printed. // VERBOSITY_LEVEL 2 ==> Stuff inside the first level of loops is printed. // VERBOSITY_LEVEL 3 ==> Stuff inside the second level of loops is printed. // // Flag: VERBOSITY_LEVEL #define VERBOSITY_LEVEL 1 // If SAY_HI is on, some routines will display "hi" and "bye" messages // to stdout. // Flag: SAY_HI #define SAY_HI 0 // NUM_FLUID_COMPONENTS specifies the number of fluid components. // Flag: NUM_FLUID_COMPONENTS #define NUM_FLUID_COMPONENTS 2 // If NUM_FLUID_COMPONENTS is 2, the second component can be the sigma // component for solute (or thermal) transport as in Inamuro & Yoshino // by turning on INAMURO_SIGMA_COMPONENT . // Flag: INAMURO_SIGMA_COMPONENT #define INAMURO_SIGMA_COMPONENT ( 0 && NUM_FLUID_COMPONENTS==2) // Toggle Zhang & Chen energy transport method, PRE 67, 0066711 (2003). // Supposed to give thermodynamic consistency unlike old Shan & Chen method. // And supports general equation of state P = P(rho,T). // Utilizes the Inamuro component for evolution of the energy transport // equation. Employs modified compute_phase_force routine to compute // body force term representing non-local interaction potential U among // particles. // Flag: ZHANG_AND_CHEN_ENERGY_TRANSPORT #define ZHANG_AND_CHEN_ENERGY_TRANSPORT ( 0 && (INAMURO_SIGMA_COMPONENT)) // Simulate POROUS_MEDIA via a solid density parameter // as proposed by Dardis and McCloskey, // Phys Rev E, 57, 4, 4834-4837, 1998 // Flag: POROUS_MEDIA #define POROUS_MEDIA 0 // When there are two (or more) fluid components, a single velocity is // sometimes (always?) used to compute the equilibrium distribution // function. This single velocity will be called upr, and the // STORE_U_COMPOSITE flag will toggle its use. // Flag: STORE_U_COMPOSITE #define STORE_U_COMPOSITE ( 1 && ( (NUM_FLUID_COMPONENTS)==2 \ &&!((INAMURO_SIGMA_COMPONENT)))) // If DO_NOT_STORE_SOLIDS is on, then only the nodes necessary to flow are // stored. In this case, extra storage is needed for geometry information // (e.g. node neighbors). If the ratio of fluid nodes to solid nodes is // small (<~.7), this results in lower storage requirements. // Flag: DO_NOT_STORE_SOLIDS #define DO_NOT_STORE_SOLIDS 0 // NON_LOCAL_FORCES toggles any mechanisms for computing and storing // non-local (interaction) forces. // Flag: NON_LOCAL_FORCES #define NON_LOCAL_FORCES ( 1 && !(INAMURO_SIGMA_COMPONENT&&!ZHANG_AND_CHEN_ENERGY_TRANSPORT)) // The phase force weighting factors: // WM = weights in the direction of major axes // WD = weights in the direction of diagonals // According to Raskinmaki, it should be WM=2 and WD=1. // According to Chen (via correspondence) it should be WM=4 and WD=1. // According to Sukop and Thorne, it should be WM=1/9 and WD=1/36. // The corresonding G values (a.k.a. G, as in params.in) for the usual // equation of state that we like are -5, -10/3, and -120, respectively. // Flag: WM #define WM (1./ 9.) // Flag: WD #define WD (1./36.) // Toggle manage_body_force call at beginning of time loop for // gradually increasing/decreasing gravity. // Flag: MANAGE_BODY_FORCE #define MANAGE_BODY_FORCE 0 // Toggle break through curve (BTC) mechanism for sigma component. // Flag: STORE_BTC #define STORE_BTC ( 1 && INAMURO_SIGMA_COMPONENT) // // Toggle DETERMINE_FLOW_DIRECTION to attempt to determine the direction of // flow. // // Assigns FlowDir = { 0, 1, 2} = { indeterminate, vertical, horizontal} // // NOTE: This determination informs the breakthrough curve mechanism which // should be used in a simple situation with either pressure/velocity // boundaries driving the flow in one direction or gravity driving the flow // in one direction. If the direction of flow cannot be determined, FlowDir // will be set to indeterminate (=0) and a BTC will not be stored. // // NOTE: This determination also informs the sigma slip boundary which // should only be used in the simple situation of flow through a channel // where the geometry is trivial and the direction of flow is obvious. // // Flag: DETERMINE_FLOW_DIRECTION #define DETERMINE_FLOW_DIRECTION 1 // Toggle mechanism to initialize domain with ux_in or uy_in. This is // useful for setting a velocity in a periodic domain without using // fluid boundary conditions. // Flag: INITIALIZE_WITH_UX_IN #define INITIALIZE_WITH_UX_IN 0 // Flag: INITIALIZE_WITH_UY_IN #define INITIALIZE_WITH_UY_IN 1 // Dumping the density and velocity data to files can be time consuming and // take up a lot of disk space. If all that is needed is the BMP files, then // turn WRITE_MACRO_VAR_DAT_FILES off to save time and space. // Flag: WRITE_MACRO_VAR_DAT_FILES #define WRITE_MACRO_VAR_DAT_FILES 0 // Usually the density and velocity are written only for the active nodes // and in a way designed for post-processing. Additional files with the // variables written in a readable grid of all lattice nodes will be // generated when WRITE_RHO_AND_U_TO_TXT is on. This is done in an // inefficient way and is intended only for debugging purposes on tiny // lattices. Note that if WRITE_MACRO_VAR_DAT_FILES is off, this flag // has no effect. // Flag: WRITE_RHO_AND_U_TO_TXT #define WRITE_RHO_AND_U_TO_TXT 0 // WRITE_PDF_DAT_FILES is analogous to WRITE_MACRO_VAR_DAT_FILES. // Flag: WRITE_PDF_DAT_FILES #define WRITE_PDF_DAT_FILES 0 // WRITE_PDF_TO_TXT is analogous to WRITE_RHO_AND_U_TO_TXT. // Flag: WRITE_PDF_TO_TXT #define WRITE_PDF_TO_TXT 0 // Value used to represent an INACTIVE_NODE . This is used in the list // of neighbors ( struct node_struct::nn). It is also used in the // map from (i,j) space onto n index space in rho2bmp() and u2bmp(). // Flag: INACTIVE_NODE #define INACTIVE_NODE -1 // Negative densities (f_a) generally signify impending doom. The code // will die "gracefully" when this happens if PUKE_NEGATIVE_DENSITIES is on. // Might want to turn this off to boost performance on big, long runs that // are expected to survive without such instabilities. // Flag: PUKE_NEGATIVE_DENSITIES #define PUKE_NEGATIVE_DENSITIES 0 // Turn one of these on for coloring of the solids in bmp files. // Flag: SOLID_COLOR_IS_CHECKERBOARD #define SOLID_COLOR_IS_CHECKERBOARD 0 // Flag: SOLID_COLOR_IS_BLACK #define SOLID_COLOR_IS_BLACK 1 // Flag: DELAY #define DELAY 0 // Flag: END_GRAV #define END_GRAV 2000 // A single white pixel will be placed in at the (0,0) lattice node if // MARK_ORIGIN_FOR_REFERENCE is turned on. This is good for assisting with the // problem of tracking orientation of the results between regimes (e.g. C, BMP, // Matlab...). // Flag: MARK_ORIGIN_FOR_REFERENCE #define MARK_ORIGIN_FOR_REFERENCE 0 // Flag: PERTURBATIONS #define PERTURBATIONS 0 // If WRITE_CHEN_DAT_FILES is on, the code will output old style chen_*.dat // files to be processed by the old lb_rho_v*.m matlab scripts. // Flag: WRITE_CHEN_DAT_FILES #define WRITE_CHEN_DAT_FILES 0 #endif /* FLAGS_H */
111pjb-one
src/flags_mcmp.h
C
gpl3
7,416
//############################################################################## // // user_stuff.h // // - This file includes a definition of the struct user_struct, which the // user should fill in with whatever they want. It will be accessed // from the lattice structure as lattice->user_stuff->whatever // // - This file also has forward declarations for the user_stuff functions. // These functions are defined in user_stuff.c. The user should put in // them whatever they want. See user_stuff.c for more information. // // struct user_stuff_struct { double rho_c; double rho_c_start; double rho_c_inc; double rho_c_reverse; double rho_ave; double rho_ave_prev; double u_ave[2]; double u_ave_prev[2]; double tol; FILE *o; }; typedef struct user_stuff_struct *user_stuff_ptr; void user_stuff_pre_frames( lattice_ptr lattice); void user_stuff_frame( lattice_ptr lattice); void user_stuff_post_frames( lattice_ptr lattice); void user_stuff_pre_times( lattice_ptr lattice); void user_stuff_time( lattice_ptr lattice); void user_stuff_post_times( lattice_ptr lattice);
111pjb-one
src/user_stuff.h
C
gpl3
1,116
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // lattice.c // // Accessor functions for members of the data structure in lattice.h // int get_LX( lattice_ptr lattice) { return lattice->param.LX;} int get_LY( lattice_ptr lattice) { return lattice->param.LY;} int set_LX( lattice_ptr lattice, int arg_LX) { lattice->param.LX = arg_LX;} int set_LY( lattice_ptr lattice, int arg_LY) { lattice->param.LY = arg_LY;} int get_si( lattice_ptr lattice) { return 0;} int get_sj( lattice_ptr lattice) { return 0;} int get_ei( lattice_ptr lattice) { return lattice->param.LX-1;} int get_ej( lattice_ptr lattice) { return lattice->param.LY-1;} int get_NumFrames( lattice_ptr lattice) { return lattice->param.NumFrames;} int get_FrameRate( lattice_ptr lattice) { return lattice->param.FrameRate;} int get_NumNodes( lattice_ptr lattice) { if(lattice->NumNodes>0) { return lattice->NumNodes; } else { return lattice->param.LX*lattice->param.LY; } } void set_NumNodes( lattice_ptr lattice) { lattice->NumNodes = get_LX( lattice)*get_LY( lattice); } double get_G( lattice_ptr lattice) { return lattice->param.G;} double get_Gads( lattice_ptr lattice, int subs) { return lattice->param.Gads[subs]; } double *get_ftemp_ptr( lattice_ptr lattice, int subs, int j, int i, int a) { return (double *)(lattice->pdf[subs]->ftemp + IJ2N(i,j)); } int get_time( lattice_ptr lattice) { return lattice->time;} int get_frame( lattice_ptr lattice) { return lattice->frame;} int is_first_timestep( lattice_ptr lattice) { return ( lattice->time == 1); } int adjust_zero_flux_for_btc( lattice_ptr lattice) { // Toggle the adjustment in zeroconcgrad_w to make sure btc is measured // correctly. return 0; } int is_last_step_of_frame( lattice_ptr lattice) { if( (get_time(lattice)+0) == get_frame(lattice)*get_FrameRate(lattice)) { return 1; } else { return 0; } } int is_solid_node( lattice_ptr lattice, int subs, int n) { return (lattice->bc[subs][n%get_NumNodes(lattice)].bc_type&BC_SOLID_NODE)?(1):(0); } int is_not_solid_node( lattice_ptr lattice, int subs, int n) { return !is_solid_node( lattice, subs, n); } void make_solid_node( lattice_ptr lattice, const int subs, const int n) { lattice->bc[subs][n].bc_type|=BC_SOLID_NODE; } int bcs_on_solids( lattice_ptr lattice) { // TODO: Input this from params. return 0; } int is_incompressible( lattice_ptr lattice) { return lattice->param.incompressible; } int annotate_incompressible_filenames( lattice_ptr lattice) { // Put an 'i' in the filenames of outputs from incompressible runs to // distinguish from filenames of corresponding compressible runs. // This might be useful to compare results between compressible and // incompressible runs. But some scripts might not know about the 'i' and // so they would need the filenames to be sans the 'i' to work. Could // make this an option in 'params.in'... //return 1; return 0; } int hydrostatic( lattice_ptr lattice) { // Pressure boundaries enforce a hydrostatic condition. This is // experimental and not automatic -- it requires manual fiddling // in the bcs.c file. return 0; } int hydrostatic_west( lattice_ptr lattice) { // Pressure boundaries enforce a hydrostatic condition. This is // experimental and not automatic -- it requires manual fiddling // in the bcs.c file. return hydrostatic( lattice); } int hydrostatic_compressible( lattice_ptr lattice) { // Use compressible version of density profile as opposed to linear // approximation. return 0; } int hydrostatic_compute_rho_ref( lattice_ptr lattice) { // Compute the reference density for the compressible density profile. // If this switch is off, the value of rho_out will be used as the // reference density. return 0; } double get_tau( lattice_ptr lattice, const int subs) { return lattice->param.tau[subs]; } int gravitationally_adjacent_to_a_solid( lattice_ptr lattice, int subs, int n, int dir) { if( lattice->param.gval[subs][dir] != 0) { return ( is_solid_node( lattice, subs, n-get_LX(lattice)) ||is_solid_node( lattice, subs, n+get_LX(lattice))); } else { return 0; } } int on_the_east( lattice_ptr lattice, const int n) { return( /*east*/(n+1)%get_LX(lattice) == 0); } int on_the_east_or_west( lattice_ptr lattice, const int n) { return( /*west*/(n )%get_LX(lattice) == 0 || /*east*/(n+1)%get_LX(lattice) == 0); } int on_the_north_or_south( lattice_ptr lattice, const int n) { return( /*north*/ n >= get_NumNodes(lattice) - get_LX(lattice) || /*south*/ n < get_LX(lattice) ); } #if INAMURO_SIGMA_COMPONENT int flow_dir_is_vertical( lattice_ptr lattice) { return( lattice->FlowDir == /*Vertical*/2); } int flow_dir_is_horizontal( lattice_ptr lattice) { return( lattice->FlowDir == /*Horizontal*/1); } #endif double get_rho_A( lattice_ptr lattice, int subs) { return lattice->param.rho_A[subs]; } double get_rho_B( lattice_ptr lattice, int subs) { return lattice->param.rho_B[subs]; } #if INAMURO_SIGMA_COMPONENT double get_rho_sigma( lattice_ptr lattice) { return lattice->param.rho_sigma;} double get_C( lattice_ptr lattice) { return get_rho_sigma(lattice);} double get_C0( lattice_ptr lattice) { return lattice->param.C0;} double get_rho0( lattice_ptr lattice) { return lattice->param.rho0;} double get_drhodC( lattice_ptr lattice) { return lattice->param.drhodC;} double get_C_in( lattice_ptr lattice) { return lattice->param.C_in;} double get_rho_sigma_in( lattice_ptr lattice) { return lattice->param.rho_sigma_in;} double get_C_out( lattice_ptr lattice) { return lattice->param.C_out;} double get_rho_sigma_out( lattice_ptr lattice) { return lattice->param.rho_sigma_out;} double get_beta( lattice_ptr lattice) { return lattice->param.beta;} #endif /* INAMURO_SIGMA_COMPONENT */ int is_periodic_in_x( lattice_ptr lattice, int subs) { return lattice->periodic_x[subs]; } int is_periodic_in_y( lattice_ptr lattice, int subs) { return lattice->periodic_y[subs]; } int get_ns_flag( lattice_ptr lattice) { return lattice->param.ns_flag;} int get_slice_x( lattice_ptr lattice) { return lattice->param.slice_x;} int get_slice_y( lattice_ptr lattice) { return lattice->param.slice_y;} int make_octave_scripts( lattice_ptr lattice) { // TODO: return value based on (pending) "struct param_struct" entry. return lattice->param.make_octave_scripts; } #if INAMURO_SIGMA_COMPONENT int bc_sigma_walls( lattice_ptr lattice) { return lattice->param.bc_sigma_walls;} #endif /* (INAMURO_SIGMA_COMPONENT) */ int get_buoyancy( lattice_ptr lattice) { return lattice->param.buoyancy;} int get_buoyancy_flag( lattice_ptr lattice) { return ( lattice->param.buoyancy!=0)?(1):(0); } int get_buoyancy_sign( lattice_ptr lattice) { return ( lattice->param.buoyancy!=0) ?((lattice->param.buoyancy>0)?(1):(-1)) :(0); } int get_buoy_subs( lattice_ptr lattice) { return lattice->param.buoy_subs; } int use_slice_dot_in_file( lattice_ptr lattice) { if( get_slice_x(lattice) < 0 && get_slice_y(lattice) < 0) { return 1; } else { return 0; } } /* int use_slice_dot_in_file( lattice_ptr lattice) */ int do_user_stuff( lattice_ptr lattice) { return lattice->param.do_user_stuff; } int do_check_point_save( lattice_ptr lattice) { // Later, have a check point frequency input from params.in. return 0; } int do_check_point_load( lattice_ptr lattice) { FILE *o; char filename[1024]; sprintf(filename, "./out/checkpoint.dat"); if( o=fopen(filename,"r")) { fclose(o); // Later, have a toggle switch input from params.in. return 0; } else { return 0; } } double get_rhoij( lattice_ptr lattice, int i, int j, int subs) { return lattice->macro_vars[subs][IJ2N(i,j)].rho; } double get_rho( lattice_ptr lattice, int i, int j, int subs) { // TODO: Deprecate this function. return get_rhoij( lattice, i, j, subs); } double get_rhon( lattice_ptr lattice, int n, int subs) { return lattice->macro_vars[subs][n].rho; } const char* get_out_path( lattice_ptr lattice) { return lattice->param.out_path; } double* pressure_n_in0( lattice_ptr lattice, int subs) { return lattice->bcs_in[subs].pressure_n_in0; } double** pressure_n_in0_ptr( lattice_ptr lattice, int subs) { return &( lattice->bcs_in[subs].pressure_n_in0); } int num_pressure_n_in0( lattice_ptr lattice, int subs) { return lattice->bcs_in[subs].num_pressure_n_in0; } int* num_pressure_n_in0_ptr( lattice_ptr lattice, int subs) { return &( lattice->bcs_in[subs].num_pressure_n_in0); } double* pressure_s_in0( lattice_ptr lattice, int subs) { return lattice->bcs_in[subs].pressure_s_in0; } double** pressure_s_in0_ptr( lattice_ptr lattice, int subs) { return &( lattice->bcs_in[subs].pressure_s_in0); } int num_pressure_s_in0( lattice_ptr lattice, int subs) { return lattice->bcs_in[subs].num_pressure_s_in0; } int* num_pressure_s_in0_ptr( lattice_ptr lattice, int subs) { return &( lattice->bcs_in[subs].num_pressure_s_in0); }
111pjb-one
src/lattice.c
C
gpl3
9,134
//############################################################################## // // lbio.c // // - Lattice Boltzmann I/O routines. // // - Mainly, dump the data to files that can be read by Matlab. // // - Also, output routines for facilitating debugging. // // - Should have a routine that dumps a matlab script? // // Some compilers, e.g., VC++, don't have the usual round() function // in their math library. Alternatively, ROUND can be defined as // ceil or floor or some other rounding function. It is used in // the below routines for converting the real number valued of // quantities at a lattice node into integer RGB values for writing // to BMP files. #define ROUND floor // Swap byte order. #define ENDIAN2(w) ((((w)&0x00ff)<<8)|(((w)&0xff00)>>8)) #define ENDIAN4(w) ((((w)&0x000000ff)<<24)|(((w)&0xff000000)>>24)|(((w)&0x0000ff00)<<8)|(((w)&0x00ff0000)>>8)) //#define ENDIAN4(w) (((w)&0xff000000)>>8) //void output_frame( lattice_ptr lattice) //############################################################################## // // O U T P U T F R A M E // void output_frame( lattice_ptr lattice) { double s, u[2]; double nu; double L; #if VERBOSITY_LEVEL > 0 printf("\n"); printf( "========================================" "========================================\n"); printf("Begin file I/O at time = %d, frame = %d.\n", lattice->time, lattice->time/lattice->param.FrameRate); printf("\n"); #endif /* VERBOSITY_LEVEL > 0 */ dump_frame_summary( lattice); #if WRITE_MACRO_VAR_DAT_FILES dump_macro_vars( lattice, lattice->time); #endif /* WRITE_MACRO_VAR_DAT_FILES */ #if WRITE_PDF_DAT_FILES dump_pdf( lattice, lattice->time); #endif /* WRITE_PDF_DAT_FILES */ if( lattice->param.dump_rho) { rho2bmp( lattice, lattice->time);} if( lattice->param.dump_u ) { u2bmp( lattice, lattice->time);} if( lattice->param.dump_vor) { vor2bmp( lattice, lattice->time);} #if NON_LOCAL_FORCES if( lattice->param.G != 0.) { if( lattice->param.dump_force) { force2bmp( lattice);} } if( lattice->param.Gads[0] != 0. || lattice->param.Gads[0] != 0.) { if( lattice->param.dump_force) { sforce2bmp( lattice);} } #endif /* NON_LOCAL_FORCES */ slice( lattice); #if WRITE_CHEN_DAT_FILES chen_output( lattice); #endif /* WRITE_CHEN_DAT_FILES */ #if VERBOSITY_LEVEL > 0 printf("\n"); printf("File I/O done.\n"); printf("--\n"); #endif /* VERBOSITY_LEVEL > 0 */ nu = (1./3.)*(lattice->param.tau[0] - .5); L = lattice->param.length_scale; compute_ave_u( lattice, u, 0); s = sqrt( u[0]*u[0] + u[1]*u[1]); printf("subs 0: Re = ux_ave*L/nu = %f * %f / %f = %f\n", u[0], L, nu, u[0]*L/nu ); printf("subs 0: Re = uy_ave*L/nu = %f * %f / %f = %f\n", u[1], L, nu, u[1]*L/nu ); printf("subs 0: Re = u_ave*L/nu = %f * %f / %f = %f\n", s, L, nu, s*L/nu ); #if NUM_FLUID_COMPONENTS == 2 compute_ave_u( lattice, u, 1); s = sqrt( u[0]*u[0] + u[1]*u[1]); printf("subs 1: Re = ux_ave*L/nu = %f * %f / %f = %f\n", u[0], L, nu, u[0]*L/nu ); printf("subs 1: Re = uy_ave*L/nu = %f * %f / %f = %f\n", u[1], L, nu, u[1]*L/nu ); printf("subs 1: Re = u_ave*L/nu = %f * %f / %f = %f\n", s, L, nu, s*L/nu ); #endif /* NUM_FLUID_COMPONENTS == 2 */ #if STORE_U_COMPOSITE compute_ave_upr( lattice, u); s = sqrt( u[0]*u[0] + u[1]*u[1]); printf("eq: Re = ux_ave*L/nu = %f * %f / %f = %f\n", u[0], L, nu, u[0]*L/nu ); printf("eq: Re = uy_ave*L/nu = %f * %f / %f = %f\n", u[1], L, nu, u[1]*L/nu ); printf("eq: Re = u_ave*L/nu = %f * %f / %f = %f\n", s, L, nu, s*L/nu ); #endif /* STORE_U_COMPOSITE */ } /* void output_frame( lattice_ptr lattice) */ // void dump_frame_info( struct lattice_struct *lattice) //############################################################################## // // D U M P F R A M E I N F O // void dump_frame_summary( struct lattice_struct *lattice) { char filename[1024]; FILE *o; double min_u[5], max_u[5], ave_u[5], flux[3]; double min_rho, max_rho, ave_rho; double rho_ratio, u_x_ratio, u_y_ratio; int subs; for( subs = 0; subs < NUM_FLUID_COMPONENTS; subs++) { sprintf( filename, "./out/frames%dx%d_subs%02d.dat", lattice->param.LX, lattice->param.LY, subs); // On the first timestep, make sure we start with a new file. if( lattice->time==0) { if( !( o = fopen(filename,"w+"))) { printf("ERROR: fopen(\"%s\",\"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } else { // Put a header on the file. fprintf( o, "\n"); fprintf( o, " time " " |j| " " j_x " " j_y " " ave |u| " " ave |u_x| " " ave |u_y| " " ave u_x " " ave u_y " " min |u| " " min |u_x| " " min |u_y| " " min u_x " " min u_y " " max |u| " " max |u_x| " " max |u_y| " " max u_x " " max u_y " " max/ave_x " " max/ave_y " " min rho " " max rho " " ave rho " " max/ave " "\n"); fprintf( o, " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" " ------------" "\n"); fclose(o); } } if( !( o = fopen(filename,"a+"))) { printf("ERROR: fopen(\"%s\",\"a+\") = NULL. Bye, bye!\n", filename); process_exit(1); } compute_min_u_all( lattice, min_u, subs); compute_max_u_all( lattice, max_u, subs); compute_ave_u_all( lattice, ave_u, subs); compute_min_rho( lattice, &min_rho, subs); compute_max_rho( lattice, &max_rho, subs); compute_ave_rho( lattice, &ave_rho, subs); rho_ratio = ( ave_rho != 0.) ? ( max_rho /ave_rho ):( 1.); u_x_ratio = ( ave_u[1] != 0.) ? ( max_u[1]/ave_u[0]):( 1.); u_y_ratio = ( ave_u[2] != 0.) ? ( max_u[2]/ave_u[1]):( 1.); compute_flux( lattice, flux, subs); fprintf( o, "%12d " "%12.7f %12.7f %12.7f %12.7f %12.7f %12.7f %12.7f %12.7f %12.7f " "%12.7f %12.7f %12.7f %12.7f %12.7f %12.7f %12.7f %12.7f %12.7f " "%12.7f %12.7f %12.7f %12.7f %12.7f %12.7f\n", lattice->time, flux [0], flux [1], flux [2], ave_u[0], ave_u[1], ave_u[2], ave_u[3], ave_u[4], min_u[0], min_u[1], min_u[2], min_u[3], min_u[4], max_u[0], max_u[1], max_u[2], max_u[3], max_u[4], (u_x_ratio<=9999.)?(u_x_ratio):(9999.), (u_y_ratio<=9999.)?(u_y_ratio):(9999.), min_rho, max_rho, ave_rho, (rho_ratio<=9999.)?(rho_ratio):(9999.) ); fclose(o); #if VERBOSITY_LEVEL > 0 printf("dump_frame_info() -- Wrote file \"%s\"\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ #if VERBOSITY_LEVEL > 0 printf("dump_frame_info() -- frame = %d/%d = %d\n", lattice->time, lattice->param.FrameRate, (int)((double)lattice->time/(double)lattice->param.FrameRate)); #endif /* VERBOSITY_LEVEL > 0 */ } } /* void dump_frame_info( struct lattice_struct *lattice) */ // void dump_macro_vars( struct lattice_struct *lattice) //############################################################################## // // D U M P M A C R O S C O P I C // // - Output the macro_vars variables to files. // void dump_macro_vars( struct lattice_struct *lattice, int time) { char filename[1024]; FILE *o, *o_u, *o_rho, *o_ux, *o_uy, *o_upr, *o_upr_x, *o_upr_y; int *node_ptr; int n; double *macro_vars_ptr; double *upr; int frame; #if WRITE_RHO_AND_U_TO_TXT int i, j; #endif /* WRITE_RHO_AND_U_TO_TXT */ double min_u[2], max_u[2], ave_u[2]; double min_rho, max_rho, ave_rho; double rho_ratio, u_x_ratio, u_y_ratio; int subs; frame = (int)((double)lattice->time/(double)lattice->param.FrameRate); for( subs = 0; subs < NUM_FLUID_COMPONENTS; subs++) { // W R I T E R H O A N D U // // - Write the density and velocity values at the active nodes to // the rho and u dat files. // sprintf( filename, "./out/rho_frame%04d_subs%02d.dat", frame, subs); if( !( o_rho = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/u_frame%04d_subs%02d.dat", frame, subs); if( !( o_u = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } #if STORE_U_COMPOSITE sprintf( filename, "./out/upr_frame%04d_subs%02d.dat", frame, subs); if( !( o_upr = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } upr = lattice->upr[0].u; #endif /* STORE_U_COMPOSITE */ macro_vars_ptr = &( lattice->macro_vars[subs][0].rho); for( n=0; n<lattice->NumNodes; n++) { fprintf( o_rho, "%20.17f\n", *macro_vars_ptr++); fprintf( o_u, "%20.17f ", *macro_vars_ptr++); fprintf( o_u, "%20.17f\n", *macro_vars_ptr++); #if STORE_U_COMPOSITE fprintf( o_upr, "%20.17f ", *upr++); fprintf( o_upr, "%20.17f\n", *upr++); #endif /* STORE_U_COMPOSITE */ } fclose(o_u); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/u_frame%04d_subs%02d.dat", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); fclose(o_rho); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/rho_frame%04d_subs%02d.dat", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); #if STORE_U_COMPOSITE fclose(o_upr); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/upr_frame%04d_subs%02d.dat", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); #endif /* STORE_U_COMPOSITE */ #if WRITE_RHO_AND_U_TO_TXT // NOTE: This is very inefficient. But it's only intended // for debugging purposes on small problems. sprintf( filename, "./out/rho_frame%04d_subs%02d.txt", frame, subs); if( !( o_rho = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/ux_frame%04d_subs%02d.txt", frame, subs); if( !( o_ux = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/uy_frame%04d_subs%02d.txt", frame, subs); if( !( o_uy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } #if STORE_U_COMPOSITE sprintf( filename, "./out/upr_x_frame%04d_subs%02d.txt", frame, subs); if( !( o_upr_x = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/upr_y_frame%04d_subs%02d.txt", frame, subs); if( !( o_upr_y = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } #endif /* STORE_U_COMPOSITE */ for( j=lattice->param.LY-1; j>=0; j--) { n = j*lattice->param.LX; for( i=0; i<lattice->param.LX; i++, n++) { fprintf( o_rho, "%12.7f ", lattice->macro_vars[subs][n].rho); fprintf( o_ux, "%12.7f ", lattice->macro_vars[subs][n].u[0]); fprintf( o_uy, "%12.7f ", lattice->macro_vars[subs][n].u[1]); #if STORE_U_COMPOSITE fprintf( o_upr_x, "%12.7f ", lattice->upr[n].u[0]); fprintf( o_upr_y, "%12.7f ", lattice->upr[n].u[1]); #endif /* STORE_U_COMPOSITE */ if( n==lattice->NumNodes) { fprintf( o_rho, "%12.7f ", 0.); fprintf( o_ux, "%12.7f ", 0.); fprintf( o_uy, "%12.7f ", 0.); #if STORE_U_COMPOSITE fprintf( o_upr_x, "%12.7f ", 0.); fprintf( o_upr_y, "%12.7f ", 0.); #endif /* STORE_U_COMPOSITE */ } } fprintf( o_rho, "\n"); fprintf( o_ux, "\n"); fprintf( o_uy, "\n"); #if STORE_U_COMPOSITE fprintf( o_upr_x, "\n"); fprintf( o_upr_y, "\n"); #endif /* STORE_U_COMPOSITE */ } fclose(o_ux); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/ux_frame%04d_subs%02d.txt", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); fclose(o_uy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/uy_frame%04d_subs%02d.txt", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); fclose(o_rho); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/rho_frame%04d_subs%02d.txt", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); #if STORE_U_COMPOSITE fclose(o_upr_x); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/upr_x_frame%04d_subs%02d.txt", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); fclose(o_upr_y); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/upr_y_frame%04d_subs%02d.txt", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); #endif /* STORE_U_COMPOSITE */ #endif /* WRITE_RHO_AND_U_TO_TXT */ } /* for( subs = 0; subs < NUM_FLUID_COMPONENTS; subs++) */ } /* void dump_macro_vars( struct lattice_struct *lattice, int time) */ #if 1 // void read_macro_vars( struct lattice_struct *lattice) //############################################################################## // // R E A D M A C R O S C O P I C // // - Read the macro_vars variables from files. // void read_macro_vars( struct lattice_struct *lattice, int time) { char filename[1024]; FILE *in, *rho_in, *u_in; int *node_ptr; int n; double *macro_vars_ptr; int frame; double max_u[2], ave_u[2]; double max_rho, ave_rho; double rho_ratio, u_x_ratio, u_y_ratio; int subs; for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = (int)((double)time/(double)lattice->param.FrameRate); #if VERBOSITY_LEVEL > 0 printf("read_macro_vars() -- frame = %d/%d = %d\n", time, lattice->param.FrameRate, frame); #endif /* VERBOSITY_LEVEL > 0 */ // R E A D R H O A N D U // // - Read the density and velocity values at the active nodes to // the rho and u dat files. // sprintf( filename, "./out/rho_frame%04d_subs%02d.dat", frame, subs); if( !( rho_in = fopen( filename, "r+"))) { printf("ERROR: fopen( \"%s\", \"r+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/u_frame%04d_subs%02d.dat", frame, subs); if( !( u_in = fopen( filename, "r+"))) { printf("ERROR: fopen( \"%s\", \"r+\") = NULL. Bye, bye!\n", filename); process_exit(1); } macro_vars_ptr = &( lattice->macro_vars[subs][0].rho); for( n=0; n<lattice->NumNodes; n++) { fscanf( rho_in, "%lf\n", macro_vars_ptr++); fscanf( u_in, "%lf ", macro_vars_ptr++); fscanf( u_in, "%lf\n", macro_vars_ptr++); } fclose(u_in); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/u_frame%04d_subs%02d.dat", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("read_macro_vars() -- Read file \"%s\"\n", filename); fclose(rho_in); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/rho_frame%04d_subs%02d.dat", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("read_macro_vars() -- Read file \"%s\"\n", filename); } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ } /* void read_macro_vars( struct lattice_struct *lattice, int time) */ #endif // void dump_pdf( struct lattice_struct *lattice, int time) //############################################################################## // // D U M P P D F // // - Output the particle distribution functions to a text file. // // - This is useful mainly for debugging with small problems. // void dump_pdf( struct lattice_struct *lattice, int time) { char filename[1024]; FILE *o_feq, *o_f, *o_ftemp; double *fptr, *end_ptr; bc_ptr bc; int frame; int subs; #if WRITE_PDF_TO_TXT int i, j, n; #endif /* WRITE_PDF_TO_TXT */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = time/lattice->param.FrameRate; sprintf( filename, "./out/feq_frame%04d_subs%02d.dat", frame, subs); if( !( o_feq = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/f_frame%04d_subs%02d.dat", frame, subs); if( !( o_f = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/ftemp_frame%04d_subs%02d.dat", frame, subs); if( !( o_ftemp = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } bc = lattice->bc[subs]; fptr = lattice->pdf[subs][0].feq; end_ptr = &(lattice->pdf[subs][ lattice->NumNodes-1].ftemp[8]) + 1; while( fptr!=end_ptr) { if( 1 || !( bc++->bc_type & BC_SOLID_NODE)) { fprintf( o_feq , "%10.7f ", *fptr++); fprintf( o_feq , "%10.7f ", *fptr++); fprintf( o_feq , "%10.7f ", *fptr++); fprintf( o_feq , "%10.7f ", *fptr++); fprintf( o_feq , "%10.7f ", *fptr++); fprintf( o_feq , "%10.7f ", *fptr++); fprintf( o_feq , "%10.7f ", *fptr++); fprintf( o_feq , "%10.7f ", *fptr++); fprintf( o_feq , "%10.7f ", *fptr++); } else { fprintf( o_feq , "%10.7f ", 0.); fprintf( o_feq , "%10.7f ", 0.); fprintf( o_feq , "%10.7f ", 0.); fprintf( o_feq , "%10.7f ", 0.); fprintf( o_feq , "%10.7f ", 0.); fprintf( o_feq , "%10.7f ", 0.); fprintf( o_feq , "%10.7f ", 0.); fprintf( o_feq , "%10.7f ", 0.); fprintf( o_feq , "%10.7f ", 0.); fptr+=9; } fprintf( o_feq , "\n"); fprintf( o_f , "%10.7f ", *fptr++); fprintf( o_f , "%10.7f ", *fptr++); fprintf( o_f , "%10.7f ", *fptr++); fprintf( o_f , "%10.7f ", *fptr++); fprintf( o_f , "%10.7f ", *fptr++); fprintf( o_f , "%10.7f ", *fptr++); fprintf( o_f , "%10.7f ", *fptr++); fprintf( o_f , "%10.7f ", *fptr++); fprintf( o_f , "%10.7f ", *fptr++); fprintf( o_f , "\n"); fprintf( o_ftemp, "%10.7f ", *fptr++); fprintf( o_ftemp, "%10.7f ", *fptr++); fprintf( o_ftemp, "%10.7f ", *fptr++); fprintf( o_ftemp, "%10.7f ", *fptr++); fprintf( o_ftemp, "%10.7f ", *fptr++); fprintf( o_ftemp, "%10.7f ", *fptr++); fprintf( o_ftemp, "%10.7f ", *fptr++); fprintf( o_ftemp, "%10.7f ", *fptr++); fprintf( o_ftemp, "%10.7f ", *fptr++); fprintf( o_ftemp, "\n"); } /* while( fptr!=end_ptr) */ fclose( o_feq); fclose( o_f); fclose( o_ftemp); } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if WRITE_PDF_TO_TXT for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = time/lattice->param.FrameRate; sprintf( filename, "./out/feq_frame%04d_subs%02d.txt", frame, subs); if( !( o_feq = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/f_frame%04d_subs%02d.txt", frame, subs); if( !( o_f = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/ftemp_frame%04d_subs%02d.txt", frame, subs); if( !( o_ftemp = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } for( i=0; i<lattice->param.LX; i++) { fprintf( o_feq , "-----------"); fprintf( o_feq , "-----------"); fprintf( o_feq , "----------|"); fprintf( o_f , "-----------"); fprintf( o_f , "-----------"); fprintf( o_f , "----------|"); fprintf( o_ftemp, "-----------"); fprintf( o_ftemp, "-----------"); fprintf( o_ftemp, "----------|"); } fprintf( o_feq , "\n"); fprintf( o_f , "\n"); fprintf( o_ftemp, "\n"); for( j=lattice->param.LY-1; j>=0; j--) { n = j*lattice->param.LX; for( i=0; i<lattice->param.LX; i++, n++) { fprintf( o_feq, "%10.6f ", lattice->pdf[subs][n].feq[6] ); fprintf( o_feq, "%10.6f ", lattice->pdf[subs][n].feq[2] ); fprintf( o_feq, "%10.6f|", lattice->pdf[subs][n].feq[5] ); fprintf( o_f, "%10.6f ", lattice->pdf[subs][n].f[6] ); fprintf( o_f, "%10.6f ", lattice->pdf[subs][n].f[2] ); fprintf( o_f, "%10.6f|", lattice->pdf[subs][n].f[5] ); fprintf( o_ftemp,"%10.6f ", lattice->pdf[subs][n].ftemp[6]); fprintf( o_ftemp,"%10.6f ", lattice->pdf[subs][n].ftemp[2]); fprintf( o_ftemp,"%10.6f|", lattice->pdf[subs][n].ftemp[5]); } /* for( i=0; i<lattice->param.LX; i++, n++) */ fprintf( o_feq, "\n"); fprintf( o_f, "\n"); fprintf( o_ftemp,"\n"); n = j*lattice->param.LX; for( i=0; i<lattice->param.LX; i++, n++) { fprintf( o_feq, "%10.6f ", lattice->pdf[subs][n].feq[3] ); fprintf( o_feq, "%10.6f ", lattice->pdf[subs][n].feq[0] ); fprintf( o_feq, "%10.6f|", lattice->pdf[subs][n].feq[1] ); fprintf( o_f, "%10.6f ", lattice->pdf[subs][n].f[3] ); fprintf( o_f, "%10.6f ", lattice->pdf[subs][n].f[0] ); fprintf( o_f, "%10.6f|", lattice->pdf[subs][n].f[1] ); fprintf( o_ftemp,"%10.6f ", lattice->pdf[subs][n].ftemp[3]); fprintf( o_ftemp,"%10.6f ", lattice->pdf[subs][n].ftemp[0]); fprintf( o_ftemp,"%10.6f|", lattice->pdf[subs][n].ftemp[1]); } /* for( i=0; i<lattice->param.LX; i++, n++) */ fprintf( o_feq, "\n"); fprintf( o_f, "\n"); fprintf( o_ftemp,"\n"); n = j*lattice->param.LX; for( i=0; i<lattice->param.LX; i++, n++) { fprintf( o_feq, "%10.6f ", lattice->pdf[subs][n].feq[7] ); fprintf( o_feq, "%10.6f ", lattice->pdf[subs][n].feq[4] ); fprintf( o_feq, "%10.6f|", lattice->pdf[subs][n].feq[8] ); fprintf( o_f, "%10.6f ", lattice->pdf[subs][n].f[7] ); fprintf( o_f, "%10.6f ", lattice->pdf[subs][n].f[4] ); fprintf( o_f, "%10.6f|", lattice->pdf[subs][n].f[8] ); fprintf( o_ftemp,"%10.6f ", lattice->pdf[subs][n].ftemp[7]); fprintf( o_ftemp,"%10.6f ", lattice->pdf[subs][n].ftemp[4]); fprintf( o_ftemp,"%10.6f|", lattice->pdf[subs][n].ftemp[8]); } /* for( i=0; i<lattice->param.LX; i++, n++) */ fprintf( o_feq, "\n"); fprintf( o_f, "\n"); fprintf( o_ftemp,"\n"); for( i=0; i<lattice->param.LX; i++) { fprintf( o_feq , "-----------"); fprintf( o_feq , "-----------"); fprintf( o_feq , "----------|"); fprintf( o_f , "-----------"); fprintf( o_f , "-----------"); fprintf( o_f , "----------|"); fprintf( o_ftemp, "-----------"); fprintf( o_ftemp, "-----------"); fprintf( o_ftemp, "----------|"); } fprintf( o_feq , "\n"); fprintf( o_f , "\n"); fprintf( o_ftemp, "\n"); } /* for( j=lattice->param.LY-1; j>=0; j--) */ fclose( o_feq); fclose( o_f); fclose( o_ftemp); } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #endif /* WRITE_PDF_TO_TXT */ } /* void dump_pdf( struct lattice_struct *lattice, int time) */ #if NON_LOCAL_FORCES // void dump_forces( struct lattice_struct *lattice) //############################################################################## // // D U M P F O R C E S // // - Output the interactive force values to file. // void dump_forces( struct lattice_struct *lattice) { char filename[1024]; FILE *ox, *oy; int n; double *force; int frame; #if WRITE_RHO_AND_U_TO_TXT int i, j; #endif /* WRITE_RHO_AND_U_TO_TXT */ int subs; for( subs = 0; subs < NUM_FLUID_COMPONENTS; subs++) { frame = (int)((double)lattice->time/(double)lattice->param.FrameRate); #if VERBOSITY_LEVEL > 0 printf("dump_forces() -- frame = %d/%d = %d\n", lattice->time, lattice->param.FrameRate, frame); #endif /* VERBOSITY_LEVEL > 0 */ sprintf( filename, "./out/force_x_frame%04d_subs%02d.dat", frame, subs); if( !( ox = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/force_y_frame%04d_subs%02d.dat", frame, subs); if( !( oy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } force = lattice->force[subs][0].force; for( n=0; n<lattice->NumNodes; n++) { fprintf( ox, "%20.17f\n", *force++); fprintf( oy, "%20.17f\n", *force++); force += ( sizeof( struct force_struct)/8 - 2); } fclose(ox); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/force_x_frame%04d_subs%02d.dat", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_forces() -- Wrote file \"%s\"\n", filename); fclose(oy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/force_y_frame%04d_subs%02d.dat", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_forces() -- Wrote file \"%s\"\n", filename); #if WRITE_RHO_AND_U_TO_TXT // NOTE: This is very inefficient. But it's only intended // for debugging purposes on small problems. sprintf( filename, "./out/force_x_frame%04d_subs%02d.txt", frame, subs); if( !( ox = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/force_y_frame%04d_subs%02d.txt", frame, subs); if( !( oy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } for( j=0; j<lattice->param.LY; j++) { n = j*lattice->param.LX; for( i=0; i<lattice->param.LX; i++, n++) { fprintf( ox, "%10.7f ", lattice->force[subs][n].force[0]); fprintf( oy, "%10.7f ", lattice->force[subs][n].force[1]); if( n==lattice->NumNodes) { fprintf( ox, "%10.7f ", 0.); fprintf( oy, "%10.7f ", 0.); } } fprintf( ox, "\n"); fprintf( oy, "\n"); } fclose(ox); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/force_x_frame%04d_subs%02d.txt", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_forces() -- Wrote file \"%s\"\n", filename); fclose(oy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/force_y_frame%04d_subs%02d.txt", frame, subs); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_forces() -- Wrote file \"%s\"\n", filename); #endif /* WRITE_RHO_AND_U_TO_TXT */ } /* for( subs = 0; subs < NUM_FLUID_COMPONENTS; subs++) */ } /* void dump_forces( struct lattice_struct *lattice) */ #endif /* NON_LOCAL_FORCES */ // void dump_checkpoint( struct lattice_struct *lattice, int time, char *fn) //############################################################################## // // D U M P C H E C K P O I N T // // - Write lattice to a checkpoint file. // // - Should be binary and store all information necessary to // restart the current run at this point. // void dump_checkpoint( struct lattice_struct *lattice, int time, char *fn) { } /* void dump_checkpoint( struct lattice_struct *lattice, ...) */ // void read_checkpoint( struct lattice_struct *lattice) //############################################################################## // // R E A D C H E C K P O I N T // // - Read lattice from a checkpoint file (as written by dump_checkpoint). // // - With this information, should be able to restart where // the previous run stopped. // void read_checkpoint( struct lattice_struct *lattice) { } /* void read_checkpoint( struct lattice_struct *lattice) */ // void spy_bmp( char *filename, int ***spy) //############################################################################## // // S P Y B M P // // - Returns matrix 'spy' of ones and zeros. // // - Zeros for white pixels. // // - Ones for non-white pixels. // void spy_bmp( char *filename, lattice_ptr lattice, int **spy) { FILE *in, *o; int i, j, n, m; int pad, bytes_per_row; char k; char b, g, r; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char ctemp; int itemp; printf("spy_bmp() -- Hi!\n"); // Clear the spy array. for( j=0; j<lattice->param.LY; j++) { for( i=0; i<lattice->param.LX; i++) { spy[j][i] = 0; } } if( !( in = fopen( filename, "r"))) { #if 1 printf("spy_bmp() -- Error opening file \"%s\".\n", filename); process_exit(1); #else printf(" %s::spy_bmp() %d >> File \"%s\" cannot be opened for reading.\n", __FILE__, __LINE__, filename); if( !( o = fopen( filename, "w+"))) { // TODO: Write blank bmp file. } printf(" %s::spy_bmp() %d >> Wrote a blank \"%s\" file.\n", __FILE__, __LINE__, filename); printf(" %s::spy_bmp() %d >> Returning all zeros!\n", __FILE__, __LINE__); fclose( o); return; #endif } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); #if 0 printf("%s %d >> sizeof(int) = %d \n", __FILE__, __LINE__, sizeof(int)); printf("%s %d >> biWidth = %d \n", __FILE__, __LINE__, (int)*(int*)bmih.biWidth); printf("%s %d >> biWidth = [ '%c' '%c' '%c' '%c'] \n", __FILE__, __LINE__, bmih.biWidth[0], bmih.biWidth[1], bmih.biWidth[2], bmih.biWidth[3] ); printf("%s %d >> biWidth = [ '%d' '%d' '%d' '%d'] \n", __FILE__, __LINE__, bmih.biWidth[0], bmih.biWidth[1], bmih.biWidth[2], bmih.biWidth[3] ); ctemp = bmih.biWidth[0]; bmih.biWidth[0] = bmih.biWidth[3]; bmih.biWidth[3] = ctemp; ctemp = bmih.biWidth[1]; bmih.biWidth[1] = bmih.biWidth[2]; bmih.biWidth[2] = ctemp; itemp = 0xaabbccdd;//(int)*(int*)bmih.biWidth; printf("%s %d >> itemp = %d\n",__FILE__,__LINE__, itemp); printf("%s %d >> itemp = [ '%d' '%d' '%d' '%d'] \n", __FILE__, __LINE__, (itemp&0xff000000)>>24, (itemp&0x00ff0000)>>16, (itemp&0x0000ff00)>> 8, (itemp&0x000000ff)>> 0 ); itemp = ENDIAN4(itemp); printf("%s %d >> itemp = %d\n",__FILE__,__LINE__, itemp); printf("%s %d >> itemp = [ '%d' '%d' '%d' '%d'] \n", __FILE__, __LINE__, (itemp&0xff000000)>>24, (itemp&0x00ff0000)>>16, (itemp&0x0000ff00)>> 8, (itemp&0x000000ff)>> 0 ); printf("%s %d >> biWidth = [ '%d' '%d' '%d' '%d'] \n", __FILE__, __LINE__, bmih.biWidth[0], bmih.biWidth[1], bmih.biWidth[2], bmih.biWidth[3] ); printf("%s %d >> biWidth = %d \n", __FILE__, __LINE__, (int)*(int*)bmih.biWidth); printf("%s %d >> sizeof(int) = %d \n", __FILE__, __LINE__, sizeof(int)); printf("%s %d >> biHeight = %d \n", __FILE__, __LINE__, (int)*(int*)bmih.biHeight); printf("%s %d >> biHeight = [ '%c' '%c' '%c' '%c'] \n", __FILE__, __LINE__, bmih.biHeight[0], bmih.biHeight[1], bmih.biHeight[2], bmih.biHeight[3] ); printf("%s %d >> biHeight = [ '%d' '%d' '%d' '%d'] \n", __FILE__, __LINE__, bmih.biHeight[0], bmih.biHeight[1], bmih.biHeight[2], bmih.biHeight[3] ); ctemp = bmih.biHeight[0]; bmih.biHeight[0] = bmih.biHeight[3]; bmih.biHeight[3] = ctemp; ctemp = bmih.biHeight[1]; bmih.biHeight[1] = bmih.biHeight[2]; bmih.biHeight[2] = ctemp; printf("%s %d >> biHeight = [ '%d' '%d' '%d' '%d'] \n", __FILE__, __LINE__, bmih.biHeight[0], bmih.biHeight[1], bmih.biHeight[2], bmih.biHeight[3] ); printf("%s %d >> biHeight = %d \n", __FILE__, __LINE__, (int)*(int*)bmih.biHeight); ctemp = bmih.biBitCount[0]; bmih.biBitCount[0] = bmih.biBitCount[1]; bmih.biBitCount[1] = ctemp; #endif *((int*)(bmih.biWidth)) = ENDIAN4(((int)(*((int*)(bmih.biWidth))))); *((int*)(bmih.biHeight)) = ENDIAN4(((int)(*((int*)(bmih.biHeight))))); *((short int*)(bmih.biBitCount)) = ENDIAN2(((short int)(*((short int*)(bmih.biBitCount))))); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("%s %d >> ERROR: Can't handle compression. Exiting!\n",__FILE__,__LINE__); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; if( *width_ptr != lattice->param.LX) { printf("%s %d >> ERROR: LX %d does not match the " "width %d of the BMP file. Exiting!\n", __FILE__, __LINE__, lattice->param.LX, *width_ptr); process_exit(1); } printf("%s %d >> biWidth = %d \n", __FILE__, __LINE__, (int)*bmih.biWidth); printf("%s %d >> width_ptr = %d \n", __FILE__, __LINE__, (int)*width_ptr); if( *height_ptr != lattice->param.LY) { printf("%s %d >> ERROR: LY %d does not match the " "height %d of the BMP file. Exiting!\n", __FILE__, __LINE__, lattice->param.LY, *height_ptr); process_exit(1); } if( (*bitcount_ptr) < 24) { n = (int)pow(2.,(double)(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("%s %d >> Error reading palette entry %d. Exiting!\n", __FILE__, __LINE__, i); process_exit(1); } } } // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(*width_ptr))*((double)((*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; n = 0; m = 0; n+=( k = fread( &b, 1, 1, in )); i = 0; j = 0; while( !feof(in)) { switch((*bitcount_ptr)) { case 1: // Monochrome. printf("%s %d >> spy_bmp() -- " "Support for Monochrome BMPs is pending. " "Exiting!\n", __FILE__, __LINE__); process_exit(1); if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x80) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x40) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x20) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x10) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x08) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x04) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x02) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x01) == 0); } i++; break; case 4: // 16 colors. printf("%s %d >> spy_bmp() -- " "Support for 16 color BMPs is pending. " "Exiting!\n", __FILE__, __LINE__); process_exit(1); if( i < *width_ptr) { (spy)[j][i] = ( (b&0xf0)>>4 != 15); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b&0x0f) != 15); } i++; break; case 8: // 256 colors. printf("%s %d >> spy_bmp() -- " "Support for 256 color BMPs is pending. " "Exiting!\n", __FILE__, __LINE__); process_exit(1); if( i < *width_ptr) { (spy)[j][i] = ( (b&0xff) != 255); } i++; break; case 24: // 24-bit colors. if( i < 3*(*width_ptr)) { i++; n+=( k = fread( &g, 1, 1, in )); i++; n+=( k = fread( &r, 1, 1, in )); if( ( (b&0xff) == 0) &&( (g&0xff) == 0) &&( (r&0xff) == 0) ) { (spy)[j][(int)floor((double)i/3.)] = 1; } #if 0 if( ( (b&0xff) == 0) &&( (g&0xff) == 0) &&( (r&0xff) == 255) ) { // Red ==> Inflow, Pressure boundaries. if( (int)floor((double)i/3.) == 0 || (int)floor((double)i/3.) == lattice->param.LX-1 ) { if( !( j==0 || j == lattice->param.LY-1)) { lattice->periodic_x[subs] = 0; } } if( j == 0 || j == lattice->param.LY-1 ) { if( !( (int)floor((double)i/3.) == 0 || (int)floor((double)i/3.) == lattice->param.LX-1)) { lattice->periodic_y[subs] = 0; } } } if( ( (b&0xff) == 0) &&( (g&0xff) == 255) &&( (r&0xff) == 0) ) { // Green ==> Outflow, Pressure boundaries. if( (int)floor((double)i/3.) == 0 || (int)floor((double)i/3.) == lattice->param.LX-1 ) { if( !( j==0 || j == lattice->param.LY-1)) { lattice->periodic_x[subs] = 0; } } if( j == 0 || j == lattice->param.LY-1 ) { if( !( (int)floor((double)i/3.) == 0 || (int)floor((double)i/3.) == lattice->param.LX-1)) { lattice->periodic_y[subs] = 0; } } } #endif } i++; break; default: // 32-bit colors? printf("%s %d >> ERROR: Unhandled color depth, " "BitCount = %d. Exiting!\n", __FILE__, __LINE__, *bitcount_ptr); process_exit(1); break; } /* switch(*(bmih.biBitCount)) */ if( !(n%(bytes_per_row+pad))) { m++; i=0; j++;} n+=( k = fread( &b, 1, 1, in )); } /* while( !feof(in)) */ if( (bytes_per_row+pad)*m!=n) { printf("WARNING: Num bytes read = %d versus num bytes predicted = %d .\n", n, (bytes_per_row+pad)*m); } if( m != *height_ptr) { printf("WARNING: m (%d) != bmih.biHeight (%d).\n", m, *height_ptr); } fclose(in); printf("spy_bmp() -- Bye!\n"); printf("\n"); } /* spy_bmp( char *filename, int **spy) */ // void read_bcs( char *filename, int **bcs) //############################################################################## // // R E A D B C S // // - Read boundary condition information from file. // void read_bcs( lattice_ptr lattice, int **bcs) { FILE *in; char filename[1024]; int i, j, n, m; int ei, ej; int pad, bytes_per_row; char k; char b, g, r; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; int subs; printf("read_bcs() -- Hi!\n"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { // Clear the bcs array. for( j=0; j<lattice->param.LY; j++) { for( i=0; i<lattice->param.LX; i++) { bcs[j][i] = 0; } } sprintf( filename, "./in/%dx%dbc_subs%02d.bmp", lattice->param.LX, lattice->param.LY, subs); if( !( in = fopen( filename, "r"))) { printf("read_bcs() -- Error opening file \"%s\".\n", filename); process_exit(1); } // Read the headers. n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; if( ENDIAN4(*height_ptr) != lattice->param.LY) { printf("ERROR: Lattice height does not match " "soil matrix data \"%s\". (%d!=%d) Exiting!\n", filename, lattice->param.LY, ENDIAN4(*height_ptr) ); printf("\n"); process_exit(1); } if( ENDIAN4(*width_ptr) != lattice->param.LX) { printf("ERROR: Lattice width does not match " "soil matrix data \"%s\". (%d!=%d) Exiting!\n", filename, lattice->param.LX, ENDIAN4(*width_ptr) ); printf("\n"); process_exit(1); } // Read the palette, if necessary. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; n = 0; m = 0; n+=( k = fread( &b, 1, 1, in )); i = 0; //j = *height_ptr-1; j = 0;//*height_ptr-1; while( !feof(in)) { switch(ENDIAN2(*bitcount_ptr)) { case 1: // Monochrome. printf("read_bcs() -- " "Support for Monochrome BMPs is pending. " "Exiting!\n"); process_exit(1); if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x80) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x40) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x20) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x10) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x08) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x04) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x02) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x01) == 0); } i++; break; case 4: // 16 colors. printf("read_bcs() -- " "Support for 16 color BMPs is pending. " "Exiting!\n"); process_exit(1); if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b&0xf0)>>4 != 15); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b&0x0f) != 15); } i++; break; case 8: // 256 colors. printf("read_bcs() -- " "Support for 256 color BMPs is pending. " "Exiting!\n"); process_exit(1); if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b&0xff) != 255); } i++; break; case 24: // 24-bit colors. if( i < 3*(ENDIAN4(*width_ptr))) { i++; n+=( k = fread( &g, 1, 1, in )); i++; n+=( k = fread( &r, 1, 1, in )); if( ( (b&0xff) == 0) &&( (g&0xff) == 0) &&( (r&0xff) == 255) ) { // R E D ==> Inflow, Pressure boundaries. bcs[j][(int)floor((double)i/3.)] = 1; } if( ( (b&0xff) == 0) &&( (g&0xff) == 255) &&( (r&0xff) == 0) ) { // G R E E N ==> Outflow, Pressure boundaries. bcs[j][(int)floor((double)i/3.)] = 2; } } i++; break; default: // 32-bit colors? printf("ERROR: Unhandled color depth, " "BitCount = %d. Exiting!\n", ENDIAN2(*bitcount_ptr)); process_exit(1); break; } /* switch(*(bmih.biBitCount)) */ if( !(n%(bytes_per_row+pad))) { m++; i=0; j++;} n+=( k = fread( &b, 1, 1, in )); } /* while( !feof(in)) */ if( (bytes_per_row+pad)*m!=n) { printf("WARNING: Num bytes read = %d versus num bytes predicted = %d .\n", n, (bytes_per_row+pad)*m); } if( m != ENDIAN4(*height_ptr)) { printf("WARNING: m (%d) != bmih.biHeight (%d).\n", m, ENDIAN4(*height_ptr)); } fclose(in); ei = lattice->param.LX-1; ej = lattice->param.LY-1; for( n=0; n<lattice->NumNodes; n++) { i = n%lattice->param.LX; j = n/lattice->param.LX; if( bcs[ j][ i] != 0) { //printf("read_bcs() -- n = %d, ( %d, %d) of ( %d, %d).\n", n, i, j, ei, ej); #if 0 if( ( i==0 && j==0 ) || ( i==ei && j==0 ) || ( i==ei && j==ej) || ( i==0 && j==ej) ) { // Skip corners for now. printf("read_bcs() -- WARNING: Skipping corner ( %d, %d).", i, j); } else { #endif #if 0 if( i==0) { // West if( bcs[ j][ i] == 1) { // Inflow lattice->bc[n].bc_type |= BC_PRESSURE_W_IN; //lattice->periodic_x = 0; } else if( bcs[ j][ i] == 2) { // Outflow lattice->bc[n].bc_type |= BC_PRESSURE_W_OUT; //lattice->periodic_x = 0; } else { // Unhandled case. printf("read_bcs() -- Unhandled case: " "bcs[ %d][ %d] = %d . Exiting!\n", i, j, bcs[j][i]); process_exit(1); } } else if( i==ei) { // East if( bcs[ j][ i] == 1) { // Inflow lattice->bc[n].bc_type |= BC_PRESSURE_E_IN; //lattice->periodic_x = 0; } else if( bcs[ j][ i] == 2) { // Outflow lattice->bc[n].bc_type |= BC_PRESSURE_E_OUT; //lattice->periodic_x = 0; } else { // Unhandled case. printf("read_bcs() -- Unhandled case: " "bcs[ %d][ %d] = %d . Exiting!\n", i, j, bcs[j][i]); process_exit(1); } } else #endif if( j==0) { //printf("read_bcs() -- South at i=%d\n", i); // South if( bcs[ j][ i] == 1) { // Inflow lattice->bc[subs][n].bc_type |= BC_PRESSURE_S_IN; //lattice->periodic_y = 0; } else if( bcs[ j][ i] == 2) { // Outflow lattice->bc[subs][n].bc_type |= BC_PRESSURE_S_OUT; //lattice->periodic_y = 0; } else { // Unhandled case. printf("read_bcs() -- Unhandled case: " "bcs[ %d][ %d] = %d . Exiting!\n", i, j, bcs[j][i]); process_exit(1); } } else if( j==ej) { //printf("read_bcs() -- North at i=%d\n", i); // North if( bcs[ j][ i] == 1) { // Inflow lattice->bc[subs][n].bc_type |= BC_PRESSURE_N_IN; //lattice->periodic_y = 0; } else if( bcs[ j][ i] == 2) { // Outflow lattice->bc[subs][n].bc_type |= BC_PRESSURE_N_OUT; //lattice->periodic_y = 0; } else { // Unhandled case. printf("read_bcs() -- Unhandled case: " "bcs[ %d][ %d] = %d . Exiting!\n", i, j, bcs[j][i]); process_exit(1); } } else { // Unhandled case. printf("read_bcs() -- WARNING: " "Support for interior flow bcs is pending! " "Skipping ( i, j) = ( %d, %d).\n", i, j); } #if 0 } #endif } } } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ printf("read_bcs() -- Bye!\n"); printf("\n"); } /* read_bcs( char *filename, int ***bcs, int *height, int *width) */ // void rho2bmp( char *filename, int time) //############################################################################## // // R H O 2 B M P // #if 1 void rho2bmp( lattice_ptr lattice, int time) { FILE *in, *o; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double fval; double min_rho, max_rho; int subs; double **colormap; int num_colors; #if SAY_HI printf("rho2bmp() -- Hi!\n"); #endif /* SAY_HI */ if( lattice->param.use_colormap) { count_colormap( &num_colors); allocate_colormap( &colormap, num_colors); read_colormap( colormap, num_colors); } for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = time/lattice->param.FrameRate; sprintf( filename, "./in/%dx%d.bmp", lattice->param.LX, lattice->param.LY); if( !( in = fopen( filename, "r"))) { printf("rho2bmp() -- Error opening file \"%s\".\n", filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; compute_min_rho( lattice, &min_rho, subs); compute_max_rho( lattice, &max_rho, subs); sprintf( filename, "./out/rho%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); if( !( o = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o ); for( j=0; j<lattice->param.LY; j++) { n = j*lattice->param.LX; for( i=0; i<lattice->param.LX; i++, n++) { if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { if( lattice->param.use_colormap) { if( lattice->param.plot_scale_dynamic) { if( max_rho!=min_rho) { get_color( colormap, num_colors, (lattice->macro_vars[subs][ n].rho - min_rho)/(max_rho-min_rho), &red_val, &green_val, &blue_val ); } else { get_color( colormap, num_colors, 1., &red_val, &green_val, &blue_val ); } } else { get_color( colormap, num_colors, (lattice->macro_vars[subs][ n].rho /( (lattice->param.rho_A[subs]>lattice->param.rho_B[subs]) ?(lattice->param.rho_A[subs]) :(lattice->param.rho_B[subs]) )), &red_val, &green_val, &blue_val ); } } else { if( subs==0) { if( lattice->param.plot_scale_dynamic) { if( max_rho!=min_rho) { fval = ROUND( 255.*( lattice->macro_vars[subs][ n].rho - min_rho) /( max_rho-min_rho)); } else { fval = 255.; } } else { fval = ROUND( 255.*(lattice->macro_vars[subs][ n].rho /( (lattice->param.rho_A[subs]>lattice->param.rho_B[subs]) ?(lattice->param.rho_A[subs]) :(lattice->param.rho_B[subs]) ) )); } if( fval >= 0.) { if( fval <= 255.) { red_val = (char)((int)(255. - fval)%256); green_val = (char)((int)(255. - fval)%256); blue_val = (char)255; } else { red_val = (char)0; green_val = (char)0; blue_val = (char)255; } } else { red_val = (char)((int)(255. + fval)%256); green_val = (char)((int)(255. + fval)%256); blue_val = (char)((int)(255. + fval)%256); // TODO: Issue warning or something? Potential instability? } } /* if( subs==0) */ else // subs == 1 { if( lattice->param.plot_scale_dynamic) { if( max_rho!=min_rho) { fval = ROUND( 255.*( lattice->macro_vars[subs][ n].rho - min_rho) /( max_rho-min_rho)); } else { fval = 0.; } } else { //printf("%s (%d) >> fval = %f -> ", __FILE__, __LINE__, fval); #if INAMURO_SIGMA_COMPONENT fval = ROUND( 255.*(lattice->macro_vars[subs][ n].rho) /(lattice->param.rho_sigma)); #else /* !( INAMURO_SIGMA_COMPONENT) */ fval = ROUND( 255.*(lattice->macro_vars[subs][ n].rho /(lattice->param.rho_A[subs]))); #endif /* INAMURO_SIGMA_COMPONENT */ //printf("%f\n", fval); } if( fval >= 0.) { if( fval <= 255.) { red_val = (char)255; green_val = (char)((int)(255. - fval)%256); blue_val = (char)((int)(255. - fval)%256); } else { red_val = (char)255;//((int)(255. - (fval - 255.))%256); green_val = (char) 0;//((int)(255. - (fval - 255.))%256); blue_val = (char) 0;//((int)(255. - (fval - 255.))%256); } } else { red_val = (char)((int)(255. + fval)%256); green_val = (char)((int)(255. + fval)%256); blue_val = (char)((int)(255. + fval)%256); // TODO: Issue a warning or something? Potential instability? } } /* if( subs==0) else */ } } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ //printf("blue_val( %d, %d) = %d\n", i, j, (int)blue_val); if( fwrite( &blue_val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} //printf("BING %d %d\n", i, j); if( fwrite( &green_val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} //printf("BING %d %d\n", i, j); if( fwrite( &red_val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} //printf("BING %d %d\n", i, j); } /* for( i=0; i<lattice->param.LX; i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<lattice->param.LY; j++) */ fclose(o); #if VERBOSITY_LEVEL > 0 printf("rho2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ if( lattice->param.use_colormap) { deallocate_colormap( &colormap, num_colors); } #if SAY_HI printf("rho2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* rho2bmp( lattice_ptr lattice, int time) */ #else void rho2bmp( lattice_ptr lattice, int time) { FILE *in, *o; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double min_rho, max_rho; int subs; #if SAY_HI printf("rho2bmp() -- Hi!\n"); #endif /* SAY_HI */ compute_max_rho( lattice, &min_rho, 0); compute_max_rho( lattice, &max_rho, 1); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = time/lattice->param.FrameRate; sprintf( filename, "./in/%dx%d.bmp", lattice->param.LX, lattice->param.LY); if( !( in = fopen( filename, "r"))) { printf("rho2bmp() -- Error opening file \"%s\".\n", filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; sprintf( filename, "./out/rho%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); if( !( o = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o ); for( j=0; j<lattice->param.LY; j++) { n = j*lattice->param.LX; for( i=0; i<lattice->param.LX; i++, n++) { if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { red_val = (char)0; green_val = (char)0; red_val = (char)ROUND( 255.*(lattice->macro_vars[subs][ n].rho - min_rho)/(max_rho-min_rho)); blue_val = (char)255-red_val; } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ //printf("blue_val( %d, %d) = %d\n", i, j, (int)blue_val); if( fwrite( &blue_val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} //printf("BING %d %d\n", i, j); if( fwrite( &green_val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} //printf("BING %d %d\n", i, j); if( fwrite( &red_val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} //printf("BING %d %d\n", i, j); } /* for( i=0; i<lattice->param.LX; i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<lattice->param.LY; j++) */ fclose(o); #if VERBOSITY_LEVEL > 0 printf("rho2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("rho2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* rho2bmp( lattice_ptr lattice, int time) */ #endif // void u2bmp( char *filename, int time) //############################################################################## // // U 2 B M P // void u2bmp( lattice_ptr lattice, int time) { FILE *in, *o_u, *o_ux, *o_uy; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double max_u[2], maxu; double u_x, u_y, u; int subs; #if SAY_HI printf("u2bmp() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = time/lattice->param.FrameRate; sprintf( filename, "./in/%dx%d.bmp", lattice->param.LX, lattice->param.LY); if( !( in = fopen( filename, "r"))) { printf("u2bmp() -- Error opening file \"%s\".\n", filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } #if 0 *((int*)(bmih.biWidth)) = ENDIAN4(((int)(*((int*)(bmih.biWidth))))); *((int*)(bmih.biHeight)) = ENDIAN4(((int)(*((int*)(bmih.biHeight))))); *((short int*)(bmih.biBitCount)) = ENDIAN2(((short int)(*((short int*)(bmih.biBitCount))))); #endif width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; printf("%s %d >> width = %d\n",__FILE__,__LINE__, ENDIAN4(*width_ptr) ); printf("%s %d >> height = %d\n",__FILE__,__LINE__, ENDIAN4(*height_ptr) ); printf("%s %d >> bitcount = %d\n",__FILE__,__LINE__, ENDIAN2(*bitcount_ptr)); // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; compute_max_u( lattice, max_u, subs); sprintf( filename, "./out/u%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); if( !( o_u = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/u_x%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); if( !( o_ux = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/u_y%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); if( !( o_uy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_u ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_u ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_ux ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_ux ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_uy); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_uy); //for( j=lattice->param.LY-1; j>=0; j--) for( j=0; j<lattice->param.LY; j++) { n = j*lattice->param.LX; for( i=0; i<lattice->param.LX; i++, n++) { if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { #if 1 blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->macro_vars[subs][ n].u[0]); u_y = (lattice->macro_vars[subs][ n].u[1]); u = sqrt(u_x*u_x + u_y*u_y); maxu = sqrt( max_u[0]*max_u[0] + max_u[1]*max_u[1]); if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); green_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { #if 0 blue_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); green_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); red_val = 0.;//(char)ROUND( 128.*fabs(u)/maxu); #else blue_val = (char)ROUND( 255.*((fabs(u_x)!=0.)?(fabs(u_x)/maxu):(0.))); green_val = (char)ROUND( 255.*((fabs(u_y)!=0.)?(fabs(u_y)/maxu):(0.))); red_val = 0.;//(char)ROUND( 128.*((fabs(u )!=0.)?(fabs(u )/maxu):(0.))); #endif } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ #else blue_val = (char)255; green_val = (char)255; red_val = (char)255; u = sqrt(u_x*u_x + u_y*u_y); maxu = sqrt( max_u[0]*max_u[0] + max_u[1]*max_u[1]); //if( fabs(u) > .1*maxu) //{ green_val = (char)ROUND( 255.-255.*fabs(u)/maxu); red_val = (char)ROUND( 255.-255.*fabs(u)/maxu); blue_val = (char)ROUND( 255.-255.*fabs(u)/maxu); //} //else //{ // green_val = (char)0; // red_val = (char)0; // blue_val = (char)0; //} #endif val = (char)0; } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->macro_vars[subs][ n].u[0]); u_y = (lattice->macro_vars[subs][ n].u[1]); val = (char)0; if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); } else { red_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 255.*((fabs(u_x)!=0.)?(fabs(u_x)/max_u[0]):(0.))); } else { red_val = (char)ROUND( 255.*((fabs(u_x)!=0.)?(fabs(u_x)/max_u[0]):(0.))); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->macro_vars[subs][ n].u[0]); u_y = (lattice->macro_vars[subs][ n].u[1]); val = (char)0; if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { red_val = val; green_val = (char)ROUND( 128.*((fabs(u_y)!=0.)?(fabs(u_y)/max_u[1]):(0.))); } else { red_val = (char)ROUND( 128.*((fabs(u_y)!=0.)?(fabs(u_y)/max_u[1]):(0.))); green_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { blue_val = (char)ROUND( 255.*((fabs(u_y)!=0.)?(fabs(u_y)/max_u[1]):(0.))); green_val = val; } else { blue_val = val; green_val = (char)ROUND( 255.*((fabs(u_y)!=0.)?(fabs(u_y)/max_u[1]):(0.))); } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } /* for( i=0; i<lattice->param.LY; i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<lattice->param.LY; j++) */ fclose(o_u ); fclose(o_ux); fclose(o_uy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/u%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); printf("u2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "./out/u_x%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); printf("u2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "./out/u_y%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); printf("u2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if STORE_U_COMPOSITE frame = time/lattice->param.FrameRate; sprintf( filename, "./in/%dx%d.bmp", lattice->param.LX, lattice->param.LY); if( !( in = fopen( filename, "r"))) { printf("u2bmp() -- Error opening file \"%s\".\n", filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; compute_max_upr( lattice, max_u); sprintf( filename, "./out/upr%dx%d_frame%04d.bmp", lattice->param.LX, lattice->param.LY, frame); if( !( o_u = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/upr_x%dx%d_frame%04d.bmp", lattice->param.LX, lattice->param.LY, frame); if( !( o_ux = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/upr_y%dx%d_frame%04d.bmp", lattice->param.LX, lattice->param.LY, frame); if( !( o_uy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_u ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_u ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_ux ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_ux ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_uy); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_uy); //for( j=lattice->param.LY-1; j>=0; j--) for( j=0; j<lattice->param.LY; j++) { n = j*lattice->param.LX; for( i=0; i<lattice->param.LX; i++, n++) { if( lattice->bc[0][ n].bc_type == /*FLUID_NODE*/0) { #if 1 blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->upr[ n].u[0]); u_y = (lattice->upr[ n].u[1]); u = sqrt(u_x*u_x + u_y*u_y); maxu = sqrt( max_u[0]*max_u[0] + max_u[1]*max_u[1]); if( lattice->bc[0][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); green_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); green_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); //red_val = (char)ROUND( 128.*fabs(u)/maxu); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ #else blue_val = (char)255; green_val = (char)255; red_val = (char)255; u = sqrt(u_x*u_x + u_y*u_y); maxu = sqrt( max_u[0]*max_u[0] + max_u[1]*max_u[1]); //if( fabs(u) > .1*maxu) //{ green_val = (char)ROUND( 255.-255.*fabs(u)/maxu); red_val = (char)ROUND( 255.-255.*fabs(u)/maxu); blue_val = (char)ROUND( 255.-255.*fabs(u)/maxu); //} //else //{ // green_val = (char)0; // red_val = (char)0; // blue_val = (char)0; //} #endif val = (char)0; } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[0][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->upr[ n].u[0]); u_y = (lattice->upr[ n].u[1]); val = (char)0; if( lattice->bc[0][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); } else { red_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); } else { red_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[0][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->upr[ n].u[0]); u_y = (lattice->upr[ n].u[1]); val = (char)0; if( lattice->bc[0][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { red_val = val; green_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); } else { red_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); green_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { blue_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); green_val = val; } else { blue_val = val; green_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } /* for( i=0; i<lattice->param.LY; i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<lattice->param.LY; j++) */ fclose(o_u ); fclose(o_ux); fclose(o_uy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/upr%dx%d_frame%04d.bmp", lattice->param.LX, lattice->param.LY, frame); printf("u2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "./out/upr_x%dx%d_frame%04d.bmp", lattice->param.LX, lattice->param.LY, frame); printf("u2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "./out/upr_y%dx%d_frame%04d.bmp", lattice->param.LX, lattice->param.LY, frame); printf("u2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ #endif /* STORE_U_COMPOSITE */ #if SAY_HI printf("u2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* u2bmp( lattice_ptr lattice, int time) */ // void vor2bmp( char *filename, int time) //############################################################################## // // V O R 2 B M P // void vor2bmp( lattice_ptr lattice, int time) { FILE *in, *o_vor; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double max_vor_p, max_vor_n; double ave_vor_p, ave_vor_n; double vor; int subs; #if SAY_HI printf("vor2bmp() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = time/lattice->param.FrameRate; sprintf( filename, "./in/%dx%d.bmp", lattice->param.LX, lattice->param.LY); if( !( in = fopen( filename, "r"))) { printf("vor2bmp() -- Error opening file \"%s\".\n", filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; compute_max_vor( lattice, &max_vor_p, &max_vor_n, subs); #if 0 && VERBOSITY_LEVEL > 0 printf("vor2bmp() -- max_vor_p = %f\n", max_vor_p); printf("vor2bmp() -- max_vor_n = %f\n", max_vor_n); #endif /* 0 && VERBOSITY_LEVEL > 0 */ compute_ave_vor( lattice, &ave_vor_p, &ave_vor_n, subs); #if 0 && VERBOSITY_LEVEL > 0 printf("vor2bmp() -- ave_vor_p = %f\n", ave_vor_p); printf("vor2bmp() -- ave_vor_n = %f\n", ave_vor_n); #endif /* 0 && VERBOSITY_LEVEL > 0 */ sprintf( filename, "./out/vor%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); if( !( o_vor = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_vor ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_vor ); //for( j=lattice->param.LY-1; j>=0; j--) for( j=0; j<lattice->param.LY; j++) { n = j*lattice->param.LX; for( i=0; i<lattice->param.LX; i++, n++) { if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { //u_x = (lattice->macro_vars[subs][ n].u[0]); //u_y = (lattice->macro_vars[subs][ n].u[1]); compute_vorticity( lattice, i, j, n, &vor, subs); //if( fabs(vor)/max_vor_p > .5) //{ // printf("vor2bmp() -- vor/max_vor_p = %f/%f = %f\n", vor, max_vor_p, vor/max_vor_p); //} #if 0 blue_val = (char)255; green_val = (char)255; red_val = (char)255; if( vor > 0) { if( 100.*vor/ave_vor_p > 1.) { //printf("vor2bmp() -- vor/ave_vor_p = %f > 1.\n", vor/ave_vor_p); red_val = (char)0; green_val = (char)0; } else { //printf("vor2bmp() -- vor/ave_vor_p = %f <= 1.\n", vor/ave_vor_p); red_val = (char)ROUND( 255.*( 1. - 10000.*(vor/ave_vor_p)*(vor/ave_vor_p))); green_val = (char)ROUND( 255.*( 1. - 10000.*(vor/ave_vor_p)*(vor/ave_vor_p))); } } else { if( 100.*vor/ave_vor_n > 1.) { //printf("vor2bmp() -- vor/ave_vor_n = %f > 1.\n", vor/ave_vor_n); red_val = (char)0; blue_val = (char)0; } else { //printf("vor2bmp() -- vor/ave_vor_n = %f <= 1.\n", vor/ave_vor_n); red_val = (char)ROUND( 255.*( 1. - 10000.*(vor/ave_vor_n)*(vor/ave_vor_n))); blue_val = (char)ROUND( 255.*( 1. - 10000.*(vor/ave_vor_n)*(vor/ave_vor_n))); } } #else #if 0 blue_val = (char)0; green_val = (char)0; red_val = (char)0; // blue_val = //(char)ROUND( 255.*(vor - max_vor_n)/(max_vor_p-max_vor_n)); if( vor >= 0.) { blue_val = (char)ROUND( 255.*(vor)/(max_vor_p)); } else { red_val = (char)ROUND( 255.*(vor)/(max_vor_n)); } #else red_val = (char)ROUND( 255.*(vor - max_vor_n)/(max_vor_p-max_vor_n)); green_val = (char)ROUND( 255.*(vor - max_vor_n)/(max_vor_p-max_vor_n)); blue_val = (char)ROUND( 255.*(vor - max_vor_n)/(max_vor_p-max_vor_n)); #endif #endif val = (char)0; } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ //#if SOLID_COLOR_IS_BLACK // red_val = (char)0; // green_val = (char)0; // blue_val = (char)0; // val = (char)0; //#else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; //#endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_vor ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_vor ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_vor ) != 1) { printf("BOOM!\n"); process_exit(1);} } /* for( i=0; i<lattice->param.LY; i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o_vor ) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<lattice->param.LY; j++) */ fclose(o_vor ); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/vor%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); printf("vor2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("vor2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* vor2bmp( lattice_ptr lattice, int time) */ #if NON_LOCAL_FORCES // void force2bmp( char *filename, int time) //############################################################################## // // F O R C E 2 B M P // void force2bmp( lattice_ptr lattice) { FILE *in, *o_u, *o_ux, *o_uy; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double max_u[2], maxu; double u_x, u_y, u; int subs; #if SAY_HI printf("force2bmp() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = lattice->time/lattice->param.FrameRate; sprintf( filename, "./in/%dx%d.bmp", lattice->param.LX, lattice->param.LY); if( !( in = fopen( filename, "r"))) { printf("force2bmp() -- Error opening file \"%s\".\n", filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; compute_max_u( lattice, max_u, subs); sprintf( filename, "./out/force_%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); if( !( o_u = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/force_x_%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); if( !( o_ux = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/force_y_%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); if( !( o_uy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_u ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_u ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_ux ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_ux ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_uy); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_uy); //for( j=lattice->param.LY-1; j>=0; j--) for( j=0; j<lattice->param.LY; j++) { n = j*lattice->param.LX; for( i=0; i<lattice->param.LX; i++, n++) { if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { #if 1 blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->force[subs][ n].force[0]); u_y = (lattice->force[subs][ n].force[1]); u = sqrt(u_x*u_x + u_y*u_y); maxu = sqrt( max_u[0]*max_u[0] + max_u[1]*max_u[1]); if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); green_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); green_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); red_val = (char)ROUND( 128.*fabs(u)/maxu); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ #else blue_val = (char)255; green_val = (char)255; red_val = (char)255; u = sqrt(u_x*u_x + u_y*u_y); maxu = sqrt( max_u[0]*max_u[0] + max_u[1]*max_u[1]); //if( fabs(u) > .1*maxu) //{ green_val = (char)ROUND( 255.-255.*fabs(u)/maxu); red_val = (char)ROUND( 255.-255.*fabs(u)/maxu); blue_val = (char)ROUND( 255.-255.*fabs(u)/maxu); //} //else //{ // green_val = (char)0; // red_val = (char)0; // blue_val = (char)0; //} #endif val = (char)0; } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->force[subs][ n].force[0]); u_y = (lattice->force[subs][ n].force[1]); val = (char)0; if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); } else { red_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); } else { red_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->force[subs][ n].force[0]); u_y = (lattice->force[subs][ n].force[1]); val = (char)0; if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { red_val = val; green_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); } else { red_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); green_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { blue_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); green_val = val; } else { blue_val = val; green_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } /* for( i=0; i<lattice->param.LY; i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<lattice->param.LY; j++) */ fclose(o_u ); fclose(o_ux); fclose(o_uy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/force_%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); printf("force2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "./out/force_x_%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); printf("force2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "./out/force_y_%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); printf("force2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("force2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* void force2bmp( lattice_ptr lattice) */ // void sforce2bmp( char *filename, int time) //############################################################################## // // F O R C E 2 B M P // void sforce2bmp( lattice_ptr lattice) { FILE *in, *o_u, *o_ux, *o_uy; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double max_u[2], maxu; double u_x, u_y, u; int subs; #if SAY_HI printf("sforce2bmp() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = lattice->time/lattice->param.FrameRate; sprintf( filename, "./in/%dx%d.bmp", lattice->param.LX, lattice->param.LY); if( !( in = fopen( filename, "r"))) { printf("sforce2bmp() -- Error opening file \"%s\".\n", filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; compute_max_u( lattice, max_u, subs); sprintf( filename, "./out/sforce_%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); if( !( o_u = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/sforce_x_%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); if( !( o_ux = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "./out/sforce_y_%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); if( !( o_uy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_u ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_u ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_ux ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_ux ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_uy); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_uy); //for( j=lattice->param.LY-1; j>=0; j--) for( j=0; j<lattice->param.LY; j++) { n = j*lattice->param.LX; for( i=0; i<lattice->param.LX; i++, n++) { if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { #if 1 blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->force[subs][ n].sforce[0]); u_y = (lattice->force[subs][ n].sforce[1]); u = sqrt(u_x*u_x + u_y*u_y); maxu = sqrt( max_u[0]*max_u[0] + max_u[1]*max_u[1]); if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); green_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); green_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); red_val = (char)ROUND( 128.*fabs(u)/maxu); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ #else blue_val = (char)255; green_val = (char)255; red_val = (char)255; u = sqrt(u_x*u_x + u_y*u_y); maxu = sqrt( max_u[0]*max_u[0] + max_u[1]*max_u[1]); //if( fabs(u) > .1*maxu) //{ green_val = (char)ROUND( 255.-255.*fabs(u)/maxu); red_val = (char)ROUND( 255.-255.*fabs(u)/maxu); blue_val = (char)ROUND( 255.-255.*fabs(u)/maxu); //} //else //{ // green_val = (char)0; // red_val = (char)0; // blue_val = (char)0; //} #endif val = (char)0; } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->force[subs][ n].sforce[0]); u_y = (lattice->force[subs][ n].sforce[1]); val = (char)0; if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); } else { red_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); } else { red_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->force[subs][ n].sforce[0]); u_y = (lattice->force[subs][ n].sforce[1]); val = (char)0; if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { red_val = val; green_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); } else { red_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); green_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { blue_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); green_val = val; } else { blue_val = val; green_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } /* for( i=0; i<lattice->param.LY; i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<lattice->param.LY; j++) */ fclose(o_u ); fclose(o_ux); fclose(o_uy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "./out/sforce_%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); printf("sforce2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "./out/sforce_x_%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); printf("sforce2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "./out/sforce_y_%dx%d_frame%04d_subs%02d.bmp", lattice->param.LX, lattice->param.LY, frame, subs); printf("sforce2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("sforce2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* void sforce2bmp( lattice_ptr lattice) */ #endif /* NON_LOCAL_FORCES */ // void pdf2bmp( char *filename, int time) //############################################################################## // // P D F 2 B M P // void pdf2bmp( lattice_ptr lattice, int time) { FILE *in, *o; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double fval; double min_rho, max_rho; int subs; double **colormap; int num_colors; int fx=2, fy=2; // Number of pixels to use to represent a pdf value. #if SAY_HI printf("pdf2bmp() -- Hi!\n"); #endif /* SAY_HI */ // TODO: Implement pdf2bmp() printf("%s (%d) >> pdf2bmp() is not yet implemented. Exiting!\n", __FILE__, __LINE__); process_exit(1); #if SAY_HI printf("pdf2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* pdf2bmp( lattice_ptr lattice, int time) */ //void slice( lattice_ptr lattice) //############################################################################## // // - Extract slice (i0,j0)..(i1,j1) from the macroscopic variables. // // - Write to matlab scripts for easy processing. // void slice( lattice_ptr lattice) { int i0, j0, i1, j1; int i, j, n; int len; double *rho_slice; double *u_x_slice; double *u_y_slice; char filename[1024]; FILE *in, *o; int subs; if( use_slice_dot_in_file( lattice)) { printf("%s %d >> Using slice.in file.\n",__FILE__,__LINE__); if( !( in = fopen( "./in/slice.in", "r"))) { // Default slice. i0 = 0; j0 = (int)floor((double)lattice->param.LY/2.); i1 = lattice->param.LX-1; j1 = (int)floor((double)lattice->param.LY/2.); } else { // Read slice from file. fscanf( in, "%d", &i0); fscanf( in, "%d", &j0); fscanf( in, "%d", &i1); fscanf( in, "%d", &j1); fclose( in); } private_slice( lattice, "slice", i0, j0, i1, j1); } else { if( get_slice_x( lattice) >= 0) { private_slice( lattice, "slice_x", get_slice_x( lattice), 0, get_slice_x( lattice), get_LY( lattice) ); } if( get_slice_y( lattice) >= 0) { private_slice( lattice, "slice_y", 0, get_slice_y( lattice), get_LX( lattice), get_slice_y( lattice) ); } } } /* void slice( lattice_ptr lattice) */ //void private_slice( lattice_ptr lattice, int i0, int j0, int i1, int j1) //############################################################################## // // - Extract slice (i0,j0)..(i1,j1) from the macroscopic variables. // // - Write to matlab scripts for easy processing. // void private_slice( lattice_ptr lattice, char *root_word, int i0, int j0, int i1, int j1) { int i, j, k, n; int len, wid; double *rho_slice; double *rho_ave; double *u_x_slice; double *u_x_ave; double *u_y_slice; double *u_y_ave; char filename[1024]; FILE *in, *o; double ave_rho; int subs; char plot_specs[2][4] = { { '\'', 'b', '\'', '\x0'}, { '\'', 'r', '\'', '\x0'} }; if( i0 == i1) { if( i0 < 0 || i0 >= get_LX( lattice)) { printf("lbio.c: private_slice() -- " "ERROR: Can't take slice at " "i0 = i1 = %d.\n", i0 ); i0 = lattice->param.LX/2; i1 = lattice->param.LX/2; printf("lbio.c: private_slice() -- Defaulting to i0 = i1 = %d.\n", i0); return; } len = j1 - j0 + 1; if( len > lattice->param.LY) { len = lattice->param.LY; } rho_slice = (double*)malloc( len*sizeof(double)); rho_ave = (double*)malloc( len*sizeof(double)); u_x_slice = (double*)malloc( len*sizeof(double)); u_x_ave = (double*)malloc( len*sizeof(double)); u_y_slice = (double*)malloc( len*sizeof(double)); u_y_ave = (double*)malloc( len*sizeof(double)); // Generate matlab script to plot the slices. sprintf( filename, "./out/%s%dx%d_frame%04d.m", root_word, lattice->param.LX, lattice->param.LY, lattice->time/lattice->param.FrameRate); if( !( o = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fprintf( o, "%% function [ slice_data] = slice%dx%d_frame%04d( plot_stuff)\n", lattice->param.LX, lattice->param.LY, lattice->time/lattice->param.FrameRate); fprintf( o, "function [ slice_data] = slice%dx%d_frame%04d( plot_stuff)\n\n", lattice->param.LX, lattice->param.LY, lattice->time/lattice->param.FrameRate); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { // Slice. len = 0; for( j=j0; j<=j1; j++) { n = j*lattice->param.LX + i0; if( j>=0 && j<lattice->param.LY) { rho_slice[ len] = lattice->macro_vars[subs][ n].rho; u_x_slice[ len] = lattice->macro_vars[subs][ n].u[0]; u_y_slice[ len] = lattice->macro_vars[subs][ n].u[1]; rho_ave[ len] = 0.; u_x_ave[ len] = 0.; u_y_ave[ len] = 0.; wid = 0; for( i=0; i<lattice->param.LX; i++) { if( !( lattice->bc[subs][ j*lattice->param.LX + i].bc_type & BC_SOLID_NODE)) { rho_ave[ len] += lattice->macro_vars[subs][ j*lattice->param.LX+i].rho; u_x_ave[ len] += lattice->macro_vars[subs][ j*lattice->param.LX+i].u[0]; u_y_ave[ len] += lattice->macro_vars[subs][ j*lattice->param.LX+i].u[1]; wid++; } } rho_ave[ len] /= wid; u_x_ave[ len] /= wid; u_y_ave[ len] /= wid; len++; } } fprintf( o, "rho_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", rho_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "rho_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", rho_ave[ n]); } fprintf( o, "];\n"); fprintf( o, "u_x_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_x_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "u_x_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_x_ave[ n]); } fprintf( o, "];\n"); fprintf( o, "u_y_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_y_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "u_y_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_y_ave[ n]); } fprintf( o, "];\n"); } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ fprintf( o, "slice_data = zeros(%d,%d,%d);\n", len, 6, NUM_FLUID_COMPONENTS); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "slice_data(:,1,%d) = rho_slice%02d;\n", subs+1, subs); fprintf( o, "slice_data(:,2,%d) = rho_ave%02d;\n" , subs+1, subs); fprintf( o, "slice_data(:,3,%d) = u_x_slice%02d;\n", subs+1, subs); fprintf( o, "slice_data(:,4,%d) = u_x_ave%02d;\n" , subs+1, subs); fprintf( o, "slice_data(:,5,%d) = u_y_slice%02d;\n", subs+1, subs); fprintf( o, "slice_data(:,6,%d) = u_y_ave%02d;\n" , subs+1, subs); fprintf( o, "disp('slice_data(:,1,%d) = rho_slice%02d');\n", subs+1, subs); fprintf( o, "disp('slice_data(:,2,%d) = rho_ave%02d' );\n", subs+1, subs); fprintf( o, "disp('slice_data(:,3,%d) = u_x_slice%02d');\n", subs+1, subs); fprintf( o, "disp('slice_data(:,4,%d) = u_x_ave%02d' );\n", subs+1, subs); fprintf( o, "disp('slice_data(:,5,%d) = u_y_slice%02d');\n", subs+1, subs); fprintf( o, "disp('slice_data(:,6,%d) = u_y_ave%02d' );\n", subs+1, subs); } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ } /* if( i0 == i1) */ else if( j0 == j1) { if( j0 < 0 || j0 >= lattice->param.LY) { printf("lbio.c: private_slice() -- " "ERROR: Can't take slice at " "j0 = j1 = %d.\n", j0 ); j0 = lattice->param.LY/2; j1 = lattice->param.LY/2; printf("lbio.c: private_slice() -- Defaulting to j0 = j1 = %d.\n", j0); return; } len = i1 - i0 + 1; if( len > lattice->param.LX) { len = lattice->param.LX; } rho_slice = (double*)malloc( len*sizeof(double)); rho_ave = (double*)malloc( len*sizeof(double)); u_x_slice = (double*)malloc( len*sizeof(double)); u_x_ave = (double*)malloc( len*sizeof(double)); u_y_slice = (double*)malloc( len*sizeof(double)); u_y_ave = (double*)malloc( len*sizeof(double)); // Generate matlab script to plot the slices. sprintf( filename, "./out/%s%dx%d_frame%04d.m", root_word, lattice->param.LX, lattice->param.LY, lattice->time/lattice->param.FrameRate); if( !( o = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fprintf( o, "%% function [ slice_data] = slice%dx%d_frame%04d( plot_stuff)\n", lattice->param.LX, lattice->param.LY, lattice->time/lattice->param.FrameRate); fprintf( o, "function [ slice_data] = slice%dx%d_frame%04d( plot_stuff)\n\n", lattice->param.LX, lattice->param.LY, lattice->time/lattice->param.FrameRate); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { // Slice. len = 0; for( i=i0; i<=i1; i++) { n = j0*lattice->param.LX + i; if( i>=0 && i<lattice->param.LX) { rho_slice[ len] = lattice->macro_vars[subs][ n].rho; u_x_slice[ len] = lattice->macro_vars[subs][ n].u[0]; u_y_slice[ len] = lattice->macro_vars[subs][ n].u[1]; rho_ave[ len] = 0.; u_x_ave[ len] = 0.; u_y_ave[ len] = 0.; wid = 0; for( j=0; j<lattice->param.LY; j++) { if( !( lattice->bc[subs][ j*lattice->param.LX + i].bc_type & BC_SOLID_NODE)) { rho_ave[ len] += lattice->macro_vars[subs][ j*lattice->param.LX+i].rho; u_x_ave[ len] += lattice->macro_vars[subs][ j*lattice->param.LX+i].u[0]; u_y_ave[ len] += lattice->macro_vars[subs][ j*lattice->param.LX+i].u[1]; wid++; } } rho_ave[ len] /= wid; u_x_ave[ len] /= wid; u_y_ave[ len] /= wid; len++; } } fprintf( o, "rho_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", rho_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "rho_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", rho_ave[ n]); } fprintf( o, "];\n"); fprintf( o, "u_x_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_x_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "u_x_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_x_ave[ n]); } fprintf( o, "];\n"); if(1) { fprintf( o, "u_y_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_y_slice[ n]); } fprintf( o, "];\n"); } else { // // Output a series of slices showing entry length effects. // len = 0; // fprintf( o, "u_y_slice%02d_j%d = [ ", subs, j); // for( i=i0; i<=i1; i++) // { // n = j0*lattice->param.LX + i; // if( i>=0 && i<lattice->param.LX) // { // for( j=1; // j<lattice->param.LY-1; // j+=(int)floor(((double)lattice->param.LY/10.)) ) // { // fprintf( o, " %20.17f ", lattice->macro_vars[subs][ n].u[1]); // } // } // } // fprintf( o, "];\n"); } fprintf( o, "u_y_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_y_ave[ n]); } fprintf( o, "];\n"); } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ fprintf( o, "slice_data = zeros(%d,%d,%d);\n", len, 6, NUM_FLUID_COMPONENTS); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "slice_data(:,1,%d) = rho_slice%02d;\n", subs+1, subs); fprintf( o, "slice_data(:,2,%d) = rho_ave%02d;\n" , subs+1, subs); fprintf( o, "slice_data(:,3,%d) = u_x_slice%02d;\n", subs+1, subs); fprintf( o, "slice_data(:,4,%d) = u_x_ave%02d;\n" , subs+1, subs); fprintf( o, "slice_data(:,5,%d) = u_y_slice%02d;\n", subs+1, subs); fprintf( o, "slice_data(:,6,%d) = u_y_ave%02d;\n" , subs+1, subs); fprintf( o, "disp('slice_data(:,1,%d) = rho_slice%02d');\n", subs+1, subs); fprintf( o, "disp('slice_data(:,2,%d) = rho_ave%02d' );\n", subs+1, subs); fprintf( o, "disp('slice_data(:,3,%d) = u_x_slice%02d');\n", subs+1, subs); fprintf( o, "disp('slice_data(:,4,%d) = u_x_ave%02d' );\n", subs+1, subs); fprintf( o, "disp('slice_data(:,5,%d) = u_y_slice%02d');\n", subs+1, subs); fprintf( o, "disp('slice_data(:,6,%d) = u_y_ave%02d' );\n", subs+1, subs); } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ } /* if( i0 == i1) else if( j0 == j1) */ else { // Count. len = 0; for( i=i0; i<=i1; i++) { if( i>=0 && i<lattice->param.LX) { j = j0 + (i-i0)*((j1-j0)/(i1-i0)); if( j>=0 && j<lattice->param.LY) { len++; } } } rho_slice = (double*)malloc( len*sizeof(double)); rho_ave = (double*)malloc( len*sizeof(double)); u_x_slice = (double*)malloc( len*sizeof(double)); u_x_ave = (double*)malloc( len*sizeof(double)); u_y_slice = (double*)malloc( len*sizeof(double)); u_y_ave = (double*)malloc( len*sizeof(double)); // Generate matlab script to plot the slices. sprintf( filename, "./out/%s%dx%d_frame%04d.m", root_word, lattice->param.LX, lattice->param.LY, lattice->time/lattice->param.FrameRate); if( !( o = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { // Slice. len = 0; for( i=i0; i<=i1; i++) { if( i>=0 && i<lattice->param.LX) { j = j0 + (i-i0)*((j1-j0)/(i1-i0)); if( j>=0 && j<lattice->param.LY) { n = j*lattice->param.LX + i; if( n != -1) { rho_slice[ len] = lattice->macro_vars[subs][ n].rho; u_x_slice[ len] = lattice->macro_vars[subs][ n].u[0]; u_y_slice[ len] = lattice->macro_vars[subs][ n].u[1]; rho_ave[ len] = 0.; u_x_ave[ len] = 0.; u_y_ave[ len] = 0.; wid = 0; for( k=0; k<lattice->param.LY; k++) { if( !( lattice->bc[subs][ j*lattice->param.LX + i].bc_type & BC_SOLID_NODE)) { rho_ave[ len] += lattice->macro_vars[subs][ k*lattice->param.LX+i].rho; u_x_ave[ len] += lattice->macro_vars[subs][ k*lattice->param.LX+i].u[0]; u_y_ave[ len] += lattice->macro_vars[subs][ k*lattice->param.LX+i].u[1]; wid++; } } rho_ave[ len] /= wid; u_x_ave[ len] /= wid; u_y_ave[ len] /= wid; } else { rho_slice[ len] = 0.; rho_ave[ len] = 0.; u_x_slice[ len] = 0.; u_x_ave[ len] = 0.; u_y_slice[ len] = 0.; u_y_ave[ len] = 0.; } len++; } } } fprintf( o, "rho_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", rho_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "rho_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", rho_ave[ n]); } fprintf( o, "];\n"); fprintf( o, "u_x_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_x_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "u_x_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_x_ave[ n]); } fprintf( o, "];\n"); fprintf( o, "u_y_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_y_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "u_y_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_y_ave[ n]); } fprintf( o, "];\n"); } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ } /* if( i0 == i1) else if( j0 == j1) else */ free( rho_slice); free( rho_ave ); free( u_x_slice); free( u_x_ave ); free( u_y_slice); free( u_y_ave ); fprintf( o, "if( plot_stuff)\n"); // Plot density. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( rho_slice%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "warning off;"); fprintf( o, "title('\\rho slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( rho_slice%02d, %s);", subs, plot_specs[subs]); fprintf( o, "warning off;"); fprintf( o, "title('\\rho slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); fprintf( o, "warning on;"); } // Plot average density. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( rho_ave%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "warning off;"); fprintf( o, "title('\\rho_{ave} slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( rho_ave%02d, %s);", subs, plot_specs[subs]); fprintf( o, "warning off;"); fprintf( o, "title('\\rho_{ave} slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); fprintf( o, "warning on;"); } // Plot x velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( u_x_slice%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "warning off;"); fprintf( o, "title('u_x slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( u_x_slice%02d, %s);", subs, plot_specs[subs]); fprintf( o, "warning off;"); fprintf( o, "title('u_x slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); fprintf( o, "warning on;"); } // Plot average x-velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( u_x_ave%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "warning off;"); fprintf( o, "title('ux_{ave} slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( u_x_ave%02d, %s);", subs, plot_specs[subs]); fprintf( o, "warning off;"); fprintf( o, "title('ux_{ave} slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); fprintf( o, "warning on;"); } // Plot y velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( u_y_slice%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "warning off;"); fprintf( o, "title('u_y slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( u_y_slice%02d, %s);", subs, plot_specs[subs]); fprintf( o, "warning off;"); fprintf( o, "title('u_y slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); fprintf( o, "warning on;"); } // Plot average y-velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( u_y_ave%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "warning off;"); fprintf( o, "title('uy_{ave} slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( u_y_ave%02d, %s);", subs, plot_specs[subs]); fprintf( o, "warning off;"); fprintf( o, "title('uy_{ave} slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); fprintf( o, "warning on;"); } #if 1 // Compare with analytical poissuille flow profile. for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { if( lattice->param.gforce[subs][0] == 0 && lattice->param.gforce[subs][1] != 0 ) { // Poisseuille in y direction. fprintf( o, "disp(sprintf('\\nPoisseuille in y direction:'));\n"); fprintf( o, "figure;\n"); fprintf( o, "i0 = %d;\n", i0); fprintf( o, "i1 = %d;\n", i1); fprintf( o, "disp(sprintf(' [ i0 i1] = [ %%d %%d]',i0,i1));\n"); fprintf( o, "H = i1 - i0 + 1;\n"); fprintf( o, "disp(sprintf(' H = %%d', H));\n"); fprintf( o, "R = H/2;\n"); fprintf( o, "disp(sprintf(' R = H/2 = %%20.17f', R));\n"); fprintf( o, "nu = 1/6;\n"); fprintf( o, "disp(sprintf(' nu = %%20.17f', nu));\n"); compute_ave_rho( lattice, &ave_rho, subs); fprintf( o, "rho_ave = %20.17f;\n", ave_rho); fprintf( o, "disp(sprintf(' rho_ave = %%20.17f', rho_ave));\n"); //fprintf( o, "mu = nu*%20.17f;\n", ave_rho); //fprintf( o, "disp(sprintf(' mu = %%20.17f', mu));\n"); fprintf( o, "gforceval = %20.17f;\n", lattice->param.gforce[subs][1]/lattice->param.tau[subs]); fprintf( o, "disp(sprintf(' gforceval = %%20.17f', gforceval));\n"); fprintf( o, "i = [i0:.1:i1];\n" "ucalc = " "( gforceval / (2*nu)) * " "( R^2 - ( abs( i - (i1+i0)/2 ).^2));\n" ); fprintf( o, "disp(sprintf(' size(ucalc) = %%dx%%d\\n',size(ucalc,1),size(ucalc,2)));\n"); fprintf( o, "plot( i, ucalc, 'k');"); fprintf( o, "title('analytical Poiseuille profile');\n"); fprintf( o, "figure;\n"); fprintf( o, "hold on;\n"); fprintf( o, "plot( i, ucalc, 'k');\n"); fprintf( o, "plot( u_y_slice%02d, 'bo');", subs); fprintf( o, "title('LB results overlaying analytical Poiseuille profile');\n"); fprintf( o, "hold off;\n"); } /* if( lattice->param.gforce[subs][0] == 0 && lattice->param.gforce... */ else if( lattice->param.gforce[subs][1] == 0 && lattice->param.gforce[subs][0] != 0 ) { // Poisseuille in x direction. fprintf( o, "disp(sprintf('\\nPoisseuille in x direction:'));\n"); fprintf( o, "figure;\n"); fprintf( o, "j0 = %d;\n", j0); fprintf( o, "j1 = %d;\n", j1); fprintf( o, "disp(sprintf(' [ j0 j1] = [ %%d %%d]',j0,j1));\n"); fprintf( o, "H = j1 - j0 + 1;\n"); fprintf( o, "disp(sprintf(' H = %%d', H));\n"); fprintf( o, "R = H/2;\n"); fprintf( o, "disp(sprintf(' R = H/2 = %%20.17f', R));\n"); fprintf( o, "nu = 1/6;\n"); fprintf( o, "disp(sprintf(' nu = %%20.17f', nu));\n"); compute_ave_rho( lattice, &ave_rho, subs); fprintf( o, "rho_ave = %20.17f;\n", ave_rho); fprintf( o, "disp(sprintf(' rho_ave = %%20.17f', rho_ave));\n"); //fprintf( o, "mu = nu*%20.17f;\n", ave_rho); //fprintf( o, "disp(sprintf(' mu = %%20.17f', mu));\n"); fprintf( o, "gforceval = %20.17f;\n", lattice->param.gforce[subs][0]/lattice->param.tau[subs]); fprintf( o, "disp(sprintf(' gforceval = %%20.17f', gforceval));\n"); fprintf( o, "j = [j0:.1:j1];" "ucalc = " "( gforceval / (2*nu)) * " "( R^2 - ( abs( j - (j1+j0)/2 ).^2));\n" ); fprintf( o, "disp(sprintf(' size(ucalc) = %%dx%%d\\n'," "size(ucalc,1),size(ucalc,2)));\n"); fprintf( o, "plot( j, ucalc, 'k');"); fprintf( o, "title('analytical Poiseuille profile');\n"); fprintf( o, "figure;\n"); fprintf( o, "hold on;\n"); fprintf( o, "plot( j, ucalc, 'k');\n"); fprintf( o, "plot( u_x_slice%02d, 'bo');", subs); fprintf( o, "title('LB results overlaying analytical " "Poiseuille profile');\n"); fprintf( o, "hold off;\n"); //printf( o, "figure;\n"); //fprintf( o, "plot( ucalc(j0+1:10:10*j1+1) - u_x_slice%02d, 'r');", subs); //fprintf( o, "title( 'ucalc - u_x_slice%02d');\n", subs); } /* if( lattice->param.gforce[subs][0] == 0 && lattice->param.gforce... */ // Slice key. (Shows where in the domain the slice cuts.) fprintf( o, "figure; plot( [ %d %d], [ %d %d], 'r-.');", i0, i1, j0, j1); fprintf( o, "axis equal;"); fprintf( o, "axis([ %d %d %d %d]);", 0, lattice->param.LX-1, 0, lattice->param.LY-1); fprintf( o, "title('Slice key.');\n"); #if VERBOSITY_LEVEL > 0 printf("private_slice() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #endif fprintf( o, "end\n"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "disp(sprintf('q_x = %%f',rho_slice%02d*u_x_slice%02d'/max(size(rho_slice%02d))'));\n", subs, subs, subs); fprintf( o, "disp(sprintf('q_y = %%f',rho_slice%02d*u_y_slice%02d'/max(size(rho_slice%02d))'));\n", subs, subs, subs); } fclose(o); } /* void private_slice( lattice_ptr lattice, int i0, int j0, int i1, int j1) */ #if INAMURO_SIGMA_COMPONENT && STORE_BTC void dump_sigma_btc( lattice_ptr lattice) { FILE *o; char fn[1024]; int n; double D; int btc_spot, start_time; if( lattice->param.sigma_btc_rate <= 0 || lattice->FlowDir==0) { return; } btc_spot = (lattice->param.sigma_btc_spot >= 0) ? (lattice->param.sigma_btc_spot-1) : (((lattice->FlowDir==1)?(lattice->param.LX):(lattice->param.LY))-2-1); start_time = (lattice->param.sigma_start>0) ?(lattice->param.sigma_start) :(0); sprintf( fn, "./out/sigma_btc.m"); o = fopen( fn, "w+"); // Timesteps where measurements are taken. fprintf( o, "ts = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", lattice->param.sigma_btc[5*n+0]-start_time); } fprintf( o, "];\n"); // Break through curve at sigma_spot-1. fprintf( o, "btc01 = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", lattice->param.sigma_btc[5*n+1]); } fprintf( o, "];\n"); // Break through curve at sigma_spot. fprintf( o, "btc02 = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", lattice->param.sigma_btc[5*n+2]); } fprintf( o, "];\n"); // Break through curve at sigma_spot+1. fprintf( o, "btc03 = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", lattice->param.sigma_btc[5*n+3]); } fprintf( o, "];\n"); // Velocity at sigma_spot. fprintf( o, "btc_v = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", lattice->param.sigma_btc[5*n+4]); } fprintf( o, "];\n"); // Concentration gradient. fprintf( o, "dcdx = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", .5*( lattice->param.sigma_btc[5*n+3] - lattice->param.sigma_btc[5*n+1]) ); } fprintf( o, "];\n"); // C*v. fprintf( o, "Cv = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", //lattice->param.sigma_btc[4*n+1]*lattice->param.sigma_btc[4*n+3] ); ( lattice->param.sigma_btc[5*n+2]*lattice->param.sigma_btc[5*n+4]) ); } fprintf( o, "];\n"); // Cf = ( C*v - D*dcdx) / v. D = (1./3.)*(lattice->param.tau[1] - .5); fprintf( o, "Cf = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", ( ( lattice->param.sigma_btc[5*n+2]*lattice->param.sigma_btc[5*n+4]) - ( D)*.5*( lattice->param.sigma_btc[5*n+3] - lattice->param.sigma_btc[5*n+1]) ) / ( lattice->param.sigma_btc[5*n+4]) ); } fprintf( o, "];\n"); fprintf( o, "D = %20.17f;\n", D); fprintf( o, "disp(sprintf('D = %%20.17f',D));\n"); // Plot btc01. //fprintf( o, "figure; plot(btc01);\n"); //fprintf( o, "axis([ %d %d 0 max(max(btc01),%20.17f)])\n", // 1, lattice->SizeBTC+1, lattice->param.rho_sigma); //fprintf( o, "title('BTC at L=%d, t=%d:%d:%d');\n", // btc_spot-1, start_time, // lattice->param.sigma_btc_rate, // lattice->NumTimeSteps ); fprintf( o, "figure;\n"); // SubPlot btc0{1,2,3}. fprintf( o, "subplot(2,2,1);\n"); fprintf( o, "hold on; plot(btc01);\n"); fprintf( o, "hnd = get(gca,'Children');\n"); fprintf( o, "set( hnd(1), 'Color', [ .8 .8 .8]);\n"); fprintf( o, "hold on; plot(btc03);\n"); fprintf( o, "hnd = get(gca,'Children');\n"); fprintf( o, "set( hnd(1), 'Color', [ .8 .8 .8]);\n"); fprintf( o, "hold on; plot(btc02);\n"); fprintf( o, "set(gca,'Xlim',[ 0 size(btc02,1)])\n"); //fprintf( o, "axis([ %d %d 0 max(max(btc02),%20.17f)])\n", // 1, lattice->SizeBTC+1, lattice->param.rho_sigma); fprintf( o, "title('BTC at L\\in\\{%d,%d,%d\\}, t=%d:%d:%d');\n", btc_spot-1, btc_spot, btc_spot+1, start_time, lattice->param.sigma_btc_rate, lattice->NumTimeSteps ); // Plot btc03. //fprintf( o, "figure; plot(btc03);\n"); //fprintf( o, "axis([ %d %d 0 max(max(btc03),%20.17f)])\n", // 1, lattice->SizeBTC+1, lattice->param.rho_sigma); //fprintf( o, "title('BTC at L=%d, t=%d:%d:%d');\n", // btc_spot+1, start_time, // lattice->param.sigma_btc_rate, // lattice->NumTimeSteps ); // SubPlot C*v. fprintf( o, "subplot(2,2,2);\n"); fprintf( o, "plot(Cv);\n"); fprintf( o, "set(gca,'Xlim',[ 0 size(btc02,1)]);\n"); fprintf( o, "title('C*v at L=%d, t=%d:%d:%d');\n", btc_spot, start_time, lattice->param.sigma_btc_rate, lattice->NumTimeSteps ); // SubPlot dcdx. fprintf( o, "subplot(2,2,3);\n"); fprintf( o, "plot(dcdx);\n"); fprintf( o, "set(gca,'Xlim',[ 0 size(btc02,1)]);\n"); fprintf( o, "title('dc/dx at L=%d, t=%d:%d:%d');\n", btc_spot, start_time, lattice->param.sigma_btc_rate, lattice->NumTimeSteps ); // SubPlot Cf. fprintf( o, "subplot(2,2,4);\n"); fprintf( o, "plot(Cf);\n"); fprintf( o, "set(gca,'Xlim',[ 0 size(btc02,1)]);\n"); fprintf( o, "title('Cf=(C*v-D*(dC/dx))/v at L=%d, t=%d:%d:%d');\n", btc_spot, start_time, lattice->param.sigma_btc_rate, lattice->NumTimeSteps ); // Give figure a name (shows up in title bar). fprintf( o, "set(gcf,'Name','Breakthrough curve data at t=%d:%d:%d');\n", start_time, lattice->param.sigma_btc_rate, lattice->NumTimeSteps ); // Plot [Cr(x),'r'][Cr(x-dx),'m'][Cv(x),'g'][Cf(x),'b'] fprintf( o, "figure;\n"); fprintf( o, "hold on;\n"); fprintf( o, "plot( btc02, 'rx');\n"); fprintf( o, "plot(Cf, 'bo');\n"); fprintf( o, "hold off;\n"); fprintf( o, "set(gca,'Xlim',[ 0 size(btc02,1)]);\n"); fprintf( o, "title('Cr=''rx'', Cf=''bo''');\n"); // Give figure a name (shows up in title bar). fprintf( o, "set(gcf,'Name','Resident C_r and flux averaged C_f concentrations " "at t=%d:%d:%d');\n", start_time, lattice->param.sigma_btc_rate, lattice->NumTimeSteps ); // Turn off figure number in title bar. fprintf( o, "set(gcf,'NumberTitle','off');\n"); fprintf( o, "%% FlowDir = %d;\n", lattice->FlowDir); fclose(o); printf("\nBTC (size=%d) stored in file \"%s\".\n", lattice->SizeBTC, fn); } /* void dump_sigma_btc( lattice_ptr lattice) */ #endif /* INAMURO_SIGMA_COMPONENT && STORE_BTC */ //void count_colormap( int *num_colors) //############################################################################## // // C O U N T C O L O R M A P // // - Count colormap entries in file colormap.rgb . // void count_colormap( int *num_colors) { FILE *in; char filename[1024]; double r, g, b; // First, count the number of entries. sprintf( filename, "%s", "./in/colormap.rgb"); if( !( in = fopen( filename, "r+"))) { printf("Error opening file \"%s\" for reading. Exiting!\n", filename); process_exit(1); } *num_colors = 0; fscanf( in, "%lf %lf %lf", &r, &g, &b); while( !feof(in)) { (*num_colors)++; fscanf( in, "%lf %lf %lf", &r, &g, &b); } fclose(in); } /* void count_colormap( int *num_colors) */ //void allocate_colormap( double ***colormap, int *num_colors) //############################################################################## // // A L L O C A T E C O L O R M A P // void allocate_colormap( double ***colormap, int num_colors) { int i; *colormap = (double**)malloc( num_colors*sizeof(double*)); for( i=0; i<num_colors; i++) { (*colormap)[i] = (double*)malloc( 3*sizeof(double)); } } /* void allocate_colormap( double ***colormap, int num_colors) */ //void read_colormap( double **colormap, int num_colors) //############################################################################## // // R E A D C O L O R M A P // // - Read colormap from file colormap.rgb . // // - Color map values are stored with one set of rgb values per line. // // - RGB values are stored between 0 and 1 . // // - Colormap values could come from Matlab, e.g. // // >> cm = colormap; // >> save 'colormap.rgb' cm -ascii; // void read_colormap( double **colormap, int num_colors) { FILE *in; char filename[1024]; double r, g, b; int n; sprintf( filename, "%s", "./in/colormap.rgb"); if( !( in = fopen( filename, "r+"))) { printf("Error opening file \"%s\" for reading. Exiting!\n", filename); process_exit(1); } n = 0; fscanf( in, "%lf %lf %lf", &r, &g, &b); while( !feof(in)) { assert( n!=num_colors); colormap[n][0] = r; colormap[n][1] = g; colormap[n][2] = b; n++; fscanf( in, "%lf %lf %lf", &r, &g, &b); } fclose(in); } /* void read_colormap( double **colormap, int num_colors) */ //void deallocate_colormap( double ***colormap, int num_colors) //############################################################################## // // D E A L L O C A T E C O L O R M A P // void deallocate_colormap( double ***colormap, int num_colors) { int i; for( i=0; i<num_colors; i++) { free( (*colormap)[i]); } free( *colormap); } /* void deallocate_colormap( double ***colormap, int num_colors) */ void get_color( double **colormap, int num_colors, double c, char *r, char *g, char *b) { int n; double n1, n2; double w1, w2; if( c>=0. && c<=1.) { #if 1 n = (int)ROUND( c*((double)num_colors-1.)); // printf("get_color() -- c = %f, num_colors = %d, n = %d\n", c, num_colors, n); *r = (char)ROUND(255.*colormap[ n][0]); *g = (char)ROUND(255.*colormap[ n][1]); *b = (char)ROUND(255.*colormap[ n][2]); // printf("get_color() -- n = %d, (%f,%f,%f)\n", n, (double)*r, (double)*g, (double)*b); #else n1 = floor( c*((double)num_colors-1.)); n2 = ceil( c*((double)num_colors-1.)); w1 = c-n1; w2 = n2-c; *r = (char)ROUND(255.* ( w1*colormap[ (int)n1][0] + w2*colormap[ (int)n2][0])); *g = (char)ROUND(255.* ( w1*colormap[ (int)n1][1] + w2*colormap[ (int)n2][1])); *b = (char)ROUND(255.* ( w1*colormap[ (int)n1][2] + w2*colormap[ (int)n2][2])); #endif } else { *r = (char)(255.); *g = (char)(255.); *b = (char)(255.); } } /* void get_color( double **colormap, int num_colors, double c, ... */ #if WRITE_CHEN_DAT_FILES void chen_output( lattice_ptr lattice) { int x, y; int LX = lattice->param.LX, LY = lattice->param.LY; double *u, *rho[NUM_FLUID_COMPONENTS]; double ux_sum, uy_sum, rho_in, rho_out; FILE *app7, *app8, *app9; char filename[1024]; double sum_mass[NUM_FLUID_COMPONENTS]; int subs; ux_sum = 0.; uy_sum = 0.; for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { sum_mass[ subs] = 0.; } sprintf( filename, "%s", "./out/chen_xyrho.dat"); if( !( app7 = fopen( filename,"a"))) { printf("Error opening \"%s\" for reading. Exiting!\n", filename); process_exit(1); } sprintf( filename, "%s", "./out/chen_xy_ux_uy.dat"); if( !( app8 = fopen( filename,"a"))) { printf("Error opening \"%s\" for reading. Exiting!\n", filename); process_exit(1); } sprintf( filename, "%s", "./out/chen_time.dat"); if( !( app9 = fopen( filename,"a"))) { printf("Error opening \"%s\" for reading. Exiting!\n", filename); process_exit(1); } #if STORE_U_COMPOSITE u = lattice->upr[0].u; #else /* !( STORE_U_COMPOSITE) */ u = lattice->macro_vars[0][0].u; #endif /* STORE_U_COMPOSITE */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { rho[subs] = &( lattice->macro_vars[subs][0].rho); } for( y = 0; y < LY; y++) { for( x = 0; x < LX; x++) { fprintf( app8, " %9.1f %9.1f %13.5e %13.5e\n", (double)(x+1.), (double)(y+1.), *u, *(u+1)); if( !( lattice->bc[0][ y*LX + x].bc_type & BC_SOLID_NODE)) { ux_sum = ux_sum + *u; uy_sum = uy_sum + *(u+1); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { sum_mass[subs] = sum_mass[subs] + *rho[subs]; } } /* if( !obst[y][x]) */ #if STORE_U_COMPOSITE u+=2; #else /* !( STORE_U_COMPOSITE) */ u+=3; #endif /* STORE_U_COMPOSITE */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { rho[subs]+=3; } } /* for( x = 1; x <= LX; x++) */ } /* for( y = 1; y <= LY; y++) */ fprintf( app9, "%10d %15.7f %15.7f ", lattice->time, ux_sum, uy_sum); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( app9, "%15.7f ", sum_mass[subs]); } fprintf( app9, "\n"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { rho[subs] = &( lattice->macro_vars[subs][0].rho); } for( y = 0; y < LY; y++) { for( x = 0; x < LX; x++) { if( !( lattice->bc[0][ y*LX + x].bc_type & BC_SOLID_NODE)) { for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( app7, "%f ", *rho[subs]); } fprintf( app7, "\n"); } else { for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( app7, "%f ", 0.); } fprintf( app7, "\n"); } for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { rho[subs]+=3; } } /* for( x = 1; x <= LX; x++) */ } /* for( y = 1; y <= LY; y++) */ fclose( app7); fclose( app8); fclose( app9); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s", "./out/chen_xyrho.dat"); printf("chen_output() -- Wrote file \"%s\".\n", filename); sprintf( filename, "%s", "./out/chen_xy_ux_uy.dat"); printf("chen_output() -- Wrote file \"%s\".\n", filename); sprintf( filename, "%s", "./out/chen_time.dat"); printf("chen_output() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* void chen_output( lattice_ptr lattice) */ #endif /* WRITE_CHEN_DAT_FILES */ //void bmp_read_header( FILE *in) //############################################################################## // // B M P R E A D H E A D E R // void bmp_read_header( FILE *in, struct bitmap_info_header *bmih) { char filename[1024]; int i, j, n, m; int ei, ej; int pad, bytes_per_row; char k; char b, g, r; struct bitmap_file_header bmfh; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; int subs; // Read the headers. n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih->biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } printf("%s %d >> biWidth = %d\n", __FILE__, __LINE__, bmih->biWidth); width_ptr = (int*)bmih->biWidth; height_ptr = (int*)bmih->biHeight; bitcount_ptr = (short int*)bmih->biBitCount; // Read the palette, if necessary. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; } /* void bmp_read_header( FILE *in) */ //void bmp_read_entry( FILE *in, char *r, char *g, char *b) //############################################################################## // // B M P R E A D E N T R Y // void bmp_read_entry( FILE *in, struct bitmap_info_header bmih, char *r, char *g, char *b) { char filename[1024]; int i, j, m; static int n=0; int ei, ej; int pad, bytes_per_row; char k, p; struct bitmap_file_header bmfh; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; int subs; width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; if( (n%(bytes_per_row+pad)) == 3*(*width_ptr)) { // Read pad bytes first. for( i=1; i<=pad; i++) { if( !feof(in)) { n+=( k = fread( &p, 1, 1, in ));} } } if( feof(in)) { printf( "bmp_read_entry() -- ERROR:" "Attempt to read past the end of file. " "Exiting!\n"); process_exit(1); } switch(ENDIAN2(*bitcount_ptr)) { case 1: // Monochrome. printf("read_bcs() -- " "Support for Monochrome BMPs is pending. " "Exiting!\n"); process_exit(1); case 4: // 16 colors. printf("read_bcs() -- " "Support for 16 color BMPs is pending. " "Exiting!\n"); process_exit(1); case 8: // 256 colors. printf("read_bcs() -- " "Support for 256 color BMPs is pending. " "Exiting!\n"); process_exit(1); case 24: // 24-bit colors. if( !feof(in)) { n+=( k = fread( b, 1, 1, in ));} if( !feof(in)) { n+=( k = fread( g, 1, 1, in ));} if( !feof(in)) { n+=( k = fread( r, 1, 1, in ));} break; default: // 32-bit colors? printf("ERROR: Unhandled color depth, " "BitCount = %d. Exiting!\n", ENDIAN2(*bitcount_ptr)); process_exit(1); break; } /* switch(*(bmih.biBitCount)) */ if( feof(in)) { printf( "bmp_read_entry() -- ERROR:" "Attempt to read past the end of file. " "Exiting!\n"); process_exit(1); } } /* void bmp_read_entry( FILE *in, char *r, char *g, char *b) */ void report_open( report_ptr report, char *name) { sprintf( report->name, "%s.txt", name); #if VERBOSITY_LEVEL >=1 printf( "\n"); printf( "%s\n", HRULE1); printf( " R E P O R T\n"); printf( "%s\n", HRULE1); printf( "\n"); #endif /* VERBOSITY_LEVEL > 1 */ if( !( report->file = fopen( report->name, "w+"))) { printf("%s %d: ERROR: fopen( %s, \"w+\") = %d\n", __FILE__, __LINE__, report->name, (int)(report->file)); } else { fprintf( report->file, "\n"); fprintf( report->file, "%s\n", HRULE1); fprintf( report->file, " R E P O R T\n"); fprintf( report->file, "%s\n", HRULE1); fprintf( report->file, "\n"); } } /* void report_open( report_ptr report, char *name) */ void report_close( report_ptr report) { #if VERBOSITY_LEVEL >=1 printf( "%s\n", HRULE1); printf( "\n"); #endif /* VERBOSITY_LEVEL >=1 */ if( report->file) { //fprintf( report->file, ""); fprintf( report->file, "\n"); fclose( report->file); #if VERBOSITY_LEVEL >=1 printf( "See file \"%s\".\n", report->name); #endif /* VERBOSITY_LEVEL >=1 */ } /* if( report->file) */ } /* void report_close( report_ptr report) */ void report_entry( report_ptr report, char *entry_left, char *entry_right) { char dots[80]; const int left_col_width = 50; int n; // Fill with dots between columns. Careful if length of left // entry is too long. if( left_col_width > strlen(entry_left) + 2) { dots[ 0] = ' '; for( n=1; n<left_col_width-strlen(entry_left); n++) { dots[n]='.'; } dots[ n ] = ' '; dots[ n+1] = (char)NULL; } else if( left_col_width > strlen(entry_left)) { dots[ 0] = ' '; dots[ left_col_width-strlen(entry_left)-1] = ' '; dots[ left_col_width-strlen(entry_left) ] = ' '; dots[ left_col_width-strlen(entry_left)+1] = (char)NULL; } else { dots[0] = ' '; dots[1] = (char)NULL; } #if VERBOSITY_LEVEL >=1 printf(" %s%s%s\n", entry_left, dots, entry_right); //printf("\n"); #endif /* VERBOSITY_LEVEL >=1 */ if( report->file) { fprintf( report->file, " %s%s%s\n", entry_left, dots, entry_right); //fprintf( report->file, "\n"); } } /* void report_entry( char *entry_left, char *entry_right) */ void report_integer_entry( report_ptr report, char *label, int value, char *units) { char entry[1024]; sprintf( entry, "%d %s", value, units); report_entry( report, label, entry); } /* void report_integer_entry( char *label, int value, char *units) */ void report_ratio_entry( report_ptr report, char *label, double num, double den, char *units) { char entry[1024]; if( den!=0) { sprintf( entry, "%f %s", num/den, units); } else { sprintf( entry, "UNDEF %s", units); } report_entry( report, label, entry); } /* void report_integer_entry( char *label, int value, char *units) */ void report_partition( report_ptr report) { printf( "%s\n", HRULE0); printf( "\n"); if( report->file) { fprintf( report->file, "%s\n", HRULE0); fprintf( report->file, "\n"); } } /* void report_partition( report_ptr report) */ //
111pjb-one
src/lbio_endian.c
C
gpl3
173,688
//############################################################################## // // lbio.c // // - Lattice Boltzmann I/O routines. // // - Mainly, dump the data to files that can be read by Matlab. // // - Also, output routines for facilitating debugging. // // - Should have a routine that dumps a matlab script? // // Some compilers, e.g., VC++, don't have the usual round() function // in their math library. Alternatively, ROUND can be defined as // ceil or floor or some other rounding function. It is used in // the below routines for converting the real number valued of // quantities at a lattice node into integer RGB values for writing // to BMP files. #define ROUND floor //#if SWAP_BYTE_ORDER || OSTYPE==darwin #if SWAP_BYTE_ORDER // Swap byte order. #define ENDIAN2(w) ((((w)&0x00ff)<<8)|(((w)&0xff00)>>8)) #define ENDIAN4(w) ((((w)&0x000000ff)<<24)|(((w)&0xff000000)>>24)|(((w)&0x0000ff00)<<8)|(((w)&0x00ff0000)>>8)) #else /* !( SWAP_BYTE_ORDER) */ #define ENDIAN2(w) (w) #define ENDIAN4(w) (w) #endif /* SWAP_BYTE_ORDER */ #define X2N( x, d) (int)( (((double)d-1.)/(double)d)*floor( ((double)(d))*((double)(x)))) // O U T P U T F R A M E {{{ //############################################################################## //void output_frame( lattice_ptr lattice) // void output_frame( lattice_ptr lattice) { double s, u[2]; double nu; int L; #if VERBOSITY_LEVEL > 0 printf("\n"); printf( "========================================" "========================================\n"); printf("Begin file I/O at time = %d, frame = %d.\n", lattice->time, lattice->frame); printf("\n"); #endif /* VERBOSITY_LEVEL > 0 */ dump_frame_summary( lattice); #if WRITE_MACRO_VAR_DAT_FILES dump_macro_vars( lattice, lattice->time); #endif /* WRITE_MACRO_VAR_DAT_FILES */ #if WRITE_PDF_DAT_FILES dump_pdf( lattice, lattice->time); #endif /* WRITE_PDF_DAT_FILES */ if( lattice->param.dump_rho) { rho2bmp( lattice, lattice->time);} if( lattice->param.dump_u ) { u2bmp( lattice, lattice->time);} if( lattice->param.dump_vor) { vor2bmp( lattice, lattice->time);} #if NON_LOCAL_FORCES if( lattice->param.G != 0.) { if( lattice->param.dump_force) { force2bmp( lattice);} } if( lattice->param.Gads[0] != 0. || lattice->param.Gads[1] != 0.) { if( lattice->param.dump_force) { sforce2bmp( lattice);} } #endif /* NON_LOCAL_FORCES */ slice( lattice); #if WRITE_CHEN_DAT_FILES chen_output( lattice); #endif /* WRITE_CHEN_DAT_FILES */ #if VERBOSITY_LEVEL > 0 printf("\n"); printf("File I/O done.\n"); printf("--\n"); #endif /* VERBOSITY_LEVEL > 0 */ nu = (1./3.)*(lattice->param.tau[0] - .5); L = lattice->param.length_scale; compute_ave_u( lattice, u, 0); s = sqrt( u[0]*u[0] + u[1]*u[1]); printf("p%02d, subs 0: Re = ux_ave*L/nu = %20.17f * %d / %20.17f = %20.17f\n", get_proc_id(lattice), u[0], L, nu, u[0]*L/nu ); printf("p%02d, subs 0: Re = uy_ave*L/nu = %20.17f * %d / %20.17f = %20.17f\n", get_proc_id(lattice), u[1], L, nu, u[1]*L/nu ); printf("p%02d, subs 0: Re = u_ave*L/nu = %20.17f * %d / %20.17f = %20.17f\n", get_proc_id(lattice), s, L, nu, s*L/nu ); #if NUM_FLUID_COMPONENTS == 2 compute_ave_u( lattice, u, 1); s = sqrt( u[0]*u[0] + u[1]*u[1]); printf("p%02d, subs 1: Re = ux_ave*L/nu = %20.17f * %d / %20.17f = %20.17f\n", get_proc_id(lattice), u[0], L, nu, u[0]*L/nu ); printf("p%02d, subs 1: Re = uy_ave*L/nu = %20.17f * %d / %20.17f = %20.17f\n", get_proc_id(lattice), u[1], L, nu, u[1]*L/nu ); printf("p%02d, subs 1: Re = u_ave*L/nu = %20.17f * %d / %20.17f = %20.17f\n", get_proc_id(lattice), s, L, nu, s*L/nu ); #endif /* NUM_FLUID_COMPONENTS == 2 */ #if STORE_U_COMPOSITE compute_ave_upr( lattice, u); s = sqrt( u[0]*u[0] + u[1]*u[1]); printf("p%02d, eq: Re = ux_ave*L/nu = %20.17f * %d / %20.17f = %20.17f\n", get_proc_id(lattice), u[0], L, nu, u[0]*L/nu ); printf("p%02d, eq: Re = uy_ave*L/nu = %20.17f * %d / %20.17f = %20.17f\n", get_proc_id(lattice), u[1], L, nu, u[1]*L/nu ); printf("p%02d, eq: Re = u_ave*L/nu = %20.17f * %d / %20.17f = %20.17f\n", get_proc_id(lattice), s, L, nu, s*L/nu ); #endif /* STORE_U_COMPOSITE */ } /* void output_frame( lattice_ptr lattice) */ // }}} // D U M P F R A M E I N F O {{{ //############################################################################## // void dump_frame_info( struct lattice_struct *lattice) // void dump_frame_summary( struct lattice_struct *lattice) { char filename[1024]; FILE *o; double min_u[5], max_u[5], ave_u[5], flux[3]; double min_rho, max_rho, ave_rho; double rho_ratio, u_x_ratio, u_y_ratio; int subs; for( subs = 0; subs < NUM_FLUID_COMPONENTS; subs++) { if( is_incompressible( lattice) && annotate_incompressible_filenames( lattice)) { sprintf( filename, "%s/frames%dx%di_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), subs, get_proc_id(lattice)); } else { sprintf( filename, "%s/frames%dx%d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), subs, get_proc_id(lattice)); } // On the first timestep, make sure we start with a new file. if( lattice->time==0) { if( !( o = fopen(filename,"w+"))) { printf("ERROR: fopen(\"%s\",\"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } else { // Put a header on the file. fprintf( o, "\n"); fprintf( o, " time " " |j| " " j_x " " j_y " " ave |u| " " ave |u_x| " " ave |u_y| " " ave u_x " " ave u_y " " min |u| " " min |u_x| " " min |u_y| " " min u_x " " min u_y " " max |u| " " max |u_x| " " max |u_y| " " max u_x " " max u_y " " max/ave_x " " max/ave_y " " min rho " " max rho " " ave rho " " max/ave " "\n"); fprintf( o, " -----------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" " --------------------" "\n"); fclose(o); } } if( !( o = fopen(filename,"a+"))) { printf("ERROR: fopen(\"%s\",\"a+\") = NULL. Bye, bye!\n", filename); process_exit(1); } compute_min_u_all( lattice, min_u, subs); compute_max_u_all( lattice, max_u, subs); compute_ave_u_all( lattice, ave_u, subs); compute_min_rho( lattice, &min_rho, subs); compute_max_rho( lattice, &max_rho, subs); compute_ave_rho( lattice, &ave_rho, subs); rho_ratio = ( ave_rho != 0.) ? ( max_rho /ave_rho ):( 1.); u_x_ratio = ( ave_u[1] != 0.) ? ( max_u[1]/ave_u[0]):( 1.); u_y_ratio = ( ave_u[2] != 0.) ? ( max_u[2]/ave_u[1]):( 1.); compute_flux( lattice, flux, subs); fprintf( o, "%12d " "%20.17f %20.17f %20.17f %20.17f %20.17f %20.17f %20.17f %20.17f %20.17f " "%20.17f %20.17f %20.17f %20.17f %20.17f %20.17f %20.17f %20.17f %20.17f " "%20.17f %20.17f %20.17f %20.17f %20.17f %20.17f\n", lattice->time, flux [0], flux [1], flux [2], ave_u[0], ave_u[1], ave_u[2], ave_u[3], ave_u[4], min_u[0], min_u[1], min_u[2], min_u[3], min_u[4], max_u[0], max_u[1], max_u[2], max_u[3], max_u[4], (u_x_ratio<=9999.)?(u_x_ratio):(9999.), (u_y_ratio<=9999.)?(u_y_ratio):(9999.), min_rho, max_rho, ave_rho, (rho_ratio<=9999.)?(rho_ratio):(9999.) ); fclose(o); #if VERBOSITY_LEVEL > 0 printf("dump_frame_info() -- Wrote file \"%s\"\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ #if VERBOSITY_LEVEL > 0 printf("dump_frame_info() -- frame = %d/%d = %d\n", lattice->time, lattice->param.FrameRate, (int)((double)lattice->time/(double)lattice->param.FrameRate)); #endif /* VERBOSITY_LEVEL > 0 */ } } /* void dump_frame_info( struct lattice_struct *lattice) */ // }}} // D U M P M A C R O S C O P I C {{{ //############################################################################## // void dump_macro_vars( struct lattice_struct *lattice) // // - Output the macro_vars variables to files. // void dump_macro_vars( struct lattice_struct *lattice, int time) { char filename[1024]; FILE *o, *o_u, *o_rho, *o_ux, *o_uy, *o_upr, *o_upr_x, *o_upr_y; int *node_ptr; int n; double *macro_vars_ptr; double *upr; int frame; #if WRITE_MACRO_VAR_DAT_FILES || WRITE_PDF_DAT_FILES || WRITE_RHO_AND_U_TO_TXT int i, j; #endif double min_u[2], max_u[2], ave_u[2]; double min_rho, max_rho, ave_rho; double rho_ratio, u_x_ratio, u_y_ratio; int subs; frame = (int)((double)lattice->time/(double)lattice->param.FrameRate); for( subs = 0; subs < NUM_FLUID_COMPONENTS; subs++) { // W R I T E R H O A N D U // // - Write the density and velocity values at the active nodes to // the rho and u dat files. // if( is_incompressible( lattice) && annotate_incompressible_filenames( lattice)) { sprintf( filename, "%s/rho%dx%di_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX( lattice), get_LY( lattice), frame, subs, get_proc_id(lattice)); } else { sprintf( filename, "%s/rho%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX( lattice), get_LY( lattice), frame, subs, get_proc_id(lattice)); } if( !( o_rho = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/u%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX( lattice), get_LY( lattice), frame, subs, get_proc_id(lattice)); if( !( o_u = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } #if STORE_U_COMPOSITE sprintf( filename, "%s/upr%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX( lattice), get_LY( lattice), frame, subs, get_proc_id(lattice)); if( !( o_upr = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } upr = lattice->upr[0].u; #endif /* STORE_U_COMPOSITE */ macro_vars_ptr = &( lattice->macro_vars[subs][0].rho); for( n=0; n<lattice->NumNodes; n++) { if( is_solid_node( lattice, subs, n)) { fprintf( o_rho, "%20.17f\n", 0.); *macro_vars_ptr++; fprintf( o_u, "%20.17f ", 0.); *macro_vars_ptr++; fprintf( o_u, "%20.17f\n", 0.); *macro_vars_ptr++; #if STORE_U_COMPOSITE fprintf( o_upr, "%20.17f ", 0.); *upr++; fprintf( o_upr, "%20.17f\n", 0.); *upr++; #endif /* STORE_U_COMPOSITE */ } else { fprintf( o_rho, "%20.17f\n", *macro_vars_ptr++); fprintf( o_u, "%20.17f ", *macro_vars_ptr++); fprintf( o_u, "%20.17f\n", *macro_vars_ptr++); #if STORE_U_COMPOSITE fprintf( o_upr, "%20.17f ", *upr++); fprintf( o_upr, "%20.17f\n", *upr++); #endif /* STORE_U_COMPOSITE */ } } fclose(o_u); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/u%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); fclose(o_rho); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/rho%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); #if STORE_U_COMPOSITE fclose(o_upr); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/upr%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); #endif /* STORE_U_COMPOSITE */ #if WRITE_RHO_AND_U_TO_TXT // NOTE: This is very inefficient. But it's only intended // for debugging purposes on small problems. sprintf( filename, "%s/rho%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_rho = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/ux%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_ux = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/uy%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_uy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } #if STORE_U_COMPOSITE sprintf( filename, "%s/upr_x%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_upr_x = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/upr_y%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_upr_y = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } #endif /* STORE_U_COMPOSITE */ for( j=get_LY(lattice)-1; j>=0; j--) { n = j*get_LX(lattice); for( i=0; i<get_LX(lattice); i++, n++) { if( is_not_solid_node(lattice, subs, n)) { fprintf( o_rho, "%10.8f ", lattice->macro_vars[subs][n].rho); fprintf( o_ux, "%10.8f ", lattice->macro_vars[subs][n].u[0]); fprintf( o_uy, "%10.8f ", lattice->macro_vars[subs][n].u[1]); } else { fprintf( o_rho, "---------- "); fprintf( o_ux, "---------- "); fprintf( o_uy, "---------- "); } #if STORE_U_COMPOSITE fprintf( o_upr_x, "%10.8f ", lattice->upr[n].u[0]); fprintf( o_upr_y, "%10.8f ", lattice->upr[n].u[1]); #endif /* STORE_U_COMPOSITE */ if( n==lattice->NumNodes) { fprintf( o_rho, "%10.8f ", 0.); fprintf( o_ux, "%10.8f ", 0.); fprintf( o_uy, "%10.8f ", 0.); #if STORE_U_COMPOSITE fprintf( o_upr_x, "%10.8f ", 0.); fprintf( o_upr_y, "%10.8f ", 0.); #endif /* STORE_U_COMPOSITE */ } } fprintf( o_rho, "\n"); fprintf( o_ux, "\n"); fprintf( o_uy, "\n"); #if STORE_U_COMPOSITE fprintf( o_upr_x, "\n"); fprintf( o_upr_y, "\n"); #endif /* STORE_U_COMPOSITE */ } fclose(o_ux); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/ux%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); fclose(o_uy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/uy%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); fclose(o_rho); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/rho%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); #if STORE_U_COMPOSITE fclose(o_upr_x); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/upr_x%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); fclose(o_upr_y); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/upr_y%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_macro_vars() -- Wrote file \"%s\"\n", filename); #endif /* STORE_U_COMPOSITE */ #endif /* WRITE_RHO_AND_U_TO_TXT */ } /* for( subs = 0; subs < NUM_FLUID_COMPONENTS; subs++) */ #if WRITE_MACRO_VAR_DAT_FILES || WRITE_PDF_DAT_FILES sprintf( filename, "%s/obst%dx%d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), get_proc_id(lattice)); if( !( o = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } for( j=0; j<get_LY( lattice); j++) { for( i=0; i<get_LX( lattice); i++) { fprintf( o, " %d", is_solid_node( lattice, /*subs*/0, IJ2N( i, j))); } fprintf( o, "\n"); } fclose(o); #endif } /* void dump_macro_vars( struct lattice_struct *lattice, int time) */ // }}} #if 1 // R E A D M A C R O S C O P I C {{{ //############################################################################## // void read_macro_vars( struct lattice_struct *lattice) // // - Read the macro_vars variables from files. // void read_macro_vars( struct lattice_struct *lattice, int time) { char filename[1024]; FILE *in, *rho_in, *u_in; int *node_ptr; int n; double *macro_vars_ptr; int frame; double max_u[2], ave_u[2]; double max_rho, ave_rho; double rho_ratio, u_x_ratio, u_y_ratio; int subs; for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = (int)((double)time/(double)lattice->param.FrameRate); #if VERBOSITY_LEVEL > 0 printf("read_macro_vars() -- frame = %d/%d = %d\n", time, lattice->param.FrameRate, frame); #endif /* VERBOSITY_LEVEL > 0 */ // R E A D R H O A N D U // // - Read the density and velocity values at the active nodes to // the rho and u dat files. // sprintf( filename, "%s/rho%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( rho_in = fopen( filename, "r+"))) { printf("ERROR: fopen( \"%s\", \"r+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/u%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( u_in = fopen( filename, "r+"))) { printf("ERROR: fopen( \"%s\", \"r+\") = NULL. Bye, bye!\n", filename); process_exit(1); } macro_vars_ptr = &( lattice->macro_vars[subs][0].rho); for( n=0; n<lattice->NumNodes; n++) { fscanf( rho_in, "%lf\n", macro_vars_ptr++); fscanf( u_in, "%lf ", macro_vars_ptr++); fscanf( u_in, "%lf\n", macro_vars_ptr++); } fclose(u_in); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/u%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("read_macro_vars() -- Read file \"%s\"\n", filename); fclose(rho_in); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/rho%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("read_macro_vars() -- Read file \"%s\"\n", filename); } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ } /* void read_macro_vars( struct lattice_struct *lattice, int time) */ // }}} #endif // D U M P P D F {{{ //############################################################################## // void dump_pdf( struct lattice_struct *lattice, int time) // // - Output the particle distribution functions to a text file. // // - This is useful mainly for debugging with small problems. // void dump_pdf( struct lattice_struct *lattice, int time) { char filename[1024]; FILE *o_feq, *o_f, *o_ftemp, *o_fdiff; double *fdiff; double *fptr, *end_ptr; bc_ptr bc; int frame; int subs; int a; int i, j, n; #if WRITE_PDF_TO_TXT double max_feq, max_f, max_ftemp, max_fdiff; double max_feq0, max_f0, min_f0, max_ftemp0, max_fdiff0; double max_feq1234, max_f1234, max_ftemp1234, max_fdiff1234; double max_feq5678, max_f5678, max_ftemp5678, max_fdiff5678; double the_max; int s; #endif /* WRITE_PDF_TO_TXT */ fdiff = (double*)malloc( 9*get_NumNodes(lattice)*sizeof(double)); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = time/lattice->param.FrameRate; sprintf( filename, "%s/feq%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_feq = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/f%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_f = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/ftemp%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_ftemp = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/fdiff%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_fdiff = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fptr = lattice->pdf[subs][0].feq; for( n=0; n<get_NumNodes(lattice); n++) { for( a=0; a<9; a++) { fdiff[ 9*n + a] = fptr[ 27*n + 9 + a] // f - fptr[ 27*n + 18 + a] // ftemp ; } } bc = lattice->bc[subs]; fptr = lattice->pdf[subs][0].feq; end_ptr = &(lattice->pdf[subs][ lattice->NumNodes-1].ftemp[8]) + 1; while( fptr!=end_ptr) { if( COMPUTE_ON_SOLIDS || !( bc++->bc_type & BC_SOLID_NODE)) { fprintf( o_feq , "%10.17f ", *fptr++); fprintf( o_feq , "%10.17f ", *fptr++); fprintf( o_feq , "%10.17f ", *fptr++); fprintf( o_feq , "%10.17f ", *fptr++); fprintf( o_feq , "%10.17f ", *fptr++); fprintf( o_feq , "%10.17f ", *fptr++); fprintf( o_feq , "%10.17f ", *fptr++); fprintf( o_feq , "%10.17f ", *fptr++); fprintf( o_feq , "%10.17f ", *fptr++); } else { fprintf( o_feq , "%10.17f ", 0.); fprintf( o_feq , "%10.17f ", 0.); fprintf( o_feq , "%10.17f ", 0.); fprintf( o_feq , "%10.17f ", 0.); fprintf( o_feq , "%10.17f ", 0.); fprintf( o_feq , "%10.17f ", 0.); fprintf( o_feq , "%10.17f ", 0.); fprintf( o_feq , "%10.17f ", 0.); fprintf( o_feq , "%10.17f ", 0.); fptr+=9; } fprintf( o_feq , "\n"); fprintf( o_f , "%10.17f ", *fptr++); fprintf( o_f , "%10.17f ", *fptr++); fprintf( o_f , "%10.17f ", *fptr++); fprintf( o_f , "%10.17f ", *fptr++); fprintf( o_f , "%10.17f ", *fptr++); fprintf( o_f , "%10.17f ", *fptr++); fprintf( o_f , "%10.17f ", *fptr++); fprintf( o_f , "%10.17f ", *fptr++); fprintf( o_f , "%10.17f ", *fptr++); fprintf( o_f , "\n"); fprintf( o_ftemp, "%10.17f ", *fptr++); fprintf( o_ftemp, "%10.17f ", *fptr++); fprintf( o_ftemp, "%10.17f ", *fptr++); fprintf( o_ftemp, "%10.17f ", *fptr++); fprintf( o_ftemp, "%10.17f ", *fptr++); fprintf( o_ftemp, "%10.17f ", *fptr++); fprintf( o_ftemp, "%10.17f ", *fptr++); fprintf( o_ftemp, "%10.17f ", *fptr++); fprintf( o_ftemp, "%10.17f ", *fptr++); fprintf( o_ftemp, "\n"); } /* while( fptr!=end_ptr) */ fclose( o_feq); fclose( o_f); fclose( o_ftemp); fclose( o_fdiff); } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if WRITE_PDF_TO_TXT for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = time/lattice->param.FrameRate; sprintf( filename, "%s/feq%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_feq = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/f%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_f = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/ftemp%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_ftemp = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/fdiff%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_fdiff = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fptr = lattice->pdf[subs][0].feq; for( n=0; n<get_NumNodes(lattice); n++) { for( a=0; a<9; a++) { fdiff[ 9*n + a] = fptr[ 27*n + 9 + a] // f - fptr[ 27*n + 18 + a] // ftemp ; } } fprintf( o_feq , "+"); fprintf( o_f , "+"); fprintf( o_ftemp, "+"); fprintf( o_fdiff, "+"); for( i=0; i<get_LX(lattice); i++) { fprintf( o_feq , "----"); fprintf( o_feq , "----"); fprintf( o_feq , "---+"); fprintf( o_f , "----"); fprintf( o_f , "----"); fprintf( o_f , "---+"); fprintf( o_ftemp, "----"); fprintf( o_ftemp, "----"); fprintf( o_ftemp, "---+"); fprintf( o_fdiff, "----"); fprintf( o_fdiff, "----"); fprintf( o_fdiff, "---+"); } fprintf( o_feq , "\n"); fprintf( o_f , "\n"); fprintf( o_ftemp, "\n"); fprintf( o_fdiff, "\n"); if( /*scale_f_vals*/ 0) { compute_max_f( lattice, &(lattice->pdf[subs][0].feq[0]), &max_feq, subs); compute_max_f0( lattice, &(lattice->pdf[subs][0].feq[0]), &max_feq0, subs); compute_max_f1234(lattice,&(lattice->pdf[subs][0].feq[0]),&max_feq1234, subs); compute_max_f5678(lattice,&(lattice->pdf[subs][0].feq[0]),&max_feq5678, subs); compute_max_f( lattice, &(lattice->pdf[subs][0].f[0]), &max_f, subs); compute_max_f0( lattice, &(lattice->pdf[subs][0].f[0]), &max_f0, subs); if( max_f0 == 0.) { max_f0 = 1.;} compute_max_f1234(lattice,&(lattice->pdf[subs][0].f[0]),&max_f1234, subs); compute_max_f5678(lattice,&(lattice->pdf[subs][0].f[0]),&max_f5678, subs); compute_max_f( lattice, &(lattice->pdf[subs][0].ftemp[0]), &max_ftemp, subs); compute_max_f0( lattice,&(lattice->pdf[subs][0].ftemp[0]), &max_ftemp0, subs); compute_max_f1234(lattice,&(lattice->pdf[subs][0].ftemp[0]),&max_ftemp1234,subs); compute_max_f5678(lattice,&(lattice->pdf[subs][0].ftemp[0]),&max_ftemp5678,subs); compute_max_f( lattice, fdiff, &max_fdiff, subs); if( max_fdiff == 0.) { max_fdiff = 1.;} compute_max_f0( lattice, fdiff, &max_fdiff0, subs); if( max_fdiff0 == 0.) { max_fdiff0 = 1.;} compute_max_f1234(lattice, fdiff, &max_fdiff1234, subs); if( max_fdiff1234 == 0.) { max_fdiff1234 = 1.;} compute_max_f5678(lattice, fdiff, &max_fdiff5678, subs); if( max_fdiff5678 == 0.) { max_fdiff5678 = 1.;} s = 1000; } else { the_max = 1.; max_feq = the_max; max_feq0 = the_max; max_feq1234 = the_max; max_feq5678 = the_max; max_f = the_max; max_f0 = the_max; max_f1234 = the_max; max_f5678 = the_max; max_ftemp = the_max; max_ftemp0 = the_max; max_ftemp1234 = the_max; max_ftemp5678 = the_max; max_fdiff = the_max; max_fdiff0 = the_max; max_fdiff1234 = the_max; max_fdiff5678 = the_max; s = 100; } for( j=get_LY(lattice)-1; j>=0; j--) { n = j*get_LX(lattice); fprintf( o_feq , "|"); fprintf( o_f , "|"); fprintf( o_ftemp, "|"); fprintf( o_fdiff, "|"); for( i=0; i<get_LX(lattice); i++, n++) { #if 0 fprintf(o_feq, "%3d ",X2N(lattice->pdf[subs][n].feq[6] /max_feq5678 ,s)); fprintf(o_feq, "%3d ",X2N(lattice->pdf[subs][n].feq[2] /max_feq1234 ,s)); fprintf(o_feq, "%3d|",X2N(lattice->pdf[subs][n].feq[5] /max_feq5678 ,s)); fprintf(o_f, "%3d ",X2N(lattice->pdf[subs][n].f[6] /max_f5678 ,s)); fprintf(o_f, "%3d ",X2N(lattice->pdf[subs][n].f[2] /max_f1234 ,s)); fprintf(o_f, "%3d|",X2N(lattice->pdf[subs][n].f[5] /max_f5678 ,s)); fprintf(o_ftemp,"%3d ",X2N(lattice->pdf[subs][n].ftemp[6]/max_ftemp5678,s)); fprintf(o_ftemp,"%3d ",X2N(lattice->pdf[subs][n].ftemp[2]/max_ftemp1234,s)); fprintf(o_ftemp,"%3d|",X2N(lattice->pdf[subs][n].ftemp[5]/max_ftemp5678,s)); fprintf(o_fdiff,"%3d ",X2N(fdiff[9*n+6]/max_fdiff5678,s)); fprintf(o_fdiff,"%3d ",X2N(fdiff[9*n+2]/max_fdiff1234,s)); fprintf(o_fdiff,"%3d|",X2N(fdiff[9*n+5]/max_fdiff5678,s)); #else fprintf(o_feq, "%.15f ", lattice->pdf[subs][n].feq[6] ); fprintf(o_feq, "%.15f ", lattice->pdf[subs][n].feq[2] ); fprintf(o_feq, "%.15f|", lattice->pdf[subs][n].feq[5] ); fprintf(o_f, "%.15f ", lattice->pdf[subs][n].f[6] ); fprintf(o_f, "%.15f ", lattice->pdf[subs][n].f[2] ); fprintf(o_f, "%.15f|", lattice->pdf[subs][n].f[5] ); fprintf(o_ftemp,"%.15f ", lattice->pdf[subs][n].ftemp[6]); fprintf(o_ftemp,"%.15f ", lattice->pdf[subs][n].ftemp[2]); fprintf(o_ftemp,"%.15f|", lattice->pdf[subs][n].ftemp[5]); fprintf(o_fdiff,"%.15f ", fdiff[9*n+6] ); fprintf(o_fdiff,"%.15f ", fdiff[9*n+2] ); fprintf(o_fdiff,"%.15f|", fdiff[9*n+5] ); #endif } /* for( i=0; i<get_LX(lattice); i++, n++) */ fprintf( o_feq, "\n"); fprintf( o_f, "\n"); fprintf( o_ftemp,"\n"); fprintf( o_fdiff,"\n"); n = j*get_LX(lattice); fprintf( o_feq , "|"); fprintf( o_f , "|"); fprintf( o_ftemp, "|"); fprintf( o_fdiff, "|"); for( i=0; i<get_LX(lattice); i++, n++) { #if 0 fprintf(o_feq, "%3d ",X2N( lattice->pdf[subs][n].feq[3] /max_feq1234 ,s)); fprintf(o_feq, "%3d ",X2N( lattice->pdf[subs][n].feq[0] /max_feq0 ,s)); fprintf(o_feq, "%3d|",X2N( lattice->pdf[subs][n].feq[1] /max_feq1234 ,s)); fprintf(o_f, "%3d ",X2N( lattice->pdf[subs][n].f[3] /max_f1234 ,s)); fprintf(o_f, "%3d ",X2N( lattice->pdf[subs][n].f[0] /max_f0 ,s)); fprintf(o_f, "%3d|",X2N( lattice->pdf[subs][n].f[1] /max_f1234 ,s)); fprintf(o_ftemp,"%3d ",X2N( lattice->pdf[subs][n].ftemp[3]/max_ftemp1234,s)); fprintf(o_ftemp,"%3d ",X2N( lattice->pdf[subs][n].ftemp[0]/max_ftemp0 ,s)); fprintf(o_ftemp,"%3d|",X2N( lattice->pdf[subs][n].ftemp[1]/max_ftemp1234,s)); fprintf(o_fdiff,"%3d ",X2N( fdiff[9*n+3]/max_fdiff1234,s)); fprintf(o_fdiff,"%3d ",X2N( fdiff[9*n+0]/max_fdiff0 ,s)); fprintf(o_fdiff,"%3d|",X2N( fdiff[9*n+1]/max_fdiff1234,s)); #else fprintf(o_feq, "%.15f ", lattice->pdf[subs][n].feq[3] ); fprintf(o_feq, "%.15f ", lattice->pdf[subs][n].feq[0] ); fprintf(o_feq, "%.15f|", lattice->pdf[subs][n].feq[1] ); fprintf(o_f, "%.15f ", lattice->pdf[subs][n].f[3] ); fprintf(o_f, "%.15f ", lattice->pdf[subs][n].f[0] ); fprintf(o_f, "%.15f|", lattice->pdf[subs][n].f[1] ); fprintf(o_ftemp,"%.15f ", lattice->pdf[subs][n].ftemp[3]); fprintf(o_ftemp,"%.15f ", lattice->pdf[subs][n].ftemp[0]); fprintf(o_ftemp,"%.15f|", lattice->pdf[subs][n].ftemp[1]); fprintf(o_fdiff,"%.15f ", fdiff[9*n+3] ); fprintf(o_fdiff,"%.15f ", fdiff[9*n+0] ); fprintf(o_fdiff,"%.15f|", fdiff[9*n+1] ); #endif } /* for( i=0; i<get_LX(lattice); i++, n++) */ fprintf( o_feq, "\n"); fprintf( o_f, "\n"); fprintf( o_ftemp,"\n"); fprintf( o_fdiff,"\n"); n = j*get_LX(lattice); fprintf( o_feq , "|"); fprintf( o_f , "|"); fprintf( o_ftemp, "|"); fprintf( o_fdiff, "|"); for( i=0; i<get_LX(lattice); i++, n++) { #if 0 fprintf(o_feq, "%3d ",X2N(lattice->pdf[subs][n].feq[7] /max_feq5678 ,s)); fprintf(o_feq, "%3d ",X2N(lattice->pdf[subs][n].feq[4] /max_feq1234 ,s)); fprintf(o_feq, "%3d|",X2N(lattice->pdf[subs][n].feq[8] /max_feq5678 ,s)); fprintf(o_f, "%3d ",X2N(lattice->pdf[subs][n].f[7] /max_f5678 ,s)); fprintf(o_f, "%3d ",X2N(lattice->pdf[subs][n].f[4] /max_f1234 ,s)); fprintf(o_f, "%3d|",X2N(lattice->pdf[subs][n].f[8] /max_f5678 ,s)); fprintf(o_ftemp,"%3d ",X2N(lattice->pdf[subs][n].ftemp[7]/max_ftemp5678,s)); fprintf(o_ftemp,"%3d ",X2N(lattice->pdf[subs][n].ftemp[4]/max_ftemp1234,s)); fprintf(o_ftemp,"%3d|",X2N(lattice->pdf[subs][n].ftemp[8]/max_ftemp5678,s)); fprintf(o_fdiff,"%3d ",X2N(fdiff[9*n+7]/max_fdiff5678,s)); fprintf(o_fdiff,"%3d ",X2N(fdiff[9*n+4]/max_fdiff1234,s)); fprintf(o_fdiff,"%3d|",X2N(fdiff[9*n+8]/max_fdiff5678,s)); #else fprintf(o_feq, "%.15f ", lattice->pdf[subs][n].feq[7] ); fprintf(o_feq, "%.15f ", lattice->pdf[subs][n].feq[4] ); fprintf(o_feq, "%.15f|", lattice->pdf[subs][n].feq[8] ); fprintf(o_f, "%.15f ", lattice->pdf[subs][n].f[7] ); fprintf(o_f, "%.15f ", lattice->pdf[subs][n].f[4] ); fprintf(o_f, "%.15f|", lattice->pdf[subs][n].f[8] ); fprintf(o_ftemp,"%.15f ", lattice->pdf[subs][n].ftemp[7]); fprintf(o_ftemp,"%.15f ", lattice->pdf[subs][n].ftemp[4]); fprintf(o_ftemp,"%.15f|", lattice->pdf[subs][n].ftemp[8]); fprintf(o_fdiff,"%.15f ", fdiff[9*n+7] ); fprintf(o_fdiff,"%.15f ", fdiff[9*n+4] ); fprintf(o_fdiff,"%.15f|", fdiff[9*n+8] ); #endif } /* for( i=0; i<get_LX(lattice); i++, n++) */ fprintf( o_feq, "\n"); fprintf( o_f, "\n"); fprintf( o_ftemp,"\n"); fprintf( o_fdiff,"\n"); fprintf( o_feq , "+"); fprintf( o_f , "+"); fprintf( o_ftemp, "+"); fprintf( o_fdiff, "+"); for( i=0; i<get_LX(lattice); i++) { fprintf( o_feq , "----"); fprintf( o_feq , "----"); fprintf( o_feq , "---+"); fprintf( o_f , "----"); fprintf( o_f , "----"); fprintf( o_f , "---+"); fprintf( o_ftemp, "----"); fprintf( o_ftemp, "----"); fprintf( o_ftemp, "---+"); fprintf( o_fdiff, "----"); fprintf( o_fdiff, "----"); fprintf( o_fdiff, "---+"); } fprintf( o_feq , "\n"); fprintf( o_f , "\n"); fprintf( o_ftemp, "\n"); fprintf( o_fdiff, "\n"); } /* for( j=get_LY(lattice)-1; j>=0; j--) */ fclose( o_feq); fclose( o_f); fclose( o_ftemp); fclose( o_fdiff); } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #endif /* WRITE_PDF_TO_TXT */ } /* void dump_pdf( struct lattice_struct *lattice, int time) */ // }}} #if NON_LOCAL_FORCES // D U M P F O R C E S {{{ //############################################################################## // void dump_forces( struct lattice_struct *lattice) // // - Output the interactive force values to file. // void dump_forces( struct lattice_struct *lattice) { char filename[1024]; FILE *ox, *oy; int n; double *force; int frame; #if WRITE_RHO_AND_U_TO_TXT int i, j; #endif /* WRITE_RHO_AND_U_TO_TXT */ int subs; for( subs = 0; subs < NUM_FLUID_COMPONENTS; subs++) { frame = (int)((double)lattice->time/(double)lattice->param.FrameRate); #if VERBOSITY_LEVEL > 0 printf("dump_forces() -- frame = %d/%d = %d\n", lattice->time, lattice->param.FrameRate, frame); #endif /* VERBOSITY_LEVEL > 0 */ sprintf( filename, "%s/force_x%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( ox = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/force_y%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( oy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } force = lattice->force[subs][0].force; for( n=0; n<lattice->NumNodes; n++) { fprintf( ox, "%20.17f\n", *force++); fprintf( oy, "%20.17f\n", *force++); force += ( sizeof( struct force_struct)/8 - 2); } fclose(ox); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/force_x%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_forces() -- Wrote file \"%s\"\n", filename); fclose(oy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/force_y%dx%d_frame%04d_subs%02d_proc%04d.dat", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_forces() -- Wrote file \"%s\"\n", filename); #if WRITE_RHO_AND_U_TO_TXT // NOTE: This is very inefficient. But it's only intended // for debugging purposes on small problems. sprintf( filename, "%s/force_x%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( ox = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/force_y%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( oy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } for( j=0; j<get_LY(lattice); j++) { n = j*get_LX(lattice); for( i=0; i<get_LX(lattice); i++, n++) { fprintf( ox, "%10.7f ", lattice->force[subs][n].force[0]); fprintf( oy, "%10.7f ", lattice->force[subs][n].force[1]); if( n==lattice->NumNodes) { fprintf( ox, "%10.7f ", 0.); fprintf( oy, "%10.7f ", 0.); } } fprintf( ox, "\n"); fprintf( oy, "\n"); } fclose(ox); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/force_x%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_forces() -- Wrote file \"%s\"\n", filename); fclose(oy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/force_y%dx%d_frame%04d_subs%02d_proc%04d.txt", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); #endif /* VERBOSITY_LEVEL > 0 */ printf("dump_forces() -- Wrote file \"%s\"\n", filename); #endif /* WRITE_RHO_AND_U_TO_TXT */ } /* for( subs = 0; subs < NUM_FLUID_COMPONENTS; subs++) */ } /* void dump_forces( struct lattice_struct *lattice) */ // }}} #endif /* NON_LOCAL_FORCES */ // D U M P C H E C K P O I N T {{{ //############################################################################## // void dump_checkpoint( struct lattice_struct *lattice, int time, char *fn) // // - Write lattice to a checkpoint file. // // - Should be binary and store all information necessary to // restart the current run at this point. // void dump_checkpoint( struct lattice_struct *lattice, int time, char *fn) { } /* void dump_checkpoint( struct lattice_struct *lattice, ...) */ // }}} // R E A D C H E C K P O I N T {{{ //############################################################################## // void read_checkpoint( struct lattice_struct *lattice) // // - Read lattice from a checkpoint file (as written by dump_checkpoint). // // - With this information, should be able to restart where // the previous run stopped. // void read_checkpoint( struct lattice_struct *lattice) { } /* void read_checkpoint( struct lattice_struct *lattice) */ // }}} // S P Y B M P {{{ //############################################################################## // void spy_bmp( char *filename, int ***spy) // // - Returns matrix 'spy' of ones and zeros. // // - Zeros for white pixels. // // - Ones for non-white pixels. // void spy_bmp( char *filename, lattice_ptr lattice, int **matrix) { FILE *in, *o; int i, j, n, m; int g_i, g_j; int pad, bytes_per_row; char k; char b, g, r; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char ctemp; int itemp; int **spy; printf("spy_bmp() -- Hi!\n"); spy = (int**)malloc( get_g_LY(lattice)*sizeof(int*)); for( j=0; j<get_g_LY(lattice); j++) { spy[j] = (int*)malloc( get_g_LX(lattice)*sizeof(int)); } // Clear the spy array. for( j=0; j<get_g_LY(lattice); j++) { for( i=0; i<get_g_LX(lattice); i++) { spy[j][i] = 0; } } // Clear the matrix array. for( j=0; j<get_LY(lattice); j++) { for( i=0; i<get_LX(lattice); i++) { matrix[j][i] = 0; } } if(/*ignore_solids*/0) return; if( !( in = fopen( filename, "r"))) { #if 1 printf("%s %d >> spy_bmp() -- Error opening file \"%s\".\n", __FILE__, __LINE__, filename); process_exit(1); #else printf(" %s::spy_bmp() %d >> File \"%s\" cannot be opened for reading.\n", __FILE__, __LINE__, filename); if( !( o = fopen( filename, "w+"))) { // TODO: Write blank bmp file. } printf(" %s::spy_bmp() %d >> Wrote a blank \"%s\" file.\n", __FILE__, __LINE__, filename); printf(" %s::spy_bmp() %d >> Returning all zeros!\n", __FILE__, __LINE__); fclose( o); return; #endif } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); #if 0 printf("%s %d >> sizeof(int) = %d \n", __FILE__, __LINE__, sizeof(int)); printf("%s %d >> biWidth = %d \n", __FILE__, __LINE__, (int)*(int*)bmih.biWidth); printf("%s %d >> biWidth = [ '%c' '%c' '%c' '%c'] \n", __FILE__, __LINE__, bmih.biWidth[0], bmih.biWidth[1], bmih.biWidth[2], bmih.biWidth[3] ); printf("%s %d >> biWidth = [ '%d' '%d' '%d' '%d'] \n", __FILE__, __LINE__, bmih.biWidth[0], bmih.biWidth[1], bmih.biWidth[2], bmih.biWidth[3] ); ctemp = bmih.biWidth[0]; bmih.biWidth[0] = bmih.biWidth[3]; bmih.biWidth[3] = ctemp; ctemp = bmih.biWidth[1]; bmih.biWidth[1] = bmih.biWidth[2]; bmih.biWidth[2] = ctemp; itemp = 0xaabbccdd;//(int)*(int*)bmih.biWidth; printf("%s %d >> itemp = %d\n",__FILE__,__LINE__, itemp); printf("%s %d >> itemp = [ '%d' '%d' '%d' '%d'] \n", __FILE__, __LINE__, (itemp&0xff000000)>>24, (itemp&0x00ff0000)>>16, (itemp&0x0000ff00)>> 8, (itemp&0x000000ff)>> 0 ); itemp = ENDIAN4(itemp); printf("%s %d >> itemp = %d\n",__FILE__,__LINE__, itemp); printf("%s %d >> itemp = [ '%d' '%d' '%d' '%d'] \n", __FILE__, __LINE__, (itemp&0xff000000)>>24, (itemp&0x00ff0000)>>16, (itemp&0x0000ff00)>> 8, (itemp&0x000000ff)>> 0 ); printf("%s %d >> biWidth = [ '%d' '%d' '%d' '%d'] \n", __FILE__, __LINE__, bmih.biWidth[0], bmih.biWidth[1], bmih.biWidth[2], bmih.biWidth[3] ); printf("%s %d >> biWidth = %d \n", __FILE__, __LINE__, (int)*(int*)bmih.biWidth); printf("%s %d >> sizeof(int) = %d \n", __FILE__, __LINE__, sizeof(int)); printf("%s %d >> biHeight = %d \n", __FILE__, __LINE__, (int)*(int*)bmih.biHeight); printf("%s %d >> biHeight = [ '%c' '%c' '%c' '%c'] \n", __FILE__, __LINE__, bmih.biHeight[0], bmih.biHeight[1], bmih.biHeight[2], bmih.biHeight[3] ); printf("%s %d >> biHeight = [ '%d' '%d' '%d' '%d'] \n", __FILE__, __LINE__, bmih.biHeight[0], bmih.biHeight[1], bmih.biHeight[2], bmih.biHeight[3] ); ctemp = bmih.biHeight[0]; bmih.biHeight[0] = bmih.biHeight[3]; bmih.biHeight[3] = ctemp; ctemp = bmih.biHeight[1]; bmih.biHeight[1] = bmih.biHeight[2]; bmih.biHeight[2] = ctemp; printf("%s %d >> biHeight = [ '%d' '%d' '%d' '%d'] \n", __FILE__, __LINE__, bmih.biHeight[0], bmih.biHeight[1], bmih.biHeight[2], bmih.biHeight[3] ); printf("%s %d >> biHeight = %d \n", __FILE__, __LINE__, (int)*(int*)bmih.biHeight); ctemp = bmih.biBitCount[0]; bmih.biBitCount[0] = bmih.biBitCount[1]; bmih.biBitCount[1] = ctemp; #endif *((int*)(bmih.biWidth)) = ENDIAN4(((int)(*((int*)(bmih.biWidth))))); *((int*)(bmih.biHeight)) = ENDIAN4(((int)(*((int*)(bmih.biHeight))))); *((short int*)(bmih.biBitCount)) = ENDIAN2(((short int)(*((short int*)(bmih.biBitCount))))); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("%s %d >> ERROR: Can't handle compression. Exiting!\n",__FILE__,__LINE__); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; //LBMPI #if PARALLEL //LBMPI if( *width_ptr != lattice->lbmpi->GLX) //LBMPI { //LBMPI printf("%s %d >> ERROR: GLX %d does not match the " //LBMPI "width %d of the BMP file. Exiting!\n", //LBMPI __FILE__, __LINE__, lattice->lbmpi->GLX, *width_ptr); //LBMPI process_exit(1); //LBMPI } //LBMPI #else /* !(PARALLEL) */ if( *width_ptr != get_g_LX(lattice)) { printf("%s %d >> ERROR: LX %d does not match the " "width %d of the BMP file. Exiting!\n" "Note that, if the width stated here seems absurd, you\n" "might need to recompile with the SWAP_BYTE_ORDER flag.\n" "This can be done by \"make swap\".\n", __FILE__, __LINE__, get_g_LX(lattice), *width_ptr); process_exit(1); } //LBMPI #endif /* (PARALLEL) */ printf("%s %d >> biWidth = %d \n", __FILE__, __LINE__, (int)*bmih.biWidth); printf("%s %d >> width_ptr = %d \n", __FILE__, __LINE__, (int)*width_ptr); //LBMPI #if PARALLEL //LBMPI if( *height_ptr != lattice->lbmpi->GLY) //LBMPI { //LBMPI printf("%s %d >> ERROR: GLY %d does not match the " //LBMPI "height %d of the BMP file. Exiting!\n", //LBMPI __FILE__, __LINE__, lattice->lbmpi->GLY, *height_ptr); //LBMPI process_exit(1); //LBMPI } //LBMPI #else /* !(PARALLEL) */ if( *height_ptr != get_g_LY(lattice)) { printf("%s %d >> ERROR: LY %d does not match the " "height %d of the BMP file. Exiting!\n", __FILE__, __LINE__, get_g_LY(lattice), *height_ptr); process_exit(1); } //LBMPI #endif /* (PARALLEL) */ if( (*bitcount_ptr) < 24) { n = (int)pow(2.,(double)(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("%s %d >> Error reading palette entry %d. Exiting!\n", __FILE__, __LINE__, i); process_exit(1); } } } // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(*width_ptr))*((double)((*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; n = 0; m = 0; n+=( k = fread( &b, 1, 1, in )); i = 0; j = 0; while( !feof(in)) { switch((*bitcount_ptr)) { case 1: // Monochrome. printf("%s %d >> spy_bmp() -- " "Support for Monochrome BMPs is pending. " "Exiting!\n", __FILE__, __LINE__); process_exit(1); if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x80) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x40) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x20) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x10) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x08) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x04) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x02) == 0); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b & 0x01) == 0); } i++; break; case 4: // 16 colors. printf("%s %d >> spy_bmp() -- " "Support for 16 color BMPs is pending. " "Exiting!\n", __FILE__, __LINE__); process_exit(1); if( i < *width_ptr) { (spy)[j][i] = ( (b&0xf0)>>4 != 15); } i++; if( i < *width_ptr) { (spy)[j][i] = ( (b&0x0f) != 15); } i++; break; case 8: // 256 colors. printf("%s %d >> spy_bmp() -- " "Support for 256 color BMPs is pending. " "Exiting!\n", __FILE__, __LINE__); process_exit(1); if( i < *width_ptr) { (spy)[j][i] = ( (b&0xff) != 255); } i++; break; case 24: // 24-bit colors. if( i < 3*(*width_ptr)) { i++; n+=( k = fread( &g, 1, 1, in )); i++; n+=( k = fread( &r, 1, 1, in )); if( ( (b&0xff) == 0) &&( (g&0xff) == 0) &&( (r&0xff) == 0) ) { (spy)[j][(int)floor((double)i/3.)] = 1; } #if 0 if( ( (b&0xff) == 0) &&( (g&0xff) == 0) &&( (r&0xff) == 255) ) { // Red ==> Inflow, Pressure boundaries. if( (int)floor((double)i/3.) == 0 || (int)floor((double)i/3.) == get_g_LX(lattice)-1 ) { if( !( j==0 || j == get_g_LY(lattice)-1)) { lattice->periodic_x[subs] = 0; } } if( j == 0 || j == get_g_LY(lattice)-1 ) { if( !( (int)floor((double)i/3.) == 0 || (int)floor((double)i/3.) == get_g_LX(lattice)-1)) { lattice->periodic_y[subs] = 0; } } } if( ( (b&0xff) == 0) &&( (g&0xff) == 255) &&( (r&0xff) == 0) ) { // Green ==> Outflow, Pressure boundaries. if( (int)floor((double)i/3.) == 0 || (int)floor((double)i/3.) == get_g_LX(lattice)-1 ) { if( !( j==0 || j == get_g_LY(lattice)-1)) { lattice->periodic_x[subs] = 0; } } if( j == 0 || j == get_g_LY(lattice)-1 ) { if( !( (int)floor((double)i/3.) == 0 || (int)floor((double)i/3.) == get_g_LX(lattice)-1)) { lattice->periodic_y[subs] = 0; } } } #endif } i++; break; default: // 32-bit colors? printf("%s %d >> ERROR: Unhandled color depth, " "BitCount = %d. Exiting!\n", __FILE__, __LINE__, *bitcount_ptr); process_exit(1); break; } /* switch(*(bmih.biBitCount)) */ if( !(n%(bytes_per_row+pad))) { m++; i=0; j++;} n+=( k = fread( &b, 1, 1, in )); } /* while( !feof(in)) */ if( (bytes_per_row+pad)*m!=n) { printf("WARNING: Num bytes read = %d versus num bytes predicted = %d .\n", n, (bytes_per_row+pad)*m); } if( m != *height_ptr) { printf("WARNING: m (%d) != bmih.biHeight (%d).\n", m, *height_ptr); } fclose(in); for( j=0, g_j=get_g_SY(lattice); j<get_LY(lattice); j++, g_j++) { for( i=0, g_i=get_g_SX(lattice); i<get_LX(lattice); i++, g_i++) { matrix[j][i] = spy[g_j][g_i]; } } for( j=0; j<get_g_LY(lattice); j++) { free(spy[j]); } free(spy); printf("spy_bmp() -- Bye!\n"); printf("\n"); } /* spy_bmp( char *filename, int **spy) */ // }}} // R E A D B C S {{{ //############################################################################## // void read_bcs( char *filename, int **bcs) // // - Read boundary condition information from file. // void read_bcs( lattice_ptr lattice, int **bcs) { FILE *in; char filename[1024]; int i, j, n, m; int ei, ej; int pad, bytes_per_row; char k; char b, g, r; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; int subs; printf("read_bcs() -- Hi!\n"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { // Clear the bcs array. for( j=0; j<get_LY(lattice); j++) { for( i=0; i<get_LX(lattice); i++) { bcs[j][i] = 0; } } sprintf( filename, "./in/%dx%dbc_subs%02d_proc%04d.bmp", get_LX(lattice), get_LY(lattice), subs, get_proc_id(lattice)); if( !( in = fopen( filename, "r"), get_proc_id(lattice))) { printf("%s %d >> read_bcs() -- Error opening file \"%s\".\n", __FILE__,__LINE__,filename); process_exit(1); } // Read the headers. n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; if( ENDIAN4(*height_ptr) != get_LY(lattice)) { printf("ERROR: Lattice height does not match " "soil matrix data \"%s\". (%d!=%d) Exiting!\n", filename, get_LY(lattice), ENDIAN4(*height_ptr) ); printf("\n"); process_exit(1); } if( ENDIAN4(*width_ptr) != get_LX(lattice)) { printf("ERROR: Lattice width does not match " "soil matrix data \"%s\". (%d!=%d) Exiting!\n", filename, get_LX(lattice), ENDIAN4(*width_ptr) ); printf("\n"); process_exit(1); } // Read the palette, if necessary. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; n = 0; m = 0; n+=( k = fread( &b, 1, 1, in )); i = 0; //j = *height_ptr-1; j = 0;//*height_ptr-1; while( !feof(in)) { switch(ENDIAN2(*bitcount_ptr)) { case 1: // Monochrome. printf("read_bcs() -- " "Support for Monochrome BMPs is pending. " "Exiting!\n"); process_exit(1); if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x80) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x40) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x20) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x10) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x08) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x04) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x02) == 0); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b & 0x01) == 0); } i++; break; case 4: // 16 colors. printf("read_bcs() -- " "Support for 16 color BMPs is pending. " "Exiting!\n"); process_exit(1); if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b&0xf0)>>4 != 15); } i++; if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b&0x0f) != 15); } i++; break; case 8: // 256 colors. printf("read_bcs() -- " "Support for 256 color BMPs is pending. " "Exiting!\n"); process_exit(1); if( i < ENDIAN4(*width_ptr)) { (bcs)[j][i] = ( (b&0xff) != 255); } i++; break; case 24: // 24-bit colors. if( i < 3*(ENDIAN4(*width_ptr))) { i++; n+=( k = fread( &g, 1, 1, in )); i++; n+=( k = fread( &r, 1, 1, in )); if( ( (b&0xff) == 0) &&( (g&0xff) == 0) &&( (r&0xff) == 255) ) { // R E D ==> Inflow, Pressure boundaries. bcs[j][(int)floor((double)i/3.)] = 1; } if( ( (b&0xff) == 0) &&( (g&0xff) == 255) &&( (r&0xff) == 0) ) { // G R E E N ==> Outflow, Pressure boundaries. bcs[j][(int)floor((double)i/3.)] = 2; } } i++; break; default: // 32-bit colors? printf("ERROR: Unhandled color depth, " "BitCount = %d. Exiting!\n", ENDIAN2(*bitcount_ptr)); process_exit(1); break; } /* switch(*(bmih.biBitCount)) */ if( !(n%(bytes_per_row+pad))) { m++; i=0; j++;} n+=( k = fread( &b, 1, 1, in )); } /* while( !feof(in)) */ if( (bytes_per_row+pad)*m!=n) { printf("WARNING: Num bytes read = %d versus num bytes predicted = %d .\n", n, (bytes_per_row+pad)*m); } if( m != ENDIAN4(*height_ptr)) { printf("WARNING: m (%d) != bmih.biHeight (%d).\n", m, ENDIAN4(*height_ptr)); } fclose(in); ei = get_LX(lattice)-1; ej = get_LY(lattice)-1; for( n=0; n<lattice->NumNodes; n++) { i = n%get_LX(lattice); j = n/get_LX(lattice); if( bcs[ j][ i] != 0) { //printf("read_bcs() -- n = %d, ( %d, %d) of ( %d, %d).\n", n, i, j, ei, ej); #if 0 if( ( i==0 && j==0 ) || ( i==ei && j==0 ) || ( i==ei && j==ej) || ( i==0 && j==ej) ) { // Skip corners for now. printf("read_bcs() -- WARNING: Skipping corner ( %d, %d).", i, j); } else { #endif #if 0 if( i==0) { // West if( bcs[ j][ i] == 1) { // Inflow lattice->bc[n].bc_type |= BC_PRESSURE_W_IN; //lattice->periodic_x = 0; } else if( bcs[ j][ i] == 2) { // Outflow lattice->bc[n].bc_type |= BC_PRESSURE_W_OUT; //lattice->periodic_x = 0; } else { // Unhandled case. printf("read_bcs() -- Unhandled case: " "bcs[ %d][ %d] = %d . Exiting!\n", i, j, bcs[j][i]); process_exit(1); } } else if( i==ei) { // East if( bcs[ j][ i] == 1) { // Inflow lattice->bc[n].bc_type |= BC_PRESSURE_E_IN; //lattice->periodic_x = 0; } else if( bcs[ j][ i] == 2) { // Outflow lattice->bc[n].bc_type |= BC_PRESSURE_E_OUT; //lattice->periodic_x = 0; } else { // Unhandled case. printf("read_bcs() -- Unhandled case: " "bcs[ %d][ %d] = %d . Exiting!\n", i, j, bcs[j][i]); process_exit(1); } } else #endif if( j==0) { //printf("read_bcs() -- South at i=%d\n", i); // South if( bcs[ j][ i] == 1) { // Inflow lattice->bc[subs][n].bc_type |= BC_PRESSURE_S_IN; //lattice->periodic_y = 0; } else if( bcs[ j][ i] == 2) { // Outflow lattice->bc[subs][n].bc_type |= BC_PRESSURE_S_OUT; //lattice->periodic_y = 0; } else { // Unhandled case. printf("read_bcs() -- Unhandled case: " "bcs[ %d][ %d] = %d . Exiting!\n", i, j, bcs[j][i]); process_exit(1); } } else if( j==ej) { //printf("read_bcs() -- North at i=%d\n", i); // North if( bcs[ j][ i] == 1) { // Inflow lattice->bc[subs][n].bc_type |= BC_PRESSURE_N_IN; //lattice->periodic_y = 0; } else if( bcs[ j][ i] == 2) { // Outflow lattice->bc[subs][n].bc_type |= BC_PRESSURE_N_OUT; //lattice->periodic_y = 0; } else { // Unhandled case. printf("read_bcs() -- Unhandled case: " "bcs[ %d][ %d] = %d . Exiting!\n", i, j, bcs[j][i]); process_exit(1); } } else { // Unhandled case. printf("read_bcs() -- WARNING: " "Support for interior flow bcs is pending! " "Skipping ( i, j) = ( %d, %d).\n", i, j); } #if 0 } #endif } } } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ printf("read_bcs() -- Bye!\n"); printf("\n"); } /* read_bcs( char *filename, int ***bcs, int *height, int *width) */ // }}} #if 1 // R H O 2 B M P {{{ //############################################################################## // void rho2bmp( char *filename, int time) // void rho2bmp( lattice_ptr lattice, int time) { FILE *in, *o; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double fval; double min_rho, max_rho; int subs; double **colormap; int num_colors; #if SAY_HI printf("rho2bmp() -- Hi!\n"); #endif /* SAY_HI */ if( lattice->param.use_colormap) { count_colormap( &num_colors); allocate_colormap( &colormap, num_colors); read_colormap( colormap, num_colors); } for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = time/lattice->param.FrameRate; #if 0 sprintf( filename, "./in/%dx%d_proc%04d.bmp", get_LX(lattice), get_LY(lattice), get_proc_id(lattice)); if( !( in = fopen( filename, "r"))) { printf("%s %d >> rho2bmp() -- Error opening file \"%s\".\n", __FILE__,__LINE__,filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); #else bmfh.bfType[0] = 'B'; bmfh.bfType[1] = 'M'; *((int*)bmfh.bfSize)= get_LY(lattice)*( (int)ceil( ( ((double)get_LX(lattice))*( /*depth*/24.))/8.) // bytes per row + ( 4 - (int)ceil( ( ((double)get_LX(lattice))*( /*depth*/24.))/8.) % 4) % 4 // pad ); *((short int*)bmfh.bfReserved1) = 0; *((short int*)bmfh.bfReserved2) = 0; *((int*)bmfh.bfOffBits) = 54; // 14 byte file header and 40 byte info header *((int*)bmih.biSize) = 40; *((int*)bmih.biWidth) = get_LX(lattice); *((int*)bmih.biHeight) = get_LY(lattice); *((short int*)bmih.biPlanes) = 1; *((short int*)bmih.biBitCount) = 24; *((int*)bmih.biCompression) = 0; *((int*)bmih.biSizeImage) = 0; *((int*)bmih.biXPelsPerMeter) = 0; *((int*)bmih.biYPelsPerMeter) = 0; *((int*)bmih.biClrUsed) = 0; *((int*)bmih.biClrImportant) = 0; width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; #endif // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; compute_min_rho( lattice, &min_rho, subs); compute_max_rho( lattice, &max_rho, subs); sprintf( filename, "%s/rho%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o ); for( j=0; j<get_LY(lattice); j++) { n = j*get_LX(lattice); for( i=0; i<get_LX(lattice); i++, n++) { if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { if( lattice->param.use_colormap) { if( lattice->param.plot_scale_dynamic) { if( max_rho!=min_rho) { get_color( colormap, num_colors, (lattice->macro_vars[subs][ n].rho - min_rho)/(max_rho-min_rho), &red_val, &green_val, &blue_val ); } else { get_color( colormap, num_colors, 1., &red_val, &green_val, &blue_val ); } } else { get_color( colormap, num_colors, (lattice->macro_vars[subs][ n].rho /( (lattice->param.rho_A[subs]>lattice->param.rho_B[subs]) ?(lattice->param.rho_A[subs]) :(lattice->param.rho_B[subs]) )), &red_val, &green_val, &blue_val ); } } else { if( subs==0) { if( lattice->param.plot_scale_dynamic) { if( max_rho!=min_rho) { fval = ROUND( 255.*( lattice->macro_vars[subs][ n].rho - min_rho) /( max_rho-min_rho)); } else { fval = 255.; } } else { fval = ROUND( 255.*(lattice->macro_vars[subs][ n].rho /( (lattice->param.rho_A[subs]>lattice->param.rho_B[subs]) ?(lattice->param.rho_A[subs]) :(lattice->param.rho_B[subs]) ) )); } if( fval >= 0.) { if( fval <= 255.) { red_val = (char)((int)(255. - fval)%256); green_val = (char)((int)(255. - fval)%256); blue_val = (char)255; } else { red_val = (char)0; green_val = (char)0; blue_val = (char)255; } } else { red_val = (char)((int)(255. + fval)%256); green_val = (char)((int)(255. + fval)%256); blue_val = (char)((int)(255. + fval)%256); // TODO: Issue warning or something? Potential instability? } } /* if( subs==0) */ else // subs == 1 { if( lattice->param.plot_scale_dynamic) { if( max_rho!=min_rho) { fval = ROUND( 255.*( lattice->macro_vars[subs][ n].rho - min_rho) /( max_rho-min_rho)); } else { fval = 0.; } } else { //printf("%s (%d) >> fval = %f -> ", __FILE__, __LINE__, fval); #if INAMURO_SIGMA_COMPONENT fval = ROUND( 255.*(lattice->macro_vars[subs][ n].rho) /(lattice->param.rho_sigma)); #else /* !( INAMURO_SIGMA_COMPONENT) */ fval = ROUND( 255.*(lattice->macro_vars[subs][ n].rho /( (lattice->param.rho_A[subs]>lattice->param.rho_B[subs]) ?(lattice->param.rho_A[subs]) :(lattice->param.rho_B[subs]) ) )); #endif /* INAMURO_SIGMA_COMPONENT */ //printf("%f\n", fval); } if( fval >= 0.) { if( fval <= 255.) { red_val = (char)255; green_val = (char)((int)(255. - fval)%256); blue_val = (char)((int)(255. - fval)%256); } else { red_val = (char)255;//((int)(255. - (fval - 255.))%256); green_val = (char) 0;//((int)(255. - (fval - 255.))%256); blue_val = (char) 0;//((int)(255. - (fval - 255.))%256); } } else { red_val = (char)((int)(255. + fval)%256); green_val = (char)((int)(255. + fval)%256); blue_val = (char)((int)(255. + fval)%256); // TODO: Issue a warning or something? Potential instability? } } /* if( subs==0) else */ } } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ //printf("blue_val( %d, %d) = %d\n", i, j, (int)blue_val); if( fwrite( &blue_val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} //printf("BING %d %d\n", i, j); if( fwrite( &green_val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} //printf("BING %d %d\n", i, j); if( fwrite( &red_val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} //printf("BING %d %d\n", i, j); } /* for( i=0; i<get_LX(lattice); i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<get_LY(lattice); j++) */ fclose(o); #if VERBOSITY_LEVEL > 0 printf("rho2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ if( lattice->param.use_colormap) { deallocate_colormap( &colormap, num_colors); } #if SAY_HI printf("rho2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* rho2bmp( lattice_ptr lattice, int time) */ // }}} #else // R H O 2 B M P {{{ //############################################################################## // void rho2bmp( char *filename, int time) // void rho2bmp( lattice_ptr lattice, int time) { FILE *in, *o; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double min_rho, max_rho; int subs; #if SAY_HI printf("rho2bmp() -- Hi!\n"); #endif /* SAY_HI */ compute_max_rho( lattice, &min_rho, 0); compute_max_rho( lattice, &max_rho, 1); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = time/lattice->param.FrameRate; sprintf( filename, "./in/%dx%d_proc%04d.bmp", get_LX(lattice), get_LY(lattice), get_proc_id(lattice)); if( !( in = fopen( filename, "r"))) { printf("%s %d >> rho2bmp() -- Error opening file \"%s\".\n", __FILE__,__LINE__,filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; sprintf( filename, "%s/rho%dx%d_frame%04d_subs%02d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs); if( !( o = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o ); for( j=0; j<get_LY(lattice); j++) { n = j*get_LX(lattice); for( i=0; i<get_LX(lattice); i++, n++) { if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { red_val = (char)0; green_val = (char)0; red_val = (char)ROUND( 255.*(lattice->macro_vars[subs][ n].rho - min_rho)/(max_rho-min_rho)); blue_val = (char)255-red_val; } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ //printf("blue_val( %d, %d) = %d\n", i, j, (int)blue_val); if( fwrite( &blue_val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} //printf("BING %d %d\n", i, j); if( fwrite( &green_val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} //printf("BING %d %d\n", i, j); if( fwrite( &red_val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} //printf("BING %d %d\n", i, j); } /* for( i=0; i<get_LX(lattice); i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<get_LY(lattice); j++) */ fclose(o); #if VERBOSITY_LEVEL > 0 printf("rho2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("rho2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* rho2bmp( lattice_ptr lattice, int time) */ // }}} #endif // U 2 B M P {{{ //############################################################################## // void u2bmp( char *filename, int time) // void u2bmp( lattice_ptr lattice, int time) { FILE *in, *o_u, *o_ux, *o_uy; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double max_u[2], maxu; double u_x, u_y, u; int subs; #if SAY_HI printf("u2bmp() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = time/lattice->param.FrameRate; #if 0 sprintf( filename, "./in/%dx%d_proc%04d.bmp", get_LX(lattice), get_LY(lattice), get_proc_id(lattice)); if( !( in = fopen( filename, "r"))) { printf("%s %d >> u2bmp() -- Error opening file \"%s\".\n", __FILE__,__LINE__,filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } #if 0 *((int*)(bmih.biWidth)) = ENDIAN4(((int)(*((int*)(bmih.biWidth))))); *((int*)(bmih.biHeight)) = ENDIAN4(((int)(*((int*)(bmih.biHeight))))); *((short int*)(bmih.biBitCount)) = ENDIAN2(((short int)(*((short int*)(bmih.biBitCount))))); #endif width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; printf("%s %d >> width = %d\n",__FILE__,__LINE__, ENDIAN4(*width_ptr) ); printf("%s %d >> height = %d\n",__FILE__,__LINE__, ENDIAN4(*height_ptr) ); printf("%s %d >> bitcount = %d\n",__FILE__,__LINE__, ENDIAN2(*bitcount_ptr)); // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); #else bmfh.bfType[0] = 'B'; bmfh.bfType[1] = 'M'; *((int*)bmfh.bfSize)= get_LY(lattice)*( (int)ceil( ( ((double)get_LX(lattice))*( /*depth*/24.))/8.) // bytes per row + ( 4 - (int)ceil( ( ((double)get_LX(lattice))*( /*depth*/24.))/8.) % 4) % 4 // pad ); *((short int*)bmfh.bfReserved1) = 0; *((short int*)bmfh.bfReserved2) = 0; *((int*)bmfh.bfOffBits) = 54; // 14 byte file header and 40 byte info header *((int*)bmih.biSize) = 40; *((int*)bmih.biWidth) = get_LX(lattice); *((int*)bmih.biHeight) = get_LY(lattice); *((short int*)bmih.biPlanes) = 1; *((short int*)bmih.biBitCount) = 24; *((int*)bmih.biCompression) = 0; *((int*)bmih.biSizeImage) = 0; *((int*)bmih.biXPelsPerMeter) = 0; *((int*)bmih.biYPelsPerMeter) = 0; *((int*)bmih.biClrUsed) = 0; *((int*)bmih.biClrImportant) = 0; width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; #endif // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; compute_max_u( lattice, max_u, subs); sprintf( filename, "%s/u%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_u = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/u_x%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_ux = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/u_y%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_uy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_u ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_u ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_ux ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_ux ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_uy); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_uy); //for( j=get_LY(lattice)-1; j>=0; j--) for( j=0; j<get_LY(lattice); j++) { n = j*get_LX(lattice); for( i=0; i<get_LX(lattice); i++, n++) { if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { #if 1 blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->macro_vars[subs][ n].u[0]); u_y = (lattice->macro_vars[subs][ n].u[1]); u = sqrt(u_x*u_x + u_y*u_y); maxu = sqrt( max_u[0]*max_u[0] + max_u[1]*max_u[1]); if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); green_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { #if 0 blue_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); green_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); red_val = 0.;//(char)ROUND( 128.*fabs(u)/maxu); #else blue_val = (char)ROUND( 255.*((fabs(u_x)!=0.)?(fabs(u_x)/max_u[0]):(0.))); green_val = (char)ROUND( 255.*((fabs(u_y)!=0.)?(fabs(u_y)/max_u[1]):(0.))); red_val = 0.;//(char)ROUND( 128.*((fabs(u )!=0.)?(fabs(u )/maxu):(0.))); #endif } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ #else blue_val = (char)255; green_val = (char)255; red_val = (char)255; u = sqrt(u_x*u_x + u_y*u_y); maxu = sqrt( max_u[0]*max_u[0] + max_u[1]*max_u[1]); //if( fabs(u) > .1*maxu) //{ green_val = (char)ROUND( 255.-255.*fabs(u)/maxu); red_val = (char)ROUND( 255.-255.*fabs(u)/maxu); blue_val = (char)ROUND( 255.-255.*fabs(u)/maxu); //} //else //{ // green_val = (char)0; // red_val = (char)0; // blue_val = (char)0; //} #endif val = (char)0; } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->macro_vars[subs][ n].u[0]); u_y = (lattice->macro_vars[subs][ n].u[1]); val = (char)0; if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); } else { red_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 255.*((fabs(u_x)!=0.)?(fabs(u_x)/max_u[0]):(0.))); } else { red_val = (char)ROUND( 255.*((fabs(u_x)!=0.)?(fabs(u_x)/max_u[0]):(0.))); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->macro_vars[subs][ n].u[0]); u_y = (lattice->macro_vars[subs][ n].u[1]); val = (char)0; if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { red_val = val; green_val = (char)ROUND( 128.*((fabs(u_y)!=0.)?(fabs(u_y)/max_u[1]):(0.))); } else { red_val = (char)ROUND( 128.*((fabs(u_y)!=0.)?(fabs(u_y)/max_u[1]):(0.))); green_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { blue_val = (char)ROUND( 255.*((fabs(u_y)!=0.)?(fabs(u_y)/max_u[1]):(0.))); green_val = val; } else { blue_val = val; green_val = (char)ROUND( 255.*((fabs(u_y)!=0.)?(fabs(u_y)/max_u[1]):(0.))); } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } /* for( i=0; i<get_LY(lattice); i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<get_LY(lattice); j++) */ fclose(o_u ); fclose(o_ux); fclose(o_uy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/u%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); printf("u2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "%s/u_x%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); printf("u2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "%s/u_y%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); printf("u2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if STORE_U_COMPOSITE frame = time/lattice->param.FrameRate; #if !(PARALLEL) sprintf( filename, "./in/%dx%d.bmp", get_LX(lattice), get_LY(lattice)); #else /*#if PARALLEL*/ sprintf( filename, "./in/%dx%d_proc%04d.bmp", get_LX(lattice), get_LY(lattice), get_proc_id(lattice)); #endif if( !( in = fopen( filename, "r"))) { printf("%s %d >> u2bmp() -- Error opening file \"%s\".\n", __FILE__,__LINE__,filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; compute_max_upr( lattice, max_u); sprintf( filename, "%s/upr%dx%d_frame%04d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, get_proc_id(lattice)); if( !( o_u = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/upr_x%dx%d_frame%04d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, get_proc_id(lattice)); if( !( o_ux = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/upr_y%dx%d_frame%04d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, get_proc_id(lattice)); if( !( o_uy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_u ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_u ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_ux ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_ux ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_uy); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_uy); //for( j=get_LY(lattice)-1; j>=0; j--) for( j=0; j<get_LY(lattice); j++) { n = j*get_LX(lattice); for( i=0; i<get_LX(lattice); i++, n++) { if( lattice->bc[0][ n].bc_type == /*FLUID_NODE*/0) { #if 1 blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->upr[ n].u[0]); u_y = (lattice->upr[ n].u[1]); u = sqrt(u_x*u_x + u_y*u_y); maxu = sqrt( max_u[0]*max_u[0] + max_u[1]*max_u[1]); if( lattice->bc[0][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); green_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); green_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); //red_val = (char)ROUND( 128.*fabs(u)/maxu); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ #else blue_val = (char)255; green_val = (char)255; red_val = (char)255; u = sqrt(u_x*u_x + u_y*u_y); maxu = sqrt( max_u[0]*max_u[0] + max_u[1]*max_u[1]); //if( fabs(u) > .1*maxu) //{ green_val = (char)ROUND( 255.-255.*fabs(u)/maxu); red_val = (char)ROUND( 255.-255.*fabs(u)/maxu); blue_val = (char)ROUND( 255.-255.*fabs(u)/maxu); //} //else //{ // green_val = (char)0; // red_val = (char)0; // blue_val = (char)0; //} #endif val = (char)0; } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[0][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->upr[ n].u[0]); u_y = (lattice->upr[ n].u[1]); val = (char)0; if( lattice->bc[0][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); } else { red_val = (char)ROUND( 128.*fabs(u_x)/max_u[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); } else { red_val = (char)ROUND( 255.*fabs(u_x)/max_u[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[0][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->upr[ n].u[0]); u_y = (lattice->upr[ n].u[1]); val = (char)0; if( lattice->bc[0][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { red_val = val; green_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); } else { red_val = (char)ROUND( 128.*fabs(u_y)/max_u[1]); green_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { blue_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); green_val = val; } else { blue_val = val; green_val = (char)ROUND( 255.*fabs(u_y)/max_u[1]); } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } /* for( i=0; i<get_LY(lattice); i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<get_LY(lattice); j++) */ fclose(o_u ); fclose(o_ux); fclose(o_uy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/upr%dx%d_frame%04d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, get_proc_id(lattice)); printf("u2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "%s/upr_x%dx%d_frame%04d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, get_proc_id(lattice)); printf("u2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "%s/upr_y%dx%d_frame%04d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, get_proc_id(lattice)); printf("u2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ #endif /* STORE_U_COMPOSITE */ #if SAY_HI printf("u2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* u2bmp( lattice_ptr lattice, int time) */ // }}} // V O R 2 B M P {{{ //############################################################################## // void vor2bmp( char *filename, int time) // void vor2bmp( lattice_ptr lattice, int time) { FILE *in, *o_vor; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double max_vor_p, max_vor_n; double ave_vor_p, ave_vor_n; double vor; int subs; #if SAY_HI printf("vor2bmp() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = time/lattice->param.FrameRate; #if 0 sprintf( filename, "./in/%dx%d_proc%04d.bmp", get_LX(lattice), get_LY(lattice), get_proc_id(lattice)); if( !( in = fopen( filename, "r"))) { printf("%s %d >> vor2bmp() -- Error opening file \"%s\".\n", __FILE__,__LINE__,filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); #else bmfh.bfType[0] = 'B'; bmfh.bfType[1] = 'M'; *((int*)bmfh.bfSize)= get_LY(lattice)*( (int)ceil( ( ((double)get_LX(lattice))*( /*depth*/24.))/8.) // bytes per row + ( 4 - (int)ceil( ( ((double)get_LX(lattice))*( /*depth*/24.))/8.) % 4) % 4 // pad ); *((short int*)bmfh.bfReserved1) = 0; *((short int*)bmfh.bfReserved2) = 0; *((int*)bmfh.bfOffBits) = 54; // 14 byte file header and 40 byte info header *((int*)bmih.biSize) = 40; *((int*)bmih.biWidth) = get_LX(lattice); *((int*)bmih.biHeight) = get_LY(lattice); *((short int*)bmih.biPlanes) = 1; *((short int*)bmih.biBitCount) = 24; *((int*)bmih.biCompression) = 0; *((int*)bmih.biSizeImage) = 0; *((int*)bmih.biXPelsPerMeter) = 0; *((int*)bmih.biYPelsPerMeter) = 0; *((int*)bmih.biClrUsed) = 0; *((int*)bmih.biClrImportant) = 0; width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; #endif // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; compute_max_vor( lattice, &max_vor_p, &max_vor_n, subs); #if 0 && VERBOSITY_LEVEL > 0 printf("vor2bmp() -- max_vor_p = %f\n", max_vor_p); printf("vor2bmp() -- max_vor_n = %f\n", max_vor_n); #endif /* 0 && VERBOSITY_LEVEL > 0 */ compute_ave_vor( lattice, &ave_vor_p, &ave_vor_n, subs); #if 0 && VERBOSITY_LEVEL > 0 printf("vor2bmp() -- ave_vor_p = %f\n", ave_vor_p); printf("vor2bmp() -- ave_vor_n = %f\n", ave_vor_n); #endif /* 0 && VERBOSITY_LEVEL > 0 */ sprintf( filename, "%s/vor%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_vor = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_vor ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_vor ); //for( j=get_LY(lattice)-1; j>=0; j--) for( j=0; j<get_LY(lattice); j++) { n = j*get_LX(lattice); for( i=0; i<get_LX(lattice); i++, n++) { if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { //u_x = (lattice->macro_vars[subs][ n].u[0]); //u_y = (lattice->macro_vars[subs][ n].u[1]); compute_vorticity( lattice, i, j, n, &vor, subs); //if( fabs(vor)/max_vor_p > .5) //{ // printf("vor2bmp() -- vor/max_vor_p = %f/%f = %f\n", vor, max_vor_p, vor/max_vor_p); //} #if 0 blue_val = (char)255; green_val = (char)255; red_val = (char)255; if( vor > 0) { if( 100.*vor/ave_vor_p > 1.) { //printf("vor2bmp() -- vor/ave_vor_p = %f > 1.\n", vor/ave_vor_p); red_val = (char)0; green_val = (char)0; } else { //printf("vor2bmp() -- vor/ave_vor_p = %f <= 1.\n", vor/ave_vor_p); red_val = (char)ROUND( 255.*( 1. - 10000.*(vor/ave_vor_p)*(vor/ave_vor_p))); green_val = (char)ROUND( 255.*( 1. - 10000.*(vor/ave_vor_p)*(vor/ave_vor_p))); } } else { if( 100.*vor/ave_vor_n > 1.) { //printf("vor2bmp() -- vor/ave_vor_n = %f > 1.\n", vor/ave_vor_n); red_val = (char)0; blue_val = (char)0; } else { //printf("vor2bmp() -- vor/ave_vor_n = %f <= 1.\n", vor/ave_vor_n); red_val = (char)ROUND( 255.*( 1. - 10000.*(vor/ave_vor_n)*(vor/ave_vor_n))); blue_val = (char)ROUND( 255.*( 1. - 10000.*(vor/ave_vor_n)*(vor/ave_vor_n))); } } #else #if 0 blue_val = (char)0; green_val = (char)0; red_val = (char)0; // blue_val = //(char)ROUND( 255.*(vor - max_vor_n)/(max_vor_p-max_vor_n)); if( vor >= 0.) { blue_val = (char)ROUND( 255.*(vor)/(max_vor_p)); } else { red_val = (char)ROUND( 255.*(vor)/(max_vor_n)); } #else red_val = (char)ROUND( 255.*(vor - max_vor_n)/(max_vor_p-max_vor_n)); green_val = (char)ROUND( 255.*(vor - max_vor_n)/(max_vor_p-max_vor_n)); blue_val = (char)ROUND( 255.*(vor - max_vor_n)/(max_vor_p-max_vor_n)); #endif #endif val = (char)0; } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ //#if SOLID_COLOR_IS_BLACK // red_val = (char)0; // green_val = (char)0; // blue_val = (char)0; // val = (char)0; //#else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; //#endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_vor ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_vor ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_vor ) != 1) { printf("BOOM!\n"); process_exit(1);} } /* for( i=0; i<get_LY(lattice); i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o_vor ) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<get_LY(lattice); j++) */ fclose(o_vor ); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/vor%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); printf("vor2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("vor2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* vor2bmp( lattice_ptr lattice, int time) */ // }}} #if NON_LOCAL_FORCES // F O R C E 2 B M P {{{ //############################################################################## // void force2bmp( char *filename, int time) // void force2bmp( lattice_ptr lattice) { FILE *in, *o_u, *o_ux, *o_uy; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double max_force[2], maxforce; double u_x, u_y, u; int subs; #if SAY_HI printf("force2bmp() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = lattice->time/lattice->param.FrameRate; #if 0 sprintf( filename, "./in/%dx%d_proc%04d.bmp", get_LX(lattice), get_LY(lattice), get_proc_id(lattice)); if( !( in = fopen( filename, "r"))) { printf("%s %d >> force2bmp() -- Error opening file \"%s\".\n", __FILE__,__LINE__,filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); #else bmfh.bfType[0] = 'B'; bmfh.bfType[1] = 'M'; *((int*)bmfh.bfSize)= get_LY(lattice)*( (int)ceil( ( ((double)get_LX(lattice))*( /*depth*/24.))/8.) // bytes per row + ( 4 - (int)ceil( ( ((double)get_LX(lattice))*( /*depth*/24.))/8.) % 4) % 4 // pad ); *((short int*)bmfh.bfReserved1) = 0; *((short int*)bmfh.bfReserved2) = 0; *((int*)bmfh.bfOffBits) = 54; // 14 byte file header and 40 byte info header *((int*)bmih.biSize) = 40; *((int*)bmih.biWidth) = get_LX(lattice); *((int*)bmih.biHeight) = get_LY(lattice); *((short int*)bmih.biPlanes) = 1; *((short int*)bmih.biBitCount) = 24; *((int*)bmih.biCompression) = 0; *((int*)bmih.biSizeImage) = 0; *((int*)bmih.biXPelsPerMeter) = 0; *((int*)bmih.biYPelsPerMeter) = 0; *((int*)bmih.biClrUsed) = 0; *((int*)bmih.biClrImportant) = 0; width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; #endif // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; compute_max_force( lattice, max_force, subs); sprintf( filename, "%s/force_%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_u = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/force_x_%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_ux = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/force_y_%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_uy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_u ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_u ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_ux ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_ux ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_uy); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_uy); //for( j=get_LY(lattice)-1; j>=0; j--) for( j=0; j<get_LY(lattice); j++) { n = j*get_LX(lattice); for( i=0; i<get_LX(lattice); i++, n++) { if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { #if 1 blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->force[subs][ n].force[0]); u_y = (lattice->force[subs][ n].force[1]); u = sqrt(u_x*u_x + u_y*u_y); maxforce = sqrt( max_force[0]*max_force[0] + max_force[1]*max_force[1]); if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 128.*fabs(u_x)/max_force[0]); green_val = (char)ROUND( 128.*fabs(u_y)/max_force[1]); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 255.*fabs(u_x)/max_force[0]); green_val = (char)ROUND( 255.*fabs(u_y)/max_force[1]); //red_val = (char)ROUND( 128.*fabs(u)/maxforce); red_val = (char)ROUND( 255.*fabs(u)/maxforce); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ #else blue_val = (char)255; green_val = (char)255; red_val = (char)255; u = sqrt(u_x*u_x + u_y*u_y); maxforce = sqrt( max_force[0]*max_force[0] + max_force[1]*max_force[1]); //if( fabs(u) > .1*maxforce) //{ green_val = (char)ROUND( 255.-255.*fabs(u)/maxforce); red_val = (char)ROUND( 255.-255.*fabs(u)/maxforce); blue_val = (char)ROUND( 255.-255.*fabs(u)/maxforce); //} //else //{ // green_val = (char)0; // red_val = (char)0; // blue_val = (char)0; //} #endif val = (char)0; } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->force[subs][ n].force[0]); u_y = (lattice->force[subs][ n].force[1]); val = (char)0; if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 128.*fabs(u_x)/max_force[0]); } else { red_val = (char)ROUND( 128.*fabs(u_x)/max_force[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 255.*fabs(u_x)/max_force[0]); } else { red_val = (char)ROUND( 255.*fabs(u_x)/max_force[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->force[subs][ n].force[0]); u_y = (lattice->force[subs][ n].force[1]); val = (char)0; if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { red_val = val; green_val = (char)ROUND( 128.*fabs(u_y)/max_force[1]); } else { red_val = (char)ROUND( 128.*fabs(u_y)/max_force[1]); green_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { blue_val = (char)ROUND( 255.*fabs(u_y)/max_force[1]); green_val = val; } else { blue_val = val; green_val = (char)ROUND( 255.*fabs(u_y)/max_force[1]); } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } /* for( i=0; i<get_LY(lattice); i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<get_LY(lattice); j++) */ fclose(o_u ); fclose(o_ux); fclose(o_uy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/force_%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); printf("force2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "%s/force_x_%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); printf("force2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "%s/force_y_%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); printf("force2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("force2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* void force2bmp( lattice_ptr lattice) */ // }}} // S F O R C E 2 B M P {{{ //############################################################################## // void sforce2bmp( char *filename, int time) // void sforce2bmp( lattice_ptr lattice) { FILE *in, *o_u, *o_ux, *o_uy; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double max_sforce[2], maxsforce; double u_x, u_y, u; int subs; #if SAY_HI printf("sforce2bmp() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { frame = lattice->time/lattice->param.FrameRate; #if 0 sprintf( filename, "./in/%dx%d_proc%04d.bmp", get_LX(lattice), get_LY(lattice), get_proc_id(lattice)); if( !( in = fopen( filename, "r"))) { printf("%s %d >> sforce2bmp() -- Error opening file \"%s\".\n", __FILE__,__LINE__,filename); process_exit(1); } // n = fread( void *BUF, size_t SIZE, size_t COUNT, FILE *FP); n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( &bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih.biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; // Read palette entries, if applicable. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } fclose(in); #else bmfh.bfType[0] = 'B'; bmfh.bfType[1] = 'M'; *((int*)bmfh.bfSize)= get_LY(lattice)*( (int)ceil( ( ((double)get_LX(lattice))*( /*depth*/24.))/8.) // bytes per row + ( 4 - (int)ceil( ( ((double)get_LX(lattice))*( /*depth*/24.))/8.) % 4) % 4 // pad ); *((short int*)bmfh.bfReserved1) = 0; *((short int*)bmfh.bfReserved2) = 0; *((int*)bmfh.bfOffBits) = 54; // 14 byte file header and 40 byte info header *((int*)bmih.biSize) = 40; *((int*)bmih.biWidth) = get_LX(lattice); *((int*)bmih.biHeight) = get_LY(lattice); *((short int*)bmih.biPlanes) = 1; *((short int*)bmih.biBitCount) = 24; *((int*)bmih.biCompression) = 0; *((int*)bmih.biSizeImage) = 0; *((int*)bmih.biXPelsPerMeter) = 0; *((int*)bmih.biYPelsPerMeter) = 0; *((int*)bmih.biClrUsed) = 0; *((int*)bmih.biClrImportant) = 0; width_ptr = (int*)bmih.biWidth; height_ptr = (int*)bmih.biHeight; bitcount_ptr = (short int*)bmih.biBitCount; #endif // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; compute_max_sforce( lattice, max_sforce, subs); sprintf( filename, "%s/sforce_%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_u = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/sforce_x_%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_ux = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } sprintf( filename, "%s/sforce_y_%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); if( !( o_uy = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_u ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_u ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_ux ); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_ux ); fwrite( &bmfh, sizeof(struct bitmap_file_header), 1, o_uy); fwrite( &bmih, sizeof(struct bitmap_info_header), 1, o_uy); //for( j=get_LY(lattice)-1; j>=0; j--) for( j=0; j<get_LY(lattice); j++) { n = j*get_LX(lattice); for( i=0; i<get_LX(lattice); i++, n++) { if( 1)//lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { #if 1 blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->force[subs][ n].sforce[0]); u_y = (lattice->force[subs][ n].sforce[1]); u = sqrt(u_x*u_x + u_y*u_y); maxsforce = sqrt( max_sforce[0]*max_sforce[0] + max_sforce[1]*max_sforce[1]); if( 0)//lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 128.*fabs(u_x)/max_sforce[0]); green_val = (char)ROUND( 128.*fabs(u_y)/max_sforce[1]); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { blue_val = (char)ROUND( 255.*fabs(u_x)/max_sforce[0]); green_val = (char)ROUND( 255.*fabs(u_y)/max_sforce[1]); //red_val = (char)ROUND( 128.*fabs(u)/maxsforce); red_val = (char)ROUND( 255.*fabs(u)/maxsforce); } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ #else blue_val = (char)255; green_val = (char)255; red_val = (char)255; u = sqrt(u_x*u_x + u_y*u_y); maxsforce = sqrt( max_sforce[0]*max_sforce[0] + max_sforce[1]*max_sforce[1]); //if( fabs(u) > .1*maxsforce) //{ green_val = (char)ROUND( 255.-255.*fabs(u)/maxsforce); red_val = (char)ROUND( 255.-255.*fabs(u)/maxsforce); blue_val = (char)ROUND( 255.-255.*fabs(u)/maxsforce); //} //else //{ // green_val = (char)0; // red_val = (char)0; // blue_val = (char)0; //} #endif val = (char)0; } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ //printf("RGB=(%d,%d,%d)\n",red_val,green_val,blue_val); if( fwrite( &blue_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->force[subs][ n].sforce[0]); u_y = (lattice->force[subs][ n].sforce[1]); val = (char)0; if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 128.*fabs(u_x)/max_sforce[0]); } else { red_val = (char)ROUND( 128.*fabs(u_x)/max_sforce[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_x > 0) { red_val = val; blue_val = (char)ROUND( 255.*fabs(u_x)/max_sforce[0]); } else { red_val = (char)ROUND( 255.*fabs(u_x)/max_sforce[0]); blue_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( lattice->bc[subs][ n].bc_type == /*FLUID_NODE*/0) { blue_val = (char)0; green_val = (char)0; red_val = (char)0; u_x = (lattice->force[subs][ n].sforce[0]); u_y = (lattice->force[subs][ n].sforce[1]); val = (char)0; if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { red_val = val; green_val = (char)ROUND( 128.*fabs(u_y)/max_sforce[1]); } else { red_val = (char)ROUND( 128.*fabs(u_y)/max_sforce[1]); green_val = val; } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) */ else // !( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) { if( u_y > 0) { blue_val = (char)ROUND( 255.*fabs(u_y)/max_sforce[1]); green_val = val; } else { blue_val = val; green_val = (char)ROUND( 255.*fabs(u_y)/max_sforce[1]); } } /* if( lattice->bc[subs][ n].bc_type & BC_SOLID_NODE) else */ } /* if( lattice->bc[subs][ n].bc_type == 0) */ else // lattice->bc[subs][ n].bc_type != 0 { #if SOLID_COLOR_IS_CHECKERBOARD // Checkerboard pattern over the solids and boundary conditions. if( (i+j)%2) { red_val = (char)200; green_val = (char)200; blue_val = (char)200; val = (char)200; } else { red_val = (char)184; green_val = (char)184; blue_val = (char)184; val = (char)184; } #else /* !( SOLID_COLOR_IS_CHECKERBOARD) */ #if SOLID_COLOR_IS_BLACK red_val = (char)0; green_val = (char)0; blue_val = (char)0; val = (char)0; #else /* !( SOLID_COLOR_IS_BLACK) */ red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; #endif /* SOLID_COLOR_IS_BLACK */ #endif /* SOLID_COLOR_IS_CHECKERBOARD */ } /* if( lattice->bc[subs][ n].bc_type == 0) else */ #if MARK_ORIGIN_FOR_REFERENCE // Mark the origin for reference. if( ( i == 0 && j == 0)) { red_val = (char)255; green_val = (char)255; blue_val = (char)255; val = (char)255; } #endif /* MARK_ORIGIN_FOR_REFERENCE */ if( fwrite( &blue_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &green_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &red_val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } /* for( i=0; i<get_LY(lattice); i++) */ // Pad for 4-byte boundaries. val = (char)0; for( i=0; i<pad; i++) { if( fwrite( &val, 1, 1, o_u ) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_ux) != 1) { printf("BOOM!\n"); process_exit(1);} if( fwrite( &val, 1, 1, o_uy) != 1) { printf("BOOM!\n"); process_exit(1);} } } /* for( j=0; j<get_LY(lattice); j++) */ fclose(o_u ); fclose(o_ux); fclose(o_uy); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s/sforce_%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); printf("sforce2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "%s/sforce_x_%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); printf("sforce2bmp() -- Wrote file \"%s\".\n", filename); sprintf( filename, "%s/sforce_y_%dx%d_frame%04d_subs%02d_proc%04d.bmp", get_out_path(lattice), get_LX(lattice), get_LY(lattice), frame, subs, get_proc_id(lattice)); printf("sforce2bmp() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("sforce2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* void sforce2bmp( lattice_ptr lattice) */ // }}} #endif /* NON_LOCAL_FORCES */ // P D F 2 B M P {{{ //############################################################################## // void pdf2bmp( char *filename, int time) // void pdf2bmp( lattice_ptr lattice, int time) { FILE *in, *o; int i, j, n, m; int pad, bytes_per_row; int frame; char k; char b; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; char filename[1024]; char red_val, green_val, blue_val, val; double fval; double min_rho, max_rho; int subs; double **colormap; int num_colors; int fx=2, fy=2; // Number of pixels to use to represent a pdf value. #if SAY_HI printf("pdf2bmp() -- Hi!\n"); #endif /* SAY_HI */ // TODO: Implement pdf2bmp() printf("%s (%d) >> pdf2bmp() is not yet implemented. Exiting!\n", __FILE__, __LINE__); process_exit(1); #if SAY_HI printf("pdf2bmp() -- Bye!\n"); printf("\n"); #endif /* SAY_HI */ } /* pdf2bmp( lattice_ptr lattice, int time) */ // }}} // S L I C E {{{ //############################################################################## //void slice( lattice_ptr lattice) // // - Extract slice (i0,j0)..(i1,j1) from the macroscopic variables. // // - Write to matlab scripts for easy processing. // void slice( lattice_ptr lattice) { int i0, j0, i1, j1; int i, j, n; int len; double *rho_slice; double *u_x_slice; double *u_y_slice; char filename[1024]; FILE *in, *o; int subs; if( use_slice_dot_in_file( lattice)) { printf("%s %d >> Using slice.in file.\n",__FILE__,__LINE__); if( !( in = fopen( "./in/slice.in", "r"))) { // Default slice. i0 = 0; j0 = (int)floor((double)get_LY(lattice)/2.); i1 = get_LX(lattice)-1; j1 = (int)floor((double)get_LY(lattice)/2.); } else { // Read slice from file. fscanf( in, "%d", &i0); fscanf( in, "%d", &j0); fscanf( in, "%d", &i1); fscanf( in, "%d", &j1); fclose( in); } private_slice( lattice, "slice", i0, j0, i1, j1); } else { if( get_slice_x( lattice) >= 0) { private_slice( lattice, "slice_x", get_slice_x( lattice), 0, get_slice_x( lattice), get_LY( lattice)-1 ); } if( get_slice_y( lattice) >= 0) { private_slice( lattice, "slice_y", 0, get_slice_y( lattice), get_LX( lattice)-1, get_slice_y( lattice) ); } } } /* void slice( lattice_ptr lattice) */ // }}} // P R I V A T E _ S L I C E {{{ //############################################################################## //void private_slice( lattice_ptr lattice, int i0, int j0, int i1, int j1) // // - Extract slice (i0,j0)..(i1,j1) from the macroscopic variables. // // - Write to matlab scripts for easy processing. // void private_slice( lattice_ptr lattice, char *root_word, int i0, int j0, int i1, int j1) { int i, j, k, n; int len, wid; double *rho_slice; double *rho_ave; double *u_x_slice; double *u_x_ave; double *u_y_slice; double *u_y_ave; #if STORE_U_COMPOSITE double *upr_x_slice; double *upr_x_ave; double *upr_y_slice; double *upr_y_ave; #endif /* (STORE_U_COMPOSITE) */ char filename[1024]; FILE *in, *o; double ave_rho; int subs; char plot_specs[2][4] = { { '\'', 'b', '\'', '\x0'}, { '\'', 'r', '\'', '\x0'} }; if( i0 == i1) { if( i0 < 0 || i0 >= get_LX( lattice)) { printf("lbio.c: private_slice() -- " "ERROR: Can't take slice at " "i0 = i1 = %d.\n", i0 ); i0 = get_LX(lattice)/2; i1 = get_LX(lattice)/2; printf("lbio.c: private_slice() -- Defaulting to i0 = i1 = %d.\n", i0); return; } len = j1 - j0 + 1; if( len > get_LY(lattice)) { len = get_LY(lattice); } rho_slice = (double*)malloc( len*sizeof(double)); rho_ave = (double*)malloc( len*sizeof(double)); u_x_slice = (double*)malloc( len*sizeof(double)); u_x_ave = (double*)malloc( len*sizeof(double)); u_y_slice = (double*)malloc( len*sizeof(double)); u_y_ave = (double*)malloc( len*sizeof(double)); #if STORE_U_COMPOSITE upr_x_slice = (double*)malloc( len*sizeof(double)); upr_x_ave = (double*)malloc( len*sizeof(double)); upr_y_slice = (double*)malloc( len*sizeof(double)); upr_y_ave = (double*)malloc( len*sizeof(double)); #endif /* (STORE_U_COMPOSITE) */ // Generate matlab script to plot the slices. sprintf( filename, "%s/%s%dx%d_frame%04d.m", get_out_path(lattice), root_word, get_LX(lattice), get_LY(lattice), lattice->time/lattice->param.FrameRate); if( !( o = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fprintf( o, "%% function [ slice_data] = %s%dx%d_frame%04d( plot_stuff)\n", root_word, get_LX(lattice), get_LY(lattice), lattice->time/lattice->param.FrameRate); fprintf( o, "function [ slice_data] = %s%dx%d_frame%04d( plot_stuff)\n\n", root_word, get_LX(lattice), get_LY(lattice), lattice->time/lattice->param.FrameRate); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { // Slice. len = 0; for( j=j0; j<=j1; j++) { n = j*get_LX(lattice) + i0; if( j>=0 && j<get_LY(lattice)) { rho_slice[ len] = lattice->macro_vars[subs][ n].rho; u_x_slice[ len] = lattice->macro_vars[subs][ n].u[0]; u_y_slice[ len] = lattice->macro_vars[subs][ n].u[1]; #if STORE_U_COMPOSITE if(subs==0) { upr_x_slice[ len] = lattice->upr[ n].u[0]; upr_y_slice[ len] = lattice->upr[ n].u[1]; } #endif /* (STORE_U_COMPOSITE) */ rho_ave[ len] = 0.; u_x_ave[ len] = 0.; u_y_ave[ len] = 0.; #if STORE_U_COMPOSITE if(subs==0) { upr_x_ave[ len] = 0.; upr_y_ave[ len] = 0.; } #endif /* (STORE_U_COMPOSITE) */ wid = 0; for( i=0; i<get_LX(lattice); i++) { if( !( lattice->bc[subs][ j*get_LX(lattice) + i].bc_type & BC_SOLID_NODE)) { rho_ave[ len] += lattice->macro_vars[subs][ j*get_LX(lattice)+i].rho; u_x_ave[ len] += lattice->macro_vars[subs][ j*get_LX(lattice)+i].u[0]; u_y_ave[ len] += lattice->macro_vars[subs][ j*get_LX(lattice)+i].u[1]; #if STORE_U_COMPOSITE if(subs==0) { upr_x_ave[ len] += lattice->upr[ j*get_LX(lattice)+i].u[0]; upr_y_ave[ len] += lattice->upr[ j*get_LX(lattice)+i].u[1]; } #endif /* (STORE_U_COMPOSITE) */ wid++; } } rho_ave[ len] /= wid; u_x_ave[ len] /= wid; u_y_ave[ len] /= wid; #if STORE_U_COMPOSITE if(subs==0) { upr_x_ave[ len] /= wid; upr_y_ave[ len] /= wid; } #endif /* (STORE_U_COMPOSITE) */ len++; } } fprintf( o, "rho_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", rho_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "rho_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", rho_ave[ n]); } fprintf( o, "];\n"); fprintf( o, "u_x_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_x_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "u_x_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_x_ave[ n]); } fprintf( o, "];\n"); fprintf( o, "u_y_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_y_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "u_y_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_y_ave[ n]); } fprintf( o, "];\n"); #if STORE_U_COMPOSITE if(subs==0) { fprintf( o, "upr_x_slice= [ "); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", upr_x_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "upr_x_ave= [ "); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", upr_x_ave[ n]); } fprintf( o, "];\n"); fprintf( o, "upr_y_slice= [ "); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", upr_y_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "upr_y_ave= [ "); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", upr_y_ave[ n]); } fprintf( o, "];\n"); } #endif /* (STORE_U_COMPOSITE) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ if( make_octave_scripts(lattice)) { } /* if( make_octave_scripts(lattice)) */ else // make Matlab scripts { fprintf( o, "slice_data = zeros(%d,%d,%d);\n", len, 10, NUM_FLUID_COMPONENTS); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "slice_data(:,1,%d) = rho_slice%02d;\n", subs+1, subs); fprintf( o, "slice_data(:,2,%d) = rho_ave%02d;\n" , subs+1, subs); fprintf( o, "slice_data(:,3,%d) = u_x_slice%02d;\n", subs+1, subs); fprintf( o, "slice_data(:,4,%d) = u_x_ave%02d;\n" , subs+1, subs); fprintf( o, "slice_data(:,5,%d) = u_y_slice%02d;\n", subs+1, subs); fprintf( o, "slice_data(:,6,%d) = u_y_ave%02d;\n" , subs+1, subs); #if STORE_U_COMPOSITE if(subs==0) { fprintf( o, "slice_data(:,7,%d) = upr_x_slice;\n", subs+1); fprintf( o, "slice_data(:,8,%d) = upr_x_ave;\n" , subs+1); fprintf( o, "slice_data(:,9,%d) = upr_y_slice;\n", subs+1); fprintf( o, "slice_data(:,10,%d) = upr_y_ave;\n" , subs+1); } #endif /* (STORE_U_COMPOSITE) */ fprintf( o, "disp('slice_data(:,1,%d) = rho_slice%02d');\n", subs+1, subs); fprintf( o, "disp('slice_data(:,2,%d) = rho_ave%02d' );\n", subs+1, subs); fprintf( o, "disp('slice_data(:,3,%d) = u_x_slice%02d');\n", subs+1, subs); fprintf( o, "disp('slice_data(:,4,%d) = u_x_ave%02d' );\n", subs+1, subs); fprintf( o, "disp('slice_data(:,5,%d) = u_y_slice%02d');\n", subs+1, subs); fprintf( o, "disp('slice_data(:,6,%d) = u_y_ave%02d' );\n", subs+1, subs); #if STORE_U_COMPOSITE if(subs==0) { fprintf( o, "disp('slice_data(:,7,%d) = upr_x_slice');\n", subs+1); fprintf( o, "disp('slice_data(:,8,%d) = upr_x_ave' );\n", subs+1); fprintf( o, "disp('slice_data(:,9,%d) = upr_y_slice');\n", subs+1); fprintf( o, "disp('slice_data(:,10,%d) = upr_y_ave' );\n", subs+1); } #endif /* (STORE_U_COMPOSITE) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ } } /* if( i0 == i1) */ else if( j0 == j1) { if( j0 < 0 || j0 >= get_LY(lattice)) { printf("lbio.c: private_slice() -- " "ERROR: Can't take slice at " "j0 = j1 = %d.\n", j0 ); j0 = get_LY(lattice)/2; j1 = get_LY(lattice)/2; printf("lbio.c: private_slice() -- Defaulting to j0 = j1 = %d.\n", j0); return; } len = i1 - i0 + 1; if( len > get_LX(lattice)) { len = get_LX(lattice); } rho_slice = (double*)malloc( len*sizeof(double)); rho_ave = (double*)malloc( len*sizeof(double)); u_x_slice = (double*)malloc( len*sizeof(double)); u_x_ave = (double*)malloc( len*sizeof(double)); u_y_slice = (double*)malloc( len*sizeof(double)); u_y_ave = (double*)malloc( len*sizeof(double)); #if STORE_U_COMPOSITE upr_x_slice = (double*)malloc( len*sizeof(double)); upr_x_ave = (double*)malloc( len*sizeof(double)); upr_y_slice = (double*)malloc( len*sizeof(double)); upr_y_ave = (double*)malloc( len*sizeof(double)); #endif /* (STORE_U_COMPOSITE) */ // Generate matlab script to plot the slices. sprintf( filename, "%s/%s%dx%d_frame%04d.m", get_out_path(lattice), root_word, get_LX(lattice), get_LY(lattice), lattice->time/lattice->param.FrameRate); if( !( o = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } fprintf( o, "%% function [ slice_data] = %s%dx%d_frame%04d( plot_stuff)\n", root_word, get_LX(lattice), get_LY(lattice), lattice->time/lattice->param.FrameRate); fprintf( o, "function [ slice_data] = %s%dx%d_frame%04d( plot_stuff)\n\n", root_word, get_LX(lattice), get_LY(lattice), lattice->time/lattice->param.FrameRate); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { // Slice. len = 0; for( i=i0; i<=i1; i++) { n = j0*get_LX(lattice) + i; if( i>=0 && i<get_LX(lattice)) { rho_slice[ len] = lattice->macro_vars[subs][ n].rho; u_x_slice[ len] = lattice->macro_vars[subs][ n].u[0]; u_y_slice[ len] = lattice->macro_vars[subs][ n].u[1]; #if STORE_U_COMPOSITE if(subs==0) { upr_x_slice[ len] = lattice->upr[ n].u[0]; upr_y_slice[ len] = lattice->upr[ n].u[1]; } #endif /* (STORE_U_COMPOSITE) */ rho_ave[ len] = 0.; u_x_ave[ len] = 0.; u_y_ave[ len] = 0.; #if STORE_U_COMPOSITE if(subs==0) { upr_x_ave[ len] = 0.; upr_y_ave[ len] = 0.; } #endif /* (STORE_U_COMPOSITE) */ wid = 0; for( j=0; j<get_LY(lattice); j++) { if( !( lattice->bc[subs][ j*get_LX(lattice) + i].bc_type & BC_SOLID_NODE)) { rho_ave[ len] += lattice->macro_vars[subs][ j*get_LX(lattice)+i].rho; u_x_ave[ len] += lattice->macro_vars[subs][ j*get_LX(lattice)+i].u[0]; u_y_ave[ len] += lattice->macro_vars[subs][ j*get_LX(lattice)+i].u[1]; #if STORE_U_COMPOSITE if(subs==0) { upr_x_ave[ len] += lattice->upr[ j*get_LX(lattice)+i].u[0]; upr_y_ave[ len] += lattice->upr[ j*get_LX(lattice)+i].u[1]; } #endif /* (STORE_U_COMPOSITE) */ wid++; } } rho_ave[ len] /= wid; u_x_ave[ len] /= wid; u_y_ave[ len] /= wid; #if STORE_U_COMPOSITE if(subs==0) { upr_x_ave[ len] /= wid; upr_y_ave[ len] /= wid; } #endif /* (STORE_U_COMPOSITE) */ len++; } } fprintf( o, "rho_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", rho_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "rho_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", rho_ave[ n]); } fprintf( o, "];\n"); fprintf( o, "u_x_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_x_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "u_x_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_x_ave[ n]); } fprintf( o, "];\n"); if(1) { fprintf( o, "u_y_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_y_slice[ n]); } fprintf( o, "];\n"); } else { // // Output a series of slices showing entry length effects. // len = 0; // fprintf( o, "u_y_slice%02d_j%d = [ ", subs, j); // for( i=i0; i<=i1; i++) // { // n = j0*get_LX(lattice) + i; // if( i>=0 && i<get_LX(lattice)) // { // for( j=1; // j<get_LY(lattice)-1; // j+=(int)floor(((double)get_LY(lattice)/10.)) ) // { // fprintf( o, " %20.17f ", lattice->macro_vars[subs][ n].u[1]); // } // } // } // fprintf( o, "];\n"); } fprintf( o, "u_y_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_y_ave[ n]); } fprintf( o, "];\n"); #if STORE_U_COMPOSITE if(subs==0) { fprintf( o, "upr_x_slice= [ "); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", upr_x_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "upr_x_ave= [ "); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", upr_x_ave[ n]); } fprintf( o, "];\n"); fprintf( o, "upr_y_slice= [ "); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", upr_y_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "upr_y_ave= [ "); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", upr_y_ave[ n]); } fprintf( o, "];\n"); } #endif /* (STORE_U_COMPOSITE) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ if( make_octave_scripts(lattice)) { } /* if( make_octave_scripts(lattice)) */ else // make Matlab scripts { fprintf( o, "slice_data = zeros(%d,%d,%d);\n", len, 10, NUM_FLUID_COMPONENTS); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "slice_data(:,1,%d) = rho_slice%02d;\n", subs+1, subs); fprintf( o, "slice_data(:,2,%d) = rho_ave%02d;\n" , subs+1, subs); fprintf( o, "slice_data(:,3,%d) = u_x_slice%02d;\n", subs+1, subs); fprintf( o, "slice_data(:,4,%d) = u_x_ave%02d;\n" , subs+1, subs); fprintf( o, "slice_data(:,5,%d) = u_y_slice%02d;\n", subs+1, subs); fprintf( o, "slice_data(:,6,%d) = u_y_ave%02d;\n" , subs+1, subs); #if STORE_U_COMPOSITE if(subs==0) { fprintf( o, "slice_data(:,7,%d) = upr_x_slice;\n", subs+1); fprintf( o, "slice_data(:,8,%d) = upr_x_ave;\n" , subs+1); fprintf( o, "slice_data(:,9,%d) = upr_y_slice;\n", subs+1); fprintf( o, "slice_data(:,10,%d) = upr_y_ave;\n" , subs+1); } #endif /* (STORE_U_COMPOSITE) */ fprintf( o, "disp('slice_data(:,1,%d) = rho_slice%02d');\n", subs+1, subs); fprintf( o, "disp('slice_data(:,2,%d) = rho_ave%02d' );\n", subs+1, subs); fprintf( o, "disp('slice_data(:,3,%d) = u_x_slice%02d');\n", subs+1, subs); fprintf( o, "disp('slice_data(:,4,%d) = u_x_ave%02d' );\n", subs+1, subs); fprintf( o, "disp('slice_data(:,5,%d) = u_y_slice%02d');\n", subs+1, subs); fprintf( o, "disp('slice_data(:,6,%d) = u_y_ave%02d' );\n", subs+1, subs); #if STORE_U_COMPOSITE if(subs==0) { fprintf( o, "disp('slice_data(:,7,%d) = upr_x_slice');\n", subs+1); fprintf( o, "disp('slice_data(:,8,%d) = upr_x_ave' );\n", subs+1); fprintf( o, "disp('slice_data(:,9,%d) = upr_y_slice');\n", subs+1); fprintf( o, "disp('slice_data(:,10,%d) = upr_y_ave' );\n", subs+1); } #endif /* (STORE_U_COMPOSITE) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ } } /* if( i0 == i1) else if( j0 == j1) */ else { // Count. len = 0; for( i=i0; i<=i1; i++) { if( i>=0 && i<get_LX(lattice)) { j = j0 + (i-i0)*((j1-j0)/(i1-i0)); if( j>=0 && j<get_LY(lattice)) { len++; } } } rho_slice = (double*)malloc( len*sizeof(double)); rho_ave = (double*)malloc( len*sizeof(double)); u_x_slice = (double*)malloc( len*sizeof(double)); u_x_ave = (double*)malloc( len*sizeof(double)); u_y_slice = (double*)malloc( len*sizeof(double)); u_y_ave = (double*)malloc( len*sizeof(double)); #if STORE_U_COMPOSITE if(subs==0) { upr_x_slice = (double*)malloc( len*sizeof(double)); upr_x_ave = (double*)malloc( len*sizeof(double)); upr_y_slice = (double*)malloc( len*sizeof(double)); upr_y_ave = (double*)malloc( len*sizeof(double)); } #endif /* (STORE_U_COMPOSITE) */ // Generate matlab script to plot the slices. sprintf( filename, "%s/%s%dx%d_frame%04d.m", get_out_path(lattice), root_word, get_LX(lattice), get_LY(lattice), lattice->time/lattice->param.FrameRate); if( !( o = fopen( filename, "w+"))) { printf("ERROR: fopen( \"%s\", \"w+\") = NULL. Bye, bye!\n", filename); process_exit(1); } for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { // Slice. len = 0; for( i=i0; i<=i1; i++) { if( i>=0 && i<get_LX(lattice)) { j = j0 + (i-i0)*((j1-j0)/(i1-i0)); if( j>=0 && j<get_LY(lattice)) { n = j*get_LX(lattice) + i; if( n != -1) { rho_slice[ len] = lattice->macro_vars[subs][ n].rho; u_x_slice[ len] = lattice->macro_vars[subs][ n].u[0]; u_y_slice[ len] = lattice->macro_vars[subs][ n].u[1]; #if STORE_U_COMPOSITE if(subs==0) { upr_x_slice[ len] = lattice->upr[ n].u[0]; upr_y_slice[ len] = lattice->upr[ n].u[1]; } #endif /* (STORE_U_COMPOSITE) */ rho_ave[ len] = 0.; u_x_ave[ len] = 0.; u_y_ave[ len] = 0.; #if STORE_U_COMPOSITE if(subs==0) { upr_x_ave[ len] = 0.; upr_y_ave[ len] = 0.; } #endif /* (STORE_U_COMPOSITE) */ wid = 0; for( k=0; k<get_LY(lattice); k++) { if( !( lattice->bc[subs][ j*get_LX(lattice) + i].bc_type & BC_SOLID_NODE)) { rho_ave[ len] += lattice->macro_vars[subs][ k*get_LX(lattice)+i].rho; u_x_ave[ len] += lattice->macro_vars[subs][ k*get_LX(lattice)+i].u[0]; u_y_ave[ len] += lattice->macro_vars[subs][ k*get_LX(lattice)+i].u[1]; #if STORE_U_COMPOSITE if(subs==0) { upr_x_ave[ len] += lattice->upr[ k*get_LX(lattice)+i].u[0]; upr_y_ave[ len] += lattice->upr[ k*get_LX(lattice)+i].u[1]; } #endif /* (STORE_U_COMPOSITE) */ wid++; } } rho_ave[ len] /= wid; u_x_ave[ len] /= wid; u_y_ave[ len] /= wid; #if STORE_U_COMPOSITE if(subs==0) { upr_x_ave[ len] /= wid; upr_y_ave[ len] /= wid; } #endif /* (STORE_U_COMPOSITE) */ } else { rho_slice[ len] = 0.; rho_ave[ len] = 0.; u_x_slice[ len] = 0.; u_x_ave[ len] = 0.; u_y_slice[ len] = 0.; u_y_ave[ len] = 0.; #if STORE_U_COMPOSITE if(subs==0) { upr_x_slice[ len] = 0.; upr_x_ave[ len] = 0.; upr_y_slice[ len] = 0.; upr_y_ave[ len] = 0.; } #endif /* (STORE_U_COMPOSITE) */ } len++; } } } fprintf( o, "rho_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", rho_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "rho_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", rho_ave[ n]); } fprintf( o, "];\n"); fprintf( o, "u_x_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_x_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "u_x_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_x_ave[ n]); } fprintf( o, "];\n"); fprintf( o, "u_y_slice%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_y_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "u_y_ave%02d = [ ", subs); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", u_y_ave[ n]); } fprintf( o, "];\n"); #if STORE_U_COMPOSITE if(subs==0) { fprintf( o, "upr_x_slice= [ "); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", upr_x_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "upr_x_ave= [ "); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", upr_x_ave[ n]); } fprintf( o, "];\n"); fprintf( o, "upr_y_slice= [ "); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", upr_y_slice[ n]); } fprintf( o, "];\n"); fprintf( o, "upr_y_ave= [ "); for( n=0; n<len; n++) { fprintf( o, " %20.17f ", upr_y_ave[ n]); } fprintf( o, "];\n"); } #endif /* (STORE_U_COMPOSITE) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ } /* if( i0 == i1) else if( j0 == j1) else */ free( rho_slice); free( rho_ave ); free( u_x_slice); free( u_x_ave ); free( u_y_slice); free( u_y_ave ); #if STORE_U_COMPOSITE if(subs==0) { free( upr_x_slice); free( upr_x_ave ); free( upr_y_slice); free( upr_y_ave ); } #endif /* (STORE_U_COMPOSITE) */ fprintf( o, "if( plot_stuff>0)\n"); if( make_octave_scripts(lattice)) { fprintf( o, "\nif(plot_stuff==1)\n"); // Plot density. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( rho_slice%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "title('\\rho slice (%d,%d)..(%d,%d)');", i0, j0, i1, j1); fprintf( o, "hold off;"); fprintf( o, "\n"); // Plot x velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( u_x_slice%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "title('u_x slice (%d,%d)..(%d,%d)');", i0, j0, i1, j1); fprintf( o, "hold off;"); fprintf( o, "\n"); // Plot y velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( u_y_slice%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "title('u_y slice (%d,%d)..(%d,%d)');", i0, j0, i1, j1); fprintf( o, "hold off;"); fprintf( o, "\n"); fprintf( o, "\nelse\n"); // Plot density. for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( rho_slice%02d, %s);", subs, plot_specs[subs]); fprintf( o, "title('\\rho slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); } // Plot x velocity. for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( u_x_slice%02d, %s);", subs, plot_specs[subs]); fprintf( o, "title('u_x slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); } // Plot y velocity. for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( u_y_slice%02d, %s);", subs, plot_specs[subs]); fprintf( o, "title('u_y slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); } fprintf( o, "\nend\n"); } /* if( make_octave_scripts(lattice)) */ else // make Matlab scripts { // Plot density. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( rho_slice%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "warning off;"); fprintf( o, "title('\\rho slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( rho_slice%02d, %s);", subs, plot_specs[subs]); fprintf( o, "warning off;"); fprintf( o, "title('\\rho slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); fprintf( o, "warning on;"); } // Plot average density. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( rho_ave%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "warning off;"); fprintf( o, "title('\\rho_{ave} slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( rho_ave%02d, %s);", subs, plot_specs[subs]); fprintf( o, "warning off;"); fprintf( o, "title('\\rho_{ave} slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); fprintf( o, "warning on;"); } // Plot x velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( u_x_slice%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "warning off;"); fprintf( o, "title('u_x slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( u_x_slice%02d, %s);", subs, plot_specs[subs]); fprintf( o, "warning off;"); fprintf( o, "title('u_x slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); fprintf( o, "warning on;"); } // Plot average x-velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( u_x_ave%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "warning off;"); fprintf( o, "title('ux_{ave} slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( u_x_ave%02d, %s);", subs, plot_specs[subs]); fprintf( o, "warning off;"); fprintf( o, "title('ux_{ave} slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); fprintf( o, "warning on;"); } // Plot y velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( u_y_slice%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "warning off;"); fprintf( o, "title('u_y slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( u_y_slice%02d, %s);", subs, plot_specs[subs]); fprintf( o, "warning off;"); fprintf( o, "title('u_y slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); fprintf( o, "warning on;"); } // Plot average y-velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "plot( u_y_ave%02d, %s);", subs, plot_specs[subs]); } fprintf( o, "warning off;"); fprintf( o, "title('uy_{ave} slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "figure;"); fprintf( o, "plot( u_y_ave%02d, %s);", subs, plot_specs[subs]); fprintf( o, "warning off;"); fprintf( o, "title('uy_{ave} slice (%d,%d)..(%d,%d), subs %d');\n", i0, j0, i1, j1, subs); fprintf( o, "warning on;"); } #if STORE_U_COMPOSITE // Plot x velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); fprintf( o, "plot( upr_x_slice, %s);", plot_specs[0]); fprintf( o, "warning off;"); fprintf( o, "title('upr_x slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); fprintf( o, "figure;"); fprintf( o, "plot( upr_x_slice, %s);", plot_specs[0]); fprintf( o, "warning off;"); fprintf( o, "title('upr_x slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); // Plot average x-velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); fprintf( o, "plot( upr_x_ave, %s);", plot_specs[0]); fprintf( o, "warning off;"); fprintf( o, "title('uprx_{ave} slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); fprintf( o, "figure;"); fprintf( o, "plot( upr_x_ave, %s);", plot_specs[0]); fprintf( o, "warning off;"); fprintf( o, "title('uprx_{ave} slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); // Plot y velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); fprintf( o, "plot( upr_y_slice, %s);", plot_specs[0]); fprintf( o, "warning off;"); fprintf( o, "title('upr_y slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); fprintf( o, "figure;"); fprintf( o, "plot( upr_y_slice, %s);", plot_specs[0]); fprintf( o, "warning off;"); fprintf( o, "title('upr_y slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); // Plot average y-velocity. fprintf( o, "figure;"); fprintf( o, "hold on;"); fprintf( o, "plot( upr_y_ave, %s);", plot_specs[0]); fprintf( o, "warning off;"); fprintf( o, "title('upry_{ave} slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); fprintf( o, "figure;"); fprintf( o, "plot( upr_y_ave, %s);", plot_specs[0]); fprintf( o, "warning off;"); fprintf( o, "title('upry_{ave} slice (%d,%d)..(%d,%d)');\n", i0, j0, i1, j1); fprintf( o, "warning on;"); #endif /* (STORE_U_COMPOSITE) */ #if 1 // Compare with analytical poiseuille flow profile. for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { if( lattice->param.gval[subs][0] == 0 && lattice->param.gval[subs][1] != 0 ) { // Poiseuille in y direction. fprintf( o, "disp(sprintf('\\nPoiseuille in y direction:'));\n"); fprintf( o, "figure;\n"); fprintf( o, "i0 = %d;\n", i0); fprintf( o, "i1 = %d;\n", i1); fprintf( o, "disp(sprintf(' [ i0 i1] = [ %%d %%d]',i0,i1));\n"); fprintf( o, "%%XXX H = i1 - i0;%% + 1;\n"); fprintf( o, "H = i1 - i0 - 1; %% Assuming solids on both sides.\n"); fprintf( o, "disp(sprintf(' H = %%d', H));\n"); fprintf( o, "R = H/2;\n"); fprintf( o, "disp(sprintf(' R = H/2 = %%20.17f', R));\n"); fprintf( o, "tau = %20.17f;\n",lattice->param.tau[0]); fprintf( o, "nu = (1/3)*(tau-.5);\n"); fprintf( o, "disp(sprintf(' nu = %%20.17f', nu));\n"); compute_ave_rho( lattice, &ave_rho, subs); fprintf( o, "rho_ave = %20.17f;\n", ave_rho); fprintf( o, "disp(sprintf(' rho_ave = %%20.17f', rho_ave));\n"); //fprintf( o, "mu = nu*%20.17f;\n", ave_rho); //fprintf( o, "disp(sprintf(' mu = %%20.17f', mu));\n"); fprintf( o, "gvalval = %20.17f;\n", lattice->param.gval[subs][1]/lattice->param.tau[subs]); fprintf( o, "disp(sprintf(' gvalval = %%20.17f', gvalval));\n"); fprintf( o, "i = [i0:1:i1];\n" "ucalc = " "( gvalval / (2*nu)) * " "( R^2 - ( abs( i - (i1+i0)/2 ).^2));\n" ); fprintf( o, "disp(sprintf(' size(ucalc) = %%dx%%d\\n',size(ucalc,1),size(ucalc,2)));\n"); fprintf( o, "plot( i, ucalc, 'k');"); fprintf( o, "title('analytical Poiseuille profile');\n"); fprintf( o, "figure;\n"); fprintf( o, "hold on;\n"); fprintf( o, "plot( i, ucalc, 'k');\n"); fprintf( o, "plot( i, u_y_slice%02d, 'bo');\n", subs); fprintf( o, "title(sprintf('LB results overlaying analytical Poiseuille profile, norm(diff)=%%20.17f',norm(u_y_slice%02d-ucalc)));\n", subs); fprintf( o, "xlims = get(gca,'xlim'); dx = xlims(2)-xlims(1);"); fprintf( o, "ylims = get(gca,'ylim'); dy = ylims(2)-ylims(1);"); fprintf( o, "axis( [ xlims(1)-.05*dx xlims(2)+.05*dx ylims(1) ylims(2)]);"); fprintf( o, "hold off;\n"); } /* if( lattice->param.gval[subs][0] == 0 && lattice->param.gval... */ else if( lattice->param.gval[subs][1] == 0 && lattice->param.gval[subs][0] != 0 ) { // Poiseuille in x direction. fprintf( o, "disp(sprintf('\\nPoiseuille in x direction:'));\n"); fprintf( o, "figure;\n"); fprintf( o, "j0 = %d;\n", j0); fprintf( o, "j1 = %d;\n", j1); fprintf( o, "disp(sprintf(' [ j0 j1] = [ %%d %%d]',j0,j1));\n"); fprintf( o, "H = j1 - j0 - 1; %% Assuming solids on both sides.\n"); fprintf( o, "disp(sprintf(' H = %%d', H));\n"); fprintf( o, "R = H/2;\n"); fprintf( o, "disp(sprintf(' R = H/2 = %%20.17f', R));\n"); fprintf( o, "nu = 1/6;\n"); fprintf( o, "disp(sprintf(' nu = %%20.17f', nu));\n"); compute_ave_rho( lattice, &ave_rho, subs); fprintf( o, "rho_ave = %20.17f;\n", ave_rho); fprintf( o, "disp(sprintf(' rho_ave = %%20.17f', rho_ave));\n"); //fprintf( o, "mu = nu*%20.17f;\n", ave_rho); //fprintf( o, "disp(sprintf(' mu = %%20.17f', mu));\n"); fprintf( o, "gvalval = %20.17f;\n", lattice->param.gval[subs][0]/lattice->param.tau[subs]); fprintf( o, "disp(sprintf(' gvalval = %%20.17f', gvalval));\n"); fprintf( o, "j = [j0:1:j1];" "ucalc = " "( gvalval / (2*nu)) * " "( R^2 - ( abs( j - (j1+j0)/2 ).^2));\n" ); fprintf( o, "disp(sprintf(' size(ucalc) = %%dx%%d\\n'," "size(ucalc,1),size(ucalc,2)));\n"); fprintf( o, "plot( j, ucalc, 'k');"); fprintf( o, "title('analytical Poiseuille profile');\n"); fprintf( o, "figure;\n"); fprintf( o, "hold on;\n"); fprintf( o, "plot( j, ucalc, 'k');\n"); fprintf( o, "plot( u_x_slice%02d, 'bo');\n", subs); fprintf( o, "title(sprintf('LB results overlaying analytical Poiseuille profile, norm(diff)=%%20.17f',norm(u_x_slice%02d-ucalc)));\n", subs); fprintf( o, "xlims = get(gca,'xlim'); dx = xlims(2)-xlims(1);"); fprintf( o, "ylims = get(gca,'ylim'); dy = ylims(2)-ylims(1);"); fprintf( o, "axis( [ xlims(1) xlims(2) ylims(1)-.05*dy ylims(2)+.05*dy]);"); fprintf( o, "hold off;\n"); //printf( o, "figure;\n"); //fprintf( o, "plot( ucalc(j0+1:10:10*j1+1) - u_x_slice%02d, 'r');", subs); //fprintf( o, "title( 'ucalc - u_x_slice%02d');\n", subs); } /* if( lattice->param.gval[subs][0] == 0 && lattice->param.gval... */ // Slice key. (Shows where in the domain the slice cuts.) fprintf( o, "figure; plot( [ %d %d], [ %d %d], 'r-.');", i0, i1, j0, j1); fprintf( o, "axis equal;"); fprintf( o, "axis([ %d %d %d %d]);", 0, get_LX(lattice)-1, 0, get_LY(lattice)-1); fprintf( o, "title('Slice key.');\n"); #if VERBOSITY_LEVEL > 0 printf("private_slice() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #endif } fprintf( o, "end %% if(plot_stuff>0)\n"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( o, "disp(sprintf('q_x = %%f',rho_slice%02d*u_x_slice%02d'/max(size(rho_slice%02d))'));\n", subs, subs, subs); fprintf( o, "disp(sprintf('q_y = %%f',rho_slice%02d*u_y_slice%02d'/max(size(rho_slice%02d))'));\n", subs, subs, subs); } fclose(o); } /* void private_slice( lattice_ptr lattice, int i0, int j0, int i1, int j1) */ // }}} #if INAMURO_SIGMA_COMPONENT && STORE_BTC // dump_sigma_btc {{{ void dump_sigma_btc( lattice_ptr lattice) { FILE *o; char fn[1024]; int n; double D; int btc_spot, start_time; if( lattice->param.sigma_btc_rate <= 0 || lattice->FlowDir==0) { return; } btc_spot = (lattice->param.sigma_btc_spot >= 0) ? (lattice->param.sigma_btc_spot-0) : (((lattice->FlowDir==1)?(get_LX(lattice)):(get_LY(lattice)))-2-0); start_time = (lattice->param.sigma_start>0) ?(lattice->param.sigma_start) :(0); sprintf( fn, "%s/sigma_btc.m", get_out_path(lattice)); o = fopen( fn, "w+"); // Timesteps where measurements are taken. fprintf( o, "ts = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", lattice->param.sigma_btc[5*n+0]-start_time); } fprintf( o, "];\n"); // Break through curve at sigma_spot-1. fprintf( o, "btc01 = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", lattice->param.sigma_btc[5*n+1]); } fprintf( o, "];\n"); // Break through curve at sigma_spot. fprintf( o, "btc02 = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", lattice->param.sigma_btc[5*n+2]); } fprintf( o, "];\n"); // Break through curve at sigma_spot+1. fprintf( o, "btc03 = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", lattice->param.sigma_btc[5*n+3]); } fprintf( o, "];\n"); // Velocity at sigma_spot. fprintf( o, "btc_v = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", lattice->param.sigma_btc[5*n+4]); } fprintf( o, "];\n"); // Concentration gradient. fprintf( o, "dcdx = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", .5*( lattice->param.sigma_btc[5*n+3] - lattice->param.sigma_btc[5*n+1]) ); } fprintf( o, "];\n"); // C*v. fprintf( o, "Cv = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", //lattice->param.sigma_btc[4*n+1]*lattice->param.sigma_btc[4*n+3] ); ( lattice->param.sigma_btc[5*n+2]*lattice->param.sigma_btc[5*n+4]) ); } fprintf( o, "];\n"); // Cf = ( C*v - D*dcdx) / v. D = (1./3.)*(lattice->param.tau[1] - .5); fprintf( o, "Cf = [\n"); for( n=1; n<lattice->SizeBTC; n++) { fprintf( o, "%20.17f\n", ( ( lattice->param.sigma_btc[5*n+2]*lattice->param.sigma_btc[5*n+4]) - ( D)*.5*( lattice->param.sigma_btc[5*n+3] - lattice->param.sigma_btc[5*n+1]) ) / ( lattice->param.sigma_btc[5*n+4]) ); } fprintf( o, "];\n"); fprintf( o, "D = %20.17f;\n", D); fprintf( o, "disp(sprintf('D = %%20.17f',D));\n"); // Plot btc01. //fprintf( o, "figure; plot(btc01);\n"); //fprintf( o, "axis([ %d %d 0 max(max(btc01),%20.17f)])\n", // 1, lattice->SizeBTC+1, lattice->param.rho_sigma); //fprintf( o, "title('BTC at L=%d, t=%d:%d:%d');\n", // btc_spot-1, start_time, // lattice->param.sigma_btc_rate, // lattice->NumTimeSteps ); if( make_octave_scripts(lattice)) { fprintf( o, "figure(1);\n"); fprintf( o, "hold on; plot(btc01);\n"); } else { fprintf( o, "figure;\n"); // SubPlot btc0{1,2,3}. fprintf( o, "subplot(2,2,1);\n"); fprintf( o, "hold on; plot(btc01);\n"); fprintf( o, "hnd = get(gca,'Children');\n"); fprintf( o, "set( hnd(1), 'Color', [ .8 .8 .8]);\n"); } if( make_octave_scripts(lattice)) { fprintf( o, "hold on; plot(btc03);\n"); } else { fprintf( o, "hold on; plot(btc03);\n"); fprintf( o, "hnd = get(gca,'Children');\n"); fprintf( o, "set( hnd(1), 'Color', [ .8 .8 .8]);\n"); } if( make_octave_scripts(lattice)) { fprintf( o, "hold on; plot(btc02);\n"); } else { fprintf( o, "hold on; plot(btc02);\n"); fprintf( o, "set(gca,'Xlim',[ 0 size(btc02,1)])\n"); } //fprintf( o, "axis([ %d %d 0 max(max(btc02),%20.17f)])\n", // 1, lattice->SizeBTC+1, lattice->param.rho_sigma); fprintf( o, "title('BTC at L\\in\\{%d,%d,%d\\}, t=%d:%d:%d');\n", btc_spot-1, btc_spot, btc_spot+1, start_time, lattice->param.sigma_btc_rate, lattice->NumTimeSteps ); if( make_octave_scripts( lattice)){ return;} // Plot btc03. //fprintf( o, "figure; plot(btc03);\n"); //fprintf( o, "axis([ %d %d 0 max(max(btc03),%20.17f)])\n", // 1, lattice->SizeBTC+1, lattice->param.rho_sigma); //fprintf( o, "title('BTC at L=%d, t=%d:%d:%d');\n", // btc_spot+1, start_time, // lattice->param.sigma_btc_rate, // lattice->NumTimeSteps ); if( make_octave_scripts(lattice)) { fprintf( o, "figure(2);\n"); fprintf( o, "plot(Cv);\n"); } else { fprintf( o, "subplot(2,2,2);\n"); fprintf( o, "plot(Cv);\n"); fprintf( o, "set(gca,'Xlim',[ 0 size(btc02,1)]);\n"); } fprintf( o, "title('C*v at L=%d, t=%d:%d:%d');\n", btc_spot, start_time, lattice->param.sigma_btc_rate, lattice->NumTimeSteps ); if( make_octave_scripts(lattice)) { fprintf( o, "figure(3);\n"); fprintf( o, "plot(dcdx);\n"); } else { fprintf( o, "subplot(2,2,3);\n"); fprintf( o, "plot(dcdx);\n"); fprintf( o, "set(gca,'Xlim',[ 0 size(btc02,1)]);\n"); } fprintf( o, "title('dc/dx at L=%d, t=%d:%d:%d');\n", btc_spot, start_time, lattice->param.sigma_btc_rate, lattice->NumTimeSteps ); if( make_octave_scripts(lattice)) { fprintf( o, "figure(4);\n"); fprintf( o, "plot(Cf);\n"); } else { fprintf( o, "subplot(2,2,4);\n"); fprintf( o, "plot(Cf);\n"); fprintf( o, "set(gca,'Xlim',[ 0 size(btc02,1)]);\n"); } fprintf( o, "title('Cf=(C*v-D*(dC/dx))/v at L=%d, t=%d:%d:%d');\n", btc_spot, start_time, lattice->param.sigma_btc_rate, lattice->NumTimeSteps ); if( make_octave_scripts(lattice)) { } else { // Give figure a name (shows up in title bar). fprintf( o, "set(gcf,'Name','Breakthrough curve data at t=%d:%d:%d');\n", start_time, lattice->param.sigma_btc_rate, lattice->NumTimeSteps ); } // Plot [Cr(x),'r'][Cr(x-dx),'m'][Cv(x),'g'][Cf(x),'b'] fprintf( o, "figure;\n"); fprintf( o, "hold on;\n"); fprintf( o, "plot( btc02, 'rx');\n"); fprintf( o, "plot(Cf, 'bo');\n"); fprintf( o, "hold off;\n"); if( make_octave_scripts(lattice)) { } else { fprintf( o, "set(gca,'Xlim',[ 0 size(btc02,1)]);\n"); } fprintf( o, "title('Cr=''rx'', Cf=''bo''');\n"); if( make_octave_scripts(lattice)) { } else { // Give figure a name (shows up in title bar). fprintf( o, "set(gcf,'Name','Resident C_r and flux averaged C_f concentrations " "at t=%d:%d:%d');\n", start_time, lattice->param.sigma_btc_rate, lattice->NumTimeSteps ); // Turn off figure number in title bar. fprintf( o, "set(gcf,'NumberTitle','off');\n"); } fprintf( o, "%% FlowDir = %d;\n", lattice->FlowDir); fclose(o); printf("\nBTC (size=%d) stored in file \"%s\".\n", lattice->SizeBTC, fn); } /* void dump_sigma_btc( lattice_ptr lattice) */ // }}} #endif /* INAMURO_SIGMA_COMPONENT && STORE_BTC */ // C O U N T C O L O R M A P {{{ //############################################################################## //void count_colormap( int *num_colors) // // - Count colormap entries in file colormap.rgb . // void count_colormap( int *num_colors) { FILE *in; char filename[1024]; double r, g, b; // First, count the number of entries. sprintf( filename, "%s", "./in/colormap.rgb"); if( !( in = fopen( filename, "r+"))) { printf("%s %d >> Error opening file \"%s\" for reading. Exiting!\n", __FILE__,__LINE__,filename); process_exit(1); } *num_colors = 0; fscanf( in, "%lf %lf %lf", &r, &g, &b); while( !feof(in)) { (*num_colors)++; fscanf( in, "%lf %lf %lf", &r, &g, &b); } fclose(in); } /* void count_colormap( int *num_colors) */ // }}} // A L L O C A T E C O L O R M A P {{{ //############################################################################## //void allocate_colormap( double ***colormap, int *num_colors) // void allocate_colormap( double ***colormap, int num_colors) { int i; *colormap = (double**)malloc( num_colors*sizeof(double*)); for( i=0; i<num_colors; i++) { (*colormap)[i] = (double*)malloc( 3*sizeof(double)); } } /* void allocate_colormap( double ***colormap, int num_colors) */ // }}} // R E A D C O L O R M A P {{{ //############################################################################## //void read_colormap( double **colormap, int num_colors) // // - Read colormap from file colormap.rgb . // // - Color map values are stored with one set of rgb values per line. // // - RGB values are stored between 0 and 1 . // // - Colormap values could come from Matlab, e.g. // // >> cm = colormap; // >> save 'colormap.rgb' cm -ascii; // void read_colormap( double **colormap, int num_colors) { FILE *in; char filename[1024]; double r, g, b; int n; sprintf( filename, "%s", "./in/colormap.rgb"); if( !( in = fopen( filename, "r+"))) { printf("%s %d >> Error opening file \"%s\" for reading. Exiting!\n", __FILE__,__LINE__,filename); process_exit(1); } n = 0; fscanf( in, "%lf %lf %lf", &r, &g, &b); while( !feof(in)) { assert( n!=num_colors); colormap[n][0] = r; colormap[n][1] = g; colormap[n][2] = b; n++; fscanf( in, "%lf %lf %lf", &r, &g, &b); } fclose(in); } /* void read_colormap( double **colormap, int num_colors) */ // }}} // D E A L L O C A T E C O L O R M A P {{{ //############################################################################## //void deallocate_colormap( double ***colormap, int num_colors) // void deallocate_colormap( double ***colormap, int num_colors) { int i; for( i=0; i<num_colors; i++) { free( (*colormap)[i]); } free( *colormap); } /* void deallocate_colormap( double ***colormap, int num_colors) */ // }}} // get_color {{{ void get_color( double **colormap, int num_colors, double c, char *r, char *g, char *b) { int n; double n1, n2; double w1, w2; if( c>=0. && c<=1.) { #if 1 n = (int)ROUND( c*((double)num_colors-1.)); // printf("get_color() -- c = %f, num_colors = %d, n = %d\n", c, num_colors, n); *r = (char)ROUND(255.*colormap[ n][0]); *g = (char)ROUND(255.*colormap[ n][1]); *b = (char)ROUND(255.*colormap[ n][2]); // printf("get_color() -- n = %d, (%f,%f,%f)\n", n, (double)*r, (double)*g, (double)*b); #else n1 = floor( c*((double)num_colors-1.)); n2 = ceil( c*((double)num_colors-1.)); w1 = c-n1; w2 = n2-c; *r = (char)ROUND(255.* ( w1*colormap[ (int)n1][0] + w2*colormap[ (int)n2][0])); *g = (char)ROUND(255.* ( w1*colormap[ (int)n1][1] + w2*colormap[ (int)n2][1])); *b = (char)ROUND(255.* ( w1*colormap[ (int)n1][2] + w2*colormap[ (int)n2][2])); #endif } else { *r = (char)(255.); *g = (char)(255.); *b = (char)(255.); } } /* void get_color( double **colormap, int num_colors, double c, ... */ // }}} #if WRITE_CHEN_DAT_FILES // chen_output {{{ void chen_output( lattice_ptr lattice) { int x, y; int LX = get_LX(lattice), LY = get_LY(lattice); double *u, *rho[NUM_FLUID_COMPONENTS]; double ux_sum, uy_sum, rho_in, rho_out; FILE *app7, *app8, *app9; char filename[1024]; double sum_mass[NUM_FLUID_COMPONENTS]; int subs; printf("\n\nWARNING: chen_output() function is deprecated!\n\n"); ux_sum = 0.; uy_sum = 0.; for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { sum_mass[ subs] = 0.; } sprintf( filename, "%s", "%s/chen_xyrho.dat", get_out_path(lattice)); if( !( app7 = fopen( filename,"a"))) { printf("Error opening \"%s\" for reading. Exiting!\n", filename); process_exit(1); } sprintf( filename, "%s", "%s/chen_xy_ux_uy.dat", get_out_path(lattice)); if( !( app8 = fopen( filename,"a"))) { printf("Error opening \"%s\" for reading. Exiting!\n", filename); process_exit(1); } sprintf( filename, "%s", "%s/chen_time.dat", get_out_path(lattice)); if( !( app9 = fopen( filename,"a"))) { printf("Error opening \"%s\" for reading. Exiting!\n", filename); process_exit(1); } #if STORE_U_COMPOSITE u = lattice->upr[0].u; #else /* !( STORE_U_COMPOSITE) */ u = lattice->macro_vars[0][0].u; #endif /* STORE_U_COMPOSITE */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { rho[subs] = &( lattice->macro_vars[subs][0].rho); } for( y = 0; y < LY; y++) { for( x = 0; x < LX; x++) { fprintf( app8, " %9.1f %9.1f %13.5e %13.5e\n", (double)(x+1.), (double)(y+1.), *u, *(u+1)); if( !( lattice->bc[0][ y*LX + x].bc_type & BC_SOLID_NODE)) { ux_sum = ux_sum + *u; uy_sum = uy_sum + *(u+1); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { sum_mass[subs] = sum_mass[subs] + *rho[subs]; } } /* if( !obst[y][x]) */ #if STORE_U_COMPOSITE u+=2; #else /* !( STORE_U_COMPOSITE) */ u+=3; #endif /* STORE_U_COMPOSITE */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { rho[subs]+=3; } } /* for( x = 1; x <= LX; x++) */ } /* for( y = 1; y <= LY; y++) */ fprintf( app9, "%10d %15.7f %15.7f ", lattice->time, ux_sum, uy_sum); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( app9, "%15.7f ", sum_mass[subs]); } fprintf( app9, "\n"); for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { rho[subs] = &( lattice->macro_vars[subs][0].rho); } for( y = 0; y < LY; y++) { for( x = 0; x < LX; x++) { if( !( lattice->bc[0][ y*LX + x].bc_type & BC_SOLID_NODE)) { for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( app7, "%f ", *rho[subs]); } fprintf( app7, "\n"); } else { for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { fprintf( app7, "%f ", 0.); } fprintf( app7, "\n"); } for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { rho[subs]+=3; } } /* for( x = 1; x <= LX; x++) */ } /* for( y = 1; y <= LY; y++) */ fclose( app7); fclose( app8); fclose( app9); #if VERBOSITY_LEVEL > 0 sprintf( filename, "%s", "%s/chen_xyrho.dat", get_out_path(lattice)); printf("chen_output() -- Wrote file \"%s\".\n", filename); sprintf( filename, "%s", "%s/chen_xy_ux_uy.dat", get_out_path(lattice)); printf("chen_output() -- Wrote file \"%s\".\n", filename); sprintf( filename, "%s", "%s/chen_time.dat", get_out_path(lattice)); printf("chen_output() -- Wrote file \"%s\".\n", filename); #endif /* VERBOSITY_LEVEL > 0 */ } /* void chen_output( lattice_ptr lattice) */ // }}} #endif /* WRITE_CHEN_DAT_FILES */ // B M P R E A D H E A D E R {{{ //############################################################################## //void bmp_read_header( FILE *in) // void bmp_read_header( FILE *in, struct bitmap_info_header *bmih) { char filename[1024]; int i, j, n, m; int ei, ej; int pad, bytes_per_row; char k; char b, g, r; struct bitmap_file_header bmfh; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; int subs; // Read the headers. n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, in ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( bmih, sizeof(struct bitmap_info_header), 1, in ); int_ptr = (int*)bmih->biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } printf("%s %d >> biWidth = %d\n", __FILE__, __LINE__, *((int*)bmih->biWidth)); width_ptr = (int*)bmih->biWidth; height_ptr = (int*)bmih->biHeight; bitcount_ptr = (short int*)bmih->biBitCount; // Read the palette, if necessary. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, in ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; } /* void bmp_read_header( FILE *in) */ // }}} // B M P R E A D E N T R Y {{{ //############################################################################## //void bmp_read_entry( FILE *in, char *r, char *g, char *b) // // Reads an RGB value from file on 'in' with bmp info header 'bmih'. // The RGB values are returned in the 'r', 'g', and 'b' char* arguments. // // WARNING: As implemented, with the static 'n' counter, this mechanism // only supports reading from one BMP file at a time. Furthermore, if // reading is aborted before all entries are read, the counter will // not be reset and subsequent attempts to read BMP files will be // screwed up. // void bmp_read_entry( FILE *in, struct bitmap_info_header *bmih, char *r, char *g, char *b) { char filename[1024]; int i, j, m; static int n=0; int ei, ej; int pad, bytes_per_row; char k, p; struct bitmap_file_header bmfh; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; int subs; width_ptr = (int*)bmih->biWidth; height_ptr = (int*)bmih->biHeight; bitcount_ptr = (short int*)bmih->biBitCount; // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; switch(ENDIAN2(*bitcount_ptr)) { case 1: // Monochrome. printf("read_bcs() -- " "Support for Monochrome BMPs is pending. " "Exiting!\n"); process_exit(1); case 4: // 16 colors. printf("read_bcs() -- " "Support for 16 color BMPs is pending. " "Exiting!\n"); process_exit(1); case 8: // 256 colors. printf("read_bcs() -- " "Support for 256 color BMPs is pending. " "Exiting!\n"); process_exit(1); case 24: // 24-bit colors. if( !feof(in)) { n+=( k = fread( b, 1, 1, in ));} if( !feof(in)) { n+=( k = fread( g, 1, 1, in ));} if( !feof(in)) { n+=( k = fread( r, 1, 1, in ));} break; default: // 32-bit colors? printf("ERROR: Unhandled color depth, " "BitCount = %d. Exiting!\n", ENDIAN2(*bitcount_ptr)); process_exit(1); break; } /* switch(*(bmih->biBitCount)) */ if( (n%(bytes_per_row+pad)) == 3*(*width_ptr)) { // Read pad bytes first. for( i=1; i<=pad; i++) { if( !feof(in)) { n+=( k = fread( &p, 1, 1, in ));} } } if( feof(in)) { printf( "bmp_read_entry() -- ERROR:" "Attempt to read past the end of file. " "Exiting!\n"); process_exit(1); } // If all the entries have been read, reset the counter. if( n == (bytes_per_row+pad)*(*height_ptr) ) { n = 0; } } /* void bmp_read_entry( FILE *in, char *r, char *g, char *b) */ // }}} // B M P W R I T E H E A D E R {{{ //############################################################################## //void bmp_write_header( FILE *in) // void bmp_write_header( FILE *out, bmp_hdr_ptr bmp_hdr, int ni, int nj, int bits) { int bytes_per_row; int pad; int n; int *intptr; // Bytes per row of the bitmap. bytes_per_row = ((int)ceil((( ((double)(ni))*((double)(bits)) )/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; bmp_hdr->type[0]='B'; bmp_hdr->type[1]='M'; *(int*)(bmp_hdr->size) = ENDIAN4((int)(/*header*/54 + /*data*/(ni*bits + pad*8)*nj/8)); *(int*)(bmp_hdr->rsvd) = (int)0; *(int*)(bmp_hdr->dptr) = ENDIAN4((int)54); *(int*)(bmp_hdr->forty) = ENDIAN4((int)40); *(int*)(bmp_hdr->width) = ENDIAN4((int)ni); *(int*)(bmp_hdr->height) = ENDIAN4((int)nj); *(short int*)(bmp_hdr->planes) = ENDIAN2((short int)1); *(short int*)(bmp_hdr->depth) = ENDIAN2((short int)bits); *(int*)(bmp_hdr->zeros+0) = (int)0; *(int*)(bmp_hdr->zeros+4) = (int)0; *(int*)(bmp_hdr->zeros+8) = (int)0; *(int*)(bmp_hdr->zeros+12) = (int)0; *(int*)(bmp_hdr->zeros+16) = (int)0; *(int*)(bmp_hdr->zeros+20) = (int)0; printf("size = %d\n", ENDIAN4((int)bmp_hdr->size)); printf("sizeof(short int) = %d\n",sizeof(short int)); printf("sizeof(bmp_hdr) = %d\n",sizeof(struct bmp_hdr_struct)); printf("sizeof(test_struct) = %d\n",sizeof(struct test_struct)); n = fwrite( bmp_hdr, sizeof(struct bmp_hdr_struct), 1, out); #if 0 char filename[1024]; int i, j, n, m; int ei, ej; int pad, bytes_per_row; char k; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; int subs; // Read the headers. n = fread( &bmfh, sizeof(struct bitmap_file_header), 1, out ); if( strncmp(bmfh.bfType,"BM",2)) { printf("ERROR: Can't process this file type. Exiting!\n"); printf("\n"); process_exit(1); } n = fread( bmih, sizeof(struct bitmap_info_header), 1, out ); int_ptr = (int*)bmih->biCompression; if( *int_ptr != 0) { printf("ERROR: Can't handle compression. Exiting!\n"); printf("\n"); process_exit(1); } printf("%s %d >> biWidth = %d\n", __FILE__, __LINE__, *((int*)bmih->biWidth)); width_ptr = (int*)bmih->biWidth; height_ptr = (int*)bmih->biHeight; bitcount_ptr = (short int*)bmih->biBitCount; // Read the palette, if necessary. if( ENDIAN2(*bitcount_ptr) < 24) { n = (int)pow(2.,(double)ENDIAN2(*bitcount_ptr)); // Num palette entries. for( i=0; i<n; i++) { k = fread( &rgb, sizeof(struct rgb_quad), 1, out ); if( k!=1) { printf("Error reading palette entry %d. Exiting!\n", i); process_exit(1); } } } // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; #endif } /* void bmp_write_header( FILE *out) */ // }}} // B M P W R I T E E N T R Y {{{ //############################################################################## //void bmp_write_entry( FILE *in, char *r, char *g, char *b) // // Writes an RGB value to file on 'out' with bmp info header 'bmih'. // The RGB values are passed in the 'r', 'g', and 'b' char arguments. // // void bmp_write_entry( FILE *out, bmp_hdr_ptr bmp_hdr, int n, char r, char g, char b) { int bytes_per_row; int pad; int k; char z; int i; // Bytes per row of the bitmap. bytes_per_row = ((int)ceil((( ((double)*(bmp_hdr->width)) * ((double)*(bmp_hdr->depth)) )/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; k = fwrite( &b, 1, 1, out); printf("k %d, b %d\n", k, (int)b); k = fwrite( &g, 1, 1, out); printf("k %d, g %d\n", k, (int)g); k = fwrite( &r, 1, 1, out); printf("k %d, r %d\n", k, (int)r); // If end of row, add padding. if( (n+1)%(*(bmp_hdr->width)) == 0) { z = (char)0; for( i=1; i<=pad; i++) { k = fwrite( &z, 1, 1, out); printf("i %d, k %d, z %d\n", i, k, (int)z); } } #if 0 char filename[1024]; int i, j, m; static int n=0; int ei, ej; int pad, bytes_per_row; char k, p; struct bitmap_file_header bmfh; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; int subs; width_ptr = (int*)bmih->biWidth; height_ptr = (int*)bmih->biHeight; bitcount_ptr = (short int*)bmih->biBitCount; // Bytes per row of the bitmap. bytes_per_row = ((int)ceil(( (((double)(ENDIAN4(*width_ptr)))*((double)(ENDIAN2(*bitcount_ptr))))/8.))); // Bitmaps pad rows to preserve 4-byte boundaries. // The length of a row in the file will be bytes_per_row + pad . pad = ((4) - bytes_per_row%4)%4; switch(ENDIAN2(*bitcount_ptr)) { case 1: // Monochrome. printf("write_bcs() -- " "Support for Monochrome BMPs is pending. " "Exiting!\n"); process_exit(1); case 4: // 16 colors. printf("write_bcs() -- " "Support for 16 color BMPs is pending. " "Exiting!\n"); process_exit(1); case 8: // 256 colors. printf("write_bcs() -- " "Support for 256 color BMPs is pending. " "Exiting!\n"); process_exit(1); case 24: // 24-bit colors. if( !feof(out)) { n+=( k = fread( b, 1, 1, out ));} if( !feof(out)) { n+=( k = fread( g, 1, 1, out ));} if( !feof(out)) { n+=( k = fread( r, 1, 1, out ));} break; default: // 32-bit colors? printf("ERROR: Unhandled color depth, " "BitCount = %d. Exiting!\n", ENDIAN2(*bitcount_ptr)); process_exit(1); break; } /* switch(*(bmih->biBitCount)) */ if( (n%(bytes_per_row+pad)) == 3*(*width_ptr)) { // Read pad bytes first. for( i=1; i<=pad; i++) { if( !feof(out)) { n+=( k = fread( &p, 1, 1, out ));} } } if( feof(out)) { printf( "bmp_write_entry() -- ERROR:" "Attempt to write past the end of file. " "Exiting!\n"); process_exit(1); } // If all the entries have been write, reset the counter. if( n == (bytes_per_row+pad)*(*height_ptr) ) { n = 0; } #endif } /* void bmp_write_entry( FILE *out, char *r, char *g, char *b) */ // }}} // report_open {{{ void report_open( report_ptr report, char *name) { sprintf( report->name, "%s.txt", name); #if VERBOSITY_LEVEL >=1 printf( "\n"); printf( "%s\n", HRULE1); printf( " R E P O R T\n"); printf( "%s\n", HRULE1); printf( "\n"); #endif /* VERBOSITY_LEVEL > 1 */ if( !( report->file = fopen( report->name, "w+"))) { printf("%s %d: ERROR: fopen( %s, \"w+\") = %x\n", __FILE__, __LINE__, report->name, (report->file)); } else { fprintf( report->file, "\n"); fprintf( report->file, "%s\n", HRULE1); fprintf( report->file, " R E P O R T\n"); fprintf( report->file, "%s\n", HRULE1); fprintf( report->file, "\n"); } } /* void report_open( report_ptr report, char *name) */ // }}} // report_close {{{ void report_close( report_ptr report) { #if VERBOSITY_LEVEL >=1 printf( "%s\n", HRULE1); printf( "\n"); #endif /* VERBOSITY_LEVEL >=1 */ if( report->file) { //fprintf( report->file, ""); fprintf( report->file, "\n"); fclose( report->file); #if VERBOSITY_LEVEL >=1 printf( "See file \"%s\".\n", report->name); #endif /* VERBOSITY_LEVEL >=1 */ } /* if( report->file) */ } /* void report_close( report_ptr report) */ // }}} // report_entry {{{ void report_entry( report_ptr report, char *entry_left, char *entry_right) { char dots[80]; const int left_col_width = 50; int n; // Fill with dots between columns. Careful if length of left // entry is too long. if( left_col_width > strlen(entry_left) + 2) { dots[ 0] = ' '; for( n=1; n<left_col_width-strlen(entry_left); n++) { dots[n]='.'; } dots[ n ] = ' '; dots[ n+1] = '\x0'; } else if( left_col_width > strlen(entry_left)) { dots[ 0] = ' '; dots[ left_col_width-strlen(entry_left)-1] = ' '; dots[ left_col_width-strlen(entry_left) ] = ' '; dots[ left_col_width-strlen(entry_left)+1] = '\x0'; } else { dots[0] = ' '; dots[1] = '\x0'; } #if VERBOSITY_LEVEL >=1 printf(" %s%s%s\n", entry_left, dots, entry_right); //printf("\n"); #endif /* VERBOSITY_LEVEL >=1 */ if( report->file) { fprintf( report->file, " %s%s%s\n", entry_left, dots, entry_right); //fprintf( report->file, "\n"); } } /* void report_entry( char *entry_left, char *entry_right) */ // }}} // report_integer_entry {{{ void report_integer_entry( report_ptr report, char *label, int value, char *units) { char entry[1024]; sprintf( entry, "%d %s", value, units); report_entry( report, label, entry); } /* void report_integer_entry( char *label, int value, char *units) */ // }}} // report_ratio_entry {{{ void report_ratio_entry( report_ptr report, char *label, double num, double den, char *units) { char entry[1024]; if( den!=0) { sprintf( entry, "%f %s", num/den, units); } else { sprintf( entry, "UNDEF %s", units); } report_entry( report, label, entry); } /* void report_integer_entry( char *label, int value, char *units) */ // }}} // report_partition {{{ void report_partition( report_ptr report) { printf( "%s\n", HRULE0); printf( "\n"); if( report->file) { fprintf( report->file, "%s\n", HRULE0); fprintf( report->file, "\n"); } } /* void report_partition( report_ptr report) */ // }}} //############################################################################## // vim: foldmethod=marker:foldlevel=0
111pjb-one
src/lbio.c
C
gpl3
220,422
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // lbio.h // // - Header file for IO stuff. // // - Mainly, a structure containing paths to input and output files // and routines for reading these paths from a file or command line // or environment variables... // // - This stuff is in the global scope, included from lb2d_prime.h. // struct io_struct { char *in_path; char *out_path; char *subs00_path; char *subs01_path; }; typedef struct io_struct *io_ptr; //
111pjb-one
src/lbio.h
C
gpl3
577
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // ic_flags.h // // - IC preprocessor flags for lb2d_prime. // #ifndef IC_FLAGS_H #define IC_FLAGS_H // IC_* flags are for initial conditions. Used in switch statement in // init_problem() in latmat.c . Set the initial_condition parameter // in params.in . #define IC_UNIFORM_RHO_A 1 #define IC_UNIFORM_RHO_B 2 #define IC_UNIFORM_RHO_IN 3 #define IC_BUBBLE 4 #define IC_DIAGONAL 5 #define IC_2X2_CHECKERS 6 #define IC_STATIC 7 #define IC_RECTANGLE 8 #define IC_DOT 9 #define IC_WOLF_GLADROW_DIFFUSION 10 #define IC_YIN_YANG 11 #define IC_HYDROSTATIC 12 #define IC_READ_FROM_FILE 99 #endif /* IC_FLAGS_H */
111pjb-one
src/ic_flags.h
C
gpl3
901
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // forward_declarations.h // // - Forward declarations of routines for lb_prime. // #ifndef FORWARD_DECLARATIONS_H #define FORWARD_DECLARATIONS_H struct lattice_struct; typedef struct lattice_struct *lattice_ptr; struct bitmap_file_header; struct bitmap_info_header; struct bmp_hdr_struct; typedef struct bmp_hdr_struct *bmp_hdr_ptr; struct rgb_quad; struct report_struct; typedef struct report_struct *report_ptr; void dump_frame_summary( struct lattice_struct *lattice); void dump_macro_vars( struct lattice_struct *lattice, int time); void collide( struct lattice_struct *lattice); void compute_macro_vars( struct lattice_struct *lattice, int which_f); void compute_feq( struct lattice_struct *lattice, int skip_sigma); void compute_max_rho( lattice_ptr lattice, double *max_rho, int subs); void compute_max_u( lattice_ptr lattice, double *max_u, int subs); void compute_ave_u( lattice_ptr lattice, double *max_u, int subs); void compute_ave_upr( lattice_ptr lattice, double *max_u); void compute_ave_rho( lattice_ptr lattice, double *ave_rho, int subs); void process_matrix( struct lattice_struct *lattice, int **matrix, int subs); void process_bcs( lattice_ptr lattice, int subs); void read_params( lattice_ptr lattice, const char *infile); void construct_lattice( lattice_ptr *lattice, int argc, char **argv); void init_problem( struct lattice_struct *lattice); void destruct_lattice( struct lattice_struct *lattice); void init_problem( struct lattice_struct *lattice); void destruct_lattice( struct lattice_struct *lattice); void dump_macro_vars( struct lattice_struct *lattice, int time); void dump_pdf( struct lattice_struct *lattice, int time); void dump_lattice_info( struct lattice_struct *lattice); #if DO_NOT_STORE_SOLIDS void dump_node_info( struct lattice_struct *lattice); #endif /* DO_NOT_STORE_SOLIDS */ void dump_checkpoint( struct lattice_struct *lattice, int time, char *fn); void read_checkpoint( struct lattice_struct *lattice); void stream( struct lattice_struct *lattice); void slice( lattice_ptr lattice); void private_slice( lattice_ptr lattice, char *root_word, int i0, int j0, int i1, int j1); #if NON_LOCAL_FORCES void compute_phase_force( lattice_ptr lattice, int subs); void compute_fluid_fluid_force( lattice_ptr lattice); void compute_double_fluid_solid_force( lattice_ptr lattice); void compute_single_fluid_solid_force( lattice_ptr lattice, int subs); void dump_forces( struct lattice_struct *lattice); void force2bmp( lattice_ptr lattice); void sforce2bmp( lattice_ptr lattice); #endif /* NON_LOCAL_FORCES */ void rho2bmp( lattice_ptr lattice, int time); void u2bmp( lattice_ptr lattice, int time); void vor2bmp( lattice_ptr lattice, int time); void count_colormap( int *num_colors); void allocate_colormap( double ***colormap, int num_colors); void read_colormap( double **colormap, int num_colors); void deallocate_colormap( double ***colormap, int num_colors); void get_color( double **colormap, int num_colors, double c, char *r, char *g, char *b); #if WRITE_CHEN_DAT_FILES void chen_output( lattice_ptr lattice); #endif /* WRITE_CHEN_DAT_FILES */ #if MANAGE_BODY_FORCE inline void manage_body_force( lattice_ptr lattice); #endif /* MANAGE_BODY_FORCE */ #if INAMURO_SIGMA_COMPONENT && STORE_BTC void sigma_stuff( lattice_ptr lattice); #endif /* INAMURO_SIGMA_COMPONENT && STORE_BTC */ int do_check_point_save( lattice_ptr lattice); int do_check_point_load( lattice_ptr lattice); void bmp_read_header( FILE *in, struct bitmap_info_header *bmih); void bmp_read_entry( FILE *in, struct bitmap_info_header *bmih, char *r, char *g, char *b); void bmp_write_header( FILE *out, bmp_hdr_ptr bmp_hdr, int ni, int nj, int bits); void bmp_write_entry( FILE *out, bmp_hdr_ptr bmp_hdr, int n, char r, char g, char b); void report_open( report_ptr report, char *name); void report_integer_entry( report_ptr report, char *label, int value, char *units); void report_ratio_entry( report_ptr report, char *label, double num, double den, char *units); void report_entry( report_ptr report, char *entry_left, char *entry_right); void report_close( report_ptr report); void report_partition( report_ptr report); int get_sizeof_lattice_structure( lattice_ptr lattice); int get_sizeof_lattice( lattice_ptr lattice); int get_num_active_nodes( lattice_ptr lattice); inline void run_man( lattice_ptr lattice); inline void dump( lattice_ptr lattice, int tick_num); //LBMPI #ifdef PARALLEL //LBMPI struct lbmpi_struct; //LBMPI typedef struct lbmpi_struct *lbmpi_ptr; //LBMPI void lbmpi_construct( lbmpi_ptr lbmpi, lattice_ptr lattice, int argc, char **argv); //LBMPI void lbmpi_allocate_datatypes( lbmpi_ptr lbmpi, lattice_ptr lattice); //LBMPI MPI_Aint *lbmpi_get_Index0_ptr( lbmpi_ptr lbmpi); //LBMPI #endif /* (PARALLEL) */ #endif /* FORWARD_DECLARATIONS_H */
111pjb-one
src/forward_declarations.h
C
gpl3
4,996
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // bcs.c // // - Boundary conditions. // // - void bcs( lattice_ptr lattice); // // - void process_bcs( char *filename, int **bcs); // #define RHO0_TEST 0 #if 0 // {{{ // B C S {{{ void bcs( lattice_ptr lattice) { int n; int subs; int *bc; double *ftemp; double u_x, u_y, rho; for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { bc = &( lattice->bc[subs][0].bc_type); ftemp = lattice->pdf[subs][0].ftemp; for( n=0; n<lattice->NumNodes; n++) { if( *bc != BC_FLUID_NODE && *bc != ( BC_FLUID_NODE | BC_FILM_NODE) && *bc != BC_SOLID_NODE) { if( *bc & BC_PRESSURE_N_IN ) { // North, Inflow //printf("bcs() -- North, Inflow at n = %d, ( %d, %d)\n", // n, lattice->node[n].i, lattice->node[n].j); //printf(" Before>> %f %f %f %f [%f] %f %f [%f] [%f]\n", // ftemp[0], ftemp[1], ftemp[2], // ftemp[3], ftemp[4], ftemp[5], // ftemp[6], ftemp[7], ftemp[8] ); u_y = -1. + ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])) / lattice->param.rho_in; ftemp[4] = ftemp[2] - (2./3.)*lattice->param.rho_in*u_y; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[1] - ftemp[3]) - (1./6.)*lattice->param.rho_in*u_y; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[3] - ftemp[1]) - (1./6.)*lattice->param.rho_in*u_y; //printf(" Before>> %f %f %f %f [%f] %f %f [%f] [%f]\n", // ftemp[0], ftemp[1], ftemp[2], // ftemp[3], ftemp[4], ftemp[5], // ftemp[6], ftemp[7], ftemp[8] ); } /* if( *bc & BC_PRESSURE_N_IN ) */ if( *bc & BC_PRESSURE_S_IN ) { printf("bcs() -- ERROR: Support for South, Inflow pressure " "boundaries is pending. (Exiting!)"); process_exit(1); } if( *bc & BC_PRESSURE_E_IN ) { printf("bcs() -- ERROR: Support for East, Inflow pressure " "boundaries is pending. (Exiting!)"); process_exit(1); } if( *bc & BC_PRESSURE_W_IN ) { printf("bcs() -- ERROR: Support for West, Inflow pressure " "boundaries is pending. (Exiting!)"); process_exit(1); } if( *bc & BC_PRESSURE_N_OUT) { printf("bcs() -- ERROR: Support for North, Outflow pressure " "boundaries is pending. (Exiting!)"); process_exit(1); } if( *bc & BC_PRESSURE_S_OUT) { // South, Outflow //printf("bcs() -- South, Outflow at n = %d, ( %d, %d)\n", // n, lattice->node[n].i, lattice->node[n].j); //printf(" Before>> %f %f [%f] %f %f [%f] [%f] %f %f\n", // ftemp[0], ftemp[1], ftemp[2], // ftemp[3], ftemp[4], ftemp[5], // ftemp[6], ftemp[7], ftemp[8] ); u_y = 1. - ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])) / lattice->param.rho_out; ftemp[2] = ftemp[4] + (2./3.)*lattice->param.rho_out*u_y; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[3] - ftemp[1]) + (1./6.)*lattice->param.rho_out*u_y; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[1] - ftemp[3]) + (1./6.)*lattice->param.rho_out*u_y; //printf(" Before>> %f %f [%f] %f %f [%f] [%f] %f %f\n", // ftemp[0], ftemp[1], ftemp[2], // ftemp[3], ftemp[4], ftemp[5], // ftemp[6], ftemp[7], ftemp[8] ); } /* if( *bc & BC_PRESSURE_S_OUT) */ if( *bc & BC_PRESSURE_E_OUT) { printf("bcs() -- ERROR: Support for East, Outflow pressure " "boundaries is pending. (Exiting!)"); process_exit(1); } if( *bc & BC_PRESSURE_W_OUT) { printf("bcs() -- ERROR: Support for West, Outflow pressure " "boundaries is pending. (Exiting!)"); process_exit(1); } } /* if( *bc != 0 && *bc != BC_SOLID_NODE) */ ftemp+=27; bc++; } /* for( n=0; n<lattice->NumNodes; n++) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ } /* void bcs( lattice_ptr lattice) */ // }}} #else //}}} #if 0 // {{{ // B C S {{{ void bcs( lattice_ptr lattice) { int i, j, n; int subs; int *bc; double *ftemp, *ftemp_end, *ftemp_mid; double u_x, u_y; double u_in[2][2], u_out[2][2], u, rho; #if 0 u_in[0][0] = lattice->param.uy_in; u_in[1][0] = lattice->param.uy_in; u_in[0][1] = -lattice->param.uy_in; u_in[1][1] = -lattice->param.uy_in; u_out[0][0] = lattice->param.uy_out; u_out[1][0] = lattice->param.uy_out; u_out[0][1] = -lattice->param.uy_out; u_out[1][1] = -lattice->param.uy_out; #else u_in[0][0] = 0.; u_in[1][0] = lattice->param.uy_in; u_in[0][1] = -lattice->param.uy_in; u_in[1][1] = 0.; u_out[0][0] = lattice->param.uy_out; u_out[1][0] = 0.; u_out[0][1] = 0.; u_out[1][1] = -lattice->param.uy_out; #endif for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { #if 0 bc = &( lattice->bc[subs][0].bc_type); ftemp = lattice->pdf[subs][0].ftemp; for( n=0; n<lattice->NumNodes; n++) { if( *bc != BC_FLUID_NODE && *bc != ( BC_FLUID_NODE | BC_FILM_NODE) && *bc != BC_SOLID_NODE) { if( *bc & BC_PRESSURE_N_IN ) { // North, Inflow u_y = -1. + ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])) / lattice->param.rho_in; ftemp[4] = ftemp[2] - (2./3.)*lattice->param.rho_in*u_y; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[1] - ftemp[3]) - (1./6.)*lattice->param.rho_in*u_y; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[3] - ftemp[1]) - (1./6.)*lattice->param.rho_in*u_y; } /* if( *bc & BC_PRESSURE_N_IN ) */ if( *bc & BC_PRESSURE_S_IN ) { printf("bcs() -- ERROR: Support for South, Inflow pressure " "boundaries is pending. (Exiting!)"); process_exit(1); } if( *bc & BC_PRESSURE_E_IN ) { printf("bcs() -- ERROR: Support for East, Inflow pressure " "boundaries is pending. (Exiting!)"); process_exit(1); } if( *bc & BC_PRESSURE_W_IN ) { printf("bcs() -- ERROR: Support for West, Inflow pressure " "boundaries is pending. (Exiting!)"); process_exit(1); } if( *bc & BC_PRESSURE_N_OUT) { printf("bcs() -- ERROR: Support for North, Outflow pressure " "boundaries is pending. (Exiting!)"); process_exit(1); } if( *bc & BC_PRESSURE_S_OUT) { // South, Outflow u_y = 1. - ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])) / lattice->param.rho_out; ftemp[2] = ftemp[4] + (2./3.)*lattice->param.rho_out*u_y; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[3] - ftemp[1]) + (1./6.)*lattice->param.rho_out*u_y; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[1] - ftemp[3]) + (1./6.)*lattice->param.rho_out*u_y; } /* if( *bc & BC_PRESSURE_S_OUT) */ if( *bc & BC_PRESSURE_E_OUT) { printf("bcs() -- ERROR: Support for East, Outflow pressure " "boundaries is pending. (Exiting!)"); process_exit(1); } if( *bc & BC_PRESSURE_W_OUT) { printf("bcs() -- ERROR: Support for West, Outflow pressure " "boundaries is pending. (Exiting!)"); process_exit(1); } } /* if( *bc != 0 && *bc != BC_SOLID_NODE) */ ftemp+=27; bc++; } /* for( n=0; n<lattice->NumNodes; n++) */ #else // NOTE: Should previously (in initialization stage) have checked to // insure no solid nodes on inflow/outflow boundaries. Do not do it here // inside the loop! if( lattice->param.pressure_n_in[subs] ) { //printf("bcs() -- pressure_n_in[%d]\n", subs); ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; while( ftemp < ftemp_end) { // North, Inflow u_y = -1. + ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])) / lattice->param.rho_in; ftemp[4] = ftemp[2] - (2./3.)*lattice->param.rho_in*u_y; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[1] - ftemp[3]) - (1./6.)*lattice->param.rho_in*u_y; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[3] - ftemp[1]) - (1./6.)*lattice->param.rho_in*u_y; ftemp += ( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.pressure_n_in[subs] ) */ if( lattice->param.pressure_s_in[subs] ) { } if( lattice->param.pressure_n_out[subs]) { } if( lattice->param.pressure_s_out[subs]) { //printf("bcs() -- pressure_s_out[%d]\n", subs); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][lattice->param.LX].ftemp; while( ftemp < ftemp_end) { u_y = 1. - ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])) / lattice->param.rho_out; ftemp[2] = ftemp[4] + (2./3.)*lattice->param.rho_out*u_y; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[3] - ftemp[1]) + (1./6.)*lattice->param.rho_out*u_y; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[1] - ftemp[3]) + (1./6.)*lattice->param.rho_out*u_y; ftemp += ( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ } /* if( pressure_s_out[subs]) */ if( lattice->param.velocity_n_in[subs] ) { //printf("bcs() -- velocity_n_in[%d]\n", subs); ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp_mid = lattice->pdf[subs][lattice->NumNodes-7*lattice->param.LX/8].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; //u = ((subs==1)?(-1):(1))*lattice->param.uy_in; while( ftemp < ftemp_mid) { // North, Inflow //u = u_in[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; u = 0.; rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])) / ( 1. + u); ftemp[4] = ftemp[2] - (2./3.)*rho*u; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[1] - ftemp[3]) - (1./6.)*rho*u; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[3] - ftemp[1]) - (1./6.)*rho*u; ftemp += 27;//( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ ftemp_mid = lattice->pdf[subs][lattice->NumNodes-3*lattice->param.LX/4].ftemp; while( ftemp < ftemp_mid) { // North, Inflow //u = u_in[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; u = u_in[0][subs]; rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])) / ( 1. + u); ftemp[4] = ftemp[2] - (2./3.)*rho*u; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[1] - ftemp[3]) - (1./6.)*rho*u; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[3] - ftemp[1]) - (1./6.)*rho*u; ftemp += 27;//( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ ftemp_mid = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX/2].ftemp; while( ftemp < ftemp_mid) { // North, Inflow //u = u_in[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; u = 0.; rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])) / ( 1. + u); ftemp[4] = ftemp[2] - (2./3.)*rho*u; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[1] - ftemp[3]) - (1./6.)*rho*u; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[3] - ftemp[1]) - (1./6.)*rho*u; ftemp += 27;//( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ ftemp_mid = lattice->pdf[subs][lattice->NumNodes-3*lattice->param.LX/8].ftemp; while( ftemp < ftemp_mid) { // North, Inflow //u = u_in[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; u = u_in[1][subs]; rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])) / ( 1. + u); ftemp[4] = ftemp[2] - (2./3.)*rho*u; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[1] - ftemp[3]) - (1./6.)*rho*u; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[3] - ftemp[1]) - (1./6.)*rho*u; ftemp += 27;//( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ while( ftemp < ftemp_end) { // North, Inflow //u = u_in[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; u = 0.; rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])) / ( 1. + u); ftemp[4] = ftemp[2] - (2./3.)*rho*u; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[1] - ftemp[3]) - (1./6.)*rho*u; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[3] - ftemp[1]) - (1./6.)*rho*u; ftemp += 27;//( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ } if( lattice->param.velocity_s_in[subs] ) { } if( lattice->param.velocity_n_out[subs]) { } if( lattice->param.velocity_s_out[subs]) { //printf("bcs() -- velocity_s_out[%d]\n", subs); ftemp = lattice->pdf[subs][0].ftemp; ftemp_mid = lattice->pdf[subs][lattice->param.LX/8].ftemp; ftemp_end = lattice->pdf[subs][lattice->param.LX].ftemp; //u = ((subs==1)?(-1):(1))*lattice->param.uy_out; while( ftemp < ftemp_mid) { //u = u_out[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; u = 0.; rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])) / ( 1. - u); ftemp[2] = ftemp[4] + (2./3.)*rho*u; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[3] - ftemp[1]) + (1./6.)*rho*u; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[1] - ftemp[3]) + (1./6.)*rho*u; ftemp += 27;//( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ ftemp_mid = lattice->pdf[subs][lattice->param.LX/4].ftemp; while( ftemp < ftemp_mid) { //u = u_out[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; u = u_out[0][subs]; rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])) / ( 1. - u); ftemp[2] = ftemp[4] + (2./3.)*rho*u; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[3] - ftemp[1]) + (1./6.)*rho*u; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[1] - ftemp[3]) + (1./6.)*rho*u; ftemp += 27;//( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ ftemp_mid = lattice->pdf[subs][lattice->param.LX/2].ftemp; while( ftemp < ftemp_mid) { //u = u_out[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; u = 0.; rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])) / ( 1. - u); ftemp[2] = ftemp[4] + (2./3.)*rho*u; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[3] - ftemp[1]) + (1./6.)*rho*u; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[1] - ftemp[3]) + (1./6.)*rho*u; ftemp += 27;//( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ ftemp_mid = lattice->pdf[subs][5*lattice->param.LX/8].ftemp; while( ftemp < ftemp_mid) { //u = u_out[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; u = u_out[1][subs]; rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])) / ( 1. - u); ftemp[2] = ftemp[4] + (2./3.)*rho*u; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[3] - ftemp[1]) + (1./6.)*rho*u; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[1] - ftemp[3]) + (1./6.)*rho*u; ftemp += 27;//( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ while( ftemp < ftemp_end) { //u = u_out[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; u = 0.; rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])) / ( 1. - u); ftemp[2] = ftemp[4] + (2./3.)*rho*u; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[3] - ftemp[1]) + (1./6.)*rho*u; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[1] - ftemp[3]) + (1./6.)*rho*u; ftemp += 27;//( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.velocity_s_out[subs]) */ #endif } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ } /* void bcs( lattice_ptr lattice) */ // }}} #else // }}} // B C S {{{ //############################################################################## // void bcs( lattice_ptr lattice) // // B C S // // - Apply boundary conditions. // void bcs( lattice_ptr lattice) { int i, j, n, a; int subs; int *bc_type; double *ftemp, *ftemp_end, *ftemp_mid; double v; double c0; double D; double c2; #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- double *rho0; //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ double u_x, u_y; double u_in[2][2], u_out[2][2], u, rho; double c; int id; #if PARALLEL id = get_proc_id(lattice); #else id = get_num_procs(lattice)-1; #endif // NOTE: Should previously (in initialization stage) have checked to // insure no solid nodes on inflow/outflow boundaries. Do not do it here // inside the loop! for( subs=0; subs<(NUM_FLUID_COMPONENTS)-(INAMURO_SIGMA_COMPONENT); subs++) { // P R E S S U R E N O R T H I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // pressure north inflow // -- Pressure boundary on north side using inflow pressure condition. if( (id==get_num_procs(lattice)-1) && lattice->param.pressure_n_in[subs] ) { //printf("bcs() %s %d >> pressure_n_in[%d]\n", __FILE__, __LINE__, subs); if( lattice->param.pressure_n_in[subs]==2) { rho = *( pressure_n_in0( lattice, subs) + get_time(lattice)%num_pressure_n_in0(lattice,subs)); } else { rho = lattice->param.rho_in; } ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; while( ftemp < ftemp_end) { if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { // North, Inflow if( lattice->param.incompressible) { u_y = -rho + ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])); c = u_y; } else // compressible { u_y = -1. + ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])) / rho; c = u_y*rho; } ftemp[4] = ftemp[2] - (2./3.)*c; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[1] - ftemp[3]) - (1./6.)*c; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[3] - ftemp[1]) - (1./6.)*c; } ftemp += ( sizeof(struct pdf_struct)/sizeof(double)); } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.pressure_n_in[subs] ) */ // }}} // P R E S S U R E S O U T H I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // pressure south inflow // -- Pressure boundary on south side using inflow pressure condition. if( (id==0) && lattice->param.pressure_s_in[subs] ) { if( lattice->param.pressure_s_in[subs]==2) { rho = *( pressure_s_in0( lattice, subs) + get_time(lattice)%num_pressure_s_in0(lattice,subs)); } else { rho = lattice->param.rho_in; } //printf("bcs() %s %d >> pressure_s_in[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][lattice->param.LX].ftemp; while( ftemp < ftemp_end) { if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { // South, Inflow if( lattice->param.incompressible) { u_y = rho - ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])); c = u_y; } else // compressible { u_y = 1. - ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])) / rho; c = u_y*rho; } ftemp[2] = ftemp[4] + (2./3.)*c; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[3] - ftemp[1]) + (1./6.)*c; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[1] - ftemp[3]) + (1./6.)*c; } ftemp += ( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.pressure_s_in[subs] ) */ // }}} // P R E S S U R E N O R T H O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // pressure north outflow // -- Pressure boundary on north side using outflow pressure condition. if( (id==get_num_procs(lattice)-1) && lattice->param.pressure_n_out[subs]) { //printf("bcs() %s %d >> pressure_n_out[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; while( ftemp < ftemp_end) { if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { // North, Inflow if( lattice->param.incompressible) { u_y = -lattice->param.rho_out + ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])); c = u_y; } else // compressible { u_y = -1. + ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])) / lattice->param.rho_out; c = u_y*lattice->param.rho_out; } ftemp[4] = ftemp[2] - (2./3.)*c; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[1] - ftemp[3]) - (1./6.)*c; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[3] - ftemp[1]) - (1./6.)*c; } ftemp += ( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.pressure_n_out[subs]) */ // }}} // P R E S S U R E S O U T H O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // pressure south outflow // -- Pressure boundary on south side using outflow pressure condition. if( (id==0) && lattice->param.pressure_s_out[subs]) { //printf("bcs() %s %d >> pressure_s_out[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][lattice->param.LX].ftemp; while( ftemp < ftemp_end) { if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { // South, Outflow if( lattice->param.incompressible) { u_y = lattice->param.rho_out - ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])); c = u_y; } else // compressible { u_y = 1. - ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])) / lattice->param.rho_out; c = u_y*lattice->param.rho_out; } ftemp[2] = ftemp[4] + (2./3.)*c; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[3] - ftemp[1]) + (1./6.)*c; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[1] - ftemp[3]) + (1./6.)*c; } ftemp += ( sizeof(struct pdf_struct)/sizeof(double)); } /* while( ftemp < ftemp_end) */ } /* if( pressure_s_out[subs]) */ // }}} // V E L O C I T Y N O R T H I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // velocity north inflow // -- Velocity boundary on north side using inflow velocity condition. if( (id==get_num_procs(lattice)-1) && lattice->param.velocity_n_in[subs]) { //printf("bcs() %s %d >> velocity_n_in[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; bc_type = &( lattice->bc[subs][lattice->NumNodes-lattice->param.LX].bc_type); #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 = &( lattice->macro_vars[subs][lattice->NumNodes-lattice->param.LX].rho); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ //u = ((subs==1)?(-1):(1))*lattice->param.uy_in; if( lattice->param.bc_poiseuille) { i = 0; } else { u = lattice->param.uy_in; } while( ftemp < ftemp_end) { // North, Inflow if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { //u = u_in[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; //u = 0.; if( lattice->param.bc_poiseuille) { u = ( 1.5*( lattice->param.uy_in) /( .25*(lattice->param.LX-2)*(lattice->param.LX-2)) ) *( .25*( lattice->param.LX-2)*( lattice->param.LX-2) - (i-.5*( lattice->param.LX-2)-.5) *(i-.5*( lattice->param.LX-2)-.5) ) ; //printf("%s (%d) -- %d %f\n", __FILE__, __LINE__, i, u); i++; } if( lattice->param.incompressible) { rho = -u + ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])); c = u; } else // compressible { rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])) / ( 1. + u); c = rho*u; } ftemp[4] = ftemp[2] - (2./3.)*c; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[1] - ftemp[3]) - (1./6.)*c; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[3] - ftemp[1]) - (1./6.)*c; #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- ftemp[0] = *rho0 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8]); rho0 += ( sizeof(struct macro_vars_struct)/8); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8); } else { if( lattice->param.bc_poiseuille) { i++;} #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 += ( sizeof(struct macro_vars_struct)/8); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8); } bc_type++; } /* while( ftemp < ftemp_end) */ #if 0 if( lattice->param.bc_poiseuille) { // Fix corners ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp[4] = ( ftemp[27+4] + ftemp[-27*lattice->param.LX + 4]) /2; ftemp[8] = ( ftemp[27+8] + ftemp[-27*lattice->param.LX + 8]) /2; ftemp = lattice->pdf[subs][lattice->NumNodes-1].ftemp; ftemp[4] = ( ftemp[-27+4] + ftemp[-27*lattice->param.LX + 4]) /2; ftemp[7] = ( ftemp[-27+7] + ftemp[-27*lattice->param.LX + 7]) /2; } #endif } // }}} // V E L O C I T Y S O U T H I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // velocity south inflow // -- Velocity boundary on south side using inflow velocity condition. if( (id==0) && lattice->param.velocity_s_in[subs] ) { //printf("bcs() %s %d >> velocity_s_in[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][lattice->param.LX].ftemp; bc_type = &( lattice->bc[subs][0].bc_type); #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 = &( lattice->macro_vars[subs][0].rho); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ //u = ((subs==1)?(-1):(1))*lattice->param.uy_in; if( lattice->param.bc_poiseuille) { i = 0; } else { u = lattice->param.uy_in; } while( ftemp < ftemp_end) { // South, Inflow if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { //u = u_in[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; //u = 0.; if( lattice->param.bc_poiseuille) { u = ( 1.5*( lattice->param.uy_in) /( .25*(lattice->param.LX-2)*(lattice->param.LX-2)) ) *( .25*( lattice->param.LX-2)*( lattice->param.LX-2) - (i-.5*( lattice->param.LX-2)-.5) *(i-.5*( lattice->param.LX-2)-.5) ) ; i++; } if( lattice->param.incompressible) { rho = u + ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])); c = u; } else { rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])) / ( 1. - u); c = rho*u; } ftemp[2] = ftemp[4] + (2./3.)*c; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[3] - ftemp[1]) + (1./6.)*c; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[1] - ftemp[3]) + (1./6.)*c; #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- ftemp[0] = *rho0 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8]); rho0 += ( sizeof(struct macro_vars_struct)/8); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8); } else { if( lattice->param.bc_poiseuille) { i++;} #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 += ( sizeof(struct macro_vars_struct)/8); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8); } bc_type++; } /* while( ftemp < ftemp_end) */ #if 0 if( lattice->param.bc_poiseuille) { // Fix corners ftemp = lattice->pdf[subs][0].ftemp; ftemp[2] = ( ftemp[27+2] + ftemp[27*lattice->param.LX + 2]) /2; ftemp[5] = ( ftemp[27+5] + ftemp[27*lattice->param.LX + 5]) /2; ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp[2] = ( ftemp[-27+2] + ftemp[27*lattice->param.LX + 2]) /2; ftemp[6] = ( ftemp[-27+6] + ftemp[27*lattice->param.LX + 6]) /2; } #endif } // }}} // V E L O C I T Y N O R T H O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // velocity north outflow // -- Velocity boundary on north side using outflow velocity condition. if( (id==get_num_procs(lattice)-1) && lattice->param.velocity_n_out[subs]) { //printf("bcs() %s %d >> velocity_n_in[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; bc_type = &( lattice->bc[subs][lattice->NumNodes-lattice->param.LX].bc_type); i = 0; #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 = &( lattice->macro_vars[subs][lattice->NumNodes-lattice->param.LX].rho); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ //u = ((subs==1)?(-1):(1))*lattice->param.uy_out; if( lattice->param.bc_poiseuille) { i = 0; } else { u = lattice->param.uy_out; } while( ftemp < ftemp_end) { // North, Inflow if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { //u = u_out[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; //u = 0.; if( lattice->param.bc_poiseuille) { u = ( 1.5*( lattice->param.uy_out) /( .25*(lattice->param.LX-2)*(lattice->param.LX-2)) ) *( .25*( lattice->param.LX-2)*( lattice->param.LX-2) - (i-.5*( lattice->param.LX-2)-.5) *(i-.5*( lattice->param.LX-2)-.5) ) ; //printf("%s (%d) -- %d %f\n", __FILE__, __LINE__, i, u); i++; } if( lattice->param.incompressible) { //rho = -u + ( ftemp[0] + ftemp[1] + ftemp[3] // + 2.*( ftemp[2] + ftemp[5] + ftemp[6])); c = u; } else // compressible { rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[2] + ftemp[5] + ftemp[6])) / ( 1. + u); c = rho*u; } ftemp[4] = ftemp[2] - (2./3.)*c; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[1] - ftemp[3]) - (1./6.)*c; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[3] - ftemp[1]) - (1./6.)*c; #if 0 // Enforce a prescribed pressure by adjusting the resting distribution. ftemp[0] = 1.00054 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8] ); #endif #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- ftemp[0] = *rho0 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8]); rho0 += ( sizeof(struct macro_vars_struct)/8); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8); } else { if( lattice->param.bc_poiseuille) { i++;} #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 += ( sizeof(struct macro_vars_struct)/8); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8); } bc_type++; if( !( lattice->param.bc_poiseuille)) { i++;} } /* while( ftemp < ftemp_end) */ #if 0 if( lattice->param.bc_poiseuille) { // Fix corners ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp[4] = ( ftemp[27+4] + ftemp[-27*lattice->param.LX + 4]) /2; ftemp[8] = ( ftemp[27+8] + ftemp[-27*lattice->param.LX + 8]) /2; ftemp = lattice->pdf[subs][lattice->NumNodes-1].ftemp; ftemp[4] = ( ftemp[-27+4] + ftemp[-27*lattice->param.LX + 4]) /2; ftemp[7] = ( ftemp[-27+7] + ftemp[-27*lattice->param.LX + 7]) /2; } #endif } // }}} // V E L O C I T Y S O U T H O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // velocity south outflow // -- Velocity boundary on south side using outflow velocity condition. if( (id==0) && lattice->param.velocity_s_out[subs]) { //printf("bcs() %s %d >> velocity_s_out[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][lattice->param.LX].ftemp; bc_type = &( lattice->bc[subs][0].bc_type); i = 0; #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 = &( lattice->macro_vars[subs][0].rho); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ //u = ((subs==1)?(-1):(1))*lattice->param.uy_out; if( lattice->param.bc_poiseuille) { i = 0; } else { u = lattice->param.uy_out; } while( ftemp < ftemp_end) { // South, Outflow if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { //u = u_out[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; //u = 0.; if( lattice->param.bc_poiseuille) { u = ( 1.5*( lattice->param.uy_out) /( .25*(lattice->param.LX-2)*(lattice->param.LX-2)) ) *( .25*( lattice->param.LX-2)*( lattice->param.LX-2) - (i-.5*( lattice->param.LX-2)-.5) *(i-.5*( lattice->param.LX-2)-.5) ) ; i++; } if( lattice->param.incompressible) { //rho = u + ( ftemp[0] + ftemp[1] + ftemp[3] // + 2.*( ftemp[4] + ftemp[7] + ftemp[8])); c = u; } else { rho = ( ftemp[0] + ftemp[1] + ftemp[3] + 2.*( ftemp[4] + ftemp[7] + ftemp[8])) / ( 1. - u); c = rho*u; } ftemp[2] = ftemp[4] + (2./3.)*c; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[3] - ftemp[1]) + (1./6.)*c; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[1] - ftemp[3]) + (1./6.)*c; #if 0 // Enforce a prescribed pressure by adjusting the resting distribution. ftemp[0] = 1.0027 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8] ); #endif #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- ftemp[0] = *rho0 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8]); rho0 += ( sizeof(struct macro_vars_struct)/8); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8); } else { if( lattice->param.bc_poiseuille) { i++;} #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 += ( sizeof(struct macro_vars_struct)/8); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8); } bc_type++; if( !( lattice->param.bc_poiseuille)) { i++;} } /* while( ftemp < ftemp_end) */ #if 0 if( lattice->param.bc_poiseuille) { // Fix corners ftemp = lattice->pdf[subs][0].ftemp; ftemp[2] = ( ftemp[27+2] + ftemp[27*lattice->param.LX + 2]) /2; ftemp[5] = ( ftemp[27+5] + ftemp[27*lattice->param.LX + 5]) /2; ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp[2] = ( ftemp[-27+2] + ftemp[27*lattice->param.LX + 2]) /2; ftemp[6] = ( ftemp[-27+6] + ftemp[27*lattice->param.LX + 6]) /2; } #endif } /* if( lattice->param.velocity_s_out[subs]) */ // }}} // P R E S S U R E E A S T I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // pressure east inflow // -- Pressure boundary on east side using inflow pressure condition. if( lattice->param.pressure_e_in[subs] ) { //printf("bcs() %s %d >> pressure_e_in[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; while( ftemp < ftemp_end) { if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { // East, Inflow if( lattice->param.incompressible) { u_x = -lattice->param.rho_in + ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[1] + ftemp[5] + ftemp[8])); c = u_x; } else // compressible { u_x = -1. + ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[1] + ftemp[5] + ftemp[8])) / lattice->param.rho_in; c = u_x*lattice->param.rho_in; } ftemp[3] = ftemp[1] - (2./3.)*c; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[2] - ftemp[4]) - (1./6.)*c; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[4] - ftemp[2]) - (1./6.)*c; } ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.pressure_e_in[subs] ) */ // }}} // P R E S S U R E W E S T I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // pressure west inflow // -- Pressure boundary on west side using inflow pressure condition. if( lattice->param.pressure_w_in[subs] ) { //printf("bcs() %s %d >> pressure_w_in[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][(lattice->param.LY+1)*lattice->param.LX].ftemp; while( ftemp < ftemp_end) { if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { // West, Inflow if( lattice->param.incompressible) { u_x = lattice->param.rho_in - ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[3] + ftemp[7] + ftemp[6])); c = u_x; } else // compressible { u_x = 1. - ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[3] + ftemp[7] + ftemp[6])) / lattice->param.rho_in; c = u_x*lattice->param.rho_in; } ftemp[1] = ftemp[3] + (2./3.)*c; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[4] - ftemp[2]) + (1./6.)*c; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[2] - ftemp[4]) + (1./6.)*c; } ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.pressure_w_in[subs] ) */ // }}} // P R E S S U R E E A S T O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // pressure east outflow // -- Pressure boundary on east side using outflow pressure condition. if( lattice->param.pressure_e_out[subs]) { #if 1 //printf("bcs() %s %d >> pressure_e_out[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; n = get_LX( lattice) - 1; j = 0; while( ftemp < ftemp_end) { if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { // East, Outflow if( hydrostatic( lattice)) { if( hydrostatic_compressible( lattice)) { //if( get_time( lattice) == 6400) //{ // Try to adjust for discrepancy between rho_out and rho_ave. // compute_ave_rho( lattice, &(lattice->param.rho_out), /*subs*/0); //} if( hydrostatic_compute_rho_ref(lattice)) { // Reference density computed in terms of average density lattice->param.rho_out = ( 3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *(get_LY(lattice)-2) *lattice->param.rho_A[0]) / ( 1. - exp( -3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *(get_LY(lattice)-2))); } rho = #if 0 lattice->param.rho_out *exp( -3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *( (get_LY(lattice)-1.)-0.)) *exp( 3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *(j+1.0)); #else 3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *(get_LY(lattice)-2) *lattice->param.rho_A[0] *exp( -3.*lattice->param.gval[0][1] *( ( get_LY(lattice)-2.) - (j-.5)) ) / ( 1. - exp( -3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *(get_LY(lattice)-2))); #endif } else { rho = lattice->param.rho_out * ( 1. - 3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *( ( get_LY(lattice) + ((get_LY(lattice)%2)?(-1.):(1.)))/2. - j ) ); } } else { rho = lattice->param.rho_out; } if( lattice->param.incompressible) { u_x = -rho + ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[1] + ftemp[5] + ftemp[8]) ); c = u_x; } else // compressible { u_x = -1. + ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[1] + ftemp[5] + ftemp[8]) ) / rho; c = u_x*rho; } if( j==1) { //c = 0.; } ftemp[3] = ftemp[1] - (2./3.)*c; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[2] - ftemp[4]) #if 1 // Body force term - (1./2.)*(-1./2.) *lattice->param.gval[subs][1]*rho #if NUM_FLUID_COMPONENTS==2 && INAMURO_SIGMA_COMPONENT==1 *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif #endif - (1./6.)*c; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[4] - ftemp[2]) #if 1 // Body force term + (1./2.)*(-1./2.) *lattice->param.gval[subs][1]*rho #if NUM_FLUID_COMPONENTS==2 && INAMURO_SIGMA_COMPONENT==1 *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif #endif - (1./6.)*c; if( j==1) { } } /* if( is_not_solid_node( lattice, subs, n)) */ ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; j++; n += get_LX( lattice); } /* while( ftemp < ftemp_end) */ #else // Old version for comparison. ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; while( ftemp < ftemp_end) { // East, Outflow if( lattice->param.incompressible) { u_x = -lattice->param.rho_out + ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[1] + ftemp[5] + ftemp[8])); c = u_x; } else // compressible { u_x = -1. + ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[1] + ftemp[5] + ftemp[8])) / lattice->param.rho_out; c = u_x*lattice->param.rho_out; } ftemp[3] = ftemp[1] - (2./3.)*c; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[2] - ftemp[4]) - (1./6.)*c; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[4] - ftemp[2]) - (1./6.)*c; ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } /* while( ftemp < ftemp_end) */ #endif } /* if( lattice->param.pressure_e_out[subs]) */ // }}} // P R E S S U R E W E S T O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // pressure west outflow // -- Pressure boundary on west side using outflow pressure condition. if( lattice->param.pressure_w_out[subs]) { //printf("bcs() %s %d >> pressure_w_out[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][(lattice->param.LY+1)*lattice->param.LX].ftemp; j = 0; n = 0; while( ftemp < ftemp_end) { // West, Outflow if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { if( hydrostatic_west( lattice)) { if( hydrostatic_compressible( lattice)) { //if( get_time( lattice) == 6400) //{ // Try to adjust for discrepancy between rho_out and rho_ave. // compute_ave_rho( lattice, &(lattice->param.rho_out), /*subs*/0); //} if( hydrostatic_compute_rho_ref(lattice)) { // Reference density computed in terms of average density lattice->param.rho_out = ( 3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *(get_LY(lattice)-2) *lattice->param.rho_A[0]) / ( 1. - exp( -3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *(get_LY(lattice)-2))); //printf("rho_ref = %20.17f\n", lattice->param.rho_out); } rho = #if 0 lattice->param.rho_out *exp( -3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT //*(1.+(get_buoyancy(lattice))*lattice->param.C_out) *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif //*(0.5*(get_LY(lattice)-1.)-1.)) *( (get_LY(lattice)-1.)-0.)) *exp( 3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT //*(1.+(get_buoyancy(lattice))*lattice->param.C_out) *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *(j+1.0)); //*exp( -3.*lattice->param.gval[0][1] // *(0.5*(get_LY(lattice)-1)-1)) //*exp( 3.*lattice->param.gval[0][1] // *(get_LY(lattice)+.5-j)); #else 3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT //*(1.+(get_buoyancy(lattice))*lattice->param.C_out) *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *(get_LY(lattice)-2) *lattice->param.rho_A[0] *exp( -3.*lattice->param.gval[0][1] *( ( get_LY(lattice)-2.) - (j-.5)) ) / ( 1. - exp( -3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT //*(1.+(get_buoyancy(lattice))*lattice->param.C_out) *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *(get_LY(lattice)-2))); #endif } else { rho = lattice->param.rho_out * ( 1. - 3.*lattice->param.gval[0][1] #if INAMURO_SIGMA_COMPONENT //*(1.+(get_buoyancy(lattice))*lattice->param.C_out) *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif *( ( get_LY(lattice) + ((get_LY(lattice)%2)?(-1.):(1.)))/2. - j ) ); } } else { rho = lattice->param.rho_out; } if( lattice->param.incompressible) { u_x = rho - ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[3] + ftemp[7] + ftemp[6]) ); c = u_x; } else // compressible { u_x = 1. - ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[3] + ftemp[7] + ftemp[6]) ) / rho; c = u_x*rho; } ftemp[1] = ftemp[3] + (2./3.)*c; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[4] - ftemp[2]) #if 1 // Body force term + (1./2.)*(-1./2.) *lattice->param.gval[subs][1]*rho #if NUM_FLUID_COMPONENTS==2 && INAMURO_SIGMA_COMPONENT==1 //*(1.+(get_buoyancy(lattice))*(lattice->macro_vars[/*subs*/1][n].rho)) //*(1.+(get_buoyancy(lattice))*(lattice->param.C_out)) *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif #endif + (1./6.)*c; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[2] - ftemp[4]) #if 1 // Body force term - (1./2.)*(-1./2.) *lattice->param.gval[subs][1]*rho #if NUM_FLUID_COMPONENTS==2 && INAMURO_SIGMA_COMPONENT==1 //*(1.+(get_buoyancy(lattice))*(lattice->macro_vars[/*subs*/1][n].rho)) //*(1.+(get_buoyancy(lattice))*(lattice->param.C_out)) *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) *(get_C_out(lattice)-get_C0(lattice)) ) #endif #endif + (1./6.)*c; if( j==1) { } if( 0)//j==1) // Debug output {{{ { if( lattice->time==1) { printf("BCSW\n"); printf("BCSW time ftemp[0] ftemp[2] ftemp[4]" " ftemp[3] ftemp[7] ftemp[6] --> u_x" " ftemp[1] ftemp[5] ftemp[8] \n"); printf("BCSW ---- -------- -------- --------" " -------- -------- -------- ---" " -------- -------- --------\n"); } printf("BCSW %4d %f %f %f %f %f %f --> %f %f %f %f\n", lattice->time, ftemp[0], ftemp[2], ftemp[4], ftemp[3], ftemp[7], ftemp[6], u_x, ftemp[1], ftemp[5], ftemp[8] ); } /* if( j==1) }}} */ } /* if( is_not_solid_node( lattice, subs, n)) */ ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; n+=get_LX( lattice); j++; } /* while( ftemp < ftemp_end) */ } /* if( pressure_w_out[subs]) */ // }}} // V E L O C I T Y E A S T I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // velocity east inflow // -- Velocity boundary on east side using inflow velocity condition. if( lattice->param.velocity_e_in[subs]) { //printf("bcs() %s %d >> velocity_e_in[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; bc_type = &( lattice->bc[subs][lattice->param.LX-1].bc_type); #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 = &( lattice->macro_vars[subs][lattice->param.LX-1].rho); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ //u = ((subs==1)?(-1):(1))*lattice->param.ux_in; if( lattice->param.bc_poiseuille) { i = 0; } else { u = lattice->param.ux_in; } while( ftemp < ftemp_end) { // East, Inflow if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { //u = u_in[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; //u = 0.; if( lattice->param.bc_poiseuille) { u = ( 1.5*( lattice->param.ux_in) /( .25*(lattice->param.LY-2)*(lattice->param.LY-2)) ) *( .25*( lattice->param.LY-2)*( lattice->param.LY-2) - (i-.5*( lattice->param.LY-2)-.5) *(i-.5*( lattice->param.LY-2)-.5) ) ; //printf("%s (%d) -- %d %f\n", __FILE__, __LINE__, i, u); i++; } if( lattice->param.incompressible) { rho = -u + ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[1] + ftemp[5] + ftemp[8])); c = u; } else // compressible { rho = ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[1] + ftemp[5] + ftemp[8])) / ( 1. + u); c = rho*u; } ftemp[3] = ftemp[1] - (2./3.)*c; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[2] - ftemp[4]) - (1./6.)*c; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[4] - ftemp[2]) - (1./6.)*c; #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- ftemp[0] = *rho0 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8]); rho0 += ( sizeof(struct macro_vars_struct)/8)*lattice->param.LX; //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } else { if( lattice->param.bc_poiseuille) { i++;} #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 += ( sizeof(struct macro_vars_struct)/8)*lattice->param.LX; //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } bc_type+=lattice->param.LX; } /* while( ftemp < ftemp_end) */ #if 0 if( lattice->param.bc_poiseuille) { // Fix corners ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp[4] = ( ftemp[27+4] + ftemp[-27*lattice->param.LX + 4]) /2; ftemp[8] = ( ftemp[27+8] + ftemp[-27*lattice->param.LX + 8]) /2; ftemp = lattice->pdf[subs][lattice->NumNodes-1].ftemp; ftemp[4] = ( ftemp[-27+4] + ftemp[-27*lattice->param.LX + 4]) /2; ftemp[7] = ( ftemp[-27+7] + ftemp[-27*lattice->param.LX + 7]) /2; } #endif } /* if( lattice->param.velocity_e_in[subs]) */ // }}} // V E L O C I T Y W E S T I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // velocity west inflow // -- Velocity boundary on west side using inflow velocity condition. if( lattice->param.velocity_w_in[subs] ) { //printf("bcs() %s %d >> velocity_w_in[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][(lattice->param.LY+1)*lattice->param.LX].ftemp; bc_type = &( lattice->bc[subs][0].bc_type); j = 0; n = 0; #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 = &( lattice->macro_vars[subs][0].rho); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ //u = ((subs==1)?(-1):(1))*lattice->param.ux_in; if( lattice->param.bc_poiseuille) { i = 0; } else { u = lattice->param.ux_in; } while( ftemp < ftemp_end) { // West, Inflow if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { //u = u_in[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; //u = 0.; if( lattice->param.bc_poiseuille) { u = ( 1.5*( lattice->param.ux_in) /( .25*( lattice->param.LY-2)*( lattice->param.LY-2)) ) *( .25*( lattice->param.LY-2)*( lattice->param.LY-2) - (i-.5*( lattice->param.LY-2)-.5) *(i-.5*( lattice->param.LY-2)-.5) ) ; i++; } if( lattice->param.incompressible) { rho = u + ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[3] + ftemp[7] + ftemp[6])); c = u; } else { rho = ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[3] + ftemp[7] + ftemp[6])) / ( 1. - u); c = rho*u; } ftemp[1] = ftemp[3] + (2./3.)*c; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[4] - ftemp[2]) + (1./2.)*(-1./2.)*lattice->param.gval[subs][1] *rho #if NUM_FLUID_COMPONENTS==2 && INAMURO_SIGMA_COMPONENT==1 //*(1.+(get_buoyancy(lattice))*(lattice->macro_vars[/*subs*/1][n].rho)) *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) //*(get_rhon(lattice,n,/*subs*/1)-get_C0(lattice)) ) *(get_C_in(lattice)-get_C0(lattice)) ) #endif + (1./6.)*c; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[2] - ftemp[4]) - (1./2.)*(-1./2.)*lattice->param.gval[subs][1] *rho #if NUM_FLUID_COMPONENTS==2 && INAMURO_SIGMA_COMPONENT==1 //*(1.+(get_buoyancy(lattice))*(lattice->macro_vars[/*subs*/1][n].rho)) *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) //*(get_rhon(lattice,n,/*subs*/1)-get_C0(lattice)) ) *(get_C_in(lattice)-get_C0(lattice)) ) #endif + (1./6.)*c; #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- ftemp[0] = *rho0 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8]); rho0 += ( sizeof(struct macro_vars_struct)/8)*lattice->param.LX; //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } else { if( lattice->param.bc_poiseuille) { i++;} #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 += ( sizeof(struct macro_vars_struct)/8)*lattice->param.LX; //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } bc_type++; j++; n+=get_LX(lattice); } /* while( ftemp < ftemp_end) */ #if 0 if( lattice->param.bc_poiseuille) { // Fix corners ftemp = lattice->pdf[subs][0].ftemp; ftemp[2] = ( ftemp[27+2] + ftemp[27*lattice->param.LX + 2]) /2; ftemp[5] = ( ftemp[27+5] + ftemp[27*lattice->param.LX + 5]) /2; ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp[2] = ( ftemp[-27+2] + ftemp[27*lattice->param.LX + 2]) /2; ftemp[6] = ( ftemp[-27+6] + ftemp[27*lattice->param.LX + 6]) /2; } #endif } // }}} // V E L O C I T Y E A S T O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // velocity east outflow // -- Velocity boundary on east side using outflow velocity condition. if( lattice->param.velocity_e_out[subs]) { //printf("bcs() %s %d >> velocity_e_in[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; bc_type = &( lattice->bc[subs][lattice->param.LX-1].bc_type); #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 = &( lattice->macro_vars[subs][lattice->param.LX-1].rho); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ //u = ((subs==1)?(-1):(1))*lattice->param.ux_out; if( lattice->param.bc_poiseuille) { i = 0; } else { u = lattice->param.ux_out; } while( ftemp < ftemp_end) { // East, Outflow if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { //u = u_out[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; //u = 0.; if( lattice->param.bc_poiseuille) { u = ( 1.5*( lattice->param.ux_out) /( .25*(lattice->param.LY-2)*(lattice->param.LY-2)) ) *( .25*( lattice->param.LY-2)*( lattice->param.LY-2) - (i-.5*( lattice->param.LY-2)-.5) *(i-.5*( lattice->param.LY-2)-.5) ) ; //printf("%s (%d) -- %d %f\n", __FILE__, __LINE__, i, u); i++; } if( lattice->param.incompressible) { rho = -u + ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[1] + ftemp[5] + ftemp[8])); c = u; } else // compressible { rho = ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[1] + ftemp[5] + ftemp[8])) / ( 1. + u); c = rho*u; } ftemp[3] = ftemp[1] - (2./3.)*c; ftemp[7] = ftemp[5] + (1./2.)*( ftemp[2] - ftemp[4]) - (1./2.)*(-1./2.)*lattice->param.gval[subs][1] *rho #if NUM_FLUID_COMPONENTS==2 && INAMURO_SIGMA_COMPONENT==1 //*(1.+(get_buoyancy(lattice))*(lattice->macro_vars[/*subs*/1][n].rho)) *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) //*(get_rhon(lattice,n,/*subs*/1)-get_C0(lattice)) ) *(get_C_out(lattice)-get_C0(lattice)) ) #endif - (1./6.)*c; ftemp[6] = ftemp[8] + (1./2.)*( ftemp[4] - ftemp[2]) - (1./2.)*(-1./2.)*lattice->param.gval[subs][1] *rho #if NUM_FLUID_COMPONENTS==2 && INAMURO_SIGMA_COMPONENT==1 //*(1.+(get_buoyancy(lattice))*(lattice->macro_vars[/*subs*/1][n].rho)) *( 1. + (get_buoyancy(lattice)) *(get_beta(lattice)) //*(get_rhon(lattice,n,/*subs*/1)-get_C0(lattice)) ) *(get_C_out(lattice)-get_C0(lattice)) ) #endif - (1./6.)*c; #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- ftemp[0] = *rho0 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8]); rho0 += ( sizeof(struct macro_vars_struct)/8)*lattice->param.LX; //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } else { if( lattice->param.bc_poiseuille) { i++;} #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 += ( sizeof(struct macro_vars_struct)/8)*lattice->param.LX; //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } bc_type++; } /* while( ftemp < ftemp_end) */ #if 0 if( lattice->param.bc_poiseuille) { // Fix corners ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp[4] = ( ftemp[27+4] + ftemp[-27*lattice->param.LX + 4]) /2; ftemp[8] = ( ftemp[27+8] + ftemp[-27*lattice->param.LX + 8]) /2; ftemp = lattice->pdf[subs][lattice->NumNodes-1].ftemp; ftemp[4] = ( ftemp[-27+4] + ftemp[-27*lattice->param.LX + 4]) /2; ftemp[7] = ( ftemp[-27+7] + ftemp[-27*lattice->param.LX + 7]) /2; } #endif } /* if( lattice->param.velocity_e_out[subs]) */ // }}} // V E L O C I T Y W E S T O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // velocity west outflow // -- Velocity boundary on west side using outflow velocity condition. if( lattice->param.velocity_w_out[subs]) { //printf("bcs() %s %d >> velocity_w_out[%d]\n", __FILE__, __LINE__, subs); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][(lattice->param.LY+1)*lattice->param.LX].ftemp; bc_type = &( lattice->bc[subs][0].bc_type); #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 = &( lattice->macro_vars[subs][0].rho); //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ //u = ((subs==1)?(-1):(1))*lattice->param.ux_out; if( lattice->param.bc_poiseuille) { i = 0; } else { u = lattice->param.ux_out; } while( ftemp < ftemp_end) { // West, Outflow if( bcs_on_solids(lattice) || is_not_solid_node(lattice,0,n)) { //u = u_out[((double)rand()/(double)RAND_MAX<.5)?(0):(1)][subs]; //u = 0.; if( lattice->param.bc_poiseuille) { u = ( 1.5*( lattice->param.ux_out) /( .25*(lattice->param.LY-2)*(lattice->param.LY-2)) ) *( .25*( lattice->param.LY-2)*( lattice->param.LY-2) - (i-.5*( lattice->param.LY-2)-.5) *(i-.5*( lattice->param.LY-2)-.5) ) ; i++; } if( lattice->param.incompressible) { rho = u + ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[3] + ftemp[7] + ftemp[6])); c = u; } else { rho = ( ftemp[0] + ftemp[2] + ftemp[4] + 2.*( ftemp[3] + ftemp[7] + ftemp[6])) / ( 1. - u); c = rho*u; } ftemp[1] = ftemp[3] + (2./3.)*c; ftemp[5] = ftemp[7] + (1./2.)*( ftemp[4] - ftemp[2]) + (1./6.)*c; ftemp[8] = ftemp[6] + (1./2.)*( ftemp[2] - ftemp[4]) + (1./6.)*c; #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- ftemp[0] = *rho0 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8]); rho0 += ( sizeof(struct macro_vars_struct)/8)*lattice->param.LX; //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } else { if( lattice->param.bc_poiseuille) { i++;} #if RHO0_TEST //------------------------------------------------------------------[ TEST ]---- rho0 += ( sizeof(struct macro_vars_struct)/8)*lattice->param.LX; //------------------------------------------------------------------[ TEST ]---- #endif /* RHO0_TEST */ ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } bc_type++; } /* while( ftemp < ftemp_end) */ #if 0 if( lattice->param.bc_poiseuille) { // Fix corners ftemp = lattice->pdf[subs][0].ftemp; ftemp[2] = ( ftemp[27+2] + ftemp[27*lattice->param.LX + 2]) /2; ftemp[5] = ( ftemp[27+5] + ftemp[27*lattice->param.LX + 5]) /2; ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp[2] = ( ftemp[-27+2] + ftemp[27*lattice->param.LX + 2]) /2; ftemp[6] = ( ftemp[-27+6] + ftemp[27*lattice->param.LX + 6]) /2; } #endif } /* if( lattice->param.velocity_w_out[subs]) */ // }}} #if 0 // C O R N E R S //############################################################################ // S O U T H W E S T C O R N E R B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // south west corner // -- Average adjacent cells (east side and north side cells) // -- This is only for when boundary conditions are applied on the // adjecent sides, south and west, so that the corners overlap. if( (id==0) && ( 1 || ( ( lattice->param.velocity_w_out[subs] ||lattice->param.velocity_w_in[subs] ||lattice->param.pressure_w_out[subs] ||lattice->param.pressure_w_in[subs] ) && ( lattice->param.velocity_s_out[subs] ||lattice->param.velocity_s_in[subs] ||lattice->param.pressure_s_out[subs] ||lattice->param.pressure_s_in[subs] ) ) ) ) { ftemp = lattice->pdf[subs][0].ftemp; #if 0 // Leverage the existing supplementary pointers, even though the // names don't make sense in this context. ftemp_end = lattice->pdf[subs][1].ftemp; ftemp_mid = lattice->pdf[subs][get_LX(lattice)].ftemp; for( a=0; a<9; a++) { ftemp[a] = ( ftemp_end[a] + ftemp_mid[a]) / 2.; } #if 1 // Enforce a prescribed pressure by adjusting the resting distribution. ftemp[0] = 1.0027 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8] ); #endif #else // 6 2 5 // \|/ // 3 o-1 // \ // 7 4 8 ftemp[1] = ftemp[3]; ftemp[2] = ftemp[4]; ftemp[8] = ftemp[7]; ftemp[6] = 0.; ftemp[5] = 1.0027 //ftemp[5] = 1.00054 - ( ftemp[0] + ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[6] + ftemp[7] + ftemp[8] ); ftemp[5] /= 2.; ftemp[6] = ftemp[5]; #endif } // }}} // S O U T H E A S T C O R N E R B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // south east corner // -- Average adjacent cells (west side and north side cells) // -- This is only for when boundary conditions are applied on the // adjecent sides, south and east, so that the corners overlap. if( (id==0) && ( 1 || ( ( lattice->param.velocity_e_out[subs] ||lattice->param.velocity_e_in[subs] ||lattice->param.pressure_e_out[subs] ||lattice->param.pressure_e_in[subs] ) && ( lattice->param.velocity_s_out[subs] ||lattice->param.velocity_s_in[subs] ||lattice->param.pressure_s_out[subs] ||lattice->param.pressure_s_in[subs] ) ) ) ) { ftemp = lattice->pdf[subs][get_LX(lattice)-1].ftemp; #if 0 // Leverage the existing supplementary pointers, even though the // names don't make sense in this context. ftemp_end = lattice->pdf[subs][get_LX(lattice)-2].ftemp; ftemp_mid = lattice->pdf[subs][2*get_LX(lattice)-1].ftemp; for( a=0; a<9; a++) { ftemp[a] = ( ftemp_end[a] + ftemp_mid[a]) / 2.; } #if 1 // Enforce a prescribed pressure by adjusting the resting distribution. ftemp[0] = 1.0027 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8] ); #endif #else // 6 2 5 // \|/ // 3-o 1 // / // 7 4 8 ftemp[3] = ftemp[1]; ftemp[2] = ftemp[4]; ftemp[7] = ftemp[8]; ftemp[5] = 0.; ftemp[6] = 1.0027 //ftemp[6] = 1.00054 - ( ftemp[0] + ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[7] + ftemp[8] ); ftemp[6] /= 2.; ftemp[5] = ftemp[6]; #endif } // }}} // N O R T H W E S T C O R N E R B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // north west corner // -- Average adjacent cells (east side and south side cells) // -- This is only for when boundary conditions are applied on the // adjecent sides, north and west, so that the corners overlap. if( (id==get_num_procs(lattice)-1) && ( 1 || ( ( lattice->param.velocity_w_out[subs] ||lattice->param.velocity_w_in[subs] ||lattice->param.pressure_w_out[subs] ||lattice->param.pressure_w_in[subs] ) && ( lattice->param.velocity_n_out[subs] ||lattice->param.velocity_n_in[subs] ||lattice->param.pressure_n_out[subs] ||lattice->param.pressure_n_in[subs] ) ) ) ) { ftemp = lattice->pdf[subs][get_NumNodes(lattice)-get_LX(lattice)].ftemp; #if 0 // Leverage the existing supplementary pointers, even though the // names don't make sense in this context. ftemp_end = lattice->pdf[subs][get_NumNodes(lattice)-get_LX(lattice)+1].ftemp; ftemp_mid = lattice->pdf[subs][get_NumNodes(lattice)-2*get_LX(lattice)].ftemp; for( a=0; a<9; a++) { ftemp[a] = ( ftemp_end[a] + ftemp_mid[a]) / 2.; } #if 1 // Enforce a prescribed pressure by adjusting the resting distribution. ftemp[0] = 1.00054 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8] ); #endif #else // 6 2 5 // / // 3 o-1 // /|\ // 7 4 8 ftemp[1] = ftemp[3]; ftemp[4] = ftemp[2]; ftemp[5] = ftemp[6]; ftemp[7] = 0.; //ftemp[8] = 1.00054 ftemp[8] = ( 1.0027 - (get_LY(lattice)-1)*.00054) - ( ftemp[0] + ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] ); ftemp[8] /= 2.; ftemp[7] = ftemp[8]; #endif } // }}} // N O R T H E A S T C O R N E R B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // north east corner // -- Average adjacent cells (west side and south side cells) // -- This is only for when boundary conditions are applied on the // adjecent sides, north and east, so that the corners overlap. if( (id==get_num_procs(lattice)-1) && ( 1 || ( ( lattice->param.velocity_e_out[subs] ||lattice->param.velocity_e_in[subs] ||lattice->param.pressure_e_out[subs] ||lattice->param.pressure_e_in[subs] ) && ( lattice->param.velocity_n_out[subs] ||lattice->param.velocity_n_in[subs] ||lattice->param.pressure_n_out[subs] ||lattice->param.pressure_n_in[subs] ) ) ) ) { ftemp = lattice->pdf[subs][get_NumNodes(lattice)-1].ftemp; #if 0 // Leverage the existing supplementary pointers, even though the // names don't make sense in this context. ftemp_end = lattice->pdf[subs][get_NumNodes(lattice)-2].ftemp; ftemp_mid = lattice->pdf[subs][get_NumNodes(lattice)-get_LX(lattice)-1].ftemp; for( a=0; a<9; a++) { ftemp[a] = ( ftemp_end[a] + ftemp_mid[a]) / 2.; } #if 1 // Enforce a prescribed pressure by adjusting the resting distribution. ftemp[0] = 1.00054 - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[7] + ftemp[8] ); #endif #else // 6 2 5 // \ // 3-o 1 // /|\ // 7 4 8 ftemp[3] = ftemp[1]; ftemp[4] = ftemp[2]; ftemp[6] = ftemp[5]; ftemp[8] = 0.; //ftemp[7] = 1.00054 ftemp[7] = ( 1.0027 - (get_LY(lattice)-1)*.00054) - ( ftemp[1] + ftemp[2] + ftemp[3] + ftemp[4] + ftemp[5] + ftemp[6] + ftemp[0] + ftemp[8] ); ftemp[7] /= 2.; ftemp[8] = ftemp[7]; #endif } // }}} #endif } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if INAMURO_SIGMA_COMPONENT subs=1; #if SIGMA_BULK_FLAG if(lattice->time > lattice->param.sigma_bulk_on) { #endif // C O N S T C O N C N O R T H I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant conc north inflow // -- Constant concentration boundary on north side using inflow value. if( (id==get_num_procs(lattice)-1) && lattice->param.constcon_n_in ) { //printf("%s %d -- constcon_n_in\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; while( ftemp < ftemp_end) { // North, Inflow if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { c = lattice->param.C_in; } else { c = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( c - ( ftemp[0] + ftemp[1] + ftemp[3] + ftemp[2])); ftemp[4] = (1./8.)*rho; } else { rho = 6.*( c - ( ftemp[0] + ftemp[1] + ftemp[3] + ftemp[2] + ftemp[5] + ftemp[6])); ftemp[4] = (1./9.)*rho; ftemp[7] = (1./36.)*rho; ftemp[8] = (1./36.)*rho; } ftemp += ( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constcon_n_in ) */ // }}} // C O N S T C O N C S O U T H I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant conc south inflow // -- Constant concentration boundary on south side using inflow value. if( (id==0) && lattice->param.constcon_s_in ) { //printf("bcs() %s %d >> constcon_s_in\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][lattice->param.LX].ftemp; while( ftemp < ftemp_end) { // South, Inflow if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { c = lattice->param.C_in; } else { c = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( c - ( ftemp[0] + ftemp[1] + ftemp[3] + ftemp[4])); ftemp[2] = (1./8.)*rho; } else { rho = 6.*( c - ( ftemp[0] + ftemp[1] + ftemp[3] + ftemp[7] + ftemp[4] + ftemp[8])); ftemp[2] = (1./9.)*rho; ftemp[5] = (1./36.)*rho; ftemp[6] = (1./36.)*rho; } ftemp += ( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constcon_s_in ) */ // }}} // C O N S T C O N C N O R T H O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant conc north outflow // -- Constant concentration boundary on north side using outflow value. if( (id==get_num_procs(lattice)-1) && lattice->param.constcon_n_out) { //printf("%s %d -- constcon_n_out\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; i=0; while( ftemp < ftemp_end) { //if( i>0 && i<get_LX(lattice)-1) //{ // North, Outflow if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { c = lattice->param.C_out; } else { c = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( c - ( ftemp[0] + ftemp[1] + ftemp[3] + ftemp[2])); ftemp[4] = (1./8.)*rho; } else { //printf("%s %d >> constcon_n_out\n",__FILE__,__LINE__); rho = 6.*( c - ( ftemp[0] + ftemp[1] + ftemp[3] + ftemp[2] + ftemp[5] + ftemp[6])); ftemp[4] = (1./9.)*rho; ftemp[7] = (1./36.)*rho; ftemp[8] = (1./36.)*rho; } //} ftemp += ( sizeof(struct pdf_struct)/8); i++; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constcon_n_out) */ // }}} // C O N S T C O N C S O U T H O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant conc south outflow // -- Constant concentration boundary on south side with outflow value. if( (id==0) && lattice->param.constcon_s_out) { //printf("bcs() %s %d >> constcon_s_out\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][lattice->param.LX].ftemp; i=0; while( ftemp < ftemp_end) { // South, Outflow //if( i>0 && i<get_LX(lattice)-1) //{ if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { c = lattice->param.C_out; } else { c = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( c - ( ftemp[0] + ftemp[1] + ftemp[3] + ftemp[4])); ftemp[2] = (1./8.)*rho; } else { rho = 6.*( c - ( ftemp[0] + ftemp[1] + ftemp[3] + ftemp[7] + ftemp[4] + ftemp[8])); ftemp[2] = (1./9.)*rho; ftemp[5] = (1./36.)*rho; ftemp[6] = (1./36.)*rho; } //} ftemp += ( sizeof(struct pdf_struct)/8); i++; } /* while( ftemp < ftemp_end) */ } /* if( constcon_s_out) */ // }}} // C O N S T F L U X N O R T H I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant flux north inflow // -- Constant flux boundary on north side with inflow value. if( (id==get_num_procs(lattice)-1) && lattice->param.constflx_n_in ) { //printf("%s %d -- constflx_n_in\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; while( ftemp < ftemp_end) { // North, Inflow if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { u = lattice->param.u_sigma_in; } else { u = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( u + ftemp[2]); ftemp[4] = (1./ 8.)*rho; } else { rho = 6.*( u + ftemp[2] + ftemp[5] + ftemp[6]); ftemp[4] = (1./ 9.)*rho; ftemp[7] = (1./36.)*rho; ftemp[8] = (1./36.)*rho; } ftemp += ( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constflx_n_in ) */ // }}} // C O N S T F L U X S O U T H I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant flux south inflow // -- Constant flux boundary on south side with inflow value. if( (id==0) && lattice->param.constflx_s_in ) { //printf("bcs() %s %d >> constflx_s_in\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][lattice->param.LX].ftemp; while( ftemp < ftemp_end) { // South, Inflow if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { u = lattice->param.u_sigma_in; } else { u = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( u + ftemp[4]); ftemp[2] = (1./8.)*rho; } else { rho = 6.*( u + ftemp[7] + ftemp[4] + ftemp[8]); ftemp[2] = (1./9.)*rho; ftemp[5] = (1./36.)*rho; ftemp[6] = (1./36.)*rho; } ftemp += ( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constflx_s_in ) */ // }}} // C O N S T F L U X N O R T H O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant flux north outflow // -- Constant flux boundary on north side with outflow value. if( (id==get_num_procs(lattice)-1) && lattice->param.constflx_n_out) { //printf("%s %d -- constflx_n_out\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; n = get_NumNodes(lattice) - get_LX(lattice); i = 0; while( ftemp < ftemp_end) { // North, Outflow if( (i>0 && i<get_LX(lattice)-1) && is_not_solid_node(lattice,subs,n)) { if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { u = lattice->param.u_sigma_out; } else { u = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( u + ftemp[2]); ftemp[4] = (1./8.)*rho; } else { rho = 6.*( u + ftemp[2] + ftemp[5] + ftemp[6]); ftemp[4] = (1./9.)*rho; ftemp[7] = (1./36.)*rho; ftemp[8] = (1./36.)*rho; } } else { // Corners if( i!=0) { // East corner ftemp[6] = ftemp[5]; rho = 6.*( u + ftemp[2] + ftemp[5] + ftemp[6]); ftemp[4] = (1./9.)*rho; ftemp[7] = (1./36.)*rho; ftemp[8] = (1./36.)*rho; } else { // West corner ftemp[5] = ftemp[6]; rho = 6.*( u + ftemp[2] + ftemp[5] + ftemp[6]); ftemp[4] = (1./9.)*rho; ftemp[7] = (1./36.)*rho; ftemp[8] = (1./36.)*rho; } } ftemp += ( sizeof(struct pdf_struct)/8); n++; i++; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constflx_n_out) */ // }}} // C O N S T F L U X S O U T H O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant flux south outflow // -- Constant flux boundary on south side with outflow value. if( (id==0) && lattice->param.constflx_s_out) { //printf("bcs() %s %d >> constflx_s_out\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][lattice->param.LX].ftemp; n = 0; i = 0; while( ftemp < ftemp_end) { // South, Outflow if( ( i>0 && i<get_LX(lattice)-1) && is_not_solid_node(lattice,subs,n)) { if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { u = lattice->param.u_sigma_out; } else { u = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( u + ftemp[4]); ftemp[2] = (1./8.)*rho; } else { rho = 6.*( u + ftemp[7] + ftemp[4] + ftemp[8]); ftemp[2] = (1./9.)*rho; ftemp[5] = (1./36.)*rho; ftemp[6] = (1./36.)*rho; } } else { // Corners if( i!=0) { // East corner ftemp[7] = ftemp[8]; rho = 6.*( u + ftemp[7] + ftemp[4] + ftemp[8]); ftemp[2] = (1./9.)*rho; ftemp[5] = (1./36.)*rho; ftemp[6] = (1./36.)*rho; } else { // West corner ftemp[8] = ftemp[7]; rho = 6.*( u + ftemp[7] + ftemp[4] + ftemp[8]); ftemp[2] = (1./9.)*rho; ftemp[5] = (1./36.)*rho; ftemp[6] = (1./36.)*rho; } } ftemp += ( sizeof(struct pdf_struct)/8); n++; i++; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constflx_s_out) */ // }}} // Z E R O C O N C G R A D I E N T S O U T H B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // zero conc gradient south // -- Zero concentration gradient boundary on south side. if( (id==0) && lattice->param.zeroconcgrad_s) { //printf("bcs() %s %d >> zeroconcgrad_s_out\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][lattice->param.LX].ftemp; while( ftemp < ftemp_end) { // South // Copy from the adjacent interior neighbor values for the // unknown distributions. ftemp[2] = ftemp[ 2 + (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[5] = ftemp[ 5 + (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[6] = ftemp[ 6 + (sizeof(struct pdf_struct)/8)*lattice->param.LX]; if( lattice->param.zeroconcgrad_full) { // Copy all the rest of the distribution functions from the adjacent // interior neighbor. ftemp[0] = ftemp[ 0 + (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[1] = ftemp[ 1 + (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[3] = ftemp[ 3 + (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[4] = ftemp[ 4 + (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[7] = ftemp[ 7 + (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[8] = ftemp[ 8 + (sizeof(struct pdf_struct)/8)*lattice->param.LX]; } ftemp += ( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.zerograd_s) */ // }}} // Z E R O C O N C G R A D I E N T N O R T H B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // zero conc gradient north // -- Zero concentration gradient boundary on north side. if( (id==get_num_procs(lattice)-1) && lattice->param.zeroconcgrad_n) { //printf("bcs() %s %d >> zeroconcgrad_n\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][lattice->NumNodes-lattice->param.LX].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; while( ftemp < ftemp_end) { // North // Copy from the adjacent interior neighbor values for the // unknown distributions. ftemp[4] = ftemp[ 4 - (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[7] = ftemp[ 7 - (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[8] = ftemp[ 8 - (sizeof(struct pdf_struct)/8)*lattice->param.LX]; if( lattice->param.zeroconcgrad_full) { // Copy all the rest of the distribution functions from the adjacent // interior neighbor. ftemp[0] = ftemp[ 0 - (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[1] = ftemp[ 1 - (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[2] = ftemp[ 2 - (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[3] = ftemp[ 3 - (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[5] = ftemp[ 5 - (sizeof(struct pdf_struct)/8)*lattice->param.LX]; ftemp[6] = ftemp[ 6 - (sizeof(struct pdf_struct)/8)*lattice->param.LX]; } ftemp += ( sizeof(struct pdf_struct)/8); } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.zerograd_n) */ // }}} // C O N S T C O N C E A S T I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant conc east inflow // -- Constant concentration boundary on east side using inflow value. if( lattice->param.constcon_e_in ) { //printf("%s %d -- constcon_e_in\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; n = get_LX(lattice)-1; j = 0; while( ftemp < ftemp_end) { // East, Inflow if( ( j>0 && j<get_LY(lattice)-1) && is_not_solid_node( lattice, subs, n)) { if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { c = lattice->param.C_in; } else { c = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( c - ( ftemp[0] + ftemp[2] + ftemp[4] + ftemp[1])); ftemp[3] = (1./8.)*rho; } else { rho = 6.*( c - ( ftemp[0] + ftemp[2] + ftemp[4] + ftemp[1] + ftemp[5] + ftemp[8])); ftemp[3] = (1./9.)*rho; ftemp[7] = (1./36.)*rho; ftemp[6] = (1./36.)*rho; } } ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; n+=get_LX(lattice); j++; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constcon_e_in ) */ // }}} // C O N S T C O N C W E S T I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant conc west inflow // -- Constant concentration boundary on west side using inflow value. if( lattice->param.constcon_w_in ) { //printf("bcs() %s %d >> constcon_w_in\n", __FILE__, __LINE__); n = 0; ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][(lattice->param.LY+1)*lattice->param.LX].ftemp; j = 0; while( ftemp < ftemp_end) { // West, Inflow bc_type = &( lattice->bc[0][n].bc_type); if( 1)//( j>0 && j<get_LY(lattice)-1) || is_not_solid_node(lattice,subs,n)) { if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { if(lattice->param.constcon_w_in==1) { c = lattice->param.C_in; } else if(lattice->param.constcon_w_in==3) { // // (-D*(dC/dx) + v*C) = v*C0 ==> // // c = (v*c0 + D*c2)/( D + v) // v = lattice->macro_vars[0][n].u[0]; c0 = lattice->param.C_in; D = (1./3.)*( lattice->param.tau[1] - .5); c2 = lattice->macro_vars[1][n+1].rho; c = (v*c0 + D*c2)/( D + v); } else { printf( "%s (%d) >> ERROR: " "constcon_w_in = %d type BC not valid. Exiting!\n", __FILE__,__LINE__,lattice->param.constcon_w_in); process_exit(1); } } else { c = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( c - ( ftemp[0] + ftemp[2] + ftemp[4] + ftemp[3])); ftemp[1] = (1./8.)*rho; } else { rho = 6.*( c - ( ftemp[0] + ftemp[2] + ftemp[4] + ftemp[3] + ftemp[6] + ftemp[7])); #if 0 ftemp[1] = (1./9.)*rho; ftemp[5] = (1./36.)*rho; ftemp[8] = (1./36.)*rho; #else ftemp[1] = (1./6.)*rho*lattice->pdf[0][n].ftemp[1] /(lattice->pdf[0][n].ftemp[1] + lattice->pdf[0][n].ftemp[5] + lattice->pdf[0][n].ftemp[8]); ftemp[5] = (1./6.)*rho*lattice->pdf[0][n].ftemp[5] /(lattice->pdf[0][n].ftemp[1] + lattice->pdf[0][n].ftemp[5] + lattice->pdf[0][n].ftemp[8]); ftemp[8] = (1./6.)*rho*lattice->pdf[0][n].ftemp[8] /(lattice->pdf[0][n].ftemp[1] + lattice->pdf[0][n].ftemp[5] + lattice->pdf[0][n].ftemp[8]); #endif } } /* if( 0 || !(*bc_type && BC_SOLID_NODE)) */ else // Solid node { //printf( // "%s (%d) >> constcon_w_in: Skipping n = %d. " // "(bc_type=%d) \n", // __FILE__, __LINE__, n, *bc_type); } /* if( 0 || !(*bc_type && BC_SOLID_NODE)) else */ n += lattice->param.LX; ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; bc_type += ( sizeof(struct bc_struct)/8)*lattice->param.LX; j++; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constcon_w_in ) */ // }}} // C O N S T C O N C E A S T O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant conc east outflow // -- Constant concentration boundary on east side using outflow value. if( lattice->param.constcon_e_out) { //printf("%s %d -- constcon_e_out\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; n = get_LX(lattice)-1; j = 0; while( ftemp < ftemp_end) { // East, Outflow if( 1)//( j>0 && j<get_LX(lattice)-1) && is_not_solid_node(lattice, subs, n)) { if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { if(lattice->param.constcon_e_out==1) { //c = lattice->param.C_in; c = lattice->param.C_out; } else if(lattice->param.constcon_e_out==3) { // // (-D*(dC/dx) + v*C) = v*C0 ==> // // c = (v*c0 + D*c2)/( D + v) // v = lattice->macro_vars[0][n].u[0]; c0 = lattice->param.C_out; D = (1./3.)*( lattice->param.tau[1] - .5); c2 = lattice->macro_vars[1][n-1].rho; c = (v*c0 + D*c2)/( D + v); } else { printf( "%s (%d) >> ERROR: " "constcon_e_out = %d type BC not valid. Exiting!\n", __FILE__,__LINE__,lattice->param.constcon_e_out); process_exit(1); } } else { c = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( c - ( ftemp[0] + ftemp[2] + ftemp[4] + ftemp[1])); ftemp[3] = (1./8.)*rho; } else { rho = 6.*( c - ( ftemp[0] + ftemp[2] + ftemp[4] + ftemp[1] + ftemp[5] + ftemp[8])); ftemp[3] = (1./9.)*rho; ftemp[7] = (1./36.)*rho; ftemp[6] = (1./36.)*rho; } } ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; n+=get_LX(lattice); j++; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constcon_e_out) */ // }}} // C O N S T C O N C W E S T O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant conc west outflow // -- Constant concentration boundary on west side with outflow value. if( lattice->param.constcon_w_out) { //printf("bcs() %s %d >> constcon_w_out\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][(lattice->param.LY+1)*lattice->param.LX].ftemp; while( ftemp < ftemp_end) { // West, Outflow if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { c = lattice->param.C_out; } else { c = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( c - ( ftemp[0] + ftemp[2] + ftemp[4] + ftemp[3])); ftemp[1] = (1./8.)*rho; } else { rho = 6.*( c - ( ftemp[0] + ftemp[2] + ftemp[4] + ftemp[3] + ftemp[6] + ftemp[7])); ftemp[1] = (1./9.)*rho; ftemp[5] = (1./36.)*rho; ftemp[8] = (1./36.)*rho; } ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } /* while( ftemp < ftemp_end) */ } /* if( constcon_w_out) */ // }}} // C O N S T F L U X E A S T I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant flux east inflow // -- Constant flux boundary on east side with inflow value. if( lattice->param.constflx_e_in ) { //printf("%s %d -- constflx_e_in\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; while( ftemp < ftemp_end) { // East, Inflow if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { u = lattice->param.u_sigma_in; } else { u = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( u + ftemp[1]); ftemp[3] = (1./ 8.)*rho; } else { rho = 6.*( u + ftemp[1] + ftemp[5] + ftemp[8]); ftemp[3] = (1./ 9.)*rho; ftemp[7] = (1./36.)*rho; ftemp[6] = (1./36.)*rho; } ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constflx_e_in ) */ // }}} // C O N S T F L U X W E S T I N B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant flux west inflow // -- Constant flux boundary on west side with inflow value. if( lattice->param.constflx_w_in ) { //printf("bcs() %s %d >> constflx_w_in\n", __FILE__, __LINE__); n = 0; ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][(lattice->param.LY+1)*lattice->param.LX].ftemp; while( ftemp < ftemp_end) { // West, Inflow if( lattice->param.constflx_w_in==1) { if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { u = lattice->param.u_sigma_in; } else { u = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( u + ftemp[3]); ftemp[1] = (1./8.)*rho; } else { rho = 6.*( u + ftemp[7] + ftemp[3] + ftemp[6]); ftemp[1] = (1./9.)*rho; ftemp[5] = (1./36.)*rho; ftemp[8] = (1./36.)*rho; } } else if( lattice->param.constflx_w_in==3) { v = lattice->macro_vars[0][n].u[0]; if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { c0 = lattice->param.C_in; } else { c0 = 0.; } rho = 6.*( c0 - ftemp[0] - ftemp[2] - ftemp[4] - (1.-1./v)*( ftemp[3] + ftemp[6] + ftemp[7])) / (1.+1./v); ftemp[1] = (1./9.)*rho; ftemp[5] = (1./36.)*rho; ftemp[8] = (1./36.)*rho; } else { printf( "%s (%d) >> ERROR: " "constflx_w_in = %d type BC not valid. Exiting!\n", __FILE__,__LINE__,lattice->param.constflx_w_in); process_exit(1); } n += lattice->param.LX; ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constflx_w_in ) */ // }}} // C O N S T F L U X E A S T O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant flux east outflow // -- Constant flux boundary on east side with outflow value. if( lattice->param.constflx_e_out) { //printf("%s %d -- constflx_e_out\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; while( ftemp < ftemp_end) { // East, Outflow if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { u = lattice->param.u_sigma_out; } else { u = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( u + ftemp[1]); ftemp[3] = (1./8.)*rho; } else { rho = 6.*( u + ftemp[1] + ftemp[5] + ftemp[8]); ftemp[3] = (1./9.)*rho; ftemp[7] = (1./36.)*rho; ftemp[6] = (1./36.)*rho; } ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constflx_e_out) */ // }}} // C O N S T F L U X W E S T O U T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // constant flux west outflow // -- Constant flux boundary on west side with outflow value. if( lattice->param.constflx_w_out) { //printf("bcs() %s %d >> constflx_w_out\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][(lattice->param.LY+1)*lattice->param.LX].ftemp; while( ftemp < ftemp_end) { // West, Outflow if( lattice->time >= lattice->param.sigma_start && lattice->time <= lattice->param.sigma_stop) { u = lattice->param.u_sigma_out; } else { u = 0.; } if( lattice->param.simple_diffusion) { rho = 8.*( u + ftemp[3]); ftemp[1] = (1./8.)*rho; } else { rho = 6.*( u + ftemp[7] + ftemp[3] + ftemp[6]); ftemp[1] = (1./9.)*rho; ftemp[5] = (1./36.)*rho; ftemp[8] = (1./36.)*rho; } ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.constflx_w_out) */ // }}} // Z E R O C O N C G R A D I E N T W E S T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // zero conc gradient west // -- Zero concentration gradient boundary on west side. if( lattice->param.zeroconcgrad_w) { //printf("bcs() %s %d >> zeroconcgrad_w_out\n", __FILE__, __LINE__); ftemp = lattice->pdf[subs][0].ftemp; ftemp_end = lattice->pdf[subs][(lattice->param.LY)*lattice->param.LX].ftemp; while( ftemp < ftemp_end) { // West if( 1 || is_not_solid_node( lattice, subs, n)) { // Copy from the adjacent interior neighbor values for the // unknown distributions. ftemp[1] = ftemp[ 1 + (sizeof(struct pdf_struct)/8)]; ftemp[5] = ftemp[ 5 + (sizeof(struct pdf_struct)/8)]; ftemp[8] = ftemp[ 8 + (sizeof(struct pdf_struct)/8)]; if( lattice->param.zeroconcgrad_full) { // Copy all the rest of the distribution functions from the adjacent // interior neighbor. ftemp[0] = ftemp[ 0 + (sizeof(struct pdf_struct)/8)]; ftemp[2] = ftemp[ 2 + (sizeof(struct pdf_struct)/8)]; ftemp[3] = ftemp[ 3 + (sizeof(struct pdf_struct)/8)]; ftemp[4] = ftemp[ 4 + (sizeof(struct pdf_struct)/8)]; ftemp[6] = ftemp[ 6 + (sizeof(struct pdf_struct)/8)]; ftemp[7] = ftemp[ 7 + (sizeof(struct pdf_struct)/8)]; } } /* if( 0 || !( (*bc_type) && BC_SOLID_NODE)) */ else // Solid node { // TODO: What? } /* if( 0 || !( (*bc_type) && BC_SOLID_NODE)) else */ ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.zerograd_s) */ // }}} // Z E R O C O N C G R A D I E N T E A S T B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // zero conc gradient east // -- Zero concentration gradient boundary on east side. if( lattice->param.zeroconcgrad_e) { //printf("bcs() %s %d >> zeroconcgrad_n\n", __FILE__, __LINE__); n = lattice->param.LX-1; ftemp = lattice->pdf[subs][lattice->param.LX-1].ftemp; ftemp_end = lattice->pdf[subs][lattice->NumNodes].ftemp; while( ftemp < ftemp_end) { // East bc_type = &( lattice->bc[0][n].bc_type); if( 1 || is_not_solid_node( lattice, subs, n)) { // Copy from the adjacent interior neighbor values for the // unknown distributions. ftemp[3] = ftemp[ 3 - (sizeof(struct pdf_struct)/8)]; ftemp[6] = ftemp[ 6 - (sizeof(struct pdf_struct)/8)]; ftemp[7] = ftemp[ 7 - (sizeof(struct pdf_struct)/8)]; if( lattice->param.zeroconcgrad_full) { // Copy all the rest of the distribution functions from the adjacent // interior neighbor. ftemp[0] = ftemp[ 0 - (sizeof(struct pdf_struct)/8)]; ftemp[1] = ftemp[ 1 - (sizeof(struct pdf_struct)/8)]; ftemp[2] = ftemp[ 2 - (sizeof(struct pdf_struct)/8)]; ftemp[4] = ftemp[ 4 - (sizeof(struct pdf_struct)/8)]; ftemp[5] = ftemp[ 5 - (sizeof(struct pdf_struct)/8)]; ftemp[8] = ftemp[ 8 - (sizeof(struct pdf_struct)/8)]; } } /* if( 0 || !( (*bc_type) && BC_SOLID_NODE)) */ else // Solid node { // TODO: What? } /* if( 0 || !( (*bc_type) && BC_SOLID_NODE)) else */ if( is_first_timestep( lattice) && adjust_zero_flux_for_btc( lattice)) { // To apply a zero gradient and measure the breakthrough curve there // properly, the last three columns of the domain need to have the same // solids pattern. The following artificially enforces that pattern. // Alternatively, the user may leave three empty columns at the end of // the domain. if( is_solid_node( lattice, subs, n-2) && is_not_solid_node( lattice, subs, n-1) ) { make_solid_node( lattice,/*subs*/0, n-1); make_solid_node( lattice,/*subs*/1, n-1); } if( is_solid_node( lattice, subs, n-1) && is_not_solid_node( lattice, subs, n ) ) { make_solid_node( lattice,/*subs*/0, n ); make_solid_node( lattice,/*subs*/1, n ); } if( is_not_solid_node( lattice, subs, n-1) && is_solid_node( lattice, subs, n) ) { make_solid_node( lattice,/*subs*/0, n-1); make_solid_node( lattice,/*subs*/1, n-1); } if( is_not_solid_node( lattice, subs, n-2) && is_solid_node( lattice, subs, n-1) ) { make_solid_node( lattice,/*subs*/0, n-2); make_solid_node( lattice,/*subs*/1, n-2); } } n += lattice->param.LX; ftemp += ( sizeof(struct pdf_struct)/8)*lattice->param.LX; } /* while( ftemp < ftemp_end) */ } /* if( lattice->param.zerograd_n) */ // }}} #if 0 // C O R N E R S //############################################################################ // S O U T H W E S T C O R N E R B C {{{ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // south west corner // -- Average adjacent cells (east side and north side cells) // -- This is only for when boundary conditions are applied on the // adjecent sides, south and west, so that the corners overlap. if( (id==0) && ( 1 || ( ( lattice->param.constcon_w_out ||lattice->param.constcon_w_in ||lattice->param.constflx_w_out ||lattice->param.constflx_w_in ||lattice->param.zeroconcgrad_w ) && ( lattice->param.constcon_s_out ||lattice->param.constcon_s_in ||lattice->param.constflx_s_out ||lattice->param.constflx_s_in ||lattice->param.zeroconcgrad_s ) ) ) ) { printf("BING! SW corner..."); ftemp = &(lattice->pdf[subs][0].ftemp[0]); for( a=0; a<9; a++) { ftemp[a] = 0.; } } // }}} #endif #if SIGMA_BULK_FLAG } #endif #endif /* INAMURO_SIGMA_COMPONENT */ } /* void bcs( lattice_ptr lattice) */ // }}} #endif #endif // P R O C E S S _ B C S {{{ //############################################################################## // void process_bcs( char *filename, int **bcs) // // P R O C E S S B C S // // - Process boundary condition information based on flags read // from params.in . // // - More specifically, make sure that the requested boundary conditions // are not contradictory or incompatible with current implementation. // // - And set the periodicity flags. // void process_bcs( lattice_ptr lattice, int subs) { FILE *in; char filename[1024]; int i, j, n, m; int ei, ej; int pad, bytes_per_row; char k; char b, g, r; struct bitmap_file_header bmfh; struct bitmap_info_header bmih; struct rgb_quad rgb; int *int_ptr; short int *short_int_ptr; int *width_ptr; int *height_ptr; short int *bitcount_ptr; #if SAY_HI printf("process_bcs() -- Hi!\n"); #endif /* SAY_HI */ //############################################################################ // // Report any incompatible boundary conditions. // If there are incompatible bcs, process_exit after issuing message. // #if 0 // Want to allow mix of velocity and pressure boundaries. // Can't have coincident pressure and velocity boundaries. //---------------------------------------------------------------------------- // North if( lattice->param.pressure_n_in[subs] && ( lattice->param.velocity_n_in[subs] || lattice->param.velocity_n_out[subs])) { printf("ERROR: " "Coincident pressure and velocity north boundaries. " "Exiting!\n"); process_exit(1); } // South if( lattice->param.pressure_s_in[subs] && ( lattice->param.velocity_s_in[subs] || lattice->param.velocity_s_out[subs])) { printf("ERROR: " "Coincident pressure and velocity south boundaries. " "Exiting!\n"); process_exit(1); } // North if( lattice->param.pressure_n_out[subs] && ( lattice->param.velocity_n_out[subs] || lattice->param.velocity_n_in[subs] )) { printf("ERROR: " "Coincident pressure and velocity north boundaries. " "Exiting!\n"); process_exit(1); } // South if( lattice->param.pressure_s_out[subs] && ( lattice->param.velocity_s_out[subs] || lattice->param.velocity_s_in[subs] )) { printf("ERROR: " "Coincident pressure and velocity south boundaries. " "Exiting!\n"); process_exit(1); } // East if( lattice->param.pressure_e_in[subs] && ( lattice->param.velocity_e_in[subs] || lattice->param.velocity_e_out[subs])) { printf("ERROR: " "Coincident pressure and velocity east boundaries. " "Exiting!\n"); process_exit(1); } // West if( lattice->param.pressure_w_in[subs] && ( lattice->param.velocity_w_in[subs] || lattice->param.velocity_w_out[subs])) { printf("ERROR: " "Coincident pressure and velocity west boundaries. " "Exiting!\n"); process_exit(1); } // East if( lattice->param.pressure_e_out[subs] && ( lattice->param.velocity_e_out[subs] || lattice->param.velocity_e_in[subs] )) { printf("ERROR: " "Coincident pressure and velocity east boundaries. " "Exiting!\n"); process_exit(1); } // West if( lattice->param.pressure_w_out[subs] && ( lattice->param.velocity_w_out[subs] || lattice->param.velocity_w_in[subs] )) { printf("ERROR: " "Coincident pressure and velocity west boundaries. " "Exiting!\n"); process_exit(1); } // Can't have both inflow and outflow condition on same boundary. //---------------------------------------------------------------------------- // North if( lattice->param.pressure_n_in[subs] && lattice->param.pressure_n_out[subs]) { printf("ERROR: " "Coincident inflow and outflow condition on north boundary. " "Exiting!\n"); process_exit(1); } // South if( lattice->param.pressure_s_in[subs] && lattice->param.pressure_s_out[subs]) { printf("ERROR: " "Coincident inflow and outflow condition on south boundary. " "Exiting!\n"); process_exit(1); } // North if( lattice->param.velocity_n_in[subs] && lattice->param.velocity_n_out[subs]) { printf("ERROR: " "Coincident inflow and outflow condition on north boundary. " "Exiting!\n"); process_exit(1); } // South if( lattice->param.velocity_s_in[subs] && lattice->param.velocity_s_out[subs]) { printf("ERROR: " "Coincident inflow and outflow condition on south boundary. " "Exiting!\n"); process_exit(1); } // East if( lattice->param.pressure_e_in[subs] && lattice->param.pressure_e_out[subs]) { printf("ERROR: " "Coincident inflow and outflow condition on east boundary. " "Exiting!\n"); process_exit(1); } // West if( lattice->param.pressure_w_in[subs] && lattice->param.pressure_w_out[subs]) { printf("ERROR: " "Coincident inflow and outflow condition on west boundary. " "Exiting!\n"); process_exit(1); } // East if( lattice->param.velocity_e_in[subs] && lattice->param.velocity_e_out[subs]) { printf("ERROR: " "Coincident inflow and outflow condition on east boundary. " "Exiting!\n"); process_exit(1); } // West if( lattice->param.velocity_w_in[subs] && lattice->param.velocity_w_out[subs]) { printf("ERROR: " "Coincident inflow and outflow condition on west boundary. " "Exiting!\n"); process_exit(1); } #endif //############################################################################ // // Update periodicity settings. // // North/South if( lattice->param.pressure_n_in[subs] || lattice->param.pressure_n_out[subs] || lattice->param.velocity_n_in[subs] || lattice->param.velocity_n_out[subs] ) { if( !( lattice->param.pressure_s_in[subs] || lattice->param.pressure_s_out[subs] || lattice->param.velocity_s_in[subs] || lattice->param.velocity_s_out[subs])) { // TODO: Need to prohibit flow boundaries on only one end of the domain? //process_exit(1); } else { lattice->periodic_y[subs] = 0; } } // South/North if( lattice->param.pressure_s_in[subs] || lattice->param.pressure_s_out[subs] || lattice->param.velocity_s_in[subs] || lattice->param.velocity_s_out[subs] ) { if( !( lattice->param.pressure_n_in[subs] || lattice->param.pressure_n_out[subs] || lattice->param.velocity_n_in[subs] || lattice->param.velocity_n_out[subs])) { // TODO: Need to prohibit flow boundaries on only one end of the domain? //process_exit(1); } else { lattice->periodic_y[subs] = 0; } } // East/West if( lattice->param.pressure_e_in[subs] || lattice->param.pressure_e_out[subs] || lattice->param.velocity_e_in[subs] || lattice->param.velocity_e_out[subs] ) { if( !( lattice->param.pressure_w_in[subs] || lattice->param.pressure_w_out[subs] || lattice->param.velocity_w_in[subs] || lattice->param.velocity_w_out[subs])) { // TODO: Need to prohibit flow boundaries on only one end of the domain? //process_exit(1); } else { lattice->periodic_x[subs] = 0; } } // West/East if( lattice->param.pressure_w_in[subs] || lattice->param.pressure_w_out[subs] || lattice->param.velocity_w_in[subs] || lattice->param.velocity_w_out[subs] ) { if( !( lattice->param.pressure_e_in[subs] || lattice->param.pressure_e_out[subs] || lattice->param.velocity_e_in[subs] || lattice->param.velocity_e_out[subs])) { // TODO: Need to prohibit flow boundaries on only one end of the domain? //process_exit(1); } else { lattice->periodic_x[subs] = 0; } } if( lattice->param.pressure_n_in[subs] == 2) { // Read from file. } #if SAY_HI printf("process_bcs() -- Bye!\n"); #endif /* SAY_HI */ printf("\n"); } /* void process_bcs( lattice_ptr lattice, int subs) */ // }}} //############################################################################## // vim: foldmethod=marker:foldlevel=0
111pjb-one
src/bcs.c
C
gpl3
130,360
void collide( lattice_ptr lattice) { double *f; double omega; int bc_type; int n, a; int subs; double ns; double *ftemp, *feq; double *nsterm; int i, j; int ip, jp, in, jn; int LX = lattice->param.LX, LY = lattice->param.LY; #if SAY_HI printf("collide() -- Hi!\n"); #endif /* SAY_HI */ for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) { for( n=0; n<lattice->NumNodes; n++) { feq = lattice->pdf[subs][n].feq; f = lattice->pdf[subs][n].f; ftemp = lattice->pdf[subs][n].ftemp; bc_type = lattice->bc[subs][n].bc_type; #if ZHANG_AND_CHEN_ENERGY_TRANSPORT force = lattice->force[subs][n].force; #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ if( !( bc_type & BC_SOLID_NODE)) { // C O L L I D E // f = ftemp - (1/tau[subs])( ftemp - feq) for( a=0; a<=8; a++) { #if 1 f[a] = ftemp[a] - ( ( ftemp[a] / lattice->param.tau[subs] ) - ( feq[a] / lattice->param.tau[subs] ) ); #else f[a] = ftemp[a] - ( ( ftemp[a] ) - ( feq[a] ) ) / lattice->param.tau[subs]; #endif } /* for( a=0; a<=8; a++) */ #if ZHANG_AND_CHEN_ENERGY_TRANSPORT if( subs==0) { // // Add the body force term, equation (8), // // f_i = f_i + \Delta f_i // // = f_i + \frac{w_i}{T_0} c_i \dot F // // Assuming the weights, w_i, are the ones from compute_feq. // // Zhang & Chen state T_0 to be 1/3 for D3Q19. The same in D2Q9. // f[1] += .00032*(vx[1]*3.*2.*force[0]); f[2] += .00032*(vy[2]*3.*2.*force[1]); f[3] += .00032*(vx[3]*3.*2.*force[0]); f[4] += .00032*(vy[4]*3.*2.*force[1]); f[5] += .00032*( 3.*( vx[5]*force[0] + vy[5]*force[1])); f[6] += .00032*( 3.*( vx[6]*force[0] + vy[6]*force[1])); f[7] += .00032*( 3.*( vx[7]*force[0] + vy[7]*force[1])); f[8] += .00032*( 3.*( vx[8]*force[0] + vy[8]*force[1])); } #endif /* ZHANG_AND_CHEN_ENERGY_TRANSPORT */ #if PUKE_NEGATIVE_DENSITIES for( a=0; a<=8; a++) { if( *f < 0.) { printf("\n"); printf( "collide() -- Node %d (%d,%d), subs %d, " "has negative density %20.17f " "in direction %d " "at timestep %d. Exiting!\n", n, n%lattice->param.LX, n/lattice->param.LX, subs, f[a], a, lattice->time ); printf("\n"); process_exit(1); } } /* for( a=0; a<=8; a++) */ #endif /* PUKE_NEGATIVE_DENSITIES */ } /* if( !( bc_type & BC_SOLID_NODE)) */ else // bc_type & BC_SOLID_NODE { // B O U N C E B A C K if( lattice->param.bc_slip_north && n >= lattice->NumNodes - lattice->param.LX) { // Slip condition on north boundary. /* // A B C // \|/ \|/ // D-o-E --> D-o-E // /|\ /|\ // A B C */ f[1] = ftemp[1]; f[2] = ftemp[4]; f[3] = ftemp[3]; f[4] = ftemp[2]; f[5] = ftemp[8]; f[6] = ftemp[7]; f[7] = ftemp[6]; f[8] = ftemp[5]; } /* if( lattice->param.bc_slip_north && ... ) */ else { if( subs==0) { // Usual non-slip bounce-back condition. /* // A B C H G F // \|/ \|/ // D-o-E --> E-o-D // /|\ /|\ // F G H C B A */ f[1] = ftemp[3]; f[2] = ftemp[4]; f[3] = ftemp[1]; f[4] = ftemp[2]; f[5] = ftemp[7]; f[6] = ftemp[8]; f[7] = ftemp[5]; f[8] = ftemp[6]; } /* if( subs==0) */ #if NUM_FLUID_COMPONENTS==2 else // subs==1 { #if INAMURO_SIGMA_COMPONENT if( lattice->param.bc_sigma_slip) { // // Slip BC for solute on side walls. // Will this make a difference on Taylor dispersion? // if( lattice->FlowDir == /*Vertical*/2) { if( /*west*/(n )%lattice->param.LX == 0 || /*east*/(n+1)%lattice->param.LX == 0) { // Slip condition on east/west boundary. /* // A B C C B A // \|/ \|/ // D-o-E --> E-o-D // /|\ /|\ // F G H H G F */ f[1] = ftemp[3]; f[2] = ftemp[2]; f[3] = ftemp[1]; f[4] = ftemp[4]; f[5] = ftemp[6]; f[6] = ftemp[5]; f[7] = ftemp[8]; f[8] = ftemp[7]; } } else if( lattice->FlowDir == /*Horizontal*/1) { if( /*north*/ n >= lattice->NumNodes - lattice->param.LX || /*south*/ n < lattice->param.LX ) { // Slip condition on north/south boundary. /* // A B C F G H // \|/ \|/ // D-o-E --> D-o-E // /|\ /|\ // F G H A B C */ f[1] = ftemp[1]; f[2] = ftemp[4]; f[3] = ftemp[3]; f[4] = ftemp[2]; f[5] = ftemp[8]; f[6] = ftemp[7]; f[7] = ftemp[6]; f[8] = ftemp[5]; } else { // ERROR: Solid exists somewhere other than as side walls. printf("%s (%d) >> " "ERROR: " "bc_sigma_slip is on. " "FlowDir is determined to be horizontal. " "Encountered solid node somewhere other than side walls. " "That situation is not supported. " "Exiting!", __FILE__, __LINE__); process_exit(1); } } else { printf("%s (%d) >> " "FlowDir is indeterminate. " "Cannot apply slip BC (bc_sigma_slip). " "Exiting!", __FILE__, __LINE__); process_exit(1); } } /* if( lattice->param.bc_sigma_slip) */ else { #endif /* INAMURO_SIGMA_COMPONENT */ // Usual non-slip bounce-back condition. /* // A B C H G F // \|/ \|/ // D-o-E --> E-o-D // /|\ /|\ // F G H C B A */ f[1] = ftemp[3]; f[2] = ftemp[4]; f[3] = ftemp[1]; f[4] = ftemp[2]; f[5] = ftemp[7]; f[6] = ftemp[8]; f[7] = ftemp[5]; f[8] = ftemp[6]; #if INAMURO_SIGMA_COMPONENT } /* if( lattice->param.bc_sigma_slip) else */ #endif /* INAMURO_SIGMA_COMPONENT */ } /* if( subs==0) else*/ #endif /* NUM_FLUID_COMPONENTS==2 */ } /* if( lattice->param.bc_slip_north && ... ) else */ } /* if( !( bc_type & BC_SOLID_NODE)) else */ } /* for( n=0; n<lattice_NumNodes; n++) */ if( INAMURO_SIGMA_COMPONENT!=0 || subs==0) { // Need separate temp space for this? nsterm = (double*)malloc( ( 9*get_LX(lattice) *get_LX(lattice))*sizeof(double)); // Compute the solid density term for fluid component. for( n=0; n<lattice->NumNodes; n++) { //nsterm = lattice->pdf[subs][n].nsterm; bc_type = lattice->bc [subs][n].bc_type; i = n%LX; j = n/LX; jp = ( j<LY-1)?( j+1):( 0 ); jn = ( j>0 )?( j-1):( LY-1); ip = ( i<LX-1)?( i+1):( 0 ); in = ( i>0 )?( i-1):( LX-1); if( !( bc_type & BC_SOLID_NODE)) { if( lattice->param.ns_flag == 0) { ns = lattice->param.ns; /* 1 */ nsterm[9*n+1] = ns*( lattice->pdf[subs][ j *LX + ip].f[3] - lattice->pdf[subs][ j *LX + i ].f[1]); /* 2 */ nsterm[9*n+2] = ns*( lattice->pdf[subs][ jp*LX + i ].f[4] - lattice->pdf[subs][ j *LX + i ].f[2]); /* 3 */ nsterm[9*n+3] = ns*( lattice->pdf[subs][ j *LX + in].f[1] - lattice->pdf[subs][ j *LX + i ].f[3]); /* 4 */ nsterm[9*n+4] = ns*( lattice->pdf[subs][ jn*LX + i ].f[2] - lattice->pdf[subs][ j *LX + i ].f[4]); /* 5 */ nsterm[9*n+5] = ns*( lattice->pdf[subs][ jp*LX + ip].f[7] - lattice->pdf[subs][ j *LX + i ].f[5]); /* 6 */ nsterm[9*n+6] = ns*( lattice->pdf[subs][ jp*LX + in].f[8] - lattice->pdf[subs][ j *LX + i ].f[6]); /* 7 */ nsterm[9*n+7] = ns*( lattice->pdf[subs][ jn*LX + in].f[5] - lattice->pdf[subs][ j *LX + i ].f[7]); /* 8 */ nsterm[9*n+8] = ns*( lattice->pdf[subs][ jn*LX + ip].f[6] - lattice->pdf[subs][ j *LX + i ].f[8]); } else /* ns_flag==1 || ns_flag==2 */ { // Variable solid density. ns = lattice->ns[n].ns; //printf("%s %d >> ns = %f\n",__FILE__,__LINE__,ns); /* 1 */ nsterm[9*n+1] = ns*( lattice->pdf[subs][ j *LX + ip].f[3] - lattice->pdf[subs][ j *LX + i ].f[1]); /* 2 */ nsterm[9*n+2] = ns*( lattice->pdf[subs][ jp*LX + i ].f[4] - lattice->pdf[subs][ j *LX + i ].f[2]); /* 3 */ nsterm[9*n+3] = ns*( lattice->pdf[subs][ j *LX + in].f[1] - lattice->pdf[subs][ j *LX + i ].f[3]); /* 4 */ nsterm[9*n+4] = ns*( lattice->pdf[subs][ jn*LX + i ].f[2] - lattice->pdf[subs][ j *LX + i ].f[4]); /* 5 */ nsterm[9*n+5] = ns*( lattice->pdf[subs][ jp*LX + ip].f[7] - lattice->pdf[subs][ j *LX + i ].f[5]); /* 6 */ nsterm[9*n+6] = ns*( lattice->pdf[subs][ jp*LX + in].f[8] - lattice->pdf[subs][ j *LX + i ].f[6]); /* 7 */ nsterm[9*n+7] = ns*( lattice->pdf[subs][ jn*LX + in].f[5] - lattice->pdf[subs][ j *LX + i ].f[7]); /* 8 */ nsterm[9*n+8] = ns*( lattice->pdf[subs][ jn*LX + ip].f[6] - lattice->pdf[subs][ j *LX + i ].f[8]); } } /* if( !( *bc_type++ & BC_SOLID_NODE)) */ } /* for( n=0; n<lattice_NumNodes; n++) */ for( n=0; n<lattice->NumNodes; n++) { f = lattice->pdf[subs][n].f; bc_type = lattice->bc [subs][n].bc_type; if( !( bc_type & BC_SOLID_NODE)) { for( a=1; a<9; a++) { //lattice->pdf[subs][n].nsterm[a] = f[a]; f[a] += nsterm[9*n+a]; } /* for( a=1; a<9; a++) */ } /* if( !( bc_type & BC_SOLID_NODE)) */ } /* for( n=0; n<lattice->NumNodes; n++, f+=18) */ free( nsterm); } /* if( INAMURO_SIGMA_COMPONENT!=0 || subs==0) */ } /* for( subs=0; subs<NUM_FLUID_COMPONENTS; subs++) */ #if SAY_HI printf("collide() -- Bye!\n"); #endif /* SAY_HI */ } /* void collide( lattice_ptr lattice) */
111pjb-one
src/a.c
C
gpl3
11,509
//############################################################################## // // Copyright (C), 2005, Michael Sukop and Danny Thorne // // bc_flags.h // // - BC preprocessor flags for lb2d_prime. // #ifndef BC_FLAGS_H #define BC_FLAGS_H // BC_XXX flags are for boundary conditions. // Used to set struct bc_struct::bc_type. // Should be powers of two so that multiple boundary types can be // checked easily via bitwise and (&). // For instance, bc_type & BC_SOLID_NODE & BC_SLIP_NODE to specify // a slip boundary. (Non-slip is the default for solid boundaries.) #define BC_SOLID_NODE 0x00000001 #define BC_FLUID_NODE 0x00000000 #define BC_SLIP_NODE 0x80000000 #define BC_FILM_NODE 0x40000000 #define BC_PRESSURE_N_IN 0x00000010 #define BC_PRESSURE_S_IN 0x00000020 #define BC_PRESSURE_E_IN 0x00000040 #define BC_PRESSURE_W_IN 0x00000080 #define BC_PRESSURE_N_OUT 0x00000100 #define BC_PRESSURE_S_OUT 0x00000200 #define BC_PRESSURE_E_OUT 0x00000400 #define BC_PRESSURE_W_OUT 0x00000800 #define BC_VELOCITY_N_IN 0x00001000 #define BC_VELOCITY_S_IN 0x00002000 #define BC_VELOCITY_E_IN 0x00004000 #define BC_VELOCITY_W_IN 0x00008000 #define BC_VELOCITY_N_OUT 0x00010000 #define BC_VELOCITY_S_OUT 0x00020000 #define BC_VELOCITY_E_OUT 0x00040000 #define BC_VELOCITY_W_OUT 0x00080000 #endif /* BC_FLAGS_H */
111pjb-one
src/bc_flags.h
C
gpl3
1,338
pushd src cp flags_taylor_pressure_x_infile.h flags.h popd make ./lb2d_prime ./in/params_taylor_pressure_x_infile.in
111pjb-one
taylor_pressure_x_infile.sh
Shell
gpl3
117
pushd src cp flags_taylor_pressure_y_infile.h flags.h popd make ./lb2d_prime ./in/params_taylor_pressure_y_infile.in
111pjb-one
taylor_pressure_y_infile.sh
Shell
gpl3
117
package com.besttone.app; import android.content.ContentValues; import android.content.SearchRecentSuggestionsProvider; import android.database.Cursor; import android.net.Uri; public class SuggestionProvider extends SearchRecentSuggestionsProvider { public static final String AUTHORITY = "com.besttone.app.114SuggestionProvider"; public static final String[] COLUMNS; public static final int MODE = DATABASE_MODE_QUERIES; private static String sDatabaseName = "suggestions.db"; private static int totalRecord; private final int MAXCOUNT = 20; static { String[] arrayOfString = new String[4]; arrayOfString[0] = "_id"; arrayOfString[1] = "display1"; arrayOfString[2] = "query"; arrayOfString[3] = "date"; COLUMNS = arrayOfString; } public SuggestionProvider() { //super(contex, AUTHORITY, MODE); setupSuggestions(AUTHORITY, MODE); } private Object[] columnValuesOfWord(int paramInt, String paramString1, String paramString2) { Object[] arrayOfObject = new Object[4]; arrayOfObject[0] = Integer.valueOf(paramInt); arrayOfObject[1] = paramString1; arrayOfObject[2] = paramString2; arrayOfObject[3] = paramString1; return arrayOfObject; } public Uri insert(Uri uri, ContentValues values) { String selection = "query=?"; String[] selectionArgs = new String[1]; selectionArgs[0] = "没有搜索记录"; super.delete(uri, selection, selectionArgs); Cursor localCursor = super.query(uri, COLUMNS, null, null, null); if (localCursor!=null && localCursor.getCount() == 0) { ContentValues localContentValues = new ContentValues(); localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[0], Integer.valueOf(2)); localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[1], Long.valueOf(System.currentTimeMillis())); localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[2], "清空搜索记录"); localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[3], "清空搜索记录"); super.insert(uri, localContentValues); } values.put("date", Long.valueOf(System.currentTimeMillis())); Uri localUri = super.insert(uri, values); return localUri; } public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Cursor localCursor = super.query(uri, projection, selection, selectionArgs, sortOrder); Object localObject; if (selectionArgs == null || selectionArgs.length == 0) if (localCursor.getCount() == 0) { ContentValues localContentValues = new ContentValues(); localContentValues .put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[0], Integer.valueOf(1)); localContentValues .put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[1], Long.valueOf(System.currentTimeMillis())); localContentValues .put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[2], "没有搜索记录"); localContentValues .put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[3], "没有搜索记录"); super.insert(uri, localContentValues); } localCursor = super.query(uri, projection, selection, selectionArgs, sortOrder); totalRecord = localCursor.getCount(); if (totalRecord > 20) truncateHistory(uri, -20 + totalRecord); return localCursor; } protected void truncateHistory(Uri paramUri, int paramInt) { if (paramInt < 0) throw new IllegalArgumentException(); String str = null; if (paramInt > 0) try { str = "_id IN (SELECT _id FROM suggestions ORDER BY date ASC LIMIT " + String.valueOf(paramInt) + " OFFSET 1)"; delete(paramUri, str, null); return; } catch (RuntimeException localRuntimeException) { } } }
114ch
version_without_location/src/com/besttone/app/SuggestionProvider.java
Java
asf20
3,994
package com.besttone.http; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.MarshalBase64; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import org.xmlpull.v1.XmlPullParser; import com.besttone.search.Client; import com.besttone.search.ServerListener; import com.besttone.search.model.ChResultInfo; import com.besttone.search.model.OrgInfo; import com.besttone.search.model.RequestInfo; import com.besttone.search.util.Constants; import com.besttone.search.util.XmlHelper; import android.util.Log; import android.util.Xml; public class WebServiceHelper { private static final String TAG = "WebServiceHelper"; //命名空间 private static final String serviceNameSpace="http://ws.besttone.com/"; //调用方法(获得支持的城市) //private static final String methodName="SearchChInfo"; private static final String methodName="searchChNewInfo"; private ChResultInfo resultInfo; private int i = 0; private List<Map<String, Object>> list; public static interface WebServiceListener { public void onWebServiceSuccess(); public void onWebServiceFailed(); } public void setmListener(WebServiceListener mListener) { this.mListener = mListener; } private WebServiceListener mListener; public List<Map<String, Object>> searchChInfo(RequestInfo rqInfo){ Long t1 = System.currentTimeMillis(); list = new LinkedList<Map<String, Object>>(); //返回的查询结果 String result =null; //实例化SoapObject对象 SoapObject request=new SoapObject(serviceNameSpace, methodName); //假设方法有参数的话,设置调用方法参数 String rqXml = XmlHelper.getRequestXml(rqInfo); request.addProperty("xml", rqXml); request.addProperty("name",Constants.chName); request.addProperty("key",Constants.chKey); //设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致) //获得序列化的Envelope SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER10); //设置是否调用的是dotNet开发的 envelope.dotNet = false; envelope.bodyOut=request; envelope.setOutputSoapObject(request); //注册Envelope (new MarshalBase64()).register(envelope); //构建传输对象,并指明WSDL文档URL //Android传输对象 HttpTransportSE transport=new HttpTransportSE(Constants.serviceURL); transport.debug=true; //调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象): String soapAction = serviceNameSpace+methodName; try { transport.call(soapAction, envelope); //解析返回数据 Object resultObj = envelope.getResponse(); result = resultObj.toString(); parseChInfo(result); } catch (Exception e) { e.printStackTrace(); Log.v(TAG, "获取XML出错"); } Long t2 = System.currentTimeMillis(); Log.v(TAG, "获取查号信息耗时"+(t2-t1)+"毫秒"); return list; } public void parseChInfo(String xmlString) { Map<String, Object> map = new HashMap<String, Object>(); InputStream inputStream=null; //获得XmlPullParser解析器 XmlPullParser xmlParser = Xml.newPullParser(); try { //得到文件流,并设置编码方式 xmlParser.setInput(new StringReader(xmlString)); //获得解析到的事件类别,这里有开始文档,结束文档,开始标签,结束标签,文本等等事件。 int evtType=xmlParser.getEventType(); List<OrgInfo> orgList = null; OrgInfo info = null; String propertyName = null; String propertyValue = null; //一直循环,直到文档结束 while(evtType!=XmlPullParser.END_DOCUMENT){ String tag = xmlParser.getName(); switch(evtType){ case XmlPullParser.START_TAG: //如果是river标签开始,则说明需要实例化对象了 if (tag.equalsIgnoreCase("SearchResult")) { resultInfo = new ChResultInfo(); break; } if (tag.equalsIgnoreCase("BDCDataSource")) { resultInfo.setSource(xmlParser.nextText()); break; } if (tag.equalsIgnoreCase("BDCSearchflag")) { resultInfo.setSearchFlag(xmlParser.nextText()); break; } if (tag.equalsIgnoreCase("ResultCount")) { String cnt = xmlParser.nextText(); break; } if (tag.equalsIgnoreCase("ResultTime")) { String time = xmlParser.nextText(); break; } if (tag.equalsIgnoreCase("SingleResult")) { map = new HashMap<String, Object>(); break; } if (tag.equalsIgnoreCase("propertyName")) { propertyName = xmlParser.nextText(); break; } if (tag.equalsIgnoreCase("propertyValue")) { propertyValue = xmlParser.nextText(); if(propertyName!=null && "产品序列号".equals(propertyName)) { // if(propertyValue!=null && !Constants.SPACE.equals(propertyValue)){ // info.setChId(Integer.valueOf(propertyValue)); // } if(propertyValue==null || Constants.SPACE.equals(propertyValue)) { propertyValue = Constants.SPACE; } map.put("chId", propertyValue); } if(propertyName!=null && "公司名称".equals(propertyName)) { if(propertyValue==null || Constants.SPACE.equals(propertyValue)) { propertyValue = Constants.SPACE; } map.put("name", propertyValue); } if(propertyName!=null && "首查电话".equals(propertyName)) { if(propertyValue==null || Constants.SPACE.equals(propertyValue)) { propertyValue = Constants.SPACE; } map.put("tel", propertyValue); } if(propertyName!=null && "地址".equals(propertyName)) { if(propertyValue==null || Constants.SPACE.equals(propertyValue)) { propertyValue = Constants.SPACE; } map.put("addr", propertyValue); } if(propertyName!=null && "ORG_ID".equals(propertyName)) { map.put("orgId", propertyValue); } if(propertyName!=null && "所属城市".equals(propertyName)) { map.put("city", Constants.getCity(propertyValue)); } if(propertyName!=null && "Region_Cede".equals(propertyName)) { map.put("regionCode", propertyValue); } if(propertyName!=null && "IS_DC".equals(propertyName)) { map.put("isDc", propertyValue); } if(propertyName!=null && "IS_DF".equals(propertyName)) { map.put("isDf", propertyValue); } if(propertyName!=null && "QYMP".equals(propertyName)) { map.put("isQymp", propertyValue); } propertyName = null; propertyValue = null; } break; case XmlPullParser.END_TAG: //如果遇到river标签结束,则把river对象添加进集合中 if (tag.equalsIgnoreCase("SingleResult")) { if(map.get("addr")==null) { map.put("addr", Constants.SPACE); } if(map.get("tel")==null) { map.put("tel", Constants.SPACE); } list.add(map); } break; default:break; } //如果xml没有结束,则导航到下一个river节点 evtType=xmlParser.next(); } } catch (Exception e) { e.printStackTrace(); Log.v(TAG, "xml解析出错"+e.getMessage()); } } public void sendRequest(final ServerListener listener, final RequestInfo rqInfo) { Client.getThreadPoolForRequest().execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { Thread.sleep(1000); } catch (Exception e) { } list = searchChInfo(rqInfo); listener.serverDataArrived(list, false); } }); } public ArrayList<String> getAssociateList(String key) { Long t1 = System.currentTimeMillis(); ArrayList<String> resultAssociateList = new ArrayList<String>(); // new ArrayList<String>(); //返回的查询结果 String result =null; //实例化SoapObject对象 SoapObject request=new SoapObject(serviceNameSpace, Constants.associate_method); //假设方法有参数的话,设置调用方法参数 StringBuilder sb = new StringBuilder(""); if (key != null) { sb.append("<ChKeyInpara>"); sb.append("<content><![CDATA[" + key + "]]></content>"); sb.append("</ChKeyInpara>"); } request.addProperty("xml", sb.toString()); request.addProperty("name",Constants.chName); request.addProperty("key",Constants.chKey); //设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致) //获得序列化的Envelope SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER10); //设置是否调用的是dotNet开发的 envelope.dotNet = false; envelope.bodyOut=request; envelope.setOutputSoapObject(request); //注册Envelope (new MarshalBase64()).register(envelope); //构建传输对象,并指明WSDL文档URL //Android传输对象 HttpTransportSE transport=new HttpTransportSE(Constants.serviceURL); transport.debug=true; //调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象): String soapAction = serviceNameSpace+Constants.associate_method; try { transport.call(soapAction, envelope); //解析返回数据 Object resultObj = envelope.getResponse(); result = resultObj.toString(); resultAssociateList = parseKeywordInfo(result); } catch (Exception e) { e.printStackTrace(); Log.v(TAG, "关键词联想获取出错"); } Long t2 = System.currentTimeMillis(); Log.v(TAG, "关键词联想获取耗时"+(t2-t1)+"毫秒"); // if(mListener!=null) // mListener.onWebServiceSuccess(); return resultAssociateList; } public ArrayList<String> parseKeywordInfo(String xmlString) { Map<String, Object> map = new HashMap<String, Object>(); ArrayList<String> resultList = new ArrayList<String>(); InputStream inputStream=null; //获得XmlPullParser解析器 XmlPullParser xmlParser = Xml.newPullParser(); try{ //得到文件流,并设置编码方式 xmlParser.setInput(new StringReader(xmlString)); //获得解析到的事件类别,这里有开始文档,结束文档,开始标签,结束标签,文本等等事件。 int evtType=xmlParser.getEventType(); // 一直循环,直到文档结束 while (evtType != XmlPullParser.END_DOCUMENT) { String tag = xmlParser.getName(); switch (evtType) { case XmlPullParser.START_TAG: // 如果是river标签开始,则说明需要实例化对象了 if (tag.equalsIgnoreCase("ChKeyResult")) { map = new HashMap<String, Object>(); break; } if (tag.equalsIgnoreCase("resultNum")) { String resultNum = xmlParser.nextText(); map.put("resultNum", resultNum); break; } if (tag.equalsIgnoreCase("result")) { String result = xmlParser.nextText(); map.put("result", result); break; } if (tag.equalsIgnoreCase("searchTime")) { String searchTime = xmlParser.nextText(); map.put("searchTime", searchTime); break; } if (tag.equalsIgnoreCase("ChKeyList")) { break; } if (tag.equalsIgnoreCase("searchKey")) { String searchKey = xmlParser.nextText(); resultList.add(searchKey); break; } break; case XmlPullParser.END_TAG: // 如果遇到river标签结束,则把river对象添加进集合中 if (tag.equalsIgnoreCase("ChKeyResult")) { map.put("resultList", resultList); } break; default: break; } // 如果xml没有结束,则导航到下一个river节点 evtType = xmlParser.next(); } } catch (Exception e) { e.printStackTrace(); Log.v(TAG, "xml解析出错"+e.getMessage()); } return resultList; } }
114ch
version_without_location/src/com/besttone/http/WebServiceHelper.java
Java
asf20
14,399
package com.besttone.http; import com.besttone.search.Client; public class UpdateRequest extends WebServiceHelper { public static interface UpdateListener { public void onUpdateAvaiable(String msg, String url); public void onUpdateMust(String msg, String url); public void onUpdateNoNeed(String msg); public void onUpdateError(short code, Exception e); } private int latestVersionCode = 0; private String url = ""; private UpdateListener mListener = null; public void setListener(UpdateListener mListener) { this.mListener = mListener; } public void checkUpdate() { Client.getThreadPoolForRequest().execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub getUpdateInfo(); Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if (Client.getVersion(Client.getContext()) != latestVersionCode) { mListener.onUpdateAvaiable("", url); } else { mListener.onUpdateNoNeed(""); } } }); } }); } private void getUpdateInfo() { this.latestVersionCode = 2; this.url = "http://droidapps.googlecode.com/files/MiniFetion-2.8.4.apk"; } }
114ch
version_without_location/src/com/besttone/http/UpdateRequest.java
Java
asf20
1,328
package com.besttone.search; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.besttone.adapter.AreaAdapter; import com.besttone.adapter.CateAdapter; import com.besttone.adapter.SortAdapter; import com.besttone.http.WebServiceHelper; import com.besttone.search.model.RequestInfo; import com.besttone.search.util.Constants; import com.besttone.search.util.SharedUtils; import com.besttone.widget.PoiListItem; import com.besttone.search.R; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.RawContacts; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.Toast; public class SearchResultActivity extends Activity implements ServerListener, OnClickListener { private Context mContext; private List<Map<String, Object>> filterData; private View loadingView; private View addShopView; private ListView list; private boolean isEnd = false; PoiResultAdapter resultAdapter = null; ListAdapter areaAdapter = null; CateAdapter cateAdapter = null; private ImageButton btn_back; private Button mSearchBtn; private Button mAreaBtn; private String[] mAreaArray = null; private String[] mChannelArray = null; private int mAreaIndex = 0; private Button mChannelBtn; public PopupWindow mPopupWindow; private ListView popListView; private String keyword; private RequestInfo rqInfo; private WebServiceHelper serviceHelper; private boolean isLoadingRemoved = false; private boolean isLoadingEnd = false; Handler handler = new Handler() { public void handleMessage(Message paramMessage) { if (paramMessage.what == 1) { loadingView.setVisibility(View.GONE); } else if (paramMessage.what == 2) { list.removeFooterView(loadingView); isLoadingRemoved = true; } else if (paramMessage.what == 3) { list.addFooterView(loadingView); loadingView.setVisibility(View.VISIBLE); isLoadingRemoved = false; } else if (paramMessage.what == 4) { loadingView.setVisibility(View.VISIBLE); } else if (paramMessage.what == 5) { list.removeFooterView(loadingView); isLoadingRemoved = true; if(!isLoadingEnd) addShopView(); } } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.search_result); mContext = this.getApplicationContext(); init(); } private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() { public void onClick(View v) { finish(); } }; private Button.OnClickListener searchHistroyListner = new Button.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(); intent.setClass(SearchResultActivity.this, SearchActivity.class); finish(); startActivity(intent); } }; private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // Intent intent = new Intent(); // ListView listView = (ListView)parent; // HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position); // intent.setClass(ResultActivity.this, DetailActivity.class); // if(map.get("id")==null || "".equals(map.get("id"))) { // intent.putExtra("id", "2029602847-421506714"); // } else { // intent.putExtra("id", map.get("id")); // } // startActivity(intent); // ResultActivity.this.finish(); //显示数据详情 //Toast.makeText(SearchResultActivity.this, "正在开发中,敬请期待...", Toast.LENGTH_SHORT).show(); } }; public class PoiResultAdapter extends BaseAdapter { private LayoutInflater mInflater; public PoiResultAdapter(Context context) { this.mInflater = LayoutInflater.from(context); } public int getCount() { return filterData.size(); } public Object getItem(int position) { return filterData.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { } convertView = mInflater.inflate(R.layout.search_result_item, null); // convertView.findViewById(R.id.name).setSelected(true); // convertView.findViewById(R.id.addr).setSelected(true); PoiListItem item = (PoiListItem) convertView; Map map = filterData.get(position); item.setPoiData(map.get("name").toString(), map.get("tel") .toString(), map.get("addr").toString(),(map .get("city")==null?null:(map .get("city")).toString()) ); if (position == filterData.size() - 1 && !isEnd) { loadingView.setVisibility(View.VISIBLE); //下拉获取数据 int size = filterData.size(); int page = 1 + size/Constants.PAGE_SIZE; int currentPage =Integer.valueOf(rqInfo.getPage()); if(size==currentPage*Constants.PAGE_SIZE) { rqInfo.setPage(Constants.SPACE + page); serviceHelper.sendRequest(SearchResultActivity.this, rqInfo); } else { //Toast.makeText(ResultActivity.this, "没有更多的数据", Toast.LENGTH_SHORT).show(); Message localMessage = new Message(); localMessage.what = 5; handler.sendMessage(localMessage); } } return convertView; } } public void addShopView() { isLoadingEnd = true; addShopView = getLayoutInflater().inflate(R.layout.search_result_empty, null, false); list.addFooterView(addShopView); addShopView.setVisibility(View.VISIBLE); } public void serverDataArrived(List list, boolean isEnd) { this.isEnd = isEnd; Iterator iter = list.iterator(); while (iter.hasNext()) { filterData.add((Map<String, Object>) iter.next()); } Message localMessage = new Message(); if (!isEnd) { localMessage.what = 1; } else { localMessage.what = 2; } if(list!=null && list.size()==0){ localMessage.what = 5; } this.handler.sendMessage(localMessage); } public void onClick(View v) { switch (v.getId()) { case R.id.area: { showDialogPopup(R.id.area); break; } case R.id.channel: { showDialogPopup(R.id.channel); // if (mPopupWindow != null && mPopupWindow.isShowing()) { // mPopupWindow.dismiss(); // } else { // createPopWindow(v); // } break; } } } protected void showDialogPopup(int viewId) { AlertDialog.Builder localBuilder = new AlertDialog.Builder(this); switch (viewId) { case R.id.area: { if (areaAdapter == null) { areaAdapter = new AreaAdapter(this, mAreaArray); } localBuilder.setAdapter(areaAdapter, new areaPopupListener( areaAdapter)); break; } case R.id.channel: { if (cateAdapter == null) { cateAdapter = new CateAdapter(this, mChannelArray); } localBuilder.setAdapter(cateAdapter, new channelPopupListener( cateAdapter)); break; } } AlertDialog localAlertDialog = localBuilder.create(); localAlertDialog.show(); } class areaPopupListener implements DialogInterface.OnClickListener { AreaAdapter mAdapter; public areaPopupListener(ListAdapter adapter) { mAdapter = (AreaAdapter) adapter; } public void onClick(DialogInterface dialog, int which) { ((AreaAdapter) mAdapter).setTypeIndex(which); final String cityName = ((AreaAdapter) mAdapter).getSelect(); mAreaBtn.setText(cityName); filterData.clear(); filterData = new ArrayList<Map<String, Object>>(); resultAdapter.notifyDataSetChanged(); if (isLoadingRemoved) { list.addFooterView(loadingView); loadingView.setVisibility(View.VISIBLE); isLoadingRemoved = false; } else { loadingView.setVisibility(View.VISIBLE); } if(isLoadingEnd){ list.removeFooterView(addShopView); isLoadingEnd = false; } //获取数据 String simplifyCode = null; if("全部区域".equals(cityName)) { simplifyCode = SharedUtils.getCurrentSimplifyCode(mContext); } else { simplifyCode = Constants.getSimplifyCodeByName(mContext, cityName); } rqInfo.setRegion(simplifyCode); String tradeName = mChannelBtn.getText().toString(); if(!"全部行业".equals(tradeName)) { rqInfo.setContent(keyword + "/n|" + tradeName + "/i"); } else { rqInfo.setContent(keyword+"/n"); } rqInfo.setPage("1"); rqInfo.setPageSize(Constants.SPACE + Constants.PAGE_SIZE); serviceHelper = new WebServiceHelper(); serviceHelper.sendRequest(SearchResultActivity.this, rqInfo); } } class channelPopupListener implements DialogInterface.OnClickListener { CateAdapter cAdapter; public channelPopupListener(CateAdapter adapter) { cAdapter = (CateAdapter) adapter; } public void onClick(DialogInterface dialog, int which) { ((CateAdapter) cAdapter).setTypeIndex(which); final String tradeName = ((CateAdapter) cAdapter).getSelect(); mChannelBtn.setText(tradeName); filterData.clear(); filterData = new ArrayList<Map<String, Object>>(); resultAdapter.notifyDataSetChanged(); if (isLoadingRemoved) { list.addFooterView(loadingView); loadingView.setVisibility(View.VISIBLE); isLoadingRemoved = false; } else { loadingView.setVisibility(View.VISIBLE); } if(isLoadingEnd){ list.removeFooterView(addShopView); isLoadingEnd = false; } //获取数据 String simplifyCode = null; String cityName = mAreaBtn.getText().toString(); if("全部区域".equals(cityName)) { simplifyCode = SharedUtils.getCurrentSimplifyCode(mContext); } else { simplifyCode = Constants.getSimplifyCodeByName(mContext, cityName); } if(!"全部行业".equals(tradeName)) { rqInfo.setContent(keyword + "/n|" + tradeName + "/i"); } else { rqInfo.setContent(keyword+"/n"); } rqInfo.setRegion(simplifyCode); rqInfo.setPage("1"); rqInfo.setPageSize(Constants.SPACE + Constants.PAGE_SIZE); serviceHelper = new WebServiceHelper(); serviceHelper.sendRequest(SearchResultActivity.this, rqInfo); } } private void init() { filterData = PoiResultData.getData(); list = (ListView) findViewById(R.id.resultlist); list.setFastScrollEnabled(true); resultAdapter = new PoiResultAdapter(this); btn_back = (ImageButton) findViewById(R.id.left_title_button); btn_back.setOnClickListener(backListner); rqInfo = new RequestInfo(); Bundle bundle = this.getIntent().getExtras(); rqInfo.setRegion(SharedUtils.getCurrentSimplifyCode(this)); rqInfo.setDeviceid(SharedUtils.getCurrentPhoneDeviceId(this)); rqInfo.setImsi(SharedUtils.getCurrentPhoneImsi(this)); rqInfo.setMobile(SharedUtils.getCurrentPhoneNo(this)); rqInfo.setPage("1"); rqInfo.setPageSize(Constants.SPACE + Constants.PAGE_SIZE); keyword = bundle.getString("keyword"); rqInfo.setContent(keyword+"/n"); serviceHelper = new WebServiceHelper(); serviceHelper.sendRequest(this, rqInfo); mSearchBtn = ((Button)findViewById(R.id.start_search)); mSearchBtn.setText(bundle.getString("keyword")); mSearchBtn.setOnClickListener(searchHistroyListner); loadingView = LayoutInflater.from(this).inflate(R.layout.listfooter, null); list.addFooterView(loadingView); list.setAdapter(resultAdapter); list.setOnItemClickListener(mOnClickListener); list.setOnItemLongClickListener(mOnLongClickListener); mAreaBtn = ((Button)findViewById(R.id.area)); mChannelBtn = ((Button)findViewById(R.id.channel)); mAreaBtn.setOnClickListener(this); mChannelBtn.setOnClickListener(this); initHomeView(); } private void initHomeView() { mAreaArray = Constants.getDistrictArray(this, SharedUtils.getCurrentCityCode(this)); if ((mAreaArray == null) || (this.mAreaArray.length == 0)) { mAreaBtn.setText("全部区域"); mAreaBtn.setEnabled(false); } while (true) { mChannelArray = getResources().getStringArray(R.array.trade_name_items); mAreaBtn.setText(this.mAreaArray[this.mAreaIndex]); mAreaBtn.setEnabled(true); return; } } private void createPopWindow(View parent) { // LayoutInflater lay = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); // View view = lay.inflate(R.layout.popup_window, null ); // // mPopupWindow = new PopupWindow(view, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); // // //初始化listview,加载数据 // popListView = (ListView) findViewById(R.id.pop_list); //// if (sortAdapter == null) { //// sortAdapter = new SortAdapter(this, mSortArray); //// } //// popListView.setAdapter(sortAdapter); // // // //设置整个popupwindow的样式 // mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.right_filter_bg)); // // mPopupWindow.setFocusable(true ); // mPopupWindow.setTouchable(true); // mPopupWindow.setOutsideTouchable(true); // mPopupWindow.update(); // mPopupWindow.showAsDropDown(parent, 10, 10); View contentView = LayoutInflater.from(getApplicationContext()) .inflate(R.layout.popup_window, null); mPopupWindow = new PopupWindow(contentView, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); mPopupWindow.setContentView(contentView); //设置整个popupwindow的样式 mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.right_filter_bg)); String[] name = openDir(); ListView listView = (ListView) contentView.findViewById(R.id.pop_list); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name); listView.setAdapter(adapter); mPopupWindow.setFocusable(true ); mPopupWindow.setTouchable(true); mPopupWindow.setOutsideTouchable(true); mPopupWindow.update(); mPopupWindow.showAsDropDown(parent, 10, 10); } private String[] openDir() { String[] name; String rootPath = Environment.getExternalStorageDirectory() .getAbsolutePath(); File file = new File(rootPath); File[] files = file.listFiles(); name = new String[files.length]; for (int i = 0; i < files.length; i++) { name[i] = files[i].getName(); System.out.println(name[i]); } return name; } private AdapterView.OnItemLongClickListener mOnLongClickListener = new AdapterView.OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { ListView listView = (ListView)parent; HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position); final String name = map.get("name"); final String tel = map.get("tel"); final String addr = map.get("addr"); String[] array = new String[2]; array[0] = "呼叫 " + tel; array[1] = "添加至联系人"; new AlertDialog.Builder(SearchResultActivity.this) .setTitle(name) .setItems(array, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if(which == 0) { Intent myIntentDial = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel)); startActivity(myIntentDial); } if(which == 1){ String rwContactId = getContactId(name); ContentResolver resolver = mContext.getContentResolver(); ContentValues values = new ContentValues(); //联系人中是否存在,若存在则更新 if(rwContactId!=null && !"".equals(rwContactId)){ Toast.makeText(SearchResultActivity.this, "商家已存在", Toast.LENGTH_SHORT).show(); // String whereClause = ContactsContract.RawContacts.Data.RAW_CONTACT_ID + "= ? AND " + ContactsContract.Data.MIMETYPE + "=?"; // // values.clear(); // values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); // values.put(StructuredName.DISPLAY_NAME, name); // resolver.update(Data.CONTENT_URI, values, whereClause, new String[]{rwContactId, StructuredName.CONTENT_ITEM_TYPE }); // // values.clear(); // values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); // values.put(Phone.NUMBER, tel); // if(isMobilePhone(tel)){ // values.put(Phone.TYPE, Phone.TYPE_MOBILE); // values.put(Phone.LABEL, Phone.TYPE_WORK_MOBILE); // } else { // values.put(Phone.TYPE, Phone.TYPE_WORK); // values.put(Phone.LABEL, Phone.TYPE_WORK); // } // resolver.update(Data.CONTENT_URI, values, whereClause, new String[]{rwContactId, Phone.CONTENT_ITEM_TYPE}); // // values.clear(); // values.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE); // values.put(StructuredPostal.TYPE, StructuredPostal.TYPE_WORK); // values.put(StructuredPostal.LABEL, StructuredPostal.TYPE_WORK); // values.put(StructuredPostal.STREET, addr); // resolver.update(Data.CONTENT_URI, values, whereClause, new String[]{rwContactId, StructuredPostal.CONTENT_ITEM_TYPE}); // // Toast.makeText(SearchResultActivity.this, "联系人更新成功", Toast.LENGTH_SHORT).show(); } else { Uri rawContactUri = resolver.insert( RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); values.clear(); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); values.put(StructuredName.DISPLAY_NAME, name); resolver.insert(Data.CONTENT_URI, values); values.clear(); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); values.put(Phone.NUMBER, tel); if(isMobilePhone(tel)){ values.put(Phone.TYPE, Phone.TYPE_MOBILE); values.put(Phone.LABEL, Phone.TYPE_WORK_MOBILE); } else { values.put(Phone.TYPE, Phone.TYPE_WORK); values.put(Phone.LABEL, Phone.TYPE_WORK); } resolver.insert(Data.CONTENT_URI, values); values.clear(); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE); values.put(StructuredPostal.TYPE, StructuredPostal.TYPE_WORK); values.put(StructuredPostal.LABEL, StructuredPostal.TYPE_WORK); values.put(StructuredPostal.STREET, addr); resolver.insert(Data.CONTENT_URI, values); Toast.makeText(SearchResultActivity.this, "添加成功", Toast.LENGTH_SHORT).show(); } } } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }).show(); return true; } }; public boolean isMobilePhone(String tel){ boolean flag = false; if(tel!=null && tel.length()==11){ String reg = "^(13[0-9]|15[012356789]|18[0236789]|14[57])[0-9]{8}$"; flag = tel.matches(reg); } return flag; } /* * 根据电话号码取得联系人姓名 */ public void getPeople() { String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}; // 将自己添加到 msPeers 中 Cursor cursor = this.getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, // Which columns to return. ContactsContract.CommonDataKinds.Phone.NUMBER + " = '021-65291718'", // WHERE clause. null, // WHERE clause value substitution null); // Sort order. if( cursor == null ) { return; } System.out.println(cursor.getCount()); for( int i = 0; i < cursor.getCount(); i++ ) { cursor.moveToPosition(i); // 取得联系人名字 int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME); String name = cursor.getString(nameFieldColumnIndex); System.out.println("联系人姓名:" + name); Toast.makeText(SearchResultActivity.this, "联系人姓名:" + name, Toast.LENGTH_SHORT).show(); } } /* * 根据联系人姓名取得ID */ public String getContactId(String name) { String rawContactId = null; String[] projection = { ContactsContract.RawContacts.Data.RAW_CONTACT_ID }; // 将自己添加到 msPeers 中 Cursor cursor = this.getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, // Which columns to return. ContactsContract.PhoneLookup.DISPLAY_NAME + " = '"+ name +"'", // WHERE clause. null, // WHERE clause value substitution null); // Sort order. if( cursor == null ) { return null; } else if(cursor.getCount()>0){ cursor.moveToFirst(); // 取得联系人ID int idFieldColumnIndex = cursor.getColumnIndex(ContactsContract.RawContacts.Data.RAW_CONTACT_ID); rawContactId = cursor.getString(idFieldColumnIndex); return rawContactId; } return null; } }
114ch
version_without_location/src/com/besttone/search/SearchResultActivity.java
Java
asf20
24,283
package com.besttone.search; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import android.app.Activity; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.os.Bundle; import android.os.Handler; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.WindowManager; import android.widget.Toast; public class Client { // ------------------------------------------------------------------------- private static Client instance; private static String screenSize = ""; private static String deviceId = ""; private static float dencyRate = 1.0f; private static DisplayMetrics display; private Handler mHd; private ThreadPoolExecutor mThreadPoorForLocal; private ThreadPoolExecutor mThreadPoorForDownload; private ThreadPoolExecutor mThreadPoorForRequest; private Context mContext; private final static String Tag="Client"; // public static UserInfo userInfo; // public static WordInfo wordInfo; // public static int dataType; // public static boolean turnType; // public static DrawCommon drawComm; // public static GuessCommon guessComm; // public static boolean rightWrong; // ------------------------------------------------------------------------- private Client() { instance = this; mHd = new Handler(); mThreadPoorForLocal = new ThreadPoolExecutor(3, 6, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)); mThreadPoorForRequest = new ThreadPoolExecutor(4, 8, 15, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)); mThreadPoorForDownload = new ThreadPoolExecutor(2, 5, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)); } // ------------------------------------------------------------------------- public static void release() { try { instance.mThreadPoorForLocal.shutdownNow(); instance.mThreadPoorForRequest.shutdownNow(); instance.mThreadPoorForDownload.shutdownNow(); } catch (Exception e) { e.printStackTrace(); } instance = null; } // ------------------------------------------------------------------------- public static Client getInstance() { if (instance == null) { instance = new Client(); } return instance; } // ------------------------------------------------------------------------- public static Handler getHandler() { return getInstance().mHd; } // ------------------------------------------------------------------------- public static void postRunnable(Runnable r) { getInstance().mHd.post(r); } // ------------------------------------------------------------------------- public static ThreadPoolExecutor getThreadPoolForLocal() { return getInstance().mThreadPoorForLocal; } // ------------------------------------------------------------------------- public static ThreadPoolExecutor getThreadPoolForRequest() { Log.d(Tag,"request"); return getInstance().mThreadPoorForRequest; } // ------------------------------------------------------------------------- public static ThreadPoolExecutor getThreadPoolForDownload() { return getInstance().mThreadPoorForDownload; } // ------------------------------------------------------------------------- public static void initWithContext(Context context) { getInstance().mContext = context; display = new DisplayMetrics(); WindowManager wm = (WindowManager) context.getSystemService( Context.WINDOW_SERVICE ); if (null != wm) { wm.getDefaultDisplay().getMetrics( display ); screenSize = display.widthPixels < display.heightPixels ? display.widthPixels + "x" + display.heightPixels : display.heightPixels + "x" + display.widthPixels; dencyRate = display.density / 1.5f; } TelephonyManager tm = (TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE ); if (null != tm) { deviceId = tm.getDeviceId(); if (null == deviceId) deviceId = ""; } } // ------------------------------------------------------------------------- public static Context getContext() { return getInstance().mContext; } // ------------------------------------------------------------------------- public static String getDeviceId() { return deviceId; } // ------------------------------------------------------------------------- public static String getScreenSize() { return screenSize; } // ------------------------------------------------------------------------- public static float getDencyParam() { return dencyRate; } // ------------------------------------------------------------------------- public static DisplayMetrics getDisplayMetrics() { return display; } // ------------------------------------------------------------------------- public static boolean decetNetworkOn() { try { ConnectivityManager cm = (ConnectivityManager) getInstance().mContext.getSystemService(Context.CONNECTIVITY_SERVICE); if (null != cm ) { NetworkInfo wi = cm.getActiveNetworkInfo(); if (null != wi) return wi.isConnected(); } } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean decetNetworkOn(Context c) { ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); if (null != cm ) { NetworkInfo info = cm.getActiveNetworkInfo(); if (null != info) return info.isConnected(); } return false; } public static Bundle getAppInfoBundle(Context context) { Bundle bundle = null; try { ApplicationInfo appInfo = ((Activity)context).getPackageManager().getApplicationInfo(((Activity)context).getPackageName(), PackageManager.GET_META_DATA); if (appInfo != null) { bundle = appInfo.metaData; } PackageInfo pinfo = ((Activity)context).getPackageManager().getPackageInfo(((Activity)context).getPackageName(), PackageManager.GET_CONFIGURATIONS); if(pinfo!=null) { bundle.putString("versionName", pinfo.versionName); bundle.putInt("versionCode", pinfo.versionCode); } } catch (NameNotFoundException e) { e.printStackTrace(); } return bundle; } /** * 应用程序版本 * @param context * @return */ public static int getVersion(Context context) { int uVersion = 0; Bundle bundle = getAppInfoBundle(context); if (bundle != null) { uVersion = bundle.getInt("versionCode"); } return uVersion; } }
114ch
version_without_location/src/com/besttone/search/Client.java
Java
asf20
6,865
package com.besttone.search; import android.app.Application; public class Ch114NewApplication extends Application { @Override public void onCreate() { //appContext = getApplicationContext(); super.onCreate(); Client.getInstance(); } }
114ch
version_without_location/src/com/besttone/search/Ch114NewApplication.java
Java
asf20
266
package com.besttone.search.sql; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class NativeDBHelper extends SQLiteOpenHelper { public static final String AREA_CODE = "AREA_CODE"; public static final int AREA_CODE_INDEX = 9; public static final String BUSINESS_FLAG = "BUSINESS_FLAG"; public static final int BUSINESS_FLAG_INDEX = 12; public static final int DATABASE_VERSION = 1; public static final String ENG_NAME = "ENG_NAME"; public static final int ENG_NAME_INDEX = 7; public static final String FIRST_PY = "FIRST_PY"; public static final int FIRST_PY_INDEX = 6; public static final String ID = "ID"; public static final int ID_INDEX = 0; public static final String IS_FREQUENT = "IS_FREQUENT"; public static final int IS_FREQUENT_INDEX = 10; public static final String NAME = "NAME"; public static final int NAME_INDEX = 4; public static final String PARENT_REGION = "PARENT_REGION"; public static final int PARENT_REGION_INDEX = 2; public static final String REGION_CODE = "REGION_CODE"; public static final int REGION_CODE_INDEX = 1; public static final String SHORT_NAME = "SHORT_NAME"; public static final int SHORT_NAME_INDEX = 5; public static final String SORT_VALUE = "SORT_VALUE"; public static final int SORT_VALUE_INDEX = 11; public static final String TEL_LENGTH = "TEL_LENGTH"; public static final int TEL_LENGTH_INDEX = 8; public static final String TYPE = "TYPE"; public static final String TYPE_CITY = "2"; public static final String TYPE_DISTRICT = "3"; public static final int TYPE_INDEX = 3; public static final String TYPE_PROVINCE = "1"; private static NativeDBHelper sInstance; private final String[] mColumns; private NativeDBHelper(Context paramContext) { super(paramContext, "native_database.db", null, 1); String[] arrayOfString = new String[8]; arrayOfString[0] = "ID"; arrayOfString[1] = "REGION_CODE"; arrayOfString[2] = "PARENT_REGION"; arrayOfString[3] = "TYPE"; arrayOfString[4] = "SHORT_NAME"; arrayOfString[5] = "FIRST_PY"; arrayOfString[6] = "AREA_CODE"; arrayOfString[7] = "BUSINESS_FLAG"; this.mColumns = arrayOfString; } public static NativeDBHelper getInstance(Context paramContext) { if (sInstance == null) sInstance = new NativeDBHelper(paramContext); return sInstance; } public void onCreate(SQLiteDatabase paramSQLiteDatabase) { } public void onUpgrade(SQLiteDatabase paramSQLiteDatabase, int paramInt1, int paramInt2) { } public Cursor select(String[] paramArrayOfString1, String paramString, String[] paramArrayOfString2) { return getReadableDatabase().query("PUB_LOCATION", paramArrayOfString1, paramString, paramArrayOfString2, null, null, null); } public Cursor selectAllCity() { String[] arrayOfString = new String[1]; arrayOfString[0] = "2"; return select(this.mColumns, "TYPE=?", arrayOfString); } public Cursor selectCodeByName(String paramString) { String[] arrayOfString = new String[1]; arrayOfString[0] = paramString; return select(this.mColumns, "SHORT_NAME=?", arrayOfString); } public Cursor selectDistrict(String paramString) { String[] arrayOfString = new String[2]; arrayOfString[0] = "3"; arrayOfString[1] = paramString; return select(this.mColumns, "TYPE=? AND PARENT_REGION like ?", arrayOfString); } public Cursor selectNameByCode(String paramString) { String[] arrayOfString = new String[1]; arrayOfString[0] = paramString; return select(this.mColumns, "REGION_CODE=?", arrayOfString); } }
114ch
version_without_location/src/com/besttone/search/sql/NativeDBHelper.java
Java
asf20
3,714
package com.besttone.search; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PoiResultData { public static List<Map<String, Object>> getData() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); return list; } }
114ch
version_without_location/src/com/besttone/search/PoiResultData.java
Java
asf20
321
package com.besttone.search; import java.util.ArrayList; import com.besttone.adapter.LetterListAdapter; import com.besttone.search.CityListBaseActivity.AutoCityAdapter; import com.besttone.search.model.City; import com.besttone.search.sql.NativeDBHelper; import com.besttone.search.util.Constants; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewFlipper; public abstract class CityListBaseActivity extends Activity implements AbsListView.OnScrollListener { private Context mContext; protected ArrayList<City> citylist = new ArrayList(); private Handler handler; protected ArrayAdapter<String> mAutoAdapter; protected EditText mAutoTextView; protected ArrayList<String> autoCitylist = new ArrayList<String>(); protected String[] autoArray; protected String[] mCityFirstLetter; private TextView mDialogText; protected int mHotCount = 0; protected Cursor mHotCursor; private String mLetter = ""; protected LetterListAdapter mListAdapter; protected ListView mListView; private RemoveWindow mRemoveWindow; private int mScroll; private boolean mShowing = false; private NativeDBHelper mDB; private WindowManager windowManager; protected AutoCityAdapter mAutoCityAdapter; protected ListView mAutoListView; private final TextWatcher textWatcher = new TextWatcher() { private int selectionEnd; private int selectionStart; private CharSequence temp; public void afterTextChanged(Editable paramEditable) { this.selectionStart = CityListBaseActivity.this.mAutoTextView .getSelectionStart(); this.selectionEnd = CityListBaseActivity.this.mAutoTextView .getSelectionEnd(); if (this.temp.length() > 25) { Toast.makeText(CityListBaseActivity.this, "temp 长度大于25", Toast.LENGTH_SHORT).show(); paramEditable.delete(this.selectionStart - (-25 + this.temp.length()), this.selectionEnd); int i = this.selectionStart; CityListBaseActivity.this.mAutoTextView.setText(paramEditable); CityListBaseActivity.this.mAutoTextView.setSelection(i); } //获取mAutoTextView结果 String str = temp.toString(); Cursor localCursor = null; String[] arrayParm = new String[2]; arrayParm[0] = "2"; arrayParm[1] = (str + "%"); autoCitylist = new ArrayList<String>(); String[] mColumns = {"FIRST_PY", "SHORT_NAME"}; // Log.d("selectCity", "search"); // Log.i("arrayParm[0]", "search"+arrayParm[0]); // Log.i("arrayParm[q]", "search"+arrayParm[1]); if(Constants.isAlphabet(str)) { localCursor =mDB.select(mColumns, "TYPE=? AND FIRST_PY like ?",arrayParm); } else { localCursor =mDB.select(mColumns, "TYPE=? AND SHORT_NAME like ?",arrayParm); } if (localCursor!=null && localCursor.getCount()>0) { localCursor.moveToFirst(); while (true) { if (localCursor.isAfterLast()) { localCursor.close(); break; } autoCitylist.add(localCursor.getString(0) + "," + localCursor.getString(1)); // Log.i("result", localCursor.getString(0) + "," + localCursor.getString(1)); localCursor.moveToNext(); } } autoArray = autoCitylist.toArray(new String[autoCitylist.size()]); // mAutoAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_dropdown_item_1line, autoArray); // mAutoTextView.setAdapter(mAutoAdapter); // for(int i=0;i<autoArray.length;i++) // Log.i("autoArray[i]", "result"+autoArray[i]); if(str.length()>0&&autoArray.length>0) { mAutoListView.setVisibility(View.VISIBLE); } else { mAutoListView.setVisibility(View.GONE); } mAutoCityAdapter.notifyDataSetChanged(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { this.temp = s; } public void onTextChanged(CharSequence s, int start, int count, int after) { } }; private void init() { this.mDialogText = ((TextView) ((LayoutInflater) getSystemService("layout_inflater")).inflate(R.layout.select_city_position_dialog, null)); this.mDialogText.setVisibility(4); this.mRemoveWindow = new RemoveWindow(); this.handler = new Handler(); this.windowManager = getWindowManager(); setAdapter(); this.mListView.setOnScrollListener(this); this.mListView.setFastScrollEnabled(true); initAutoData(); mAutoTextView = (EditText)this.findViewById(R.id.change_city_auto_text); // this.mAutoTextView.setAdapter(this.mAutoAdapter); // this.mAutoTextView.setThreshold(1); this.mAutoTextView.addTextChangedListener(this.textWatcher); mDB = NativeDBHelper.getInstance(this); } private void initFirstLetter() { setFirstletter(); initDBHelper(); addHotCityFirstLetter(); this.mHotCount = this.citylist.size(); addCityFirstLetter(); } private void removeWindow() { if (!this.mShowing) ; while (true) { this.mShowing = false; this.mDialogText.setVisibility(4); return; } } public abstract void addCityFirstLetter(); public abstract void addHotCityFirstLetter(); public abstract void initAutoData(); public abstract void initDBHelper(); protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); requestWindowFeature(1); setTheContentView(); mContext = this.getApplicationContext(); initFirstLetter(); init(); setListViewOnItemClickListener(); setAutoCompassTextViewOnItemClickListener(); // mAutoTextView.setAdapter(mAutoCityAdapter); } public void onScroll(AbsListView paramAbsListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { this.mScroll = (1 + this.mScroll); if (this.mScroll >= 2) { while (true) { int i = firstVisibleItem - 1 + visibleItemCount / 2; String str = ((City) this.mListView.getAdapter().getItem(i)) .getFirstLetter(); if (str == null) continue; this.mShowing = true; this.mDialogText.setVisibility(0); this.mDialogText.setText(str); this.mLetter = str; this.handler.removeCallbacks(this.mRemoveWindow); this.handler.postDelayed(this.mRemoveWindow, 3000L); return; } } } public void onScrollStateChanged(AbsListView paramAbsListView, int paramInt) { } protected void onStart() { super.onStart(); WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams( -1, -1, 2, 24, -3); this.windowManager.addView(this.mDialogText, localLayoutParams); this.mScroll = 0; } protected void onStop() { super.onStop(); try { this.mScroll = 0; this.windowManager.removeView(this.mDialogText); return; } catch (Exception localException) { while (true) localException.printStackTrace(); } } public abstract void setAdapter(); public abstract void setAutoCompassTextViewOnItemClickListener(); public abstract void setFirstletter(); public abstract void setListViewOnItemClickListener(); public abstract void setTheContentView(); final class RemoveWindow implements Runnable { private RemoveWindow() { } public void run() { CityListBaseActivity.this.removeWindow(); } } public class AutoCityAdapter extends BaseAdapter { private LayoutInflater mInflater; public AutoCityAdapter(Context context) { this.mInflater = LayoutInflater.from(context); autoArray = new String[1]; } public int getCount() { return autoArray.length; } public Object getItem(int position) { return autoArray[position]; } public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub convertView = mInflater.inflate(R.layout.auto_city_item, null); Log.i("adapt", "getDropDownView"); String searchRecord = autoArray[position]; ((TextView) convertView.findViewById(R.id.auto_city_info)).setText(searchRecord); return convertView; } } }
114ch
version_without_location/src/com/besttone/search/CityListBaseActivity.java
Java
asf20
9,038
package com.besttone.search.dialog; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.DecimalFormat; import java.text.NumberFormat; import com.besttone.search.Client; import com.besttone.search.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.StatFs; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class ProgressBarDialog extends Dialog { private ProgressBar mProgress; private TextView mProgressNumber; private TextView mProgressPercent; public static final int M = 1024 * 1024; public static final int K = 1024; private double dMax; private double dProgress; private int middle = K; private int prev = 0; private Handler mViewUpdateHandler; private int fileSize; private int downLoadFileSize; private static final NumberFormat nf = NumberFormat.getPercentInstance(); private static final DecimalFormat df = new DecimalFormat("###.##"); private static final int msg_init = 0; private static final int msg_update = 1; private static final int msg_complete = 2; private static final int msg_error = -1; private String mUrl; private File fileOut; private String downloadPath; public ProgressBarDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { LayoutInflater inflater = LayoutInflater.from(getContext()); mViewUpdateHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (!Thread.currentThread().isInterrupted()) { // Log.i("msg what", String.valueOf(msg.what)); switch (msg.what) { case msg_init: // pbr.setMax(fileSize); mProgress.setMax(100); break; case msg_update: setDProgress((double) downLoadFileSize); break; case msg_complete: setTitle("文件下载完成"); break; case msg_error: String error = msg.getData().getString("更新失败"); setTitle(error); break; default: break; } } double precent = dProgress / dMax; if (prev != (int) (precent * 100)) { mProgress.setProgress((int) (precent * 100)); mProgressNumber.setText(df.format(dProgress) + "/" + df.format(dMax) + (middle == K ? "K" : "M")); mProgressPercent.setText(nf.format(precent)); prev = (int) (precent * 100); } } }; View view = inflater.inflate(R.layout.dialog_progress_bar, null); mProgress = (ProgressBar) view.findViewById(R.id.progress); mProgress.setMax(100); mProgressNumber = (TextView) view.findViewById(R.id.progress_number); mProgressPercent = (TextView) view.findViewById(R.id.progress_percent); setContentView(view); onProgressChanged(); super.onCreate(savedInstanceState); } private void onProgressChanged() { mViewUpdateHandler.sendEmptyMessage(0); } public double getDMax() { return dMax; } public void setDMax(double max) { if (max > M) { middle = M; } else { middle = K; } dMax = max / middle; } public double getDProgress() { return dProgress; } public void setDProgress(double progress) { dProgress = progress / middle; onProgressChanged(); } // String downloadPath = Environment.getExternalStorageDirectory().getPath() // + "/download_cache"; public void downLoadFile(final String httpUrl) { this.mUrl = httpUrl; File sdDir = null; boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在 if (sdCardExist) { sdDir = Environment.getExternalStorageDirectory();// 获取跟目录 if (getAvailableExternalMemorySize() < 50000000) { Toast.makeText(Client.getContext(), "存储空间不足", Toast.LENGTH_SHORT).show(); dismiss(); return; } } else { Toast.makeText(Client.getContext(), "SD卡不存在", Toast.LENGTH_SHORT).show(); dismiss(); return; } downloadPath = sdDir + "/114update"; Client.getThreadPoolForDownload().execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub URL url = null; try { url = new URL(mUrl); String fileName = mUrl.substring(mUrl.lastIndexOf("/")); // String downloadPath = sdDir+"/114update"; File tmpFile = new File(downloadPath); if (!tmpFile.exists()) { tmpFile.mkdir(); } fileOut = new File(downloadPath + fileName); // URL url = new URL(appurl); // URL url = new URL(mUrl); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); InputStream in; in = con.getInputStream(); fileSize = con.getContentLength(); setDMax((double) fileSize); FileOutputStream out = new FileOutputStream(fileOut); byte[] bytes = new byte[1024]; downLoadFileSize = 0; setDProgress((double) downLoadFileSize); sendMsg(msg_init); int c; while ((c = in.read(bytes)) != -1) { out.write(bytes, 0, c); downLoadFileSize += c; sendMsg(msg_update);// 更新进度条 } in.close(); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); sendMsg(msg_error);// error } sendMsg(msg_complete);// 下载完成 Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub dismiss(); installApk(fileOut); exitApp(); } }); } }); } private void sendMsg(int flag) { Message msg = new Message(); msg.what = flag; mViewUpdateHandler.sendMessage(msg); } private void installApk(File file) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(Intent.ACTION_VIEW); String type = "application/vnd.android.package-archive"; intent.setDataAndType(Uri.fromFile(file), type); Client.getContext().startActivity(intent); Log.e("success", "the end"); } // 彻底关闭程序 protected void exitApp() { Client.release(); System.exit(0); // 或者下面这种方式 // android.os.Process.killProcess(android.os.Process.myPid()); } public static long getAvailableExternalMemorySize() { if (externalMemoryAvailable()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } else { return msg_error; } } public static boolean externalMemoryAvailable() { return android.os.Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED); } }
114ch
version_without_location/src/com/besttone/search/dialog/ProgressBarDialog.java
Java
asf20
7,572
package com.besttone.search; import java.io.File; import com.besttone.http.UpdateRequest; import com.besttone.http.UpdateRequest.UpdateListener; import com.besttone.search.dialog.ProgressBarDialog; import com.besttone.search.model.City; import com.besttone.search.model.PhoneInfo; import com.besttone.search.util.Constants; import com.besttone.search.util.LogUtils; import com.besttone.search.util.PhoneUtil; import com.besttone.search.util.SharedUtils; import com.besttone.search.util.StringUtils; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; public class SplashActivity extends Activity { private final int TIME_UP = 1; protected Context mContext; protected UpdateRequest r; private Handler handler = new Handler() { public void handleMessage(Message msg) { if (msg.what == TIME_UP) { Intent intent = new Intent(); intent.setClass(SplashActivity.this, MainActivity.class); startActivity(intent); overridePendingTransition(R.anim.splash_screen_fade, R.anim.splash_screen_hold); SplashActivity.this.finish(); } } }; public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.splash_screen_view); initApp(); initCity(); initPhoneInfo(); Client.initWithContext(this); detectUpdate(); // new Thread() { // public void run() { // try { // Thread.sleep(500); // } catch (Exception e) { // // } // Message msg = new Message(); // msg.what = TIME_UP; // handler.sendMessage(msg); // } // }.start(); } private void initApp() { initNativeDB(); } private void initNativeDB() { SharedPreferences localSharedPreferences = getSharedPreferences( "NativeDB", 0); if (1 > localSharedPreferences.getInt("Version", 0)) { Constants.copyNativeDB(this, getResources().openRawResource(R.raw.native_database)); localSharedPreferences.edit().putInt("Version", 1).commit(); } Constants.copyNativeDB(this, getResources().openRawResource(R.raw.native_database)); localSharedPreferences.edit().putInt("Version", 1).commit(); } private boolean isUnSelectedCity() { if ((!SharedUtils.isFirstSelectedCityComplete(this.mContext)) || (StringUtils.isEmpty(SharedUtils .getCurrentCityName(this.mContext))) || (StringUtils.isEmpty(SharedUtils .getCurrentCityCode(this.mContext))) || (StringUtils.isEmpty(SharedUtils .getCurrentProvinceCode(this.mContext)))) { return true; } return false; } private void initCity() { City localCity = new City(); localCity.setCityName("上海"); localCity.setCityCode("310000"); localCity.setSimplifyCode("31"); localCity.setCityId("75"); localCity.setProvinceCode("310000"); SharedUtils.setCurrentCity(this, localCity); } public void initPhoneInfo() { TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE); String imei = tm.getDeviceId(); //IMEI String provider = tm.getNetworkOperatorName(); //运营商 String imsi = tm.getSubscriberId(); //IMSI PhoneUtil util = new PhoneUtil(); PhoneInfo info = null; try { if(NetWorkStatus()) { //info = util.getPhoneNoByIMSI(imsi); } } catch (Exception e) { e.printStackTrace(); } if(info==null) info = new PhoneInfo(); info.setImei(imei); info.setImsi(imsi); info.setProvider(provider); SharedUtils.setCurrentPhoneInfo(this, info); } private boolean NetWorkStatus() { boolean netSataus = false; ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); cwjManager.getActiveNetworkInfo(); if (cwjManager.getActiveNetworkInfo() != null) { netSataus = cwjManager.getActiveNetworkInfo().isAvailable(); } // if (netSataus) { // Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络").setMessage("是否对网络进行设置?"); // b.setPositiveButton("是", new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int whichButton) { // Intent mIntent = new Intent("/"); // ComponentName comp = new ComponentName("com.android.settings", // "com.android.settings.WirelessSettings"); // mIntent.setComponent(comp); // mIntent.setAction("android.intent.action.VIEW"); // startActivityForResult(mIntent,0); // 如果在设置完成后需要再次进行操作,可以重写操作代码,在这里不再重写 // } // }).setNeutralButton("否", new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int whichButton) { // dialog.cancel(); // } // }).show(); // } return netSataus; } private void detectUpdate() { r = new UpdateRequest(); r.setListener(new UpdateListener() { @Override public void onUpdateNoNeed(String msg) { gotoLogin(); } public void onUpdateMust(String msg, final String url) { AlertDialog.Builder b = new AlertDialog.Builder(Client.getContext()); b.setTitle("程序必须升级才能继续"); b.setMessage(msg+"\r\n"+url); b.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); System.gc(); } }); b.setPositiveButton("升级",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoUpdate(url); } }); b.setCancelable(false); b.show(); } public void onUpdateError(short code, Exception e) { AlertDialog.Builder b = new AlertDialog.Builder(Client.getContext()); b.setTitle("升级验证失败"); b.setMessage("请检查网络..."); b.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); System.gc(); } }); b.setCancelable(false); b.show(); } public void onUpdateAvaiable(String msg, final String url) { AlertDialog.Builder b = new AlertDialog.Builder(Client.getContext()); b.setTitle("程序可以升级,请选择"); b.setMessage(msg+"\r\n"+url); b.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoLogin(); } }); b.setPositiveButton("升级",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoUpdate(url); } }); b.setCancelable(false); b.show(); } }); if (Client.decetNetworkOn()) { // Log.d("check","on"); r.checkUpdate(); } else { // Log.d("check","off"); gotoLogin(); Toast.makeText(Client.getContext(), "网络异常,没有可用网络", Toast.LENGTH_SHORT).show(); } } private void gotoLogin() { new Thread() { public void run() { try { Thread.sleep(500); } catch (Exception e) { } Message msg = new Message(); msg.what = TIME_UP; handler.sendMessage(msg); } }.start(); } private void gotoUpdate(String url) { if (TextUtils.isEmpty(url)) { Toast.makeText(this, "升级的地址有误", Toast.LENGTH_SHORT).show(); finish(); System.gc(); return; } // url = url.toLowerCase(); if (url.startsWith("www")) { url = "http://" + url; } if (url.startsWith("http")) { try { // Uri u = Uri.parse(url); ProgressBarDialog pbd=new ProgressBarDialog(Client.getContext()); pbd.setTitle("下载中"); pbd.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // TODO Auto-generated method stub gotoLogin(); } }); pbd.show(); pbd.downLoadFile(url); // Intent i = new Intent( Intent.ACTION_VIEW, u ); // startActivity( i ); // finish(); System.gc(); } catch(Exception e) { e.printStackTrace(); } } } }
114ch
version_without_location/src/com/besttone/search/SplashActivity.java
Java
asf20
8,894
package com.besttone.search; import java.util.List; public interface ServerListener { void serverDataArrived(List list, boolean isEnd); }
114ch
version_without_location/src/com/besttone/search/ServerListener.java
Java
asf20
150
package com.besttone.search; import com.besttone.app.SuggestionProvider; import com.besttone.search.R.color; import com.besttone.search.util.LogUtils; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.provider.SearchRecentSuggestions; import android.util.DisplayMetrics; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ListAdapter; import android.widget.TextView; public class MainActivity extends Activity { private GridView grid; private DisplayMetrics localDisplayMetrics; private View view; private Button btn_city_search; private Button mSearchBtn; private SearchRecentSuggestions suggestions; public void onCreate(Bundle bundle) { super.onCreate(bundle); requestWindowFeature(Window.FEATURE_NO_TITLE); view = this.getLayoutInflater().inflate(R.layout.main, null); setContentView(view); btn_city_search = (Button) findViewById(R.id.btn_city); btn_city_search.setOnClickListener(searchCityListner); mSearchBtn = ((Button)findViewById(R.id.start_search)); mSearchBtn.setOnClickListener(searchHistroyListner); localDisplayMetrics = getResources().getDisplayMetrics(); suggestions = new SearchRecentSuggestions(this, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE); grid = (GridView)view.findViewById(R.id.my_grid); ListAdapter adapter = new GridAdapter(this); grid.setAdapter(adapter); grid.setOnItemClickListener(mOnClickListener); } private Button.OnClickListener searchHistroyListner = new Button.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(); intent.setClass(MainActivity.this, SearchActivity.class); startActivity(intent); } }; private Button.OnClickListener searchCityListner = new Button.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(); intent.setClass(MainActivity.this, SelectCityActivity.class); intent.putExtra("SelectCityName", btn_city_search.getText().toString()); startActivityForResult(intent, 100); } }; protected void onActivityResult(int requestCode, int resultCode, Intent data) { LogUtils.i("resultCode:" + resultCode + ", requestCode:" + requestCode); String str = null; String cityName = (String) this.btn_city_search.getText(); if (resultCode == RESULT_OK) { str = data.getStringExtra("cityName"); LogUtils.d(LogUtils.LOG_TAG, "new city:" + str); LogUtils.d(LogUtils.LOG_TAG, "old city:" + cityName); super.onActivityResult(requestCode, resultCode, data); this.btn_city_search.setText(str); } } private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position,long id) { TextView text = (TextView)v.findViewById(R.id.activity_name); String keyword = text.getText().toString(); Intent intent = new Intent(); if (keyword != null) { if ("更多".equals(keyword)) { intent.setClass(MainActivity.this, MoreKeywordActivity.class); startActivity(intent); } else { intent.setClass(MainActivity.this, SearchResultActivity.class); Bundle bundle = new Bundle(); bundle.putString("keyword", keyword); intent.putExtras(bundle); suggestions.saveRecentQuery(keyword, null); startActivity(intent); } } } }; public class GridAdapter extends BaseAdapter { private LayoutInflater inflater; public GridAdapter(Context context) { inflater = LayoutInflater.from(context); } public final int getCount() { return 6; } public final Object getItem(int paramInt) { return null; } public final long getItemId(int paramInt) { return paramInt; } public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) { paramView = inflater.inflate(R.layout.activity_label_item, null); TextView text = (TextView)paramView.findViewById(R.id.activity_name); text.setTextSize(15); text.setTextColor(color.text_color_grey); switch(paramInt) { case 0: { text.setText("KTV"); Drawable draw = getResources().getDrawable(R.drawable.ktv); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 1: { text.setText("宾馆"); Drawable draw = getResources().getDrawable(R.drawable.hotel); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 2: { text.setText("加油站"); Drawable draw = getResources().getDrawable(R.drawable.gas); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 3: { text.setText("川菜"); Drawable draw = getResources().getDrawable(R.drawable.chuan); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 4: { text.setText("快递"); Drawable draw = getResources().getDrawable(R.drawable.kuaidi); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 5: { text.setText("更多"); Drawable draw = getResources().getDrawable(R.drawable.more); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } // case 6: // { // text.setText("最近浏览"); // Drawable draw = getResources().getDrawable(R.drawable.home_button_history); // draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); // text.setCompoundDrawables(null, draw, null, null); // break; // } // // case 7: // { // text.setText("个人中心"); // Drawable draw = getResources().getDrawable(R.drawable.home_button_myzone); // draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); // text.setCompoundDrawables(null, draw, null, null); // break; // } // case 8: // { // text.setText("更多"); // Drawable draw = getResources().getDrawable(R.drawable.home_button_more); // draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); // text.setCompoundDrawables(null, draw, null, null); // break; // } } paramView.setMinimumHeight((int)(96.0F * localDisplayMetrics.density)); paramView.setMinimumWidth(((-12 + localDisplayMetrics.widthPixels) / 3)); return paramView; } } protected static final int MENU_ABOUT = Menu.FIRST; protected static final int MENU_Quit = Menu.FIRST+1; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_ABOUT, 0, " 关于 ..."); menu.add(0, MENU_Quit, 0, " 结束 "); return true; } public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case MENU_ABOUT: openOptionsDialog(); break; case MENU_Quit: showExitAlert(); break; } return true; } private void openOptionsDialog() { new AlertDialog.Builder(MainActivity.this) .setTitle(R.string.about_title) .setMessage(R.string.about_msg) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialoginterface, int i) {} }) .setNegativeButton(R.string.homepage_label, new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialoginterface, int i){ //go to url Uri uri = Uri.parse(getString(R.string.homepage_uri)); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } }) .show(); } public boolean onKeyDown(int keyCode, KeyEvent event) { // 按下键盘上返回按钮 if(keyCode == KeyEvent.KEYCODE_BACK ){ showExitAlert(); return true; } else { return super.onKeyDown(keyCode, event); } } private void showExitAlert() { new AlertDialog.Builder(this) .setTitle(R.string.prompt) .setMessage(R.string.quit_desc) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {} }) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { exitApp(); } }).show(); } //彻底关闭程序 protected void exitApp() { super.onDestroy(); Client.release(); System.exit(0); // 或者下面这种方式 // android.os.Process.killProcess(android.os.Process.myPid()); } }
114ch
version_without_location/src/com/besttone/search/MainActivity.java
Java
asf20
9,722
package com.besttone.search; import java.util.ArrayList; import java.util.List; import com.besttone.widget.AlphabetBar; import android.R.integer; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.besttone.adapter.CityListAdapter; import com.besttone.search.model.City; import com.besttone.search.sql.NativeDBHelper; import com.besttone.search.util.LogUtils; import com.besttone.search.util.SharedUtils; public class SelectCityActivity extends CityListBaseActivity { private ImageButton btn_back; private Context mContext; private NativeDBHelper mDB; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); //this.imm = ((InputMethodManager)getSystemService("input_method")); btn_back = (ImageButton) findViewById(R.id.left_title_button); btn_back.setOnClickListener(backListner); } private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() { public void onClick(View v) { finish(); } }; private void selectComplete(City paramCity) { String simplifyCode = ""; if(paramCity!=null && paramCity.getCityCode()!=null) { simplifyCode = paramCity.getCityCode(); if(simplifyCode.endsWith("00")) { simplifyCode = simplifyCode.substring(0, simplifyCode.length()-2); } if(simplifyCode.endsWith("00")) { simplifyCode = simplifyCode.substring(0, simplifyCode.length()-2); } } paramCity.setSimplifyCode(simplifyCode); SharedUtils.setCurrentCity(this.mContext, paramCity); Intent localIntent = getIntent(); localIntent.putExtra("cityName", paramCity.getCityName()); setResult(RESULT_OK, localIntent); finish(); } @Override public void addCityFirstLetter() { if (this.mCityFirstLetter.length <= 0) return; String str = null; Cursor localCursor = null; for (int i = 1; i < this.mCityFirstLetter.length; i++) { str = this.mCityFirstLetter[i]; String[] arrayParm = new String[2]; arrayParm[0] = "2"; arrayParm[1] = (str + "%"); localCursor = this.mDB.select(null, "TYPE=? AND FIRST_PY like ?", arrayParm); if (localCursor != null) if (localCursor.moveToNext()) { City localCity1 = new City(); localCity1.setCityName("-1"); localCity1.setFirstLetter(str); this.citylist.add(localCity1); } while (true) { if (localCursor.isAfterLast()) { localCursor.close(); break; } City localCity2 = new City(); localCity2.setBusinessFlag(localCursor.getString(12)); localCity2.setCityCode(localCursor.getString(1)); localCity2.setCityId(localCursor.getString(0)); localCity2.setCityName(localCursor.getString(5)); localCity2.setFirstPy(localCursor.getString(6)); localCity2.setAreaCode(localCursor.getString(9)); localCity2.setProvinceCode(localCursor.getString(2)); localCity2.setFirstLetter(str); this.citylist.add(localCity2); localCursor.moveToNext(); } } } public void addHotCityFirstLetter() { if (this.mCityFirstLetter.length <= 0) return; String str; do { str = this.mCityFirstLetter[0]; } while (this.mHotCursor == null); if (this.mHotCursor.moveToNext()) { City localCity1 = new City(); localCity1.setCityName("-1"); localCity1.setFirstLetter(str); this.citylist.add(localCity1); } while (true) { if (this.mHotCursor.isAfterLast()) { this.mHotCursor.close(); break; } City localCity2 = new City(); localCity2.setBusinessFlag(this.mHotCursor.getString(12)); localCity2.setCityCode(this.mHotCursor.getString(1)); localCity2.setCityId(this.mHotCursor.getString(0)); localCity2.setCityName(this.mHotCursor.getString(5)); localCity2.setFirstPy(this.mHotCursor.getString(6)); localCity2.setAreaCode(this.mHotCursor.getString(9)); localCity2.setProvinceCode(this.mHotCursor.getString(2)); localCity2.setFirstLetter(str); this.citylist.add(localCity2); this.mHotCursor.moveToNext(); } } public void initAutoData() { ArrayList localArrayList = new ArrayList(); for (int i = this.mHotCount;; i++) { if (i >= this.citylist.size()) { this.mAutoAdapter = new ArrayAdapter(this, R.id.selected_item, R.id.city_info, localArrayList); return; } City localCity = (City) this.citylist.get(i); if ((localCity.getFirstPy() == null) || (localCity.getCityName() == null)) continue; localArrayList.add(localCity.getCityName()); localArrayList.add(localCity.getFirstPy() + "," + localCity.getCityName()); } } public void initDBHelper() { this.mAutoTextView = ((EditText) findViewById(R.id.change_city_auto_text)); this.mDB = NativeDBHelper.getInstance(this); this.mHotCursor = this.mDB.select(null, "IS_FREQUENT = '1' ORDER BY CAST(SORT_VALUE AS INTEGER)", null); } public void setAdapter() { this.mListView = ((ListView) findViewById(R.id.city_list)); this.mListAdapter = new CityListAdapter(this, this.citylist); this.mListView.setAdapter(this.mListAdapter); this.mAutoListView = ((ListView) findViewById(R.id.auto_city_list)); this.mAutoCityAdapter = new AutoCityAdapter(this); this.mAutoListView.setAdapter(this.mAutoCityAdapter); this.mAutoListView.setVisibility(View.GONE); } public void setAutoCompassTextViewOnItemClickListener() { mAutoListView.setOnItemClickListener(cityAutoTvOnClickListener); // this.mAutoTextView.setOnItemClickListener(cityAutoTvOnClickListener); } public void setFirstletter() { this.mCityFirstLetter = getResources().getStringArray( R.array.city_first_letter); } public void setListViewOnItemClickListener() { this.mListView.setOnItemClickListener(cityLvOnClickListener); } public void setTheContentView() { requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.select_city); } private AdapterView.OnItemClickListener cityLvOnClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { ListView listView = (ListView) parent; City localCity = (City) listView.getItemAtPosition(position); if (!"-1".equals(localCity.getCityName())) { // Toast.makeText(SelectCityActivity.this, // "你选择的城市是" + localCity.getCityName(), Toast.LENGTH_SHORT) // .show(); selectComplete(localCity); } } }; private AdapterView.OnItemClickListener cityAutoTvOnClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { String str1 = (String) mAutoCityAdapter.getItem(position); if (str1.contains(",")) { for (String str2 = str1.split(",")[1];; str2 = str1) { String[] arrayOfString = new String[2]; arrayOfString[0] = "2"; arrayOfString[1] = str2.trim(); Cursor localCursor = mDB.select(null, "TYPE=? AND SHORT_NAME=?", arrayOfString); if (localCursor.moveToFirst()) { City localCity = new City(); localCity.setAreaCode(localCursor.getString(9)); localCity.setCityCode(localCursor.getString(1)); localCity.setCityId(localCursor.getString(0)); localCity.setCityName(localCursor.getString(5)); localCity.setProvinceCode(localCursor.getString(2)); selectComplete(localCity); } return; } } } }; protected void onPause() { super.onPause(); //this.imm.hideSoftInputFromInputMethod(this.mAutoTextView.getWindowToken(), 0); } protected void onResume() { super.onResume(); //this.imm.hideSoftInputFromInputMethod(this.mAutoTextView.getWindowToken(), 0); } public void onScrollStateChanged(AbsListView paramAbsListView, int paramInt) { } }
114ch
version_without_location/src/com/besttone/search/SelectCityActivity.java
Java
asf20
8,434
package com.besttone.search; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.SearchRecentSuggestions; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.besttone.app.SuggestionProvider; import com.besttone.http.WebServiceHelper; import com.besttone.http.WebServiceHelper.WebServiceListener; import com.besttone.search.util.SharedUtils; import com.besttone.widget.EditSearchBar; import com.besttone.widget.EditSearchBar.OnKeywordChangeListner; import java.util.ArrayList; import java.util.List; public class SearchActivity extends Activity implements EditSearchBar.OnKeywordChangeListner{ private View view; private ImageButton btn_back; private ListView histroyListView; private EditText field_keyword; private Button mSearchBtn; private ImageButton mClearBtn; private EditSearchBar editSearchBar; private HistoryAdapter historyAdapter; private ArrayList<String> historyData = new ArrayList<String>(); private ArrayList<String> keywordList = new ArrayList<String>(); private SearchRecentSuggestions suggestions; private Handler mhandler=new Handler(); public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); view = this.getLayoutInflater().inflate(R.layout.search_histroy, null); setContentView(view); suggestions = new SearchRecentSuggestions(this, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE); histroyListView = (ListView) findViewById(R.id.search_histroy); historyAdapter = new HistoryAdapter(this); histroyListView.setAdapter(historyAdapter); histroyListView.setOnItemClickListener(mOnClickListener); field_keyword = (EditText) findViewById(R.id.search_edit); mSearchBtn = (Button) findViewById(R.id.begin_search); mSearchBtn.setOnClickListener(searchListner); // mClearBtn = (ImageButton) findViewById(R.id.search_clear); // mClearBtn.setOnClickListener(clearListner); btn_back = (ImageButton) findViewById(R.id.left_title_button); btn_back.setOnClickListener(backListner); editSearchBar = (EditSearchBar)findViewById(R.id.search_bar); editSearchBar.setOnKeywordChangeListner(this); } private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() { public void onClick(View v) { finish(); } }; private ImageButton.OnClickListener clearListner = new ImageButton.OnClickListener() { public void onClick(View v) { mClearBtn.setVisibility(View.GONE); field_keyword.setHint(R.string.search_hint); } }; private Button.OnClickListener searchListner = new Button.OnClickListener() { public void onClick(View v) { if(NetWorkStatus()) { String keyword = field_keyword.getText().toString(); if(keyword!=null && !"".equals(keyword)) { String simplifyCode = SharedUtils.getCurrentSimplifyCode(SearchActivity.this); Log.v("simplifyCode", simplifyCode); Intent intent = new Intent(); intent.setClass(SearchActivity.this, SearchResultActivity.class); Bundle bundle = new Bundle(); bundle.putString("simplifyCode", simplifyCode); bundle.putString("keyword", keyword); intent.putExtras(bundle); suggestions.saveRecentQuery(keyword, null); finish(); startActivity(intent); } else { Toast.makeText(SearchActivity.this, "搜索关键词为空", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(SearchActivity.this, "网络异常,没有可用网络", Toast.LENGTH_SHORT).show(); } } }; private ListView.OnItemClickListener mOnClickListener = new ListView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { ListView listView = (ListView) parent; String searchHistory = (String) listView.getItemAtPosition(position); if(searchHistory!=null && "清空搜索记录".equals(searchHistory)){ suggestions.clearHistory(); finish(); } else if(!"没有搜索记录".equals(searchHistory)){ Intent intent = new Intent(); intent.setClass(SearchActivity.this, SearchResultActivity.class); Bundle bundle = new Bundle(); bundle.putString("keyword", searchHistory); intent.putExtras(bundle); finish(); startActivity(intent); } } }; public class HistoryAdapter extends BaseAdapter { private LayoutInflater mInflater; public HistoryAdapter(Context context) { this.mInflater = LayoutInflater.from(context); historyData = getData(); } public int getCount() { return historyData.size(); } public Object getItem(int position) { return historyData.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(R.layout.search_history_item, null); String searchRecord = historyData.get(position); ((TextView) convertView.findViewById(R.id.history_text1)).setText(searchRecord); return convertView; } } public ArrayList<String> getData() { historyData = new ArrayList<String>(); String sortStr = " _id desc"; ContentResolver contentResolver = getContentResolver(); Uri quri = Uri.parse("content://" + SuggestionProvider.AUTHORITY + "/suggestions"); Cursor localCursor = contentResolver.query(quri, SuggestionProvider.COLUMNS, null, null, sortStr); if (localCursor!=null && localCursor.getCount()>0) { localCursor.moveToFirst(); while (true) { if (localCursor.isAfterLast()) { localCursor.close(); break; } historyData.add(localCursor.getString(1)); localCursor.moveToNext(); } } return historyData; } private boolean NetWorkStatus() { boolean netSataus = false; ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); cwjManager.getActiveNetworkInfo(); if (cwjManager.getActiveNetworkInfo() != null) { netSataus = cwjManager.getActiveNetworkInfo().isAvailable(); } return netSataus; } public void onKeywordChanged(final String paramString) { //获取联想关键词 final WebServiceHelper serviceHelper = new WebServiceHelper(); if(paramString!=null && !"".equals(paramString)){ Client.getThreadPoolForRequest().execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub keywordList=serviceHelper.getAssociateList(paramString); if(keywordList!=null && keywordList.size()>0){ historyData = keywordList; }else{ historyData = getData(); } Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub // for(int i=0;i<historyData.size();i++) // { // Log.d("historyData",""+historyData.get(i)); // } historyAdapter.notifyDataSetChanged(); } }); } }); } else { historyData = getData(); historyAdapter.notifyDataSetChanged(); } // ArrayList<String> keywordList = new ArrayList<String>(); // WebServiceHelper serviceHelper = new WebServiceHelper(); // if(paramString!=null && !"".equals(paramString)){ // keywordList = serviceHelper.getAssociateList(paramString); // } else { // historyData = getData(); // } // // if(keywordList!=null && keywordList.size()>0){ // historyData = keywordList; // }else{ // historyData = getData(); // } // historyAdapter.notifyDataSetChanged(); } }
114ch
version_without_location/src/com/besttone/search/SearchActivity.java
Java
asf20
8,549
package com.besttone.search.util; import com.besttone.search.model.RequestInfo; public class XmlHelper { public static String getRequestXml(RequestInfo info) { StringBuilder sb = new StringBuilder(""); if(info!=null) { sb.append("<RequestInfo>"); sb.append("<region><![CDATA["+info.getRegion()+"]]></region>"); sb.append("<deviceid><![CDATA["+info.getDeviceid()+"]]></deviceid>"); sb.append("<imsi><![CDATA["+info.getImsi()+"]]></imsi>"); sb.append("<content><![CDATA["+info.getContent()+"]]></content>"); if(info.getPage()!=null){ sb.append("<Page><![CDATA["+info.getPage()+"]]></Page>"); } if(info.getPageSize()!=null){ sb.append("<PageSize><![CDATA["+info.getPageSize()+"]]></PageSize>"); } if(info.getMobile()!=null){ sb.append("<mobile><![CDATA["+info.getMobile()+"]]></mobile>"); } if(info.getMobguishu()!=null){ sb.append("<mobguishu><![CDATA["+info.getMobguishu()+"]]></mobguishu>"); } sb.append("</RequestInfo>"); } return sb.toString(); } }
114ch
version_without_location/src/com/besttone/search/util/XmlHelper.java
Java
asf20
1,053
package com.besttone.search.util; public class LogUtils { public static final boolean IF_LOG = false; public static final String LOG_TAG = "zwj-code"; public static void d(String paramString) { } public static void d(String paramString1, String paramString2) { } public static void e(String paramString) { } public static void e(String paramString1, String paramString2) { } public static void e(String paramString, Throwable paramThrowable) { } public static void i(String paramString) { } public static void i(String paramString1, String paramString2) { } }
114ch
version_without_location/src/com/besttone/search/util/LogUtils.java
Java
asf20
609
package com.besttone.search.util; public class StringUtils { public static String getDateByTime(String paramString) { if ((isEmpty(paramString)) || (paramString.length() < 16)); while (true) { paramString = paramString.substring(0, 10); } } public static String getString(String paramString) { if ((paramString == null) || ("null".equals(paramString)) || ("NULL".equals(paramString))) paramString = ""; return paramString; } public static boolean isEmpty(String paramString) { if (paramString == null) return true; if (paramString!=null && paramString.trim().length() == 0) return true; return false; } public static String toZero(String paramString) { if (paramString == null) paramString = "0"; return paramString; } }
114ch
version_without_location/src/com/besttone/search/util/StringUtils.java
Java
asf20
803
package com.besttone.search.util; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.text.TextUtils; import com.besttone.search.model.City; import com.besttone.search.model.PhoneInfo; public class SharedUtils { public static final String Custom_Channel = "custom_channel"; public static final String Data_Selected_City = "Data_Selected_City"; public static final String First_Selected_City = "First_Selected_City"; public static final String Location_AreaCode = "Location_AreaCode"; public static final String Location_City = "Location_City"; public static final String Location_CityCode = "Location_CityCode"; public static final String Location_CityId = "Location_CityId"; public static final String Location_ProvinceCode = "Location_ProvinceCode"; public static final String NOTIFICATION_SET = "notification_set"; public static final String SHORT_CUT_INSTALLED = "short_cut_installed"; public static final String Switch_City_Notice = "Switch_City_Notice"; public static final String Total_Channel = "total_channel"; public static SharedPreferences mPreference; public static String getCurrentCityCode(Context paramContext) { return getPreference(paramContext).getString("Location_CityCode", ""); } public static String getCurrentCityId(Context paramContext) { return getPreference(paramContext).getString("Location_CityId", ""); } public static String getCurrentCityName(Context paramContext) { return getPreference(paramContext).getString("Location_City", ""); } public static String getCurrentProvinceCode(Context paramContext) { return getPreference(paramContext).getString("Location_ProvinceCode", ""); } public static String getCurrentSimplifyCode(Context paramContext) { return getPreference(paramContext).getString("Location_SimplifyCode", ""); } public static long getNotificationHistory(Context paramContext, String paramString) { return getPreference(paramContext).getLong(paramString, 0L); } public static int getNotificationSet(Context paramContext) { return getPreference(paramContext).getInt("notification_set", 0); } public static SharedPreferences getPreference(Context paramContext) { if (mPreference == null) mPreference = PreferenceManager .getDefaultSharedPreferences(paramContext); return mPreference; } public static String getUseVersion(Context paramContext) { return getPreference(paramContext).getString("USE_VERSION", ""); } public static String getVersionChannelList(Context paramContext) { String str1 = getUseVersion(paramContext); String str2 = getPreference(paramContext).getString( "CHANNEL_VERSION_" + str1, ""); LogUtils.d("getCityChannelList: CHANNEL_VERSION_" + str1 + ", " + str2); return str2; } public static boolean hasShowHelp(Context paramContext) { return getPreference(paramContext).getBoolean("SHOW_HELP", false); } public static boolean isFirstSelectedCityComplete(Context paramContext) { return getPreference(paramContext).getBoolean("First_Selected_City", false); } public static boolean isShortCutInstalled(Context paramContext) { return getPreference(paramContext).getBoolean("short_cut_installed", false); } public static boolean isShowSwitchCityNotice(Context paramContext) { return getPreference(paramContext).getBoolean("Switch_City_Notice", true); } public static void setCurrentCity(Context paramContext, City paramCity) { SharedPreferences.Editor localEditor = getPreference(paramContext) .edit(); localEditor.putString("Location_City", paramCity.getCityName()); localEditor.putString("Location_CityCode", paramCity.getCityCode()); localEditor.putString("Location_CityId", paramCity.getCityId()); localEditor.putString("Location_ProvinceCode", paramCity.getProvinceCode()); localEditor.putString("Location_AreaCode", paramCity.getAreaCode()); localEditor.putString("Location_SimplifyCode", paramCity.getSimplifyCode()); LogUtils.d("setCurrentCity================"); LogUtils.d("cityCode:" + paramCity.getCityCode()); LogUtils.d("cityName:" + paramCity.getCityName()); LogUtils.d("areaCode:" + paramCity.getAreaCode()); LogUtils.d("SimplifyCode:" + paramCity.getSimplifyCode()); localEditor.commit(); } public static void setFirstSelectedCityComplete(Context paramContext) { getPreference(paramContext).edit() .putBoolean("First_Selected_City", true).commit(); } public static void setNotificationHistory(Context paramContext, String paramString, long paramLong) { if (!TextUtils.isEmpty(paramString)) { getPreference(paramContext).edit().putLong(paramString, paramLong) .commit(); LogUtils.d("SET:" + paramString + " ," + paramLong); } } public static void setNotificationSet(Context paramContext, int paramInt) { getPreference(paramContext).edit().putInt("notification_set", paramInt) .commit(); } public static void setShortCutInstalled(Context paramContext) { getPreference(paramContext).edit() .putBoolean("short_cut_installed", true).commit(); } public static void setShowHelp(Context paramContext) { getPreference(paramContext).edit().putBoolean("SHOW_HELP", true) .commit(); } public static void setSwitchCityNotice(Context paramContext, boolean paramBoolean) { getPreference(paramContext).edit() .putBoolean("Switch_City_Notice", paramBoolean).commit(); } public static void setUseVersion(Context paramContext, String paramString) { getPreference(paramContext).edit() .putString("USE_VERSION", paramString).commit(); LogUtils.d("setUseVersion: " + paramString); } public static void setVersionChannelList(Context paramContext, String paramString1, String paramString2) { getPreference(paramContext).edit() .putString("CHANNEL_VERSION_" + paramString1, paramString2) .commit(); LogUtils.d("setCityChannelList: CHANNEL_VERSION_" + paramString1 + ", " + paramString2); } public static boolean versionListExist(Context paramContext, String paramString) { if (getPreference(paramContext).contains( "CHANNEL_VERSION_" + paramString)) LogUtils.d("Version:" + paramString + "Exist!"); return true; } public static void setCurrentPhoneInfo(Context paramContext, PhoneInfo info) { SharedPreferences.Editor localEditor = getPreference(paramContext) .edit(); localEditor.putString("Phone_DeviceId", info.getImei()); localEditor.putString("Phone_Imsi", info.getImsi()); localEditor.putString("Phone_No", info.getPhoneNo()); localEditor.putString("Phone_Provider", info.getProvider()); localEditor.commit(); } public static String getCurrentPhoneDeviceId(Context paramContext) { return getPreference(paramContext).getString("Phone_DeviceId", ""); } public static String getCurrentPhoneImsi(Context paramContext) { return getPreference(paramContext).getString("Phone_Imsi", ""); } public static String getCurrentPhoneNo(Context paramContext) { return getPreference(paramContext).getString("Phone_No", ""); } public static String getCurrentPhoneProvider(Context paramContext) { return getPreference(paramContext).getString("Phone_Provider", ""); } }
114ch
version_without_location/src/com/besttone/search/util/SharedUtils.java
Java
asf20
7,402
package com.besttone.search.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.logging.Logger; public class MD5Builder { public static Logger logger = Logger.getLogger("MD5Builder"); // 用来将字节转换成 16 进制表示的字符 public static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** * 对文件全文生成MD5摘要 * * @param file * 要加密的文件 * @return MD5摘要码 */ public static String getMD5(File file) { FileInputStream fis = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); logger.info("MD5摘要长度:" + md.getDigestLength()); fis = new FileInputStream(file); byte[] buffer = new byte[2048]; int length = -1; logger.info("开始生成摘要"); long s = System.currentTimeMillis(); while ((length = fis.read(buffer)) != -1) { md.update(buffer, 0, length); } logger.info("摘要生成成功,总用时: " + (System.currentTimeMillis() - s) + "ms"); byte[] b = md.digest(); return byteToHexString(b); // 16位加密 // return buf.toString().substring(8, 24); } catch (Exception ex) { ex.printStackTrace(); return null; } finally { try { fis.close(); } catch (IOException ex) { ex.printStackTrace(); } } } /** * 对一段String生成MD5加密信息 * * @param message * 要加密的String * @return 生成的MD5信息 */ public static String getMD5(String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); logger.info("MD5摘要长度:" + md.getDigestLength()); byte[] b = md.digest(message.getBytes()); return byteToHexString(b); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /** * 把byte[]数组转换成十六进制字符串表示形式 * * @param tmp * 要转换的byte[] * @return 十六进制字符串表示形式 */ private static String byteToHexString(byte[] tmp) { String s; // 用字节表示就是 16 个字节 char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符, // 所以表示成 16 进制需要 32 个字符 int k = 0; // 表示转换结果中对应的字符位置 for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节 // 转换成 16 进制字符的转换 byte byte0 = tmp[i]; // 取第 i 个字节 str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, // >>> 为逻辑右移,将符号位一起右移 str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换 } s = new String(str); // 换后的结果转换为字符串 return s; } /** * * @param message * @return */ public static String getMD5Str(String source) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); byte[] byteArray = messageDigest.digest(source.getBytes("UTF-8")); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } } return md5StrBuff.toString(); } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) { String tmp = "sasdfafd"; System.out.println(getMD5(tmp)); System.out.println(getMD5Str(tmp)); } }
114ch
version_without_location/src/com/besttone/search/util/MD5Builder.java
Java
asf20
4,399
package com.besttone.search.util; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.besttone.search.model.City; import com.besttone.search.model.District; import com.besttone.search.sql.NativeDBHelper; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.util.DisplayMetrics; public class Constants { public static String appKey = "50D033D17E0140F1919EF0508FC9A41E"; public static String appSecret = "35D31BE854EC4F2BAF9F9A61821C7460"; public static String apiName = "mobile"; public static String apiMethod = "getMobileByIMSI"; // public static String serverAddress = // "http://116.228.55.196:8060/open_api/"; public static String serverAddress = "http://open.118114.cn/api"; // public static String serverAddress = "http://116.228.55.106/api"; public static String abServerAddress = "http://openapi.aibang.com/search"; // public static String abAppKey = "a312b2321506db8a3a566370fdca7e29"; public static String abAppKey = "f41c8afccc586de03a99c86097e98ccb"; public static String SPACE = ""; public static int PAGE_SIZE = 10; // 测试地址 public static final String serviceURL = "http://116.228.55.13:8085/ch_trs_ws/ch_search"; public static String chName= "jichu_client"; public static String chKey = "123456"; //public static final String serviceURL = "http://116.228.55.103:9273/ch_trs_ws/ch_search"; // public static String chName = "jichu_client"; // public static String chKey = "j0c7c2t9"; //关键词联想 public static String associate_method = "searchCHkeyNum"; public static final String NATIVE_DATABASE_NAME = "native_database.db"; public static int mDeviceHeight; public static int mDeviceWidth = 0; static { mDeviceHeight = 0; } public static void copyNativeDB(Context paramContext, InputStream paramInputStream) { try { File localFile1 = new File("/data/data/" + paramContext.getPackageName() + "/databases/"); if (!localFile1.exists()) localFile1.mkdir(); String str = "/data/data/" + paramContext.getPackageName() + "/databases/" + "native_database.db"; File localFile2 = new File(str); if (localFile2.exists()) localFile2.delete(); FileOutputStream localFileOutputStream = new FileOutputStream(str); byte[] arrayOfByte = new byte[18000]; while (true) { int i = paramInputStream.read(arrayOfByte); if (i <= 0) { localFileOutputStream.close(); paramInputStream.close(); break; } localFileOutputStream.write(arrayOfByte, 0, i); } } catch (Exception localException) { } } public static City getCity(Context paramContext, String paramString) { City localCity = null; if ((paramString != null) && (!paramString.equals(""))) { NativeDBHelper localNativeDBHelper = NativeDBHelper .getInstance(paramContext); String[] arrayOfString = new String[2]; arrayOfString[0] = "2"; arrayOfString[1] = paramString.trim(); Cursor localCursor = localNativeDBHelper.select(null, "TYPE=? AND REGION_CODE=?", arrayOfString); if ((localCursor != null) && (localCursor.getCount() > 0) && (localCursor.moveToFirst())) { localCity = new City(); localCity.setAreaCode(localCursor.getString(9)); localCity.setCityCode(localCursor.getString(1)); localCity.setCityId(localCursor.getString(0)); localCity.setCityName(localCursor.getString(5)); localCity.setProvinceCode(localCursor.getString(2)); } if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); } return localCity; } public static String getCityCode(Context paramContext, String paramString) { String str = ""; if ((paramString != null) && (!paramString.equals(""))) { NativeDBHelper localNativeDBHelper = NativeDBHelper .getInstance(paramContext); if (!paramString.startsWith("0")) paramString = "0" + paramString; String[] arrayOfString1 = new String[4]; arrayOfString1[0] = "ID"; arrayOfString1[1] = "REGION_CODE"; arrayOfString1[2] = "NAME"; arrayOfString1[3] = "AREA_CODE"; String[] arrayOfString2 = new String[2]; arrayOfString2[0] = "2"; arrayOfString2[1] = paramString; Cursor localCursor = localNativeDBHelper.select(arrayOfString1, "TYPE=? AND AREA_CODE=?", arrayOfString2); if ((localCursor != null) && (localCursor.getCount() > 0) && (localCursor.moveToFirst())) str = localCursor.getString(1); if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); } return str; } public static String getCodeByName(Context paramContext, String paramString) { String str = null; NativeDBHelper localNativeDBHelper = NativeDBHelper .getInstance(paramContext); Cursor localCursor = localNativeDBHelper.selectCodeByName(paramString); if ((localCursor != null) && (localCursor.getCount() > 0)) localCursor.moveToFirst(); while (true) { if (localCursor.isAfterLast()) { if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); } str = localCursor.getString(1); localCursor.moveToNext(); return str; } } public static String getSimplifyCodeByName(Context paramContext, String paramString) { String cityCode = getCodeByName(paramContext, paramString); return getSimplifyCode(cityCode); } public static int getDeviceWidth(Activity paramActivity) { if (mDeviceWidth == 0) { DisplayMetrics localDisplayMetrics = new DisplayMetrics(); paramActivity.getWindowManager().getDefaultDisplay() .getMetrics(localDisplayMetrics); mDeviceWidth = localDisplayMetrics.widthPixels; } return mDeviceWidth; } public static String[] getDistrictArray(Context paramContext, String paramString) { String[] arrayOfString = null; List localList = getDistrictList(paramContext, paramString); if ((localList != null) && (localList.size() > 0)) { arrayOfString = new String[1 + localList.size()]; arrayOfString[0] = "全部区域"; } for (int i = 0; ; i++) { if (i >= localList.size()) return arrayOfString; arrayOfString[(i + 1)] = ((District)localList.get(i)).getDistrictName(); } } public static List<District> getDistrictList(Context paramContext, String paramString) { ArrayList localArrayList = null; NativeDBHelper localNativeDBHelper = NativeDBHelper.getInstance(paramContext); paramString = paramString.substring(0,2) + "%"; Cursor localCursor = localNativeDBHelper.selectDistrict(paramString); if ((localCursor != null) && (localCursor.getCount() > 0)) { localArrayList = new ArrayList(); localCursor.moveToFirst(); } while (true) { if (localCursor.isAfterLast()) { if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); return localArrayList; } District localDistrict = new District(); localDistrict.setDistrictId(localCursor.getString(0)); localDistrict.setDistrictName(localCursor.getString(4)); localDistrict.setDistrictCode(localCursor.getString(1)); localDistrict.setCityCode(localCursor.getString(2)); String simplifyCode = localCursor.getString(2); if (simplifyCode != null && simplifyCode.endsWith("00")) { simplifyCode = simplifyCode.substring(0, simplifyCode.length() - 2); } if (simplifyCode != null && simplifyCode.endsWith("00")) { simplifyCode = simplifyCode.substring(0, simplifyCode.length() - 2); } localDistrict.setSimplifyCode(simplifyCode); localArrayList.add(localDistrict); localCursor.moveToNext(); } } public static JSONObject getJSONObject(HashMap<String, String> paramHashMap) { JSONObject localJSONObject = new JSONObject(); Iterator localIterator = paramHashMap.entrySet().iterator(); while (true) { if (!localIterator.hasNext()) return localJSONObject; Map.Entry localEntry = (Map.Entry) localIterator.next(); try { localJSONObject.put((String) localEntry.getKey(), localEntry.getValue()); } catch (JSONException localJSONException) { localJSONException.printStackTrace(); } } } public static String getNameByCode(Context paramContext, String paramString) { String str = null; NativeDBHelper localNativeDBHelper = NativeDBHelper .getInstance(paramContext); Cursor localCursor = localNativeDBHelper.selectNameByCode(paramString); if ((localCursor != null) && (localCursor.getCount() > 0)) localCursor.moveToFirst(); while (true) { if (localCursor.isAfterLast()) { if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); return str; } str = localCursor.getString(4); localCursor.moveToNext(); } } public static String getProvinceId(Context paramContext, String paramString) { String str = ""; if (!StringUtils.isEmpty(paramString)) { NativeDBHelper localNativeDBHelper = NativeDBHelper .getInstance(paramContext); String[] arrayOfString1 = new String[1]; arrayOfString1[0] = "ID"; String[] arrayOfString2 = new String[2]; arrayOfString2[0] = "1"; arrayOfString2[1] = paramString; Cursor localCursor = localNativeDBHelper.select(arrayOfString1, "TYPE=? AND REGION_CODE=?", arrayOfString2); if ((localCursor != null) && (localCursor.getCount() > 0) && (localCursor.moveToFirst())) str = localCursor.getString(0); if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); } return str; } public static boolean isBusinessOpen(Context paramContext, String paramString) { boolean flag = false; if ((paramString != null) && (!paramString.equals(""))) { NativeDBHelper localNativeDBHelper = NativeDBHelper .getInstance(paramContext); String[] arrayOfString1 = new String[1]; arrayOfString1[0] = "BUSINESS_FLAG"; String[] arrayOfString2 = new String[1]; arrayOfString2[0] = paramString; Cursor localCursor = localNativeDBHelper.select(arrayOfString1, "REGION_CODE=?", arrayOfString2); if ((localCursor != null) && (localCursor.getCount() > 0) && (localCursor.moveToFirst())) { String str = localCursor.getString(0); if ((str != null) && (str.equals("1"))) flag = true; } if (localCursor != null) localCursor.close(); if (localNativeDBHelper != null) localNativeDBHelper.close(); } return flag; } public static String getSimplifyCode(String cityCode) { if(cityCode!=null) { if(cityCode.endsWith("00")) { cityCode = cityCode.substring(0, cityCode.length()-2); } if(cityCode.endsWith("00")) { cityCode = cityCode.substring(0, cityCode.length()-2); } } return cityCode; } public static boolean isAlphabet(String s) { if(s!=null) { return s.matches("^[a-zA-Z]*$"); } return false; } public static String getCity(String s){ String city = null; if(s!=null && s.trim().length()!=0) { String[] cityArray = s.split("\\|\\|"); int index = cityArray.length - 1; city = cityArray[index]; } return city; } }
114ch
version_without_location/src/com/besttone/search/util/Constants.java
Java
asf20
11,882
package com.besttone.search.util; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.util.Log; import com.besttone.search.model.PhoneInfo; public class PhoneUtil { private static final String TAG = "PhoneUtil"; public PhoneInfo getPhoneNoByIMSI(String imsi) throws Exception { PhoneInfo info; // 生成请求xml String reqXml = createParm(imsi); //返回XML String rtnXml = getRtnXml(reqXml); //DOM方式解析XML info = dealXml(rtnXml); return info; } public PhoneInfo dealXml(String rtnXml) { PhoneInfo info = new PhoneInfo(); try { // 创建解析工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 指定DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder(); // 从文件构造一个Document,因为XML文件中已经指定了编码,所以这里不必了 ByteArrayInputStream is = new ByteArrayInputStream(rtnXml.getBytes("UTF-8")); Document document = builder.parse(is); //得到Document的根 Element root = document.getDocumentElement(); NodeList nodes = root.getElementsByTagName("data"); // 遍历根节点所有子节点 for (int i = 0; i < nodes.getLength(); i++) { // 获取data元素节点 Element phoneElement = (Element) (nodes.item(i)); // 获取data中mobile属性值 info.setPhoneNo(phoneElement.getAttribute("mobile")); } NodeList list = root.getElementsByTagName("error"); // 遍历根节点所有子节点 for (int i = 0; i < list.getLength(); i++) { info.setErrorFlag(true); Element errElement = (Element) (list.item(i)); // 获取errorCode属性 NodeList codeNode = errElement.getElementsByTagName("errorCode"); // 获取errorCode元素 Element codeElement = (Element)codeNode.item(0); //获得errorCode元素的第一个值 String errorCode = codeElement.getFirstChild().getNodeValue(); info.setErrorCode(errorCode); // 获取errorMsg属性 NodeList msgNode = errElement.getElementsByTagName("errorMessage"); // 获取errorMsg元素 Element msgElement = (Element)msgNode.item(0); //获得errorMsg元素的第一个值 String errorMsg = msgElement.getFirstChild().getNodeValue(); info.setErrorMsg(errorMsg); } } catch (Exception e) { Log.e(TAG, "XML解析出错;"+e.getMessage()); } return info; } public String getRtnXml(String reqXml) throws UnsupportedEncodingException, IOException, ClientProtocolException { //返回XML String rtnXml = ""; //http地址 StringBuilder requestUrl = new StringBuilder(Constants.serverAddress); String parm = "?reqXml=" + URLEncoder.encode(reqXml, "UTF-8") + "&sign=" + MD5Builder.getMD5Str(reqXml + Constants.appSecret); requestUrl.append(parm); String httpUrl = requestUrl.toString(); //HttpGet连接对象 HttpGet httpRequest = new HttpGet(httpUrl); //取得HttpClient对象 HttpClient httpclient = new DefaultHttpClient(); //请求HttpClient,取得HttpResponse HttpResponse httpResponse = httpclient.execute(httpRequest); //请求成功 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { //取得返回的字符串 rtnXml = EntityUtils.toString(httpResponse.getEntity()).trim(); } return rtnXml; } public String createParm(String imsi) { StringBuffer parmXml = new StringBuffer(""); parmXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); parmXml.append("<reqXML version=\"1.0\">"); String appKeyParm = "<appKey>" + Constants.appKey + "</appKey>"; String apiNameParm = "<apiName>" + Constants.apiName + "</apiName>"; String apiMethodParm = "<apiMethod>" + Constants.apiMethod + "</apiMethod>"; String timestampParm = "<timestamp>" + getTimeStamp() + "</timestamp>"; parmXml.append(appKeyParm); parmXml.append(apiNameParm); parmXml.append(apiMethodParm); parmXml.append(timestampParm); parmXml.append("<params>"); String mobileParm = "<param name=\"imsi\" value=\"" + imsi + "\"/>"; parmXml.append(mobileParm); parmXml.append("</params>"); parmXml.append("</reqXML>"); String parmXmlStr = parmXml.toString(); return parmXmlStr; } public String getTimeStamp() { String timestamp = ""; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); timestamp = sdf.format(new Date()); return timestamp; } }
114ch
version_without_location/src/com/besttone/search/util/PhoneUtil.java
Java
asf20
5,184
package com.besttone.search.model; public class PhoneInfo { private String model; //手机型号 private String phoneNo; //手机号码 private String imei; //IMEI private String simSN; //sim卡序列号 private String country; //国家 private String providerNo; //运营商编号 private String provider; //运营商 private String imsi; private boolean errorFlag = false;//错误标志位 private String errorCode = "";//错误代码 private String errorMsg = "";//错误信息 public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getPhoneNo() { return phoneNo; } public void setPhoneNo(String phoneNo) { this.phoneNo = phoneNo; } public String getImei() { return imei; } public void setImei(String imei) { this.imei = imei; } public String getSimSN() { return simSN; } public void setSimSN(String simSN) { this.simSN = simSN; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getProviderNo() { return providerNo; } public void setProviderNo(String providerNo) { this.providerNo = providerNo; } public String getProvider() { return provider; } public void setProvider(String provider) { this.provider = provider; } public String getImsi() { return imsi; } public void setImsi(String imsi) { this.imsi = imsi; } public boolean isErrorFlag() { return errorFlag; } public void setErrorFlag(boolean errorFlag) { this.errorFlag = errorFlag; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } }
114ch
version_without_location/src/com/besttone/search/model/PhoneInfo.java
Java
asf20
1,924
package com.besttone.search.model; public class OrgInfo { private String name; private String tel; private String addr; private int chId; private String orgId; private String city; private int regionCode; private int isQymp; private int isDc; private int isDf; private long relevance; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public int getChId() { return chId; } public void setChId(int chId) { this.chId = chId; } public String getOrgId() { return orgId; } public void setOrgId(String orgId) { this.orgId = orgId; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getRegionCode() { return regionCode; } public void setRegionCode(int regionCode) { this.regionCode = regionCode; } public int getIsQymp() { return isQymp; } public void setIsQymp(int isQymp) { this.isQymp = isQymp; } public int getIsDc() { return isDc; } public void setIsDc(int isDc) { this.isDc = isDc; } public int getIsDf() { return isDf; } public void setIsDf(int isDf) { this.isDf = isDf; } public long getRelevance() { return relevance; } public void setRelevance(long relevance) { this.relevance = relevance; } }
114ch
version_without_location/src/com/besttone/search/model/OrgInfo.java
Java
asf20
1,571
package com.besttone.search.model; import java.io.Serializable; public class City implements Serializable { private static final long serialVersionUID = 4060207134630300518L; private String areaCode; private String businessFlag; private String cityCode; private String cityId; private String cityName; private String firstLetter; private String firstPy; private String isFrequent; private String provinceCode; private String provinceId; private String simplifyCode; public String getAreaCode() { return areaCode; } public void setAreaCode(String areaCode) { this.areaCode = areaCode; } public String getBusinessFlag() { return businessFlag; } public void setBusinessFlag(String businessFlag) { this.businessFlag = businessFlag; } public String getCityCode() { return cityCode; } public void setCityCode(String cityCode) { this.cityCode = cityCode; } public String getCityId() { return cityId; } public void setCityId(String cityId) { this.cityId = cityId; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getFirstLetter() { return firstLetter; } public void setFirstLetter(String firstLetter) { this.firstLetter = firstLetter; } public String getFirstPy() { return firstPy; } public void setFirstPy(String firstPy) { this.firstPy = firstPy; } public String getIsFrequent() { return isFrequent; } public void setIsFrequent(String isFrequent) { this.isFrequent = isFrequent; } public String getProvinceCode() { return provinceCode; } public void setProvinceCode(String provinceCode) { this.provinceCode = provinceCode; } public String getProvinceId() { return provinceId; } public void setProvinceId(String provinceId) { this.provinceId = provinceId; } public String getSimplifyCode() { return simplifyCode; } public void setSimplifyCode(String simplifyCode) { this.simplifyCode = simplifyCode; } }
114ch
version_without_location/src/com/besttone/search/model/City.java
Java
asf20
2,116
package com.besttone.search.model; import java.io.Serializable; public class District implements Serializable { private static final long serialVersionUID = 1428165031459553637L; private String cityCode; private String simplifyCode; private String districtCode; private String districtId; private String districtName; public String getCityCode() { return cityCode; } public void setCityCode(String cityCode) { this.cityCode = cityCode; } public String getSimplifyCode() { return simplifyCode; } public void setSimplifyCode(String simplifyCode) { this.simplifyCode = simplifyCode; } public String getDistrictCode() { return districtCode; } public void setDistrictCode(String districtCode) { this.districtCode = districtCode; } public String getDistrictId() { return districtId; } public void setDistrictId(String districtId) { this.districtId = districtId; } public String getDistrictName() { return districtName; } public void setDistrictName(String districtName) { this.districtName = districtName; } }
114ch
version_without_location/src/com/besttone/search/model/District.java
Java
asf20
1,094
package com.besttone.search.model; import java.util.List; public class ChResultInfo { private String source; private String searchFlag; private int count; private int searchTime; private List<OrgInfo> orgList; public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getSearchFlag() { return searchFlag; } public void setSearchFlag(String searchFlag) { this.searchFlag = searchFlag; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getSearchTime() { return searchTime; } public void setSearchTime(int searchTime) { this.searchTime = searchTime; } public List<OrgInfo> getOrgList() { return orgList; } public void setOrgList(List<OrgInfo> orgList) { this.orgList = orgList; } }
114ch
version_without_location/src/com/besttone/search/model/ChResultInfo.java
Java
asf20
893
package com.besttone.search.model; public class RequestInfo { private String region; private String deviceid; private String imsi; private String content; private String Page; private String PageSize; private String mobile; private String mobguishu; public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getDeviceid() { return deviceid; } public void setDeviceid(String deviceid) { this.deviceid = deviceid; } public String getImsi() { return imsi; } public void setImsi(String imsi) { this.imsi = imsi; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getPage() { return Page; } public void setPage(String page) { Page = page; } public String getPageSize() { return PageSize; } public void setPageSize(String pageSize) { PageSize = pageSize; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getMobguishu() { return mobguishu; } public void setMobguishu(String mobguishu) { this.mobguishu = mobguishu; } }
114ch
version_without_location/src/com/besttone/search/model/RequestInfo.java
Java
asf20
1,266
package com.besttone.search; import com.besttone.app.SuggestionProvider; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.provider.SearchRecentSuggestions; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; public class MoreKeywordActivity extends Activity { private View view; private ImageButton btn_back; private ListView keywordListView; private String[] mKeywordArray = null; private SearchRecentSuggestions suggestions; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); requestWindowFeature(Window.FEATURE_NO_TITLE); view = this.getLayoutInflater().inflate(R.layout.more_keyword, null); setContentView(view); btn_back = (ImageButton) findViewById(R.id.left_title_button); btn_back.setOnClickListener(backListner); suggestions = new SearchRecentSuggestions(this, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE); mKeywordArray = getResources().getStringArray(R.array.hot_search_items); keywordListView =(ListView) findViewById(R.id.keyword_list); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.more_keyword_item, mKeywordArray); keywordListView.setFastScrollEnabled(true); keywordListView.setTextFilterEnabled(true); keywordListView.setAdapter(arrayAdapter); keywordListView.setOnItemClickListener(mOnClickListener); } private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() { public void onClick(View v) { finish(); } }; private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { TextView text = (TextView)v; String keyword = text.getText().toString(); Intent intent = new Intent(); intent.setClass(MoreKeywordActivity.this, SearchResultActivity.class); Bundle bundle = new Bundle(); bundle.putString("keyword", keyword); intent.putExtras(bundle); suggestions.saveRecentQuery(keyword, null); startActivity(intent); } }; }
114ch
version_without_location/src/com/besttone/search/MoreKeywordActivity.java
Java
asf20
2,377
package com.besttone.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; public class MarqueeTextView extends TextView { public MarqueeTextView(Context context) { super(context); } public MarqueeTextView(Context context, AttributeSet attrs){ super(context,attrs); } public MarqueeTextView(Context context, AttributeSet attrs, int defStyle){ super(context, attrs, defStyle); } public boolean isFocused(){ return true;// 返回true,任何时候都处于focused状态,就能跑马 } }
114ch
version_without_location/src/com/besttone/widget/MarqueeTextView.java
Java
asf20
584
package com.besttone.widget; import com.besttone.search.R; import android.content.Context; import android.os.Handler; import android.os.Message; import android.text.Editable; import android.text.InputFilter; import android.text.Spanned; import android.text.TextUtils; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; public class EditSearchBar extends LinearLayout implements TextWatcher, View.OnClickListener, TextView.OnEditorActionListener { private static final int CMD_CHANGED = 1; private static final long DEALY = 500L; private MSCButton mBtnMsc; private ImageButton mClear; private Handler mDelayHandler = new Handler() { public void handleMessage(Message paramMessage) { if (paramMessage.what == 1) { String str = (String) paramMessage.obj; if (EditSearchBar.this.mListener != null) EditSearchBar.this.mListener.onKeywordChanged(str); } } }; private EditText mEdit; private OnKeywordChangeListner mListener; private OnStartSearchListner mStartListener; public EditSearchBar(Context paramContext) { super(paramContext); } public EditSearchBar(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); } private void publishKeywordChange(String paramString) { this.mDelayHandler.removeMessages(1); this.mDelayHandler.sendMessageDelayed( this.mDelayHandler.obtainMessage(1, paramString), 500L); } public void afterTextChanged(Editable paramEditable) { } public void beforeTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3) { } public String getKeyword() { String str; if (this.mEdit != null) { str = this.mEdit.getText().toString().trim(); if (TextUtils.isEmpty(str)) this.mEdit.setText(""); } while (true) { str = ""; } } public void onClick(View paramView) { if ((paramView == this.mClear) && (this.mEdit != null)) { this.mEdit.setText(""); publishKeywordChange(""); } } public boolean onEditorAction(TextView paramTextView, int paramInt, KeyEvent paramKeyEvent) { String str = getKeyword(); if ((this.mStartListener != null) && (!TextUtils.isEmpty(str))) { this.mStartListener.onStartSearch(str); return true; } return false; } protected void onFinishInflate() { super.onFinishInflate(); this.mEdit = ((EditText) findViewById(R.id.search_edit)); this.mEdit.addTextChangedListener(this); this.mEdit.setOnEditorActionListener(this); new InputFilter() { private static final String FORBID_CHARS = " ~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/"; private StringBuilder sb = new StringBuilder(); public CharSequence filter(CharSequence paramCharSequence, int paramInt1, int paramInt2, Spanned paramSpanned, int paramInt3, int paramInt4) { String str; if (paramInt1 == paramInt2) str = null; while (true) { this.sb.setLength(0); for (int i = paramInt1;; i++) { if (i >= paramInt2) { if (this.sb.length() <= 0) break; str = this.sb.toString(); break; } char c = paramCharSequence.charAt(i); if (" ~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/".indexOf(c) >= 0) continue; this.sb.append(c); } str = ""; } } }; this.mClear = ((ImageButton) findViewById(R.id.search_clear)); this.mClear.setOnClickListener(this); } public void onTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3) { if (TextUtils.isEmpty(paramCharSequence)) { this.mClear.setVisibility(View.GONE); publishKeywordChange(paramCharSequence.toString()); } else { while (true) { publishKeywordChange(paramCharSequence.toString()); this.mClear.setVisibility(View.VISIBLE); return; } } } public void onVoiceKeyword(String paramString) { if ((this.mStartListener != null) && (!TextUtils.isEmpty(paramString))) this.mStartListener.onStartSearch(paramString); } public void setHint(int paramInt) { if (this.mEdit != null) this.mEdit.setHint(paramInt); } public void setKeyword(String paramString) { if (paramString == null) { while (true) { if ((this.mEdit != null) && (paramString.compareTo(this.mEdit.getText() .toString()) != 0)) { this.mEdit.setText(paramString); this.mEdit.setSelection(-1 + paramString.length()); continue; } return; } } } public void setOnKeywordChangeListner( OnKeywordChangeListner paramOnKeywordChangeListner) { this.mListener = paramOnKeywordChangeListner; } public void setOnStartSearchListner( OnStartSearchListner paramOnStartSearchListner) { this.mStartListener = paramOnStartSearchListner; } public static abstract interface OnKeywordChangeListner { public abstract void onKeywordChanged(String paramString); } public static abstract interface OnStartSearchListner { public abstract void onStartSearch(String paramString); } }
114ch
version_without_location/src/com/besttone/widget/EditSearchBar.java
Java
asf20
5,410
package com.besttone.widget; import com.besttone.search.R; import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; import android.widget.TextView; public class PoiListItem extends LinearLayout { TextView name; TextView tel; TextView addr; public PoiListItem(Context context) { super(context); } public PoiListItem(Context context, AttributeSet attrs) { super(context, attrs); } public void setPoiData(String name, String tel, String addr, String city) { int m = 0; if(city!=null && city.trim().length()!=0){ this.addr.setText("【" + city +"】" + addr); } else { this.addr.setText(addr); } this.tel.setText(tel); this.name.setText(name); this.name.setPadding(this.name.getPaddingLeft(), this.name.getPaddingTop(), m, this.name.getPaddingBottom()); } protected void onFinishInflate() { super.onFinishInflate(); this.name = ((TextView) findViewById(R.id.name)); this.tel = ((TextView) findViewById(R.id.tel)); this.addr = ((TextView) findViewById(R.id.addr)); } }
114ch
version_without_location/src/com/besttone/widget/PoiListItem.java
Java
asf20
1,116
package com.besttone.widget; public class MSCButton { }
114ch
version_without_location/src/com/besttone/widget/MSCButton.java
Java
asf20
63
package com.besttone.widget; import com.besttone.search.R; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; public class ButtonSearchBar extends LinearLayout implements View.OnClickListener { private Button btnSearch; private ButtonSearchBarListener mListener; public ButtonSearchBar(Context paramContext) { super(paramContext); } public ButtonSearchBar(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); } public void onClick(View paramView) { // if (this.mListener != null) // this.mListener.onSearchRequested(); } protected void onFinishInflate() { super.onFinishInflate(); // this.btnSearch = ((Button) findViewById(R.id.start_search)); // this.btnSearch.setOnClickListener(this); } public void onVoiceKeyword(String paramString) { if (this.mListener != null) this.mListener.onSearchRequested(paramString); } public void setButtonSearchBarListener( ButtonSearchBarListener paramButtonSearchBarListener) { this.mListener = paramButtonSearchBarListener; } public void setGaTag(String paramString) { } public void setHint(int paramInt) { if (this.btnSearch == null); while (true) { if (paramInt > 0) { this.btnSearch.setHint(paramInt); continue; } this.btnSearch.setHint(R.string.search_hint); return; } } public void setHint(String paramString) { if (this.btnSearch != null) this.btnSearch.setHint(paramString); } public void setKeyword(String paramString) { if (this.btnSearch != null) this.btnSearch.setText(paramString); } public static abstract interface ButtonSearchBarListener { public abstract void onSearchRequested(); public abstract void onSearchRequested(String paramString); } }
114ch
version_without_location/src/com/besttone/widget/ButtonSearchBar.java
Java
asf20
1,965
package com.besttone.widget; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.ListView; import android.widget.SectionIndexer; @SuppressLint("ResourceAsColor") public class AlphabetBar extends View { private String[] l; private ListView list; private int mCurIdx; private OnSelectedListener mOnSelectedListener; private int m_nItemHeight; private SectionIndexer sectionIndexter; public AlphabetBar(Context paramContext) { super(paramContext); String[] arrayOfString = new String[27]; arrayOfString[0] = "热门"; arrayOfString[1] = "A"; arrayOfString[2] = "B"; arrayOfString[3] = "C"; arrayOfString[4] = "D"; arrayOfString[5] = "E"; arrayOfString[6] = "F"; arrayOfString[7] = "G"; arrayOfString[8] = "H"; arrayOfString[9] = "I"; arrayOfString[10] = "J"; arrayOfString[11] = "K"; arrayOfString[12] = "L"; arrayOfString[13] = "M"; arrayOfString[14] = "N"; arrayOfString[15] = "O"; arrayOfString[16] = "P"; arrayOfString[17] = "Q"; arrayOfString[18] = "R"; arrayOfString[19] = "S"; arrayOfString[20] = "T"; arrayOfString[21] = "U"; arrayOfString[22] = "V"; arrayOfString[23] = "W"; arrayOfString[24] = "X"; arrayOfString[25] = "Y"; arrayOfString[26] = "Z"; this.l = arrayOfString; this.sectionIndexter = null; this.m_nItemHeight = 25; setBackgroundColor(1157627903); } public AlphabetBar(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); String[] arrayOfString = new String[27]; arrayOfString[0] = "热门"; arrayOfString[1] = "A"; arrayOfString[2] = "B"; arrayOfString[3] = "C"; arrayOfString[4] = "D"; arrayOfString[5] = "E"; arrayOfString[6] = "F"; arrayOfString[7] = "G"; arrayOfString[8] = "H"; arrayOfString[9] = "I"; arrayOfString[10] = "J"; arrayOfString[11] = "K"; arrayOfString[12] = "L"; arrayOfString[13] = "M"; arrayOfString[14] = "N"; arrayOfString[15] = "O"; arrayOfString[16] = "P"; arrayOfString[17] = "Q"; arrayOfString[18] = "R"; arrayOfString[19] = "S"; arrayOfString[20] = "T"; arrayOfString[21] = "U"; arrayOfString[22] = "V"; arrayOfString[23] = "W"; arrayOfString[24] = "X"; arrayOfString[25] = "Y"; arrayOfString[26] = "Z"; this.l = arrayOfString; this.sectionIndexter = null; this.m_nItemHeight = 25; setBackgroundColor(1157627903); } public AlphabetBar(Context paramContext, AttributeSet paramAttributeSet, int paramInt) { super(paramContext, paramAttributeSet, paramInt); String[] arrayOfString = new String[27]; arrayOfString[0] = "热门"; arrayOfString[1] = "A"; arrayOfString[2] = "B"; arrayOfString[3] = "C"; arrayOfString[4] = "D"; arrayOfString[5] = "E"; arrayOfString[6] = "F"; arrayOfString[7] = "G"; arrayOfString[8] = "H"; arrayOfString[9] = "I"; arrayOfString[10] = "J"; arrayOfString[11] = "K"; arrayOfString[12] = "L"; arrayOfString[13] = "M"; arrayOfString[14] = "N"; arrayOfString[15] = "O"; arrayOfString[16] = "P"; arrayOfString[17] = "Q"; arrayOfString[18] = "R"; arrayOfString[19] = "S"; arrayOfString[20] = "T"; arrayOfString[21] = "U"; arrayOfString[22] = "V"; arrayOfString[23] = "W"; arrayOfString[24] = "X"; arrayOfString[25] = "Y"; arrayOfString[26] = "Z"; this.l = arrayOfString; this.sectionIndexter = null; this.m_nItemHeight = 25; setBackgroundColor(1157627903); } public int getCurIndex() { return this.mCurIdx; } @SuppressLint("ResourceAsColor") protected void onDraw(Canvas paramCanvas) { Paint localPaint = new Paint(); localPaint.setColor(Color.LTGRAY); float f = 0; if (this.m_nItemHeight > 25) { localPaint.setTextSize(20.0F); localPaint.setTextAlign(Paint.Align.CENTER); f = getMeasuredWidth() / 2; } for (int i = 0;; i++) { if (i >= this.l.length) { super.onDraw(paramCanvas); if (-5 + this.m_nItemHeight < 5) { localPaint.setTextSize(5.0F); break; } localPaint.setTextSize(-5 + this.m_nItemHeight); break; } paramCanvas.drawText(String.valueOf(this.l[i]), f, this.m_nItemHeight + i * this.m_nItemHeight, localPaint); return; } } protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { super.onLayout(paramBoolean, paramInt1, paramInt2, paramInt3, paramInt4); this.m_nItemHeight = ((-10 + (paramInt4 - paramInt2)) / this.l.length); } public boolean onTouchEvent(MotionEvent paramMotionEvent) { super.onTouchEvent(paramMotionEvent); int i = (int) paramMotionEvent.getY() / this.m_nItemHeight; int j = 0; if (i >= this.l.length) { i = -1 + this.l.length; this.mCurIdx = i; if (this.sectionIndexter == null) this.sectionIndexter = ((SectionIndexer) this.list.getAdapter()); j = this.sectionIndexter.getPositionForSection(i); } while (true) { if (i >= 0) break; i = 0; this.list.setSelection(j); if (this.mOnSelectedListener != null) this.mOnSelectedListener.onSelected(j); setBackgroundColor(-3355444); return true; } return false; } public void setListView(ListView paramListView) { this.list = paramListView; } public void setOnSelectedListener(OnSelectedListener paramOnSelectedListener) { this.mOnSelectedListener = paramOnSelectedListener; } public void setSectionIndexter(SectionIndexer paramSectionIndexer) { this.sectionIndexter = paramSectionIndexer; } public static abstract interface OnSelectedListener { public abstract void onSelected(int paramInt); public abstract void onUnselected(); } }
114ch
version_without_location/src/com/besttone/widget/AlphabetBar.java
Java
asf20
5,994
package com.besttone.adapter; import java.util.ArrayList; import com.besttone.search.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; public class CateAdapter extends BaseAdapter { private String[] data; Context mContext; private LayoutInflater mInflater; private int typeIndex = 0; public CateAdapter(Context context, String[] mChannelArray) { mContext = context; data = mChannelArray; this.mInflater = LayoutInflater.from(context); } public String getSelect() { return data[typeIndex]; } public void setTypeIndex(int index) { typeIndex = index; } public int getCount() { return data.length; } public Object getItem(int position) { return data[position]; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(R.layout.dialog_list_item, null); String area = data[position]; ((TextView) convertView.findViewById(R.id.id_area)).setText(area); View view = new View(mContext); LayoutParams param = new LayoutParams(30, 30); view.setLayoutParams(param); if (position == typeIndex) { convertView.findViewById(R.id.ic_checked).setVisibility( View.VISIBLE); } ((LinearLayout) convertView).addView(view, 0); return convertView; } private ArrayList<String> getData() { ArrayList<String> data = new ArrayList<String>(); data.add("全部频道"); data.add("美食"); data.add("休闲娱乐"); data.add("购物"); data.add("酒店"); data.add("丽人"); data.add("运动健身"); data.add("结婚"); data.add("生活服务"); return data; } }
114ch
version_without_location/src/com/besttone/adapter/CateAdapter.java
Java
asf20
1,978
package com.besttone.adapter; import android.content.Context; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.besttone.search.R; import com.besttone.search.model.City; import com.besttone.search.util.SharedUtils; import com.besttone.search.util.StringUtils; import java.util.ArrayList; public class CityListAdapter extends LetterListAdapter { public CityListAdapter() { } public CityListAdapter(Context paramContext, ArrayList<City> paramArrayList) { super(paramContext, paramArrayList); } public View setTheView(int paramInt, View paramView, ViewGroup paramViewGroup) { City localCity = (City) this.mCitylist.get(paramInt); if ("-1".equals(localCity.getCityName())) { TextView localTextView = new TextView(this.mContext); localTextView.setTextAppearance(this.mContext, R.style.text_18_black); localTextView.setPadding(15, 0, 0, 0); localTextView.setBackgroundResource(R.color.title_grey); localTextView.setGravity(16); localTextView.setText(localCity.getFirstLetter()); return localTextView; } View localView = LayoutInflater.from(this.mContext).inflate(R.layout.select_city_list_item, null); String str1 = localCity.getCityName(); ((TextView) localView.findViewById(R.id.city_info)).setText(str1); ImageView localImageView = (ImageView) localView.findViewById(R.id.selected_item); String str2 = SharedUtils.getCurrentCityName(this.mContext); if ((!StringUtils.isEmpty(str2)) && (str2.equals(str1))) { localImageView.setVisibility(View.VISIBLE); } else { while (true) { localImageView.setVisibility(View.INVISIBLE); break; } } return localView; } }
114ch
version_without_location/src/com/besttone/adapter/CityListAdapter.java
Java
asf20
1,837
package com.besttone.adapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.besttone.search.model.City; import java.util.ArrayList; public abstract class LetterListAdapter extends BaseAdapter { ArrayList<City> mCitylist; Context mContext; public LetterListAdapter() { } public LetterListAdapter(Context paramContext, ArrayList<City> paramArrayList) { this.mCitylist = paramArrayList; this.mContext = paramContext; } public int getCount() { return this.mCitylist.size(); } public Object getItem(int paramInt) { return this.mCitylist.get(paramInt); } public long getItemId(int paramInt) { return paramInt; } public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) { return setTheView(paramInt, paramView, paramViewGroup); } public abstract View setTheView(int paramInt, View paramView, ViewGroup paramViewGroup); }
114ch
version_without_location/src/com/besttone/adapter/LetterListAdapter.java
Java
asf20
1,005
package com.besttone.adapter; import java.util.ArrayList; import com.besttone.search.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; public class SortAdapter extends BaseAdapter { private String[] data; Context mContext; private LayoutInflater mInflater; private int disableIndex = -1; private int typeIndex = 0; public SortAdapter(Context context, String[] mSortArray) { mContext = context; data = mSortArray; this.mInflater = LayoutInflater.from(context); } public String[] getDataArray() { return data; } public String getSelect() { return data[typeIndex]; } public void setTypeIndex(int index) { typeIndex = index; } public int getCount() { return data.length; } public Object getItem(int position) { return data[position]; } public long getItemId(int position) { return position; } public boolean isEnabled(int position) { return true; } public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(R.layout.dialog_list_item, null); String area = data[position]; ((TextView) convertView.findViewById(R.id.id_area)).setText(area); View view = new View(mContext); LayoutParams param = new LayoutParams(30, 30); view.setLayoutParams(param); if (position == typeIndex) { convertView.findViewById(R.id.ic_checked).setVisibility( View.VISIBLE); } ((LinearLayout) convertView).addView(view, 0); return convertView; } private ArrayList<String> getData() { ArrayList<String> data = new ArrayList<String>(); data.add("按默认排序"); data.add("按距离排序"); data.add("按人气排序"); data.add("按星级排序"); data.add("按点评数排序"); data.add("优惠劵商户优先"); data.add("titlebar"); data.add("20元以下"); data.add("21-50"); data.add("51-80"); data.add("81-120"); data.add("121-200"); data.add("201以上"); return data; } }
114ch
version_without_location/src/com/besttone/adapter/SortAdapter.java
Java
asf20
2,278
package com.besttone.adapter; import java.util.ArrayList; import java.util.Map; import com.besttone.search.R; import com.besttone.search.util.Constants; import com.besttone.search.util.SharedUtils; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; public class AreaAdapter extends BaseAdapter { private LayoutInflater mInflater; private String[] mData; private int typeIndex = 0; private Context context; public AreaAdapter(Context context, String[] mAreaArray) { this.context = context; this.mInflater = LayoutInflater.from(context); mData = mAreaArray; } public String[] getDataArray() { return mData; } public String getSelect() { return mData[typeIndex]; } public void setTypeIndex(int index) { typeIndex = index; } public int getCount() { return mData.length; } public Object getItem(int position) { return mData[position]; } public long getItemId(int arg0) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(R.layout.dialog_list_item, null); View view = new View(context); LayoutParams param = new LayoutParams(30, 30); view.setLayoutParams(param); String area = mData[position]; ((TextView)convertView.findViewById(R.id.id_area)).setText(area); if(position == typeIndex) { convertView.findViewById(R.id.ic_checked).setVisibility(View.VISIBLE); } ((LinearLayout)convertView).addView(view, 0); return convertView; } // private ArrayList<ArrayList<String>> getData() // { // ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>(); // // ArrayList<String> quanbu = new ArrayList<String>(); // quanbu.add("全部地区"); // quanbu.add("全部地区 "); // data.add(quanbu); // // ArrayList<String> hongkou = new ArrayList<String>(); // hongkou.add("全部地区"); // hongkou.add("虹口区"); // hongkou.add("海宁路/七浦路"); // hongkou.add("临平路/和平公园"); // hongkou.add("曲阳地区"); // hongkou.add("四川北路"); // hongkou.add("鲁迅公园"); // data.add(hongkou); // // ArrayList<String> zhabei = new ArrayList<String>(); // zhabei.add("全部地区"); // zhabei.add("闸北区"); // zhabei.add("大宁大区"); // zhabei.add("北区汽车站"); // zhabei.add("火车站"); // zhabei.add("闸北公园"); // data.add(zhabei); // // ArrayList<String> xuhui = new ArrayList<String>(); // xuhui.add("全部地区"); // xuhui.add("徐汇区"); // xuhui.add("衡山路"); // xuhui.add("音乐学院"); // xuhui.add("肇家浜路沿线"); // xuhui.add("漕河泾/田林"); // data.add(xuhui); // // ArrayList<String> changning = new ArrayList<String>(); // changning.add("全部地区"); // changning.add("长宁区"); // changning.add("天山"); // changning.add("上海影城/新华路"); // changning.add("中山公园"); // changning.add("古北"); // data.add(changning); // // ArrayList<String> yangpu = new ArrayList<String>(); // yangpu.add("全部地区"); // yangpu.add("杨浦区"); // yangpu.add("五角场"); // yangpu.add("控江地区"); // yangpu.add("平凉路"); // yangpu.add("黄兴公园"); // data.add(yangpu); // // ArrayList<String> qingpu = new ArrayList<String>(); // qingpu.add("全部地区"); // qingpu.add("青浦区"); // qingpu.add("朱家角"); // data.add(qingpu); // // ArrayList<String> songjiang = new ArrayList<String>(); // songjiang.add("全部地区"); // songjiang.add("松江区"); // songjiang.add("松江镇"); // songjiang.add("九亭"); // songjiang.add("佘山"); // songjiang.add("松江大学城"); // data.add(songjiang); // // ArrayList<String> baoshan = new ArrayList<String>(); // baoshan.add("全部地区"); // baoshan.add("宝山区"); // baoshan.add("大华大区"); // baoshan.add("庙行镇"); // baoshan.add("吴淞"); // baoshan.add("上海大学"); // data.add(baoshan); // // ArrayList<String> pudong = new ArrayList<String>(); // pudong.add("全部地区"); // pudong.add("康桥/周浦"); // pudong.add("陆家嘴"); // pudong.add("世纪公园"); // pudong.add("八佰伴"); // data.add(pudong); // // return data; // } }
114ch
version_without_location/src/com/besttone/adapter/AreaAdapter.java
Java
asf20
4,602
package com.amap.cn.apis.util; public class ConstantsAmap { public static final int POISEARCH=1000; public static final int ERROR=1001; public static final int FIRST_LOCATION=1002; public static final int ROUTE_START_SEARCH=2000;//路径规划起点搜索 public static final int ROUTE_END_SEARCH=2001;//路径规划起点搜索 public static final int ROUTE_SEARCH_RESULT=2002;//路径规划结果 public static final int ROUTE_SEARCH_ERROR=2004;//路径规划起起始点搜索异常 public static final int REOCODER_RESULT=3000;//地理编码结果 public static final int DIALOG_LAYER=4000; public static final int POISEARCH_NEXT=5000; public static final int BUSLINE_RESULT=6000; public static final int BUSLINE_DETAIL_RESULT=6001; public static final int BUSLINE_ERROR_RESULT=6002; }
114ch
trunk/src/com/amap/cn/apis/util/ConstantsAmap.java
Java
asf20
837
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpVersion; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.params.HttpParams; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpProtocolParams; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.OutputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.text.SimpleDateFormat; import java.text.ParseException; import java.net.URL; import android.util.Xml; import android.view.InflateException; import android.net.Uri; import android.os.Parcelable; import android.os.Parcel; import android.graphics.Bitmap; import android.graphics.BitmapFactory; /** * Utility class to interact with the Flickr REST-based web services. * * This class uses a default Flickr API key that you should replace with your own if * you reuse this code to redistribute it with your application(s). * * This class is used as a singleton and cannot be instanciated. Instead, you must use * {@link #get()} to retrieve the unique instance of this class. */ class Flickr { static final String LOG_TAG = "Photostream"; // IMPORTANT: Replace this Flickr API key with your own private static final String API_KEY = "730e3a4f253b30adf30177df803d38c4"; private static final String API_REST_HOST = "api.flickr.com"; private static final String API_REST_URL = "/services/rest/"; private static final String API_FEED_URL = "/services/feeds/photos_public.gne"; private static final String API_PEOPLE_FIND_BY_USERNAME = "flickr.people.findByUsername"; private static final String API_PEOPLE_GET_INFO = "flickr.people.getInfo"; private static final String API_PEOPLE_GET_PUBLIC_PHOTOS = "flickr.people.getPublicPhotos"; private static final String API_PEOPLE_GET_LOCATION = "flickr.photos.geo.getLocation"; private static final String PARAM_API_KEY = "api_key"; private static final String PARAM_METHOD= "method"; private static final String PARAM_USERNAME = "username"; private static final String PARAM_USERID = "user_id"; private static final String PARAM_PER_PAGE = "per_page"; private static final String PARAM_PAGE = "page"; private static final String PARAM_EXTRAS = "extras"; private static final String PARAM_PHOTO_ID = "photo_id"; private static final String PARAM_FEED_ID = "id"; private static final String PARAM_FEED_FORMAT = "format"; private static final String VALUE_DEFAULT_EXTRAS = "date_taken"; private static final String VALUE_DEFAULT_FORMAT = "atom"; private static final String RESPONSE_TAG_RSP = "rsp"; private static final String RESPONSE_ATTR_STAT = "stat"; private static final String RESPONSE_STATUS_OK = "ok"; private static final String RESPONSE_TAG_USER = "user"; private static final String RESPONSE_ATTR_NSID = "nsid"; private static final String RESPONSE_TAG_PHOTOS = "photos"; private static final String RESPONSE_ATTR_PAGE = "page"; private static final String RESPONSE_ATTR_PAGES = "pages"; private static final String RESPONSE_TAG_PHOTO = "photo"; private static final String RESPONSE_ATTR_ID = "id"; private static final String RESPONSE_ATTR_SECRET = "secret"; private static final String RESPONSE_ATTR_SERVER = "server"; private static final String RESPONSE_ATTR_FARM = "farm"; private static final String RESPONSE_ATTR_TITLE = "title"; private static final String RESPONSE_ATTR_DATE_TAKEN = "datetaken"; private static final String RESPONSE_TAG_PERSON = "person"; private static final String RESPONSE_ATTR_ISPRO = "ispro"; private static final String RESPONSE_ATTR_ICONSERVER = "iconserver"; private static final String RESPONSE_ATTR_ICONFARM = "iconfarm"; private static final String RESPONSE_TAG_USERNAME = "username"; private static final String RESPONSE_TAG_REALNAME = "realname"; private static final String RESPONSE_TAG_LOCATION = "location"; private static final String RESPONSE_ATTR_LATITUDE = "latitude"; private static final String RESPONSE_ATTR_LONGITUDE = "longitude"; private static final String RESPONSE_TAG_PHOTOSURL = "photosurl"; private static final String RESPONSE_TAG_PROFILEURL = "profileurl"; private static final String RESPONSE_TAG_MOBILEURL = "mobileurl"; private static final String RESPONSE_TAG_FEED = "feed"; private static final String RESPONSE_TAG_UPDATED = "updated"; private static final String PHOTO_IMAGE_URL = "http://farm%s.static.flickr.com/%s/%s_%s%s.jpg"; private static final String BUDDY_ICON_URL = "http://farm%s.static.flickr.com/%s/buddyicons/%s.jpg"; private static final String DEFAULT_BUDDY_ICON_URL = "http://www.flickr.com/images/buddyicon.jpg"; private static final int IO_BUFFER_SIZE = 4 * 1024; private static final boolean FLAG_DECODE_PHOTO_STREAM_WITH_SKIA = false; private static final Flickr sInstance = new Flickr(); private HttpClient mClient; /** * Defines the size of the image to download from Flickr. * * @see com.google.android.photostream.Flickr.Photo */ enum PhotoSize { /** * Small square image (75x75 px). */ SMALL_SQUARE("_s", 75), /** * Thumbnail image (the longest side measures 100 px). */ THUMBNAIL("_t", 100), /** * Small image (the longest side measures 240 px). */ SMALL("_m", 240), /** * Medium image (the longest side measures 500 px). */ MEDIUM("", 500), /** * Large image (the longest side measures 1024 px). */ LARGE("_b", 1024); private final String mSize; private final int mLongSide; private PhotoSize(String size, int longSide) { mSize = size; mLongSide = longSide; } /** * Returns the size in pixels of the longest side of the image. * * @return THe dimension in pixels of the longest side. */ int longSide() { return mLongSide; } /** * Returns the name of the size, as defined by Flickr. For instance, * the LARGE size is defined by the String "_b". * * @return */ String size() { return mSize; } @Override public String toString() { return name() + ", longSide=" + mLongSide; } } /** * Represents the geographical location of a photo. */ static class Location { private float mLatitude; private float mLongitude; private Location(float latitude, float longitude) { mLatitude = latitude; mLongitude = longitude; } float getLatitude() { return mLatitude; } float getLongitude() { return mLongitude; } } /** * A Flickr user, in the strictest sense, is only defined by its NSID. The NSID * is usually obtained by {@link Flickr#findByUserName(String) * looking up a user by its user name}. * * To obtain more information about a given user, refer to the UserInfo class. * * @see Flickr#findByUserName(String) * @see Flickr#getUserInfo(com.google.android.photostream.Flickr.User) * @see com.google.android.photostream.Flickr.UserInfo */ static class User implements Parcelable { private final String mId; private User(String id) { mId = id; } private User(Parcel in) { mId = in.readString(); } /** * Returns the Flickr NSDID of the user. The NSID is used to identify the * user with any operation performed on Flickr. * * @return The user's NSID. */ String getId() { return mId; } /** * Creates a new instance of this class from the specified Flickr NSID. * * @param id The NSID of the Flickr user. * * @return An instance of User whose id might not be valid. */ static User fromId(String id) { return new User(id); } @Override public String toString() { return "User[" + mId + "]"; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeString(mId); } public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { public User createFromParcel(Parcel in) { return new User(in); } public User[] newArray(int size) { return new User[size]; } }; } /** * A set of information for a given Flickr user. The information exposed include: * - The user's NSDID * - The user's name * - The user's real name * - The user's location * - The URL to the user's photos * - The URL to the user's profile * - The URL to the user's mobile web site * - Whether the user has a pro account */ static class UserInfo implements Parcelable { private String mId; private String mUserName; private String mRealName; private String mLocation; private String mPhotosUrl; private String mProfileUrl; private String mMobileUrl; private boolean mIsPro; private String mIconServer; private String mIconFarm; private UserInfo(String nsid) { mId = nsid; } private UserInfo(Parcel in) { mId = in.readString(); mUserName = in.readString(); mRealName = in.readString(); mLocation = in.readString(); mPhotosUrl = in.readString(); mProfileUrl = in.readString(); mMobileUrl = in.readString(); mIsPro = in.readInt() == 1; mIconServer = in.readString(); mIconFarm = in.readString(); } /** * Returns the Flickr NSID that identifies this user. * * @return The Flickr NSID. */ String getId() { return mId; } /** * Returns the user's name. This is the name that the user authenticates with, * and the name that Flickr uses in the URLs * (for instance, http://flickr.com/photos/romainguy, where romainguy is the user * name.) * * @return The user's Flickr name. */ String getUserName() { return mUserName; } /** * Returns the user's real name. The real name is chosen by the user when * creating his account and might not reflect his civil name. * * @return The real name of the user. */ String getRealName() { return mRealName; } /** * Returns the user's location, if publicly exposed. * * @return The location of the user. */ String getLocation() { return mLocation; } /** * Returns the URL to the photos of the user. For instance, * http://flickr.com/photos/romainguy. * * @return The URL to the photos of the user. */ String getPhotosUrl() { return mPhotosUrl; } /** * Returns the URL to the profile of the user. For instance, * http://flickr.com/people/romainguy/. * * @return The URL to the photos of the user. */ String getProfileUrl() { return mProfileUrl; } /** * Returns the mobile URL of the user. * * @return The mobile URL of the user. */ String getMobileUrl() { return mMobileUrl; } /** * Indicates whether the user owns a pro account. * * @return true, if the user has a pro account, false otherwise. */ boolean isPro() { return mIsPro; } /** * Returns the URL to the user's buddy icon. The buddy icon is a 48x48 * image chosen by the user. If no icon can be found, a default image * URL is returned. * * @return The URL to the user's buddy icon. */ String getBuddyIconUrl() { if (mIconFarm == null || mIconServer == null || mId == null) { return DEFAULT_BUDDY_ICON_URL; } return String.format(BUDDY_ICON_URL, mIconFarm, mIconServer, mId); } /** * Loads the user's buddy icon as a Bitmap. The user's buddy icon is loaded * from the URL returned by {@link #getBuddyIconUrl()}. The buddy icon is * not cached locally. * * @return A 48x48 bitmap if the icon was loaded successfully or null otherwise. */ Bitmap loadBuddyIcon() { Bitmap bitmap = null; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new URL(getBuddyIconUrl()).openStream(), IO_BUFFER_SIZE); if (FLAG_DECODE_PHOTO_STREAM_WITH_SKIA) { bitmap = BitmapFactory.decodeStream(in); } else { final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); copy(in, out); out.flush(); final byte[] data = dataStream.toByteArray(); bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); } } catch (IOException e) { android.util.Log.e(Flickr.LOG_TAG, "Could not load buddy icon: " + this, e); } finally { closeStream(in); closeStream(out); } return bitmap; } @Override public String toString() { return mRealName + " (" + mUserName + ", " + mId + ")"; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeString(mId); dest.writeString(mUserName); dest.writeString(mRealName); dest.writeString(mLocation); dest.writeString(mPhotosUrl); dest.writeString(mProfileUrl); dest.writeString(mMobileUrl); dest.writeInt(mIsPro ? 1 : 0); dest.writeString(mIconServer); dest.writeString(mIconFarm); } public static final Parcelable.Creator<UserInfo> CREATOR = new Parcelable.Creator<UserInfo>() { public UserInfo createFromParcel(Parcel in) { return new UserInfo(in); } public UserInfo[] newArray(int size) { return new UserInfo[size]; } }; } /** * A photo is represented by a title, the date at which it was taken and a URL. * The URL depends on the desired {@link com.google.android.photostream.Flickr.PhotoSize}. */ static class Photo implements Parcelable { private String mId; private String mSecret; private String mServer; private String mFarm; private String mTitle; private String mDate; private Photo() { } private Photo(Parcel in) { mId = in.readString(); mSecret = in.readString(); mServer = in.readString(); mFarm = in.readString(); mTitle = in.readString(); mDate = in.readString(); } /** * Returns the title of the photo, if specified. * * @return The title of the photo. The returned value can be empty or null. */ String getTitle() { return mTitle; } /** * Returns the date at which the photo was taken, formatted in the current locale * with the following pattern: MMMM d, yyyy. * * @return The title of the photo. The returned value can be empty or null. */ String getDate() { return mDate; } /** * Returns the URL to the photo for the specified size. * * @param photoSize The required size of the photo. * * @return A URL to the photo for the specified size. * * @see com.google.android.photostream.Flickr.PhotoSize */ String getUrl(PhotoSize photoSize) { return String.format(PHOTO_IMAGE_URL, mFarm, mServer, mId, mSecret, photoSize.size()); } /** * Loads a Bitmap representing the photo for the specified size. The Bitmap is loaded * from the URL returned by * {@link #getUrl(com.google.android.photostream.Flickr.PhotoSize)}. * * @param size The size of the photo to load. * * @return A Bitmap whose longest size is the same as the longest side of the * specified {@link com.google.android.photostream.Flickr.PhotoSize}, or null * if the photo could not be loaded. */ Bitmap loadPhotoBitmap(PhotoSize size) { Bitmap bitmap = null; InputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new URL(getUrl(size)).openStream(), IO_BUFFER_SIZE); if (FLAG_DECODE_PHOTO_STREAM_WITH_SKIA) { bitmap = BitmapFactory.decodeStream(in); } else { final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); copy(in, out); out.flush(); final byte[] data = dataStream.toByteArray(); bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); } } catch (IOException e) { android.util.Log.e(Flickr.LOG_TAG, "Could not load photo: " + this, e); } finally { closeStream(in); closeStream(out); } return bitmap; } @Override public String toString() { return mTitle + ", " + mDate + " @" + mId; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeString(mId); dest.writeString(mSecret); dest.writeString(mServer); dest.writeString(mFarm); dest.writeString(mTitle); dest.writeString(mDate); } public static final Parcelable.Creator<Photo> CREATOR = new Parcelable.Creator<Photo>() { public Photo createFromParcel(Parcel in) { return new Photo(in); } public Photo[] newArray(int size) { return new Photo[size]; } }; } /** * A list of {@link com.google.android.photostream.Flickr.Photo photos}. A list * represents a series of photo on a page from the user's photostream, a list is * therefore associated with a page index and a page count. The page index and the * page count both depend on the number of photos per page. */ static class PhotoList { private ArrayList<Photo> mPhotos; private int mPage; private int mPageCount; private void add(Photo photo) { mPhotos.add(photo); } /** * Returns the photo at the specified index in the current set. An * {@link ArrayIndexOutOfBoundsException} can be thrown if the index is * less than 0 or greater then or equals to {@link #getCount()}. * * @param index The index of the photo to retrieve from the list. * * @return A valid {@link com.google.android.photostream.Flickr.Photo}. */ public Photo get(int index) { return mPhotos.get(index); } /** * Returns the number of photos in the list. * * @return A positive integer, or 0 if the list is empty. */ public int getCount() { return mPhotos.size(); } /** * Returns the page index of the photos from this list. * * @return The index of the Flickr page that contains the photos of this list. */ public int getPage() { return mPage; } /** * Returns the total number of photo pages. * * @return A positive integer, or 0 if the photostream is empty. */ public int getPageCount() { return mPageCount; } } /** * Returns the unique instance of this class. * * @return The unique instance of this class. */ static Flickr get() { return sInstance; } private Flickr() { final HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); final ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry); mClient = new DefaultHttpClient(manager, params); } /** * Finds a user by its user name. This method will return an instance of * {@link com.google.android.photostream.Flickr.User} containing the user's * NSID, or null if the user could not be found. * * The returned User contains only the user's NSID. To retrieve more information * about the user, please refer to * {@link #getUserInfo(com.google.android.photostream.Flickr.User)} * * @param userName The name of the user to find. * * @return A User instance with a valid NSID, or null if the user cannot be found. * * @see #getUserInfo(com.google.android.photostream.Flickr.User) * @see com.google.android.photostream.Flickr.User * @see com.google.android.photostream.Flickr.UserInfo */ User findByUserName(String userName) { final Uri.Builder uri = buildGetMethod(API_PEOPLE_FIND_BY_USERNAME); uri.appendQueryParameter(PARAM_USERNAME, userName); final HttpGet get = new HttpGet(uri.build().toString()); final String[] userId = new String[1]; try { executeRequest(get, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseResponse(in, new ResponseParser() { public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException { parseUser(parser, userId); } }); } }); if (userId[0] != null) { return new User(userId[0]); } } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not find the user with name: " + userName); } return null; } /** * Retrieves a public set of information about the specified user. The user can * either be {@link com.google.android.photostream.Flickr.User#fromId(String) created manually} * or {@link #findByUserName(String) obtained from a user name}. * * @param user The user, whose NSID is valid, to retrive public information for. * * @return An instance of {@link com.google.android.photostream.Flickr.UserInfo} or null * if the user could not be found. * * @see com.google.android.photostream.Flickr.UserInfo * @see com.google.android.photostream.Flickr.User * @see #findByUserName(String) */ UserInfo getUserInfo(User user) { final String nsid = user.getId(); final Uri.Builder uri = buildGetMethod(API_PEOPLE_GET_INFO); uri.appendQueryParameter(PARAM_USERID, nsid); final HttpGet get = new HttpGet(uri.build().toString()); try { final UserInfo info = new UserInfo(nsid); executeRequest(get, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseResponse(in, new ResponseParser() { public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException { parseUserInfo(parser, info); } }); } }); return info; } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not find the user with id: " + nsid); } return null; } /** * Retrives a list of photos for the specified user. The list contains at most the * number of photos specified by <code>perPage</code>. The photos are retrieved * starting a the specified page index. For instance, if a user has 10 photos in * his photostream, calling getPublicPhotos(user, 5, 2) will return the last 5 photos * of the photo stream. * * The page index starts at 1, not 0. * * @param user The user to retrieve photos from. * @param perPage The maximum number of photos to retrieve. * @param page The index (starting at 1) of the page in the photostream. * * @return A list of at most perPage photos. * * @see com.google.android.photostream.Flickr.Photo * @see com.google.android.photostream.Flickr.PhotoList * @see #downloadPhoto(com.google.android.photostream.Flickr.Photo, * com.google.android.photostream.Flickr.PhotoSize, java.io.OutputStream) */ PhotoList getPublicPhotos(User user, int perPage, int page) { final Uri.Builder uri = buildGetMethod(API_PEOPLE_GET_PUBLIC_PHOTOS); uri.appendQueryParameter(PARAM_USERID, user.getId()); uri.appendQueryParameter(PARAM_PER_PAGE, String.valueOf(perPage)); uri.appendQueryParameter(PARAM_PAGE, String.valueOf(page)); uri.appendQueryParameter(PARAM_EXTRAS, VALUE_DEFAULT_EXTRAS); final HttpGet get = new HttpGet(uri.build().toString()); final PhotoList photos = new PhotoList(); try { executeRequest(get, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseResponse(in, new ResponseParser() { public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException { parsePhotos(parser, photos); } }); } }); } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not find photos for user: " + user); } return photos; } /** * Retrieves the geographical location of the specified photo. If the photo * has no geodata associated with it, this method returns null. * * @param photo The photo to get the location of. * * @return The geo location of the photo, or null if the photo has no geodata * or the photo cannot be found. * * @see com.google.android.photostream.Flickr.Location */ Location getLocation(Flickr.Photo photo) { final Uri.Builder uri = buildGetMethod(API_PEOPLE_GET_LOCATION); uri.appendQueryParameter(PARAM_PHOTO_ID, photo.mId); final HttpGet get = new HttpGet(uri.build().toString()); final Location location = new Location(0.0f, 0.0f); try { executeRequest(get, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseResponse(in, new ResponseParser() { public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException { parsePhotoLocation(parser, location); } }); } }); return location; } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not find location for photo: " + photo); } return null; } /** * Checks the specified user's feed to see if any updated occured after the * specified date. * * @param user The user whose feed must be checked. * @param reference The date after which to check for updates. * * @return True if any update occured after the reference date, false otherwise. */ boolean hasUpdates(User user, final Calendar reference) { final Uri.Builder uri = new Uri.Builder(); uri.path(API_FEED_URL); uri.appendQueryParameter(PARAM_FEED_ID, user.getId()); uri.appendQueryParameter(PARAM_FEED_FORMAT, VALUE_DEFAULT_FORMAT); final HttpGet get = new HttpGet(uri.build().toString()); final boolean[] updated = new boolean[1]; try { executeRequest(get, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseFeedResponse(in, new ResponseParser() { public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException { updated[0] = parseUpdated(parser, reference); } }); } }); } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not find feed for user: " + user); } return updated[0]; } /** * Downloads the specified photo at the specified size in the specified destination. * * @param photo The photo to download. * @param size The size of the photo to download. * @param destination The output stream in which to write the downloaded photo. * * @throws IOException If any network exception occurs during the download. */ void downloadPhoto(Photo photo, PhotoSize size, OutputStream destination) throws IOException { final BufferedOutputStream out = new BufferedOutputStream(destination, IO_BUFFER_SIZE); final String url = photo.getUrl(size); final HttpGet get = new HttpGet(url); HttpEntity entity = null; try { final HttpResponse response = mClient.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = response.getEntity(); entity.writeTo(out); out.flush(); } } finally { if (entity != null) { entity.consumeContent(); } } } private boolean parseUpdated(XmlPullParser parser, Calendar reference) throws IOException, XmlPullParserException { int type; String name; final int depth = parser.getDepth(); while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } name = parser.getName(); if (RESPONSE_TAG_UPDATED.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { final String text = parser.getText().replace('T', ' ').replace('Z', ' '); final Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(format.parse(text).getTime()); return calendar.after(reference); } catch (ParseException e) { // Ignore } } } } return false; } private void parsePhotos(XmlPullParser parser, PhotoList photos) throws XmlPullParserException, IOException { int type; String name; SimpleDateFormat parseFormat = null; SimpleDateFormat outputFormat = null; final int depth = parser.getDepth(); while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } name = parser.getName(); if (RESPONSE_TAG_PHOTOS.equals(name)) { photos.mPage = Integer.parseInt(parser.getAttributeValue(null, RESPONSE_ATTR_PAGE)); photos.mPageCount = Integer.parseInt(parser.getAttributeValue(null, RESPONSE_ATTR_PAGES)); photos.mPhotos = new ArrayList<Photo>(); } else if (RESPONSE_TAG_PHOTO.equals(name)) { final Photo photo = new Photo(); photo.mId = parser.getAttributeValue(null, RESPONSE_ATTR_ID); photo.mSecret = parser.getAttributeValue(null, RESPONSE_ATTR_SECRET); photo.mServer = parser.getAttributeValue(null, RESPONSE_ATTR_SERVER); photo.mFarm = parser.getAttributeValue(null, RESPONSE_ATTR_FARM); photo.mTitle = parser.getAttributeValue(null, RESPONSE_ATTR_TITLE); photo.mDate = parser.getAttributeValue(null, RESPONSE_ATTR_DATE_TAKEN); if (parseFormat == null) { parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); outputFormat = new SimpleDateFormat("MMMM d, yyyy"); } try { photo.mDate = outputFormat.format(parseFormat.parse(photo.mDate)); } catch (ParseException e) { android.util.Log.w(LOG_TAG, "Could not parse photo date", e); } photos.add(photo); } } } private void parsePhotoLocation(XmlPullParser parser, Location location) throws XmlPullParserException, IOException { int type; String name; final int depth = parser.getDepth(); while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } name = parser.getName(); if (RESPONSE_TAG_LOCATION.equals(name)) { try { location.mLatitude = Float.parseFloat(parser.getAttributeValue(null, RESPONSE_ATTR_LATITUDE)); location.mLongitude = Float.parseFloat(parser.getAttributeValue(null, RESPONSE_ATTR_LONGITUDE)); } catch (NumberFormatException e) { throw new XmlPullParserException("Could not parse lat/lon", parser, e); } } } } private void parseUser(XmlPullParser parser, String[] userId) throws XmlPullParserException, IOException { int type; String name; final int depth = parser.getDepth(); while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } name = parser.getName(); if (RESPONSE_TAG_USER.equals(name)) { userId[0] = parser.getAttributeValue(null, RESPONSE_ATTR_NSID); } } } private void parseUserInfo(XmlPullParser parser, UserInfo info) throws XmlPullParserException, IOException { int type; String name; final int depth = parser.getDepth(); while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } name = parser.getName(); if (RESPONSE_TAG_PERSON.equals(name)) { info.mIsPro = "1".equals(parser.getAttributeValue(null, RESPONSE_ATTR_ISPRO)); info.mIconServer = parser.getAttributeValue(null, RESPONSE_ATTR_ICONSERVER); info.mIconFarm = parser.getAttributeValue(null, RESPONSE_ATTR_ICONFARM); } else if (RESPONSE_TAG_USERNAME.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { info.mUserName = parser.getText(); } } else if (RESPONSE_TAG_REALNAME.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { info.mRealName = parser.getText(); } } else if (RESPONSE_TAG_LOCATION.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { info.mLocation = parser.getText(); } } else if (RESPONSE_TAG_PHOTOSURL.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { info.mPhotosUrl = parser.getText(); } } else if (RESPONSE_TAG_PROFILEURL.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { info.mProfileUrl = parser.getText(); } } else if (RESPONSE_TAG_MOBILEURL.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { info.mMobileUrl = parser.getText(); } } } } /** * Parses a valid Flickr XML response from the specified input stream. When the Flickr * response contains the OK tag, the response is sent to the specified response parser. * * @param in The input stream containing the response sent by Flickr. * @param responseParser The parser to use when the response is valid. * * @throws IOException */ private void parseResponse(InputStream in, ResponseParser responseParser) throws IOException { final XmlPullParser parser = Xml.newPullParser(); try { parser.setInput(new InputStreamReader(in)); int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty } if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } String name = parser.getName(); if (RESPONSE_TAG_RSP.equals(name)) { final String value = parser.getAttributeValue(null, RESPONSE_ATTR_STAT); if (!RESPONSE_STATUS_OK.equals(value)) { throw new IOException("Wrong status: " + value); } } responseParser.parseResponse(parser); } catch (XmlPullParserException e) { final IOException ioe = new IOException("Could not parser the response"); ioe.initCause(e); throw ioe; } } /** * Parses a valid Flickr Atom feed response from the specified input stream. * * @param in The input stream containing the response sent by Flickr. * @param responseParser The parser to use when the response is valid. * * @throws IOException */ private void parseFeedResponse(InputStream in, ResponseParser responseParser) throws IOException { final XmlPullParser parser = Xml.newPullParser(); try { parser.setInput(new InputStreamReader(in)); int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty } if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } String name = parser.getName(); if (RESPONSE_TAG_FEED.equals(name)) { responseParser.parseResponse(parser); } else { throw new IOException("Wrong start tag: " + name); } } catch (XmlPullParserException e) { final IOException ioe = new IOException("Could not parser the response"); ioe.initCause(e); throw ioe; } } /** * Executes an HTTP request on Flickr's web service. If the response is ok, the content * is sent to the specified response handler. * * @param get The GET request to executed. * @param handler The handler which will parse the response. * * @throws IOException */ private void executeRequest(HttpGet get, ResponseHandler handler) throws IOException { HttpEntity entity = null; HttpHost host = new HttpHost(API_REST_HOST, 80, "http"); try { final HttpResponse response = mClient.execute(host, get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = response.getEntity(); final InputStream in = entity.getContent(); handler.handleResponse(in); } } finally { if (entity != null) { entity.consumeContent(); } } } /** * Builds an HTTP GET request for the specified Flickr API method. The returned request * contains the web service path, the query parameter for the API KEY and the query * parameter for the specified method. * * @param method The Flickr API method to invoke. * * @return A Uri.Builder containing the GET path, the API key and the method already * encoded. */ private static Uri.Builder buildGetMethod(String method) { final Uri.Builder builder = new Uri.Builder(); builder.path(API_REST_URL).appendQueryParameter(PARAM_API_KEY, API_KEY); builder.appendQueryParameter(PARAM_METHOD, method); return builder; } /** * Copy the content of the input stream into the output stream, using a temporary * byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}. * * @param in The input stream to copy from. * @param out The output stream to copy to. * * @throws IOException If any error occurs during the copy. */ private static void copy(InputStream in, OutputStream out) throws IOException { byte[] b = new byte[IO_BUFFER_SIZE]; int read; while ((read = in.read(b)) != -1) { out.write(b, 0, read); } } /** * Closes the specified stream. * * @param stream The stream to close. */ private static void closeStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { android.util.Log.e(Flickr.LOG_TAG, "Could not close stream", e); } } } /** * Response handler used with * {@link Flickr#executeRequest(org.apache.http.client.methods.HttpGet, * com.google.android.photostream.Flickr.ResponseHandler)}. The handler is invoked when * a response is sent by the server. The response is made available as an input stream. */ private static interface ResponseHandler { /** * Processes the responses sent by the HTTP server following a GET request. * * @param in The stream containing the server's response. * * @throws IOException */ public void handleResponse(InputStream in) throws IOException; } /** * Response parser used with {@link Flickr#parseResponse(java.io.InputStream, * com.google.android.photostream.Flickr.ResponseParser)}. When Flickr returns a valid * response, this parser is invoked to process the XML response. */ private static interface ResponseParser { /** * Processes the XML response sent by the Flickr web service after a successful * request. * * @param parser The parser containing the XML responses. * * @throws XmlPullParserException * @throws IOException */ public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException; } }
114ch
trunk/src/com/google/android/photostream/Flickr.java
Java
asf20
47,139
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.os.*; import android.os.Process; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicInteger; /** * <p>UserTask enables proper and easy use of the UI thread. This class allows to * perform background operations and publish results on the UI thread without * having to manipulate threads and/or handlers.</p> * * <p>A user task is defined by a computation that runs on a background thread and * whose result is published on the UI thread. A user task is defined by 3 generic * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>, * and 4 steps, called <code>begin</code>, <code>doInBackground</code>, * <code>processProgress<code> and <code>end</code>.</p> * * <h2>Usage</h2> * <p>UserTask must be subclassed to be used. The subclass will override at least * one method ({@link #doInBackground(Object[])}), and most often will override a * second one ({@link #onPostExecute(Object)}.)</p> * * <p>Here is an example of subclassing:</p> * <pre> * private class DownloadFilesTask extends UserTask&lt;URL, Integer, Long&gt; { * public File doInBackground(URL... urls) { * int count = urls.length; * long totalSize = 0; * for (int i = 0; i < count; i++) { * totalSize += Downloader.downloadFile(urls[i]); * publishProgress((int) ((i / (float) count) * 100)); * } * } * * public void onProgressUpdate(Integer... progress) { * setProgressPercent(progress[0]); * } * * public void onPostExecute(Long result) { * showDialog("Downloaded " + result + " bytes"); * } * } * </pre> * * <p>Once created, a task is executed very simply:</p> * <pre> * new DownloadFilesTask().execute(new URL[] { ... }); * </pre> * * <h2>User task's generic types</h2> * <p>The three types used by a user task are the following:</p> * <ol> * <li><code>Params</code>, the type of the parameters sent to the task upon * execution.</li> * <li><code>Progress</code>, the type of the progress units published during * the background computation.</li> * <li><code>Result</code>, the type of the result of the background * computation.</li> * </ol> * <p>Not all types are always used by a user task. To mark a type as unused, * simply use the type {@link Void}:</p> * <pre> * private class MyTask extends UserTask<Void, Void, Void) { ... } * </pre> * * <h2>The 4 steps</h2> * <p>When a user task is executed, the task goes through 4 steps:</p> * <ol> * <li>{@link #onPreExecute()}, invoked on the UI thread immediately after the task * is executed. This step is normally used to setup the task, for instance by * showing a progress bar in the user interface.</li> * <li>{@link #doInBackground(Object[])}, invoked on the background thread * immediately after {@link # onPreExecute ()} finishes executing. This step is used * to perform background computation that can take a long time. The parameters * of the user task are passed to this step. The result of the computation must * be returned by this step and will be passed back to the last step. This step * can also use {@link #publishProgress(Object[])} to publish one or more units * of progress. These values are published on the UI thread, in the * {@link #onProgressUpdate(Object[])} step.</li> * <li>{@link # onProgressUpdate (Object[])}, invoked on the UI thread after a * call to {@link #publishProgress(Object[])}. The timing of the execution is * undefined. This method is used to display any form of progress in the user * interface while the background computation is still executing. For instance, * it can be used to animate a progress bar or show logs in a text field.</li> * <li>{@link # onPostExecute (Object)}, invoked on the UI thread after the background * computation finishes. The result of the background computation is passed to * this step as a parameter.</li> * </ol> * * <h2>Threading rules</h2> * <p>There are a few threading rules that must be followed for this class to * work properly:</p> * <ul> * <li>The task instance must be created on the UI thread.</li> * <li>{@link #execute(Object[])} must be invoked on the UI thread.</li> * <li>Do not call {@link # onPreExecute ()}, {@link # onPostExecute (Object)}, * {@link #doInBackground(Object[])}, {@link # onProgressUpdate (Object[])} * manually.</li> * <li>The task can be executed only once (an exception will be thrown if * a second execution is attempted.)</li> * </ul> */ public abstract class UserTask<Params, Progress, Result> { private static final String LOG_TAG = "UserTask"; private static final int CORE_POOL_SIZE = 1; private static final int MAXIMUM_POOL_SIZE = 10; private static final int KEEP_ALIVE = 10; private static final BlockingQueue<Runnable> sWorkQueue = new LinkedBlockingQueue<Runnable>(MAXIMUM_POOL_SIZE); private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "UserTask #" + mCount.getAndIncrement()); } }; private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory); private static final int MESSAGE_POST_RESULT = 0x1; private static final int MESSAGE_POST_PROGRESS = 0x2; private static final int MESSAGE_POST_CANCEL = 0x3; private static final InternalHandler sHandler = new InternalHandler(); private final WorkerRunnable<Params, Result> mWorker; private final FutureTask<Result> mFuture; private volatile Status mStatus = Status.PENDING; /** * Indicates the current status of the task. Each status will be set only once * during the lifetime of a task. */ public enum Status { /** * Indicates that the task has not been executed yet. */ PENDING, /** * Indicates that the task is running. */ RUNNING, /** * Indicates that {@link UserTask#onPostExecute(Object)} has finished. */ FINISHED, } /** * Creates a new user task. This constructor must be invoked on the UI thread. */ public UserTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); return doInBackground(mParams); } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { Message message; Result result = null; try { result = get(); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { message = sHandler.obtainMessage(MESSAGE_POST_CANCEL, new UserTaskResult<Result>(UserTask.this, (Result[]) null)); message.sendToTarget(); return; } catch (Throwable t) { throw new RuntimeException("An error occured while executing " + "doInBackground()", t); } message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new UserTaskResult<Result>(UserTask.this, result)); message.sendToTarget(); } }; } /** * Returns the current status of this task. * * @return The current status. */ public final Status getStatus() { return mStatus; } /** * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute(Object[])} * by the caller of this task. * * This method can call {@link #publishProgress(Object[])} to publish updates * on the UI thread. * * @param params The parameters of the task. * * @return A result, defined by the subclass of this task. * * @see #onPreExecute() * @see #onPostExecute(Object) * @see #publishProgress(Object[]) */ public abstract Result doInBackground(Params... params); /** * Runs on the UI thread before {@link #doInBackground(Object[])}. * * @see #onPostExecute(Object) * @see #doInBackground(Object[]) */ public void onPreExecute() { } /** * Runs on the UI thread after {@link #doInBackground(Object[])}. The * specified result is the value returned by {@link #doInBackground(Object[])} * or null if the task was cancelled or an exception occured. * * @param result The result of the operation computed by {@link #doInBackground(Object[])}. * * @see #onPreExecute() * @see #doInBackground(Object[]) */ @SuppressWarnings({"UnusedDeclaration"}) public void onPostExecute(Result result) { } /** * Runs on the UI thread after {@link #publishProgress(Object[])} is invoked. * The specified values are the values passed to {@link #publishProgress(Object[])}. * * @param values The values indicating progress. * * @see #publishProgress(Object[]) * @see #doInBackground(Object[]) */ @SuppressWarnings({"UnusedDeclaration"}) public void onProgressUpdate(Progress... values) { } /** * Runs on the UI thread after {@link #cancel(boolean)} is invoked. * * @see #cancel(boolean) * @see #isCancelled() */ public void onCancelled() { } /** * Returns <tt>true</tt> if this task was cancelled before it completed * normally. * * @return <tt>true</tt> if task was cancelled before it completed * * @see #cancel(boolean) */ public final boolean isCancelled() { return mFuture.isCancelled(); } /** * Attempts to cancel execution of this task. This attempt will * fail if the task has already completed, already been cancelled, * or could not be cancelled for some other reason. If successful, * and this task has not started when <tt>cancel</tt> is called, * this task should never run. If the task has already started, * then the <tt>mayInterruptIfRunning</tt> parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task. * * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete. * * @return <tt>false</tt> if the task could not be cancelled, * typically because it has already completed normally; * <tt>true</tt> otherwise * * @see #isCancelled() * @see #onCancelled() */ public final boolean cancel(boolean mayInterruptIfRunning) { return mFuture.cancel(mayInterruptIfRunning); } /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. */ public final Result get() throws InterruptedException, ExecutionException { return mFuture.get(); } /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result. * * @param timeout Time to wait before cancelling the operation. * @param unit The time unit for the timeout. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. * @throws TimeoutException If the wait timed out. */ public final Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mFuture.get(timeout, unit); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * This method must be invoked on the UI thread. * * @param params The parameters of the task. * * @return This instance of UserTask. * * @throws IllegalStateException If {@link #getStatus()} returns either * {@link UserTask.Status#RUNNING} or {@link UserTask.Status#FINISHED}. */ public final UserTask<Params, Progress, Result> execute(Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; sExecutor.execute(mFuture); return this; } /** * This method can be invoked from {@link #doInBackground(Object[])} to * publish updates on the UI thread while the background computation is * still running. Each call to this method will trigger the execution of * {@link #onProgressUpdate(Object[])} on the UI thread. * * @param values The progress values to update the UI with. * * @see # onProgressUpdate (Object[]) * @see #doInBackground(Object[]) */ protected final void publishProgress(Progress... values) { sHandler.obtainMessage(MESSAGE_POST_PROGRESS, new UserTaskResult<Progress>(this, values)).sendToTarget(); } private void finish(Result result) { onPostExecute(result); mStatus = Status.FINISHED; } private static class InternalHandler extends Handler { @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { UserTaskResult result = (UserTaskResult) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break; case MESSAGE_POST_CANCEL: result.mTask.onCancelled(); break; } } } private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; } @SuppressWarnings({"RawUseOfParameterizedType"}) private static class UserTaskResult<Data> { final UserTask mTask; final Data[] mData; UserTaskResult(UserTask task, Data... data) { mTask = task; mData = data; } } }
114ch
trunk/src/com/google/android/photostream/UserTask.java
Java
asf20
17,155
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; final class Preferences { static final String NAME = "Photostream"; static final String KEY_ALARM_SCHEDULED = "photostream.scheduled"; static final String KEY_ENABLE_NOTIFICATIONS = "photostream.enable-notifications"; static final String KEY_VIBRATE = "photostream.vibrate"; static final String KEY_RINGTONE = "photostream.ringtone"; Preferences() { } }
114ch
trunk/src/com/google/android/photostream/Preferences.java
Java
asf20
1,027
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import java.util.Random; /** * This class contains various utilities to manipulate Bitmaps. The methods of this class, * although static, are not thread safe and cannot be invoked by several threads at the * same time. Synchronization is required by the caller. */ final class ImageUtilities { private static final float PHOTO_BORDER_WIDTH = 3.0f; private static final int PHOTO_BORDER_COLOR = 0xffffffff; private static final float ROTATION_ANGLE_MIN = 2.5f; private static final float ROTATION_ANGLE_EXTRA = 5.5f; private static final Random sRandom = new Random(); private static final Paint sPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); private static final Paint sStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG); static { sStrokePaint.setStrokeWidth(PHOTO_BORDER_WIDTH); sStrokePaint.setStyle(Paint.Style.STROKE); sStrokePaint.setColor(PHOTO_BORDER_COLOR); } /** * Rotate specified Bitmap by a random angle. The angle is either negative or positive, * and ranges, in degrees, from 2.5 to 8. After rotation a frame is overlaid on top * of the rotated image. * * This method is not thread safe. * * @param bitmap The Bitmap to rotate and apply a frame onto. * * @return A new Bitmap whose dimension are different from the original bitmap. */ static Bitmap rotateAndFrame(Bitmap bitmap) { final boolean positive = sRandom.nextFloat() >= 0.5f; final float angle = (ROTATION_ANGLE_MIN + sRandom.nextFloat() * ROTATION_ANGLE_EXTRA) * (positive ? 1.0f : -1.0f); final double radAngle = Math.toRadians(angle); final int bitmapWidth = bitmap.getWidth(); final int bitmapHeight = bitmap.getHeight(); final double cosAngle = Math.abs(Math.cos(radAngle)); final double sinAngle = Math.abs(Math.sin(radAngle)); final int strokedWidth = (int) (bitmapWidth + 2 * PHOTO_BORDER_WIDTH); final int strokedHeight = (int) (bitmapHeight + 2 * PHOTO_BORDER_WIDTH); final int width = (int) (strokedHeight * sinAngle + strokedWidth * cosAngle); final int height = (int) (strokedWidth * sinAngle + strokedHeight * cosAngle); final float x = (width - bitmapWidth) / 2.0f; final float y = (height - bitmapHeight) / 2.0f; final Bitmap decored = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(decored); canvas.rotate(angle, width / 2.0f, height / 2.0f); canvas.drawBitmap(bitmap, x, y, sPaint); canvas.drawRect(x, y, x + bitmapWidth, y + bitmapHeight, sStrokePaint); return decored; } /** * Scales the specified Bitmap to fit within the specified dimensions. After scaling, * a frame is overlaid on top of the scaled image. * * This method is not thread safe. * * @param bitmap The Bitmap to scale to fit the specified dimensions and to apply * a frame onto. * @param width The maximum width of the new Bitmap. * @param height The maximum height of the new Bitmap. * * @return A scaled version of the original bitmap, whose dimension are less than or * equal to the specified width and height. */ static Bitmap scaleAndFrame(Bitmap bitmap, int width, int height) { final int bitmapWidth = bitmap.getWidth(); final int bitmapHeight = bitmap.getHeight(); final float scale = Math.min((float) width / (float) bitmapWidth, (float) height / (float) bitmapHeight); final int scaledWidth = (int) (bitmapWidth * scale); final int scaledHeight = (int) (bitmapHeight * scale); final Bitmap decored = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true); final Canvas canvas = new Canvas(decored); final int offset = (int) (PHOTO_BORDER_WIDTH / 2); sStrokePaint.setAntiAlias(false); canvas.drawRect(offset, offset, scaledWidth - offset - 1, scaledHeight - offset - 1, sStrokePaint); sStrokePaint.setAntiAlias(true); return decored; } }
114ch
trunk/src/com/google/android/photostream/ImageUtilities.java
Java
asf20
4,964
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.graphics.drawable.Drawable; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.ColorFilter; class FastBitmapDrawable extends Drawable { private Bitmap mBitmap; FastBitmapDrawable(Bitmap b) { mBitmap = b; } @Override public void draw(Canvas canvas) { canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public void setAlpha(int alpha) { } @Override public void setColorFilter(ColorFilter cf) { } @Override public int getIntrinsicWidth() { return mBitmap.getWidth(); } @Override public int getIntrinsicHeight() { return mBitmap.getHeight(); } @Override public int getMinimumWidth() { return mBitmap.getWidth(); } @Override public int getMinimumHeight() { return mBitmap.getHeight(); } public Bitmap getBitmap() { return mBitmap; } }
114ch
trunk/src/com/google/android/photostream/FastBitmapDrawable.java
Java
asf20
1,728
package com.besttone.app; import android.content.ContentValues; import android.content.SearchRecentSuggestionsProvider; import android.database.Cursor; import android.net.Uri; public class SuggestionProvider extends SearchRecentSuggestionsProvider { public static final String AUTHORITY = "com.besttone.app.114SuggestionProvider"; public static final String[] COLUMNS; public static final int MODE = DATABASE_MODE_QUERIES; private static String sDatabaseName = "suggestions.db"; private static int totalRecord; private final int MAXCOUNT = 20; static { String[] arrayOfString = new String[4]; arrayOfString[0] = "_id"; arrayOfString[1] = "display1"; arrayOfString[2] = "query"; arrayOfString[3] = "date"; COLUMNS = arrayOfString; } public SuggestionProvider() { //super(contex, AUTHORITY, MODE); setupSuggestions(AUTHORITY, MODE); } private Object[] columnValuesOfWord(int paramInt, String paramString1, String paramString2) { Object[] arrayOfObject = new Object[4]; arrayOfObject[0] = Integer.valueOf(paramInt); arrayOfObject[1] = paramString1; arrayOfObject[2] = paramString2; arrayOfObject[3] = paramString1; return arrayOfObject; } public Uri insert(Uri uri, ContentValues values) { String selection = "query=?"; String[] selectionArgs = new String[1]; selectionArgs[0] = "没有搜索记录"; super.delete(uri, selection, selectionArgs); Cursor localCursor = super.query(uri, COLUMNS, null, null, null); if (localCursor!=null && localCursor.getCount() == 0) { ContentValues localContentValues = new ContentValues(); localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[0], Integer.valueOf(2)); localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[1], Long.valueOf(System.currentTimeMillis())); localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[2], "清空搜索记录"); localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[3], "清空搜索记录"); super.insert(uri, localContentValues); } values.put("date", Long.valueOf(System.currentTimeMillis())); Uri localUri = super.insert(uri, values); return localUri; } public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Cursor localCursor = super.query(uri, projection, selection, selectionArgs, sortOrder); Object localObject; if (selectionArgs == null || selectionArgs.length == 0) if (localCursor.getCount() == 0) { ContentValues localContentValues = new ContentValues(); localContentValues .put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[0], Integer.valueOf(1)); localContentValues .put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[1], Long.valueOf(System.currentTimeMillis())); localContentValues .put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[2], "没有搜索记录"); localContentValues .put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[3], "没有搜索记录"); super.insert(uri, localContentValues); } localCursor = super.query(uri, projection, selection, selectionArgs, sortOrder); totalRecord = localCursor.getCount(); if (totalRecord > 20) truncateHistory(uri, -20 + totalRecord); return localCursor; } protected void truncateHistory(Uri paramUri, int paramInt) { if (paramInt < 0) throw new IllegalArgumentException(); String str = null; if (paramInt > 0) try { str = "_id IN (SELECT _id FROM suggestions ORDER BY date ASC LIMIT " + String.valueOf(paramInt) + " OFFSET 1)"; delete(paramUri, str, null); return; } catch (RuntimeException localRuntimeException) { } } }
114ch
trunk/src/com/besttone/app/SuggestionProvider.java
Java
asf20
3,994
package com.besttone.http; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.MarshalBase64; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import org.xmlpull.v1.XmlPullParser; import com.besttone.search.Client; import com.besttone.search.ServerListener; import com.besttone.search.model.ChResultInfo; import com.besttone.search.model.OrgInfo; import com.besttone.search.model.RequestInfo; import com.besttone.search.util.Constants; import com.besttone.search.util.SharedUtils; import com.besttone.search.util.XmlHelper; import android.util.Log; import android.util.Xml; public class WebServiceHelper { private static final String TAG = "WebServiceHelper"; //命名空间 private static final String serviceNameSpace="http://ws.besttone.com/"; //调用方法(获得支持的城市) //private static final String methodName="SearchChInfo"; private static final String methodName="searchChNewInfo"; private ChResultInfo resultInfo; private int i = 0; private List<Map<String, Object>> list; private ArrayList <String> resultAsociateCountList = new ArrayList<String>(); public ArrayList <String> getResultAsociateCountList() { return resultAsociateCountList; } public static interface WebServiceListener { public void onWebServiceSuccess(); public void onWebServiceFailed(); } public void setmListener(WebServiceListener mListener) { this.mListener = mListener; } private WebServiceListener mListener; public List<Map<String, Object>> searchChInfo(RequestInfo rqInfo){ Long t1 = System.currentTimeMillis(); list = new LinkedList<Map<String, Object>>(); //返回的查询结果 String result =null; //实例化SoapObject对象 SoapObject request=new SoapObject(serviceNameSpace, methodName); //假设方法有参数的话,设置调用方法参数 String rqXml = XmlHelper.getRequestXml(rqInfo); request.addProperty("xml", rqXml); request.addProperty("name",Constants.chName); request.addProperty("key",Constants.chKey); //设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致) //获得序列化的Envelope SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER10); //设置是否调用的是dotNet开发的 envelope.dotNet = false; envelope.bodyOut=request; envelope.setOutputSoapObject(request); //注册Envelope (new MarshalBase64()).register(envelope); //构建传输对象,并指明WSDL文档URL //Android传输对象 HttpTransportSE transport=new HttpTransportSE(Constants.serviceURL); transport.debug=true; //调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象): String soapAction = serviceNameSpace+methodName; try { transport.call(soapAction, envelope); //解析返回数据 Object resultObj = envelope.getResponse(); result = resultObj.toString(); parseChInfo(result); } catch (Exception e) { e.printStackTrace(); Log.v(TAG, "获取XML出错"); } Long t2 = System.currentTimeMillis(); Log.v(TAG, "获取查号信息耗时"+(t2-t1)+"毫秒"); return list; } public void parseChInfo(String xmlString) { Map<String, Object> map = new HashMap<String, Object>(); InputStream inputStream=null; //获得XmlPullParser解析器 XmlPullParser xmlParser = Xml.newPullParser(); try { //得到文件流,并设置编码方式 xmlParser.setInput(new StringReader(xmlString)); //获得解析到的事件类别,这里有开始文档,结束文档,开始标签,结束标签,文本等等事件。 int evtType=xmlParser.getEventType(); List<OrgInfo> orgList = null; OrgInfo info = null; String propertyName = null; String propertyValue = null; //一直循环,直到文档结束 while(evtType!=XmlPullParser.END_DOCUMENT){ String tag = xmlParser.getName(); switch(evtType){ case XmlPullParser.START_TAG: //如果是river标签开始,则说明需要实例化对象了 if (tag.equalsIgnoreCase("SearchResult")) { resultInfo = new ChResultInfo(); break; } if (tag.equalsIgnoreCase("BDCDataSource")) { resultInfo.setSource(xmlParser.nextText()); break; } if (tag.equalsIgnoreCase("BDCSearchflag")) { resultInfo.setSearchFlag(xmlParser.nextText()); break; } if (tag.equalsIgnoreCase("ResultCount")) { String cnt = xmlParser.nextText(); break; } if (tag.equalsIgnoreCase("ResultTime")) { String time = xmlParser.nextText(); break; } if (tag.equalsIgnoreCase("SingleResult")) { map = new HashMap<String, Object>(); break; } if (tag.equalsIgnoreCase("propertyName")) { propertyName = xmlParser.nextText(); break; } if (tag.equalsIgnoreCase("propertyValue")) { propertyValue = xmlParser.nextText(); if(propertyName!=null && "产品序列号".equals(propertyName)) { // if(propertyValue!=null && !Constants.SPACE.equals(propertyValue)){ // info.setChId(Integer.valueOf(propertyValue)); // } if(propertyValue==null || Constants.SPACE.equals(propertyValue)) { propertyValue = Constants.SPACE; } map.put("chId", propertyValue); } if(propertyName!=null && "公司名称".equals(propertyName)) { if(propertyValue==null || Constants.SPACE.equals(propertyValue)) { propertyValue = Constants.SPACE; } map.put("name", propertyValue); } if(propertyName!=null && "首查电话".equals(propertyName)) { if(propertyValue==null || Constants.SPACE.equals(propertyValue)) { propertyValue = Constants.SPACE; } map.put("tel", propertyValue); } if(propertyName!=null && "地址".equals(propertyName)) { if(propertyValue==null || Constants.SPACE.equals(propertyValue)) { propertyValue = Constants.SPACE; } map.put("addr", propertyValue); } if(propertyName!=null && "ORG_ID".equals(propertyName)) { map.put("orgId", propertyValue); } if(propertyName!=null && "所属城市".equals(propertyName)) { map.put("city", Constants.getCity(propertyValue)); } if(propertyName!=null && "Region_Cede".equals(propertyName)) { map.put("regionCode", propertyValue); } if(propertyName!=null && "IS_DC".equals(propertyName)) { map.put("isDc", propertyValue); } if(propertyName!=null && "IS_DF".equals(propertyName)) { map.put("isDf", propertyValue); } if(propertyName!=null && "QYMP".equals(propertyName)) { map.put("isQymp", propertyValue); } propertyName = null; propertyValue = null; } break; case XmlPullParser.END_TAG: //如果遇到river标签结束,则把river对象添加进集合中 if (tag.equalsIgnoreCase("SingleResult")) { if(map.get("addr")==null) { map.put("addr", Constants.SPACE); } if(map.get("tel")==null) { map.put("tel", Constants.SPACE); } list.add(map); } break; default:break; } //如果xml没有结束,则导航到下一个river节点 evtType=xmlParser.next(); } } catch (Exception e) { e.printStackTrace(); Log.v(TAG, "xml解析出错"+e.getMessage()); } } public void sendRequest(final ServerListener listener, final RequestInfo rqInfo) { Client.getThreadPoolForRequest().execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { Thread.sleep(1000); } catch (Exception e) { } list = searchChInfo(rqInfo); listener.serverDataArrived(list, false); } }); } public ArrayList<String> getAssociateList(String key,String regionCode) { Long t1 = System.currentTimeMillis(); ArrayList<String> resultAssociateList = new ArrayList<String>(); // new ArrayList<String>(); //返回的查询结果 String result =null; //实例化SoapObject对象 SoapObject request=new SoapObject(serviceNameSpace, Constants.associate_method); //假设方法有参数的话,设置调用方法参数 StringBuilder sb = new StringBuilder(""); if (key != null && regionCode != null) { sb.append("<ChKeyInpara>"); sb.append("<content><![CDATA[" + key + "]]></content>"); sb.append("<regionCode><![CDATA[" + regionCode + "]]></regionCode>"); Log.d("regionCode",regionCode); sb.append("<imsi><![CDATA[" + SharedUtils.getCurrentPhoneImsi(Client.getContext()) + "]]></imsi>"); sb.append("<deviceid><![CDATA[" + SharedUtils.getCurrentPhoneDeviceId(Client.getContext()) + "]]></deviceid>"); sb.append("<pageSize><![CDATA[" + "10" + "]]></pageSize>"); sb.append("</ChKeyInpara>"); } request.addProperty("xml", sb.toString()); request.addProperty("name",Constants.chName); request.addProperty("key",Constants.chKey); //设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致) //获得序列化的Envelope SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER10); //设置是否调用的是dotNet开发的 envelope.dotNet = false; envelope.bodyOut=request; envelope.setOutputSoapObject(request); //注册Envelope (new MarshalBase64()).register(envelope); //构建传输对象,并指明WSDL文档URL //Android传输对象 HttpTransportSE transport=new HttpTransportSE(Constants.serviceURL); transport.debug=true; //调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象): String soapAction = serviceNameSpace+Constants.associate_method; try { transport.call(soapAction, envelope); //解析返回数据 Object resultObj = envelope.getResponse(); result = resultObj.toString(); resultAssociateList = parseKeywordInfo(result); } catch (Exception e) { e.printStackTrace(); Log.v(TAG, "关键词联想获取出错"); } Long t2 = System.currentTimeMillis(); Log.v(TAG, "关键词联想获取耗时"+(t2-t1)+"毫秒"); // if(mListener!=null) // mListener.onWebServiceSuccess(); return resultAssociateList; } public ArrayList<String> parseKeywordInfo(String xmlString) { Map<String, Object> map = new HashMap<String, Object>(); ArrayList<String> resultList = new ArrayList<String>(); InputStream inputStream=null; //获得XmlPullParser解析器 XmlPullParser xmlParser = Xml.newPullParser(); try{ //得到文件流,并设置编码方式 xmlParser.setInput(new StringReader(xmlString)); Log.d("xml",xmlString); //获得解析到的事件类别,这里有开始文档,结束文档,开始标签,结束标签,文本等等事件。 int evtType=xmlParser.getEventType(); // 一直循环,直到文档结束 while (evtType != XmlPullParser.END_DOCUMENT) { String tag = xmlParser.getName(); switch (evtType) { case XmlPullParser.START_TAG: // 如果是river标签开始,则说明需要实例化对象了 if (tag.equalsIgnoreCase("ChKeyResult")) { map = new HashMap<String, Object>(); break; } if (tag.equalsIgnoreCase("resultNum")) { String resultNum = xmlParser.nextText(); map.put("resultNum", resultNum); break; } if (tag.equalsIgnoreCase("result")) { String result = xmlParser.nextText(); map.put("result", result); break; } if (tag.equalsIgnoreCase("searchTime")) { String searchTime = xmlParser.nextText(); map.put("searchTime", searchTime); break; } if (tag.equalsIgnoreCase("ChKeyList")) { break; } if (tag.equalsIgnoreCase("searchKey")) { String searchKey = xmlParser.nextText(); resultList.add(searchKey); Log.v("resultlist",searchKey); break; } if (tag.equalsIgnoreCase("zqCount")) { String zqCount = xmlParser.nextText(); resultAsociateCountList.add(zqCount); Log.v("resultAsociateCountList",zqCount); break; } break; case XmlPullParser.END_TAG: // 如果遇到river标签结束,则把river对象添加进集合中 if (tag.equalsIgnoreCase("ChKeyResult")) { map.put("resultList", resultList); } break; default: break; } // 如果xml没有结束,则导航到下一个river节点 evtType = xmlParser.next(); } } catch (Exception e) { e.printStackTrace(); Log.v(TAG, "xml解析出错"+e.getMessage()); } return resultList; } }
114ch
trunk/src/com/besttone/http/WebServiceHelper.java
Java
asf20
15,494
package com.besttone.http; import com.besttone.search.Client; public class UpdateRequest extends WebServiceHelper { public static interface UpdateListener { public void onUpdateAvaiable(String msg, String url); public void onUpdateMust(String msg, String url); public void onUpdateNoNeed(String msg); public void onUpdateError(short code, Exception e); } private String latestVersionCode = ""; private String url = ""; private String versionInfo = ""; private UpdateListener mListener = null; public void setListener(UpdateListener mListener) { this.mListener = mListener; } public void checkUpdate() { Client.getThreadPoolForRequest().execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub getUpdateInfo(); Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if ( !Client.getVersion(Client.getContext()) .equals( latestVersionCode ) ) { mListener.onUpdateAvaiable(versionInfo, ""); } else { mListener.onUpdateNoNeed(""); } } }); } }); } private void getUpdateInfo() { this.latestVersionCode = "0.2.9"; this.url = "http://droidapps.googlecode.com/files/MiniFetion-2.8.4.apk"; this.versionInfo="更新信息:"; } }
114ch
trunk/src/com/besttone/http/UpdateRequest.java
Java
asf20
1,431
package com.besttone.search; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.besttone.adapter.AreaAdapter; import com.besttone.adapter.CateAdapter; import com.besttone.adapter.SortAdapter; import com.besttone.http.WebServiceHelper; import com.besttone.search.model.District; import com.besttone.search.model.RequestInfo; import com.besttone.search.util.Constants; import com.besttone.search.util.SharedUtils; import com.besttone.widget.PoiListItem; import com.besttone.search.R; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.RawContacts; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.Toast; public class SearchResultActivity extends Activity implements ServerListener, OnClickListener { private Context mContext; private List<Map<String, Object>> filterData; private View loadingView; private View addShopView; private ListView list; private boolean isEnd = false; PoiResultAdapter resultAdapter = null; ListAdapter areaAdapter = null; CateAdapter cateAdapter = null; private ImageButton btn_back; private Button mSearchBtn; private Button mAreaBtn; private String[] mAreaArray = null; private List<District> localDistrictList = null; private String[] mChannelArray = null; private int mAreaIndex = 0; private Button mChannelBtn; public PopupWindow mPopupWindow; private ListView popListView; private String keyword; private RequestInfo rqInfo; private WebServiceHelper serviceHelper; private boolean isLoadingRemoved = false; private boolean isLoadingEnd = false; Handler handler = new Handler() { public void handleMessage(Message paramMessage) { if (paramMessage.what == 1) { loadingView.setVisibility(View.GONE); } else if (paramMessage.what == 2) { list.removeFooterView(loadingView); isLoadingRemoved = true; } else if (paramMessage.what == 3) { list.addFooterView(loadingView); loadingView.setVisibility(View.VISIBLE); isLoadingRemoved = false; } else if (paramMessage.what == 4) { loadingView.setVisibility(View.VISIBLE); } else if (paramMessage.what == 5) { list.removeFooterView(loadingView); isLoadingRemoved = true; if(!isLoadingEnd) addShopView(); } } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.search_result); mContext = this.getApplicationContext(); init(); } private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() { public void onClick(View v) { finish(); } }; private Button.OnClickListener searchHistroyListner = new Button.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(); intent.setClass(SearchResultActivity.this, SearchActivity.class); finish(); startActivity(intent); } }; private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // Intent intent = new Intent(); // ListView listView = (ListView)parent; // HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position); // intent.setClass(ResultActivity.this, DetailActivity.class); // if(map.get("id")==null || "".equals(map.get("id"))) { // intent.putExtra("id", "2029602847-421506714"); // } else { // intent.putExtra("id", map.get("id")); // } // startActivity(intent); // ResultActivity.this.finish(); //显示数据详情 //Toast.makeText(SearchResultActivity.this, "正在开发中,敬请期待...", Toast.LENGTH_SHORT).show(); } }; public class PoiResultAdapter extends BaseAdapter { private LayoutInflater mInflater; public PoiResultAdapter(Context context) { this.mInflater = LayoutInflater.from(context); } public int getCount() { return filterData.size(); } public Object getItem(int position) { return filterData.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { } convertView = mInflater.inflate(R.layout.search_result_item, null); // convertView.findViewById(R.id.name).setSelected(true); // convertView.findViewById(R.id.addr).setSelected(true); PoiListItem item = (PoiListItem) convertView; Map map = filterData.get(position); item.setPoiData(map.get("name").toString(), map.get("tel") .toString(), map.get("addr").toString(),(map .get("city")==null?null:(map .get("city")).toString()) ); if (position == filterData.size() - 1 && !isEnd) { loadingView.setVisibility(View.VISIBLE); //下拉获取数据 int size = filterData.size(); int page = 1 + size/Constants.PAGE_SIZE; int currentPage =Integer.valueOf(rqInfo.getPage()); if(size==currentPage*Constants.PAGE_SIZE) { rqInfo.setPage(Constants.SPACE + page); serviceHelper.sendRequest(SearchResultActivity.this, rqInfo); } else { //Toast.makeText(ResultActivity.this, "没有更多的数据", Toast.LENGTH_SHORT).show(); Message localMessage = new Message(); localMessage.what = 5; handler.sendMessage(localMessage); } } return convertView; } } public void addShopView() { isLoadingEnd = true; addShopView = getLayoutInflater().inflate(R.layout.search_result_empty, null, false); list.addFooterView(addShopView); addShopView.setVisibility(View.VISIBLE); } public void serverDataArrived(List list, boolean isEnd) { this.isEnd = isEnd; Iterator iter = list.iterator(); while (iter.hasNext()) { filterData.add((Map<String, Object>) iter.next()); } Message localMessage = new Message(); if (!isEnd) { localMessage.what = 1; } else { localMessage.what = 2; } if(list!=null && list.size()==0){ localMessage.what = 5; } this.handler.sendMessage(localMessage); } public void onClick(View v) { switch (v.getId()) { case R.id.area: { showDialogPopup(R.id.area); break; } case R.id.channel: { showDialogPopup(R.id.channel); // if (mPopupWindow != null && mPopupWindow.isShowing()) { // mPopupWindow.dismiss(); // } else { // createPopWindow(v); // } break; } } } protected void showDialogPopup(int viewId) { AlertDialog.Builder localBuilder = new AlertDialog.Builder(this); switch (viewId) { case R.id.area: { if (areaAdapter == null) { areaAdapter = new AreaAdapter(this, mAreaArray); } localBuilder.setAdapter(areaAdapter, new areaPopupListener( areaAdapter)); break; } case R.id.channel: { if (cateAdapter == null) { cateAdapter = new CateAdapter(this, mChannelArray); } localBuilder.setAdapter(cateAdapter, new channelPopupListener( cateAdapter)); break; } } AlertDialog localAlertDialog = localBuilder.create(); localAlertDialog.show(); } class areaPopupListener implements DialogInterface.OnClickListener { AreaAdapter mAdapter; public areaPopupListener(ListAdapter adapter) { mAdapter = (AreaAdapter) adapter; } public void onClick(DialogInterface dialog, int which) { ((AreaAdapter) mAdapter).setTypeIndex(which); final String cityName = ((AreaAdapter) mAdapter).getSelect(); mAreaBtn.setText(cityName); filterData.clear(); filterData = new ArrayList<Map<String, Object>>(); resultAdapter.notifyDataSetChanged(); if (isLoadingRemoved) { list.addFooterView(loadingView); loadingView.setVisibility(View.VISIBLE); isLoadingRemoved = false; } else { loadingView.setVisibility(View.VISIBLE); } if(isLoadingEnd){ list.removeFooterView(addShopView); isLoadingEnd = false; } //获取数据 String simplifyCode = null; if("全部区域".equals(cityName)) { simplifyCode = SharedUtils.getCurrentSimplifyCode(mContext); } else { simplifyCode = ((District)(localDistrictList.get(which-1))).getDistrictCode(); // simplifyCode = Constants.getSimplifyCodeByName(mContext, cityName); } // Log.d("getdis",simplifyCode); rqInfo.setRegion(simplifyCode); String tradeName = mChannelBtn.getText().toString(); if(!"全部行业".equals(tradeName)) { rqInfo.setContent(keyword + "/n|" + tradeName + "/i"); } else { rqInfo.setContent(keyword+"/n"); } rqInfo.setPage("1"); rqInfo.setPageSize(Constants.SPACE + Constants.PAGE_SIZE); serviceHelper = new WebServiceHelper(); serviceHelper.sendRequest(SearchResultActivity.this, rqInfo); } } class channelPopupListener implements DialogInterface.OnClickListener { CateAdapter cAdapter; public channelPopupListener(CateAdapter adapter) { cAdapter = (CateAdapter) adapter; } public void onClick(DialogInterface dialog, int which) { ((CateAdapter) cAdapter).setTypeIndex(which); final String tradeName = ((CateAdapter) cAdapter).getSelect(); mChannelBtn.setText(tradeName); filterData.clear(); filterData = new ArrayList<Map<String, Object>>(); resultAdapter.notifyDataSetChanged(); if (isLoadingRemoved) { list.addFooterView(loadingView); loadingView.setVisibility(View.VISIBLE); isLoadingRemoved = false; } else { loadingView.setVisibility(View.VISIBLE); } if(isLoadingEnd){ list.removeFooterView(addShopView); isLoadingEnd = false; } //获取数据 String simplifyCode = null; String cityName = mAreaBtn.getText().toString(); if("全部区域".equals(cityName)) { simplifyCode = SharedUtils.getCurrentSimplifyCode(mContext); } else { simplifyCode = Constants.getSimplifyCodeByName(mContext, cityName); } if(!"全部行业".equals(tradeName)) { rqInfo.setContent(keyword + "/n|" + tradeName + "/i"); } else { rqInfo.setContent(keyword+"/n"); } rqInfo.setRegion(simplifyCode); rqInfo.setPage("1"); rqInfo.setPageSize(Constants.SPACE + Constants.PAGE_SIZE); serviceHelper = new WebServiceHelper(); serviceHelper.sendRequest(SearchResultActivity.this, rqInfo); } } private void init() { filterData = PoiResultData.getData(); list = (ListView) findViewById(R.id.resultlist); list.setFastScrollEnabled(true); resultAdapter = new PoiResultAdapter(this); btn_back = (ImageButton) findViewById(R.id.left_title_button); btn_back.setOnClickListener(backListner); rqInfo = new RequestInfo(); Bundle bundle = this.getIntent().getExtras(); rqInfo.setRegion(SharedUtils.getCurrentSimplifyCode(this)); rqInfo.setDeviceid(SharedUtils.getCurrentPhoneDeviceId(this)); rqInfo.setImsi(SharedUtils.getCurrentPhoneImsi(this)); rqInfo.setMobile(SharedUtils.getCurrentPhoneNo(this)); rqInfo.setPage("1"); rqInfo.setPageSize(Constants.SPACE + Constants.PAGE_SIZE); keyword = bundle.getString("keyword"); rqInfo.setContent(keyword+"/n"); serviceHelper = new WebServiceHelper(); serviceHelper.sendRequest(this, rqInfo); mSearchBtn = ((Button)findViewById(R.id.start_search)); mSearchBtn.setText(bundle.getString("keyword")); mSearchBtn.setOnClickListener(searchHistroyListner); loadingView = LayoutInflater.from(this).inflate(R.layout.listfooter, null); list.addFooterView(loadingView); list.setAdapter(resultAdapter); list.setOnItemClickListener(mOnClickListener); list.setOnItemLongClickListener(mOnLongClickListener); mAreaBtn = ((Button)findViewById(R.id.area)); mChannelBtn = ((Button)findViewById(R.id.channel)); mAreaBtn.setOnClickListener(this); mChannelBtn.setOnClickListener(this); initHomeView(); } private void initHomeView() { localDistrictList = Constants.getDistrictList(this, SharedUtils.getCurrentCityCode(this)); mAreaArray = Constants.getDistrictArray(this, SharedUtils.getCurrentCityCode(this)); if ((mAreaArray == null) || (this.mAreaArray.length == 0)) { mAreaBtn.setText("全部区域"); mAreaBtn.setEnabled(false); } while (true) { mChannelArray = getResources().getStringArray(R.array.trade_name_items); mAreaBtn.setText(this.mAreaArray[this.mAreaIndex]); mAreaBtn.setEnabled(true); return; } } private void createPopWindow(View parent) { // LayoutInflater lay = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); // View view = lay.inflate(R.layout.popup_window, null ); // // mPopupWindow = new PopupWindow(view, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); // // //初始化listview,加载数据 // popListView = (ListView) findViewById(R.id.pop_list); //// if (sortAdapter == null) { //// sortAdapter = new SortAdapter(this, mSortArray); //// } //// popListView.setAdapter(sortAdapter); // // // //设置整个popupwindow的样式 // mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.right_filter_bg)); // // mPopupWindow.setFocusable(true ); // mPopupWindow.setTouchable(true); // mPopupWindow.setOutsideTouchable(true); // mPopupWindow.update(); // mPopupWindow.showAsDropDown(parent, 10, 10); View contentView = LayoutInflater.from(getApplicationContext()) .inflate(R.layout.popup_window, null); mPopupWindow = new PopupWindow(contentView, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); mPopupWindow.setContentView(contentView); //设置整个popupwindow的样式 mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.right_filter_bg)); String[] name = openDir(); ListView listView = (ListView) contentView.findViewById(R.id.pop_list); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name); listView.setAdapter(adapter); mPopupWindow.setFocusable(true ); mPopupWindow.setTouchable(true); mPopupWindow.setOutsideTouchable(true); mPopupWindow.update(); mPopupWindow.showAsDropDown(parent, 10, 10); } private String[] openDir() { String[] name; String rootPath = Environment.getExternalStorageDirectory() .getAbsolutePath(); File file = new File(rootPath); File[] files = file.listFiles(); name = new String[files.length]; for (int i = 0; i < files.length; i++) { name[i] = files[i].getName(); System.out.println(name[i]); } return name; } private AdapterView.OnItemLongClickListener mOnLongClickListener = new AdapterView.OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { ListView listView = (ListView)parent; HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position); final String name = map.get("name"); final String tel = map.get("tel"); final String addr = map.get("addr"); String[] array = new String[2]; array[0] = "呼叫 " + tel; array[1] = "添加至联系人"; new AlertDialog.Builder(SearchResultActivity.this) .setTitle(name) .setItems(array, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if(which == 0) { Intent myIntentDial = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel)); startActivity(myIntentDial); } if(which == 1){ String rwContactId = getContactId(name); ContentResolver resolver = mContext.getContentResolver(); ContentValues values = new ContentValues(); //联系人中是否存在,若存在则更新 if(rwContactId!=null && !"".equals(rwContactId)){ Toast.makeText(SearchResultActivity.this, "商家已存在", Toast.LENGTH_SHORT).show(); // String whereClause = ContactsContract.RawContacts.Data.RAW_CONTACT_ID + "= ? AND " + ContactsContract.Data.MIMETYPE + "=?"; // // values.clear(); // values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); // values.put(StructuredName.DISPLAY_NAME, name); // resolver.update(Data.CONTENT_URI, values, whereClause, new String[]{rwContactId, StructuredName.CONTENT_ITEM_TYPE }); // // values.clear(); // values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); // values.put(Phone.NUMBER, tel); // if(isMobilePhone(tel)){ // values.put(Phone.TYPE, Phone.TYPE_MOBILE); // values.put(Phone.LABEL, Phone.TYPE_WORK_MOBILE); // } else { // values.put(Phone.TYPE, Phone.TYPE_WORK); // values.put(Phone.LABEL, Phone.TYPE_WORK); // } // resolver.update(Data.CONTENT_URI, values, whereClause, new String[]{rwContactId, Phone.CONTENT_ITEM_TYPE}); // // values.clear(); // values.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE); // values.put(StructuredPostal.TYPE, StructuredPostal.TYPE_WORK); // values.put(StructuredPostal.LABEL, StructuredPostal.TYPE_WORK); // values.put(StructuredPostal.STREET, addr); // resolver.update(Data.CONTENT_URI, values, whereClause, new String[]{rwContactId, StructuredPostal.CONTENT_ITEM_TYPE}); // // Toast.makeText(SearchResultActivity.this, "联系人更新成功", Toast.LENGTH_SHORT).show(); } else { Uri rawContactUri = resolver.insert( RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri); values.clear(); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); values.put(StructuredName.DISPLAY_NAME, name); resolver.insert(Data.CONTENT_URI, values); values.clear(); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); values.put(Phone.NUMBER, tel); if(isMobilePhone(tel)){ values.put(Phone.TYPE, Phone.TYPE_MOBILE); values.put(Phone.LABEL, Phone.TYPE_WORK_MOBILE); } else { values.put(Phone.TYPE, Phone.TYPE_WORK); values.put(Phone.LABEL, Phone.TYPE_WORK); } resolver.insert(Data.CONTENT_URI, values); values.clear(); values.put(Data.RAW_CONTACT_ID, rawContactId); values.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE); values.put(StructuredPostal.TYPE, StructuredPostal.TYPE_WORK); values.put(StructuredPostal.LABEL, StructuredPostal.TYPE_WORK); values.put(StructuredPostal.STREET, addr); resolver.insert(Data.CONTENT_URI, values); Toast.makeText(SearchResultActivity.this, "添加成功", Toast.LENGTH_SHORT).show(); } } } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }).show(); return true; } }; public boolean isMobilePhone(String tel){ boolean flag = false; if(tel!=null && tel.length()==11){ String reg = "^(13[0-9]|15[012356789]|18[0236789]|14[57])[0-9]{8}$"; flag = tel.matches(reg); } return flag; } /* * 根据电话号码取得联系人姓名 */ public void getPeople() { String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}; // 将自己添加到 msPeers 中 Cursor cursor = this.getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, // Which columns to return. ContactsContract.CommonDataKinds.Phone.NUMBER + " = '021-65291718'", // WHERE clause. null, // WHERE clause value substitution null); // Sort order. if( cursor == null ) { return; } System.out.println(cursor.getCount()); for( int i = 0; i < cursor.getCount(); i++ ) { cursor.moveToPosition(i); // 取得联系人名字 int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME); String name = cursor.getString(nameFieldColumnIndex); System.out.println("联系人姓名:" + name); Toast.makeText(SearchResultActivity.this, "联系人姓名:" + name, Toast.LENGTH_SHORT).show(); } } /* * 根据联系人姓名取得ID */ public String getContactId(String name) { String rawContactId = null; String[] projection = { ContactsContract.RawContacts.Data.RAW_CONTACT_ID }; // 将自己添加到 msPeers 中 Cursor cursor = this.getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, // Which columns to return. ContactsContract.PhoneLookup.DISPLAY_NAME + " = '"+ name +"'", // WHERE clause. null, // WHERE clause value substitution null); // Sort order. if( cursor == null ) { return null; } else if(cursor.getCount()>0){ cursor.moveToFirst(); // 取得联系人ID int idFieldColumnIndex = cursor.getColumnIndex(ContactsContract.RawContacts.Data.RAW_CONTACT_ID); rawContactId = cursor.getString(idFieldColumnIndex); return rawContactId; } return null; } }
114ch
trunk/src/com/besttone/search/SearchResultActivity.java
Java
asf20
24,622
package com.besttone.search; import java.io.InputStream; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.amap.cn.apis.util.ConstantsAmap; import com.amap.mapapi.core.AMapException; import com.amap.mapapi.geocoder.Geocoder; import com.amap.mapapi.location.LocationManagerProxy; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.location.Address; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.os.Bundle; import android.os.Handler; import android.os.IInterface; import android.os.Message; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.WindowManager; import android.widget.Toast; public class Client { // ------------------------------------------------------------------------- private static Client instance; private static String screenSize = ""; private static String deviceId = ""; private static float dencyRate = 1.0f; private static DisplayMetrics display; private Handler mHd; private ThreadPoolExecutor mThreadPoorForLocal; private ThreadPoolExecutor mThreadPoorForDownload; private ThreadPoolExecutor mThreadPoorForRequest; private Context mContext; private final static String Tag = "Client"; private Geocoder coder; private String addressName; private LocationManagerProxy locationManager = null; public String area; public String cityName; private GetLocationAdressListener mLoactionDlistener = null; public boolean bChangeCity=true; public final String iflytech_APP_ID = "508eafc2"; public void setmLoactionDlistener(GetLocationAdressListener mLoactionDlistener) { this.mLoactionDlistener = mLoactionDlistener; } // ------------------------------------------------------------------------- private Client() { instance = this; mHd = new Handler(); mThreadPoorForLocal = new ThreadPoolExecutor(3, 6, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)); mThreadPoorForRequest = new ThreadPoolExecutor(4, 8, 15, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)); mThreadPoorForDownload = new ThreadPoolExecutor(2, 5, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)); } // ------------------------------------------------------------------------- public static void release() { try { instance.mThreadPoorForLocal.shutdownNow(); instance.mThreadPoorForRequest.shutdownNow(); instance.mThreadPoorForDownload.shutdownNow(); } catch (Exception e) { e.printStackTrace(); } instance = null; } // ------------------------------------------------------------------------- public static Client getInstance() { if (instance == null) { instance = new Client(); } return instance; } // ------------------------------------------------------------------------- public static Handler getHandler() { return getInstance().mHd; } // ------------------------------------------------------------------------- public static void postRunnable(Runnable r) { getInstance().mHd.post(r); } // ------------------------------------------------------------------------- public static ThreadPoolExecutor getThreadPoolForLocal() { return getInstance().mThreadPoorForLocal; } // ------------------------------------------------------------------------- public static ThreadPoolExecutor getThreadPoolForRequest() { Log.d(Tag, "request"); return getInstance().mThreadPoorForRequest; } // ------------------------------------------------------------------------- public static ThreadPoolExecutor getThreadPoolForDownload() { return getInstance().mThreadPoorForDownload; } // ------------------------------------------------------------------------- public static void initWithContext(Context context) { getInstance().mContext = context; display = new DisplayMetrics(); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); if (null != wm) { wm.getDefaultDisplay().getMetrics(display); screenSize = display.widthPixels < display.heightPixels ? display.widthPixels + "x" + display.heightPixels : display.heightPixels + "x" + display.widthPixels; dencyRate = display.density / 1.5f; } TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (null != tm) { deviceId = tm.getDeviceId(); if (null == deviceId) deviceId = ""; } getInstance().locationManager = LocationManagerProxy.getInstance(Client.getContext()); } // ------------------------------------------------------------------------- public static Context getContext() { return getInstance().mContext; } // ------------------------------------------------------------------------- public static String getDeviceId() { return deviceId; } // ------------------------------------------------------------------------- public static String getScreenSize() { return screenSize; } // ------------------------------------------------------------------------- public static float getDencyParam() { return dencyRate; } // ------------------------------------------------------------------------- public static DisplayMetrics getDisplayMetrics() { return display; } // ------------------------------------------------------------------------- public static boolean decetNetworkOn() { try { ConnectivityManager cm = (ConnectivityManager) getInstance().mContext .getSystemService(Context.CONNECTIVITY_SERVICE); if (null != cm) { NetworkInfo wi = cm.getActiveNetworkInfo(); if (null != wi) return wi.isConnected(); } } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean decetNetworkOn(Context c) { ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); if (null != cm) { NetworkInfo info = cm.getActiveNetworkInfo(); if (null != info) return info.isConnected(); } return false; } public static Bundle getAppInfoBundle(Context context) { Bundle bundle = null; try { ApplicationInfo appInfo = ((Activity) context).getPackageManager().getApplicationInfo( ((Activity) context).getPackageName(), PackageManager.GET_META_DATA); if (appInfo != null) { bundle = appInfo.metaData; } PackageInfo pinfo = ((Activity) context).getPackageManager().getPackageInfo( ((Activity) context).getPackageName(), PackageManager.GET_CONFIGURATIONS); if (pinfo != null) { bundle.putString("versionName", pinfo.versionName); bundle.putInt("versionCode", pinfo.versionCode); } } catch (NameNotFoundException e) { e.printStackTrace(); } return bundle; } /** * 应用程序版本 * * @param context * @return */ public static String getVersion(Context context) { String uVersion = ""; Bundle bundle = getAppInfoBundle(context); if (bundle != null) { uVersion = bundle.getString("versionName"); } return uVersion; } // 高德定位 // 地理编码 public void getAddress(final double mLat, final double mLon) { this.getThreadPoolForRequest().execute(new Runnable() { public void run() { try { coder = new Geocoder(Client.getContext()); List<Address> address = coder.getFromLocation(mLat, mLon, 3); Log.d("adress", "" + address.size()); if (address != null && address.size() > 0) { Address addres = address.get(0); addressName = addres.getAdminArea() + addres.getSubLocality() + addres.getFeatureName() + "附近"; String ad = addres.getAdminArea(); String su = addres.getSubLocality(); if (ad.contains("市")) area = ad; else area = su; Log.d("adress", "" + addressName); Log.d("area", "" + area); mLoactionDlistener.onGetLocationAdress(); } } catch (AMapException e) { // TODO Auto-generated catch block Log.e("adress", ""+e.toString()); // mLoactionDlistener.onFialedGetLocationAdress(); } catch (Exception e) { // TODO Auto-generated catch block Log.e("adress", ""+e.toString()); // mLoactionDlistener.onFialedGetLocationAdress(); } } }); } public void tryGetAddress(final double mLat, final double mLon) { this.getThreadPoolForRequest().execute(new Runnable() { public void run() { try { coder = new Geocoder(Client.getContext()); List<Address> address = coder.getFromLocation(mLat, mLon, 3); Log.d("adress", "" + address.size()); if (address != null && address.size() > 0) { Address addres = address.get(0); addressName = addres.getAdminArea() + addres.getSubLocality() + addres.getFeatureName() + "附近"; Log.d("adress", "" + addressName); Log.d("area", "" + area); } } catch (AMapException e) { // TODO Auto-generated catch block Log.e("adress", ""+e.toString()); mLoactionDlistener.onFialedGetLocationAdress(); } catch (Exception e) { // TODO Auto-generated catch block Log.e("adress", ""+e.toString()); mLoactionDlistener.onFialedGetLocationAdress(); } } }); } public boolean enableMyLocation() { boolean result; result = true; try { Criteria cri = new Criteria(); cri.setAccuracy(Criteria.ACCURACY_COARSE); cri.setAltitudeRequired(false); cri.setBearingRequired(false); cri.setCostAllowed(false); String bestProvider = locationManager.getBestProvider(cri, true); Log.d("bestProvider",bestProvider); locationManager.requestLocationUpdates(bestProvider, 60000, 100, locationListener); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } public void disableMyLocation() { try { locationManager.removeUpdates(locationListener); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } LocationListener locationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub Toast.makeText(Client.getContext(), "定位失败,请检查网络和GPS", Toast.LENGTH_SHORT); } @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub if (location != null) { Double geoLat = location.getLatitude(); Double geoLng = location.getLongitude(); String str = ("定位成功:(" + geoLat + "," + geoLng + ")"); Message msg = new Message(); msg.obj = str; Log.d("location",str); // getAddress(30.783298, 120.376826); // getAddress(38.844814, 105.706442);//阿拉善盟 // getAddress(52.335262, 124.711526);//大兴安岭地区 // getAddress(42.904823, 129.513228);//延边朝鲜族自治州 getAddress(geoLat,geoLng); } } }; public static interface GetLocationAdressListener { public void onGetLocationAdress(); public void onFialedGetLocationAdress(); } /** * 读取语法文件 * @return */ public static String readAbnfFile() { int len = 0; byte []buf = null; String grammar = ""; try { InputStream in = getContext().getAssets().open("gm_continuous_digit.abnf"); len = in.available(); buf = new byte[len]; in.read(buf, 0, len); grammar = new String(buf,"gbk"); } catch (Exception e1) { e1.printStackTrace(); } return grammar; } }
114ch
trunk/src/com/besttone/search/Client.java
Java
asf20
12,726
package com.besttone.search; import android.app.Application; public class Ch114NewApplication extends Application { @Override public void onCreate() { //appContext = getApplicationContext(); super.onCreate(); Client.getInstance(); } }
114ch
trunk/src/com/besttone/search/Ch114NewApplication.java
Java
asf20
266
package com.besttone.search.sql; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class NativeDBHelper extends SQLiteOpenHelper { public static final String AREA_CODE = "AREA_CODE"; public static final int AREA_CODE_INDEX = 9; public static final String BUSINESS_FLAG = "BUSINESS_FLAG"; public static final int BUSINESS_FLAG_INDEX = 12; public static final int DATABASE_VERSION = 1; public static final String ENG_NAME = "ENG_NAME"; public static final int ENG_NAME_INDEX = 7; public static final String FIRST_PY = "FIRST_PY"; public static final int FIRST_PY_INDEX = 6; public static final String ID = "ID"; public static final int ID_INDEX = 0; public static final String IS_FREQUENT = "IS_FREQUENT"; public static final int IS_FREQUENT_INDEX = 10; public static final String NAME = "NAME"; public static final int NAME_INDEX = 4; public static final String PARENT_REGION = "PARENT_REGION"; public static final int PARENT_REGION_INDEX = 2; public static final String REGION_CODE = "REGION_CODE"; public static final int REGION_CODE_INDEX = 1; public static final String SHORT_NAME = "SHORT_NAME"; public static final int SHORT_NAME_INDEX = 5; public static final String SORT_VALUE = "SORT_VALUE"; public static final int SORT_VALUE_INDEX = 11; public static final String TEL_LENGTH = "TEL_LENGTH"; public static final int TEL_LENGTH_INDEX = 8; public static final String TYPE = "TYPE"; public static final String TYPE_CITY = "2"; public static final String TYPE_DISTRICT = "3"; public static final int TYPE_INDEX = 3; public static final String TYPE_PROVINCE = "1"; private static NativeDBHelper sInstance; private final String[] mColumns; private NativeDBHelper(Context paramContext) { super(paramContext, "native_database.db", null, 1); String[] arrayOfString = new String[8]; arrayOfString[0] = "ID"; arrayOfString[1] = "REGION_CODE"; arrayOfString[2] = "PARENT_REGION"; arrayOfString[3] = "TYPE"; arrayOfString[4] = "SHORT_NAME"; arrayOfString[5] = "FIRST_PY"; arrayOfString[6] = "AREA_CODE"; arrayOfString[7] = "BUSINESS_FLAG"; this.mColumns = arrayOfString; } public static NativeDBHelper getInstance(Context paramContext) { if (sInstance == null) sInstance = new NativeDBHelper(paramContext); return sInstance; } public void onCreate(SQLiteDatabase paramSQLiteDatabase) { } public void onUpgrade(SQLiteDatabase paramSQLiteDatabase, int paramInt1, int paramInt2) { } public Cursor select(String[] paramArrayOfString1, String paramString, String[] paramArrayOfString2) { return getReadableDatabase().query("PUB_LOCATION", paramArrayOfString1, paramString, paramArrayOfString2, null, null, null); } public Cursor selectAllCity() { String[] arrayOfString = new String[1]; arrayOfString[0] = "2"; return select(this.mColumns, "TYPE=?", arrayOfString); } public Cursor selectCodeByName(String paramString) { String[] arrayOfString = new String[1]; arrayOfString[0] = paramString; return select(this.mColumns, "SHORT_NAME=?", arrayOfString); } public Cursor selectDistrict(String paramString) { String[] arrayOfString = new String[2]; arrayOfString[0] = "3"; arrayOfString[1] = paramString; return select(this.mColumns, "TYPE=? AND PARENT_REGION like ?", arrayOfString); } public Cursor selectNameByCode(String paramString) { String[] arrayOfString = new String[1]; arrayOfString[0] = paramString; return select(this.mColumns, "REGION_CODE=?", arrayOfString); } }
114ch
trunk/src/com/besttone/search/sql/NativeDBHelper.java
Java
asf20
3,714
package com.besttone.search; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PoiResultData { public static List<Map<String, Object>> getData() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); return list; } }
114ch
trunk/src/com/besttone/search/PoiResultData.java
Java
asf20
321
package com.besttone.search; import java.util.ArrayList; import com.besttone.adapter.LetterListAdapter; import com.besttone.search.CityListBaseActivity.AutoCityAdapter; import com.besttone.search.model.City; import com.besttone.search.sql.NativeDBHelper; import com.besttone.search.util.Constants; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewFlipper; public abstract class CityListBaseActivity extends Activity implements AbsListView.OnScrollListener { private Context mContext; protected ArrayList<City> citylist = new ArrayList(); private Handler handler; protected ArrayAdapter<String> mAutoAdapter; protected EditText mAutoTextView; protected ArrayList<String> autoCitylist = new ArrayList<String>(); protected String[] autoArray; protected String[] mCityFirstLetter; private TextView mDialogText; protected int mHotCount = 0; protected Cursor mHotCursor; private String mLetter = ""; protected LetterListAdapter mListAdapter; protected ListView mListView; private RemoveWindow mRemoveWindow; private int mScroll; private boolean mShowing = false; private NativeDBHelper mDB; private WindowManager windowManager; protected AutoCityAdapter mAutoCityAdapter; protected ListView mAutoListView; private final TextWatcher textWatcher = new TextWatcher() { private int selectionEnd; private int selectionStart; private CharSequence temp; public void afterTextChanged(Editable paramEditable) { this.selectionStart = CityListBaseActivity.this.mAutoTextView .getSelectionStart(); this.selectionEnd = CityListBaseActivity.this.mAutoTextView .getSelectionEnd(); if (this.temp.length() > 25) { Toast.makeText(CityListBaseActivity.this, "temp 长度大于25", Toast.LENGTH_SHORT).show(); paramEditable.delete(this.selectionStart - (-25 + this.temp.length()), this.selectionEnd); int i = this.selectionStart; CityListBaseActivity.this.mAutoTextView.setText(paramEditable); CityListBaseActivity.this.mAutoTextView.setSelection(i); } //获取mAutoTextView结果 String str = temp.toString(); Cursor localCursor = null; String[] arrayParm = new String[2]; arrayParm[0] = "2"; arrayParm[1] = (str + "%"); autoCitylist = new ArrayList<String>(); String[] mColumns = {"FIRST_PY", "SHORT_NAME"}; // Log.d("selectCity", "search"); // Log.i("arrayParm[0]", "search"+arrayParm[0]); // Log.i("arrayParm[q]", "search"+arrayParm[1]); if(Constants.isAlphabet(str)) { localCursor =mDB.select(mColumns, "TYPE=? AND FIRST_PY like ?",arrayParm); } else { localCursor =mDB.select(mColumns, "TYPE=? AND SHORT_NAME like ?",arrayParm); } if (localCursor!=null && localCursor.getCount()>0) { localCursor.moveToFirst(); while (true) { if (localCursor.isAfterLast()) { localCursor.close(); break; } autoCitylist.add(localCursor.getString(0) + "," + localCursor.getString(1)); // Log.i("result", localCursor.getString(0) + "," + localCursor.getString(1)); localCursor.moveToNext(); } } autoArray = autoCitylist.toArray(new String[autoCitylist.size()]); // mAutoAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_dropdown_item_1line, autoArray); // mAutoTextView.setAdapter(mAutoAdapter); // for(int i=0;i<autoArray.length;i++) // Log.i("autoArray[i]", "result"+autoArray[i]); if(str.length()>0&&autoArray.length>0) { mAutoListView.setVisibility(View.VISIBLE); } else { mAutoListView.setVisibility(View.GONE); } mAutoCityAdapter.notifyDataSetChanged(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { this.temp = s; } public void onTextChanged(CharSequence s, int start, int count, int after) { } }; private void init() { this.mDialogText = ((TextView) ((LayoutInflater) getSystemService("layout_inflater")).inflate(R.layout.select_city_position_dialog, null)); this.mDialogText.setVisibility(4); this.mRemoveWindow = new RemoveWindow(); this.handler = new Handler(); this.windowManager = getWindowManager(); setAdapter(); this.mListView.setOnScrollListener(this); this.mListView.setFastScrollEnabled(true); initAutoData(); mAutoTextView = (EditText)this.findViewById(R.id.change_city_auto_text); // this.mAutoTextView.setAdapter(this.mAutoAdapter); // this.mAutoTextView.setThreshold(1); this.mAutoTextView.addTextChangedListener(this.textWatcher); mDB = NativeDBHelper.getInstance(this); } private void initFirstLetter() { setFirstletter(); initDBHelper(); addLocationCityFirstLetter(); addHotCityFirstLetter(); this.mHotCount = this.citylist.size(); addCityFirstLetter(); } private void removeWindow() { if (!this.mShowing) ; while (true) { this.mShowing = false; this.mDialogText.setVisibility(4); return; } } public abstract void addCityFirstLetter(); public abstract void addHotCityFirstLetter(); public abstract void addLocationCityFirstLetter(); public abstract void initAutoData(); public abstract void initDBHelper(); protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); requestWindowFeature(1); setTheContentView(); mContext = this.getApplicationContext(); initFirstLetter(); init(); setListViewOnItemClickListener(); setAutoCompassTextViewOnItemClickListener(); // mAutoTextView.setAdapter(mAutoCityAdapter); } public void onScroll(AbsListView paramAbsListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { this.mScroll = (1 + this.mScroll); if (this.mScroll >= 2) { while (true) { int i = firstVisibleItem - 1 + visibleItemCount / 2; String str = ((City) this.mListView.getAdapter().getItem(i)) .getFirstLetter(); if (str == null) continue; this.mShowing = true; this.mDialogText.setVisibility(0); this.mDialogText.setText(str); this.mLetter = str; this.handler.removeCallbacks(this.mRemoveWindow); this.handler.postDelayed(this.mRemoveWindow, 3000L); return; } } } public void onScrollStateChanged(AbsListView paramAbsListView, int paramInt) { } protected void onStart() { super.onStart(); WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams( -1, -1, 2, 24, -3); this.windowManager.addView(this.mDialogText, localLayoutParams); this.mScroll = 0; } protected void onStop() { super.onStop(); try { this.mScroll = 0; this.windowManager.removeView(this.mDialogText); return; } catch (Exception localException) { while (true) localException.printStackTrace(); } } public abstract void setAdapter(); public abstract void setAutoCompassTextViewOnItemClickListener(); public abstract void setFirstletter(); public abstract void setListViewOnItemClickListener(); public abstract void setTheContentView(); final class RemoveWindow implements Runnable { private RemoveWindow() { } public void run() { CityListBaseActivity.this.removeWindow(); } } public class AutoCityAdapter extends BaseAdapter { private LayoutInflater mInflater; public AutoCityAdapter(Context context) { this.mInflater = LayoutInflater.from(context); autoArray = new String[1]; } public int getCount() { return autoArray.length; } public Object getItem(int position) { return autoArray[position]; } public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub convertView = mInflater.inflate(R.layout.auto_city_item, null); Log.i("adapt", "getDropDownView"); String searchRecord = autoArray[position]; ((TextView) convertView.findViewById(R.id.auto_city_info)).setText(searchRecord); return convertView; } } }
114ch
trunk/src/com/besttone/search/CityListBaseActivity.java
Java
asf20
9,127
package com.besttone.search.dialog; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.DecimalFormat; import java.text.NumberFormat; import com.besttone.search.Client; import com.besttone.search.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.StatFs; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class ProgressBarDialog extends Dialog { private ProgressBar mProgress; private TextView mProgressNumber; private TextView mProgressPercent; public static final int M = 1024 * 1024; public static final int K = 1024; private double dMax; private double dProgress; private int middle = K; private int prev = 0; private Handler mViewUpdateHandler; private int fileSize; private int downLoadFileSize; private static final NumberFormat nf = NumberFormat.getPercentInstance(); private static final DecimalFormat df = new DecimalFormat("###.##"); private static final int msg_init = 0; private static final int msg_update = 1; private static final int msg_complete = 2; private static final int msg_error = -1; private String mUrl; private File fileOut; private String downloadPath; public ProgressBarDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { LayoutInflater inflater = LayoutInflater.from(getContext()); mViewUpdateHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (!Thread.currentThread().isInterrupted()) { // Log.i("msg what", String.valueOf(msg.what)); switch (msg.what) { case msg_init: // pbr.setMax(fileSize); mProgress.setMax(100); break; case msg_update: setDProgress((double) downLoadFileSize); break; case msg_complete: setTitle("文件下载完成"); break; case msg_error: String error = msg.getData().getString("更新失败"); setTitle(error); break; default: break; } } double precent = dProgress / dMax; if (prev != (int) (precent * 100)) { mProgress.setProgress((int) (precent * 100)); mProgressNumber.setText(df.format(dProgress) + "/" + df.format(dMax) + (middle == K ? "K" : "M")); mProgressPercent.setText(nf.format(precent)); prev = (int) (precent * 100); } } }; View view = inflater.inflate(R.layout.dialog_progress_bar, null); mProgress = (ProgressBar) view.findViewById(R.id.progress); mProgress.setMax(100); mProgressNumber = (TextView) view.findViewById(R.id.progress_number); mProgressPercent = (TextView) view.findViewById(R.id.progress_percent); setContentView(view); onProgressChanged(); super.onCreate(savedInstanceState); } private void onProgressChanged() { mViewUpdateHandler.sendEmptyMessage(0); } public double getDMax() { return dMax; } public void setDMax(double max) { if (max > M) { middle = M; } else { middle = K; } dMax = max / middle; } public double getDProgress() { return dProgress; } public void setDProgress(double progress) { dProgress = progress / middle; onProgressChanged(); } // String downloadPath = Environment.getExternalStorageDirectory().getPath() // + "/download_cache"; public void downLoadFile(final String httpUrl) { this.mUrl = httpUrl; File sdDir = null; boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在 if (sdCardExist) { sdDir = Environment.getExternalStorageDirectory();// 获取跟目录 if (getAvailableExternalMemorySize() < 50000000) { Toast.makeText(Client.getContext(), "存储空间不足", Toast.LENGTH_SHORT).show(); dismiss(); return; } } else { Toast.makeText(Client.getContext(), "SD卡不存在", Toast.LENGTH_SHORT).show(); dismiss(); return; } downloadPath = sdDir + "/114update"; Client.getThreadPoolForDownload().execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub URL url = null; try { url = new URL(mUrl); String fileName = mUrl.substring(mUrl.lastIndexOf("/")); // String downloadPath = sdDir+"/114update"; File tmpFile = new File(downloadPath); if (!tmpFile.exists()) { tmpFile.mkdir(); } fileOut = new File(downloadPath + fileName); // URL url = new URL(appurl); // URL url = new URL(mUrl); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); InputStream in; in = con.getInputStream(); fileSize = con.getContentLength(); setDMax((double) fileSize); FileOutputStream out = new FileOutputStream(fileOut); byte[] bytes = new byte[1024]; downLoadFileSize = 0; setDProgress((double) downLoadFileSize); sendMsg(msg_init); int c; while ((c = in.read(bytes)) != -1) { out.write(bytes, 0, c); downLoadFileSize += c; sendMsg(msg_update);// 更新进度条 } in.close(); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); sendMsg(msg_error);// error } sendMsg(msg_complete);// 下载完成 Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub dismiss(); installApk(fileOut); exitApp(); } }); } }); } private void sendMsg(int flag) { Message msg = new Message(); msg.what = flag; mViewUpdateHandler.sendMessage(msg); } private void installApk(File file) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(Intent.ACTION_VIEW); String type = "application/vnd.android.package-archive"; intent.setDataAndType(Uri.fromFile(file), type); Client.getContext().startActivity(intent); Log.e("success", "the end"); } // 彻底关闭程序 protected void exitApp() { Client.release(); System.exit(0); // 或者下面这种方式 // android.os.Process.killProcess(android.os.Process.myPid()); } public static long getAvailableExternalMemorySize() { if (externalMemoryAvailable()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } else { return msg_error; } } public static boolean externalMemoryAvailable() { return android.os.Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED); } }
114ch
trunk/src/com/besttone/search/dialog/ProgressBarDialog.java
Java
asf20
7,572
package com.besttone.search; import java.io.File; import java.io.IOException; import java.util.List; import com.besttone.http.UpdateRequest; import com.besttone.http.UpdateRequest.UpdateListener; import com.besttone.search.Client.GetLocationAdressListener; import com.besttone.search.dialog.ProgressBarDialog; import com.besttone.search.model.City; import com.besttone.search.model.PhoneInfo; import com.besttone.search.sql.NativeDBHelper; import com.besttone.search.util.CellInfoManager; import com.besttone.search.util.CellLocationManager; import com.besttone.search.util.Constants; import com.besttone.search.util.LogUtils; import com.besttone.search.util.PhoneUtil; import com.besttone.search.util.SharedUtils; import com.besttone.search.util.StringUtils; import com.besttone.search.util.WifiInfoManager; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; //import android.location.Address; //import android.location.Geocoder; import android.location.Address; import android.net.ConnectivityManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.amap.cn.apis.util.ConstantsAmap; import com.amap.mapapi.core.AMapException; import com.amap.mapapi.core.GeoPoint; import com.amap.mapapi.geocoder.Geocoder; import com.amap.mapapi.map.MapActivity; import com.amap.mapapi.map.MapView; public class SplashActivity extends Activity { private final int TIME_UP = 1; protected Context mContext; protected UpdateRequest r; private Handler handler = new Handler() { public void handleMessage(Message msg) { if (msg.what == TIME_UP) { Intent intent = new Intent(); intent.setClass(SplashActivity.this, MainActivity.class); startActivity(intent); overridePendingTransition(R.anim.splash_screen_fade, R.anim.splash_screen_hold); SplashActivity.this.finish(); } } }; public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.splash_screen_view); initApp(); initPhoneInfo(); Client.initWithContext(this); initCity(); // progDialog=new ProgressDialog(this); // // detectUpdate(); new Thread() { public void run() { try { Thread.sleep(500); } catch (Exception e) { } Message msg = new Message(); msg.what = TIME_UP; handler.sendMessage(msg); } }.start(); } private void initApp() { initNativeDB(); } private void initNativeDB() { SharedPreferences localSharedPreferences = getSharedPreferences( "NativeDB", 0); if (1 > localSharedPreferences.getInt("Version", 0)) { Constants.copyNativeDB(this, getResources().openRawResource(R.raw.native_database)); localSharedPreferences.edit().putInt("Version", 1).commit(); } Constants.copyNativeDB(this, getResources().openRawResource(R.raw.native_database)); localSharedPreferences.edit().putInt("Version", 1).commit(); } private boolean isUnSelectedCity() { if ((!SharedUtils.isFirstSelectedCityComplete(this.mContext)) || (StringUtils.isEmpty(SharedUtils .getCurrentCityName(this.mContext))) || (StringUtils.isEmpty(SharedUtils .getCurrentCityCode(this.mContext))) || (StringUtils.isEmpty(SharedUtils .getCurrentProvinceCode(this.mContext)))) { return true; } return false; } private void initCity() { // SharedUtils.setCurrentCity(Client.getContext(), SharedUtils.selectCity()); City localCity = new City(); localCity.setCityName("上海"); localCity.setCityCode("310000"); localCity.setSimplifyCode("31"); localCity.setCityId("75"); localCity.setProvinceCode("310000"); if(SharedUtils.getLastLocationCity()!=null) localCity=SharedUtils.getLastLocationCity(); SharedUtils.setCurrentCity(this, localCity); } public void initPhoneInfo() { TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE); String imei = tm.getDeviceId(); //IMEI String provider = tm.getNetworkOperatorName(); //运营商 String imsi = tm.getSubscriberId(); //IMSI PhoneUtil util = new PhoneUtil(); PhoneInfo info = null; try { if(NetWorkStatus()) { //info = util.getPhoneNoByIMSI(imsi); } } catch (Exception e) { e.printStackTrace(); } if(info==null) info = new PhoneInfo(); info.setImei(imei); info.setImsi(imsi); info.setProvider(provider); SharedUtils.setCurrentPhoneInfo(this, info); } private boolean NetWorkStatus() { boolean netSataus = false; ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); cwjManager.getActiveNetworkInfo(); if (cwjManager.getActiveNetworkInfo() != null) { netSataus = cwjManager.getActiveNetworkInfo().isAvailable(); } // if (netSataus) { // Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络").setMessage("是否对网络进行设置?"); // b.setPositiveButton("是", new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int whichButton) { // Intent mIntent = new Intent("/"); // ComponentName comp = new ComponentName("com.android.settings", // "com.android.settings.WirelessSettings"); // mIntent.setComponent(comp); // mIntent.setAction("android.intent.action.VIEW"); // startActivityForResult(mIntent,0); // 如果在设置完成后需要再次进行操作,可以重写操作代码,在这里不再重写 // } // }).setNeutralButton("否", new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int whichButton) { // dialog.cancel(); // } // }).show(); // } return netSataus; } private void detectUpdate() { r = new UpdateRequest(); r.setListener(new UpdateListener() { @Override public void onUpdateNoNeed(String msg) { gotoLogin(); } public void onUpdateMust(final String msg, final String url) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub AlertDialog.Builder b = new AlertDialog.Builder(SplashActivity.this); b.setTitle("程序必须升级才能继续"); b.setMessage(msg+"\r\n"+url); b.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); System.gc(); } }); b.setPositiveButton("升级",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoUpdate(url); } }); b.setCancelable(false); b.show(); } }); } public void onUpdateError(short code, Exception e) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub AlertDialog.Builder b = new AlertDialog.Builder(SplashActivity.this); b.setTitle("升级验证失败"); b.setMessage("请检查网络..."); b.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); System.gc(); } }); b.setCancelable(false); b.show(); } }); } public void onUpdateAvaiable(final String msg, final String url) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub AlertDialog.Builder b = new AlertDialog.Builder(SplashActivity.this); b.setTitle(R.string.update_title); b.setMessage(msg+"\r\n"+url); b.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoLogin(); } }); b.setPositiveButton("升级",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoUpdate(url); } }); b.setCancelable(false); b.show(); } }); } }); if (Client.decetNetworkOn()) { // Log.d("check","on"); r.checkUpdate(); } else { // Log.d("check","off"); gotoLogin(); Toast.makeText(SplashActivity.this, "网络异常,没有可用网络", Toast.LENGTH_SHORT).show(); } } private void gotoLogin() { getLoacation(); } private void gotoUpdate(String url) { if (TextUtils.isEmpty(url)) { Toast.makeText(this, "升级的地址有误", Toast.LENGTH_SHORT).show(); finish(); System.gc(); return; } // url = url.toLowerCase(); if (url.startsWith("www")) { url = "http://" + url; } if (url.startsWith("http")) { try { // Uri u = Uri.parse(url); ProgressBarDialog pbd=new ProgressBarDialog(SplashActivity.this); pbd.setTitle("下载中"); pbd.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // TODO Auto-generated method stub gotoLogin(); } }); pbd.show(); pbd.downLoadFile(url); // Intent i = new Intent( Intent.ACTION_VIEW, u ); // startActivity( i ); // finish(); System.gc(); } catch(Exception e) { e.printStackTrace(); } } } private ProgressDialog progDialog = null; private Geocoder coder; private String addressName; private double mLat = 31.130704; private double mLon = 121.5334131; public void getLoacation(){ Client.getInstance().setmLoactionDlistener(new GetLocationAdressListener() { @Override public void onGetLocationAdress() { // TODO Auto-generated method stub Client.getInstance().disableMyLocation(); initCity(); new Thread() { public void run() { try { Thread.sleep(500); } catch (Exception e) { } Message msg = new Message(); msg.what = TIME_UP; handler.sendMessage(msg); } }.start(); } @Override public void onFialedGetLocationAdress() { // TODO Auto-generated method stub Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub showExitAlert(); } }); } }); Client.getInstance().enableMyLocation(); // Client.getInstance().tryGetAddress(30.783298, 120.376826); // CellInfoManager cellManager = new CellInfoManager(this) // // WifiInfoManager wifiManager = new WifiInfoManager(this); // // Log.d("location","init"); // // coder = new Geocoder(Client.getContext()); // // CellLocationManager locationManager = new CellLocationManager(this, cellManager, wifiManager) { // // @Override // // public void onLocationChanged() { // // Log.d("location",this.latitude() + "-" + this.longitude()); // // Client.getInstance().getAddress(this.latitude(),this.longitude()); // // this.stop(); // // } // // }; // // locationManager.start(); } private void showExitAlert() { new AlertDialog.Builder(this) .setTitle(R.string.prompt) .setMessage(R.string.quit_without_connection) .setCancelable(false) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { exitApp(); } }).show(); } //彻底关闭程序 protected void exitApp() { super.onDestroy(); Client.release(); System.exit(0); // 或者下面这种方式 // android.os.Process.killProcess(android.os.Process.myPid()); } }
114ch
trunk/src/com/besttone/search/SplashActivity.java
Java
asf20
12,931
package com.besttone.search; import java.util.List; public interface ServerListener { void serverDataArrived(List list, boolean isEnd); }
114ch
trunk/src/com/besttone/search/ServerListener.java
Java
asf20
150
package com.besttone.search; import com.besttone.app.SuggestionProvider; import com.besttone.http.UpdateRequest; import com.besttone.http.UpdateRequest.UpdateListener; import com.besttone.search.Client.GetLocationAdressListener; import com.besttone.search.R.color; import com.besttone.search.dialog.ProgressBarDialog; import com.besttone.search.model.City; import com.besttone.search.sql.NativeDBHelper; import com.besttone.search.util.LogUtils; import com.besttone.search.util.SharedUtils; import com.besttone.widget.scroll.MyScrollLayout; import com.besttone.widget.scroll.OnViewChangeListener; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.provider.SearchRecentSuggestions; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private GridView grid; private DisplayMetrics localDisplayMetrics; private View mainView; private View swithViewContainer; private Button btn_city_search; private Button mSearchBtn; private SearchRecentSuggestions suggestions; private City lastLocationCity; private MyScrollLayout mScrollLayout; private ImageView[] mImageViews; private int mViewCount; private int mCurSel; private final boolean bMultiTag = false; public void onCreate(Bundle bundle) { super.onCreate(bundle); requestWindowFeature(Window.FEATURE_NO_TITLE); if(bMultiTag) { swithViewContainer = this.getLayoutInflater().inflate(R.layout.switch_view, null); setContentView(R.layout.switch_view); initChildView(); } else { mainView = this.getLayoutInflater().inflate(R.layout.main, null); setContentView(mainView); initMainView(); } detectUpdate(); } private void initMainView() { btn_city_search = (Button) mainView.findViewById(R.id.btn_city); btn_city_search.setOnClickListener(searchCityListner); String str = null; String cityName = (String) this.btn_city_search.getText(); SharedPreferences sharedPreferences = this.getSharedPreferences("Location_City_Data", 0); str=sharedPreferences.getString("Location_City", "上海"); Log.d("main", "new city:" + str); Log.d("main", "old city:" + cityName); this.btn_city_search.setText(str); mSearchBtn = ((Button)mainView.findViewById(R.id.start_search)); mSearchBtn.setOnClickListener(searchHistroyListner); localDisplayMetrics = getResources().getDisplayMetrics(); suggestions = new SearchRecentSuggestions(this, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE); grid = (GridView)mainView.findViewById(R.id.my_grid); ListAdapter adapter = new GridAdapter(this); grid.setAdapter(adapter); grid.setOnItemClickListener(mOnClickListener); } //------------------------------ 多tag切换 --------------------------------- private void initChildView() { LinearLayout linearLayout = (LinearLayout) findViewById(R.id.llayout); mScrollLayout = (MyScrollLayout)findViewById(R.id.mScrollLayout); mainView = this.getLayoutInflater().inflate(R.layout.main, mScrollLayout); initMainView(); // mScrollLayout.addView(mainView); View child = new ImageView(this); mScrollLayout.addView(child); mViewCount = mScrollLayout.getChildCount(); mImageViews = new ImageView[mViewCount]; for (int i = 0; i < mViewCount; i++) { mImageViews[i] = (ImageView) linearLayout.getChildAt(i); mImageViews[i].setEnabled(true); mImageViews[i].setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub int pos = (Integer) (v.getTag()); setCurPoint(pos); mScrollLayout.snapToScreen(pos); } }); mImageViews[i].setTag(i); } mCurSel = 0; mImageViews[mCurSel].setEnabled(false); mScrollLayout.SetOnViewChangeListener(new OnViewChangeListener() { @Override public void OnViewChange(int view) { // TODO Auto-generated method stub setCurPoint(view); } }); } private void setCurPoint(int index) { if (index < 0 || index > mViewCount - 1 || mCurSel == index) { return; } mImageViews[mCurSel].setEnabled(true); // if(index!=mViewCount - 1) // mImageViews[index].setEnabled(true); // else mImageViews[index].setEnabled(false); mCurSel = index; } //----------------------------------------------------------------- private void updateLocaton() { Client.getInstance().setmLoactionDlistener(new GetLocationAdressListener() { @Override public void onGetLocationAdress() { // TODO Auto-generated method stub try { String curCityName=SharedUtils.getCurrentCityName(Client.getContext()); lastLocationCity=SharedUtils.selectCity(); String lastLocationCityName=lastLocationCity.getCityName(); if(!curCityName.equals("")&&!curCityName.equals(lastLocationCityName)) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if(Client.getInstance().bChangeCity) openAlertChangeCityDialog(); } }); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onFialedGetLocationAdress() { // TODO Auto-generated method stub Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub Toast.makeText(Client.getContext(), "请检查网络连接!", Toast.LENGTH_SHORT); } }); } }); Client.getInstance().enableMyLocation(); // Thread t=new Thread(new Runnable() // { // // @Override // public void run() // { // // TODO Auto-generated method stub // do // { // try // { // Thread.sleep(60000); // } // catch (InterruptedException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // } // Client.getInstance().enableMyLocation(); // } // while (true); // } // }); // t.start(); } private void openAlertChangeCityDialog() { Client.getInstance().disableMyLocation(); String str=getString(R.string.change_city_by_location).replace("[]", SharedUtils.getLastLocationCity().getCityName()); new AlertDialog.Builder(MainActivity.this).setTitle(R.string.prompt) .setMessage(str) .setCancelable(false) .setPositiveButton(R.string.switch_text, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialoginterface, int i) { SharedUtils.setCurrentCity(Client.getContext(), lastLocationCity); btn_city_search.setText(lastLocationCity.getCityName()); // Client.getInstance().enableMyLocation(); } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialoginterface, int i) { Client.getInstance().bChangeCity = false; // Client.getInstance().enableMyLocation(); } }).show(); } private Button.OnClickListener searchHistroyListner = new Button.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(); intent.setClass(MainActivity.this, SearchActivity.class); startActivity(intent); } }; private Button.OnClickListener searchCityListner = new Button.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(); intent.setClass(MainActivity.this, SelectCityActivity.class); intent.putExtra("SelectCityName", btn_city_search.getText().toString()); startActivityForResult(intent, 100); } }; protected void onActivityResult(int requestCode, int resultCode, Intent data) { LogUtils.i("resultCode:" + resultCode + ", requestCode:" + requestCode); String str = null; String cityName = (String) this.btn_city_search.getText(); if (resultCode == RESULT_OK) { str = data.getStringExtra("cityName"); LogUtils.d(LogUtils.LOG_TAG, "new city:" + str); LogUtils.d(LogUtils.LOG_TAG, "old city:" + cityName); super.onActivityResult(requestCode, resultCode, data); this.btn_city_search.setText(str); } } private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position,long id) { TextView text = (TextView)v.findViewById(R.id.activity_name); String keyword = text.getText().toString(); Intent intent = new Intent(); if (keyword != null) { if ("更多".equals(keyword)) { intent.setClass(MainActivity.this, MoreKeywordActivity.class); startActivity(intent); } else { intent.setClass(MainActivity.this, SearchResultActivity.class); Bundle bundle = new Bundle(); bundle.putString("keyword", keyword); intent.putExtras(bundle); suggestions.saveRecentQuery(keyword, null); startActivity(intent); } } } }; public class GridAdapter extends BaseAdapter { private LayoutInflater inflater; public GridAdapter(Context context) { inflater = LayoutInflater.from(context); } public final int getCount() { return 6; } public final Object getItem(int paramInt) { return null; } public final long getItemId(int paramInt) { return paramInt; } public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) { paramView = inflater.inflate(R.layout.activity_label_item, null); TextView text = (TextView)paramView.findViewById(R.id.activity_name); text.setTextSize(15); text.setTextColor(color.text_color_grey); switch(paramInt) { case 0: { text.setText("KTV"); Drawable draw = getResources().getDrawable(R.drawable.ktv); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 1: { text.setText("宾馆"); Drawable draw = getResources().getDrawable(R.drawable.hotel); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 2: { text.setText("加油站"); Drawable draw = getResources().getDrawable(R.drawable.gas); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 3: { text.setText("川菜"); Drawable draw = getResources().getDrawable(R.drawable.chuan); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 4: { text.setText("快递"); Drawable draw = getResources().getDrawable(R.drawable.kuaidi); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } case 5: { text.setText("更多"); Drawable draw = getResources().getDrawable(R.drawable.more); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); text.setCompoundDrawables(null, draw, null, null); break; } // case 6: // { // text.setText("最近浏览"); // Drawable draw = getResources().getDrawable(R.drawable.home_button_history); // draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); // text.setCompoundDrawables(null, draw, null, null); // break; // } // // case 7: // { // text.setText("个人中心"); // Drawable draw = getResources().getDrawable(R.drawable.home_button_myzone); // draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); // text.setCompoundDrawables(null, draw, null, null); // break; // } // case 8: // { // text.setText("更多"); // Drawable draw = getResources().getDrawable(R.drawable.home_button_more); // draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); // text.setCompoundDrawables(null, draw, null, null); // break; // } } paramView.setMinimumHeight((int)(96.0F * localDisplayMetrics.density)); paramView.setMinimumWidth(((-12 + localDisplayMetrics.widthPixels) / 3)); return paramView; } } protected static final int MENU_ABOUT = Menu.FIRST; protected static final int MENU_Quit = Menu.FIRST+1; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_ABOUT, 0, " 关于 ..."); menu.add(0, MENU_Quit, 0, " 结束 "); return true; } public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case MENU_ABOUT: openOptionsDialog(); break; case MENU_Quit: showExitAlert(); break; } return true; } private void openOptionsDialog() { new AlertDialog.Builder(MainActivity.this) .setTitle(R.string.about_title) .setMessage(R.string.about_msg) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialoginterface, int i) {} }) .setNegativeButton(R.string.homepage_label, new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialoginterface, int i){ //go to url Uri uri = Uri.parse(getString(R.string.homepage_uri)); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } }) .show(); } public boolean onKeyDown(int keyCode, KeyEvent event) { // 按下键盘上返回按钮 if(keyCode == KeyEvent.KEYCODE_BACK ){ showExitAlert(); return true; } else { return super.onKeyDown(keyCode, event); } } private void showExitAlert() { new AlertDialog.Builder(this) .setTitle(R.string.prompt) .setMessage(R.string.quit_desc) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {} }) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { exitApp(); } }).show(); } //彻底关闭程序 protected void exitApp() { super.onDestroy(); Client.release(); System.exit(0); // 或者下面这种方式 // android.os.Process.killProcess(android.os.Process.myPid()); } //检测更新 protected UpdateRequest r; private void detectUpdate() { r = new UpdateRequest(); r.setListener(new UpdateListener() { @Override public void onUpdateNoNeed(String msg) { gotoLogin(); } public void onUpdateMust(final String msg, final String url) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this); b.setTitle("程序必须升级才能继续"); b.setMessage(msg+"\r\n"+url); b.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); System.gc(); } }); b.setPositiveButton("升级",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoUpdate(url); } }); b.setCancelable(false); b.show(); } }); } public void onUpdateError(short code, Exception e) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this); b.setTitle("升级验证失败"); b.setMessage("请检查网络..."); b.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); System.gc(); } }); b.setCancelable(false); b.show(); } }); } public void onUpdateAvaiable(final String msg, final String url) { Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this); b.setTitle(R.string.update_title); b.setMessage(msg+"\r\n"+url); b.setPositiveButton("现在升级",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoUpdate(url); } }); b.setNegativeButton("以后再说", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoLogin(); } }); b.setCancelable(false); b.show(); } }); } }); if (Client.decetNetworkOn()) { // Log.d("check","on"); r.checkUpdate(); } else { // Log.d("check","off"); gotoLogin(); Toast.makeText(MainActivity.this, "网络异常,没有可用网络", Toast.LENGTH_SHORT).show(); } } private void gotoLogin() { updateLocaton(); // getLoacation(); } private void gotoUpdate(String url) { if (TextUtils.isEmpty(url)) { Toast.makeText(this, "升级的地址有误", Toast.LENGTH_SHORT).show(); finish(); System.gc(); return; } // url = url.toLowerCase(); if (url.startsWith("www")) { url = "http://" + url; } if (url.startsWith("http")) { try { // Uri u = Uri.parse(url); ProgressBarDialog pbd=new ProgressBarDialog(MainActivity.this); pbd.setTitle("下载中"); pbd.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // TODO Auto-generated method stub gotoLogin(); } }); pbd.show(); pbd.downLoadFile(url); // Intent i = new Intent( Intent.ACTION_VIEW, u ); // startActivity( i ); // finish(); System.gc(); } catch(Exception e) { e.printStackTrace(); } } } }
114ch
trunk/src/com/besttone/search/MainActivity.java
Java
asf20
19,546
package com.besttone.search; import java.util.ArrayList; import java.util.List; import com.besttone.widget.AlphabetBar; import android.R.integer; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.besttone.adapter.CityListAdapter; import com.besttone.search.model.City; import com.besttone.search.sql.NativeDBHelper; import com.besttone.search.util.LogUtils; import com.besttone.search.util.SharedUtils; import com.besttone.search.util.SharedUtils.LocationCityListener; public class SelectCityActivity extends CityListBaseActivity { private ImageButton btn_back; private Context mContext; private NativeDBHelper mDB; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); //this.imm = ((InputMethodManager)getSystemService("input_method")); btn_back = (ImageButton) findViewById(R.id.left_title_button); btn_back.setOnClickListener(backListner); } private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() { public void onClick(View v) { finish(); } }; private void selectComplete(City paramCity) { String simplifyCode = ""; if(paramCity!=null && paramCity.getCityCode()!=null) { simplifyCode = paramCity.getCityCode(); if(simplifyCode.endsWith("00")) { simplifyCode = simplifyCode.substring(0, simplifyCode.length()-2); } if(simplifyCode.endsWith("00")) { simplifyCode = simplifyCode.substring(0, simplifyCode.length()-2); } } paramCity.setSimplifyCode(simplifyCode); SharedUtils.setCurrentCity(this.mContext, paramCity); Intent localIntent = getIntent(); localIntent.putExtra("cityName", paramCity.getCityName()); setResult(RESULT_OK, localIntent); finish(); } @Override public void addCityFirstLetter() { if (this.mCityFirstLetter.length <= 0) return; String str = null; Cursor localCursor = null; for (int i = 1; i < this.mCityFirstLetter.length; i++) { str = this.mCityFirstLetter[i]; String[] arrayParm = new String[2]; arrayParm[0] = "2"; arrayParm[1] = (str + "%"); localCursor = this.mDB.select(null, "TYPE=? AND FIRST_PY like ?", arrayParm); if (localCursor != null) if (localCursor.moveToNext()) { City localCity1 = new City(); localCity1.setCityName("-1"); localCity1.setFirstLetter(str); this.citylist.add(localCity1); } while (true) { if (localCursor.isAfterLast()) { localCursor.close(); break; } City localCity2 = new City(); localCity2.setBusinessFlag(localCursor.getString(12)); localCity2.setCityCode(localCursor.getString(1)); localCity2.setCityId(localCursor.getString(0)); localCity2.setCityName(localCursor.getString(5)); localCity2.setFirstPy(localCursor.getString(6)); localCity2.setAreaCode(localCursor.getString(9)); localCity2.setProvinceCode(localCursor.getString(2)); localCity2.setFirstLetter(str); this.citylist.add(localCity2); localCursor.moveToNext(); } } } public void addHotCityFirstLetter() { if (this.mCityFirstLetter.length <= 0) return; String str; do { str = this.mCityFirstLetter[1]; } while (this.mHotCursor == null); if (this.mHotCursor.moveToNext()) { City localCity1 = new City(); localCity1.setCityName("-1"); localCity1.setFirstLetter(str); this.citylist.add(localCity1); } while (true) { if (this.mHotCursor.isAfterLast()) { this.mHotCursor.close(); break; } City localCity2 = new City(); localCity2.setBusinessFlag(this.mHotCursor.getString(12)); localCity2.setCityCode(this.mHotCursor.getString(1)); localCity2.setCityId(this.mHotCursor.getString(0)); localCity2.setCityName(this.mHotCursor.getString(5)); localCity2.setFirstPy(this.mHotCursor.getString(6)); localCity2.setAreaCode(this.mHotCursor.getString(9)); localCity2.setProvinceCode(this.mHotCursor.getString(2)); localCity2.setFirstLetter(str); this.citylist.add(localCity2); this.mHotCursor.moveToNext(); } } public void addLocationCityFirstLetter() { if (this.mCityFirstLetter.length <= 0) return; String str; str = this.mCityFirstLetter[0]; City localCity1 = new City(); localCity1.setCityName("-1"); localCity1.setFirstLetter(str); this.citylist.add(localCity1); City localCity2=null; localCity2=SharedUtils.getLastLocationCity(); // Log.d("initLocationCity","="+(localCity2==null)); // Log.d("initLocationCity","="+(localCity2.getCityName())); if(localCity2==null) { localCity2=new City(); localCity2.setCityName(getString(R.string.locating)); } localCity2.setFirstLetter(str); this.citylist.add(localCity2); } public void initAutoData() { ArrayList localArrayList = new ArrayList(); for (int i = this.mHotCount;; i++) { if (i >= this.citylist.size()) { this.mAutoAdapter = new ArrayAdapter(this, R.id.selected_item, R.id.city_info, localArrayList); return; } City localCity = (City) this.citylist.get(i); if ((localCity.getFirstPy() == null) || (localCity.getCityName() == null)) continue; localArrayList.add(localCity.getCityName()); localArrayList.add(localCity.getFirstPy() + "," + localCity.getCityName()); } } public void initDBHelper() { this.mAutoTextView = ((EditText) findViewById(R.id.change_city_auto_text)); this.mDB = NativeDBHelper.getInstance(this); this.mHotCursor = this.mDB.select(null, "IS_FREQUENT = '1' ORDER BY CAST(SORT_VALUE AS INTEGER)", null); } public void setAdapter() { this.mListView = ((ListView) findViewById(R.id.city_list)); this.mListAdapter = new CityListAdapter(this, this.citylist); this.mListView.setAdapter(this.mListAdapter); SharedUtils.setmLocationCityListener(new LocationCityListener() { @Override public void onLocationCityChange() { // TODO Auto-generated method stub Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub // Log.d("setAdapter","onLocationCityChange"); citylist.set(1, SharedUtils.getLastLocationCity()); mListAdapter.setmCitylist(citylist); mListAdapter.notifyDataSetChanged(); } }); } }); this.mAutoListView = ((ListView) findViewById(R.id.auto_city_list)); this.mAutoCityAdapter = new AutoCityAdapter(this); this.mAutoListView.setAdapter(this.mAutoCityAdapter); this.mAutoListView.setVisibility(View.GONE); } public void setAutoCompassTextViewOnItemClickListener() { mAutoListView.setOnItemClickListener(cityAutoTvOnClickListener); // this.mAutoTextView.setOnItemClickListener(cityAutoTvOnClickListener); } public void setFirstletter() { this.mCityFirstLetter = getResources().getStringArray( R.array.city_first_letter); } public void setListViewOnItemClickListener() { this.mListView.setOnItemClickListener(cityLvOnClickListener); } public void setTheContentView() { requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.select_city); } private AdapterView.OnItemClickListener cityLvOnClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { ListView listView = (ListView) parent; City localCity = (City) listView.getItemAtPosition(position); if(localCity.getCityName().equals(getString(R.string.locating))) return; if (!"-1".equals(localCity.getCityName())) { // Toast.makeText(SelectCityActivity.this, // "你选择的城市是" + localCity.getCityName(), Toast.LENGTH_SHORT) // .show(); selectComplete(localCity); } } }; private AdapterView.OnItemClickListener cityAutoTvOnClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { String str1 = (String) mAutoCityAdapter.getItem(position); if (str1.contains(",")) { for (String str2 = str1.split(",")[1];; str2 = str1) { String[] arrayOfString = new String[2]; arrayOfString[0] = "2"; arrayOfString[1] = str2.trim(); Cursor localCursor = mDB.select(null, "TYPE=? AND SHORT_NAME=?", arrayOfString); if (localCursor.moveToFirst()) { City localCity = new City(); localCity.setAreaCode(localCursor.getString(9)); localCity.setCityCode(localCursor.getString(1)); localCity.setCityId(localCursor.getString(0)); localCity.setCityName(localCursor.getString(5)); localCity.setProvinceCode(localCursor.getString(2)); selectComplete(localCity); } return; } } } }; protected void onPause() { super.onPause(); //this.imm.hideSoftInputFromInputMethod(this.mAutoTextView.getWindowToken(), 0); } protected void onResume() { super.onResume(); //this.imm.hideSoftInputFromInputMethod(this.mAutoTextView.getWindowToken(), 0); } public void onScrollStateChanged(AbsListView paramAbsListView, int paramInt) { } }
114ch
trunk/src/com/besttone/search/SelectCityActivity.java
Java
asf20
9,815
package com.besttone.search; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.SearchRecentSuggestions; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.iflytek.speech.*; import com.iflytek.ui.RecognizerDialog; import com.iflytek.ui.RecognizerDialogListener; import com.besttone.app.SuggestionProvider; import com.besttone.http.WebServiceHelper; import com.besttone.http.WebServiceHelper.WebServiceListener; import com.besttone.search.util.SharedUtils; import com.besttone.search.util.StringUtils; import com.besttone.widget.EditSearchBar; import com.besttone.widget.EditSearchBar.OnKeywordChangeListner; import java.util.ArrayList; import java.util.List; public class SearchActivity extends Activity implements EditSearchBar.OnKeywordChangeListner{ private View view; private ImageButton btn_back; private ListView histroyListView; private EditText field_keyword; private Button mSearchBtn; private ImageButton mClearBtn; private EditSearchBar editSearchBar; private HistoryAdapter historyAdapter; private ArrayList<String> historyData = new ArrayList<String>(); private ArrayList<String> keywordList = new ArrayList<String>(); private ArrayList<String> keywordCountList = new ArrayList<String>(); private SearchRecentSuggestions suggestions; private Handler mhandler=new Handler(); private ImageButton mMicBtn; private RecognizerDialog recognizerDialog = null; private String grammar = null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); view = this.getLayoutInflater().inflate(R.layout.search_histroy, null); setContentView(view); suggestions = new SearchRecentSuggestions(this, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE); histroyListView = (ListView) findViewById(R.id.search_histroy); historyAdapter = new HistoryAdapter(this); histroyListView.setAdapter(historyAdapter); histroyListView.setOnItemClickListener(mOnClickListener); field_keyword = (EditText) findViewById(R.id.search_edit); mSearchBtn = (Button) findViewById(R.id.begin_search); mSearchBtn.setOnClickListener(searchListner); // mClearBtn = (ImageButton) findViewById(R.id.search_clear); // mClearBtn.setOnClickListener(clearListner); mMicBtn = (ImageButton) findViewById(R.id.btn_mic); mMicBtn.setOnClickListener(micListner); grammar = Client.readAbnfFile(); recognizerDialog = new RecognizerDialog(this,"appid="+Client.getInstance().iflytech_APP_ID); btn_back = (ImageButton) findViewById(R.id.left_title_button); btn_back.setOnClickListener(backListner); editSearchBar = (EditSearchBar)findViewById(R.id.search_bar); editSearchBar.setOnKeywordChangeListner(this); } private ImageButton.OnClickListener micListner = new ImageButton.OnClickListener() { public void onClick(View v) { EditText tmsg = (EditText)findViewById(R.id.search_edit); // tmsg.setText(grammar); recognizerDialog.setListener(mRecoListener); recognizerDialog.setEngine(null, "grammar_type=abnf", grammar); recognizerDialog.show(); } }; /** * 识别监听回调 */ private RecognizerDialogListener mRecoListener = new RecognizerDialogListener() { @Override public void onResults(ArrayList<RecognizerResult> results,boolean isLast) { String text = ""; for(int i = 0; i < results.size(); i++) { RecognizerResult result = results.get(i); text += result.text + " confidence=" + result.confidence + "\n"; } EditText tmsg = (EditText)findViewById(R.id.search_edit); tmsg.setText(text); tmsg.setSelection(tmsg.getText().length()); } @Override public void onEnd(SpeechError error) { } }; private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() { public void onClick(View v) { finish(); } }; private ImageButton.OnClickListener clearListner = new ImageButton.OnClickListener() { public void onClick(View v) { mClearBtn.setVisibility(View.GONE); field_keyword.setHint(R.string.search_hint); } }; private Button.OnClickListener searchListner = new Button.OnClickListener() { public void onClick(View v) { if(NetWorkStatus()) { String keyword = field_keyword.getText().toString(); if(keyword!=null && !"".equals(keyword)) { String simplifyCode = SharedUtils.getCurrentSimplifyCode(SearchActivity.this); Log.v("simplifyCode", simplifyCode); Intent intent = new Intent(); intent.setClass(SearchActivity.this, SearchResultActivity.class); Bundle bundle = new Bundle(); bundle.putString("simplifyCode", simplifyCode); bundle.putString("keyword", keyword); intent.putExtras(bundle); suggestions.saveRecentQuery(keyword, null); finish(); startActivity(intent); } else { Toast.makeText(SearchActivity.this, "搜索关键词为空", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(SearchActivity.this, "网络异常,没有可用网络", Toast.LENGTH_SHORT).show(); } } }; private ListView.OnItemClickListener mOnClickListener = new ListView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { ListView listView = (ListView) parent; String searchHistory = (String) listView.getItemAtPosition(position); if(searchHistory!=null && "清空搜索记录".equals(searchHistory)){ suggestions.clearHistory(); finish(); } else if(!"没有搜索记录".equals(searchHistory)){ Intent intent = new Intent(); intent.setClass(SearchActivity.this, SearchResultActivity.class); Bundle bundle = new Bundle(); bundle.putString("keyword", searchHistory); intent.putExtras(bundle); finish(); startActivity(intent); } } }; public class HistoryAdapter extends BaseAdapter { private LayoutInflater mInflater; public HistoryAdapter(Context context) { this.mInflater = LayoutInflater.from(context); historyData = getData(); } public int getCount() { return historyData.size(); } public Object getItem(int position) { return historyData.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(R.layout.search_history_item, null); String searchRecord = historyData.get(position); String searchRecordCount=""; String str= getString(R.string.associate_count); if(keywordCountList.size()>0) { searchRecordCount = keywordCountList.get(position); // .replace("+", ""); searchRecordCount=str.replace("[]", searchRecordCount); } else searchRecordCount=""; ((TextView) convertView.findViewById(R.id.history_text1)).setText(searchRecord); ((TextView) convertView.findViewById(R.id.history_text2)).setText(searchRecordCount); return convertView; } } public ArrayList<String> getData() { historyData = new ArrayList<String>(); String sortStr = " _id desc"; ContentResolver contentResolver = getContentResolver(); Uri quri = Uri.parse("content://" + SuggestionProvider.AUTHORITY + "/suggestions"); Cursor localCursor = contentResolver.query(quri, SuggestionProvider.COLUMNS, null, null, sortStr); if (localCursor!=null && localCursor.getCount()>0) { localCursor.moveToFirst(); while (true) { if (localCursor.isAfterLast()) { localCursor.close(); break; } historyData.add(localCursor.getString(1)); localCursor.moveToNext(); } } return historyData; } private boolean NetWorkStatus() { boolean netSataus = false; ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); cwjManager.getActiveNetworkInfo(); if (cwjManager.getActiveNetworkInfo() != null) { netSataus = cwjManager.getActiveNetworkInfo().isAvailable(); } return netSataus; } public void onKeywordChanged(final String paramString) { //获取联想关键词 final WebServiceHelper serviceHelper = new WebServiceHelper(); if(paramString!=null && !"".equals(paramString)){ Client.getThreadPoolForRequest().execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub keywordList=serviceHelper.getAssociateList(paramString,SharedUtils.getCurrentCityCode(Client.getContext())); keywordCountList=serviceHelper.getResultAsociateCountList(); if(keywordList!=null && keywordList.size()>0){ historyData = keywordList; }else{ historyData = getData(); keywordCountList.removeAll(keywordCountList); } Client.postRunnable(new Runnable() { @Override public void run() { // TODO Auto-generated method stub // for(int i=0;i<historyData.size();i++) // { // Log.d("historyData",""+historyData.get(i)); // } historyAdapter.notifyDataSetChanged(); } }); } }); } else { historyData = getData(); keywordCountList.removeAll(keywordCountList); historyAdapter.notifyDataSetChanged(); } // ArrayList<String> keywordList = new ArrayList<String>(); // WebServiceHelper serviceHelper = new WebServiceHelper(); // if(paramString!=null && !"".equals(paramString)){ // keywordList = serviceHelper.getAssociateList(paramString); // } else { // historyData = getData(); // } // // if(keywordList!=null && keywordList.size()>0){ // historyData = keywordList; // }else{ // historyData = getData(); // } // historyAdapter.notifyDataSetChanged(); } }
114ch
trunk/src/com/besttone/search/SearchActivity.java
Java
asf20
10,791
package com.besttone.search.util; import com.besttone.search.model.RequestInfo; public class XmlHelper { public static String getRequestXml(RequestInfo info) { StringBuilder sb = new StringBuilder(""); if(info!=null) { sb.append("<RequestInfo>"); sb.append("<region><![CDATA["+info.getRegion()+"]]></region>"); sb.append("<deviceid><![CDATA["+info.getDeviceid()+"]]></deviceid>"); sb.append("<imsi><![CDATA["+info.getImsi()+"]]></imsi>"); sb.append("<content><![CDATA["+info.getContent()+"]]></content>"); if(info.getPage()!=null){ sb.append("<Page><![CDATA["+info.getPage()+"]]></Page>"); } if(info.getPageSize()!=null){ sb.append("<PageSize><![CDATA["+info.getPageSize()+"]]></PageSize>"); } if(info.getMobile()!=null){ sb.append("<mobile><![CDATA["+info.getMobile()+"]]></mobile>"); } if(info.getMobguishu()!=null){ sb.append("<mobguishu><![CDATA["+info.getMobguishu()+"]]></mobguishu>"); } sb.append("</RequestInfo>"); } return sb.toString(); } }
114ch
trunk/src/com/besttone/search/util/XmlHelper.java
Java
asf20
1,053
package com.besttone.search.util; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.telephony.CellLocation; import android.telephony.NeighboringCellInfo; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.telephony.gsm.GsmCellLocation; import android.util.Log; public class CellInfoManager { private int asu; private int bid; private int cid; private boolean isCdma; private boolean isGsm; private int lac; private int lat; private final PhoneStateListener listener; private int lng; private int mcc; private int mnc; private int nid; private int sid; private TelephonyManager tel; private boolean valid; private Context context; public CellInfoManager(Context paramContext) { this.listener = new CellInfoListener(this); tel = (TelephonyManager) paramContext.getSystemService(Context.TELEPHONY_SERVICE); this.tel.listen(this.listener, PhoneStateListener.LISTEN_CELL_LOCATION | PhoneStateListener.LISTEN_SIGNAL_STRENGTH); context = paramContext; } public static int dBm(int i) { int j; if (i >= 0 && i <= 31) j = i * 2 + -113; else j = 0; return j; } public int asu() { return this.asu; } public int bid() { if (!this.valid) update(); return this.bid; } public JSONObject cdmaInfo() { if (!isCdma()) { return null; } JSONObject jsonObject = new JSONObject(); try { jsonObject.put("bid", bid()); jsonObject.put("sid", sid()); jsonObject.put("nid", nid()); jsonObject.put("lat", lat()); jsonObject.put("lng", lng()); } catch (JSONException ex) { jsonObject = null; Log.e("CellInfoManager", ex.getMessage()); } return jsonObject; } public JSONArray cellTowers() { JSONArray jsonarray = new JSONArray(); int lat; int mcc; int mnc; int aryCell[] = dumpCells(); lat = lac(); mcc = mcc(); mnc = mnc(); if (aryCell == null || aryCell.length < 2) { aryCell = new int[2]; aryCell[0] = cid; aryCell[1] = -60; } for (int i = 0; i < aryCell.length; i += 2) { try { int j2 = dBm(i + 1); JSONObject jsonobject = new JSONObject(); jsonobject.put("cell_id", aryCell[i]); jsonobject.put("location_area_code", lat); jsonobject.put("mobile_country_code", mcc); jsonobject.put("mobile_network_code", mnc); jsonobject.put("signal_strength", j2); jsonobject.put("age", 0); jsonarray.put(jsonobject); } catch (Exception ex) { ex.printStackTrace(); Log.e("CellInfoManager", ex.getMessage()); } } if (isCdma()) jsonarray = new JSONArray(); return jsonarray; } public int cid() { if (!this.valid) update(); return this.cid; } public int[] dumpCells() { int[] aryCells; if (cid() == 0) { aryCells = new int[0]; return aryCells; } List<NeighboringCellInfo> lsCellInfo = this.tel.getNeighboringCellInfo(); if (lsCellInfo == null || lsCellInfo.size() == 0) { aryCells = new int[1]; int i = cid(); aryCells[0] = i; return aryCells; } int[] arrayOfInt1 = new int[lsCellInfo.size() * 2 + 2]; int j = 0 + 1; int k = cid(); arrayOfInt1[0] = k; int m = j + 1; int n = asu(); arrayOfInt1[j] = n; Iterator<NeighboringCellInfo> iter = lsCellInfo.iterator(); while (true) { if (!iter.hasNext()) { break; } NeighboringCellInfo localNeighboringCellInfo = (NeighboringCellInfo) iter.next(); int i2 = localNeighboringCellInfo.getCid(); if ((i2 <= 0) || (i2 == 65535)) continue; int i3 = m + 1; arrayOfInt1[m] = i2; m = i3 + 1; int i4 = localNeighboringCellInfo.getRssi(); arrayOfInt1[i3] = i4; } int[] arrayOfInt2 = new int[m]; System.arraycopy(arrayOfInt1, 0, arrayOfInt2, 0, m); aryCells = arrayOfInt2; return aryCells; } public JSONObject gsmInfo() { if (!isGsm()) { return null; } JSONObject localObject = null; while (true) { try { JSONObject localJSONObject1 = new JSONObject(); String str1 = this.tel.getNetworkOperatorName(); localJSONObject1.put("operator", str1); String str2 = this.tel.getNetworkOperator(); if ((str2.length() == 5) || (str2.length() == 6)) { String str3 = str2.substring(0, 3); String str4 = str2.substring(3, str2.length()); localJSONObject1.put("mcc", str3); localJSONObject1.put("mnc", str4); } localJSONObject1.put("lac", lac()); int[] arrayOfInt = dumpCells(); JSONArray localJSONArray1 = new JSONArray(); int k = 0; int m = arrayOfInt.length / 2; while (true) { if (k >= m) { localJSONObject1.put("cells", localJSONArray1); localObject = localJSONObject1; break; } int n = k * 2; int i1 = arrayOfInt[n]; int i2 = k * 2 + 1; int i3 = arrayOfInt[i2]; JSONObject localJSONObject7 = new JSONObject(); localJSONObject7.put("cid", i1); localJSONObject7.put("asu", i3); localJSONArray1.put(localJSONObject7); k += 1; } } catch (JSONException localJSONException) { localObject = null; } } } public boolean isCdma() { if (!this.valid) update(); return this.isCdma; } public boolean isGsm() { if (!this.valid) update(); return this.isGsm; } public int lac() { if (!this.valid) update(); return this.lac; } public int lat() { if (!this.valid) update(); return this.lat; } public int lng() { if (!this.valid) update(); return this.lng; } public int mcc() { if (!this.valid) update(); return this.mcc; } public int mnc() { if (!this.valid) update(); return this.mnc; } public int nid() { if (!this.valid) update(); return this.nid; } public float score() { float f1 = 0f; int[] aryCells = null; int i = 0; float f2 = 0f; if (isCdma()) { f2 = 1065353216; return f2; } if (isGsm()) { f1 = 0.0F; aryCells = dumpCells(); int j = aryCells.length; if (i >= j) f2 = f1; } if(i <=0 ) { return 1065353216; } int m = aryCells[i]; for (i = 0; i < m; i++) { if ((m < 0) || (m > 31)) f1 += 0.5F; else f1 += 1.0F; } f2 = f1; return f2; } public int sid() { if (!this.valid) update(); return this.sid; } public void update() { this.isGsm = false; this.isCdma = false; this.cid = 0; this.lac = 0; this.mcc = 0; this.mnc = 0; CellLocation cellLocation = this.tel.getCellLocation(); int nPhoneType = this.tel.getPhoneType(); if (nPhoneType == 1 && cellLocation instanceof GsmCellLocation) { this.isGsm = true; GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation; int nGSMCID = gsmCellLocation.getCid(); if (nGSMCID > 0) { if (nGSMCID != 65535) { this.cid = nGSMCID; this.lac = gsmCellLocation.getLac(); } } } try { String strNetworkOperator = this.tel.getNetworkOperator(); int nNetworkOperatorLength = strNetworkOperator.length(); if (nNetworkOperatorLength != 5) { if (nNetworkOperatorLength != 6) ; } else { this.mcc = Integer.parseInt(strNetworkOperator.substring(0, 3)); this.mnc = Integer.parseInt(strNetworkOperator.substring(3, nNetworkOperatorLength)); } if (this.tel.getPhoneType() == 2) { this.valid = true; Class<?> clsCellLocation = cellLocation.getClass(); Class<?>[] aryClass = new Class[0]; Method localMethod1 = clsCellLocation.getMethod("getBaseStationId", aryClass); Method localMethod2 = clsCellLocation.getMethod("getSystemId", aryClass); Method localMethod3 = clsCellLocation.getMethod("getNetworkId", aryClass); Object[] aryDummy = new Object[0]; this.bid = ((Integer) localMethod1.invoke(cellLocation, aryDummy)).intValue(); this.sid = ((Integer) localMethod2.invoke(cellLocation, aryDummy)).intValue(); this.nid = ((Integer) localMethod3.invoke(cellLocation, aryDummy)).intValue(); Method localMethod7 = clsCellLocation.getMethod("getBaseStationLatitude", aryClass); Method localMethod8 = clsCellLocation.getMethod("getBaseStationLongitude", aryClass); this.lat = ((Integer) localMethod7.invoke(cellLocation, aryDummy)).intValue(); this.lng = ((Integer) localMethod8.invoke(cellLocation, aryDummy)).intValue(); this.isCdma = true; } } catch (Exception ex) { Log.e("CellInfoManager", ex.getMessage()); } } class CellInfoListener extends PhoneStateListener { CellInfoListener(CellInfoManager manager) { } public void onCellLocationChanged(CellLocation paramCellLocation) { CellInfoManager.this.valid = false; } public void onSignalStrengthChanged(int paramInt) { CellInfoManager.this.asu = paramInt; } } }
114ch
trunk/src/com/besttone/search/util/CellInfoManager.java
Java
asf20
14,528