serial_no
int64
1
24.2k
cuda_source
stringlengths
11
9.01M
1,401
extern "C" __global__ void mmkernel( float* a, float* b, float* c, int pitch_a, int pitch_b, int pitch_c, int n, int m, int p ) { int i = blockIdx.x * blockDim.x + threadIdx.x; int j = blockIdx.y; float sum = 0.0; for( int k = 0; k < p; ++k ) sum += b[i+pitch_b*k] * c[k+pitch_c*j]; a[i+pitch_a*j] = sum; }
1,402
#include "cuda_profiler_api.h" #include <stdio.h> void print_gpu_memory_usage() { size_t free_byte; size_t total_byte; cudaError_t cuda_status = cudaMemGetInfo(&free_byte, &total_byte); if (cudaSuccess != cuda_status) { printf("Error: cudaMemGetInfo fails, %s \n", cudaGetErrorString(cuda_status)); exit(1); } double free_db = (double)free_byte; double total_db = (double)total_byte; double used_db = total_db - free_db; printf("\n => GPU MEMORY USAGE (MB) : Used = %f, Free = %f MB, Total = %f", used_db / 1024.0 / 1024.0, free_db / 1024.0 / 1024.0, total_db / 1024.0 / 1024.0); fflush(stdout); } void start_cuda_profile() { cudaProfilerStart(); print_gpu_memory_usage(); } void stop_cuda_profile() { cudaProfilerStop(); print_gpu_memory_usage(); }
1,403
#include <stdio.h> #include <math.h> #include <iostream> using namespace std; #define TDB 1024 //Tamaño del bloque #define hy 0.34 #define hx 0.34 #define LT 1 //lado tuberia __device__ double my_floor(double num) { if (num >= LLONG_MAX || num <= LLONG_MIN || num != num) { return num; } int n = (int)num; double d = (double)n; if (d == num || num >= 0) return d; else return d - 1; } __global__ void crearMalla(float *matriz, float *coeficientes__GPU, int nodos_x, int nodos_y){ const unsigned int idx = threadIdx.x; const unsigned int i = my_floor(idx / nodos_x); const unsigned int j = idx % nodos_x; const unsigned int n = nodos_x * nodos_y; int k = 0, l = 0, columna = 0; printf("thread:%i \n", idx); while(k < nodos_x && columna < n ){ while(l < nodos_y){ if( k == i - 1 && l == j ) *(matriz + (idx * n) + columna) = *(coeficientes__GPU + 0); else if( k == i + 1 && l == j ) *(matriz + (idx * n) + columna) = *(coeficientes__GPU + 1); else if( k == i && l == j ) *(matriz + (idx * n) + columna) = *(coeficientes__GPU + 2); // else if( k == i && l == j - 1 ) *(matriz + (idx * n) + columna) = *(coeficientes__GPU + 3); else if( k == i && l == j + 1 ) *(matriz + (idx * n) + columna) = *(coeficientes__GPU + 4); else *(matriz + (idx * n) + columna) = 0; //printf("%.2f ", *(matriz + (idx * n) + columna)); columna++; l++; } l = 0; if(k < nodos_x) k++; else k = 0; } } __global__ void gaussSeidel(){ } int main(){ const unsigned int nodos_x = ceil( (float)LT / (float)hx ); const unsigned int nodos_y = ceil( (float)LT / (float)hy ); const unsigned int NDH = nodos_x * nodos_y; const unsigned int numero_bloques = ceil( (float) NDH / (float) TDB ); const unsigned int hilos_bloque = ceil( (float) NDH / (float) numero_bloques ); cout << " Se lanzaran " << numero_bloques << "bloque(s) de " << hilos_bloque << " hilos cada uno. \n\n"; float* coeficientes__HOST = (float*) malloc(5); *(coeficientes__HOST + 0 )= 1/(pow(hx,2)); //(i-1, j) *(coeficientes__HOST + 1) = 1/(pow(hx,2)); //(i+1, j) *(coeficientes__HOST + 2) = -2 *( (1/(pow(hx,2))) + (1/(pow(hy,2)))); //(i, j) *(coeficientes__HOST + 3) = 1/(pow(hy,2)); //(i, j+1) *(coeficientes__HOST + 4) = 1/(pow(hy,2)); //(i, j+1) //for(unsigned x = 0 ; x < 5 ; ++x) cout << *(coeficientes__HOST + x) << "\n"; float *malla_salida_device; cudaMalloc((void**)&malla_salida_device, NDH * NDH * sizeof(float)); float *coeficientes__GPU; cudaMalloc((void**)&coeficientes__GPU, 5 * sizeof(float)); cudaMemcpy(coeficientes__GPU, coeficientes__HOST, 5 * sizeof(float), cudaMemcpyHostToDevice); crearMalla<<<numero_bloques, hilos_bloque>>>(malla_salida_device, coeficientes__GPU, nodos_x, nodos_y); float *malla_salida_host = (float*) malloc(NDH * NDH * sizeof(float)); cudaMemcpy(malla_salida_host, malla_salida_device, NDH * NDH * sizeof(float), cudaMemcpyDeviceToHost); cudaFree(malla_salida_device); cudaFree(coeficientes__GPU); cout.precision(2); cout << "\n Nodos x: " << nodos_x << ", Nodos y: " << nodos_y << ", .\n \n"; for( int i = 0; i < NDH; ++i){ for(int j = 0 ; j < NDH ; ++j) cout << *(malla_salida_host + (i * NDH) + j) << "\t"; cout << "\n"; } free(coeficientes__HOST); free(malla_salida_host); return 0; }
1,404
// You need to write a simple program to perform computation with 1D array in CPU and GPU, then compare the result. // includes, system #include <stdio.h> #include <assert.h> #include <cuda_runtime.h> // Simple utility function to check for CUDA runtime errors void checkCUDAError(const char *msg); // Part 3 of 5: implement the kernel __global__ void calculate1DKernel(int *d_a) { int idx = threadIdx.x + blockIdx.x * blockDim.x; d_a[idx] = 1000 * blockIdx.x + threadIdx.x; printf("%u: \t %u = 1000 * %u + %u\n", idx, d_a[idx] , blockIdx.x, threadIdx.x); } //////////////////////////////////////////////////////////////////////////////// // Program main //////////////////////////////////////////////////////////////////////////////// int main( int argc, char** argv) { // pointer for host memory int *h_a; // pointer for device memory int *d_a; // define grid and block size int numBlocks = 8; int numThreadsPerBlock = 8; // Part 1 of 5: allocate host and device memory size_t size = numBlocks * numThreadsPerBlock * sizeof(int); cudaMallocHost((void **)&h_a, size); cudaMalloc((void **)&d_a, size); // Part 2 of 5: launch kernel cudaMemcpy(d_a, h_a, size, cudaMemcpyHostToDevice); calculate1DKernel<<<numBlocks, numThreadsPerBlock>>>(d_a); // block until the device has completed cudaThreadSynchronize(); // check if kernel execution generated an error checkCUDAError("kernel execution"); // Part 4 of 5: device to host copy cudaMemcpy(h_a, d_a, size, cudaMemcpyDeviceToHost); // Check for any CUDA errors checkCUDAError("cudaMemcpy"); // Part 5 of 5: verify the data returned to the host is correct // i represents blockIdx.x for(int i = 0; i < numBlocks; i++){ // j represents threadIdx.x for(int j = 0; j < numThreadsPerBlock; j++){ int idx = i * numThreadsPerBlock + j; printf("%u\n", idx); assert(h_a[idx] == (1000 * i + j)); } } // free device memory cudaFree(d_a); // free host memory cudaFreeHost(h_a); // If the program makes it this far, then the results are correct and // there are no run-time errors. Good work! printf("Correct!\n"); return 0; } void checkCUDAError(const char *msg) { cudaError_t err = cudaGetLastError(); if( cudaSuccess != err) { fprintf(stderr, "Cuda error: %s: %s.\n", msg, cudaGetErrorString( err) ); exit(-1); } }
1,405
#include <iostream> using namespace std; // Derived class class Rectangle { public: Rectangle() { width = (int *)malloc(sizeof(int)); height = (int *)malloc(sizeof(int)); } int getArea() { return (*width * *height); } int* width; int* height; }; // Base class class Shape { public: Shape() { rect = new Rectangle(); *(rect->width) = 20; *(rect->height) = 10; } Rectangle* rect; }; int main(void) { Shape* sha = new Shape(); // Print the area of the object. cout << "Total area: " << sha->rect->getArea() << endl; return 0; }
1,406
#include <stdio.h> #include <stdlib.h> #include <cuda.h> #include <cuda_runtime.h> static const int M = 16;//行 static const int N = 32;//列 #define CHECK_STATUS(status) \ if (status != cudaSuccess) \ fprintf(stderr, "File: %s\nLine:%d Function:%s>>>%s\n", __FILE__, __LINE__, __FUNCTION__,\ cudaGetErrorString(status)) //二维数组相加 __global__ void MatAdd(float *A, float *B, float *C) { int i = blockIdx.x * blockDim.x + threadIdx.x; int j = blockIdx.y * blockDim.y + threadIdx.y; if (i < N && j < N) { int index = i * N + j; C[index] = A[index] + B[index]; } } int main(int argc, char **argv) { CHECK_STATUS(cudaSetDevice(0)); const int SIZE = M * N; float a[SIZE]; float b[SIZE]; for(int i = 0;i<SIZE;i++){ a[i] = i; b[i] = i; } float c[SIZE]; float *d_a,*d_b,*d_c; //分配显存 CHECK_STATUS(cudaMalloc(&d_a, SIZE*sizeof(float))); CHECK_STATUS(cudaMalloc(&d_b, SIZE*sizeof(float))); CHECK_STATUS(cudaMalloc(&d_c, SIZE*sizeof(float))); // 把数据从内存复制到显存 CHECK_STATUS(cudaMemcpy(d_a,a,SIZE* sizeof(float),cudaMemcpyHostToDevice)); CHECK_STATUS(cudaMemcpy(d_b,b,SIZE* sizeof(float),cudaMemcpyHostToDevice)); // 调用kernel dim3 threadsPerBlock(16, 16); dim3 numBlocks(M / threadsPerBlock.x, N / threadsPerBlock.y); MatAdd<<<numBlocks, threadsPerBlock>>>(d_a, d_b, d_c); // 检查错误 CHECK_STATUS(cudaGetLastError()); // 从显存把数据复制到内存 CHECK_STATUS(cudaMemcpy(c,d_c,SIZE* sizeof(float),cudaMemcpyDeviceToHost)); // 打印 for(int i=0;i<M;i++) { for(int j=0;j<N;j++) printf("%f\t",c[i*N + j]); printf("\n"); } //释放显存 CHECK_STATUS(cudaFree(d_a)); CHECK_STATUS(cudaFree(d_b)); CHECK_STATUS(cudaFree(d_c)); return 0; }
1,407
#include <iostream> int main(void) { int n; cudaGetDeviceCount(&n); std::cout << n << " CUDA devices found." << std::endl; return 0; }
1,408
//////////////////////////////////////////////////////////////////////////////// // // FILE: burrows_wheeler_encoder.cu // DESCRIPTION: uses bitonic sort to encode a string with BWT // AUTHOR: Dan Fabian // DATE: 4/5/2020 #include <iostream> #include <stdio.h> using std::cout; using std::endl; // constants, MUST BE A POWER OF 2 IN LENGTH const int SIZE = 8; const char STRING[] = "^BANANA|"; // kernal func prototype __global__ void bitonic_sort(char *string, int *indices); //////////////////////////////////////////////////////////////////////////////// // // MAIN int main() { // create array of vals char *string_d; int *indices = new int[SIZE], *indices_d; // copy string to device memory and allocate mem int stringMem = sizeof(char) * SIZE, indexMem = sizeof(int) * SIZE; cudaMalloc((void**)&string_d, stringMem); cudaMalloc((void**)&indices_d, indexMem); cudaMemcpy(string_d, STRING, stringMem, cudaMemcpyHostToDevice); cudaMemcpy(indices_d, indices, indexMem, cudaMemcpyHostToDevice); // sort bitonic_sort<<<1, SIZE>>>(string_d, indices_d); // copy device memory back to host cudaMemcpy(indices, indices_d, indexMem, cudaMemcpyDeviceToHost); // print out encoded string for (int i = 0; i < SIZE; ++i) if (indices[i] != 0) cout << STRING[indices[i] - 1] << ' '; else cout << STRING[SIZE - 1] << ' '; cout << endl; // free all device memory cudaFree(indices_d); cudaFree(string_d); cudaDeviceSynchronize(); } //////////////////////////////////////////////////////////////////////////////// // // KERNEL function //////////////////////////////////////// // compare strings __device__ bool lessThan(char *string, const int& pos1, const int& pos2, const int &size) { int i = 0; while (string[(pos1 + i) % size] == string[(pos2 + i) % size] && i < size) ++i; if (i == size) return false; return string[(pos1 + i) % size] < string[(pos2 + i) % size]; } //////////////////////////////////////// // gpu sort func __global__ void bitonic_sort(char *string, int *indices) { const int size = SIZE; // create shared arrays static __shared__ char string_s[size]; // holds original string static __shared__ int indices_s[size]; // holds char indices of sorted array // thread idx int idx = threadIdx.x; // load 1 elem in each array per index string_s[idx] = string[idx]; indices_s[idx] = idx; // bitonic sort alg int tmp, elemIdx1, elemIdx2, strIdx1, strIdx2; bool max; // if max then put max elem in higher index for (int i = 2; i <= size; i *= 2) { // bitonic merge of size i max = (idx % i) < (i / 2); for (int j = i / 2; j > 0; j /= 2) { // get element indices to compare elemIdx1 = (idx / j) * (j * 2) + idx % j; elemIdx2 = elemIdx1 + j; strIdx1 = indices_s[elemIdx1]; strIdx2 = indices_s[elemIdx2]; // check if swap is needed if ((elemIdx2 < size) && ((max && lessThan(string_s, strIdx2, strIdx1, size)) || (!max && lessThan(string_s, strIdx1, strIdx2, size)))) { // swap indices tmp = indices_s[elemIdx1]; indices_s[elemIdx1] = indices_s[elemIdx2]; indices_s[elemIdx2] = tmp; } // need to sync before next step __syncthreads(); } } // transfer memory to global indices[idx] = indices_s[idx]; }
1,409
#include <stdio.h> #include <stdlib.h> #include <algorithm> // Change the code here: // This should be changed to GPU kernel definition void vecAdd(int numElements, const float* a, const float* b, float* c) { for (int i = 0; i < numElements; i++) { c[i] = a[i] + b[i]; } } int main() { int numElements = 10000; float* a = (float*)calloc(numElements, sizeof(float)); float* b = (float*)calloc(numElements, sizeof(float)); float* c = (float*)calloc(numElements, sizeof(float)); srand(1214134); for (int i = 0; i < numElements; i++) { a[i] = float(rand())/float(RAND_MAX + 1.0); b[i] = float(rand())/float(RAND_MAX + 1.0); } // Insert your code here: // 1. Create GPU device buffers // 2. Copy input data from host to device (vectors a and b) // 3. Change the CPU function call to the GPU kernel call vecAdd(numElements, a, b, c); // 4. Copy the result back (vector c) for (int i = 0; i < std::min(10, numElements); i++) { printf("%f + %f = %f\n", a[i], b[i], c[i]); } printf("...\n"); free(a); free(b); free(c); // Free GPU memory here return 0; }
1,410
#include "includes.h" __global__ void ConvolutionRowGPU(double *d_Dst, double *d_Src, double *d_Filter, int imageW, int imageH, int filterR){ int k; double sum=0; int row=blockDim.y*blockIdx.y+threadIdx.y; int col=blockDim.x*blockIdx.x+threadIdx.x; for (k = -filterR; k <= filterR; k++) { int d = col+ k; if (d >= 0 && d < imageW) { sum += d_Src[row * imageW + d] * d_Filter[filterR - k]; } d_Dst[row * imageW + col] = sum; } }
1,411
#include <thrust/sequence.h> #include <thrust/count.h> #include <thrust/execution_policy.h> #include <thrust/copy.h> #include <thrust/find.h> #include <iostream> #include <utility> using namespace std; struct saxpy { int *N; saxpy(int a) { cudaHostAlloc(&N, sizeof(int), 0); *N = a; } __host__ __device__ bool operator() (const int a) { return a%(*N) == 0; } }; __host__ __device__ int ordinal(const int N, const int x, const int y) { return (N*x)+y; } void print(int *begin, int *end, int start, int diff, const int N) { int *first = thrust::find(thrust::device, begin, end, 1); int *second = thrust::find(thrust::device, first+1, end, 1); int a = first - begin; int b = second - begin; int ordA = start + diff * a; int ordB = start + diff * b; cout << "NO" << endl; cout << ordA/N << " " << ordA % N << endl; cout << ordB/N << " " << ordB % N << endl; } int evaluate(int *A, int *B, int *C, const int N) { int *begin, *end; // row for (int i=0; i<N; ++i) { begin = A+ordinal(N, i, 0); end = A+1+ordinal(N,i,N-1); if (thrust::count(thrust::device, begin, end, 1) > 1) { print(begin, end, begin-A, 1, N); return 0; } } // column thrust::sequence(thrust::device, B, B+N*N); for (int i=0; i<N; ++i) { begin = A+ordinal(N,0,i); end = A+1+ordinal(N,N-1,i); int *r_end = thrust::copy_if(thrust::device, begin, end, B, C, saxpy(N)); if (thrust::count(thrust::device, C, r_end, 1) > 1) { print(C, r_end, begin-A, N, N); return 0; } } // diagonal 1 for (int i=1; i<N; ++i) { begin = A+ordinal(N,0,i); end = A+1+ordinal(N,i,0); int *r_end = thrust::copy_if(thrust::device, begin, end, B, C, saxpy(N-1)); if (thrust::count(thrust::device, C, r_end, 1) > 1) { print(C, r_end, begin-A, N-1, N); return 0; } } for (int i=1; i<N-1; ++i) { begin = A+ordinal(N,i,N-1); end = A+1+ordinal(N,N-1,i); int *r_end = thrust::copy_if(thrust::device, begin, end, B, C, saxpy(N-1)); if (thrust::count(thrust::device, C, r_end, 1) > 1) { print(C, r_end, begin-A, N-1, N); return 0; } } //diagonal 2 for (int i=0; i<N-1; ++i) { begin = A+ordinal(N,0,i); end = A+1+ordinal(N,N-i-1,N-1); int *r_end = thrust::copy_if(thrust::device, begin, end, B, C, saxpy(N+1)); if (thrust::count(thrust::device, C, r_end, 1) > 1) { print(C, r_end, begin-A, N+1, N); return 0; } } for (int i=1; i<N-1; ++i) { begin = A+ordinal(N,i,0); end = A+1+ordinal(N,N-1,N-i-1); int *r_end = thrust::copy_if(thrust::device, begin, end, B, C, saxpy(N+1)); if (thrust::count(thrust::device, C, r_end, 1) > 1) { print(C, r_end, begin-A, N+1, N); return 0; } } return 1; } int main(int argc, char const *argv[]) { int N; cin >> N; int *cA = new int[N*N]; for (int i=0; i<N*N; ++i) { cin >> cA[i]; } int *A, *B, *C; cudaMalloc(&A, sizeof(int)*N*N); cudaMalloc(&B, sizeof(int)*N*N); cudaMalloc(&C, sizeof(int)*N); cudaMemcpy(A, cA, sizeof(int)*N*N, cudaMemcpyHostToDevice); if (evaluate(A, B, C, N)) { cout << "YES" << endl; } cudaFree(A); cudaFree(B); cudaFree(C); delete[] cA; return 0; }
1,412
#include<stdio.h> #include<cuda.h> void printDevProp(cudaDeviceProp devProp) { printf("%s\n", devProp.name); printf("Major revision number: %d\n", devProp.major); printf("Minor revision number: %d\n", devProp.minor); printf("Total global memory: %u", devProp.totalGlobalMem); printf(" bytes\n"); printf("Number of multiprocessors: %d\n", devProp.multiProcessorCount); printf("Total shared memory per block: %u\n",devProp.sharedMemPerBlock); printf("Total registers per block: %d\n", devProp.regsPerBlock); printf("Warp size: %d\n", devProp.warpSize); printf("Maximum memory pitch: %u\n", devProp.memPitch); printf("Total constant memory: %u\n", devProp.totalConstMem); printf("Maximum threads per block: %d\n", devProp.maxThreadsPerBlock); printf("Maximum threads per dimension: %d,%d,%d\n", devProp.maxThreadsDim[0], devProp.maxThreadsDim[1], devProp.maxThreadsDim[2]); return; } int main(void) { int deviceCount; cudaGetDeviceCount(&deviceCount); int device; for (device = 0; device < deviceCount; ++device) { cudaDeviceProp deviceProp; cudaGetDeviceProperties(&deviceProp, device); printDevProp(deviceProp); } }
1,413
#include <stdio.h> #include <stdlib.h> #include <cuda.h> #include <curand_kernel.h> #include <math_constants.h> #include <cuda_runtime.h> #define N 20000 #define GRID_D1 20 #define GRID_D2 2 #define BLOCK_D1 512 #define BLOCK_D2 1 #define BLOCK_D3 1 extern "C" { __global__ void rtruncnorm_kernel(float *vals, int n, float *mu, float *sigma, float *lo, float *hi, int mu_len, int sigma_len, int lo_len, int hi_len, int maxtries, int rng_a, //RNG seed constant int rng_b, //RNG seed constant int rng_c) //RNG seed constant { // Usual block/thread indexing... int myblock = blockIdx.x + blockIdx.y * gridDim.x; int blocksize = blockDim.x * blockDim.y * blockDim.z; int subthread = threadIdx.z*(blockDim.x * blockDim.y) + threadIdx.y*blockDim.x + threadIdx.x; int idx = myblock * blocksize + subthread; // Copied this from hello_world if (idx < N){ printf("Hello world! My block index is (%d,%d) [Grid dims=(%d,%d)], 3D-thread index within block=(%d,%d,%d) => thread index=%d\n", blockIdx.x, blockIdx.y, gridDim.x, gridDim.y, threadIdx.x, threadIdx.y, threadIdx.y, idx); } else { printf("Hello world! My block index is (%d,%d) [Grid dims=(%d,%d)], 3D-thread index within block=(%d,%d,%d) => thread index=%d [### this thread would not be used for N=%d ###]\n", blockIdx.x, blockIdx.y, gridDim.x, gridDim.y, threadIdx.x, threadIdx.y, threadIdx.y, idx, N); } // Setup the RNG: // Sample: return; /* // Notes/Hints from class */ /* // i.e. threadIdx.x .y .z map these to a single index */ /* // */ /* // Check whether idx < N */ /* // */ /* // Initialize RNG */ /* curandState rng; */ /* curand_init(rng_a*idx+rng_b,rng_c,0,&rng); */ /* // Sample the truncated normal */ /* // mu for this index is mu[idx] */ /* // sigma for this index is sigma[idx] */ /* // a for this index is a[idx] */ /* // b for this index is b[idx] */ /* // X_i ~ Truncated-Normal(mu_i,sigma_i;[a_i,b_i]) */ /* // Sample N(mu, sigma^2): */ /* x[idx] = mu[idx] + sigma[idx]*curand_normal(&rng); */ /* // To get the random uniform curand_uniform(&rng) */ /* return; */ } } // END extern "C" int main(int argc,char **argv) { const dim3 blockSize(BLOCK_D1, BLOCK_D2, BLOCK_D3); const dim3 gridSize(GRID_D1, GRID_D2, 1); int nthreads = BLOCK_D1*BLOCK_D2*BLOCK_D3*GRID_D1*GRID_D2; if (nthreads < N){ printf("\n============ NOT ENOUGH THREADS TO COVER N=%d ===============\n\n",N); } else { printf("Launching %d threads (N=%d)\n",nthreads,N); } // Define the parameters float vals[10]; int n = 10; int mu_len=10; int sigma_len=10; int lo_len=10; int hi_len=10; float mu[mu_len]; float sigma[sigma_len]; float lo[lo_len]; float hi[hi_len]; int maxtries=50; int rng_a=121; //RNG seed constant int rng_b=132; //RNG seed constant int rng_c=143; //RNG seed constant // launch the kernel rtruncnorm_kernel<<<gridSize, blockSize>>>(vals, n, mu, sigma, lo, hi, mu_len, sigma_len, lo_len, hi_len, maxtries, rng_a, rng_b, rng_c); // Need to flush prints... cudaError_t cudaerr = cudaDeviceSynchronize(); if (cudaerr){ printf("kernel launch failed with error \"%s\".\n", cudaGetErrorString(cudaerr)); } else { printf("kernel launch success!\n"); } printf("That's all!\n"); return 0; }
1,414
#include "includes.h" __global__ void third_and_fourth_normal_component(float* z, float* xx, float* yy, float* zx, float* zy, int npix, float* N3) { int i = blockIdx.x*blockDim.x + threadIdx.x; if (i < npix) { N3[i] = -z[i] - (xx[i]) * zx[i] - (yy[i]) * zy[i]; N3[npix + i] = 1; } }
1,415
#include<stdio.h> __global__ void safty(int *a, int N,int arg) { int i = threadIdx.x + blockIdx.x*blockDim.x; if(arg ==0) { if(i < N) { a[i] = 1; } } else { if(i <N) { a[i]*=2; printf("%d",a[i]); } } } int main() { int *a; size_t size = 100; int N = size*sizeof(int); int thread = 32; int block = (N-1)/thread +1; cudaMallocManaged(&a,N); safty<<<block,thread>>>(a,N,0); safty<<<block,thread>>>(a,N,1); cudaDeviceSynchronize(); cudaFree(a); }
1,416
#include "includes.h" __global__ void Pi_GPU(float *x, float *y, int *totalCounts, int N) { int idx = blockIdx.x * blockDim.x + threadIdx.x; // номер элемента int threadCount = gridDim.x * blockDim.x; //cмещение int countPoints = 0; for (int i = idx; i < N; i += threadCount) { if (x[i] * x[i] + y[i] * y[i] < 1) { countPoints++; } } atomicAdd(totalCounts, countPoints); // каждый поток суммирует в переменную }
1,417
extern "C" __global__ void mmkernel( float* a, float* b, float* c, int pitch_a, int pitch_b, int pitch_c, int n, int m, int p ) { int tx = threadIdx.x; int i = blockIdx.x*64 + tx; int j = blockIdx.y*2; __shared__ float cb0[32], cb1[32]; float sum0 = 0.0, sum1 = 0., sum2 = 0.0, sum3 = 0.0; for( int ks = 0; ks < p; ks += 32 ){ cb0[tx] = c[ks+tx+pitch_c*j]; cb1[tx] = c[ks+tx+pitch_c*(j+1)]; __syncthreads(); for( int k = ks; k < ks+32; ++k ){ float rb0 = b[i+pitch_b*k]; float rb1 = b[i+32+pitch_b*k]; sum0 += rb0 * cb0[k - ks]; sum1 += rb0 * cb1[k - ks]; sum2 += rb1*cb0[k - ks]; sum3 += rb1*cb1[k - ks]; } __syncthreads(); } a[i+pitch_a*j] = sum0; a[i+pitch_a*(j+1)] = sum1; a[i+32+pitch_a*j] = sum2; a[i+32+pitch_a*(j+1)] = sum3; }
1,418
#include <stdio.h> __global__ void print_hello_world(void) { printf("Hello world from GPU\n"); } int main(int argc, char **argv) { printf("Hello world from CPU!\n"); print_hello_world<<<2, 5>>>(); cudaDeviceSynchronize(); return 0; }
1,419
#include<stdio.h> #define ROW 1000 #define COL 1000 __global__ void mat_vect(int *a, int *b, long *c, int m, int n) { int col = blockIdx.x * blockDim.x + threadIdx.x; long sum = 0; if (col < n){ for(int i = 0; i < n; i++) { printf("matrix value: %d, vect value: %d \n", a[i*m + col], b[i]); sum += a[i * m + col] * b[i]; //printf("cur sum: %d\n", sum); } //printf("col value is : %d\n", col); //printf("sum value: %d\n", sum); c[col] = sum; } } void TestMatrixGenerate(int* matrix, int row, int col) { //printf("Row: %d", row); //printf("Col: %d", col); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { matrix[i * col + j] = (j + 1) + i * row; //printf("%d ", matrix[i*col + j]); } //printf("\n"); } } void TestVectorGenerate(int* vector, int row) { for(int i = 0; i < row; i++) { vector[i] = i * 2; //printf("%d ", vector[i]); } } int main() { int m[ROW*COL]; int v[COL]; int res[COL]; int *ptr_m, *ptr_v, *ptr_res; ptr_m = m; ptr_v = v; ptr_res = res; TestMatrixGenerate(ptr_m, ROW, COL); TestVectorGenerate(ptr_v, ROW); int *d_m, *d_v; long *d_res; cudaMallocManaged(&d_m, ROW*COL*sizeof(int)); cudaMallocManaged(&d_v, ROW*sizeof(int)); cudaMallocManaged(&d_res, ROW*sizeof(long)); // init d_m, d_v on the host TestMatrixGenerate(d_m, ROW, COL); TestVectorGenerate(d_v, ROW); int blockSize = 256; mat_vect<<<COL/blockSize + 1, blockSize>>>(d_m, d_v, d_res, ROW, COL); cudaDeviceSynchronize(); // result verify //printf("the front 10 elements results: \n"); //for (int i = 0; i < 10; i++) { // printf("%d ", d_res[i]); //} cudaFree(d_m); cudaFree(d_v); cudaFree(d_res); return 0; }
1,420
#include <stdio.h> #include <cuda.h> //be careful the block_size*block_size should not exceed 1024 #define BLOCK_SIZE 32 __global__ void pictureKernel(float* d_pix,int X, int Y); int main() { float *h_pixin, *h_pixout, *d_pix; int x=76,y=62,i; //2D data size int grid_x=x/BLOCK_SIZE,grid_y=y/BLOCK_SIZE; int size=x*y*sizeof(float); dim3 dim_block(BLOCK_SIZE,BLOCK_SIZE,1); if(x%BLOCK_SIZE) grid_x++; if(y%BLOCK_SIZE) grid_y++; dim3 dim_grid(grid_x,grid_y,1); printf("grid size is:grid_x=%d,grid_y=%d\n",grid_x,grid_y); h_pixin=(float*)malloc(size); h_pixout=(float*)malloc(size); cudaMalloc((void**) &d_pix,size); if(h_pixin==NULL||h_pixout==NULL||d_pix==NULL) { printf("malloc failed!\n"); } for(i=0;i<x*y;i++) { h_pixin[i]=i*1.5; } cudaMemcpy(d_pix,h_pixin,size,cudaMemcpyHostToDevice); pictureKernel<<<dim_grid,dim_block>>>(d_pix,x,y); //after this d_pix changed cudaError_t error = cudaGetLastError(); if(error != cudaSuccess) { printf("CUDA Error: %s\n", cudaGetErrorString(error)); return 1; } cudaMemcpy(h_pixout,d_pix,size,cudaMemcpyDeviceToHost); for(i=0;i<x*y;i++) { printf("h_pixin[i]=%f,h_pixout=%f\n",h_pixin[i],h_pixout[i]); } return 0; } __global__ void pictureKernel(float* d_pix,int X, int Y) { int thread_x=blockDim.x*blockIdx.x+threadIdx.x; int thread_y=blockDim.y*blockIdx.y+threadIdx.y; // printf("thread_x=%d,blockDim.x=%d,blockIdx.x=%d,threadIdx=%d\n",thread_x,blockDim.x,blockIdx.x,threadIdx.x); // printf("thread_y=%d,blockDim.y=%d,blockIdx.y=%d,threadIdy=%d\n",thread_y,blockDim.y,blockIdx.y,threadIdx.y); // use this printf nvcc -arch compute_20 pixel.cu if(thread_x<X&&thread_y<Y) { d_pix[thread_y*X+thread_x]*=2; } }
1,421
#include <stdio.h> #include <stdlib.h> #include <math.h> #define size 1024 __global__ void sqrtvec(float *b, const float *a) { int i = threadIdx.x; b[i] = sqrtf(a[i]); } int main() { float a[size]; for (int i = 0; i < size; i++) { a[i] = (float)i; } float b[size] = {0}; float *da, *db; cudaMalloc((void**)& db, size*sizeof(int)); cudaMalloc((void**)& da, size*sizeof(int)); cudaMemcpy(da, a, size*sizeof(int), cudaMemcpyHostToDevice); sqrtvec<<<1, size>>>(db, da); cudaMemcpy(b, db, size*sizeof(int), cudaMemcpyDeviceToHost); for (int i = 0; i < size; i++) { printf("%f\n", b[i]); } cudaThreadSynchronize(); cudaFree(db); cudaFree(da); return 0; }
1,422
#include<stdio.h> // __global__ is the global kernel specifier. // identifies a kernel function (cuda c functions) __global__ void cuda_hello(){ // to print printf("Hello World from GPU!\n"); } int main() { // <<< >>> is the execution configuration syntax // it specify the number of threads that will // execute the cuda_hello program cuda_hello<<<1,1>>>(); // synchronize execution // see discussion in the link // "https://stackoverflow.com/questions/19193468/why-do-we-need-cudadevicesynchronize-in-kernels-with-device-printf" cudaDeviceSynchronize(); return 0; }
1,423
#include <stdio.h> #include <unistd.h> #define ALLOC_SIZE 1024 __global__ void access_offset_kernel(int offset) { int devMem[ALLOC_SIZE]; devMem[0] = 0; devMem[1] = devMem[0]; // for init/unused warnings if (offset >= 0) offset += (ALLOC_SIZE-1); // this slight difference in the conditional produced different results // so we include one version for posterity to investigate #ifdef R volatile int i = devMem[offset]; #elif W devMem[offset] = 42; #endif } int main(int argc, char** argv) { if (argc != 3) { fprintf(stderr, "Usage: %s -o <offset>\n", argv[0]); abort(); } int offset = 0; int c; while ((c = getopt(argc, argv, "o:")) != -1) { switch(c) { case 'o': offset = atoi(optarg); break; default: fprintf(stderr, "Usage: %s -o <offset>\n", argv[0]); abort(); } } access_offset_kernel<<<1,1>>>(offset); cudaDeviceReset(); return 0; }
1,424
#include <stdio.h> #include <cuda.h> __global__ void K1(int num) { num += num; ++num; } __device__ int sum = 0; __global__ void K2(int num) { atomicAdd(&sum, num); } __global__ void K3(int num) { __shared__ int sum; sum = 0; __syncthreads(); sum += num; } int main() { for (unsigned ii = 0; ii < 100; ++ii) { K1<<<5, 32>>>(ii); cudaDeviceSynchronize(); } for (unsigned ii = 0; ii < 100; ++ii) { K2<<<5, 32>>>(ii); cudaDeviceSynchronize(); } for (unsigned ii = 0; ii < 100; ++ii) { K3<<<5, 32>>>(ii); cudaDeviceSynchronize(); } return 0; }
1,425
// Check that types, widths, etc. match on the host and device sides of CUDA // compilations. Note that we filter out long double, as this is intentionally // different on host and device. // RUN: %clang --cuda-host-only -nocudainc -target i386-unknown-linux-gnu -x cuda -E -dM -o - /dev/null > %T/i386-host-defines // RUN: %clang --cuda-device-only -nocudainc -target i386-unknown-linux-gnu -x cuda -E -dM -o - /dev/null > %T/i386-device-defines // RUN: grep 'define __[^ ]*\(TYPE\|MAX\|SIZEOF|WIDTH\)' %T/i386-host-defines | grep -v '__LDBL\|_LONG_DOUBLE' > %T/i386-host-defines-filtered // RUN: grep 'define __[^ ]*\(TYPE\|MAX\|SIZEOF|WIDTH\)' %T/i386-device-defines | grep -v '__LDBL\|_LONG_DOUBLE' > %T/i386-device-defines-filtered // RUN: diff %T/i386-host-defines-filtered %T/i386-device-defines-filtered // RUN: %clang --cuda-host-only -nocudainc -target x86_64-unknown-linux-gnu -x cuda -E -dM -o - /dev/null > %T/x86_64-host-defines // RUN: %clang --cuda-device-only -nocudainc -target x86_64-unknown-linux-gnu -x cuda -E -dM -o - /dev/null > %T/x86_64-device-defines // RUN: grep 'define __[^ ]*\(TYPE\|MAX\|SIZEOF\|WIDTH\)' %T/x86_64-host-defines | grep -v '__LDBL\|_LONG_DOUBLE' > %T/x86_64-host-defines-filtered // RUN: grep 'define __[^ ]*\(TYPE\|MAX\|SIZEOF\|WIDTH\)' %T/x86_64-device-defines | grep -v '__LDBL\|_LONG_DOUBLE' > %T/x86_64-device-defines-filtered // RUN: diff %T/x86_64-host-defines-filtered %T/x86_64-device-defines-filtered // RUN: %clang --cuda-host-only -nocudainc -target powerpc64-unknown-linux-gnu -x cuda -E -dM -o - /dev/null > %T/powerpc64-host-defines // RUN: %clang --cuda-device-only -nocudainc -target powerpc64-unknown-linux-gnu -x cuda -E -dM -o - /dev/null > %T/powerpc64-device-defines // RUN: grep 'define __[^ ]*\(TYPE\|MAX\|SIZEOF\|WIDTH\)' %T/powerpc64-host-defines | grep -v '__LDBL\|_LONG_DOUBLE' > %T/powerpc64-host-defines-filtered // RUN: grep 'define __[^ ]*\(TYPE\|MAX\|SIZEOF\|WIDTH\)' %T/powerpc64-device-defines | grep -v '__LDBL\|_LONG_DOUBLE' > %T/powerpc64-device-defines-filtered // RUN: diff %T/powerpc64-host-defines-filtered %T/powerpc64-device-defines-filtered // RUN: %clang --cuda-host-only -nocudainc -target nvptx-nvidia-cuda -x cuda -E -dM -o - /dev/null > %T/nvptx-host-defines // RUN: %clang --cuda-device-only -nocudainc -target nvptx-nvidia-cuda -x cuda -E -dM -o - /dev/null > %T/nvptx-device-defines // RUN: grep 'define __[^ ]*\(TYPE\|MAX\|SIZEOF\|WIDTH\)' %T/nvptx-host-defines | grep -v '__LDBL\|_LONG_DOUBLE' > %T/nvptx-host-defines-filtered // RUN: grep 'define __[^ ]*\(TYPE\|MAX\|SIZEOF\|WIDTH\)' %T/nvptx-device-defines | grep -v '__LDBL\|_LONG_DOUBLE' > %T/nvptx-device-defines-filtered // RUN: diff %T/nvptx-host-defines-filtered %T/nvptx-device-defines-filtered
1,426
#include <cuda_runtime.h> #include <iostream> #include <stdlib.h> #include <time.h> __global__ void add(int * d_a,int *d_b,int n) { int idx = threadIdx.x; int i = 2,j = 1; do{ if(idx % i == 0) d_a[idx] += d_a[idx + j]; i *= 2; j *= 2; }while(n/=2); d_b[0] = d_a[0]; } int main() { int blag = 1; int n = 0; do{ std::cout << "请输入数据长度:" << std::endl; std::cin >> n; if(n <= 0) { std::cout << "你输入的数据长度不合法,请重新输入!" << std::endl; }else{ blag = 0; } }while(blag); srand(time(NULL)); int *h_a = (int*)malloc(sizeof(int) * n); int *h_b = (int*)malloc(sizeof(int)); for(int i = 0; i < n; ++i) { h_a[i] = rand() % 11; printf("h_a[%d] = %d\t",i,h_a[i]); } printf("\n"); int *d_a = NULL; int *d_b = NULL; cudaMalloc((void**)&d_a,sizeof(int) * n); cudaMalloc((void**)&d_b,sizeof(int)); cudaMemcpy(d_a,h_a,sizeof(int) * n,cudaMemcpyHostToDevice); add<<<1,n>>>(d_a,d_b,n); cudaMemcpy(h_b,d_b,sizeof(int),cudaMemcpyDeviceToHost); printf("h_b = %d\n",*h_b); free(h_a); free(h_b); cudaFree(d_a); cudaFree(d_b); printf("运行结束!\n"); return 0; }
1,427
#include "includes.h" __global__ void init_topp_id_val(int* topp_id_val_buf, int* topp_offset_buf, const int batch_size, const int vocab_size) { int tid = threadIdx.x; int bid = blockIdx.x; if(bid == 0) { for(int i = tid; i < batch_size + 1; i+= blockDim.x) { topp_offset_buf[i] = i * vocab_size; } } while(tid < vocab_size) { topp_id_val_buf[bid * vocab_size + tid] = tid; tid += blockDim.x; } }
1,428
// // Created by lifan on 2021/5/17. //
1,429
#include <cmath> #include <vector> #include <cstring> #include <algorithm> using namespace std; typedef pair<int, int> prime_pot; //MAX determines the primes limit const unsigned MAX = 100010/60, MAX_S = sqrt(MAX/60); unsigned w[16] = {1, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 49, 53, 59}; unsigned short composite[MAX]; vector<int> _primes; //Generate primes with sieve vector<int>& generate_primes() { unsigned mod[16][16], di[16][16], num; for(int i = 0; i < 16; i++) for(int j = 0; j < 16; j++) { di[i][j] = (w[i] * w[j]) / 60; mod[i][j] = lower_bound(w, w + 16, (w[i] * w[j]) % 60) - w; } _primes.push_back(2); _primes.push_back(3); _primes.push_back(5); for(unsigned i = 0; i < MAX; i++) for(int j = (i == 0); j < 16; j++) { if(composite[i] & (1 << j)) continue; _primes.push_back(num = 60 * i + w[j]); if(i > MAX_S) continue; for(unsigned k = i, done = false; !done; k++) for(int l = (k == 0); l < 16 && !done; l++) { unsigned mult = k * num + i * w[l] + di[j][l]; if(mult >= MAX) done = true; else composite[mult] |= 1 << mod[j][l]; } } return _primes; }
1,430
/** * blockAndThread.cu * description: fill two arrays with blockId and threadId values * notes: compile with nvcc and parent code: * "nvcc blockAndThread.c blockAndThread.cu" * Program is similar to one that appears in Dr. Dobbs Journal. * The tutorial is available at: * http://www.ddj.com/hpc-high-performance-computing/207200659 * Also used Andrew Bellenir's matrix multiplication program **/ #include <stdio.h> #include <stdlib.h> /* * In CUDA it is necessary to define block sizes * The grid of data that will be worked on is divided into blocks */ #define BLOCK_SIZE 8 /** * The function that will be executed in each stream processors * The __global__ directive identifies this function as being * an executable kernel on the CUDA device. * All kernesl must be declared with a return type void */ __global__ void cu_fillArray(int *block_d,int *thread_d){ int x; /* blockIdx.x is a built-in variable in CUDA that returns the blockId in the x axis. threadIdx.x is another built-in variable in CUDA that returns the threadId in the x axis of the thread that is being executed by the stream processor accessing this particular block */ x=blockIdx.x*BLOCK_SIZE+threadIdx.x; block_d[x] = blockIdx.x; thread_d[x] = threadIdx.x; } /** * This function is called from the host computer. * It calls the function that is executed on the GPU. * Recall that: * The host computer and the GPU have separate memories * Hence it is necessary to * - Allocate memory in the GPU * - Copy the variables that will be operated on from host * memory to the corresponding variables in the GPU * - Describe the configuration of the grid and the block size * - Call the kernel, the code that will be executed on the GPU * - Once the kernel has finished executing, copy the results * back from GPU memory to host memory */ extern "C" void fillArray(int *block,int *thread,int arraySize){ //block_d and thread_d are the GPU counterparts of the arrays that exist in the host memory int *block_d; int *thread_d; cudaError_t result; //allocate memory on device // cudaMalloc allocates space in the memory of the GPU result = cudaMalloc((void**)&block_d,sizeof(int)*arraySize); if (result != cudaSuccess) { printf("cudaMalloc - block_d - failed\n"); exit(1); } result = cudaMalloc((void**)&thread_d,sizeof(int)*arraySize); if (result != cudaSuccess) { printf("cudaMalloc - thread_d - failed\n"); exit(1); } //copy the arrays into the variable array_d in the device result = cudaMemcpy(block_d,block,sizeof(int)*arraySize,cudaMemcpyHostToDevice); if (result != cudaSuccess) { printf("cudaMemcpy - host-GPU - block - failed\n"); exit(1); } result = cudaMemcpy(thread_d,thread,sizeof(int)*arraySize,cudaMemcpyHostToDevice); if (result != cudaSuccess) { printf("cudaMemcpy - host-GPU - thread - failed\n"); exit(1); } //execution configuration... // Indicate the dimension of the block dim3 dimblock(BLOCK_SIZE); // Indicate the dimension of the grid in blocks dim3 dimgrid(arraySize/BLOCK_SIZE); //actual computation: Call the kernel cu_fillArray<<<dimgrid,dimblock>>>(block_d,thread_d); // read results back: // Copy the results from the memory in the GPU back to the memory on the host result = cudaMemcpy(block,block_d,sizeof(int)*arraySize,cudaMemcpyDeviceToHost); if (result != cudaSuccess) { printf("cudaMemcpy - GPU-host - block - failed\n"); exit(1); } result = cudaMemcpy(thread,thread_d,sizeof(int)*arraySize,cudaMemcpyDeviceToHost); if (result != cudaSuccess) { printf("cudaMemcpy - GPU-host - thread - failed\n"); exit(1); } // Release the memory on the GPU cudaFree(block_d); cudaFree(thread_d); }
1,431
#define GEOMETRY_STAGE_GLOBAL #include "geometry_stage.cuh"
1,432
/* #ifndef __CUDACC__ #define __CUDACC__ #endif #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <stdlib.h> #include <conio.h> __constant__ int M[3]; __global__ void convolution_1D_basic(int *N, int *P,int Mask_Width, int Width) { int i = blockIdx.x*blockDim.x + threadIdx.x; int Pvalue = 0; int N_start_point = i - (Mask_Width/2); for (int j = 0; j < Mask_Width; j++) { if (N_start_point + j >=0 && N_start_point + j < Width) { Pvalue += N[N_start_point + j]*M[j]; } } P[i] = Pvalue; } int main() { const int width=5; int i,j,size; int h_M[width],h_N[width],h_P[width]; int *d_M,*d_N,*d_P; printf("\n width= %d \n ", width); h_N[0]=0; h_N[1]=1; h_N[2]=0; printf("\n Enter elements \n", width); for(i=0;i<width;i++) scanf("%d\n",h_M[i]); printf("\n"); size=sizeof(int)*width; cudaMalloc((void**)&d_M,size); cudaMalloc((void**)&d_N,size); cudaMalloc((void**)&d_P,size); cudaMemcpyToSymbol(M,h_N,size); convolution_1D_basic<<<1,width>>>(d_N,d_P,size,width); cudaMemcpy(h_P,d_P,size,cudaMemcpyDeviceToHost); cudaFree(d_N); cudaFree(d_P); printf("\n\nRESULT : \n"); for(j=0;j<width;j++) printf("%d ",h_P[j]); getch(); return 0; } */
1,433
#include <chrono> #include <fstream> #include <stdio.h> #include <string> #include <iostream> #include <math.h> __constant__ int DbMToWattConstDivisor = 1000; __constant__ double CTen = 10; __constant__ int P = 1; __device__ void d_dbm_to_watts( const int& dbm, double& results ) { const double pow = (P * dbm) / CTen; const double numerator = std::pow( CTen, pow ); const double watts = numerator / DbMToWattConstDivisor; results = watts; } __global__ void convert_dbm_to_watts(const int* const d_dbms, double* const results) { int index = threadIdx.x + blockIdx.x * blockDim.x; d_dbm_to_watts( d_dbms[index], results[index] ); } __host__ int get_duration_ns( const std::chrono::time_point<std::chrono::high_resolution_clock>& start, const std::chrono::time_point<std::chrono::high_resolution_clock>& end ) { return int(std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()); } __host__ std::chrono::time_point<std::chrono::high_resolution_clock> get_clock_time() { return std::chrono::high_resolution_clock::now(); } // Helper function for writing the add math results to file. __host__ void write_results( const std::string& outputName, const int& totalThreads, const int& blockSize, const double* const results, const int& proc_time, const int& memcpy_time) { std::ofstream stream(outputName); if (stream.is_open()) { stream << "dBm -> Watts: " << totalThreads << " and Block Size: " << blockSize << "\n"; for( int i = 0; i < totalThreads; i++ ) { stream << i << " dBm " << " -> " << results[i] << " Watts\n"; } stream << "dbm -> watts took " << proc_time << "ns\n"; stream << "mem copy took dev->host" << memcpy_time << "ns\n"; } else{ printf("FILE NOT OPEN?\n"); } stream.close(); } // Helper function for executing the math functionality via pinned or pageable memory // calls the add_array, sub_array, mult_array, and mod_array and copies the results to an interleaved // struct __host__ void run_kernal( const int& blockSize, const int& totalThreads, const int& numBlocks, const std::string& outputName, double*& results, int* d_data, double* d_results) { auto start = get_clock_time(); convert_dbm_to_watts<<<numBlocks, blockSize>>>(d_data, d_results); cudaDeviceSynchronize(); auto stop = get_clock_time(); int proc_time = get_duration_ns( start, stop ); printf("dbm -> watts took %d ns\n", proc_time); auto results_size = totalThreads * sizeof(double); start = get_clock_time(); cudaMemcpy(results, d_results, results_size, cudaMemcpyDeviceToHost); stop = get_clock_time(); int memcpy_time = get_duration_ns( start, stop ); printf("mem copy took %d ns\n", memcpy_time); if ( !outputName.empty() ) { write_results( outputName, totalThreads, totalThreads / numBlocks, results, proc_time, memcpy_time ); } } // Helper function for initilizing the data used by the math functions will output results of pageable and // pinned memory allocation. __host__ void init_data(const int& totalThreads, int*& host_data, double*& host_results, int*& d_data, double*& d_results) { auto data_size = totalThreads * sizeof(int); auto results_size = totalThreads * sizeof(double); cudaMalloc((void**)&d_data, data_size); cudaMalloc((void**)&d_results, results_size); host_data = (int*)malloc(data_size); host_results = (double*)malloc(results_size); for( int i = 0; i < totalThreads; i++ ) { host_data[i] = i; } cudaMemcpy(d_data, host_data, data_size, cudaMemcpyHostToDevice); } // Helper function for cleaning up allocated memory used by math functionality. __host__ void cleanup_data( int*& data, int*& d_data, double*& results, double*& d_results) { cudaFree(d_data); cudaFree(d_results); free(data); free(results); } // Used to run the math functionality with pageable memory __host__ void execute_dBm_to_watts( const int& blockSize, const int& totalThreads, const int& numBlocks, const bool& writeResults, const std::string& outputName) { int* data = nullptr; int* d_data = nullptr; double* results = nullptr; double* d_results = nullptr; init_data(totalThreads, data, results, d_data, d_results); run_kernal(blockSize, totalThreads, numBlocks, outputName, results, d_data, d_results); cleanup_data(data, d_data, results, d_results); } int main(int argc, char** argv) { // read command line arguments int totalThreads = 512; int blockSize = 256; bool outputResults = false; std::string outputName; if (argc >= 2) { totalThreads = atoi(argv[1]); } if (argc >= 3) { blockSize = atoi(argv[2]); } if (argc >= 4) { outputResults = true; outputName = argv[3]; } int numBlocks = totalThreads/blockSize; // validate command line arguments if (totalThreads % blockSize != 0) { ++numBlocks; totalThreads = numBlocks*blockSize; printf("Warning: Total thread count is not evenly divisible by the block size\n"); printf("The total number of threads will be rounded up to %d\n", totalThreads); } printf("Executing with %d total threads %d blocks @ %d threads\n", totalThreads, numBlocks, blockSize); execute_dBm_to_watts( blockSize, totalThreads, numBlocks, outputResults, outputName); }
1,434
#include "includes.h" __global__ void matrixMulCUDA2(float *C, float *A, float *B, int n) { /* Each thread computes more than 1 matrix elements */ // Define the starting row and ending row for each thread int startRow = threadIdx.y * TILE_WIDTH; int endRow = startRow + TILE_WIDTH; // Define the starting column and ending column for each thread int startCol = threadIdx.x * TILE_WIDTH; int endCol = startCol + TILE_WIDTH; // Now we have some block in 2 dimensions for (int row = startRow; row < endRow; row++) { for (int col = startCol; col < endCol; col++) { if (row >= n || col >= n) { continue; } // Compute the proper sum for each block float sum = 0.0f; // Defined as a register (Better than directly writing to C) for (int k = 0; k < n; k++) { sum += A[row * n + k] * B[k * n + col]; } // Write back sum into C C[row * n + col] = sum; } } }
1,435
#define dis2(a_x, a_y, b_x, b_y) (((a_x) - (b_x)) * ((a_x) - (b_x)) + ((a_y) - (b_y)) * ((a_y) - (b_y))) #define normalize(x) ((x) > 1.0? 1.0: ((x) < 0.0? 0.0: (x))) extern "C" __device__ double half_tan( unsigned a_x, unsigned a_y, unsigned b_x, unsigned b_y, unsigned c_x, unsigned c_y ) { double ac2 = dis2((double)a_x, (double)a_y, (double)c_x, (double)c_y); double bc2 = dis2((double)b_x, (double)b_y, (double)c_x, (double)c_y); double ab2 = dis2((double)a_x, (double)a_y, (double)b_x, (double)b_y); double cos = (ab2 + bc2 - ac2) / (2.0 * sqrt(ab2) * sqrt(bc2)); if (cos > 1.0) { cos = 1.0; } else if (cos < -1.0) { cos = -1.0; } return sqrt((1.0 - cos) / (1.0 + cos)); } extern "C" __global__ void mvc_interpolant( //input const unsigned int* fg_mask_idx_x, const unsigned int* fg_mask_idx_y, const unsigned int* fg_bound_idx_x, const unsigned int* fg_bound_idx_y, const double* fg_bound_r, const double* fg_bound_g, const double* fg_bound_b, const unsigned int len, const unsigned int bound_len, //output double* out_r, double* out_g, double* out_b ) { //data parallel double sum; unsigned prev_x, prev_y, next_x, next_y; double reg_r, reg_g, reg_b; for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < len; i += blockDim.x * gridDim.x) { sum = reg_r = reg_g = reg_b = 0.0; for (int j = 0; j < bound_len; ++j) { if (j == 0) { prev_x = fg_bound_idx_x[bound_len - 1]; prev_y = fg_bound_idx_y[bound_len - 1]; } else { prev_x = fg_bound_idx_x[j - 1]; prev_y = fg_bound_idx_y[j - 1]; } if (j == bound_len - 1) { next_x = fg_bound_idx_x[0]; next_y = fg_bound_idx_y[0]; } else { next_x = fg_bound_idx_x[j + 1]; next_y = fg_bound_idx_y[j + 1]; } double w = (half_tan(prev_x, prev_y, fg_mask_idx_x[i], fg_mask_idx_y[i], fg_bound_idx_x[j], fg_bound_idx_y[j]) + half_tan(fg_bound_idx_x[j], fg_bound_idx_y[j], fg_mask_idx_x[i], fg_mask_idx_y[i], next_x, next_y)) / sqrt(dis2((double)fg_bound_idx_x[j], (double)fg_bound_idx_y[j], (double)fg_mask_idx_x[i], (double)fg_mask_idx_y[i])); sum += w; reg_r += w * fg_bound_r[j]; reg_g += w * fg_bound_g[j]; reg_b += w * fg_bound_b[j]; } out_r[i] = reg_r / sum; out_g[i] = reg_g / sum; out_b[i] = reg_b / sum; } }
1,436
#include <iostream> #include <memory> #include <cassert> using namespace std; #include <cuda.h> struct MyStruct { float *floats; float afloat; }; struct MyStruct2 { float *floats1; float *floats2; float afloat; }; __global__ void getValue(struct MyStruct mystruct, float *data) { data[0] = mystruct.floats[0] + 3.0f; } __global__ void getValue2(struct MyStruct2 mystruct, float *data1, float *data2) { data1[0] = mystruct.floats1[0] + 3.0f; data2[0] = mystruct.floats2[0] + 5.0f; } void test1(CUstream &stream) { int N = 1024; // CUstream stream; // cuStreamCreate(&stream, 0); float *hostFloats1; float *hostFloats2; cuMemHostAlloc((void **)&hostFloats1, N * sizeof(float), CU_MEMHOSTALLOC_PORTABLE); cuMemHostAlloc((void **)&hostFloats2, N * sizeof(float), CU_MEMHOSTALLOC_PORTABLE); CUdeviceptr deviceFloats1; CUdeviceptr deviceFloats2; cuMemAlloc(&deviceFloats1, N * sizeof(float)); cuMemAlloc(&deviceFloats2, N * sizeof(float)); MyStruct mystruct; mystruct.floats = (float *)deviceFloats1; hostFloats1[0] = 123; cuMemcpyHtoDAsync( (CUdeviceptr)(((float *)deviceFloats1)), hostFloats1, N * sizeof(float), stream ); getValue<<<dim3(1,1,1), dim3(32,1,1), 0, stream>>>(mystruct, ((float *)deviceFloats2) + 0); // now copy back entire buffer // hostFloats[64] = 0.0f; cuMemcpyDtoHAsync(hostFloats2, deviceFloats2, N * sizeof(float), stream); cuStreamSynchronize(stream); // and check the values... cout << hostFloats2[0] << endl; assert(hostFloats2[0] == 126); cuMemFreeHost(hostFloats1); cuMemFreeHost(hostFloats2); cuMemFree(deviceFloats1); cuMemFree(deviceFloats2); // cuStreamDestroy(stream); } void test2(CUstream &stream) { int N = 1024; float *hostFloats1; float *hostFloats2; float *hostFloats3; float *hostFloats4; cuMemHostAlloc((void **)&hostFloats1, N * sizeof(float), CU_MEMHOSTALLOC_PORTABLE); cuMemHostAlloc((void **)&hostFloats2, N * sizeof(float), CU_MEMHOSTALLOC_PORTABLE); cuMemHostAlloc((void **)&hostFloats3, N * sizeof(float), CU_MEMHOSTALLOC_PORTABLE); cuMemHostAlloc((void **)&hostFloats4, N * sizeof(float), CU_MEMHOSTALLOC_PORTABLE); CUdeviceptr deviceFloats1; CUdeviceptr deviceFloats2; CUdeviceptr deviceFloats3; CUdeviceptr deviceFloats4; cuMemAlloc(&deviceFloats1, N * sizeof(float)); cuMemAlloc(&deviceFloats2, N * sizeof(float)); cuMemAlloc(&deviceFloats3, N * sizeof(float)); cuMemAlloc(&deviceFloats4, N * sizeof(float)); MyStruct2 mystruct; mystruct.floats1 = (float *)deviceFloats1; mystruct.floats2 = (float *)deviceFloats2; hostFloats1[0] = 123; hostFloats2[0] = 333; cuMemcpyHtoDAsync( (CUdeviceptr)(((float *)deviceFloats1)), hostFloats1, N * sizeof(float), stream ); cuMemcpyHtoDAsync( (CUdeviceptr)(((float *)deviceFloats2)), hostFloats2, N * sizeof(float), stream ); getValue2<<<dim3(1,1,1), dim3(32,1,1), 0, stream>>>(mystruct, (float *)deviceFloats3, (float *)deviceFloats4); cuMemcpyDtoHAsync(hostFloats3, deviceFloats3, N * sizeof(float), stream); cuMemcpyDtoHAsync(hostFloats4, deviceFloats4, N * sizeof(float), stream); cuStreamSynchronize(stream); // and check the values... cout << "hostFloats3[0] " << hostFloats3[0] << endl; cout << "hostFloats4[0] " << hostFloats4[0] << endl; assert(hostFloats3[0] == 126); assert(hostFloats4[0] == 338); cuMemFreeHost(hostFloats1); cuMemFreeHost(hostFloats2); cuMemFreeHost(hostFloats3); cuMemFreeHost(hostFloats4); cuMemFree(deviceFloats1); cuMemFree(deviceFloats2); cuMemFree(deviceFloats3); cuMemFree(deviceFloats4); } int main(int argc, char *argv[]) { CUstream stream; cuStreamCreate(&stream, 0); // test1(stream); test2(stream); cuStreamDestroy(stream); return 0; }
1,437
#include <cuda.h> #include <cuda_runtime.h> #include <stdio.h> #include <stdlib.h> #define N 512 #define CLUSTER 10 __global__ void histrogram_atomic(int* d_a, int* d_b){ int threadId = threadIdx.x + blockIdx.x * blockDim.x; if (threadId < N) { int val = d_a[threadId]; //atomicAdd(&(d_b[val]), 1);// 原子操作+1 d_b[val]++; __syncthreads(); } } __global__ void histogram_shared(int* d_a, int* d_b){ int threadId = threadIdx.x + blockIdx.x * blockDim.x; __shared__ int shr[CLUSTER]; shr[threadIdx.x] = 0; __syncthreads(); if(threadId < N){ atomicAdd(&(shr[d_a[threadId]]), 1);// 原子操作+1 } __syncthreads(); atomicAdd(&(d_b[threadIdx.x]), shr[threadIdx.x]); } int main(){ int sizeByte = N*sizeof(int); int* h_a = (int*) malloc(sizeByte); int* h_b = (int*) malloc(CLUSTER*sizeof(int)); int* h_b_shared = (int*) malloc(CLUSTER*sizeof(int)); int* ref = (int *) malloc(CLUSTER*sizeof(int)); for(int i=0;i<N;i++){ h_a[i] = i%CLUSTER; } for(int i=0;i<CLUSTER;i++){ h_b[i] = 0; h_b_shared[i] = 0; ref[i] = 0; } //allocate device memory int *d_a, *d_b, *d_b_shared; cudaMalloc(&d_a, sizeByte); cudaMalloc(&d_b, CLUSTER*sizeof(int)); cudaMalloc(&d_b_shared, CLUSTER*sizeof(int)); //Memory copy: host ->> device cudaMemcpy(d_a, h_a, sizeByte, cudaMemcpyHostToDevice); cudaMemcpy(d_b, h_b, CLUSTER*sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(d_b_shared, h_b_shared, CLUSTER*sizeof(int), cudaMemcpyHostToDevice); cudaEvent_t start,stop; cudaEventCreate(&start); cudaEventCreate(&stop); cudaEventRecord(start, 0); histrogram_atomic<<<1,512>>>(d_a,d_b); cudaEventRecord(stop, 0); //copy result: device ->> host cudaMemcpy(h_b, d_b, CLUSTER*sizeof(int), cudaMemcpyDeviceToHost); float time_atomic = 0; cudaEventElapsedTime(&time_atomic, start, stop); printf("Time consumption(Atomic):%lf\n", time_atomic); //using shared memory cudaEventRecord(start, 0); histogram_shared<<<60,10>>>(d_a,d_b_shared); cudaEventRecord(stop, 0); cudaMemcpy(h_b_shared, d_b_shared, CLUSTER*sizeof(int), cudaMemcpyDeviceToHost); float time_shared = 0; cudaEventElapsedTime(&time_shared, start, stop); printf("Time consumption(Shared):%lf\n", time_shared); cudaEventDestroy(stop); cudaEventDestroy(start); //check for(int i=0;i<N;i++){ ref[h_a[i]]++; } for(int i=0;i<CLUSTER;i++){ //if(h_b[i]!=ref[i]){ printf("Ref(%d) Atomic(%d) Shared(%d)\n", ref[i],h_b[i],h_b_shared[i]); //return -1; //} } cudaFree(d_a); cudaFree(d_b); free(h_a); free(h_b); return 0; }
1,438
/** * Sum two square matrix (A = B + C) * Exercise 3.1 of programming massively parallel processors book * Solution provided with matrix view as array * @author Niccolò Bellaccini */ #include <cuda.h> #include <stdio.h> #include <stdlib.h> //rand #include <time.h> //rand #include <math.h> //ceil #include <iostream> //std::cerr #define BLOCK_WIDTH 64 void initData(float* M, int nRows){ //Remeber: matrix square for (int i=0; i<nRows; i++){ for(int j=0; j<nRows; j++){ M[nRows * i + j] = (float) (rand() & 0xFF) / 10.0f; } } } void displayData(float *M, int nRows){ for (int i=0; i<nRows; i++){ printf("\n"); for(int j=0; j<nRows; j++){ printf("%.1f\t", M[nRows * i + j]); } } } /** * function-like macro * __LINE__ = contains the line number of the currently compiled line of code * __FILE__ = string that contains the name of the source file being compiled * # operator = turns the argument it precedes into a quoted string * Reference: [C the complete reference] * check with > nvcc -E */ #define CUDA_CHECK_RETURN(value) CheckCudaErrorAux(__FILE__, __LINE__, #value, value) static void CheckCudaErrorAux (const char *file, unsigned line, const char *statement, cudaError_t err){ if(err == cudaSuccess) return; std::cerr << statement << " returned " << cudaGetErrorString(err) << "(" << err << ") at " << file << ":" << line << std::endl; exit(1); } //Kernel function (point b of exercise) __global__ void matrixAddKernel(float *A, float *B, float *C, int nRows){ int size = nRows * nRows; //Remember: square matrices int i = threadIdx.x + blockDim.x * blockIdx.x; if (i<size) A[i] = B[i] + C[i]; } //Kernel function (point c of exercise) __global__ void matrixPerRowsAddKernel(float *A, float *B, float *C, int nRows){ int i = threadIdx.x + blockDim.x * blockIdx.x; if (i<nRows){ for (int j=0; j<nRows; j++){ A[i * nRows + j] = B[i * nRows + j] + C[i * nRows + j]; } } } //Kernel function (point d of exercise) __global__ void matrixPerColumnsAddKernel(float *A, float *B, float *C, int nColumns){ int i = threadIdx.x + blockDim.x * blockIdx.x; if (i<nColumns){ for (int j=0; j<nColumns; j++){ A[i + j * nColumns] = B[i + j * nColumns] + C[i + j * nColumns]; } } } /** * Stub function used to compute matrices sum. * (function used to launch the kernel and to allocate device mem, ...) */ void matrixAdd(float* A, float *B, float *C, int nRows){ size_t size = nRows * nRows * sizeof(float); float * d_A; float * d_B; float * d_C; //Allocate device memory for matrices CUDA_CHECK_RETURN(cudaMalloc((void **) &d_B, size)); CUDA_CHECK_RETURN(cudaMalloc((void **) &d_C, size)); CUDA_CHECK_RETURN(cudaMalloc((void **) &d_A, size)); //Copy B and C to device memory CUDA_CHECK_RETURN(cudaMemcpy(d_B, B, size, cudaMemcpyHostToDevice)); CUDA_CHECK_RETURN(cudaMemcpy(d_C, C, size, cudaMemcpyHostToDevice)); //Kernel launch code //assume block of 64 threads matrixAddKernel <<< ceil((double)(nRows*nRows)/BLOCK_WIDTH), BLOCK_WIDTH>>>(d_A, d_B, d_C, nRows); //Two other possible kernel functions //matrixPerRowsAddKernel<<< ceil((double)nRows/BLOCK_WIDTH) ,BLOCK_WIDTH>>>(d_A, d_B, d_C, nRows); //matrixPerColumnsAddKernel<<< ceil((double)nRows/BLOCK_WIDTH) ,BLOCK_WIDTH>>>(d_A, d_B, d_C, nRows); //Copy A from the device memory CUDA_CHECK_RETURN(cudaMemcpy(A, d_A, size, cudaMemcpyDeviceToHost)); //Free device matrices cudaFree(d_C); cudaFree(d_B); cudaFree(d_A); } int main(int argc, char** argv){ //Initialize random seed //@see http://www.cplusplus.com/reference/cstdlib/srand/ //@see https://stackoverflow.com/questions/20158841/my-random-number-generator-function-generates-the-same-number srand(time(NULL)); int numRows; printf("\nInsert the number of rows (equivalently columns): "); scanf("%d", &numRows); int numColumns = numRows; //Square matrix int nElem = numRows * numColumns; float * B = (float *) malloc(nElem * sizeof(float)); float * C = (float *) malloc(nElem * sizeof(float)); float * A = (float *) malloc(nElem * sizeof(float)); //Initialize B and C matrices initData(B, numRows); initData(C, numRows); //Display B and C matrices printf("\n\tMatrice B\n"); displayData(B, numRows); printf("\n\n\tMatrice C\n"); displayData(C, numRows); //matrices sum matrixAdd(A, B, C, numRows); //Display A matrix printf("\n\n\tMatrice A\n"); displayData(A, numRows); }
1,439
#include <stdio.h> int reduceByHost(int *a, int n){ int sum = 0; for(int i = 0; i < n; i++){ sum += a[i]; } return sum; } /* a0 -- a1 -- a2 -- a3 -- a4 -- a5 -- a6 -- a7 :step0 -- b0 -------- b1 -------- b2 ---------b3 -- :step1 ---------c0 -------- c1 ---------c2--------- :step2 ---------------d0-----------d1-------------- :step3 ----------------------e0-------------------- :step4 max blocksize -> kich thuoc toi da cua 1 block __syncthread() : dong bo hoa tat ca thread trong 1 block */ __global__ void reduceByDevice(int *a, int n){ }
1,440
#include "includes.h" __global__ void kernel_histo_iterated( unsigned int *ct, unsigned int *histo, unsigned int offset ){ extern __shared__ unsigned int temp[]; unsigned int index = threadIdx.x + offset; temp[index] = 0; __syncthreads(); int i = threadIdx.x + blockIdx.x * blockDim.x; unsigned int size = blockDim.x * gridDim.x; unsigned int max = constant_n_hits*constant_n_test_vertices; while( i < max ){ atomicAdd( &temp[ct[i]], 1); i += size; } __syncthreads(); atomicAdd( &(histo[index]), temp[index] ); }
1,441
#include <stdio.h> /* Host = CPU stuff Device = GPU Stuff */ __global__ void mykernel(void){ /*global indicates a function that runs on device called from host */ } int main(void) { mykernel<<<1,1>>>(); //Calls from host to device printf("hello world! \n"); return 0; }
1,442
#include "includes.h" extern "C" { } #define IDX2C(i, j, ld) ((j)*(ld)+(i)) #define SQR(x) ((x)*(x)) // x^2 __global__ void multiply_arrays(double* signals, double const* weights){ signals[blockIdx.x * blockDim.x + threadIdx.x] *= weights[blockIdx.x * blockDim.x + threadIdx.x]; }
1,443
// // Created by harish on 10.03.21. // #include "cudaData.cuh" #include <iostream> using namespace std; int* cudaData::getData(int dataSize,int* hostData) { int* deviceVec; cudaMallocManaged(&deviceVec,dataSize*sizeof(int)); cudaMemcpy(deviceVec, hostData, dataSize*sizeof (int),cudaMemcpyHostToDevice); return deviceVec; } int* cudaData::copyHostToDevice(int* deviceVec, int* hostData, int dataSize){ cudaMemcpy(deviceVec, hostData, dataSize*sizeof (int),cudaMemcpyHostToDevice); return deviceVec; } int* cudaData::allocateGpuMemory(int dataSize, int* hostData){ int* deviceVec; cudaMalloc(&deviceVec,dataSize*sizeof(int)); return deviceVec; } int* cudaData::getHostData(int dataSize,int* devData) { int* hostData = (int*)malloc(sizeof (int)*dataSize); cudaMemcpy(hostData,devData, sizeof(int)*dataSize,cudaMemcpyDeviceToHost); return hostData; }
1,444
#include <stdio.h> #include <stdlib.h> #define TPB 512 __global__ void oddPopulate(int *A, int *O, int n, int *numOdds){ __shared__ int odds; if(threadIdx.x){ odds = 0; } __syncthreads(); int index = blockIdx.x * blockDim.x + threadIdx.x; if(index < n){ if(A[index] % 2 == 0){ O[index] = 0; } else{ O[index] = 1; atomicAdd(&odds, 1); } } if(threadIdx.x == 0){ atomicAdd(numOdds, odds); } } __global__ void upwardSweep(int *temp, int *c, int d, int n){ int index = threadIdx.x + blockIdx.x * blockDim.x; if(index < n){ if(index >= d){ temp[index] = c[index-d]; } else{ temp[index] = 0; } } } __global__ void downwardSweep(int *temp, int *c, int n){ int index = threadIdx.x + blockIdx.x * blockDim.x; if(index < n){ c[index] = c[index] + temp[index]; } } __global__ void fillOddArray(int *D, int *sums, int *A, int n){ int index = blockIdx.x * blockDim.x + threadIdx.x; if(index < n){ if(A[index]%2 == 1){ D[sums[index] - 1] = A[index]; } } } int main(int argc, char ** argv){ FILE *fp; char word[255]; int N = 0; fp = fopen("inp.txt", "r"); if (fp == NULL){ return -1; } while (fscanf(fp, "%*s ", word) != EOF) { //this one works N++; } if(N == 0){ return -1; } fclose(fp); fp = fopen("inp.txt", "r"); if (fp == NULL){ return -1; } int A[N]; fscanf(fp, "%d", &A[0]); int idx = 1; while(idx < N){ fscanf(fp, ", %d", &A[idx]); idx++; } int odds[1]; int O[N]; int *d_A; int *d_O; int *d_numOdds; int A_size = sizeof(int)*N; int O_size = sizeof(int)*N; int odds_size = sizeof(int)*1; cudaMalloc((void **) &d_A, A_size); cudaMalloc((void **) &d_O, O_size); cudaMalloc((void **) &d_numOdds, odds_size); cudaMemcpy(d_A, A, A_size, cudaMemcpyHostToDevice); cudaMemcpy(d_numOdds, odds, odds_size, cudaMemcpyHostToDevice); oddPopulate<<<(N + TPB - 1)/TPB, TPB>>>(d_A, d_O, N, d_numOdds); cudaMemcpy(O, d_O, O_size, cudaMemcpyDeviceToHost); cudaMemcpy(odds, d_numOdds, odds_size, cudaMemcpyDeviceToHost); cudaFree(d_A); cudaFree(d_O); cudaFree(d_numOdds); int *d_OSum; int *d_temp; int temp_size = N*sizeof(int); cudaMalloc((void **) &d_OSum, temp_size); cudaMalloc((void **) &d_temp, temp_size); cudaMemcpy(d_OSum, O, temp_size, cudaMemcpyHostToDevice); int x = 1; while(x < N) { upwardSweep<<<(N + TPB - 1)/TPB, TPB>>>(d_temp, d_OSum, x, N); downwardSweep<<<(N + TPB - 1)/TPB, TPB>>>(d_temp, d_OSum, N); x *= 2; } cudaFree(d_temp); int D[odds[0]]; int *d_D; int *d_Nums; cudaMalloc((void **) &d_D, odds[0]*sizeof(int)); cudaMalloc((void **) &d_Nums, N*sizeof(int)); cudaMemcpy(d_Nums, A, N*sizeof(int), cudaMemcpyHostToDevice); fillOddArray<<<(N + TPB - 1)/TPB, TPB>>>(d_D, d_OSum, d_Nums, N); cudaMemcpy(D, d_D, odds[0]*sizeof(int), cudaMemcpyDeviceToHost); cudaFree(d_Nums); cudaFree(d_D); cudaFree(d_OSum); fp = fopen("q3.txt","w+"); fputs("[",fp); for(int i = 0; i < odds[0]; i++){ snprintf(word, sizeof(word), "%d", D[i]); fputs(word,fp); if(i != odds[0] - 1) fputs(", ",fp); } fputs("]",fp); fclose(fp); return 0; }
1,445
extern __device__ void BiAverage(double *A, double *B, int p0, int datasize, int logsize) { int stride = datasize; for (int q = 1; q <= logsize; q++) { stride = stride >> 1; if (p0 < stride) { A[p0] += A[p0 + stride]; } else { if (p0 < 2 * stride) { B[p0 - stride] += B[p0]; } } __syncthreads(); } }
1,446
/* * Written by Sangho Lee (sangho@gatech.edu) */ #include <stdio.h> #include <unistd.h> #include <stdint.h> #define SIZE 2*1024*1024*1024 // 1 GiB // Tesla has 2687 MiB of Global Memory void cudasafe(cudaError_t error, char *message) { if (error != cudaSuccess) { fprintf(stderr, "ERROR: %s : %s\n", message, cudaGetErrorString(error)); exit(-1); } } //const int N = 14; const int N = 1; // a 1024-bit random sequence unsigned int uniq_key[32] = { 0x63636363U, 0x7c7c7c7cU, 0x77777777U, 0x7b7b7b7bU, 0xf2f2f2f2U, 0x6b6b6b6bU, 0x6f6f6f6fU, 0xc5c5c5c5U, 0x30303030U, 0x01010101U, 0x67676767U, 0x2b2b2b2bU, 0xfefefefeU, 0xd7d7d7d7U, 0xababababU, 0x76767676U, 0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU, 0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU, 0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU, 0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U }; __global__ void foobar(unsigned int *a) { int i = blockIdx.x; printf("aaaa\n"); } int main() { size_t memsize = 2752249856; // best for tesla //size_t memsize = 2093219840; // best for kepler unsigned int *a; a = (unsigned int*)malloc(memsize); // 128 B random number for (int i = 0; i < memsize/4; i += 32) { for (int j = 0; j < 32; ++j) { a[i+j] = uniq_key[j]; } } unsigned int *d_a; cudasafe(cudaMalloc((void**)&d_a, memsize), "cudaMalloc"); cudasafe(cudaMemcpy(d_a, a, memsize, cudaMemcpyHostToDevice), "cudaMemcpy"); // fill GPU memory with a predefined value cudaFree(d_a); // deallocate it!! size_t free_old, free, total; cudaMemGetInfo(&free_old, &total); while (1) { cudaMemGetInfo(&free, &total); fprintf(stderr, "Waiting for victim -- Free/Total: %llu/%llu\n", free, total); if (free_old == free) { usleep(10*1000); } else { fprintf(stderr, "victim comes!!\n"); break; } } // while (1) for (int i = 0; i < 10000; ++i) { cudaMemGetInfo(&free, &total); fprintf(stderr, "Waiting for victim's out -- Free/Total: %llu/%llu\n", free, total); if (free_old != free) { usleep(10*1000); } else { fprintf(stderr, "victim out!!\n"); break; } } while (cudaMalloc((void**)&d_a, memsize) != cudaSuccess) { fprintf(stderr,"%u\n", memsize); memsize -= 4; } fprintf(stderr,"cudaMalloc(): %u\n", memsize); cudasafe(cudaMemcpy(a, d_a, memsize, cudaMemcpyDeviceToHost), "cudaMemcpy"); fprintf(stderr,"cudaMemcpy()\n"); fprintf(stderr, "Memory dump...\n"); const int nobytes = 32; unsigned int buf[nobytes]; for (size_t i=0; i < memsize/4; i += nobytes) { int j; for (j=0; j < nobytes; ++j) { buf[j] = a[i+j]; } for (j=0; j < nobytes; ++j) { //if (buf[j] != 0x12345678) if (buf[j] != uniq_key[j]) break; } if (j != nobytes) { for (int k=0; k < nobytes; ++k) { printf("%08x\n", buf[k]); } } } fprintf(stderr, "Done...\n"); cudaFree(d_a); cudaDeviceSynchronize(); cudaDeviceReset(); return EXIT_SUCCESS; }
1,447
#include <time.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> // cache size constant for convenience/readability const size_t CACHESIZE = 1.5 * (1<<20); // function to handle CUDA API call error val returns void check_error(cudaError_t cudaerr) { if (cudaerr != cudaSuccess) { printf("FAILED WITH ERROR: \"%s\".\n", cudaGetErrorString(cudaerr)); exit(-1); } } // hammer attempt test kernel __global__ void hammer_attempt(int* data, int* indices, int* eviction, int iterations, int numvals, int stride) { uint tid = threadIdx.x + blockIdx.x * blockDim.x; uint nthreads = blockDim.x * gridDim.x; int sum; for (int j = 0; j < iterations; j++) { if (tid < 8) { int index = indices[tid]; int n = data[index]; sum += (n << 1); } /* if (tid == 0) { int n1 = data[1413]; int n2 = data[56102]; int n3 = data[101336]; int n4 = data[169659]; int n5 = data[199685]; int n6 = data[272110]; int n7 = data[309174]; int n8 = data[368505]; sum = sum + n1 - n2 + n3 - n4 + n5 - n6 + n7 - n8; } */ //__syncthreads(); for (int i = (tid * stride) + 393216; i < 393216*2.5; i += (nthreads * stride)) { int n = data[i]; sum -= (n >> 1); // __syncthreads(); } /* for (int i = 393216; i < 393216*3; i+=8) { int n = data[i]; sum -= (n >> 1); } */ /* for (int i = tid; i < numvals; i += nthreads) { int n = data[eviction[i]]; sum -= (n >> 1); } */ } } int main(int argc, char** argv) { // command line params, seed rand int blocks = atoi(argv[1]); int threads = atoi(argv[2]); int stride = atoi(argv[3]); int iterations = atoi(argv[4]); srand(time(NULL)); // host array of random vals int* data_host = (int*) malloc(2.5*CACHESIZE); for (int i = 0; i < (2.5*CACHESIZE)/4; i++) { data_host[i] = rand(); } // copy to device int* data_device; check_error(cudaMalloc((void**)&data_device, 2.5*CACHESIZE)); check_error(cudaMemcpy(data_device, data_host, 2.5*CACHESIZE, cudaMemcpyHostToDevice)); // host array for addresses // pick addresses in first 1.5MB of data // - explanation of values - // 393216: number of integers containted in 1.5MB cache // 49512: number of integers in a 1/8 slice of cache // 24576: number of integers in a 1/16 slice of cache // address choosing process: pick address in first 1/16, skip next 1/16, pick address in next 1/16... int* indices_host = (int*)malloc(sizeof(int)*8); for (int i = 0; i < 8; i++) { int sector_start = i * 49512; indices_host[i] = (rand() % 24576) + sector_start; printf("%d\n", indices_host[i]); } // copy to device int* indices_device; check_error(cudaMalloc((void**)&indices_device, sizeof(int)*8)); check_error(cudaMemcpy(indices_device, indices_host, sizeof(int)*8, cudaMemcpyHostToDevice)); // host array of indices for eviction purposes int numvals = (393216*2) / stride; int* eviction_host = (int*)malloc(sizeof(int)*numvals); for (int i = 0; i < numvals; i++) { eviction_host[i] = 393216 + (i * stride); } // copy to device int* eviction_device; check_error(cudaMalloc((void**)&eviction_device, sizeof(int)*numvals)); check_error(cudaMemcpy(eviction_device, eviction_host, sizeof(int)*numvals, cudaMemcpyHostToDevice)); // launch kernel hammer_attempt<<<blocks, threads>>>(data_device, indices_device, eviction_device, iterations, numvals, stride); check_error(cudaDeviceSynchronize()); }
1,448
#include "includes.h" __global__ void matrixMultiplyShared(float * A, float * B, float * C, int numARows, int numAColumns, int numBRows, int numBColumns, int numCRows, int numCColumns) { __shared__ float sA[TILE_SIZE][TILE_SIZE]; // Tile size to store elements in shared memory __shared__ float sB[TILE_SIZE][TILE_SIZE]; int Row = blockDim.y*blockIdx.y + threadIdx.y; //To generate ids of threads. int Col = blockDim.x*blockIdx.x + threadIdx.x; float Cvalue = 0.0; sA[threadIdx.y][threadIdx.x] = 0.0; sB[threadIdx.y][threadIdx.x] = 0.0; for (int k = 0; k < (((numAColumns - 1)/ TILE_SIZE) + 1); k++) { if ( (Row < numARows) && (threadIdx.x + (k*TILE_SIZE)) < numAColumns)//Copy Data to Tile from Matrix (Global Memory to Shared Memory) { sA[threadIdx.y][threadIdx.x] = A[(Row*numAColumns) + threadIdx.x + (k*TILE_SIZE)]; } else { sA[threadIdx.y][threadIdx.x] = 0.0; } if ( Col < numBColumns && (threadIdx.y + k*TILE_SIZE) < numBRows)//Copy Data to Tile from Matrix (Global Memory to Shared Memory) { sB[threadIdx.y][threadIdx.x] = B[(threadIdx.y + k*TILE_SIZE)*numBColumns + Col]; } else { sB[threadIdx.y][threadIdx.x] = 0.0; } __syncthreads(); for (int j = 0; j < TILE_SIZE; ++j)//Multiplying Elements present in tile { Cvalue += sA[threadIdx.y][j] * sB[j][threadIdx.x]; } } if (Row < numCRows && Col < numCColumns)//Saving Final result into Matrix C { C[Row*numCColumns + Col] = Cvalue; } }
1,449
// Created 25-Jan-2014 by Daniel Margala (University of California, Irvine) <dmargala@uci.edu> #include <iostream> int main(int argc, char **argv) { int deviceCount; cudaGetDeviceCount(&deviceCount); if (deviceCount == 0) { std::cout << "No CUDA GPU has been detected" << std::endl; return -1; } else { std::cout << "Number CUDA GPU devices detected: " << deviceCount << std::endl; } for (int dev = 0; dev < deviceCount; dev++) { cudaDeviceProp deviceProp; cudaGetDeviceProperties(&deviceProp, dev); std::cout << "Device " << dev << " name: " << deviceProp.name << std::endl; std::cout << " Computational Capabilities: " << deviceProp.major << "." << deviceProp.minor << std::endl; std::cout << " Maximum global memory size: " << deviceProp.totalGlobalMem << std::endl; std::cout << " Maximum constant memory size: " << deviceProp.totalConstMem << std::endl; std::cout << " Maximum shared memory size per block: " << deviceProp.sharedMemPerBlock << std::endl; std::cout << " Maximum block dimensions: " << deviceProp.maxThreadsDim[0] << " x " << deviceProp.maxThreadsDim[1] << " x " << deviceProp.maxThreadsDim[2] << std::endl; std::cout << " Maximum grid dimensions: " << deviceProp.maxGridSize[0] << " x " << deviceProp.maxGridSize[1] << " x " << deviceProp.maxGridSize[2] << std::endl; std::cout << " Warp size: " << deviceProp.warpSize << std::endl; } return 0; }
1,450
/* objective * C = A*B // A[m][k], B[k][n], C[m][n] * compile: nvcc --gpu-architecture=compute_60 --gpu-code=sm_60 -O3 matmul_double.cu -o matmul_double */ #include <iostream> #include <cstdlib> #include <math.h> # define BLK_SIZE 4 #define EC(ans) { chkerr((ans), __FILE__, __LINE__); } inline void chkerr(cudaError_t code, const char *file, int line) { if (code != cudaSuccess) { std::cerr << "ERROR!!!:" << cudaGetErrorString(code) << " File: " << file << " Line: " << line << '\n'; exit(-1); } } void init (double *A, double *B, int M , int N, int K) { for (int i = 0; i < M; ++i) { for (int j = 0; j < K; ++j) { A[i * K + j] = 1; //i * K + j; } } for (int i = 0; i < N; ++i) { for (int j = 0; j < K; ++j) { B[i * K + j] = 1; //i * N + j + 1; } } } void matmul_double_host(double* A, double* B, double* C, int M, int N, int K) { for (int i = 0; i < M; ++i) { for (int j = 0; j < N; ++j) { double tmp = 0; for (int k = 0; k < K; ++k) { tmp += A[i * K + k] * B[j * K + k]; } C[i * N + j] = tmp; } } } void validate (double *host, double *gpu, int M, int N) { for (int i = 0; i < M; ++i) { for (int j = 0; j < N; ++j) { if(std::abs(host[i * N + j] - gpu[i * N + j]) > 1e-3) { std::cerr << "possible error at position " << i << ',' << j << " host: " << host[i * N + j] << " device " << gpu[i * N + j] << '\n'; } } } } __global__ void matmul_double(double* A, double* B , double* C, int M, int N, int K) { int bx = blockIdx.x; int by = blockIdx.y; int tx = threadIdx.x; int ty = threadIdx.y; int row = by * blockDim.y + ty; int col = bx * blockDim.x + tx; //if(row >= M || col >= N) // return; __shared__ float SA[BLK_SIZE][BLK_SIZE]; __shared__ float SB[BLK_SIZE][BLK_SIZE]; double temp = 0; int klimit = K + BLK_SIZE - 1; for(int tilek=0;tilek<klimit;tilek+=BLK_SIZE){ if(tilek + tx < K && row < M) SA[ty][tx] = A[row*K + (tilek + tx)]; else SA[ty][tx] = 0.0; if((bx*BLK_SIZE+ty)<N && tx+tilek < K) SB[ty][tx] = B[(bx*BLK_SIZE+ty)*K+(tx+tilek)]; else SB[ty][tx] = 0.0; __syncthreads(); for(int i=0;i<BLK_SIZE;i++){ temp+= SA[ty][i] * SB[tx][i]; } __syncthreads(); } if(row < M && col <N){ int id = row * N + col; C[id] = temp; } } int main(int argc, char *argv[]) { if(argc < 3) { std::cerr << "Usage: ./matmul_double M N K\n"; exit(-1); } int M = std::atoi(argv[1]); int N = std::atoi(argv[2]); int K = std::atoi(argv[3]); /* Host alloc */ double *hA = (double*) malloc (M * K * sizeof(double)); double *hB = (double*) malloc (K * N * sizeof(double)); double *hC = (double*) malloc (M * N * sizeof(double)); double *dtohC = (double*) malloc (M * N * sizeof(double)); /* Device alloc */ double *dA, *dB, *dC; cudaMalloc((void**) &dA, M*K*sizeof(double)); cudaMalloc((void**) &dB, K*N*sizeof(double)); cudaMalloc((void**) &dC, M*N*sizeof(double)); /* Initialize host memory*/ init(hA, hB, M, N, K); /* host compute */ matmul_double_host(hA, hB, hC, M, N, K); /* Copy from host to device */ cudaMemcpy(dA, hA, M*K*sizeof(double), cudaMemcpyHostToDevice); cudaMemcpy(dB, hB, K*N*sizeof(double), cudaMemcpyHostToDevice); /* call gpu kernel */ dim3 threads(BLK_SIZE, BLK_SIZE); dim3 grid(ceil(N/float(BLK_SIZE)),ceil(M/float(BLK_SIZE))); printf("Number of threads in a block %dx%d\n",(int)BLK_SIZE, (int)BLK_SIZE); printf("Number of blocks in a grid %dx%d\n",(int)ceil(N/float(BLK_SIZE)),(int)ceil(M/float(BLK_SIZE))); matmul_double<<<grid, threads>>>(dA, dB, dC, M, N, K); std::cerr << cudaGetErrorString(cudaGetLastError()) << std::endl; /* Copy from device to host (dC -> dtohC) */ cudaMemcpy(dtohC, dC, M*N*sizeof(double), cudaMemcpyDeviceToHost); /* host vs device validation */ validate(hC, dtohC, M, N); /* be clean */ free(hA); free(hB); free(hC); free(dtohC); /// add code to free gpu memory cudaFree(dA); cudaFree(dB); cudaFree(dC); return 0; }
1,451
#include <malloc.h> #include <string.h> #include <stdio.h> #include <vector> #include <fstream> #include <iostream> using namespace std; #include <cufft.h> #define BATCH 1 //размер данных для обработки #define CUDA_CHECK_RETURN(value) {\ cudaError_t _m_cudaStat = value;\ if (_m_cudaStat != cudaSuccess) {\ fprintf(stderr, "Error \"%s\" at line %d in file %s\n",\ cudaGetErrorString(_m_cudaStat), __LINE__, __FILE__);\ exit(1);\ }\ } //макрос для обработки ошибок #define CUFFT_CHECK_RETURN(value) {\ cufftResult stat = value;\ if (stat != CUFFT_SUCCESS) {\ fprintf(stderr, "Error at line %d in file %s\n",\ __LINE__, __FILE__);\ exit(1);\ }\ } //макрос для обработки ошибок int main(void) { string line, buffer; cufftHandle plan; //дескриптор плана конфигурации (нужен для оптимизации под выбранную аппаратуру) cufftComplex *hos_data, *dev_data; //массивы для комплексных чисел vector<string> file_string; //одна строка в файле = массив из 4 чисел в виде string vector<float> Wolf_nums; //числа Вольфа (весь диск) vector<float> freq; //массив частот после преобразования Фурье (на каждый день одно число) vector<float> power; //массив значений ^ 2 из преобразования Фурье ifstream in; for (int i = 1938; i <= 1991; i++) { //цикл по годам //открыть файл i-го года string path = string("data/w") + to_string(i) + string(".dat"); in.open(path); if (!in.is_open()) { fprintf(stderr, "can't open a file data/w%d.dat\n", i); return -1; } while(getline(in, line)) { //считать строку из файла buffer = ""; line += " "; //добавить пробел для обработки последнего числа for (int k = 0; k < line.size(); k++) { if (line[k] != ' ') { buffer += line[k]; //записать число посимвольно в buffer } else { //если пробел, то есть получено число в виде строки if (buffer != "") file_string.push_back(buffer); buffer = ""; } } if (file_string.size() != 0) { if (file_string[2] == "999") { //если число Вульфа неизвестно, file_string[2] = to_string(Wolf_nums.back()); //то взять предыдущее значение } Wolf_nums.push_back(stoi(file_string[2])); //преобразовать строку в число, добавить в массив чисел file_string.clear(); //очистить строку } } //end of while(getline(in, line)) in.close(); } //end of for(int i = 1938; i <= 1991; i++) int N = Wolf_nums.size(); cudaMalloc((void**)&dev_data, sizeof(cufftComplex) * N * BATCH); hos_data = new cufftComplex[N * BATCH]; for (int i = 0; i < N * BATCH; i++) { hos_data[i].x = Wolf_nums[i]; //действительная часть hos_data[i].y = 0.0f; //мнимая часть } cudaMemcpy(dev_data, hos_data, sizeof(cufftComplex) * N * BATCH, cudaMemcpyHostToDevice); //создание плана, преобразование Фурье происходит из комплексных чисел в комплексные: CUFFT_CHECK_RETURN(cufftPlan1d(&plan, N * BATCH, CUFFT_C2C, BATCH)); //совершить быстрое преобразование Фурье (FFT): CUFFT_CHECK_RETURN(cufftExecC2C(plan, dev_data, dev_data, CUFFT_FORWARD)); //синхронизация: CUDA_CHECK_RETURN(cudaDeviceSynchronize()); //копируем обратно на хост то, что получено после FFT: CUDA_CHECK_RETURN(cudaMemcpy(hos_data, dev_data, N * sizeof(cufftComplex), cudaMemcpyDeviceToHost)); power.resize(N / 2 + 1); for (int i = 1; i <= N / 2; i++) { //преобразовать значения, т.к. комплексные числа тяжело интерпретировать: power[i] = sqrt(hos_data[i].x * hos_data[i].x + hos_data[i].y * hos_data[i].y); } float max_freq = 0.5; //максимальная частота freq.resize(N / 2 + 1); for (int i = 1; i <= N / 2; i++) { //получаем равномерно распределенную сетку частот: freq[i] = 1 / (float(i) / float(N/2) * max_freq); } int maxind = 1; //найти максимальное значение for (int i = 1 ; i <= N / 2; i++) { if (power[i] > power[maxind]) maxind = i; } //freq[maxind] - это количество дней при максимальной частоте? printf("calculated periodicity = %f years\n", freq[maxind] / 365); cufftDestroy(plan); cudaFree(dev_data); free(hos_data); return 0; }
1,452
#include <stdio.h> #include <stdlib.h> #include <cuda.h> __global__ void kernelTest() { int i; i = 100; i = i - i + i; } extern "C" void testGpu() { printf("start test kernel...\n"); kernelTest<<<1, 1>>>(); printf("end of test lernel...\n"); }
1,453
#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <string.h> #include <cuda.h> #include "math.h" #include "time.h" #include <iostream> #include <fstream> #include <iomanip> #define BLOCK_SIZE 32 __global__ void kernel_global(float* a, float* b, int n, float* c) { int bx = blockIdx.x; // x int by = blockIdx.y; // y int tx = threadIdx.x; // x int ty = threadIdx.y; // y float sum = 0.0f; int ia = n * (BLOCK_SIZE * by + ty); // A int ib = BLOCK_SIZE * bx + tx; // B int ic = ia + ib; // ђ // C for (int k = 0; k < n; k++) sum += a[ia + k] * b[ib + k * n]; c[ic] = sum; } int main() { int N = 1024; int m, n, k; // - float timerValueGPU, timerValueCPU; cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); int numBytes = N * N * sizeof(float); float* adev, * bdev, * cdev, * a, * b, * bT, * c, * cc; // host a = (float*)malloc(numBytes); b = (float*)malloc(numBytes); // B bT = (float*)malloc(numBytes); // B c = (float*)malloc(numBytes); // GPU- cc = (float*)malloc(numBytes); // CPU- // A, B B for (n = 0; n < N; n++) { for (m = 0; m < N; m++) { a[m + n * N] = 2.0f * m + n; b[m + n * N] = m - n; bT[m + n * N] = n - m; } } // dim3 threads(BLOCK_SIZE, BLOCK_SIZE); dim3 blocks(N / threads.x, N / threads.y); // GPU cudaMalloc((void**)&adev, numBytes); cudaMalloc((void**)&bdev, numBytes); cudaMalloc((void**)&cdev, numBytes); // ---------------- GPU- ------------------------ // A B host device cudaMemcpy(adev, a, numBytes, cudaMemcpyHostToDevice); cudaMemcpy(bdev, b, numBytes, cudaMemcpyHostToDevice); // cudaEventRecord(start, 0); // - kernel_global <<<blocks, threads>>> (adev, bdev, N, cdev); // GPU- cudaThreadSynchronize(); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&timerValueGPU, start, stop); printf("\n GPU calculation time %f msec\n", timerValueGPU); // , C device host cudaMemcpy(c, cdev, numBytes, cudaMemcpyDeviceToHost); // -------------------- CPU- -------------------- // cudaEventRecord(start, 0); // C for (n = 0; n < N; n++) { for (m = 0; m < N; m++) { cc[m + n * N] = 0.f; for (k = 0; k < N; k++) cc[m + n * N] += a[k + n * N] * bT[k + m * N]; // bT !!! } } // CPU- cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&timerValueCPU, start, stop); printf("\n CPU calculation time %f msec\n", timerValueCPU); // printf("\n Rate %f x\n", timerValueCPU / timerValueGPU); // GPU CPU cudaFree(adev); cudaFree(bdev); cudaFree(cdev); cudaFreeHost(a); cudaFreeHost(b); cudaFreeHost(bT); cudaFreeHost(c); cudaFreeHost(cc); // - cudaEventDestroy(start); cudaEventDestroy(stop); return 0; }
1,454
#include <stdio.h> #include <stdlib.h> // Variables float* h_A; // host vectors float* h_C; float* d_A; // device vectors float* d_C; // Functions void RandomInit(float*, int); __global__ void FindMax(const float*, float*, int); // Host Code int main(){ // Settings // gid -> GPU device id (0, 1, ...) // err -> error message get from CUDA calls // N -> Length of an array // size -> memory size of the allocate array // sb -> memory size after handle by GPU // sm -> size of shared memory in each individual block // m -> the power of threadsPerBlock // threadsPerBlock, blocksPerGrid -> For launching kernel // // start, stop -> CUDA event timer // Intime -> Calculate the input time, allocate and move data in device memory // gputime -> Time spent in GPU only // Outime -> Time used to handle the rest of finding maximum // gputime_tot -> Time total spent // // max_value -> Maximum value inside this array, find by GPU // max_value_CPU -> Maximum value inside this array, find by CPU int gid; cudaError_t err; int N; int size, sb; int sm; int m, threadsPerBlock, blocksPerGrid; cudaEvent_t start, stop; float Intime, gputime, Outime, gputime_tot, cputime; float max_value = -2.0; float max_value_CPU = -2.0; // Select GPU device printf("Select the GPU with device ID: "); scanf("%d", &gid); err = cudaSetDevice(gid); if (err != cudaSuccess) { printf("!!! Cannot select GPU with device ID = %d\n", gid); exit(1); } printf("Set GPU with device ID = %d\n", gid); // Set the size of the vector printf("Find maximum value within one array:\n"); printf("Enter the length of an array: "); scanf("%d", &N); printf("Array length = %d\n", N); // Set blocksize and grid size printf("Enter the power (m) of threads per block (2^m): "); scanf("%d", &m); threadsPerBlock = pow(2, m); printf("Threads per block = %d\n", threadsPerBlock); if(threadsPerBlock > 1024){ printf("The number of threads per block must be less than 1024 (2^m , m <=10) ! \n"); exit(0); } printf("Enter the number of blocks per grid: "); scanf("%d",&blocksPerGrid); printf("Blocks per grid = %d\n", blocksPerGrid); if( blocksPerGrid > 2147483647 ) { printf("The number of blocks must be less than 2147483647 ! \n"); exit(0); } // Allocate input array size = N * sizeof(float); sb = blocksPerGrid * sizeof(float); h_A = (float*)malloc(size); h_C = (float*)malloc(sb); // Initialize input vectors RandomInit(h_A, N); // Create the timer cudaEventCreate(&start); cudaEventCreate(&stop); // Start the timer: Record allocate memory and move data, from host to device cudaEventRecord(start, 0); // Allocate the array in device memory cudaMalloc((void**)&d_A, size); cudaMalloc((void**)&d_C, sb); // Copy array from host to device memory cudaMemcpy(d_A, h_A, size, cudaMemcpyHostToDevice); // Stop the timer: Record allocate memory and move data, from host to device cudaEventRecord(stop, 0); cudaEventSynchronize(stop); // Calculate spend time: Record allocate memory and move data, from host to device cudaEventElapsedTime(&Intime, start, stop); printf("=================================\n"); printf("Allocate memory and move data from host to device time spent for GPU: %f (ms) \n", Intime); // start the timer cudaEventRecord(start, 0); // Called the kernel sm = threadsPerBlock * sizeof(float); FindMax <<< blocksPerGrid, threadsPerBlock, sm >>>(d_A, d_C, N); // stop the timer cudaEventRecord(stop, 0); cudaEventSynchronize(stop); // Calculate spend time: Matrix Addition calculation time cudaEventElapsedTime(&gputime, start, stop); printf("Time used for GPU: %f (ms) \n", gputime); // start the timer cudaEventRecord(start,0); // Copy result from device memory to host memory // h_C contains the result of each block in host memory cudaMemcpy(h_C, d_C, sb, cudaMemcpyDeviceToHost); cudaFree(d_A); cudaFree(d_C); for(int i = 0; i < blocksPerGrid; i = i+1){ if(h_C[i] > max_value){ max_value = h_C[i]; } } // stop the timer cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime( &Outime, start, stop); printf("Time used to handle the rest of finding maximum: %f (ms) \n", Outime); gputime_tot = Intime + gputime + Outime; printf("Total time for GPU: %f (ms) \n", gputime_tot); // start the timer cudaEventRecord(start,0); // Compute the reference solution for(int i = 0; i < N; i = i+1){ if(h_A[i] > max_value_CPU){ max_value_CPU = h_A[i]; } } // stop the timer cudaEventRecord(stop,0); cudaEventSynchronize(stop); cudaEventElapsedTime(&cputime, start, stop); printf("---------------------------------\n"); printf("Processing time for CPU: %f (ms) \n",cputime); printf("=================================\n"); printf("Speed up of GPU = %f\n", cputime/(gputime_tot)); // Destroy the timer cudaEventDestroy(start); cudaEventDestroy(stop); // Check the result printf("=================================\n"); printf("Check the result:\n"); printf("Maximum find by GPU = %.23f\n", max_value); printf("Maximum find by CPU = %.23f\n", max_value_CPU); free(h_A); free(h_C); cudaDeviceReset(); return 0; } __global__ void FindMax(const float* A, float* C, int N){ extern __shared__ float cache[]; int i = blockDim.x * blockIdx.x + threadIdx.x; int cacheIndex = threadIdx.x; float max = -2.0; while (i < N) { if(A[i] > max){ max = A[i]; } i = i + blockDim.x * gridDim.x; } cache[cacheIndex] = max; __syncthreads(); // Perform parallel reduction, threadsPerBlock must be 2^m int ib = blockDim.x/2; while (ib != 0) { if(cacheIndex < ib){ if(cache[cacheIndex] < cache[cacheIndex + ib]){ cache[cacheIndex] = cache[cacheIndex + ib]; } } __syncthreads(); ib = ib / 2; } if(cacheIndex == 0){ C[blockIdx.x] = cache[0]; } } // Allocates an array with random float entries in (-1,1) void RandomInit(float* data, int n){ for (int i = 0; i < n; ++i) data[i] = 2.0*rand()/(float)RAND_MAX - 1.0; }
1,455
#include "includes.h" __global__ void add(int*a, int*b, int*c) { c[blockIdx.x] = a[blockIdx.x] + b[blockIdx.x]; }
1,456
/* Copyright 2017 the arraydiff authors 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. */ #include <cuda_runtime_api.h> #include <stdint.h> #include <stdlib.h> __global__ void rect_fwd_kernel_f32( uint32_t dim, const float *x, float *y) { uint32_t idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { float x_i = x[idx]; y[idx] = x_i * (x_i > 0.0f); } } extern "C" void arraydiff_cuda_kernel_rect_fwd_f32( size_t dim, const float *x, float *y, cudaStream_t stream) { rect_fwd_kernel_f32<<<(dim+1024-1)/1024, 1024, 0, stream>>>( dim, x, y); } __global__ void rect_bwd_kernel_f32( uint32_t dim, const float *x, const float *dy, float *dx) { uint32_t idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { dx[idx] += dy[idx] * (x[idx] > 0.0f); } } extern "C" void arraydiff_cuda_kernel_rect_bwd_f32( size_t dim, const float *x, const float *dy, float *dx, cudaStream_t stream) { rect_bwd_kernel_f32<<<(dim+1024-1)/1024, 1024, 0, stream>>>( dim, x, dy, dx); }
1,457
#include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <list> #include <map> #include <sstream> #include <stdio.h> #include <string> #include <unordered_map> #include <vector> using namespace std; map<string, double> GetTwissHeader(string filename) { vector<string> TWISSHEADERKEYS /* */ { "MASS", "CHARGE", "ENERGY", "PC", "GAMMA", "KBUNCH", "BCURRENT", "SIGE", "SIGT", "NPART", "EX", "EY", "ET", "BV_FLAG", "LENGTH", "ALFA", "ORBIT5", "GAMMATR", "Q1", "Q2", "DQ1", "DQ2", "DXMAX", "DYMAX", "XCOMAX", "YCOMAX", "BETXMAX", "BETYMAX", "XCORMS", "YCORMS", "DXRMS", "DYRMS", "DELTAP", "SYNCH_1", "SYNCH_2", "SYNCH_3", "SYNCH_4", "SYNCH_5"}; map<string, double> out; string line; ifstream file(filename); vector<int> labels; map<int, int> colmap; getline(file, line); // check if file is open if (file.is_open()) { // printf("File is open. Reading Twiss header.\n"); // read lines until eof int counter = 0; string key; string at; double value; while (!file.eof() && counter < 41) { counter++; getline(file, line); istringstream iss(line); iss >> at >> key >> at >> value; vector<string>::iterator it = find(TWISSHEADERKEYS.begin(), TWISSHEADERKEYS.end(), key); // cout << key << " " << value << " " << endl; if (it != TWISSHEADERKEYS.end()) { out[key] = value; } } } file.close(); // printf("File is closed. Done reading Twiss header.\n"); return out; } map<string, vector<double>> GetTwissTableAsMap(string filename) { vector<string> TWISSCOLS /* */ {"L", "BETX", "ALFX", "BETY", "ALFY", "DX", "DPX", "DY", "DPY", "K1L", "K1SL", "ANGLE", "K2L", "K2SL"}; map<string, vector<double>> out; map<int, string> columnnames; string line; ifstream file(filename); if (file.is_open()) { // printf("File is open\n"); vector<double> row; int rowcounter = 0; while (!file.eof()) { // update row counter rowcounter++; // read a line getline(file, line); // if line is 47 read the column names if (rowcounter == 47) { // load the current line as stream istringstream iss(line); // split the line and save in vector // vector<string> labels; int colcounter = 0; // cout << "Col idx: "; do { string sub; iss >> sub; vector<string>::iterator it = find(TWISSCOLS.begin(), TWISSCOLS.end(), sub); if (it != TWISSCOLS.end()) { columnnames[colcounter - 1] = sub; // cout << colcounter - 1 << " " << sub << endl; } ++colcounter; } while (iss); } if (rowcounter > 48) { istringstream iss(line); int colcounter = 0; do { string sub; string key; double value; iss >> sub; if (columnnames.count(colcounter) > 0) { key = columnnames[colcounter]; value = stod(sub); // cout << key << " " << value << endl; out[key].push_back(value); } ++colcounter; } while (iss); // cout << endl; } } } file.close(); return out; } void printTwissHeader(map<string, double> &twheader) { std::printf("\n"); std::printf("%-30s\n", "Twiss Header"); std::printf("%-30s\n", "============"); for (auto const &pair : twheader) { std::printf("%-30s %16.8e\n", pair.first.c_str(), pair.second); } std::printf("\n"); }
1,458
#include <time.h> #include <stdlib.h> #include <stdio.h> #define NUMTHREADS 32 #define N 129 #define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); } inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true) { if (code != cudaSuccess) { fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line); if (abort) exit(code); } } void dyadic(int* res, int* a, int* b, int n) { for(int i=0; i<N; i++) { for(int j=0; j<N; j++) { res[i+N*j] = a[j]*b[i]; } } } __global__ void dyadic_gpu(int* res, int* a, int* b, int n) { int x = threadIdx.x + blockDim.x*blockIdx.x; int y = threadIdx.y + blockDim.y*blockIdx.y; if(x < n && y < n) res[x+n*y] = a[y]*b[x]; } int main() { srand(time(NULL)); int* a = (int*)malloc(N*sizeof(int)); int* b = (int*)malloc(N*sizeof(int)); for(int i=0; i<N; i++) { a[i] = rand()%100; b[i] = rand()%100; } int* res = (int*)malloc(N*N*sizeof(int)); dyadic(res, a, b, N); // CUDA stuff int* d_a, *d_b, *d_res; gpuErrchk(cudaMalloc((void**)&d_a, N*sizeof(int))); gpuErrchk(cudaMalloc((void**)&d_b, N*sizeof(int))); gpuErrchk(cudaMalloc((void**)&d_res, N*N*sizeof(int))); gpuErrchk(cudaMemcpy(d_a, a, N*sizeof(int), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_b, b, N*sizeof(int), cudaMemcpyHostToDevice)); dim3 threads(16, 16, 1); dim3 grid(ceil((float)N/(float)16), ceil((float)N/(float)16), 1); // (N+threads.x-1)/threads.x cudaMemset(d_res, 0,N*N*sizeof(int)); dyadic_gpu<<<grid,threads>>>(d_res, d_a, d_b, N); gpuErrchk(cudaGetLastError()); int* resgpu = (int*)malloc(N*N*sizeof(int)); gpuErrchk(cudaMemcpy(resgpu, d_res, N*N*sizeof(int), cudaMemcpyDeviceToHost)); for(int i=0; i<N; i++) { for(int j=0; j<N; j++) { printf("%d ", res[i+N*j]); } printf("\n"); } printf("-----\n"); for(int i=0; i<N; i++) { for(int j=0; j<N; j++) { printf("%d ", resgpu[i+N*j]); } printf("\n"); } printf("\ngrid size: %d, %d\n", grid.x, grid.y); }
1,459
/****************************************************************************** *cr *cr (C) Copyright 2010 The Board of Trustees of the *cr University of Illinois *cr All Rights Reserved *cr ******************************************************************************/ #include <stdio.h> __global__ void VecAdd(int n, const float *A, const float *B, float* C) { //DEVICE(GPU)CODE /******************************************************************** * * Compute C = A + B * where A is a (1 * n) vector * where B is a (1 * n) vector * where C is a (1 * n) vector * ********************************************************************/ //added for extra compute time long long start = clock64(); long long cycles_elapsed; do{cycles_elapsed = clock64() - start;} while(cycles_elapsed <20000); //end of added compute time // INSERT KERNEL CODE HERE int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < n) C[i] = A[i] + B[i]; } void basicVecAdd( float *A, float *B, float *C, int n) { //HOST(CPU)CODE // Initialize thread block and kernel grid dimensions --------------------- const unsigned int BLOCK_SIZE = 256; //INSERT CODE HERE dim3 dimGRID((n-1)/BLOCK_SIZE + 1,1,1); dim3 dimBLOCK(BLOCK_SIZE,1,1); VecAdd<<<dimGRID,dimBLOCK>>>(n,A,B,C); }
1,460
#include "includes.h" __global__ void findMaxIndMultipleDetector(float *input, int* maxInd, int size) { int maxIndex = 0; int count = 1; for (int i = 1; i < size; i++){ if (input[maxIndex] < input[i]){ maxIndex = i; count = 1; } else if (input[maxIndex] == input[i]){ count++; } } if(count>1) maxInd[0] = -1; else maxInd[0] = maxIndex; }
1,461
#include <stdio.h> #ifndef COMMON_CU #define COMMON_CU #define BLOCK_SIZE (4 * 1024) #endif
1,462
#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <stdlib.h> #include <cstring> #include <time.h> // define kernel __global__ void mem_trans_ex(int *input) { int tid = threadIdx.x + blockDim.x * threadIdx.y + ((blockDim.x * blockDim.y * blockDim.z) * gridDim.y) * gridDim.z * threadIdx.z; int num_threads_per_block = blockDim.x * blockDim.y; int block_offset = blockIdx.x * num_threads_per_block; int num_threads_per_row = num_threads_per_block * gridDim.x; int row_offset = num_threads_per_row * blockIdx.y; int num_threads_per_grid = num_threads_per_row * gridDim.z; int grid_offset = num_threads_per_grid * blockIdx.z; int gid = tid + block_offset + row_offset + grid_offset; //int gid = tid + block_offset + row_offset; printf("blockIdx.x: %d, blockIdx.y: %d, blockIdx.z: %d, threadIdx.x: %d, threadIdx.y: %d, threadIdx.z: %d, tid: %d, gid: %d, value: %d\n", blockIdx.x, blockIdx.y, blockIdx.z, threadIdx.x, threadIdx.y, threadIdx.z, tid, gid, input[gid]); } int main() { int size = 64; int byte_size = size * sizeof(int); // initialize array in host int *h_input; h_input = (int *) malloc(byte_size); time_t t; srand((unsigned) time(&t)); for(int i = 0; i < size; i++){ //h_input[i] = (int) (rand() & 0xff); h_input[i] = i; } // initialize array in device int *d_input; cudaMalloc((void **)&d_input, byte_size); // copy array from host to device cudaMemcpy(d_input, h_input, byte_size, cudaMemcpyHostToDevice); // define threads dim3 block(2, 2, 2); dim3 grid(2, 2, 2); // launch kernel mem_trans_ex <<<grid, block>>>(d_input); // closing stuff cudaDeviceSynchronize(); // free mem free(h_input); cudaFree(d_input); cudaDeviceReset(); return 0; }
1,463
#include <cuda_runtime.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <cmath> #define COUNT_UNIT8_T_HASH 16 #define MD5_CHUNKS_BYTE 512/8 #define MD5_TEXT_LEN 448/8 //#define DEBUG #define LEFTROTATE(x, c) (((x) << (c)) | ((x) >> (32 - (c)))) __host__ __device__ void to_bytes(uint32_t val, uint8_t *bytes) { bytes[0] = (uint8_t) val; bytes[1] = (uint8_t) (val >> 8); bytes[2] = (uint8_t) (val >> 16); bytes[3] = (uint8_t) (val >> 24); } __host__ __device__ uint32_t to_int32(const uint8_t *bytes) { return (uint32_t) bytes[0] | ((uint32_t) bytes[1] << 8) | ((uint32_t) bytes[2] << 16) | ((uint32_t) bytes[3] << 24); } __host__ __device__ void md5(const uint8_t *initial_msg, size_t initial_len, uint8_t *digest) { // Constants are the integer part of the sines of integers (in radians) * 2^32. const uint32_t k[64] = {0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391}; // r specifies the per-round shift amounts const uint32_t r[] = {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21}; // These vars will contain the hash uint32_t h0, h1, h2, h3; // Message (to prepare) uint8_t *msg = NULL; size_t new_len, offset; uint32_t w[16]; uint32_t a, b, c, d, i, f, g, temp; // Initialize variables - simple count in nibbles: h0 = 0x67452301; h1 = 0xefcdab89; h2 = 0x98badcfe; h3 = 0x10325476; //Pre-processing: //append "1" bit to message //append "0" bits until message length in bits ≡ 448 (mod 512) //append length mod (2^64) to message for (new_len = initial_len + 1; new_len % (MD5_CHUNKS_BYTE) != MD5_TEXT_LEN; new_len++); msg = (uint8_t *) malloc(new_len + 8); memcpy(msg, initial_msg, initial_len); msg[initial_len] = 0x80; // append the "1" bit; most significant bit is "first" for (offset = initial_len + 1; offset < new_len; offset++) msg[offset] = 0; // append "0" bits // append the len in bits at the end of the buffer. to_bytes(initial_len * 8, msg + new_len); // initial_len>>29 == initial_len*8>>32, but avoids overflow. to_bytes(initial_len >> 29, msg + new_len + 4); // Process the message in successive 512-bit chunks: //for each 512-bit chunk of message: for (offset = 0; offset < new_len; offset += (MD5_CHUNKS_BYTE)) { // break chunk into sixteen 32-bit words w[j], 0 ≤ j ≤ 15 for (i = 0; i < COUNT_UNIT8_T_HASH; i++) w[i] = to_int32(msg + offset + i * 4); // Initialize hash value for this chunk: a = h0; b = h1; c = h2; d = h3; // Main loop: for (i = 0; i < 64; i++) { if (i < 16) { f = (b & c) | ((~b) & d); g = i; } else if (i < 32) { f = (d & b) | ((~d) & c); g = (5 * i + 1) % 16; } else if (i < 48) { f = b ^ c ^ d; g = (3 * i + 5) % 16; } else { f = c ^ (b | (~d)); g = (7 * i) % 16; } temp = d; d = c; c = b; b = b + LEFTROTATE((a + f + k[i] + w[g]), r[i]); a = temp; } // Add this chunk's hash to result so far: h0 += a; h1 += b; h2 += c; h3 += d; } // cleanup free(msg); //var char digest[16] := h0 append h1 append h2 append h3 //(Output is in little-endian) to_bytes(h0, digest); to_bytes(h1, digest + 4); to_bytes(h2, digest + 8); to_bytes(h3, digest + 12); } __host__ __device__ int my_strlen(char *text) { int len = 0; int i = 0; while (text[i++] != '\0') { len++; } return len; } __host__ __device__ void hash_md5(char *input, uint8_t *result) { md5((uint8_t *) input, (size_t) my_strlen(input), result); } __global__ void kernel_mult(char *words, const int height, const int width, uint8_t *cHashWords) { int l = blockDim.x * blockIdx.x + threadIdx.x; if (l >= height) { return; } char *word = new char[width + 1]; int j; for (j = 0; j < width; j++) { word[j] = words[width * l + j]; } word[j] = '\0'; hash_md5(word, &cHashWords[COUNT_UNIT8_T_HASH * l]); #ifdef DEBUG printf("debug: hashing word: %s\n", word); #endif delete[] word; } void run_mult(char *words, const int height, const int width, uint8_t *hashed_words) { cudaError_t cerr; int threads = 128; int length = height * width; int blocks = (length + threads - 1) / threads; char *cWords; cerr = cudaMalloc(&cWords, length * sizeof(char)); if (cerr != cudaSuccess) printf("CUDA Error [%d] - '%s'\n", __LINE__, cudaGetErrorString(cerr)); uint8_t *cHashWords; cerr = cudaMalloc(&cHashWords, height * COUNT_UNIT8_T_HASH * sizeof(uint8_t)); if (cerr != cudaSuccess) printf("CUDA Error [%d] - '%s'\n", __LINE__, cudaGetErrorString(cerr)); cerr = cudaMemcpy(cWords, words, length * sizeof(char), cudaMemcpyHostToDevice); if (cerr != cudaSuccess) printf("CUDA Error [%d] - '%s'\n", __LINE__, cudaGetErrorString(cerr)); kernel_mult<<< blocks, threads >>> (cWords, height, width, cHashWords); if ((cerr = cudaGetLastError()) != cudaSuccess) printf("CUDA Error [%d] - '%s'\n", __LINE__, cudaGetErrorString(cerr)); cerr = cudaMemcpy(hashed_words, cHashWords, height * COUNT_UNIT8_T_HASH * sizeof(uint8_t), cudaMemcpyDeviceToHost); if (cerr != cudaSuccess) printf("CUDA Error [%d] - '%s'\n", __LINE__, cudaGetErrorString(cerr)); cudaFree(cWords); cudaFree(cHashWords); }
1,464
/* Task #8 - Gustavo Ciotto Pinton MO644 - Parallel Programming */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <math.h> #define COMMENT "Histogram_GPU" #define RGB_COMPONENT_COLOR 255 #include <cuda.h> #define THREAD_PER_BLOCK 1024 /* Tesla k40 supports 1024 threads per block */ typedef struct { unsigned char red, green, blue; } PPMPixel; typedef struct { int x, y; PPMPixel *data; } PPMImage; double rtclock() { struct timezone Tzp; struct timeval Tp; int stat; stat = gettimeofday (&Tp, &Tzp); if (stat != 0) printf("Error return from gettimeofday: %d",stat); return(Tp.tv_sec + Tp.tv_usec*1.0e-6); } static PPMImage *readPPM(const char *filename) { char buff[16]; PPMImage *img; FILE *fp; int c, rgb_comp_color; fp = fopen(filename, "rb"); if (!fp) { fprintf(stderr, "Unable to open file '%s'\n", filename); exit(1); } if (!fgets(buff, sizeof(buff), fp)) { perror(filename); exit(1); } if (buff[0] != 'P' || buff[1] != '6') { fprintf(stderr, "Invalid image format (must be 'P6')\n"); exit(1); } img = (PPMImage *) malloc(sizeof(PPMImage)); if (!img) { fprintf(stderr, "Unable to allocate memory\n"); exit(1); } c = getc(fp); while (c == '#') { while (getc(fp) != '\n') ; c = getc(fp); } ungetc(c, fp); if (fscanf(fp, "%d %d", &img->x, &img->y) != 2) { fprintf(stderr, "Invalid image size (error loading '%s')\n", filename); exit(1); } if (fscanf(fp, "%d", &rgb_comp_color) != 1) { fprintf(stderr, "Invalid rgb component (error loading '%s')\n", filename); exit(1); } if (rgb_comp_color != RGB_COMPONENT_COLOR) { fprintf(stderr, "'%s' does not have 8-bits components\n", filename); exit(1); } while (fgetc(fp) != '\n') ; img->data = (PPMPixel*) malloc(img->x * img->y * sizeof(PPMPixel)); if (!img) { fprintf(stderr, "Unable to allocate memory\n"); exit(1); } if (fread(img->data, 3 * img->x, img->y, fp) != img->y) { fprintf(stderr, "Error loading image '%s'\n", filename); exit(1); } fclose(fp); return img; } __global__ void cudaHistogram (PPMPixel *data, int size, int *h) { int i = threadIdx.x + blockIdx.x * blockDim.x, stride = blockDim.x * gridDim.x; /* Gives the number of threads in a grid */ while (i < size) { /* Implicit conversion from float to int gives the same result of floor() function */ int r = ( (float) (data[i].red * 4) / 256), g = ( (float) (data[i].green * 4) / 256), b = ( (float) (data[i].blue * 4) / 256); int x = r * 16 + g * 4 + b; atomicAdd(&h[x], 1); i += stride; } } int main(int argc, char *argv[]) { if( argc != 2 ) { printf("Too many or no one arguments supplied.\n"); return 0; } int i, n; char *filename = argv[1]; //Recebendo o arquivo!; #ifdef PRINT_TIME double start, end, cuda_malloc_t, cuda_copy_t, cuda_kernel_t; #endif PPMImage *image = readPPM(filename); n = image->x * image->y; int *h = (int*)malloc(sizeof(int) * 64); #ifdef PRINT_TIME /* We consider in the execution delay the memory allocation time */ start = rtclock(); #endif /* Allocating memory for image data in the device */ int image_size = n * sizeof(PPMPixel); PPMPixel *cuda_image; cudaMalloc((void**) &cuda_image, image_size); /* Allocating memory for histogram in the device */ int *cuda_h; cudaMalloc((void**) &cuda_h, 64 * sizeof(int)); cudaMemset(cuda_h, 0, 64 * sizeof(int)); #ifdef PRINT_TIME cuda_malloc_t = rtclock(); #endif cudaMemcpy(cuda_image, image->data, image_size, cudaMemcpyHostToDevice); #ifdef PRINT_TIME cuda_copy_t = rtclock(); #endif /* Computes how many blocks will be used. */ int cuda_blocks = ceil ( (float) n / THREAD_PER_BLOCK ); cudaHistogram <<< cuda_blocks, THREAD_PER_BLOCK >>> (cuda_image, n, cuda_h); #ifdef PRINT_TIME cudaThreadSynchronize(); cuda_kernel_t = rtclock(); #endif /* Copying computed result from device memory */ cudaMemcpy(h, cuda_h, sizeof(int) * 64, cudaMemcpyDeviceToHost); #ifdef PRINT_TIME /* As cudaMemcpy is a blocking call, we do not need to call cudaThreadSynchronize() */ end = rtclock(); #endif for (i = 0; i < 64; i++){ printf("%0.3f ", (float) h[i] / n); } printf("\n"); #ifdef PRINT_TIME printf("\nBuffer:%0.6lfs\nEnviar:%0.6lfs\nKernel:%0.6lfs\nReceber:%0.6lfs\nTotal: %0.6lfs\n", cuda_malloc_t - start, cuda_copy_t - cuda_malloc_t, cuda_kernel_t - cuda_copy_t, end - cuda_kernel_t, end - start); #endif /* Cleaning everything up */ free(h); free(image->data); free(image); cudaFree(cuda_image); cudaFree(cuda_h); } /* Time table: arq1.ppm arq2.ppm arq3.ppm tempo_serial 0.342149s 0.608602s 1.813922s tempo_GPU_criar_buffer 0.288812s 0.292572s 0.312226s tempo_GPU_offload_enviar 0.000826s 0.001253s 0.004878s tempo_kernel 0.001099s 0.003102s 0.011870s tempo_GPU_offload_receber 0.000024s 0.000022s 0.000035s tempo_GPU_total 0.290761s 0.296949s 0.329009s speedup 1.17674 2.04952 5.51329 */
1,465
/// /// vecAddKernel01.cu /// /// This Kernel adds two Vectors A and B in C on GPU /// with using coalesced memory access. /// __global__ void AddVectors(const float* A, const float* B, float* C, int N) { int blockStartIndex = blockIdx.x * blockDim.x * N; int threadStartIndex = blockStartIndex + threadIdx.x; int threadEndIndex = threadStartIndex + N; int i, add; //loop n times coalescing through vectors for( i=threadStartIndex; i<threadEndIndex; ++i){ //get the index to add from the two vectors, jumps across vector each iteration //not one index a time though add = ((i - threadStartIndex)*blockDim.x) + threadStartIndex; C[add] = A[add] + B[add]; } }
1,466
#include "includes.h" #define TOLERANCE 0.00001 #define TRUE 1 #define FALSE 0 long usecs(); void initialize(double **A, int rows, int cols); int calc_serial(double **A, int rows, int cols, int iters, double tolerance); int calc_serial_v1(double **A, int rows, int cols, int iters, double tolerance); int calc_omp(double **A, int rows, int cols, int iters, double tolerance, int num_threads); int calc_gpu(double **A, int rows, int cols, int iters, double tolerance); double verify(double **A, double **B, int rows, int cols); __global__ void calc_kernel(double* w, double* r, int rows, int cols, double tolerance) { int row = blockIdx.x; int col = threadIdx.x; int idx = row*blockDim.x + col; if (row < rows && row > 0 && col < cols) { w[idx] = 0.2*(r[idx+1] + r[idx - 1] + r[(row-1)*blockDim.x + col] + r[(row+1)*blockDim.x + col]); } }
1,467
#include <stdio.h> #include <time.h> // by lectures and "CUDA by Example" book #define ind(k, i, j, rows, cols) (k * (rows * cols) + i * cols + j) // device code: matrices sum calculation __global__ void sum_matrices_kernel(int* mat_stack, int* mat, int rows, int cols, int num) { // row and col that correspond to current thread // process all elements that correspond to current thread for (int i = blockIdx.y * blockDim.y + threadIdx.y; i < rows; i += blockDim.y * gridDim.y) for (int j = blockIdx.x * blockDim.x + threadIdx.x; j < cols; j += blockDim.x * gridDim.x) { int mat_ind = ind(0, i, j, rows, cols); mat[mat_ind] = 0; // iterating over all elements on (i, j) position for (int k = 0; k < num; k++) { int stack_ind = ind(k, i, j, rows, cols); mat[mat_ind] += mat_stack[stack_ind]; } } } int* cuda_copy_tens(int* host_tensor, int rows, int cols, int num) { int* dev_tensor; // size of memory to allocate on device for tensor long mem_size = rows * cols * num * sizeof(int); // device memory allocation cudaMalloc((void**) &dev_tensor, mem_size); // copying data from host to device cudaMemcpy(dev_tensor, host_tensor, mem_size, cudaMemcpyHostToDevice); // returning pointer return dev_tensor; } // host code: preparation float sum_matrices_gpu(int* host_mat_stack, int* host_m, int rows, int cols, int num) { // Step 1: moving data on device int* dev_mat_stack = cuda_copy_tens(host_mat_stack, rows, cols, num); int* dev_m = cuda_copy_tens(host_m, rows, cols, 1); // Step 2 // grid (of blocks) dimensions dim3 grid_dim(128, 128, 1); // block (of threads) dimensions dim3 block_dim(32, 32, 1); // running kernel summation code clock_t start = clock(); sum_matrices_kernel<<<grid_dim, block_dim>>>(dev_mat_stack, dev_m, rows, cols, num); cudaDeviceSynchronize(); clock_t end = clock(); float time = (float)(end - start) / CLOCKS_PER_SEC; // Step 3 // copying result from device to host matrix cudaMemcpy(host_m, dev_m, rows * cols * sizeof(int), cudaMemcpyDeviceToHost); // freeing device memory cudaFree(dev_mat_stack); cudaFree(dev_m); return time; } float sum_matrices_cpu(int* mat_stack, int* mat, int rows, int cols, int num) { clock_t start = clock(); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) { int mat_ind = ind(0, i, j, rows, cols); mat[mat_ind] = 0; for (int k = 0; k < num; k++) { int stack_ind = ind(k, i, j, rows, cols); mat[mat_ind] += mat_stack[stack_ind]; } } clock_t end = clock(); float time = (float)(end - start) / CLOCKS_PER_SEC; return time; } // initialize matrix stack int* init_mat_stack(int* mat_stack, int rows, int cols, int num) { for (int k = 0; k < num; k++) for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) { int index = ind(k, i, j, rows, cols); mat_stack[index] = rand() % 20; } return mat_stack; } // QUESTION #1: why gpu times differ despite elements of each line // always processing by single thread and number of threads always more // than number of lines? // there should be time always equal to process time of single thread? // possible answer: in case of multiple threads they must wait each other // in cudaDeviceSynchronize point? // QUESTION #2: why when we set dim of block equal to 64x64 // then cudaDeviceSynchronize doesn't work? int main() { // matrix count int num = 1e6; for (int dim = 10; dim > 0; dim--) { int rows = dim; int cols = dim; // first matrix int* host_mat_stack = (int*) malloc(rows * cols * num * sizeof(int)); init_mat_stack(host_mat_stack, rows, cols, num); // result matrix int* host_m = (int*) malloc(rows * cols * sizeof(int)); // summation int num_measures = 10; float gpu_time_mean = 0; float cpu_time_mean = 0; for (int i = 0; i < num_measures; i++) { gpu_time_mean += sum_matrices_gpu(host_mat_stack, host_m, rows, cols, num); cpu_time_mean += sum_matrices_cpu(host_mat_stack, host_m, rows, cols, num); } gpu_time_mean /= num_measures; cpu_time_mean /= num_measures; printf("Matrix stack params: (%d, %d) x %.0e\n", rows, cols, double(num)); printf("CPU time mean: %.10f\n", cpu_time_mean); printf("GPU time mean: %.10f\n", gpu_time_mean); printf("CPU / GPU time: %.10f\n", cpu_time_mean / gpu_time_mean); printf("--------------------------\n"); } return 0; }
1,468
//pass //--blockDim=1024 --gridDim=1 --no-inline #include <cuda.h> #include <stdio.h> #define N 2 //1024 __global__ void definitions (int* A, unsigned int* B, unsigned long long int* C) { atomicMax(A,10); atomicMax(B,1); atomicMax(C,5); }
1,469
#include "includes.h" __global__ void GPUMult(int *A, int *B, int *C, int WIDTH) { int sol=0; int i;i = threadIdx.x; int j; j= threadIdx.y; if (i < WIDTH && j < WIDTH) { for (int k = 0; k < WIDTH; k++) { sol += A[j * WIDTH + k] * B[k * WIDTH + i]; } C[j * WIDTH + i] = sol; } }
1,470
#include "includes.h" #define SIZ 20 #define num_inp 4 using namespace std; typedef struct edge { int first, second; } edges; __global__ void initialize_vertices(int *vertices, int starting_vertex) { int v = blockDim.x * blockIdx.x + threadIdx.x; if (v == starting_vertex) vertices[v] = 0; else vertices[v] = -1; }
1,471
#include "includes.h" __global__ void sync_deconv_groups() { }
1,472
/* This code illustrates the use of the GPU to perform vector addition on arbirarily large vectors. Author: Naga Kandasamy Date modified: May 3, 2020 */ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string.h> #include <math.h> #include <float.h> /* Include kernel code during preprocessing step */ #include "vector_addition_kernel.cu" #define THREAD_BLOCK_SIZE 128 #define NUM_THREAD_BLOCKS 240 void run_test(int); void compute_on_device(float *, float *, float *, int); void check_for_error(char const *); extern "C" void compute_gold(float *, float *, float *, int); int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "Usage: %s num-elements\n", argv[0]); exit(EXIT_FAILURE); } int num_elements = atoi(argv[1]); run_test(num_elements); exit(EXIT_SUCCESS); } /* Perform vector addition on CPU and GPU */ void run_test(int num_elements) { float diff; int i; /* Allocate memory on CPU for input vectors A and B, and output vector C */ int vector_length = sizeof(float) * num_elements; float *A = (float *)malloc(vector_length); float *B = (float *)malloc(vector_length); float *gold_result = (float *)malloc(vector_length); /* Result vector computed on CPU */ float *gpu_result = (float *)malloc(vector_length); /* Result vector computed on GPU */ /* Initialize input data to be integer values between 0 and 5 */ for (i = 0; i < num_elements; i++) { A[i] = floorf(5 * (rand() / (float)RAND_MAX)); B[i] = floorf(5 * (rand() / (float)RAND_MAX)); } /* Compute reference solution on CPU */ fprintf(stderr, "Adding vectors on the CPU\n"); compute_gold(A, B, gold_result, num_elements); /* Compute result vector on GPU */ compute_on_device(A, B, gpu_result, num_elements); /* Compute differences between the CPU and GPU results. */ diff = 0.0; for (i = 0; i < num_elements; i++) diff += fabsf(gold_result[i] - gpu_result[i]); fprintf(stderr, "Difference between the CPU and GPU result: %f\n", diff); /* Free the data structures. */ free((void *)A); free((void *)B); free((void *)gold_result); free((void *)gpu_result); exit(EXIT_SUCCESS); } /* Host side code. Transfer vectors A and B from CPU to GPU, set up grid and thread dimensions, execute kernel function, and copy result vector back to CPU. */ void compute_on_device(float *A_on_host, float *B_on_host, float *gpu_result, int num_elements) { float *A_on_device = NULL; float *B_on_device = NULL; float *C_on_device = NULL; /* Allocate space on GPU for vectors A and B, and copy contents of vectors to GPU */ cudaMalloc((void **)&A_on_device, num_elements * sizeof(float)); cudaMemcpy(A_on_device, A_on_host, num_elements * sizeof(float), cudaMemcpyHostToDevice); cudaMalloc((void **)&B_on_device, num_elements * sizeof(float)); cudaMemcpy(B_on_device, B_on_host, num_elements * sizeof(float), cudaMemcpyHostToDevice); /* Allocate space for result vector on GPU */ cudaMalloc((void **)&C_on_device, num_elements * sizeof(float)); /* Set up the execution grid on the GPU. */ int num_thread_blocks = NUM_THREAD_BLOCKS; dim3 thread_block(THREAD_BLOCK_SIZE, 1, 1); /* Set number of threads in the thread block */ fprintf(stderr, "Setting up a (%d x 1) execution grid\n", num_thread_blocks); dim3 grid(num_thread_blocks, 1); fprintf(stderr, "Adding vectors on the GPU\n"); /* Launch kernel with multiple thread blocks. The kernel call is non-blocking. */ vector_addition_kernel<<< grid, thread_block >>>(A_on_device, B_on_device, C_on_device, num_elements); cudaDeviceSynchronize(); /* Force CPU to wait for GPU to complete */ check_for_error("KERNEL FAILURE"); /* Copy result vector back from GPU and store */ cudaMemcpy(gpu_result, C_on_device, num_elements * sizeof(float), cudaMemcpyDeviceToHost); /* Free memory on GPU */ cudaFree(A_on_device); cudaFree(B_on_device); cudaFree(C_on_device); } /* Check for errors when executing the kernel */ void check_for_error(char const *msg) { cudaError_t err = cudaGetLastError(); if (cudaSuccess != err) { fprintf(stderr, "CUDA ERROR: %s (%s). \n", msg, cudaGetErrorString(err)); exit(EXIT_FAILURE); } }
1,473
// Lanzar un Kernel #include <stdio.h> #include <stdlib.h> #include <cuda_runtime.h> #define N 8 __global__ void suma(int *vector_1, int *vector_2, int*vector_suma, int n) { // identificador de hilo int myID = threadIdx.x; // inicializamos el vector 2 vector_2[myID] = (n -1) - myID; // escritura de resultados vector_suma[myID] = vector_1[myID] + vector_2[myID]; } int main(int argc, char** argv) { // declaraciones int *hst_vector1, *hst_vector2, *hst_resultado; int *dev_vector1, *dev_vector2, *dev_resultado; // reserva en el host hst_vector1 = (int*)malloc(N * sizeof(int)); hst_vector2 = (int*)malloc(N * sizeof(int)); hst_resultado = (int*)malloc(N * sizeof(int)); // reserva en el device cudaMalloc((void**)&dev_vector1, N * sizeof(int)); cudaMalloc((void**)&dev_vector2, N * sizeof(int)); cudaMalloc((void**)&dev_resultado, N * sizeof(int)); // inicializacion de vectores for (int i=0; i<N; i++) { hst_vector1[i] = i; hst_vector2[i] = 0; } // copia de datos hacia el device cudaMemcpy(dev_vector1, hst_vector1, N*sizeof(int), cudaMemcpyHostToDevice); // lanzamiento del kernel suma <<< 1, N >>> (dev_vector1, dev_vector2, dev_resultado, N); // recogida de datos desde el device cudaMemcpy(hst_vector2, dev_vector2, N*sizeof(int), cudaMemcpyDeviceToHost); cudaMemcpy(hst_resultado, dev_resultado, N*sizeof(int), cudaMemcpyDeviceToHost); // impresion de resultados printf("VECTOR 1:\n"); for (int i=0; i<N; i++) { printf("%.2d ", hst_vector1[i]); } printf("\n"); printf("VECTOR 2:\n"); for (int i=0; i<N; i++) { printf("%.2d ", hst_vector2[i]); } printf("\n"); printf("SUMA:\n"); for (int i=0; i<N; i++) { printf("%.2d ", hst_resultado[i]); } printf("\n"); printf("****"); printf("<pulsa [INTRO] para finalizar>"); getchar(); return 0; }
1,474
#include <cuda_runtime.h> __global__ void powf_global(float x, float y, float *r) { *r = __powf(x, y); } float cuda_pow(float x, float y) { float *gpu_result, result; cudaMalloc((void **)&gpu_result, sizeof(float)); powf_global<<<1, 1>>>(x, y, gpu_result); cudaMemcpy(&result, gpu_result, sizeof(int), cudaMemcpyDeviceToHost); cudaFree(gpu_result); // cudaDeviceReset(); // force printf flush return result; }
1,475
#include "includes.h" // Device code for ICP computation // Currently working only on performing rotation and translation using cuda #ifndef _ICP_KERNEL_H_ #define _ICP_KERNEL_H_ #define TILE_WIDTH 256 #endif // #ifndef _ICP_KERNEL_H_ __global__ void CalculateDistanceIndexEachPoint(double point_x, double point_y, double point_z, double * data_x_d, double * data_y_d, double * data_z_d, int * bin_index_d, double * distance_d, int size_data) { int index = blockDim.x*blockIdx.x + threadIdx.x; if(index < size_data) { distance_d[index] = sqrt(pow(data_x_d[index] - point_x,2) + pow(data_y_d[index] - point_y,2) + pow(data_z_d[index] - point_z,2)); bin_index_d[index] = index; } }
1,476
/* Mmult application Written by: Riccardo Fontanini Start date: 3 May 2018 Note: This program is created to multiply 3 matrix R O T A S O P E R A T E N E T A R E P O S A T O R */ #include <stdio.h> #ifndef N #define N 1024 #endif #ifndef BLOCKDIM #define BLOCKDIM 32 #endif void __global__ shared_mmult(int *A, int *B, int *C) { __shared__ int s_A [BLOCKDIM * BLOCKDIM]; __shared__ int s_B [BLOCKDIM * BLOCKDIM]; int value = 0; int block_index = threadIdx.y * BLOCKDIM + threadIdx.x; int xa, ya, xb, yb = 0; ya = blockIdx.y; xb = blockIdx.x; /* se matrice 3*3 e multipla di 32 (blockIdx.y; blockIdx.c) == (0, 0) -> siamo nel blocco C00 = A00 * B00 + A01 * B10 + A02 * B20 (blockIdx.y; blockIdx.x) == (0, 1) -> siamo nel blocco C01 = A00 * B01 + A01 * B11 + A02 * B21 (blockIdx.y; blockIdx.x) == (1, 0) -> siamo nel blocco C10 = A10 * B00 + A11 * B10 + A12 * B20 (blockIdx.y; blockIdx.x) == (1, 1) -> siamo nel blocco C11 = A10 * B01 + A11 * B11 + A12 * B21 e così via... */ for(int i = 0; i < N/BLOCKDIM; i++) { //copy global memory Axaya and Bxbyb to shared memory xa = i; yb = i; *(s_A + block_index) = *(A + ( (ya * BLOCKDIM) + threadIdx.y ) * N + (threadIdx.x + xa * BLOCKDIM)); *(s_B + block_index) = *(B + ( (yb * BLOCKDIM) + threadIdx.y ) * N + (threadIdx.x + xb * BLOCKDIM)); if(blockIdx.y * BLOCKDIM + threadIdx.y >= N || blockIdx.x * BLOCKDIM + threadIdx.x >= N) return; __syncthreads(); for (int k = 0; k < BLOCKDIM; k++) value += *(s_A + threadIdx.y * BLOCKDIM + k) * *(s_B + k * BLOCKDIM + threadIdx.x); __syncthreads(); } *(C + ( (blockIdx.y * BLOCKDIM) + threadIdx.y ) * N + (threadIdx.x + blockIdx.x * BLOCKDIM)) = value; } void __global__ simple_mmult(int *A, int *B, int *C) { int value = 0; for (int k = 0; k < N; k++) value += *(A + ( (blockIdx.y * BLOCKDIM) + threadIdx.y ) * N + (k + blockIdx.x * BLOCKDIM) ) * *(B + ( (blockIdx.y * BLOCKDIM) + k ) * N + (threadIdx.x + blockIdx.x * BLOCKDIM)); *(C + ( (blockIdx.y * BLOCKDIM) + threadIdx.y ) * N + (threadIdx.x + blockIdx.x * BLOCKDIM)) = value; } int main () { int NN = N * N; int *A, *B, *C; cudaMallocManaged (&A, NN * sizeof (int)); cudaMallocManaged (&B, NN * sizeof (int)); cudaMallocManaged (&C, NN * sizeof (int)); cudaDeviceSynchronize(); fprintf(stderr, "PRIma\n"); int *ptrA = A; int *ptrB = B; int *ptrC = C; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++, ptrA++, ptrB++, ptrC++) { *ptrA = i * N + j; *ptrB = *ptrC = 0; if (i == j) *ptrB = 1; } cudaDeviceSynchronize(); fprintf(stderr, "seconda\n"); fprintf (stderr, "La visualizzazione delle matrici è stata limitata a 10x10\n"); fprintf (stderr, "Matrix A\n"); ptrA = A; for (int i = 0; i < 10; i++) { ptrA = A + i * N; for (int j = 0; j < 10; j++, ptrA++) fprintf (stderr, "%2d ", *ptrA); fprintf (stderr, "\n"); } fprintf (stderr, "\n\n\n"); fprintf (stderr, "Matrix B\n"); ptrB = B; for (int i = 0; i < 10; i++) { ptrB = B + i * N; for (int j = 0; j < 10; j++, ptrB++) fprintf (stderr, "%2d ", *ptrB); fprintf (stderr, "\n"); } fprintf (stderr, "\n\n\n"); cudaDeviceSynchronize (); dim3 blocksPerGrid (N/BLOCKDIM, N/BLOCKDIM); dim3 threadsPerBlock (BLOCKDIM, BLOCKDIM); #ifdef SIMPLE simple_mmult <<< blocksPerGrid, threadsPerBlock>>> (A, B, C); cudaDeviceSynchronize (); ptrC = C; fprintf (stderr, "Matrix C SIMPLE (not shared memory)\n"); for (int i = 0; i < 10; i++) { ptrC = C + i * N; for (int j = 0; j < 10; j++, ptrC++) fprintf (stderr, "%2d ", *ptrC); fprintf (stderr, "\n"); } fprintf (stderr, "\n\n\n"); #endif int dimSHARED = 3 * ( BLOCKDIM * BLOCKDIM * sizeof(int)); shared_mmult <<< blocksPerGrid, threadsPerBlock>>> (A, B, C); cudaDeviceSynchronize (); fprintf (stderr, "Matrix C Shared memory\n"); ptrC = C; for (int i = 0; i < 10; i++) { ptrC = C + i * N; for (int j = 0; j < 10; j++, ptrC++) fprintf (stderr, "%2d ", *ptrC); fprintf (stderr, "\n"); } return 0; }
1,477
#include "Atomic.cuh" __device__ bool tryAtomicStore(volatile int* ref, int oldValue, int newValue) { int replaced = atomicCAS((int*)ref, oldValue, newValue); return replaced == oldValue; } __device__ bool tryAtomicStore(volatile float* ref, float oldValue, float newValue) { return tryAtomicStore((volatile int*)ref, __float_as_int(oldValue), __float_as_int(newValue)); }
1,478
#include <stdio.h> __global__ void VectorAdd(int *a, int *b, int *c) { int tid = blockIdx.x * blockDim.x + threadIdx.x; c[tid] = a[tid] + b[tid]; } int main() { const int size = 512*65535; const int BufferSize = size*sizeof(int); int *InputA, *InputB, *Result; InputA = (int*)malloc(BufferSize); InputB = (int*)malloc(BufferSize); Result = (int*)malloc(BufferSize); int i = 0; for(i=0;i<size;i++) { InputA[i] = i; InputB[i] = i; Result[i] = 0; } int *dev_A, *dev_B, *dev_R; cudaMalloc((void**)&dev_A, size*sizeof(int)); cudaMalloc((void**)&dev_B, size*sizeof(int)); cudaMalloc((void**)&dev_R, size*sizeof(int)); cudaMemcpy(dev_A, InputA, size*sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(dev_B, InputB, size*sizeof(int), cudaMemcpyHostToDevice); VectorAdd<<<65535, 512>>>(dev_A, dev_B, dev_R); cudaMemcpy(Result, dev_R, size*sizeof(int), cudaMemcpyDeviceToHost); for(i=0;i<5;i++) printf("Result[%d] : %d\n", i, Result[i]); printf("......\n"); for(i=size-5;i<size;i++) printf("Result[%d] : %d\n", i, Result[i]); cudaFree(dev_A); cudaFree(dev_B); cudaFree(dev_R); free(InputA); free(InputB); free(Result); return 0; }
1,479
#include <cuda_runtime.h> #include <device_launch_parameters.h> #include <stdio.h> #include <stdlib.h> #include <math.h> __global__ void add(int *a, int *b, int *alpha) { int i = blockIdx.x; b[i]=*alpha*a[i]+b[i]; } int main(void) { int MAX = 10; int a[MAX], b[MAX], alpha; int *d_a, *d_b, *d_c; int size = sizeof(int)*MAX; cudaMalloc((void**)&d_a, size); cudaMalloc((void**)&d_b, size); cudaMalloc((void**)&d_c, sizeof(int)); for (int i = 0; i < MAX; ++i) { a[i] = i+10; b[i] = i*20; } alpha=2; printf("Array A:\n"); for (int i = 0; i < MAX; ++i) printf("%d\t", a[i]); printf("\nArray B:\n"); for (int i = 0; i < MAX; ++i) printf("%d\t", b[i]); cudaMemcpy(d_a, &a, size, cudaMemcpyHostToDevice); cudaMemcpy(d_b, &b, size, cudaMemcpyHostToDevice); cudaMemcpy(d_c, &alpha, sizeof(int), cudaMemcpyHostToDevice); add<<<MAX,1>>>(d_a, d_b, d_c); cudaMemcpy(&b, d_b, size, cudaMemcpyDeviceToHost); printf("\nFinal Result:\n"); for (int i = 0; i < MAX; ++i) printf("%d\t", b[i]); printf("\n"); cudaFree(d_a); cudaFree(d_b); cudaFree(d_c); return 0; }
1,480
// pour compiler : nvcc vecAdd.cu -o vecAdd #include <stdio.h> #include <stdlib.h> #include <math.h> // CUDA kernel. Each thread takes care of one element of c __global__ void vecAdd(float *a, float *b, float *c, int n){ // identifiant global du thread dans la grille 1D int tid = blockIdx.x * blockDim.x + threadIdx.x; // on s'assure de ne pas sortir des limites des tableaux a,b,c if (tid < n){ //on effectue une addition élémentaire par thread c[tid] = a[tid] + b[tid]; } } int main( int argc, char* argv[] ) { // Size of vectors int n = 100000; // Host input vectors float *h_a; float *h_b; //Host output vector float *h_c; // Device input vectors float *d_a; float *d_b; //Device output vector float *d_c; // Size, in bytes, of each vector size_t size = n*sizeof(float); ////////////////////////////////////////// // Allocate memory for each vector on host h_a = (float*) malloc (size); h_b = (float*) malloc (size); h_c = (float*) malloc (size); ///////////////////////////////////////// // Allocate memory for each vector on GPU cudaMalloc((void**)&d_a, size); cudaMalloc((void**)&d_b, size); cudaMalloc((void**)&d_c, size); int i; // Initialize vectors on host for( i = 0; i < n; i++ ) { h_a[i] = sin(i)*sin(i); h_b[i] = cos(i)*cos(i); } ///////////////////////////////////////// // Copy host vectors to device cudaMemcpy(d_a, h_a, size, cudaMemcpyHostToDevice); cudaMemcpy(d_b, h_b, size, cudaMemcpyHostToDevice); int blockSize, gridSize; ///////////////////////////////////////// // Number of threads in each thread block blockSize = 512; //////////////////////////////////////// // Number of thread blocks in grid gridSize = (n + blockSize - 1) / blockSize;; /////////////////////////////////////// // Launch the kernel vecAdd<<<gridSize, blockSize>>>(d_a, d_b, d_c, n); /////////////////////////////////////// // Copy array back to host cudaMemcpy(h_c, d_c, size, cudaMemcpyDeviceToHost); // Sum up vector c and print result divided by n, this should equal 1 within error float sum = 0; for(i=0; i<n; i++) sum += h_c[i]; printf("final result: %f\n", sum/n); ///////////////////////////////////////// cudaFree(d_a); cudaFree(d_b); cudaFree(d_c); //////////////////////////////////////// // Release host memory free(h_a); free(h_b); free(h_c); return 0; }
1,481
#include<stdlib.h> #include<stdio.h> #include<time.h> void init_array(double *a, const int N); void print_array(double *a,const int N); __global__ void vecAdd(double*a,double*b,double*c,int n) { //get thread id int id = blockIdx.x*blockDim.x + threadIdx.x; if(id<n) c[id]=a[id]+b[id]; } int main() { srand(time(NULL)); int n = 100; double *a,*b,*c; double *d_a,*d_b,*d_c; const int size = n*sizeof(double); a = (double*)malloc(size); b = (double*)malloc(size); c = (double*)malloc(size); cudaMalloc(&d_a,size); cudaMalloc(&d_b,size); cudaMalloc(&d_c,size); init_array(a,n); init_array(b,n); print_array(a,n); print_array(b,n); cudaMemcpy(d_a,a,size,cudaMemcpyHostToDevice); cudaMemcpy(d_b,b,size,cudaMemcpyHostToDevice); int blockSize,gridSize; //no. of threads in each thread block blockSize = 1024; //no of blocks in grid gridSize = (int)ceil((float)n/blockSize); vecAdd<<<gridSize,blockSize>>>(d_a,d_b,d_c,n); cudaThreadSynchronize(); cudaMemcpy(c,d_c,size,cudaMemcpyDeviceToHost); print_array(c,n); cudaFree(d_a); cudaFree(d_b); cudaFree(d_c); delete[] a; delete[] b; delete[] c; return 0; } void init_array(double*a,const int N) { for(int i=0;i<N;i++) a[i] = rand()%N + 1; } void print_array(double*a,const int N) { for(int i=0;i<N;i++) printf("%f ",a[i]); printf("\n"); }
1,482
#include "includes.h" /*****************************************************************************/ // nvcc -O1 -o bpsw bpsw.cu -lrt -lm // Assertion to check for errors __global__ void kernel_trialDiv (long* n, int* r) { int bx = blockIdx.x; // ID thread int tx = threadIdx.x; int i=0; // Identify the row and column of the Pd element to work on long memIndex = bx*TILE_WIDTH+tx; for (i = 0; i < 256; i++) { // r[memIndex] = ((n[memIndex])%(d_sPrimes[i]) == 0)? (r[memIndex] - 1) : r[memIndex]; //ternary is slower than if statement if (n[memIndex] % d_sPrimes[i] == 0) r[memIndex] = r[memIndex] - 1; //r decreases from 1. Only 1s are prime candidates } __syncthreads(); }
1,483
/**************************************** * CUDA kernel for transposing matrices * ****************************************/ #include <stdio.h> #define CUDA_SAFE_CALL( call ) { \ cudaError_t err = call; \ if( cudaSuccess != err ) { \ fprintf(stderr,"CUDA: error occurred in cuda routine. Exiting...\n"); \ exit(err); \ } } #define A(i,j) A[ (j) + ((i)*(n)) ] #define B(i,j) B[ (j) + ((i)*(m)) ] #define B_cpu(i,j) B_cpu[ (j) + ((i)*(m)) ] #define B_gpu(i,j) B_gpu[ (j) + ((i)*(m)) ] #define d_A(i,j) d_A[ (j) + ((i)*(n)) ] #define d_B(i,j) d_B[ (j) + ((i)*(m)) ] __global__ void compute_kernel( unsigned int m, unsigned int n, float *d_A, float *d_B ) { /* Index of thread in x dimension */ int x = threadIdx.x; /* Index of thread in y dimension */ int y = threadIdx.y; /* Global index to a matrix row (i) */ int i = blockIdx.x * blockDim.x + x; /* Global index to a matrix col (j) */ int j = blockIdx.y * blockDim.y + y; /* Copy element A(i,j) into B(j,i) to form the transposed matrix */ if (i < m && j < n){ d_B(j, i) = d_A(i, j); } } int cu_transpose( unsigned int m, unsigned int n, unsigned int block_size, float *h_A, float *h_B ) { // Allocate device memory unsigned int mem_size = m * n * sizeof(float); float *d_A, *d_B; CUDA_SAFE_CALL( cudaMalloc((void **) &d_A, mem_size ) ); CUDA_SAFE_CALL( cudaMalloc((void **) &d_B, mem_size ) ); // Copy host memory to device CUDA_SAFE_CALL( cudaMemcpy( d_A, h_A, mem_size, cudaMemcpyHostToDevice ) ); // Calculate blocks grid size int blocks_col = (int) ceil( (float) n / (float) block_size ); int blocks_row = (int) ceil( (float) m / (float) block_size ); // Execute the kernel dim3 dimGrid( blocks_col, blocks_row ); dim3 dimBlock( block_size, block_size ); compute_kernel<<< dimGrid, dimBlock >>>( m, n, d_A, d_B ); // Copy device memory to host CUDA_SAFE_CALL( cudaMemcpy( h_B, d_B, mem_size, cudaMemcpyDeviceToHost ) ); // Deallocate device memory CUDA_SAFE_CALL( cudaFree(d_A) ); CUDA_SAFE_CALL( cudaFree(d_B) ); return EXIT_SUCCESS; } int transpose( unsigned int m, unsigned int n, float *A, float *B ) { unsigned int i, j; for( i=0; i<m; i++ ) { for( j=0; j<n; j++ ) { B( j, i ) = A( i, j ); } } return EXIT_SUCCESS; } void printMatrix( unsigned int m, unsigned int n, float *A ) { int i, j; for( i=0; i<m; i++ ) { for( j=0; j<n; j++ ) { printf("%8.1f",A(i,j)); } printf("\n"); } } int main( int argc, char *argv[] ) { unsigned int m, n; unsigned int block_size; unsigned int i, j; /* Generating input data */ if( argc<4 ) { printf("Usage: %s n_rows n_cols block_size \n",argv[0]); exit(-1); } sscanf(argv[1],"%d",&m); sscanf(argv[2],"%d",&n); sscanf(argv[3],"%d",&block_size); float *A = (float *) malloc( m*n*sizeof(float) ); printf("%s: Generating a random matrix of size %dx%d...\n",argv[0],m,n); for( i=0; i<m; i++ ) { for( j=0; j<n; j++ ) { A( i, j ) = 2.0f * ( (float) rand() / RAND_MAX ) - 1.0f; } } float *B_cpu = (float *) malloc( m*n*sizeof(float) ); float *B_gpu = (float *) malloc( m*n*sizeof(float) ); printf("%s: Transposing matrix A into B in CPU...\n",argv[0]); transpose( m, n, A, B_cpu ); printf("%s: Transposing matrix A into B in GPU...\n",argv[0]); cu_transpose( m, n, block_size, A, B_gpu ); /* Check for correctness */ float error = 0.0f; for( i=0; i<n; i++ ) { for( j=0; j<m; j++ ) { error += fabs( B_gpu( i, j ) - B_cpu( i, j ) ); } } printf("Error CPU/GPU = %.3e\n",error); free(A); free(B_cpu); free(B_gpu); }
1,484
/* * Copyright (c) 2019 Opticks Team. All Rights Reserved. * * This file is part of Opticks * (see https://bitbucket.org/simoncblyth/opticks). * * 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. */ #include <thrust/for_each.h> #include <thrust/device_vector.h> template<typename T> struct ShortCompressor { int _imax ; T _center ; T _extent ; T _max ; T _step ; T _eps ; T _half ; ShortCompressor( T center, T extent ) : _imax(32767), _center(center), _extent(extent), _max(_imax), _step(_extent/_max), _eps(0.001), _half(0.5) { } __host__ __device__ T value(int iv) { return _center + _step*(T(iv)+_half) ; } __host__ __device__ T fvalue(T v) { return _max*(v - _center)/_extent ; } __device__ int ivalue(double v) { T vv = _max*(v - _center)/_extent ; return __double2int_rn(vv) ; } __device__ int ivalue(float v) { T vv = _max*(v - _center)/_extent ; return __float2int_rn(vv) ; } __device__ void operator()(float4 v) { printf("%15.7f %15.7f %d %15.7f %d %15.7f %d %15.7f %d \n", v.x, fvalue(v.x), ivalue(v.x), v.y, ivalue(v.y), v.z, ivalue(v.z), v.w, ivalue(v.w) ); } __host__ void test(int d0) { thrust::device_vector<float4> fvec(10); // TODO: fix this, better to prep on host then copy to dev in one go for(int i=0 ; i < 10 ; i++) { T val = value(d0+i) ; fvec[i] = make_float4( val, val, val, T(d0+i) ); } thrust::for_each(fvec.begin(), fvec.end(), *this ); } }; int main() { float center(0.); float extent(451.); ShortCompressor<float> comp(center,extent); comp.test(3445); cudaDeviceSynchronize(); }
1,485
#include "HeatEquationKernels.cuh" __global__ void HeatEquation_kernel(float3* target, float3* source, unsigned int gridSize, float deltaTime) { unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < (gridSize * gridSize)) { unsigned int x = i / gridSize; unsigned int y = i % gridSize; unsigned int x_next = (x == (gridSize - 1)) ? 0 : x + 1; unsigned int x_prev = (x == 0) ? (gridSize - 1) : x - 1; unsigned int y_next = (y == (gridSize - 1)) ? 0 : y + 1; unsigned int y_prev = (y == 0) ? (gridSize - 1) : y - 1; // write output vertex target[y * gridSize + x].y = source[y * gridSize + x].y + deltaTime * (source[y_next * gridSize + x].y + source[y_prev * gridSize + x].y + source[y * gridSize + x_next].y + source[y * gridSize + x_prev].y - 4.0f * source[y * gridSize + x].y); } } __global__ void HeatSource_kernel(float3* target, float3* source, unsigned int gridSize, float amplitude, float deltaTime) { unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < (gridSize * gridSize)) { // if (source[i].y > 0.0f) { target[i].y += (target[i].y < amplitude) ? min(source[i].y*deltaTime, amplitude-target[i].y) : 0.0f; } // if (source[i].y < 0.0f) { target[i].y += (target[i].y > 0.0) ? max(source[i].y*deltaTime, 0-target[i].y) : 0.0f; } target[i].y += (source[i].y > 0.0f) ? ((target[i].y < amplitude) ? min(source[i].y * deltaTime, amplitude - target[i].y) : 0.0f) : ((target[i].y > 0.0) ? max(source[i].y * deltaTime, 0 - target[i].y) : 0.0f); } } __global__ void SyncVertexBuffers_kernel(float3* target, float3* source, unsigned int gridSize) { unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < (gridSize * gridSize)) { target[i].y = source[i].y; } }
1,486
// // main.cpp // DS // // Created by Shubham Gupta on 31/03/17. // Copyright © 2017 Shubham Gupta. All rights reserved. // Modified by Utkarsh Aashu Mishra on 5/02/2014 // Copyright © 2018 Utkarsh Aashu Mishra. All rights reserved. #include <stdio.h> #include <iostream> #include <cmath> #include <string.h> #include <algorithm> #include <fstream> #include<sstream> #include <iomanip> #include <ctime> using namespace std; #define PI 3.1415926535897932 #define DPI 6.283185307179586 #define SPI 1.772453850905516 #define BOLTZ 1.380658e-23 #define AVOG 6.022169e26 void ALLOCATE_GAS(); void HARD_SPHERE(); void ARGON(); void IDEAL_NITROGEN(); void REAL_OXYGEN(); void IDEAL_AIR(); void REAL_AIR(); void HELIUM_ARGON_XENON(); void OXYGEN_HYDROGEN(); void INITIALISE_SAMPLES(); void DERIVED_GAS_DATA(); void SET_INITIAL_STATE_1D(); void MOLECULES_ENTER_1D(); void FIND_CELL_1D(double &,int &,int &); void FIND_CELL_MB_1D(double &,int &,int &,double &); void RVELC(double &,double &,double &); void SROT(int &,double &,double &); void SVIB(int &,double &,int &, int&); void SELE(int &,double &,double &); void CQAX(double&,double &,double&); void LBS(double,double,double&); void REFLECT_1D(int&,int,double&); void RBC(double &, double &, double & , double &, double &,double &); void AIFX(double & ,double &, double & , double &, double &, double&, double &, double&); void REMOVE_MOL(int &); void INDEX_MOLS(); void SAMPLE_FLOW(); void ADAPT_CELLS_1D(); void EXTEND_MNM(double); void DISSOCIATION(); void ENERGY(int ,double &); void COLLISIONS(); void SETXT(); void READ_RESTART(); void WRITE_RESTART(); void READ_DATA(); void OUTPUT_RESULTS(); void MOLECULES_MOVE_1D(); class Managed { public: void *operator new(size_t len) { void *ptr; cudaMallocManaged(&ptr, len); cudaDeviceSynchronize(); return ptr; } void operator delete(void *ptr) { cudaDeviceSynchronize(); cudaFree(ptr); } }; class CALC : public Managed { public: //declares the variables associated with the calculation int NVER,MVER,IMEG,NREL,MOLSC,ISF,ISAD,ISECS,IGS,IREM,NNC,IMTS,ERROR,NLINE,ICLASS,NCLASS,NMCC,NMI,NMP,ICN; double FTIME,TLIM,FNUM,DTM,TREF,TSAMP,TOUT,SAMPRAT,OUTRAT,RANF,TOTCOLI,TOTMOVI,TENERGY,DTSAMP,DTOUT,TPOUT,FRACSAM,TOTMOV,TOTCOL,ENTMASS,ENTREM,CPDTM,TPDTM,TNORM,FNUMF; double *VNMAX,*TDISS,*TRECOMB,*ALOSS,*EME,*AJM; double **TCOL; void d_allocate(int x, double*&arr){ cudaMallocManaged(&arr, x*sizeof(double)); } void d_allocate(int x, int y, double**&arr){ cudaMallocManaged(&arr, x*sizeof(double)); for(int i =0; i< x; ++i) cudaMallocManaged(&arr[i], y*sizeof(double)); } //NVER.MVER.NREL the version number //IMEG the initial number of megabytes to be used by the program //MOLSC the target number of molecules per sampling cell //FTIME the flow time //TLIM the time at which the calculation stops //FNUM the number of real molecules represented by each simulated molecule //CPDTM the maximum number of collisions per time step (standard 0.2) //TPDTM the maximum number of sampling cell transit times of the flow per time step //TOTMOV total molecule moves //TOTCOL total collisions //TDISS(L) dissociations of species L since sample reset //TRECOMB(L) recombinations of species L since sample reset //ENTMASS the current entry mass of which a fraction FREM is to be removed //ENTREM the remainder (always negative) after molecule removal //VNMAX(L) the maximum normal velocity component of species L //TCOL species dependent collision counter //ISF 0,1 for steady, unsteady flow sampling //ISAD 0,1 to not automatically adapt cells each output interval in unsteady sampling, 1 to automatically adapt //ISECS 0,1 for no secondary stream,a secondary stream that applies for positive values of x //IREM data item to set type of molecule removal //NNC 0 for normal collisions, 1 for nearest neighbor collisions //IMTS 0 for uniform move time steps, 1 for time steps that vary over the cells, 2 for fixed time steps //IGS 0 for initial gas, 1 for stream(s) or reference gas //ICLASS class of flow //NCLASS the dimension of PX for the class of flow //NMCC desired number of molecules in a collision cell //NMI the initial number of molecules //TNORM normalizing time (may vary e.g. mean collision time , or a transit time) //ALOSS(L) number of molecules of speciel L lost in the move rourine //EME(L) number of species L that enter the front boundary //AJM(L) the adjustment number to allow for negative downstream entry numbers //NMP the number of molecules at the start of the move routine //ICN 0 if molecules with ITYPE(2)=4 are not kept constant, 1 to keep molecule number constant //FNUMF adjustment factor that is applied to automatically generated value }; class MOLECS : public Managed { //declares the variables associated with the molecules public: int *IPCELL,*IPSP,*ICREF,*IPCP; int **IPVIB; void i_allocate(int x, int *&arr){ cudaMallocManaged(&arr, x*sizeof(int)); } void i_allocate(int x, int y, int **&arr){ cudaMallocManaged(&arr, x*sizeof(int)); for(int i =0; i< x; ++i) cudaMallocManaged(&arr[i], y*sizeof(int)); } double **PX,**PV; double *PTIM,*PROT,*PELE; void d_allocate(int x, double *&arr){ cudaMallocManaged(&arr, x*sizeof(double)); } void d_allocate(int x, int y, double **&arr){ cudaMallocManaged(&arr, x*sizeof(double)); for(int i =0; i< x; ++i){ try{ cudaMallocManaged(&arr[i], y*sizeof(double)); } catch (std::bad_alloc& ba){ std::cerr << "bad_alloc caught: " << ba.what() << '\n'; } } } int NM,MNM; //PX(1,2 or 3,N) x,y,z position coordinates of molecule N //PTIM(N) molecule time //IPSP(N) the molecular species //IPCELL(N) the collision cell number //ICREF the cross-reference array (molecule numbers in order of collision cells) //IPCP(N) the code number of the last collision partner of molecule //PV(1-3,N) u,v,w velocity components //PROT(N) rotational energy //IPVIB(K,N) level of vibrational mode K of molecule N //PELE(N) electronic energy //NM number of molecules //MNM the maximum number of molecules }; class GAS : public Managed { //declares the variables associated with the molecular species and the stream definition public: double RMAS,CXSS,RGFS,VMPM,FDEN,FPR,FMA,FPM,CTM; double FND[3],FTMP[3],FVTMP[3],VFX[3],VFY[3],TSURF[3],FSPEC[3],VSURF[3]; double *ERS,*CR,*TNEX,*PSF,*SLER,*FP; double **FSP,**SP,**SPR,**SPV,**VMP; double ***SPM,***SPVM,***ENTR,***QELC,***SPRT; double ****SPEX,****SPRC,****SPRP; double *****SPREX; void d_allocate(int x, double *&arr){ cudaMallocManaged(&arr, x*sizeof(double)); } void d_allocate(int x, int y, double **&arr){ cudaMallocManaged(&arr, x*sizeof(double)); for(int i =0; i< x; ++i) cudaMallocManaged(&arr[i], y*sizeof(double)); } void d_allocate(int x, int y, int z, double***&arr){ cudaMallocManaged(&arr, x*sizeof(double)); for (int i = 0; i < x; ++i) { cudaMallocManaged(&arr[i], y*sizeof(double)); for (int j = 0; j < y; ++j) cudaMallocManaged(&arr[i][j], z*sizeof(double)); } } void d_allocate(int x, int y, int z, int w, double ****&arr){ cudaMallocManaged(&arr, x*sizeof(double)); for (int i = 0; i < x; ++i) { cudaMallocManaged(&arr[i], y*sizeof(double)); for (int j = 0; j < y; ++j) { cudaMallocManaged(&arr[i][j], z*sizeof(double)); for(int k=0; k<z; ++k) cudaMallocManaged(&arr[i][j][k], w*sizeof(double)); } } } void d_allocate(int x, int y, int z, int w, int v, double*****&arr){ cudaMallocManaged(&arr, x*sizeof(double)); for (int i = 0; i < x; ++i) { cudaMallocManaged(&arr[i], y*sizeof(double)); for (int j = 0; j < y; ++j) { cudaMallocManaged(&arr[i][j], z*sizeof(double)); for(int k=0; k<z; ++k) { cudaMallocManaged(&arr[i][j][k], w*sizeof(double)); for(int l=0; l<w; ++l) cudaMallocManaged(&arr[i][j][k][l], v*sizeof(double)); } } } } int MSP,MMVM,MMRM,MNSR,IGAS,MMEX,MEX,MELE,MVIBL; int *ISP,*ISPV,*NELL; int **ISPR,**LIS,**LRS,**ISRCD,**ISPRC,**ISPRK,**TREACG,**TREACL,**NSPEX,**NSLEV; int ***ISPVM,***NEX; int ****ISPEX; void i_allocate(int x, int *&arr){ cudaMallocManaged(&arr, x); } void i_allocate(int x, int y, int **&arr){ cudaMallocManaged(&arr, x*sizeof(int)); for(int i =0; i< x; ++i) cudaMallocManaged(&arr[i], y*sizeof(int)); } void i_allocate(int x, int y, int z, int ***&arr){ cudaMallocManaged(&arr, x*sizeof(int)); for (int i = 0; i < x; ++i) { cudaMallocManaged(&arr[i], y*sizeof(int)); for (int j = 0; j < y; ++j) cudaMallocManaged(&arr[i][j], z*sizeof(int)); } } void i_allocate(int x, int y, int z, int w, int ****&arr){ cudaMallocManaged(&arr, x*sizeof(int)); for (int i = 0; i < x; ++i) { cudaMallocManaged(&arr[i], y*sizeof(int)); for (int j = 0; j < y; ++j) { cudaMallocManaged(&arr[i][j], z*sizeof(int)); for(int k=0; k<z; ++k) cudaMallocManaged(&arr[i][j][k], w*sizeof(int)); } } } //MSP the number of molecular species //MMVM the maximum number of vibrational modes of any species //MEX number of exchange or chain reactions //MELE the maximum number of electronic states of any molecule //MVIBL the maximum number of vibrational levels for detailed balance lists //MMEX the maximum number of exchange reactions involving the same precollision pair of molecules //MMRM 0 if gass is completely monatomic, 1 if some species have rotation //MNSR the number oF surface reactions //SP(1,L) the reference diameter of species L //SP(2,L) the reference temperature of species L //SP(3,L) the viscosity-temperature power law of species L //SP(4,L) the reciprocal of the VSS scattering parameter //SP(5,L) molecular mass of species L //SP(6,L) the heat of formation at 273 K. //ISPR(1,L) number of rotational degrees of freedom of species L //ISPR(2,L) 0,1 for constant, polynomial rotational relaxation collision number //SPR(1,L) constant rotational relaxation collision number of species L // or the constant in a second order polynomial in temperature //SPR(2,L) the coefficient of temperature in the polynomial //SPR(3,L) the coefficient of temperature squared in the polynomial //SPM(1,L,M) the reduced mass for species L,M //SPM(2,L,M) the reference collision cross-section for species L,M //SPM(3,L,M) the mean value of the viscosity-temperature power law //SPM(4,L,M) the reference diameter for L,M collisions //SPM(5,L,M) the reference temperature for species L,M //SPM(6,L,M) reciprocal of the gamma function of (5/2-w) for species L,M //SPM(7,L,M) rotational relaxation collision number for species L,M, or const in polynomial //SPM(8,L,M) reciprocal of VSS scattering parameter //ISPV(L) the number of vibrational modes //SPVM(1,K,L) the characteristic vibrational temperature //SPVM(2,K,L) constant Zv, or reference Zv for mode K //SPVM(3,K,L) -1. for constant Zv, or reference temperature //SPVM(4,K,L) the characteristic dissociation temperature //SPVM(5,K,L) the arbitrary rate reduction factor //ISPVM(1,K,L) the species code of the first dissociation product //ISPVM(2,K,L) the species code of the second dissociation product //NELL(L) the number of electronic levels of species L //QELC(N,M,L) for up to M levels of form g*exp(-a/T) in the electronic partition function for species L // N=1 for the degeneracy g // N=2 for the coefficient a // N=3 for the ratio of the excitation cross-section to the elastic cross-section //ISPRC(L,M) the species of the recombined molecule from species L and M //ISPRK(L,M) the applicable vibrational mode of this species //SPRC(1,L,M,K) the constant a in the ternary collision volume //SPRC(2,L,M,K) the temperature exponent b in the ternary collision volume //SPRT(1,L,M) lower temperature value for SPRP //SPRT(2,L,M) higher temperature value for SPRP //SPRP(1,L,M,K) the cumulative dissociation distribution to level K for products L and M at the lower temperature //SPRP(2,L,M,K) ditto at higher temperature, for application to post-recombination molecule// //NSPEX(L,M) the number of exchange reactios with L,M as the pre-collision species //in the following variables, J is the reaction number (1 to NSPEX(L,M)) //ISPEX(J,1,L,M) the species that splits in an exchange reaction //ISPEX(J,2,L,M) the other pre-reaction species (all ISPEX are set to 0 if no exchange reaction) //ISPEX(J,3,L,M) the post-reaction molecule that splits in the opposite reaction //ISPEX(J,4,L,M) the other post-reaction species //ISPEX(J,5,L,M) the vibrational mode of the molecule that splits //ISPEX(J,6,L,M) degeneracy of this reaction //ISPEX(J,7,L,M) the vibrational mode of the molecule that splits //SPEX(1,J,L,M) the constant a in the reaction probability for the reverse reaction //SPEX(2,J,L,M) the temperature exponent b in the reaction probability (reverse reaction only) //SPEX(3,J,L,M) for the heat of reaction //SPEX(4,J,L,M) the lower temperature for SPREX //SPEX(5,J,L,M) the higher temperature for SPREX //SPEX(6,J,L,M) the energy barrier //SPREX(1,J,L,M,K) at lower temperature, the Jth reverse exchange reaction of L,M cumulative level K viv. dist of post reac mol //SPREX(2,J,L,M,K) ditto at higher temperature //TNEX(N) total number of exchange reaction N //NEX(N,L,M) the code number of the Nth exchange or chain reaction in L,M collisions //RMAS reduced mass for single species case //CXSS reference cross-section for single species case //RGFS reciprocal of gamma function for single species case //for the following, J=1 for the reference gas and/or the minimum x boundary, J=2 for the secondary sream at maximum x boundary //FND(J) stream or reference gas number density //FTMP(J) stream temperature //FVTMP(J) the vibrational and any electronic temperature in the freestream //VFX(J) the x velocity components of the stream //VFY(J) the y velocity component in the stream //FSP(N,J)) fraction of species N in the stream //FMA stream Mach number //VMP(N,J) most probable molecular velocity of species N at FTMP(J) //VMPM the maximum value of VMP in stream 1 //ENTR(M,L,K) entry/removal information for species L at K=1 for 1, K=2 for XB(2) // M=1 number per unut time // M=2 remainder // M=3 speed ratio // M=4 first constant // M=5 second constant // M=6 the maxinum normal velocity component in the removal zone (> XREM) //LIS(1,N) the species code of the first incident molecule //LIS(2,N) the species code of the second incident molecule (0 if none) //LRS(1,N) the species code of the first reflected molecule //LRS(2,N) the species code of the second reflected molecule (0 if none) //LRS(3,N) the species code of the third reflected molecule (0 if none) //LRS(4,N) the species code of the fourth reflected molecule (0 if none) //LRS(5,N) the species code of the fifth reflected molecule (0 if none) //LRS(6,N) the species code of the sixth reflected molecule (0 if none) //ERS(N) the energy of the reaction (+ve for recombination, -ve for dissociation) //NSRSP(L) number of surface reactions that involve species L as incident molecule //ISRCD(N,L) code number of Nth surface reaction with species L as incident molecule //CTM mean collision time in stream //FPM mean free path in stream //FDEN stream 1 density //FPR stream 1 pressure //FMA stream 1 Mach number //RMAS reduced mass for single species case //CXSS reference cross-section for single species case //RGFS reciprocal of gamma function for single species case //CR(L) collision rate of species L //FP(L) mean free path of species L //TREACG(N,L) the total number of species L gained from reaction type N=1 for dissociation, 2 for recombination, 3 for forward exchange, 4 for reverse exchange //TREACL(N,L) the total number of species L lost from reaction type N=1 for dissociation, 2 for recombination, 3 for forward exchange, 4 for reverse exchange //NSLEV(2,L) 1 exo, 2 endo: vibrational levels to be made up for species L in detailed balance enforcement after reaction //SLER(L) rotational energy to be made up for species L in detailed balance enforcement after exothermic reaction }; class OUTPUT : public Managed { public: //declares the variables associated with the sampling and output int NSAMP,NMISAMP,NOUT,NDISSOC,NRECOMB,NTSAMP; //int NDISSL[201]; int *NDISSL; OUTPUT(){ cudaMallocManaged(&NDISSL,201*sizeof(int)); }; double TISAMP,XVELS,YVELS,AVDTM; double *COLLS,*WCOLLS,*CLSEP,*SREAC,*STEMP,*TRANSTEMP,*ROTTEMP,*VIBTEMP,*ELTEMP; double **VAR,**VARS,**CSSS,**SUMVIB; double ***CS,***VARSP,***VIBFRAC; double ****CSS; void d_allocate(int x, double *&arr){ cudaMallocManaged(&arr, x*sizeof(double)); } void d_allocate(int x, int y, double **&arr){ cudaMallocManaged(&arr, x*sizeof(double)); for(int i =0; i< x; ++i) cudaMallocManaged(&arr[i], y*sizeof(double)); } void d_allocate(int x, int y, int z, double ***&arr){ cudaMallocManaged(&arr, x*sizeof(double)); for (int i = 0; i < x; ++i) { cudaMallocManaged(&arr[i], y*sizeof(double)); for (int j = 0; j < y; ++j) cudaMallocManaged(&arr[i][j], z*sizeof(double)); } } void d_allocate(int x, int y, int z, int w, double ****&arr){ cudaMallocManaged(&arr, x*sizeof(double)); for (int i = 0; i < x; ++i) { cudaMallocManaged(&arr[i], y*sizeof(double)); for (int j = 0; j < y; ++j) { cudaMallocManaged(&arr[i][j], z*sizeof(double)); for(int k=0; k<z; ++k) cudaMallocManaged(&arr[i][j][k], w*sizeof(double)); } } } //NSAMP the number of samples //TISAMP the time at which the sampling was last reset //MNISAMP the number of molecules at the last reset //AVDTM the average value of DTM in the cells //NOUT the number of output intervals //COLLS(N) total number of collisions in sampling cell N //WCOLLS(N) total weighted collisins in N //CLSEP(N) sum of collision pair separation in cell N //CS(0,N,L) sampled number of species L in cell N //CS(1,N,L) sampled weighted number of species L in cell N //--all the following CS are weighted sums //CS(2,N,L), CS(3,N,L), CS(4,N,L) sampled sum of u, v, w //CS(5,N,L), CS(6,N,L), CS(7,N,L) sampled sum of u*u, v*v, w*w //CS(8,N,L) sampled sum of rotational energy of species L in cell N //CS(9,N,L) sampled sum of electronic energy of species L in cell N //CS(9+K,N,L) sampled sum of vibrational level of species L in cell N // K is the mode // //in CSS, M=1 for incident molecules and M=2 for reflected molecules //J=1 for surface at x=XB(1), 2 for surface at x=XB(2) // //CSS(0,J,L,M) number sum of molecules of species L //CSS(1,J,L,M) weighted number sum of molecules of species L //--all the following CSS are weighted //CSS(2,J,L,M) normal momentum sum to surface //CSS(3,J,L,M) y momentum sum to surface //CSS(4,J,L,M) z momentum sum to surface //CSS(5,J,L,M) tranlational energy sum to surface //CSS(6,J,L,M) rotational energy sum to surface //CSS(7,J,L,M) vibrational energy sum to the surface //CSS(8,J,L,M) electronic energy sum to the surface // //CSSS(1,J) weighted sum (over incident AND reflected molecules) of 1/normal vel. component //--all the following CSSS are weighted //CSSS(2,J) similar sum of molecular mass / normal vel. component //CSSS(3,J) similar sum of molecular mass * parallel vel. component / normal vel. component //CSSS(4,J) similar sum of molecular mass * speed squared / normal vel. component //CSSS(5,J) similar sum of rotational energy / normal vel. component //CSSS(6,J) similar sum of rotational degrees of freedom /normal velocity component // //SREAC(N) the number of type N surface reactions // //VAR(M,N) the flowfield properties in cell N //M=1 the x coordinate //M=2 sample size //M=3 number density //M=4 density //M=5 u velocity component //M=6 v velocity component //M=7 w velocity component //M=8 translational temperature //M=9 rotational temperature //M=10 vibrational temperature //M=11 temperature //M=12 Mach number //M=13 molecules per cell //M=14 mean collision time / rate //M=15 mean free path //M=16 ratio (mean collisional separation) / (mean free path) //M=17 flow speed //M=18 scalar pressure nkT //M=19 x component of translational temperature TTX //M=20 y component of translational temperature TTY //M=21 z component of translational temperature TTZ //M=22 electronic temperature // //VARSP(M,N,L) the flowfield properties for species L in cell N //M=0 the sample size //M=1 the fraction //M=2 the temperature component in the x direction //M=3 the temperature component in the y direction //M=4 the temperature component in the z direction //M=5 the translational temperature //M=6 the rotational temperature //M=7 the vibrational temperature //M=8 the temperature //M=9 the x component of the diffusion velocity //M=10 the y component of the diffusion velocity //M=11 the z component of the diffusion velocity //M=12 the electronic temperature // //VARS(N,M) surface property N on interval L of surface M // //N=0 the unweighted sample (remainder of variables are weighted for cyl. and sph. flows) //N=1 the incident sample //N=2 the reflected sample //N=3 the incident number flux //N=4 the reflected number flux //N=5 the incident pressure //N=6 the reflected pressure //N=7 the incident parallel shear tress //N=8 the reflected parallel shear stress //N=9 the incident normal-to-plane shear stress //N=10 the reflected normal shear stress //N=11 the incident translational heat flux //N=12 the reflected translational heat fluc //N=13 the incident rotational heat flux //N=14 the reflected rotational heat flux //N=15 the incident vibrational heat flux //N=16 the reflected vibrational heat flux //N=17 the incident heat flux from surface reactions //N=18 the reflected heat flux from surface reactions //N=19 slip velocity //N=20 temperature slip //N=21 rotational temperature slip //N=22 the net pressure //N=23 the net parallel in-plane shear //N=24 the net parallel normal-to-plane shear //N=25 the net translational energy flux //N=26 the net rotational heat flux //N=27 the net vibrational heat flux //N=28 the heat flux from reactions //N=29 total incident heat transfer //N=30 total reflected heat transfer //N=31 net heat transfer //N=32 surface temperature --not implemented //N=33 incident electronic energy //N=34 reflected electronic energy //N=35 net electronic energy //N=35+K the percentage of species K // //COLLS(N) the number of collisions in sampling cell N //WCOLLS(N) weighted number //CLSEP(N) the total collision partner separation distance in sampling cell N // //VIBFRAC(L,K,M) the sum of species L mode K in level M //SUMVIB(L,K) the total sample in VIBFRAC // //THE following variables apply in the sampling of distribution functions //(some are especially for the dissociation of oxygen // //NDISSOC the number of dissociations //NRECOMB the number of recombinations //NDISSL(L) the number of dissociations from level //NTSAMP the number of temperature samples //STEMP(L) the temperature of species L //TRANSTEMP(L) the translational temperature of species N //ROTTEMP(L) rotational temperature of species N //VIBTEMP(L) vibrational temperature of species N //ELTEMP(L) electronic temperature of species N // }; class GEOM_1D : public Managed { public: //declares the variables associated with the flowfield geometry and cell structure //for homogeneous gas and one-dimensional flow studies int NCELLS,NCCELLS,NCIS,NDIV,MDIV,ILEVEL,IFX,JFX,IVB,IWF; //int ITYPE[3]; int *ITYPE; int *ICELL; int ** ICCELL,**JDIV; void i_allocate(int x, int *&arr){ cudaMallocManaged(&arr, x*sizeof(int)); } void i_allocate(int x, int y, int **&arr){ cudaMallocManaged(&arr, x*sizeof(int)); for(int i =0; i< x; ++i) cudaMallocManaged(&arr[i], y*sizeof(int)); } double DDIV,XS,VELOB,WFM,AWF,FREM,XREM; //double XB[3]; double *XB; double **CELL,**CCELL; void d_allocate(int x, int y, double**&arr){ cudaMallocManaged(&arr, x*sizeof(double)); for(int i =0; i< x; ++i) cudaMallocManaged(&arr[i], y*sizeof(double)); } GEOM_1D(){ cudaMallocManaged(&ITYPE, 3*sizeof(int)); cudaMallocManaged(&XB, 3*sizeof(double)); } // //XB(1), XB(2) the minimum, maximum x coordinate //DDIV the width of a division //ITYPE(K) the tpe of boundary at the minimum x (K=1) and maximum x (K=2) boundaries // 0 for a stream boundary // 1 for a plane of symmetry // 2 for a solid surface // 3 for a vacuum //NCELLS the number of sampling cells //NCCELLS the number of collision cells //NCIS the number of collision cells in a sampling cell // MDIV the maximum number of sampling cell divisions at any level of subdivision //IVB 0,1 for stationary, moving outer boundary //IWF 0 for no radial weighting factors, 1 for radial weighting factors //WFM, set in data as the maximum weighting factor, then divided by the maximum radius //AWF overall ratio of real to weighted molecules //VELOB the speed of the outer boundary //ILEV level of subdivision in adaption (0 before adaption) //JDIV(N,M) (-cell number) or (start address -1 in JDIV(N+1,M), where M is MDIV //IFX 0 for plane flow, 1 for cylindrical flow, 3 for spherical flow //JFX IFX+1 //CELL(M,N) information on sampling cell N // M=1 x coordinate // M=2 minimum x coordinate // M=3 maximum x cooedinate // M=4 volume //ICELL(N) number of collision cells preceding those in sampling cell N //CCELL(M,N) information on collision cell N // M=1 volume // M=2 remainder in collision counting // M=3 half the allowed time step // M=4 maximum value of product of cross-section and relative velocity // M=5 collision cell time //ICCELL(M,N) integer information on collision cell N // M=1 the (start address -1) in ICREF of molecules in collision cell N // M=2 the number of molecules in collision cell N // M=3 the sampling cell in which the collision cell lies //FREM fraction of molecule removal //XREM the coordinate at which removal commences // }; clock_t start; fstream file_9; fstream file_18; CALC *calc = new CALC; GAS *gas = new GAS; MOLECS *molecs = new MOLECS; GEOM_1D *geom = new GEOM_1D; OUTPUT *output =new OUTPUT; template <typename T> string to_string(T value) { std::ostringstream os ; os << value ; return os.str() ; } int main() { // //CALC calc; // //MOLECS molecs; // //GAS gas; // //OUTPUT output; // //GEOM_1D geom; // // IMPLICIT NONE\ // int IRUN,ICONF,N,M,IADAPT,IRETREM,ISET; double A; // fstream file_7; calc->NVER=1; //for major changes, e.g. to basic architecture calc->MVER=1 ; //significant changes, but must change whenever the data in a DSnD.DAT file changes calc->NREL=1 ; //the release number // //*********************** //set constants // PI=3.1415926535897932D00 // DPI=6.283185307179586D00 // SPI=1.772453850905516D00 // BOLTZ=1.380658D-23 // AVOG=6.022169D26 //*********************** // //************************************************* //**** ADJUSTABLE COMPUTATIONAL PARAMETERS **** //************************************************* // calc->NMCC=15; //DEFAULT=15--desired number of simulated molecules in a collision cell // calc->CPDTM=0.2; //DEFAULT=0.2--fraction of the local mean collision time that is the desired maximum time step // calc->TPDTM=0.5 ; //DEFAULT=0.5--the fraction or multiple of a sampling cell transit time that is the desired maximum time step // calc->NNC=1; //DEFAULT=0--0 to select collision partner randomly from collision cell, 1 for nearest-neighbor collisions // calc->SAMPRAT=5; //DEFAULT=5--the number of time steps in a sampling interval // calc->OUTRAT=10; //50 //DEFAULT=50--the number of flow samples in a file output interval // calc->FRACSAM=0.5; //0.5 //DEFAULT=0.5--fraction of the output interval interval over which a time-averaged sample is taken in an unsteady flow // calc->ISAD=0; //DEFAULT=0--0,1 to not adapt, to adapt cells automatically at start of output interval in an unsteady flow (not yet implemented) // calc->IMTS=2; //DEFAULT=0--0 to set the move time step to the instantaneous overall time step that changes with time // 1 to use a cell dependent collision time // 2 to keep the time step fixed at the initial value // calc->FNUMF=1; //DEFAULT=1--adjustment factor to the automatically generated value for the number of real molecules // that are represented by each simulated molecule. // (The adjustment may be large because the automatic setting assumes that the whole flowfield is at the stream conditions.) // //automatic adjustments may be applied for some application classes (e.g homogeneous gas studies) // calc->TLIM=1.e-5; //DEFAULT=1.D20 sets an indefinite run - set if a define STOP time is required // //************************************************ // //open a diagnostic file and check whether an instance of the program is already running // // fstream file_9; cout<<"DSMC PROGRAM"<<endl; file_9.open("DIAG.TXT", ios::trunc | ios::out); if(file_9.is_open()){ file_9<<"File DIAG.TXT has been opened"<<endl; cout<<"File DIAG.TXT has been opened"<<endl; } else{ cout<<"Stop the DS1.EXE that is already running and try again"<<endl; //return 0; } // OPEN (9,FILE='DIAG.TXT',FORM='FORMATTED',STATUS='REPLACE') // WRITE (9,*,IOSTAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*) 'Stop the DS1.EXE that is already running and try again' // STOP // ELSE // WRITE (9,*) 'File DIAG.TXT has been opened' // END IF // //open a molecule number history file //OPEN (13,FILE='MolNum.DAT',FORM='FORMATTED',STATUS='REPLACE') // //initialise run variables IRUN=0; geom->IVB=0; //will be reset to 1 by restart program if there is a moving wall // while((IRUN < 1) || (IRUN > 2)){ cout<< "DSMC Version" <<calc->NVER<<'.'<<calc->MVER<<'.'<<calc->NREL<<endl; cout<< "enter 1 to continue a current run"<<endl; cout<< "enter 2 to start a new run :-"<<endl; // cin>> IRUN; } if(IRUN == 1) file_9<< "Continuing an existing run"<<endl;//WRITE (9,*) 'Continuing an existing run' if(IRUN == 2) { cout<< "Enter 1 to confirm, 0 to continue current run :-"<<endl; cin>> ICONF; if(ICONF == 1) file_9<<"Starting a new run"<<endl;//WRITE (9,*) 'Starting a new run' else{ IRUN=1; file_9<<"Continuing an existing run"<<endl; //WRITE (9,*) 'Continuing an existing run' } } // if(IRUN == 2){ //new run cout<< "Enter 0 for a homogeneous gas, or"<<endl; cout<< "Enter 1 for a one-dimensional flow, or"<<endl; cout<< "Enter 2 for a two-dimensional plane flow, or"<<endl; cout<< "Enter 3 for a three dimensional flow, or"<<endl; cout<< "enter 4 for an axially-symmetric flow :-"<<endl; cin>> calc->ICLASS; calc->NCLASS=2; //default 2D if(calc->ICLASS < 2) calc->NCLASS=1; //0D or 1D if(calc->ICLASS == 3) calc->NCLASS=3; //3D cout<<"Enter 0 for an eventually steady flow, or"<<endl; cout<<"enter 1 for a continuing unsteady flow :-"<<endl; cin>> calc->ISF; file_7.open("RUN_CLASS.TXT", ios::trunc |ios::out); if(file_7.is_open()){ cout<<"RUN_CLASS.TXT is opened"<<endl; } else{ cout<<"RUN_CLASS.TXT not opened"<<endl; cin.get(); } file_7<<calc->ICLASS<<calc->ISF; file_7.close(); // OPEN (7,FILE='RUN_CLASS.TXT',FORM='FORMATTED',STATUS='REPLACE') // WRITE (7,*) ICLASS,ISF // CLOSE (7) file_9<<"Starting a new run with ICLASS, ISF "<<calc->ICLASS<<" "<<calc->ISF<<endl; // WRITE (9,*) 'Starting a new run with ICLASS, ISF',ICLASS,ISF cout<<"Starting a new run with ICLASS, ISF "<<calc->ICLASS<<" "<<calc->ISF<<endl; } // if(IRUN == 1){ //continued run file_7.open("RUN_CLASS.TXT" , ios::in ); if(file_7.is_open()){ cout<<"RUN_CLASS.TXT is opened"<<endl; } else{ cout<<"RUN_CLASS.TXT not opened"<<endl; cin.get(); } file_7 >>calc->ICLASS>>calc->ISF; file_7.close(); // OPEN (7,FILE='RUN_CLASS.TXT',FORM='FORMATTED',STATUS='OLD') // READ (7,*) ICLASS,ISF // CLOSE(7) READ_RESTART(); // calc->TSAMP=calc->FTIME+calc->DTSAMP; calc->TOUT=calc->FTIME+calc->DTOUT; if((gas->MEX > 0) && (calc->ISF == 1)){ cout<<"Enter 0 to continue the reaction sample or"<<endl; cout<<"enter 1 to continue with a new reaction sample :-"<<endl; cin>> N; if(N == 1){ //memset(gas->TNEX,0.e00,sizeof(*gas->TNEX)); //memset(calc->TDISS,0.e00,sizeof(*calc->TDISS)); //memset(calc->TRECOMB,0.e00,sizeof(*calc->TRECOMB)); for(int i=0;i<gas->MEX+1;i++) gas->TNEX[i]= 0.e00; for(int i=0;i<gas->MSP+1;i++) calc->TDISS[i]=0.e00; for(int i=0;i<gas->MSP+1;i++) calc->TRECOMB[i]=0.e00; } } // if((calc->ISAD == 0) && (calc->ISF == 0)){ cout<<"Enter 0 to continue the current sample or"<<endl; cout<<"enter 1 to continue with a new sample :-"<<endl; cin>> N; if(N == 1){ if((geom->ITYPE[2] == 4) && (calc->ICN == 0)){ cout<<"Enter 0 to continue to not enforce constant molecule number"<<endl; cout<<"enter 1 to start to enforce constant molecule number :-"<<endl; cin>> M; if(M == 1) calc->ICN=1; } cout<<"Enter 1 to adapt the cells, or 0 to continue with current cells:-"<<endl; cin>>IADAPT; if(IADAPT == 1){ cout<<"Adapting cells"<<endl; ADAPT_CELLS_1D() ; INDEX_MOLS(); WRITE_RESTART(); } else cout<<"Continuing with existing cells"<<endl; // if(calc->IREM == 2){ cout<<"Enter 1 to reset the removal details, or 0 to continue with current details:-"<<endl; cin>>IRETREM; if(IRETREM == 1){ geom->FREM=-1.e00; while((geom->FREM < -0.0001) || (geom->FREM > 5.0)){ cout<<"Enter the fraction of entering molecules that are removed:-"<<endl; cin>>geom->FREM; cout<<"The ratio of removed to entering mlecules is \t"<<geom->FREM<<endl; // WRITE (*,999) FREM } file_9<<"The ratio of removed to entering mlecules is \t"<<geom->FREM<<endl; // WRITE (9,999) FREM // 999 FORMAT (' The ratio of removed to entering molecules is ',G15.5) if(geom->FREM > 1.e-10){ geom->XREM=geom->XB[1]-1.0; while((geom->XREM < geom->XB[1]-0.0001) || (geom->XREM > geom->XB[2]+0.0001)){ cout<<"Enter x coordinate of the upstream removal limit:-"<<endl; cin>>geom->XREM; cout<<"The molecules are removed from \t"<<geom->XREM<<" to "<<geom->XB[2]<<endl; //988 // WRITE (*,998) XREM,XB(2) } file_9<<"The molecules are removed from \t"<<geom->XREM<<" to "<<geom->XB[2]<<endl; // WRITE (9,998) XREM,XB(2) // 998 FORMAT (' The molecules are removed from ',G15.5,' to',G15.5) } } } // INITIALISE_SAMPLES(); } } } // if(IRUN == 2){ // READ_DATA(); // if(calc->ICLASS < 2) SET_INITIAL_STATE_1D(); // if(calc->ICLASS == 0) ENERGY(0,A); // WRITE_RESTART(); // } // while(calc->FTIME < calc->TLIM){ // // calc->FTIME=calc->FTIME+calc->DTM; // file_9<<" TIME "<<setw(20)<<setprecision(10)<<calc->FTIME<<" NM "<<molecs->NM<<" COLLS "<<std::left<<setw(20)<<setprecision(10)<<calc->TOTCOL<<endl; // WRITE (9,*) 'TIME',FTIME,' NM',NM,' COLLS',TOTCOL cout<< " TIME "<<setw(20)<<setprecision(10)<<calc->FTIME<<" NM "<<molecs->NM<<" COLLS "<<std::left<<setw(20)<<setprecision(10)<<calc->TOTCOL<<endl; // // WRITE (13,*) FTIME/TNORM,FLOAT(NM)/FLOAT(NMI) //uncomment if a MOLFILE.DAT is to be generated // // WRITE (*,*) 'MOVE' //cout<<"MOVE"<<endl; MOLECULES_MOVE_1D(); // if((geom->ITYPE[1] == 0) || (geom->ITYPE[2] == 0) || (geom->ITYPE[2] == 4)) MOLECULES_ENTER_1D(); // // WRITE (*,*) 'INDEX' //ut<<"INDEX"<<endl; // cout<<calc->TOUT<<endl; // cin.get(); INDEX_MOLS(); // // WRITE (*,*) 'COLLISIONS' COLLISIONS(); // // if(gas->MMVM > 0) { // cout<<"DISSOCIATION"<<endl; // DISSOCIATION(); // } // if(calc->FTIME > calc->TSAMP){ // WRITE (*,*) 'SAMPLE' if(calc->ISF == 0) SAMPLE_FLOW(); if((calc->ISF == 1) && (calc->FTIME < calc->TPOUT+(1.e00-calc->FRACSAM)*calc->DTOUT)){ calc->TSAMP=calc->TSAMP+calc->DTSAMP; INITIALISE_SAMPLES(); } if((calc->ISF == 1) && (calc->FTIME >= calc->TPOUT+(1.e00-calc->FRACSAM)*calc->DTOUT)) SAMPLE_FLOW(); } // if(calc->FTIME > calc->TOUT){ cout<<"writing OUTPUT"<<endl; // WRITE (*,*) 'OUTPUT' WRITE_RESTART(); // OUTPUT_RESULTS(); calc->TPOUT=calc->FTIME; } // } return 0; // } void ALLOCATE_GAS() { // //GAS gas; // //CALC calc; gas->d_allocate(gas->MSP+1,3,gas->FSP); gas->d_allocate(7,gas->MSP+1,gas->SP); gas->d_allocate(4,gas->MSP+1,gas->SPR); gas->d_allocate(9,gas->MSP+1,gas->MSP,gas->SPM); gas->i_allocate(3,gas->MSP+1,gas->ISPR); gas->i_allocate(gas->MSP+1,gas->ISPV); gas->d_allocate(7,gas->MSP+1,3,gas->ENTR); gas->d_allocate(gas->MSP+1,3,gas->VMP); calc->d_allocate(gas->MSP+1,calc->VNMAX); gas->d_allocate(gas->MSP+1,gas->CR); calc->d_allocate(gas->MSP+1,gas->MSP+1,calc->TCOL); gas->i_allocate(gas->MSP+1,gas->MSP+1,gas->ISPRC); gas->i_allocate(gas->MSP+1,gas->MSP+1,gas->ISPRK); gas->d_allocate(5,gas->MSP+1,gas->MSP+1,gas->MSP+1,gas->SPRC); gas->i_allocate(gas->MSP+1,gas->NELL); gas->d_allocate(4,gas->MELE+1,gas->MSP+1,gas->QELC); gas->d_allocate(3,gas->MSP+1,gas->MSP+1,gas->MVIBL+1,gas->SPRP); gas->d_allocate(3,gas->MSP+1,gas->MSP+1,gas->SPRT); calc->d_allocate(gas->MSP+1,calc->AJM); gas->d_allocate(gas->MSP+1,gas->FP); calc->d_allocate(gas->MSP+1,calc->ALOSS); calc->d_allocate(gas->MSP+1,calc->EME); /*ALLOCATE (FSP(MSP,2),SP(6,MSP),SPR(3,MSP),SPM(8,MSP,MSP),ISPR(2,MSP),ISPV(MSP),ENTR(6,MSP,2), & VMP(MSP,2),VNMAX(MSP),CR(MSP),TCOL(MSP,MSP),ISPRC(MSP,MSP),ISPRK(MSP,MSP),SPRC(4,MSP,MSP,MSP), & NELL(MSP),QELC(3,MELE,MSP),SPRP(2,MSP,MSP,0:MVIBL),SPRT(2,MSP,MSP),AJM(MSP),FP(MSP), & ALOSS(MSP),EME(MSP),STAT=ERROR) // IF (ERROR /= 0) THEN WRITE (*,*)'PROGRAM COULD NOT ALLOCATE SPECIES VARIABLES',ERROR END IF //*/ gas->i_allocate(gas->MMEX+1,gas->MSP+1,gas->MSP+1,gas->NEX); gas->i_allocate(gas->MSP+1,gas->MSP+1,gas->NSPEX); gas->d_allocate(7,gas->MMEX+1,gas->MSP+1,gas->MSP+1,gas->SPEX); gas->i_allocate(gas->MMEX+1,8,gas->MSP+1,gas->MSP+1,gas->ISPEX); gas->i_allocate(5,gas->MSP+1,gas->TREACG); gas->d_allocate(gas->MMEX+1,gas->PSF); gas->i_allocate(5,gas->MSP+1,gas->TREACL); gas->d_allocate(gas->MEX+1,gas->TNEX); gas->d_allocate(3,gas->MMEX+1,gas->MSP+1,gas->MSP+1,gas->MVIBL+1,gas->SPREX); gas->i_allocate(3,gas->MSP+1,gas->NSLEV); gas->d_allocate(gas->MSP+1,gas->SLER); // ALLOCATE (NEX(MMEX,MSP,MSP),NSPEX(MSP,MSP),SPEX(6,MMEX,MSP,MSP),ISPEX(MMEX,7,MSP,MSP),TREACG(4,MSP), & // PSF(MMEX),TREACL(4,MSP),TNEX(MEX),SPREX(2,MMEX,MSP,MSP,0:MVIBL),NSLEV(2,MSP),SLER(MSP),STAT=ERROR) // // // IF (ERROR /= 0) THEN // WRITE (*,*)'PROGRAM COULD NOT ALLOCATE Q-K REACTION VARIABLES',ERROR // END IF // // if(gas->MMVM >= 0){ gas->d_allocate(6,gas->MMVM+1,gas->MSP+1,gas->SPVM); gas->i_allocate(3,gas->MMVM+1,gas->MSP+1,gas->ISPVM); calc->d_allocate(gas->MSP+1,calc->TDISS); calc->d_allocate(gas->MSP+1,calc->TRECOMB); //ALLOCATE (SPVM(5,MMVM,MSP),ISPVM(2,MMVM,MSP),TDISS(MSP),TRECOMB(MSP),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*)'PROGRAM COULD NOT ALLOCATE VIBRATION VARIABLES',ERROR } //N.B. surface reactions are not yet implemented if(gas->MNSR > 0){ gas->d_allocate(gas->MNSR+1,gas->ERS); gas->i_allocate(3,gas->MNSR+1,gas->LIS); gas->i_allocate(7,gas->MNSR+1,gas->LRS); gas->i_allocate(gas->MNSR+1,gas->MSP+1,gas->ISRCD); //ALLOCATE (ERS(MNSR),LIS(2,MNSR),LRS(6,MNSR),ISRCD(MNSR,MSP),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*)'PROGRAM COULD NOT ALLOCATE SURFACE REACTION VARIABLES',ERROR } //calc->AJM=0.e00; //memset(calc->AJM,0.e00,sizeof(*calc->AJM)); for(int i=0;i<gas->MSP+1;i++){ calc->AJM[i]=0.e00; } return; } void HARD_SPHERE() { ////GAS gas; ////CALC calc; cout<<"Reading HARD_SPHERE Data"<<endl; gas->MSP=1; gas->MMRM=0; gas->MMVM=0; gas->MNSR=0; gas->MEX=0; gas->MMEX=0; gas->MELE=1; gas->MVIBL=0; ALLOCATE_GAS(); gas->SP[1][1]=4.0e-10; //reference diameter gas->SP[2][1]=273.0; //reference temperature gas->SP[3][1]=0.5; //viscosity-temperature index gas->SP[4][1]=1.0; //reciprocal of VSS scattering parameter (1 for VHS) gas->SP[5][1]=5.e-26; //mass gas->ISPR[1][1]=0; //number of rotational degrees of freedom cout<<"Hard Sphere data done"<<endl; return; } void ARGON() { // //GAS gas; // //CALC calc; cout<<"Reading Argon Data"<<endl; gas->MSP=1; gas->MMRM=0; gas->MMVM=0; gas->MNSR=0; gas->MEX=0; gas->MMEX=0; gas->MELE=1; gas->MVIBL=0; ALLOCATE_GAS(); gas->SP[1][1]=4.17e-10; gas->SP[2][1]=273.15; gas->SP[3][1]=0.81; gas->SP[4][1]=1.0; gas->SP[5][1]=6.63e-26; gas->ISPR[1][1]=0; gas->ISPR[2][1]=0; cout<<"Argon Data done"<<endl; return; } // void IDEAL_NITROGEN() { // //GAS gas; // //CALC calc; cout<<"Reading IDEAL_NITROGEN data"<<endl; gas->MSP=1; gas->MMRM=1; gas->MMVM=0; gas->MNSR=0; gas->MEX=0; gas->MMEX=0; gas->MELE=0; gas->MVIBL=0; ALLOCATE_GAS(); gas->SP[1][1]=4.17e-10; gas->SP[2][1]=273.0; gas->SP[3][1]=0.74; gas->SP[4][1]=1.0; gas->SP[5][1]=4.65e-26; gas->ISPR[1][1]=2; gas->ISPR[2][1]=0; gas->SPR[1][1]=5.0; return; } // void REAL_OXYGEN() { // //GAS gas; //CALC calc; cout<<"Reading Real_Oxygen data"<<endl; gas->MSP=2; gas->MMRM=1; gas->MMVM=1; gas->MNSR=0; gas->MEX=0; gas->MMEX=0; gas->MELE=5; gas->MVIBL=26; ALLOCATE_GAS(); gas->SP[1][1]=4.07e-10; gas->SP[2][1]=273.00; gas->SP[3][1]=0.77e00; gas->SP[4][1]=1.e00; gas->SP[5][1]=5.312e-26; gas->SP[6][1]=0.e00; gas->ISPR[1][1]=2; gas->ISPR[2][1]=0 ; //0,1 for constant,polynomial rotational relaxation collision number gas->SPR[1][1]=5.0; // the collision number or the coefficient of temperature in the polynomial (if a polynomial, the coeff. of T^2 is in spr_db(3 ) gas->ISPV[1]=1 ; // the number of vibrational modes gas->SPVM[1][1][1]=2256.e00 ; // the characteristic vibrational temperature gas->SPVM[2][1][1]=90000.e00; // a constant Zv, or the reference Zv gas->SPVM[3][1][1]=2256.e00; // -1 for a constant Zv, or the reference temperature gas->SPVM[5][1][1]=1.0; //arbitrary reduction factor gas->ISPVM[1][1][1]=2; gas->ISPVM[2][1][1]=2; gas->NELL[1]=3; if(gas->MELE > 1){ //****** gas->QELC[1][1][1]=3.0; gas->QELC[2][1][1]=0.0; gas->QELC[3][1][1]=50.0; //500. gas->QELC[1][2][1]=2.0; gas->QELC[2][2][1]=11393.0; gas->QELC[3][2][1]=50.0; //500 //for equipartition, the cross-section ratios must be the same for all levels gas->QELC[1][3][1]=1.0; gas->QELC[2][3][1]=18985.0; gas->QELC[3][3][1]=50.0; //500. } // //species 2 is atomic oxygen gas->SP[1][2]=3.e-10; gas->SP[2][2]=273.e00; gas->SP[3][2]=0.8e00; gas->SP[4][2]=1.e00; gas->SP[5][2]=2.656e-26; gas->SP[6][2]=4.099e-19; gas->ISPR[1][2]=0; gas->ISPV[2]=0; //must be set// //set electronic information if(gas->MELE > 1){ gas->NELL[2]=5; gas->QELC[1][1][2]=5.0; gas->QELC[2][1][2]=0.0; gas->QELC[3][1][2]=50.0; gas->QELC[1][2][2]=3.0; gas->QELC[2][2][2]=228.9; gas->QELC[3][2][2]=50.0; gas->QELC[1][3][2]=1.0; gas->QELC[2][3][2]=325.9; gas->QELC[3][3][2]=50.0; gas->QELC[1][4][2]=5.0; gas->QELC[2][4][2]=22830.0; gas->QELC[3][4][2]=50.0; gas->QELC[1][5][2]=1.0; gas->QELC[2][5][2]=48621.0; gas->QELC[3][5][2]=50.0; } //set data needed for recombination // for(int i=0;i<gas->MSP+1;i++){ for(int j=0;j<gas->MSP+1;j++){ gas->ISPRC[i][j]=0; gas->ISPRK[i][j]=0; } } // gas->ISPRC=0; // gas->ISPRK=0; gas->ISPRC[2][2]=1; //O+O -> O2 recombined species code for an O+O recombination gas->ISPRK[2][2]=1 ; //the relevant vibrational mode of this species gas->SPRC[1][2][2][1]=0.04; gas->SPRC[2][2][2][1]=-1.3; gas->SPRC[1][2][2][2]=0.05; gas->SPRC[2][2][2][2]=-1.1; gas->SPRT[1][2][2]=5000.e00; gas->SPRT[2][2][2]=15000.e00; // //memset(gas->NSPEX,0,sizeof(**gas->NSPEX)); //memset(gas->SPEX,0.e00,sizeof(****gas->SPEX)); for(int i=0;i<gas->MSP+1;i++){ for(int j=0;j<gas->MSP+1;j++){ gas->NSPEX[i][j]=0; } } for(int i=0;i<7;i++){ for(int j=0;j<gas->MMEX+1;j++){ for(int k=0;k<gas->MSP+1;k++){ for(int l=0;l<gas->MSP+1;l++) gas->SPEX[i][j][k][l]=0.e00; } } } //gas->SPEX=0.e00; gas->ISPEX=0; // DERIVED_GAS_DATA(); // cout<<"Real_Oxygen data done"<<endl; return; } // void IDEAL_AIR() { //GAS gas; //CALC calc; cout<<"Reading IDEAL_AIR data"<<endl; gas->MSP=2; gas->MMRM=1; gas->MMVM=0; gas->MNSR=0; gas->MEX=0; gas->MMEX=0; gas->MELE=1; gas->MVIBL=0; // ALLOCATE_GAS(); // gas->SP[1][1]=4.07e-10; gas->SP[2][1]=273.0; gas->SP[3][1]=0.77; gas->SP[4][1]=1.0; gas->SP[5][1]=5.312e-26; gas->ISPR[1][1]=2; gas->ISPR[2][1]=0; gas->SPR[1][1]=5.0; gas->SP[1][2]=4.17e-10; gas->SP[2][2]=273.0; gas->SP[3][2]=0.74; gas->SP[4][2]=1.0; gas->SP[5][2]=4.65e-26; gas->ISPR[1][2]=2; gas->ISPR[2][2]=0; gas->SPR[1][2]=5.0; cout<<"IDEAL_AIR data done"<<endl; return; } // void REAL_AIR() { //GAS gas; //CALC calc; cout<<"REAL_AIR data done"<<endl; gas->MSP=5; gas->MMRM=1; gas->MMVM=1; gas->MELE=5; gas->MVIBL=40; //? // gas->MEX=4; gas->MMEX=1; // gas->MNSR=0; ALLOCATE_GAS(); //species 1 is oxygen gas->SP[1][1]=4.07e-10; gas->SP[2][1]=273.e00; gas->SP[3][1]=0.77e00; gas->SP[4][1]=1.e00; gas->SP[5][1]=5.312e-26; gas->SP[6][1]=0.e00; gas->ISPR[1][1]=2; gas->ISPR[2][1]=0; gas->SPR[1][1]=5.e00; gas->ISPV[1]=1; // the number of vibrational modes gas->SPVM[1][1][1]=2256.e00; // the characteristic vibrational temperature gas->SPVM[2][1][1]=18000.e00; //90000.D00 // a constant Zv, or the reference Zv gas->SPVM[3][1][1]=2256.e00; // -1 for a constant Zv, or the reference temperature gas->SPVM[5][1][1]=1.0; gas->ISPVM[1][1][1]=3; gas->ISPVM[2][1][1]=3; gas->NELL[1]=3; gas->QELC[1][1][1]=3.0; gas->QELC[2][1][1]=0.0; gas->QELC[3][1][1]=50.0; gas->QELC[1][2][1]=2.0; gas->QELC[2][2][1]=11393.0; gas->QELC[3][2][1]=50.0; gas->QELC[1][3][1]=1.0; gas->QELC[2][3][1]=18985.0; gas->QELC[3][3][1]=50.0; //species 2 is nitrogen gas->SP[1][2]=4.17e-10; gas->SP[2][2]=273.e00; gas->SP[3][2]=0.74e00; gas->SP[4][2]=1.e00; gas->SP[5][2]=4.65e-26; gas->SP[6][2]=0.e00; gas->ISPR[1][2]=2; gas->ISPR[2][2]=0; gas->SPR[1][2]=5.e00; gas->ISPV[2]=1; gas->SPVM[1][1][2]=3371.e00; gas->SPVM[2][1][2]=52000.e00; //260000.D00 gas->SPVM[3][1][2]=3371.e00; gas->SPVM[5][1][2]=0.3; gas->ISPVM[1][1][2]=4; gas->ISPVM[2][1][2]=4; gas->NELL[2]=1; gas->QELC[1][1][2]=1.0; gas->QELC[2][1][2]=0.0; gas->QELC[3][1][2]=100.0; //species 3 is atomic oxygen gas->SP[1][3]=3.e-10; gas->SP[2][3]=273.e00; gas->SP[3][3]=0.8e00; gas->SP[4][3]=1.e00; gas->SP[5][3]=2.656e-26; gas->SP[6][3]=4.099e-19; gas->ISPR[1][3]=0; gas->ISPV[3]=0; gas->NELL[3]=5; gas->QELC[1][1][3]=5.0; gas->QELC[2][1][3]=0.0; gas->QELC[3][1][3]=50.0; gas->QELC[1][2][3]=3.0; gas->QELC[2][2][3]=228.9; gas->QELC[3][2][3]=50.0; gas->QELC[1][3][3]=1.0; gas->QELC[2][3][3]=325.9; gas->QELC[3][3][3]=50.0; gas->QELC[1][4][3]=5.0; gas->QELC[2][4][3]=22830.0; gas->QELC[3][4][3]=50.0; gas->QELC[1][5][3]=1.0; gas->QELC[2][5][3]=48621.0; gas->QELC[3][5][3]=50.0; //species 4 is atomic nitrogen gas->SP[1][4]=3.e-10; gas->SP[2][4]=273.e00; gas->SP[3][4]=0.8e00; gas->SP[4][4]=1.0e00; gas->SP[5][4]=2.325e-26; gas->SP[6][4]=7.849e-19; gas->ISPR[1][4]=0; gas->ISPV[4]=0; gas->NELL[4]=3; gas->QELC[1][1][4]=4.0; gas->QELC[2][1][4]=0.0; gas->QELC[3][1][4]=50.0; gas->QELC[1][2][4]=10.0; gas->QELC[2][2][4]=27658.0; gas->QELC[3][2][4]=50.0; gas->QELC[1][3][4]=6.0; gas->QELC[2][3][4]=41495.0; gas->QELC[3][3][4]=50.0; //species 5 is NO gas->SP[1][5]=4.2e-10; gas->SP[2][5]=273.e00; gas->SP[3][5]=0.79e00; gas->SP[4][5]=1.0e00; gas->SP[5][5]=4.98e-26; gas->SP[6][5]=1.512e-19; gas->ISPR[1][5]=2; gas->ISPR[2][5]=0; gas->SPR[1][5]=5.e00; gas->ISPV[5]=1; gas->SPVM[1][1][5]=2719.e00; gas->SPVM[2][1][5]=14000.e00; //70000.D00 gas->SPVM[3][1][5]=2719.e00; gas->SPVM[5][1][5]=0.2; gas->ISPVM[1][1][5]=3; gas->ISPVM[2][1][5]=4; gas->NELL[5]=2; gas->QELC[1][1][5]=2.0; gas->QELC[2][1][5]=0.0; gas->QELC[3][1][5]=50.0; gas->QELC[1][2][5]=2.0; gas->QELC[2][2][5]=174.2; gas->QELC[3][2][5]=50.0; //set the recombination data for the molecule pairs //memset(gas->ISPRC,0,sizeof(**gas->ISPRC));//gas->ISPRC=0; //data os zero unless explicitly set //memset(gas->ISPRK,0,sizeof(**gas->ISPRK));//gas->ISPRK=0; //memset(gas->SPRC,0,sizeof(****gas->SPRC));//gas->SPRC=0.e00; for(int i=0;i<gas->MSP+1;i++){ for(int j=0;j<gas->MSP+1;j++){ gas->ISPRC[i][j]=0; } } for(int i=0;i<gas->MSP+1;i++){ for(int j=0;j<gas->MSP+1;j++){ gas->ISPRK[i][j]=0; } } for(int i=0;i<5;i++){ for(int j=0;j<gas->MSP+1;j++){ for(int k=0;k<gas->MSP+1;k++){ for(int l=0;l<gas->MSP+1;l++) gas->SPEX[i][j][k][l]=0.e00; } } } gas->ISPRC[3][3]=1; //O+O -> O2 recombined species code for an O+O recombination gas->ISPRK[3][3]=1; gas->SPRC[1][3][3][1]=0.04e00; gas->SPRC[2][3][3][1]=-1.3e00; gas->SPRC[1][3][3][2]=0.07e00; gas->SPRC[2][3][3][2]=-1.2e00; gas->SPRC[1][3][3][3]=0.08e00; gas->SPRC[2][3][3][3]=-1.2e00; gas->SPRC[1][3][3][4]=0.09e00; gas->SPRC[2][3][3][4]=-1.2e00; gas->SPRC[1][3][3][5]=0.065e00; gas->SPRC[2][3][3][5]=-1.2e00; gas->SPRT[1][3][3]=5000.e00; gas->SPRT[2][3][3]=15000.e00; gas->ISPRC[4][4]=2; //N+N -> N2 gas->ISPRK[4][4]=1; gas->SPRC[1][4][4][1]=0.15e00; gas->SPRC[2][4][4][1]=-2.05e00; gas->SPRC[1][4][4][2]=0.09e00; gas->SPRC[2][4][4][2]=-2.1e00; gas->SPRC[1][4][4][3]=0.16e00; gas->SPRC[2][4][4][3]=-2.0e00; gas->SPRC[1][4][4][4]=0.17e00; gas->SPRC[2][4][4][4]=-2.0e00; gas->SPRC[1][4][4][5]=0.17e00; gas->SPRC[2][4][4][5]=-2.1e00; gas->SPRT[1][4][4]=5000.e00; gas->SPRT[2][4][4]=15000.e00; gas->ISPRC[3][4]=5; gas->ISPRK[3][4]=1; gas->SPRC[1][3][4][1]=0.3e00; gas->SPRC[2][3][4][1]=-1.9e00; gas->SPRC[1][3][4][2]=0.4e00; gas->SPRC[2][3][4][2]=-2.0e00; gas->SPRC[1][3][4][3]=0.3e00; gas->SPRC[2][3][4][3]=-1.75e00; gas->SPRC[1][3][4][4]=0.3e00; gas->SPRC[2][3][4][4]=-1.75e00; gas->SPRC[1][3][4][5]=0.15e00; gas->SPRC[2][3][4][5]=-1.9e00; gas->SPRT[1][3][4]=5000.e00; gas->SPRT[2][3][4]=15000.e00; //set the exchange reaction data //memset(gas->SPEX,0,sizeof(****gas->SPEX));//gas->SPEX=0.e00; for(int i=0;i<7;i++){ for(int j=0;j<gas->MMEX+1;j++){ for(int k=0;k<gas->MSP+1;k++){ for(int l=0;l<gas->MSP+1;l++) gas->SPEX[i][j][k][l]=0.e00; } } } gas->ISPEX=0; gas->NSPEX=0; gas->NSPEX[2][3]=1; gas->NSPEX[4][5]=1; gas->NSPEX[3][5]=1; gas->NSPEX[1][4]=1; //N2+O->NO+N gas->ISPEX[1][1][2][3]=2; gas->ISPEX[1][2][2][3]=3; gas->ISPEX[1][3][2][3]=5; gas->ISPEX[1][4][2][3]=4; gas->ISPEX[1][5][2][3]=1; gas->ISPEX[1][6][2][3]=1; gas->SPEX[6][1][2][3]=0.e00; gas->NEX[1][2][3]=1; //NO+N->N2+0 gas->ISPEX[1][1][4][5]=5; gas->ISPEX[1][2][4][5]=4; gas->ISPEX[1][3][4][5]=2; gas->ISPEX[1][4][4][5]=3; gas->ISPEX[1][5][4][5]=1; gas->ISPEX[1][6][4][5]=1; gas->ISPEX[1][7][4][5]=1; gas->SPEX[1][1][4][5]=0.8e00; gas->SPEX[2][1][4][5]=-0.75e00; gas->SPEX[4][1][4][5]=5000.e00; gas->SPEX[5][1][4][5]=15000.e00; gas->SPEX[6][1][4][5]=0.e00; gas->NEX[1][4][5]=2; //NO+O->O2+N gas->ISPEX[1][1][3][5]=5; gas->ISPEX[1][2][3][5]=3; gas->ISPEX[1][3][3][5]=1; gas->ISPEX[1][4][3][5]=4; gas->ISPEX[1][5][3][5]=1; gas->ISPEX[1][6][3][5]=1; gas->SPEX[6][1][3][5]=2.e-19; gas->NEX[1][3][5]=3; //O2+N->NO+O gas->ISPEX[1][1][1][4]=1; gas->ISPEX[1][2][1][4]=4; gas->ISPEX[1][3][1][4]=5; gas->ISPEX[1][4][1][4]=3; gas->ISPEX[1][5][1][4]=1; gas->ISPEX[1][6][1][4]=1; gas->ISPEX[1][7][1][4]=1 ; gas->SPEX[1][1][1][4]=7.e00; gas->SPEX[2][1][1][4]=-0.85e00; gas->SPEX[4][1][1][4]=5000.e00; gas->SPEX[5][1][1][4]=15000.e00; gas->SPEX[6][1][1][4]=0.e00; gas->NEX[1][1][4]=4; DERIVED_GAS_DATA(); cout<<"REAL_AIR data done"<<endl; return; } // void HELIUM_ARGON_XENON() { //GAS gas; //CALC calc; cout<<"Reading HELIUM_ARGON_XENON data"<<endl; gas->MSP=3; gas->MMRM=0; gas->MMVM=0; gas->MNSR=0; gas->MEX=0; gas->MMEX=0; gas->MELE=1; gas->MVIBL=0; ALLOCATE_GAS(); gas->SP[1][1]=2.30e-10; //2.33D-10 gas->SP[2][1]=273.0; gas->SP[3][1]=0.66; gas->SP[4][1]=0.794; //1. gas->SP[5][1]=6.65e-27; gas->ISPR[1][1]=0; gas->ISPR[2][1]=0; // gas->SP[1][2]=4.11e-10; //4.17D-10 gas->SP[2][2]=273.15; gas->SP[3][2]=0.81; gas->SP[4][2]=0.714; //1. gas->SP[5][2]=6.63e-26; gas->ISPR[1][2]=0; gas->ISPR[2][2]=0; // gas->SP[1][3]=5.65e-10; //5.74D-10 gas->SP[2][3]=273.0; gas->SP[3][3]=0.85; gas->SP[4][3]=0.694; //1. gas->SP[5][3]=21.8e-26; gas->ISPR[1][3]=0; gas->ISPR[2][3]=0; cout<<"HELIUM_ARGON_XENON data done"<<endl; return; } // void OXYGEN_HYDROGEN() { // //GAS gas; //CALC calc; cout<<"Reading OXYGEN_HYDROGEN data"<<endl; gas->MSP=8; gas->MMRM=3; gas->MMVM=3; gas->MELE=1; gas->MVIBL=40; //the maximum number of vibrational levels before a cumulative level reaches 1 // gas->MEX=16; gas->MMEX=3; // gas->MNSR=0; // ALLOCATE_GAS(); // //species 1 is hydrogen H2 gas->SP[1][1]=2.92e-10; gas->SP[2][1]=273.e00; gas->SP[3][1]=0.67e00; gas->SP[4][1]=1.e00; gas->SP[5][1]=3.34e-27; gas->SP[6][1]=0.e00; gas->ISPR[1][1]=2; gas->ISPR[2][1]=0; gas->SPR[1][1]=5.e00; gas->ISPV[1]=1; // the number of vibrational modes gas->SPVM[1][1][1]=6159.e00; // the characteristic vibrational temperature gas->SPVM[2][1][1]=20000.e00; //estimate gas->SPVM[3][1][1]=2000.e00; //estimate gas->SPVM[5][1][1]=1.0; gas->ISPVM[1][1][1]=2; gas->ISPVM[2][1][1]=2; //species 2 is atomic hydrogen H gas->SP[1][2]=2.5e-10; //estimate gas->SP[2][2]=273.e00; gas->SP[3][2]=0.8e00; gas->SP[4][2]=1.e00; gas->SP[5][2]=1.67e-27; gas->SP[6][2]=3.62e-19; gas->ISPR[1][2]=0; gas->ISPV[2]=0; //species 3 is oxygen O2 gas->SP[1][3]=4.07e-10; gas->SP[2][3]=273.e00; gas->SP[3][3]=0.77e00; gas->SP[4][3]=1.e00; gas->SP[5][3]=5.312e-26; gas->SP[6][3]=0.e00; gas->ISPR[1][3]=2; gas->ISPR[2][3]=0; gas->SPR[1][3]=5.e00; gas->ISPV[3]=1; // the number of vibrational modes gas->SPVM[1][1][3]=2256.e00; // the characteristic vibrational temperature gas->SPVM[2][1][3]=18000.e00; //90000.D00 // a constant Zv, or the reference Zv gas->SPVM[3][1][3]=2256.e00; // -1 for a constant Zv, or the reference temperature gas->SPVM[5][1][3]=1.e00; gas->ISPVM[1][1][3]=4; gas->ISPVM[2][1][3]=4; //species 4 is atomic oxygen O gas->SP[1][4]=3.e-10; //estimate gas->SP[2][4]=273.e00; gas->SP[3][4]=0.8e00; gas->SP[4][4]=1.e00; gas->SP[5][4]=2.656e-26; gas->SP[6][4]=4.099e-19; gas->ISPR[1][4]=0; gas->ISPV[4]=0; //species 5 is hydroxy OH gas->SP[1][5]=4.e-10; //estimate gas->SP[2][5]=273.e00; gas->SP[3][5]=0.75e00; //-estimate gas->SP[4][5]=1.0e00; gas->SP[5][5]=2.823e-26; gas->SP[6][5]=6.204e-20; gas->ISPR[1][5]=2; gas->ISPR[2][5]=0; gas->SPR[1][5]=5.e00; gas->ISPV[5]=1; gas->SPVM[1][1][5]=5360.e00; gas->SPVM[2][1][5]=20000.e00; //estimate gas->SPVM[3][1][5]=2500.e00; //estimate gas->SPVM[5][1][5]=1.0e00; gas->ISPVM[1][1][5]=2; gas->ISPVM[2][1][5]=4; //species 6 is water vapor H2O gas->SP[1][6]=4.5e-10; //estimate gas->SP[2][6]=273.e00; gas->SP[3][6]=0.75e00 ; //-estimate gas->SP[4][6]=1.0e00; gas->SP[5][6]=2.99e-26; gas->SP[6][6]=-4.015e-19; gas->ISPR[1][6]=3; gas->ISPR[2][6]=0; gas->SPR[1][6]=5.e00; gas->ISPV[6]=3; gas->SPVM[1][1][6]=5261.e00; //symmetric stretch mode gas->SPVM[2][1][6]=20000.e00; //estimate gas->SPVM[3][1][6]=2500.e00; //estimate gas->SPVM[5][1][6]=1.e00; gas->SPVM[1][2][6]=2294.e00; //bend mode gas->SPVM[2][2][6]=20000.e00; //estimate gas->SPVM[3][2][6]=2500.e00; //estimate gas->SPVM[5][2][6]=1.0e00; gas->SPVM[1][3][6]=5432.e00; //asymmetric stretch mode gas->SPVM[2][3][6]=20000.e00; //estimate gas->SPVM[3][3][6]=2500.e00 ; //estimate gas->SPVM[5][3][6]=1.e00; gas->ISPVM[1][1][6]=2; gas->ISPVM[2][1][6]=5; gas->ISPVM[1][2][6]=2; gas->ISPVM[2][2][6]=5; gas->ISPVM[1][3][6]=2; gas->ISPVM[2][3][6]=5; //species 7 is hydroperoxy HO2 gas->SP[1][7]=5.5e-10; //estimate gas->SP[2][7]=273.e00; gas->SP[3][7]=0.75e00 ; //-estimate gas->SP[4][7]=1.0e00; gas->SP[5][7]=5.479e-26; gas->SP[6][7]=2.04e-20; gas->ISPR[1][7]=2; //assumes that HO2 is linear gas->ISPR[2][7]=0; gas->SPR[1][7]=5.e00; gas->ISPV[7]=3; gas->SPVM[1][1][7]=4950.e00; gas->SPVM[2][1][7]=20000.e00; //estimate gas->SPVM[3][1][7]=2500.e00 ; //estimate gas->SPVM[5][1][7]=1.e00; gas->SPVM[1][2][7]=2000.e00; gas->SPVM[2][2][7]=20000.e00; //estimate gas->SPVM[3][2][7]=2500.e00; //estimate gas->SPVM[5][2][7]=1.e00; gas->SPVM[1][3][7]=1580.e00; gas->SPVM[2][3][7]=20000.e00; //estimate gas->SPVM[3][3][7]=2500.e00; //estimate gas->SPVM[5][3][7]=1.e00; gas->ISPVM[1][1][7]=2; gas->ISPVM[2][1][7]=3; gas->ISPVM[1][2][7]=2; gas->ISPVM[2][2][7]=3; gas->ISPVM[1][3][7]=2; gas->ISPVM[2][3][7]=3; //Species 8 is argon gas->SP[1][8]=4.17e-10; gas->SP[2][8]=273.15; gas->SP[3][8]=0.81 ; gas->SP[4][8]=1.0; gas->SP[5][8]=6.63e-26; gas->SP[6][8]=0.e00; gas->ISPR[1][8]=0; gas->ISPV[8]=0; // for(int i=0;i<gas->MSP+1;i++){ for(int j=0;j<gas->MSP+1;j++){ gas->ISPRC[i][j]=0; } } //gas->ISPRC=0; //data is zero unless explicitly set // gas->ISPRC[4][4]=3; //O+O+M -> O2+M recombined species code for an O+O recombination gas->ISPRK[4][4]=1; gas->SPRC[1][4][4][1]=0.26e00; gas->SPRC[2][4][4][1]=-1.3e00; gas->SPRC[1][4][4][2]=0.29e00; gas->SPRC[2][4][4][2]=-1.3e00; gas->SPRC[1][4][4][3]=0.04e00; gas->SPRC[2][4][4][3]=-1.5e00; gas->SPRC[1][4][4][4]=0.1e00; gas->SPRC[2][4][4][4]=-1.4e00; gas->SPRC[1][4][4][5]=0.1e00; gas->SPRC[2][4][4][5]=-1.4e00; gas->SPRC[1][4][4][6]=0.1e00; gas->SPRC[2][4][4][6]=-1.4e00; gas->SPRC[1][4][4][7]=0.07e00; gas->SPRC[2][4][4][7]=-1.5e00; gas->SPRC[1][4][4][8]=0.07e00; gas->SPRC[2][4][4][8]=-1.5e00; gas->SPRT[1][4][4]=1000.e00; gas->SPRT[2][4][4]=3000.e00; // gas->ISPRC[2][2]=1; //H+H+M -> H2+M gas->ISPRK[2][2]=1; gas->SPRC[1][2][2][1]=0.07e00; gas->SPRC[2][2][2][1]=-2.e00; gas->SPRC[1][2][2][2]=0.11e00; gas->SPRC[2][2][2][2]=-2.2e00; gas->SPRC[1][2][2][3]=0.052e00; gas->SPRC[2][2][2][3]=-2.5e00; gas->SPRC[1][2][2][4]=0.052e00; gas->SPRC[2][2][2][4]=-2.5e00; gas->SPRC[1][2][2][5]=0.052e00; gas->SPRC[2][2][2][5]=-2.5e00; gas->SPRC[1][2][2][6]=0.052e00; gas->SPRC[2][2][2][6]=-2.5e00; gas->SPRC[1][2][2][7]=0.052e00; gas->SPRC[2][2][2][7]=-2.5e00; gas->SPRC[1][2][2][8]=0.04e00; gas->SPRC[2][2][2][7]=-2.5e00; gas->SPRT[1][2][2]=1000.e00; gas->SPRT[2][2][2]=3000.e00; // gas->ISPRC[2][4]=5; //H+0+M -> OH+M gas->ISPRK[2][4]=1; gas->SPRC[1][2][4][1]=0.15e00; gas->SPRC[2][2][4][1]=-2.e00; gas->SPRC[1][2][4][2]=0.04e00; gas->SPRC[2][2][4][2]=-1.3e00; gas->SPRC[1][2][4][3]=0.04e00; gas->SPRC[2][2][4][3]=-1.3e00; gas->SPRC[1][2][4][4]=0.04e00; gas->SPRC[2][2][4][4]=-1.3e00; gas->SPRC[1][2][4][5]=0.04e00; gas->SPRC[2][2][4][5]=-1.3e00; gas->SPRC[1][2][4][6]=0.21e00; gas->SPRC[2][2][4][6]=-2.1e00; gas->SPRC[1][2][4][7]=0.18e00; gas->SPRC[2][2][4][7]=-2.3e00; gas->SPRC[1][2][4][8]=0.16e00; gas->SPRC[2][2][4][8]=-2.3e00; gas->SPRT[1][2][4]=1000.e00; gas->SPRT[2][2][4]=3000.e00; // gas->ISPRC[2][5]=6; //H+OH+M -> H2O+M gas->ISPRK[2][5]=1; gas->SPRC[1][2][5][1]=0.1e00; gas->SPRC[2][2][5][1]=-2.0e00; gas->SPRC[1][2][5][2]=0.1e00; gas->SPRC[2][2][5][2]=-2.0e00; gas->SPRC[1][2][5][3]=0.0025e00; gas->SPRC[2][2][5][3]=-2.2e00; gas->SPRC[1][2][5][4]=0.0025e00; gas->SPRC[2][2][5][4]=-2.2e00; gas->SPRC[1][2][5][5]=0.0025e00; gas->SPRC[2][2][5][5]=-2.2e00; gas->SPRC[1][2][5][6]=0.0015e00; gas->SPRC[2][2][5][6]=-2.2e00; gas->SPRC[1][2][5][7]=0.0027e00; gas->SPRC[2][2][5][7]=-2.e00; gas->SPRC[1][2][5][8]=0.0025e00; gas->SPRC[2][2][5][8]=-2.e00; gas->SPRT[1][2][5]=1000.e00; gas->SPRT[2][2][5]=3000.e00; // gas->ISPRC[2][3]=7; //H+O2+M -> H02+M gas->ISPRK[2][3]=1; gas->SPRC[1][2][3][1]=0.0001e00; gas->SPRC[2][2][3][1]=-1.7e00; gas->SPRC[1][2][3][2]=0.0001e00; gas->SPRC[2][2][3][2]=-1.7e00; gas->SPRC[1][2][3][3]=0.00003e00; gas->SPRC[2][2][3][3]=-1.5e00; gas->SPRC[1][2][3][4]=0.00003e00; gas->SPRC[2][2][3][4]=-1.7e00; gas->SPRC[1][2][3][5]=0.00003e00; gas->SPRC[2][2][3][5]=-1.7e00; gas->SPRC[1][2][3][6]=0.00003e00; gas->SPRC[2][2][3][6]=-1.7e00; gas->SPRC[1][2][3][7]=0.000012e00; gas->SPRC[2][2][3][7]=-1.7e00; gas->SPRC[1][2][3][8]=0.00002e00; gas->SPRC[2][2][3][8]=-1.7e00; gas->SPRT[1][2][3]=1000.e00; gas->SPRT[2][2][3]=3000.e00; // //set the exchange reaction data // memset(gas->SPEX,0,sizeof(****gas->SPEX));//gas->SPEX=0.e00; //all activation energies and heats of reaction are zero unless set otherwise for(int i=0;i<7;i++){ for(int j=0;j<gas->MMEX+1;j++){ for(int k=0;k<gas->MSP+1;k++){ for(int l=0;l<gas->MSP+1;l++) gas->SPEX[i][j][k][l]=0.e00; } } } //gas->ISPEX=0; // ISPEX is also zero unless set otherwise for(int i=0;i<gas->MMEX+1;i++){ for(int j=0;j<8;j++){ for(int k=0;k<gas->MSP+1;k++){ for(int l=0;l<gas->MSP+1;l++) gas->ISPEX[i][j][k][l]=0.e00; } } } //gas->NSPEX=0; for(int i=0;i<gas->MSP+1;i++){ for(int j=0;j<gas->MSP+1;j++){ gas->NSPEX[i][j]=0; } } //set the number of exchange reactions for each species pair gas->NSPEX[1][3]=1; gas->NSPEX[2][7]=3; gas->NSPEX[2][3]=1; gas->NSPEX[4][5]=1; gas->NSPEX[1][4]=1; gas->NSPEX[2][5]=1; gas->NSPEX[1][5]=1; gas->NSPEX[2][6]=1; gas->NSPEX[4][6]=2; gas->NSPEX[5][5]=2; gas->NSPEX[4][7]=1; gas->NSPEX[3][5]=1; //set the information on the chain reactions // //H2+O2 -> HO2+H gas->ISPEX[1][1][1][3]=1; gas->ISPEX[1][2][1][3]=3; gas->ISPEX[1][3][1][3]=7; gas->ISPEX[1][4][1][3]=2; gas->ISPEX[1][5][1][3]=1; gas->ISPEX[1][6][1][3]=1; gas->SPEX[6][1][1][3]=0.e00; gas->NEX[1][1][3]=1; // //HO2+H -> H2+02 gas->ISPEX[1][1][2][7]=7; gas->ISPEX[1][2][2][7]=2; gas->ISPEX[1][3][2][7]=1; gas->ISPEX[1][4][2][7]=3; gas->ISPEX[1][5][2][7]=1; gas->ISPEX[1][6][2][7]=1; gas->ISPEX[1][7][2][7]=1; //H02 is H-O-O so that not all vibrational modes contribute to this reaction, but the numbers here are guesses// gas->SPEX[1][1][2][7]=20.e00; gas->SPEX[2][1][2][7]=0.4e00; gas->SPEX[4][1][2][7]=2000.e00; gas->SPEX[5][1][2][7]=3000.e00; gas->SPEX[6][1][2][7]=0.e00; gas->NEX[1][2][7]=2; // //O2+H -> OH+O gas->ISPEX[1][1][2][3]=3; gas->ISPEX[1][2][2][3]=2; gas->ISPEX[1][3][2][3]=5; gas->ISPEX[1][4][2][3]=4; gas->ISPEX[1][5][2][3]=1; gas->ISPEX[1][6][2][3]=1; gas->SPEX[6][1][2][3]=0.e00; gas->NEX[1][2][3]=3; // //OH+O -> O2+H gas->ISPEX[1][1][4][5]=5; gas->ISPEX[1][2][4][5]=4; gas->ISPEX[1][3][4][5]=3; gas->ISPEX[1][4][4][5]=2; gas->ISPEX[1][5][4][5]=1; gas->ISPEX[1][6][4][5]=1; gas->ISPEX[1][7][4][5]=1; gas->SPEX[1][1][4][5]=0.65e00; gas->SPEX[2][1][4][5]=-0.26; gas->SPEX[4][1][4][5]=2000.e00; gas->SPEX[5][1][4][5]=3000.e00; gas->SPEX[6][1][4][5]=0.e00; gas->NEX[1][4][5]=4; // //H2+O -> OH+H gas->ISPEX[1][1][1][4]=1; gas->ISPEX[1][2][1][4]=4; gas->ISPEX[1][3][1][4]=5; gas->ISPEX[1][4][1][4]=2; gas->ISPEX[1][5][1][4]=1; gas->ISPEX[1][6][1][4]=1; gas->SPEX[6][1][1][4]=0.e00; gas->NEX[1][1][4]=5; // //OH+H -> H2+O gas->ISPEX[1][1][2][5]=5; gas->ISPEX[1][2][2][5]=2; gas->ISPEX[1][3][2][5]=1; gas->ISPEX[1][4][2][5]=4; gas->ISPEX[1][5][2][5]=1; gas->ISPEX[1][6][2][5]=1; gas->ISPEX[1][7][2][5]=1; gas->SPEX[1][1][2][5]=0.5e00; gas->SPEX[2][1][2][5]=-0.2e00; gas->SPEX[4][1][2][5]=2000.e00; gas->SPEX[5][1][2][5]=3000.e00; gas->SPEX[6][1][2][5]=0.e00; gas->NEX[1][2][5]=6; // //H20+H -> OH+H2 gas->ISPEX[1][1][2][6]=6; gas->ISPEX[1][2][2][6]=2; gas->ISPEX[1][3][2][6]=5; gas->ISPEX[1][4][2][6]=1; gas->ISPEX[1][5][2][6]=1; gas->ISPEX[1][6][2][6]=1; gas->SPEX[6][1][2][6]=2.0e-19; gas->NEX[1][2][6]=7; //OH+H2 -> H2O+H gas->ISPEX[1][1][1][5]=5; gas->ISPEX[1][2][1][5]=1; gas->ISPEX[1][3][1][5]=6; gas->ISPEX[1][4][1][5]=2; gas->ISPEX[1][5][1][5]=1; gas->ISPEX[1][6][1][5]=1; gas->ISPEX[1][7][1][5]=1; gas->SPEX[1][1][1][5]=0.5; gas->SPEX[2][1][1][5]=-0.2; gas->SPEX[4][1][1][5]=2000.e00; gas->SPEX[5][1][1][5]=3000.e00; gas->SPEX[6][1][1][5]=0.e00; gas->NEX[1][1][5]=8; // //H2O+O -> OH+OH gas->ISPEX[1][1][4][6]=6; gas->ISPEX[1][2][4][6]=4; gas->ISPEX[1][3][4][6]=5; gas->ISPEX[1][4][4][6]=5; gas->ISPEX[1][5][4][6]=1; gas->ISPEX[1][6][4][6]=1; gas->SPEX[6][1][4][6]=0.e00; gas->NEX[1][4][6]=9; // //0H+OH -> H2O+O gas->ISPEX[1][1][5][5]=5; gas->ISPEX[1][2][5][5]=5; gas->ISPEX[1][3][5][5]=6; gas->ISPEX[1][4][5][5]=4; gas->ISPEX[1][5][5][5]=1; gas->ISPEX[1][6][5][5]=1; gas->ISPEX[1][7][5][5]=1; gas->SPEX[1][1][5][5]=0.35; gas->SPEX[2][1][5][5]=-0.2 ; gas->SPEX[4][1][5][5]=2000.e00; gas->SPEX[5][1][5][5]=3000.e00; gas->SPEX[6][1][5][5]=0.e00; gas->NEX[1][5][5]=10; // //OH+OH -> HO2+H // gas->ISPEX[2][1][5][5]=5; gas->ISPEX[2][2][5][5]=5; gas->ISPEX[2][3][5][5]=7; gas->ISPEX[2][4][5][5]=2; gas->ISPEX[2][5][5][5]=1; gas->ISPEX[2][6][5][5]=1; gas->SPEX[6][2][5][5]=0.e00; gas->NEX[2][5][5]=11; // //H02+H -> 0H+OH gas->ISPEX[2][1][2][7]=7; gas->ISPEX[2][2][2][7]=2; gas->ISPEX[2][3][2][7]=5; gas->ISPEX[2][4][2][7]=5; gas->ISPEX[2][5][2][7]=1; gas->ISPEX[2][6][2][7]=1; gas->ISPEX[2][7][2][7]=1; gas->SPEX[1][2][2][7]=120.e00; gas->SPEX[2][2][2][7]=-0.05e00; gas->SPEX[4][2][2][7]=2000.e00; gas->SPEX[5][2][2][7]=3000.e00; gas->SPEX[6][2][2][7]=0.e00; gas->NEX[2][2][7]=12; // //H2O+O -> HO2+H // gas->ISPEX[2][1][4][6]=6; gas->ISPEX[2][2][4][6]=4; gas->ISPEX[2][3][4][6]=7; gas->ISPEX[2][4][4][6]=2; gas->ISPEX[2][5][4][6]=1; gas->ISPEX[2][6][4][6]=1; gas->SPEX[6][2][4][6]=0.e00; gas->NEX[2][4][6]=13; // //H02+H -> H2O+O // gas->ISPEX[3][1][2][7]=7; gas->ISPEX[3][2][2][7]=2; gas->ISPEX[3][3][2][7]=6; gas->ISPEX[3][4][2][7]=4; gas->ISPEX[3][5][2][7]=1; gas->ISPEX[3][6][2][7]=1; gas->ISPEX[3][7][2][7]=1; gas->SPEX[1][3][2][7]=40.e00; gas->SPEX[2][3][2][7]=-1.e00; gas->SPEX[4][3][2][7]=2000.e00; gas->SPEX[5][3][2][7]=3000.e00; gas->SPEX[6][3][2][7]=0.e00; gas->NEX[3][2][7]=14; // //OH+O2 -> HO2+O // gas->ISPEX[1][1][3][5]=5; gas->ISPEX[1][2][3][5]=3; gas->ISPEX[1][3][3][5]=7; gas->ISPEX[1][4][3][5]=4; gas->ISPEX[1][5][3][5]=1; gas->ISPEX[1][6][3][5]=1; gas->SPEX[6][1][3][5]=0.e00; gas->NEX[1][3][5]=15; // //H02+0 -> OH+O2 // gas->ISPEX[1][1][4][7]=7; gas->ISPEX[1][2][4][7]=4; gas->ISPEX[1][3][4][7]=5; gas->ISPEX[1][4][4][7]=3; gas->ISPEX[1][5][4][7]=1; gas->ISPEX[1][6][4][7]=1; gas->ISPEX[1][7][4][7]=1; gas->SPEX[1][1][4][7]=100.e00; gas->SPEX[2][1][4][7]=0.15e00; gas->SPEX[4][1][4][7]=2000.e00; gas->SPEX[5][1][4][7]=3000.e00; gas->SPEX[6][1][4][7]=0.e00; gas->NEX[1][4][7]=16; // DERIVED_GAS_DATA(); // cout<<"OXYGEN_HYDROGEN data done"<<endl; return; } //*************************************************************************** //*************************END OF GAS DATABASE******************************* //*************************************************************************** // void DERIVED_GAS_DATA() { // //GAS gas; //CALC calc; int I,II,J,JJ,K,L,M,MM,N,JMAX,MOLSP,MOLOF,NSTEP,IMAX; double A,B,BB,C,X,T,CUR,EAD,TVD,ZVT,ERD,PETD,DETD,PINT,ETD,SUMD,VAL; double **BFRAC,**TOT; double ****VRRD; double *****VRREX; // //VRRD(1,L,M,K) dissociation rate coefficient to species L,M for vibrational level K at 5,000 K //VRRD(2,L,M,K) similar for 15,000 K //VRREX(1,J,L,M,K) Jth exchange rate coefficient to species L,M for vibrational level K at 1,000 K //VRREX(2,J,L,M,K) similar for 3,000 K //BFRAC(2,J) Boltzmann fraction //JMAX imax-1 //T temperature //CUR sum of level resolved rates // VRRD = new double ***[3]; for (int i = 0; i < 3; ++i) { VRRD[i] = new double **[gas->MSP+1]; for (int j = 0; j < gas->MSP+1; ++j) { VRRD[i][j] = new double *[gas->MSP+1]; for(int k=0; k<gas->MSP+1; ++k) VRRD[i][j][k]=new double [gas->MVIBL+1]; } } BFRAC = new double*[gas->MVIBL+1]; for(int i =0; i< (gas->MVIBL+1); ++i) BFRAC[i] = new double[3]; VRREX = new double ****[3]; for (int i = 0; i < 3; ++i) { VRREX[i] = new double ***[gas->MMEX+1]; for (int j = 0; j < gas->MMEX+1; ++j) { VRREX[i][j] = new double **[gas->MSP+1]; for(int k=0; k<gas->MSP+1; ++k) { VRREX[i][j][k]=new double *[gas->MSP+1]; for(int l=0; l<gas->MSP+1; ++l) VRREX[i][j][k][l]= new double[gas->MVIBL+1]; } } } TOT = new double*[gas->MVIBL+1]; for(int i =0; i< (gas->MVIBL+1); ++i) TOT[i] = new double[3]; // ALLOCATE (VRRD(2,MSP,MSP,0:MVIBL),BFRAC(0:MVIBL,2),VRREX(2,MMEX,MSP,MSP,0:MVIBL),TOT(0:MVIBL,2),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*)'PROGRAM COULD NOT ALLOCATE VIB. RES. DISS. RATES',ERROR // END IF // cout<<"Setting derived gas data"<<endl; //copy the L,M data that has been specified for L < M so that it applies also for M>L for(L=1;L<=gas->MSP;L++){ for(M=1;M<=gas->MSP;M++){ if(L > M){ gas->NSPEX[L][M]=gas->NSPEX[M][L]; gas->ISPRC[L][M]=gas->ISPRC[M][L]; gas->ISPRK[L][M]=gas->ISPRK[M][L]; for(K=1;K<=gas->MSP;K++){ gas->SPRT[1][L][M]=gas->SPRT[1][M][L]; gas->SPRT[2][L][M]=gas->SPRT[2][M][L]; gas->SPRC[1][L][M][K]=gas->SPRC[1][M][L][K]; gas->SPRC[2][L][M][K]=gas->SPRC[2][M][L][K]; } for(K=1;K<=gas->MMEX;K++){ gas->NEX[K][L][M]=gas->NEX[K][M][L]; for(J=1;J<=6;J++){ gas->SPEX[J][K][L][M]=gas->SPEX[J][K][M][L]; } for(J=1;J<=7;J++){ gas->ISPEX[K][J][L][M]=gas->ISPEX[K][J][M][L]; } } } } } // if(gas->MMVM > 0){ //set the characteristic dissociation temperatures for(L=1;L<=gas->MSP;L++){ if(gas->ISPV[L] > 0){ for(K=1;K<=gas->ISPV[L];K++) { I=gas->ISPVM[1][K][L]; J=gas->ISPVM[2][K][L]; gas->SPVM[4][K][L]=(gas->SP[6][I]+gas->SP[6][J]-gas->SP[6][L])/BOLTZ; //WRITE (9,*) 'Char. Diss temp of species',L,' is',SPVM(4,K,L) file_9<<"Char. Diss temp of species "<<L<<" is "<<gas->SPVM[4][K][L]<<endl; } } } } // if(gas->MMEX > 0){ //set the heats of reaction of the exchange and chain reactions for(L=1;L<=gas->MSP;L++){ for(M=1;M<=gas->MSP;M++){ for(J=1;J<=gas->MMEX;J++){ if((gas->ISPEX[J][3][L][M]> 0) && (gas->ISPEX[J][4][L][M]>0) && (gas->ISPEX[J][1][L][M]>0) && (gas->ISPEX[J][2][L][M]>0)){ gas->SPEX[3][J][L][M]=gas->SP[6][gas->ISPEX[J][1][L][M]]+gas->SP[6][gas->ISPEX[J][2][L][M]]-gas->SP[6][gas->ISPEX[J][3][L][M]]-gas->SP[6][gas->ISPEX[J][4][L][M]]; // WRITE (9,*) 'Reaction',NEX(J,L,M),' heat of reaction',SPEX(3,J,L,M) file_9<<"Reaction "<<gas->NEX[J][L][M]<<" heat of reaction"<<gas->SPEX[3][J][L][M]<<endl; } } } } } // if(gas->MELE > 1){ //set the electronic cross-section ratios to a mean electronic relaxation collision number //(equipartition is not achieved unless there is a single number) for(L=1;L<=gas->MSP;L++){ A=0.e00; for(K=1;K<=gas->NELL[L];K++){ A=A+gas->QELC[3][K][L]; } gas->QELC[3][1][L]=A/double(gas->NELL[L]); } } // //set the cumulative distributions of the post-recombination vibrational distributions for establishment of detailed balance for(L=1;L<=gas->MSP;L++){ for(M=1;M<=gas->MSP;M++){ if(gas->ISPRC[L][M] > 0){ N=gas->ISPRC[L][M]; //recombined species K=gas->ISPRK[L][M]; //relevant vibrational mode //WRITE (9,*) 'SPECIES',L,M,' RECOMBINE TO',N file_9<<"SPECIES "<<L<<" "<<M<<" RECOMBINE TO"<<N<<endl; JMAX=gas->SPVM[4][K][N]/gas->SPVM[1][K][N]; if(JMAX > gas->MVIBL){ cout<<" The variable MVIBL="<<gas->MVIBL<<" in the gas database must be increased to"<<JMAX<<endl; cout<<"Enter 0 ENTER to stop"; cin>> A; return ; } A=2.5e00-gas->SP[3][N]; for(I=1;I<=2;I++){ if(I == 1) T=gas->SPRT[1][L][M]; if(I == 2) T=gas->SPRT[2][L][M]; //WRITE (9,*) 'TEMPERATURE',T file_9<<"TEMPERATURE "<<T<<endl; CUR=0.e00; for(J=0;J<=JMAX;J++){ X=double(JMAX+1-J)*gas->SPVM[1][K][N]/T; CQAX(A,X,B); VRRD[I][L][M][J]=B*exp(-double(J)*gas->SPVM[1][K][N]/T); CUR=CUR+VRRD[I][L][M][J]; } B=0.e00; for(J=0;J<=JMAX;J++){ B=B+VRRD[I][L][M][J]/CUR; gas->SPRP[I][L][M][J]=B; //WRITE (9,*) 'CDF level dissoc',J,SPRP(I,L,M,J) file_9<< "CDF level dissoc "<<J<<" "<<gas->SPRP[I][L][M][J]; } } } } } // //READ (*,*) //optionally pause program to check cumulative distributions for exchange and chain reactions // //set the cumulative distributions of the post-reverse vibrational distributions for establishment of detailed balance for(L=1;L<=gas->MSP;L++){ for(M=1;M<=gas->MSP;M++){ if(gas->NSPEX[L][M] > 0){ for(K=1;K<=gas->NSPEX[L][M];K++){ if(gas->SPEX[3][K][L][M] > 0.e00){ //exothermic (reverse) exchange reaction //L,M are the species in the reverse reaction, E_a of forward reaction is SPEX(3,K,L,M) //WRITE (9,*) 'SPECIES',L,M,' REVERSE REACTION' file_9<<"SPECIES "<<L<<" "<<M<<" REVERSE REACTION"<<endl; MOLSP=gas->ISPEX[K][3][L][M]; //molecuke that splits in the forward reaction MOLOF=gas->ISPEX[K][4][L][M]; JMAX=(gas->SPEX[3][K][L][M]+gas->SPEX[6][K][MOLSP][MOLOF])/(BOLTZ*gas->SPVM[1][gas->ISPEX[K][5][L][M]][MOLSP])+15; //should always be less than the JMAX set by dissociation reactions for(I=1;I<=2;I++){ if(I == 1) T=gas->SPEX[4][K][L][M]; if(I == 2) T=gas->SPEX[5][K][L][M]; for(J=0;J<=JMAX;J++){ EAD=(gas->SPEX[3][K][L][M]+gas->SPEX[6][K][MOLSP][MOLOF])/(BOLTZ*T); TVD=gas->SPVM[1][gas->ISPEX[K][5][L][M]][MOLSP]/T; ZVT=1.e00/(1.e00-exp(-TVD)); C=ZVT/(tgamma(2.5e00-gas->SP[3][MOLSP])*exp(-EAD)); //coefficient of integral ERD=EAD-double(J)*TVD; if(ERD < 0.e00) ERD=0.e00; PETD=ERD; DETD=0.01e00; PINT=0.e00; //progressive value of integral NSTEP=0; A=1.e00; while(A > 1.e-10){ NSTEP=NSTEP+1; ETD=PETD+0.5e00*DETD; SUMD=0.e00; //normalizing sum in the denominator IMAX=ETD/TVD+J; for(II=0;II<=IMAX;II++){ SUMD=SUMD+pow((1.e00-double(II)*TVD/(ETD+double(J)*TVD)),(1.5e00-gas->SP[3][MOLSP])); } VAL=(pow((ETD*(1.e00-EAD/(ETD+double(J)*TVD))),(1.5e00-gas->SP[3][MOLSP]))/SUMD)*exp(-ETD); PINT=PINT+VAL*DETD; A=VAL/PINT; PETD=ETD+0.5e00*DETD; } VRREX[I][K][L][M][J]=C*PINT; // WRITE (*,*) 'Level ratio exch',I,J,VRREX(I,K,L,M,J) } } // //memset(TOT,0.e00,sizeof(**TOT));//TOT=0.e00; for(int i=0;i<gas->MVIBL+1;i++){ for(int j=0;j<gas->MVIBL+1;j++){ TOT[i][j]=0; } } for(I=1;I<=2;I++){ if(I == 1) T=gas->SPEX[4][K][L][M]; if(I == 2) T=gas->SPEX[5][K][L][M]; for(J=0;J<=JMAX;J++){ TVD=gas->SPVM[1][gas->ISPEX[K][5][L][M]][MOLSP]/T; ZVT=1.e00/(1.e00-exp(-TVD)); BFRAC[J][I]=exp(-J*gas->SPVM[1][gas->ISPEX[K][5][L][M]][MOLSP]/T)/ZVT; //Boltzmann fraction VRREX[I][K][L][M][J]=VRREX[I][K][L][M][J]*BFRAC[J][I]; // WRITE (*,*) 'Contribution',I,J,VRREX(I,K,L,M,J) for(MM=0;MM<=J;MM++) TOT[J][I]=TOT[J][I]+VRREX[I][K][L][M][MM]; } } // for(I=1;I<=2;I++){ for(J=0;J<=JMAX;J++){ gas->SPREX[I][K][L][M][J]=TOT[J][I]; if(J == JMAX) gas->SPREX[I][K][L][M][J]=1.e00; //WRITE (9,*) 'Cumulative',I,J,SPREX(I,K,L,M,J) file_9<<"Cumulative "<<I<<" "<<J<<" "<<gas->SPREX[I][K][L][M][J]; } } } } gas->NSLEV=0; //memset(gas->SLER,0.e00,sizeof(*gas->SLER));//gas->SLER=0.e00; for(int i=0;i<gas->MSP+1;i++) gas->SLER[i]=0.e00; } } } // //READ (*,*) //optionally pause program to check cumulative distributions for exchange abd chain reactions return; } void READ_DATA() { //CALC calc; //MOLECS molecs; //GAS gas; //OUTPUT output; //GEOM_1D geom; fstream file_3; fstream file_4; int NVERD,MVERD,N,K; if(calc->ICLASS==0) { cout<<"Reading the data file DS0D.DAT"<<endl; file_4.open("DS0D.DAT", ios::in); file_3.open("DS0D.TXT", ios::out); file_3<<"Data summary for program DSMC"<<endl; // OPEN (4,FILE='DS0D.DAT') // OPEN (3,FILE='DS0D.TXT') // WRITE (3,*) 'Data summary for program DSMC' } if(calc->ICLASS==1) { cout<<"Reading the data file DS1D.DAT"<<endl; file_4.open("DS1D.DAT", ios::in); file_3.open("DS1D.TXT", ios::out ); file_3<<"Data summary for program DSMC"<<endl; // OPEN (4,FILE='DS1D.DAT') // OPEN (3,FILE='DS1D.TXT') // WRITE (3,*) 'Data summary for program DSMC' } //the following items are common to all classes of flow file_4>>NVERD; file_3<<"The n in version number n.m is "<<NVERD<<endl; file_4>>MVERD; file_3<<"The m in version number n.m is "<<MVERD<<endl; file_4>>calc->IMEG; file_3<<"The approximate number of megabytes for the calculation is "<<calc->IMEG<<endl; file_4>>gas->IGAS; file_3<<gas->IGAS<<endl;//gas->IGAS=1; // READ (4,*) NVERD // WRITE (3,*) 'The n in version number n.m is',NVERD // READ (4,*) MVERD // WRITE (3,*) 'The m in version number n.m is',MVERD // READ (4,*) IMEG //calc->IMEG // WRITE (3,*) 'The approximate number of megabytes for the calculation is',IMEG //calc->IMEG // READ (4,*) IGAS //gas->IGAS // WRITE (3,*) IGAS //gas->IGAS if(gas->IGAS==1) { file_3<<" Hard sphere gas "<<endl; // WRITE (3,*) 'Hard sphere gas' HARD_SPHERE(); } if(gas->IGAS==2) { file_3<<"Argon "<<endl; // WRITE (3,*) 'Argon' ARGON(); } if(gas->IGAS==3) { file_3<<"Ideal nitrogen"<<endl; // WRITE (3,*) 'Ideal nitrogen' IDEAL_NITROGEN(); } if(gas->IGAS==4) { file_3<<"Real oxygen "<<endl; // WRITE (3,*) 'Real oxygen' REAL_OXYGEN(); } if(gas->IGAS==5) { file_3<<"Ideal air "<<endl; // TE (3,*) 'Ideal air' IDEAL_AIR(); } if(gas->IGAS==6) { file_3<<"Real air @ 7.5 km/s "<<endl; // RITE (3,*) 'Real air @ 7.5 km/s' REAL_AIR(); } if(gas->IGAS==7) { file_3<<"Helium-argon-xenon mixture "<<endl; // WRITE (3,*) 'Helium-argon-xenon mixture' HELIUM_ARGON_XENON(); } if(gas->IGAS==8) { file_3<<"Oxygen-hydrogen "<<endl; // WRRITE (3,*) 'Oxygen-hydrogen' OXYGEN_HYDROGEN(); } file_3<<"The gas properties are:- "<<endl; file_4>>gas->FND[1]; file_3<<"The stream number density is "<<gas->FND[1]<<endl; file_4>>gas->FTMP[1]; file_3<<"The stream temperature is "<<gas->FTMP[1]<<endl; // WRITE (3,*) 'The gas properties are:-' // READ (4,*) FND(1) //gas->FND[1] // WRITE (3,*) ' The stream number density is',FND(1) ////gas->FND[1] // READ (4,*) FTMP(1) //gas->FTMP[1] // WRITE (3,*) ' The stream temperature is',FTMP(1) //gas->FTMP[1] if(gas->MMVM>0) { file_4>>gas->FVTMP[1]; file_3<<"The stream vibrational and electronic temperature is "<<gas->FVTMP[1]<<endl; // READ (4,*) FVTMP(1) //gas->FVTMP; // WRITE (3,*) ' The stream vibrational and electronic temperature is',FVTMP(1) //gas->FVTMP[1] } if(calc->ICLASS==1) { file_4>>gas->VFX[1]; file_3<<"The stream velocity in the x direction is "<<gas->VFX[1]<<endl; file_4>>gas->VFY[1]; file_3<<"The stream velocity in the y direction is "<<gas->VFY[1]<<endl; // READ (4,*) VFX(1) //gas->VFX[1] // WRITE (3,*) ' The stream velocity in the x direction is',VFX(1) //gas->VFX[1] // READ (4,*) VFY(1) ////gas->VFY[1] // WRITE (3,*) ' The stream velocity in the y direction is',VFY(1) ////gas->VFY[1] } if(gas->MSP>1) { for(N=1;N<=gas->MSP;N++) { file_4>>gas->FSP[N][1]; file_3<<" The fraction of species "<<N<<" is "<<gas->FSP[N][1]<<endl; // READ (4,*) FSP(N,1) //gas->FSP[N][1] // WRITE (3,*) ' The fraction of species',N,' is',FSP(N,1) //gas->FSP[N][1] } } else { gas->FSP[1][1]=1.0; //simple gas } if(calc->ICLASS==0){ // !--a homogeneous gas case is calculated as a one-dimensional flow with a single sampling cell // !--set the items that are required in the DS1D.DAT specification geom->IFX=0; geom->JFX=1; geom->XB[1]=0.e00; geom->XB[2]=0.0001e00*1.e25/gas->FND[1]; geom->ITYPE[1]=1; geom->ITYPE[2]=1; gas->VFX[1]=0.e00; calc->IGS=1; calc->ISECS=0; calc->IREM=0; calc->MOLSC=10000*calc->IMEG; //a single sampling cell } if(calc->ICLASS==1) { file_4>>geom->IFX; // READ (4,*) IFX //geom->IFX if(geom->IFX==0) file_3<<"Plane Flow"<<endl; // WRITE (3,*) 'Plane flow' if(geom->IFX==1) file_3<<"Cylindrical flow"<<endl; // WRITE (3,*) 'Cylindrical flow' if(geom->IFX==2) file_3<<"Spherical flow"<<endl; // WRITE (3,*) 'Spherical flow' geom->JFX=geom->IFX+1; file_4>>geom->XB[1]; // READ (4,*) XB(1) //geom->XB[1] file_3<<"The minimum x coordinate is "<<geom->XB[1]<<endl; // WRITE (3,*) 'The minimum x coordinate is',XB(1) //geom->XB[1] file_4>>geom->ITYPE[1]; // READ (4,*) ITYPE(1) //geom->ITYPE[1] if(geom->ITYPE[1]==0) file_3<<"The minimum x coordinate is a stream boundary"<<endl; // WRITE (3,*) 'The minimum x coordinate is a stream boundary' if(geom->ITYPE[1]==1) file_3<<"The minimum x coordinate is a plane of symmetry"<<endl; // WRITE (3,*) 'The minimum x coordinate is a plane of symmetry' if(geom->ITYPE[1]==2) file_3<<"The minimum x coordinate is a solid surface"<<endl; // WRITE (3,*) 'The minimum x coordinate is a solid surface' if(geom->ITYPE[1]==3) file_3<<"The minimum x coordinate is a vacuum"<<endl; // WRITE (3,*) 'The minimum x coordinate is a vacuum' if(geom->ITYPE[1]==4) file_3<<"The minimum x coordinate is an axis or center"<<endl; // WRITE (3,*) 'The minimum x coordinate is an axis or center' if(geom->ITYPE[1]==2) { file_3<<"The minimum x boundary is a surface with the following properties"<<endl; file_4>>gas->TSURF[1]; file_3<<"The temperature of the surface is "<<gas->TSURF[1]<<endl; file_4>>gas->FSPEC[1]; file_3<<"The fraction of specular reflection is "<<gas->FSPEC[1]<<endl; file_4>>gas->VSURF[1]; file_3<<"The velocity in the y direction of this surface is "<<gas->VSURF[1]; // WRITE (3,*) 'The minimum x boundary is a surface with the following properties' // READ (4,*) TSURF(1) //gas->TSURF[1] // WRITE (3,*) ' The temperature of the surface is',TSURF(1) //gas->TSURF[1] // READ (4,*) FSPEC(1) //gas->FSPEC[1] // WRITE (3,*) ' The fraction of specular reflection is',FSPEC(1) //gas->FSPEC[1] // READ (4,*) VSURF(1) //gas->VSURF[1] // WRITE (3,*) ' The velocity in the y direction of this surface is',VSURF(1) //gas->VSURF[1] } file_4>>geom->XB[2]; file_3<<"The maximum x coordinate is "<<geom->XB[2]<<endl; file_4>>geom->ITYPE[2]; // READ (4,*) XB(2) //geom->XB[2] // WRITE (3,*) 'The maximum x coordinate is',XB(2)//geom->XB[2] // READ (4,*) ITYPE(2)//geom->ITYPE[2] if(geom->ITYPE[2]==0) file_3<<"The mmaximum x coordinate is a stream boundary"<<endl; // WRITE (3,*) 'The mmaximum x coordinate is a stream boundary' if(geom->ITYPE[2]==1) file_3<<"The maximum x coordinate is a plane of symmetry"<<endl; // WRITE (3,*) 'The maximum x coordinate is a plane of symmetry' if(geom->ITYPE[2]==2) file_3<<"The maximum x coordinate is a solid surface"<<endl; // WRITE (3,*) 'The maximum x coordinate is a solid surface' if(geom->ITYPE[2]==3) file_3<<"The maximum x coordinate is a vacuum"<<endl; // WRITE (3,*) 'The maximum x coordinate is a vacuum' calc->ICN=0; if(geom->ITYPE[2]==4) { file_3<<"The maximum x coordinate is a stream boundary with a fixed number of simulated molecules"<<endl; // WRITE (3,*) 'The maximum x coordinate is a stream boundary with a fixed number of simulated molecules' if(gas->MSP==1) calc->ICN=1; } if(geom->ITYPE[2]==2) { file_3<<"The maximum x boundary is a surface with the following properties"<<endl; file_4>>gas->TSURF[1]; file_3<<"The temperature of the surface is "<<gas->TSURF[1]<<endl; file_4>>gas->FSPEC[1]; file_3<<"The fraction of specular reflection is "<<gas->FSPEC[1]<<endl; file_4>>gas->VSURF[1]; file_3<<"The velocity in the y direction of this surface is "<<gas->VSURF[1]<<endl; // WRITE (3,*) 'The maximum x boundary is a surface with the following properties' // READ (4,*) TSURF(1) //gas->TSURF[1] // WRITE (3,*) ' The temperature of the surface is',TSURF(1) //gas->TSURF[1] // READ (4,*) FSPEC(1) //gas->FSPEC[1] // WRITE (3,*) ' The fraction of specular reflection is',FSPEC(1) //gas->FSPEC[1] // READ (4,*) VSURF(1) //gas->VSURF[1] // WRITE (3,*) ' The velocity in the y direction of this surface is',VSURF(1) //gas->VSURF[1] } if(geom->IFX>0) { file_4>>geom->IWF; // READ (4,*) READ (4,*) IWF //geom->IWF if(geom->IWF==0) file_3<<"There are no radial weighting factors"<<endl; // WRITE (3,*) 'There are no radial weighting factors' if(geom->IWF==1) file_3<<"There are radial weighting factors"<<endl; // WRITE (3,*) 'There are radial weighting factors' if(geom->IWF==1) { file_4>>geom->WFM; file_3<<"The maximum value of the weighting factor is "<<geom->WFM<<endl; // READ (4,*) WFM //geom->WFM // WRITE (3,*) 'The maximum value of the weighting factor is ',WFM //geom->WFM geom->WFM=(geom->WFM-1)/geom->XB[2]; } } file_4>>calc->IGS; // READ (4,*) IGS //calc->IGS if(calc->IGS==0) file_3<<"The flowfield is initially a vacuum "<<endl; // WRITE (3,*) 'The flowfield is initially a vacuum' if(calc->IGS==1) file_3<<"The flowfield is initially the stream(s) or reference gas"<<endl; // WRITE (3,*) 'The flowfield is initially the stream(s) or reference gas' file_4>>calc->ISECS; // READ (4,*) ISECS //calc->ISECS if(calc->ISECS==0) file_3<<"There is no secondary stream initially at x > 0"<<endl; // WRITE (3,*) 'There is no secondary stream initially at x > 0' if(calc->ISECS==1 && geom->IFX==0) file_3<<"There is a secondary stream applied initially at x = 0 (XB(2) must be > 0)"<<endl; // WRITE (3,*) 'There is a secondary stream applied initially at x = 0 (XB(2) must be > 0)' if(calc->ISECS==1 && geom->IFX>0) { if(geom->IWF==1) { file_3<<"There cannot be a secondary stream when weighting factors are present"<<endl; // WRITE (3,*) 'There cannot be a secondary stream when weighting factors are present' return;//STOP//dout } file_3<<"There is a secondary stream"<<endl; // WRITE (3,*) 'There is a secondary stream' file_4>>geom->XS; // READ (4,*) XS //geom->XS file_3<<"The secondary stream boundary is at r= "<<geom->XS<<endl; // WRITE (3,*) 'The secondary stream boundary is at r=',XS //geom->XS } if(calc->ISECS==1) { file_3<<"The secondary stream (at x>0 or X>XS) properties are:-"<<endl; file_4>>gas->FND[2]; file_3<<"The stream number density is "<<gas->FND[2]<<endl; file_4>>gas->FTMP[2]; file_3<<"The stream temperature is "<<gas->FTMP[2]<<endl; // WRITE (3,*) 'The secondary stream (at x>0 or X>XS) properties are:-' // READ (4,*) FND(2) //gas->FND // WRITE (3,*) ' The stream number density is',FND(2) //gas->FND // READ (4,*) FTMP(2) //gas->FTMP // WRITE (3,*) ' The stream temperature is',FTMP(2) //gas->FTMP if(gas->MMVM>0) { file_4>>gas->FVTMP[2]; file_3<<"The stream vibrational and electronic temperature is "<<gas->FVTMP[2]<<endl; // READ (4,*) FVTMP(2) //gas->FVTMP[2] // WRITE (3,*) ' The stream vibrational and electronic temperature is',FVTMP(2) //gas->FVTMP[2] } file_4>>gas->VFX[2]; file_3<<"The stream velocity in the x direction is "<<gas->VFX[2]<<endl; file_4>>gas->VFY[2]; file_3<<"The stream velocity in the y direction is "<<gas->VFY[2]<<endl; // READ (4,*) VFX(2) //gas->VFX // WRITE (3,*) ' The stream velocity in the x direction is',VFX(2) //gas->VFX // READ (4,*) VFY(2) //gas->VFY // WRITE (3,*) ' The stream velocity in the y direction is',VFY(2) //gas->VFY if(gas->MSP>1) { for(N=1;N<=gas->MSP;N++) { file_4>>gas->FSP[N][2]; file_3<<"The fraction of species "<<N<<" is "<<gas->FSP[N][2]<<endl; // READ (4,*) FSP(N,2) //gas->FSP // WRITE (3,*) ' The fraction of species',N,' is',FSP(N,2) //gas->FSP } } else { gas->FSP[1][2]=1; } } if(geom->IFX==0 && geom->ITYPE[1]==0) { file_4>>calc->IREM; // READ (4,*) IREM //calc->IREM if(calc->IREM==0) { file_3<<"There is no molecule removal"<<endl; // WRITE (3,*) 'There is no molecule removal' geom->XREM=geom->XB[1]-1.e00; geom->FREM=0.e00; } else if(calc->IREM==1) { file_4>>geom->XREM; file_3<<"There is full removal of the entering (at XB(1)) molecules between "<<geom->XREM<<" and "<<geom->XB[2]<<endl; // READ (4,*) XREM //geom->XREM // WRITE (3,*) ' There is full removal of the entering (at XB(1)) molecules between',XREM,' and',XB(2) //geom->XREM ,geom->XB[2] geom->FREM=1.e00; } else if(calc->IREM==2) { file_3<<"Molecule removal is specified whenever the program is restarted"<<endl; // WRITE (3,*) ' Molecule removal is specified whenever the program is restarted' geom->XREM=geom->XB[1]-1.e00; geom->FREM=0.e00; } else { geom->XREM=geom->XB[1]-1.e00; geom->FREM=0.e00; } } geom->IVB=0; geom->VELOB=0.e00; if(geom->ITYPE[2]==1) { file_4>>geom->IVB; // READ (4,*) IVB if(geom->IVB==0) file_3<<"The outer boundary is stationary"<<endl; // WRITE (3,*) ' The outer boundary is stationary' if(geom->IVB==1) { file_3<<"The outer boundary moves with a constant speed"<<endl; file_4>>geom->VELOB; file_3<<" The speed of the outer boundary is "<<geom->VELOB<<endl; // WRITE (3,*) ' The outer boundary moves with a constant speed' // READ (4,*) VELOB //geom->VELOB // WRITE (3,*) ' The speed of the outer boundary is',VELOB //geom->VELOB } } file_4>>calc->MOLSC; file_3<<"The desired number of molecules in a sampling cell is "<<calc->MOLSC<<endl; // READ (4,*) MOLSC //calc->MOLSC // WRITE (3,*) 'The desired number of molecules in a sampling cell is',MOLSC ////calc->MOLSC } //set the speed of the outer boundary file_3.close(); file_4.close(); // CLOSE (3) // CLOSE (4) // set the stream at the maximum x boundary if there is no secondary stream if(calc->ISECS==0 && geom->ITYPE[2]==0) { gas->FND[2]=gas->FND[1]; gas->FTMP[2]=gas->FTMP[1]; if(gas->MMVM>0) gas->FVTMP[2]=gas->FVTMP[1]; gas->VFX[2]=gas->VFX[1]; if(gas->MSP>1) { for(N=1;N<=gas->MSP;N++) { gas->FSP[N][2]=gas->FSP[N][1]; } } else gas->FSP[1][2]=1; } //dout //1234 CONTINUE; return; } void INITIALISE_SAMPLES() { //start a new sample for all classes of flow //CALC calc; //GEOM_1D geom; //GAS gas; //OUTPUT output; //MOLECS molecs; int N; // output->NSAMP=0.0; output->TISAMP=calc->FTIME; output->NMISAMP=molecs->NM; //memset(output->COLLS,0.e00,sizeof(*output->COLLS));memset(output->WCOLLS,0.e00,sizeof(*output->WCOLLS));memset(output->CLSEP,0.e00,sizeof(*output->CLSEP)); for(int i=0;i<geom->NCELLS+1;i++) output->COLLS[i]=0.e00; for(int i=0;i<geom->NCELLS+1;i++) output->WCOLLS[i]=0.e00; for(int i=0;i<geom->NCELLS+1;i++) output->CLSEP[i]=0.e00; //output->COLLS=0.e00 ; output->WCOLLS=0.e00 ; output->CLSEP=0.e00; //memset(calc->TCOL,0.0,sizeof(**calc->TCOL));//calc->TCOL=0.0; for(int i=0;i<gas->MSP+1;i++){ for(int j=0;j<gas->MSP+1;j++){ calc->TCOL[i][j]=0.0; } } //gas->TREACG=0; //gas->TREACL=0; for(int i=0;i<5;i++){ for(int j=0;j<gas->MSP+1;j++){ gas->TREACG[i][j]=0; } } for(int i=0;i<5;i++){ for(int j=0;j<gas->MSP+1;j++){ gas->TREACL[i][j]=0; } } //memset(output->CS,0.0,sizeof(***output->CS));memset(output->CSS,0.0,sizeof(****output->CSS));memset(output->CSSS,0.0,sizeof(**output->CSSS)); for(int j=0;j<gas->MSP+10;j++){ for(int k=0;k<geom->NCELLS+1;k++){ for(int l=0;l<gas->MSP+1;l++) output->CS[j][k][l]=0.0; } } for(int i=0;i<9;i++){ for(int j=0;j<3;j++){ for(int k=0;k<gas->MSP+1;k++){ for(int l=0;l<3;l++) output->CSS[i][j][k][l]=0.0; } } } for(int k=0;k<7;k++){ for(int l=0;l<3;l++) output->CSSS[k][l]=0.0; } //output->CS=0.0 ; output->CSS=0.0 ; output->CSSS=0.0; //memset(output->VIBFRAC,0.e00,sizeof(***output->VIBFRAC));//output->VIBFRAC=0.e00; //memset(output->SUMVIB,0.e00,sizeof(**output->SUMVIB));//output->SUMVIB=0.e00; for(int j=0;j<gas->MSP+1;j++){ for(int k=0;k<gas->MMVM+1;k++){ for(int l=0;l<151;l++) output->VIBFRAC[j][k][l]=0.0; } } for(int k=0;k<gas->MSP+1;k++){ for(int l=0;l<gas->MMVM+1;l++) output->SUMVIB[k][l]=0.0; } } //// // void SET_INITIAL_STATE_1D() { //set the initial state of a homogeneous or one-dimensional flow // //MOLECS molecs; //GEOM_1D geom; //GAS gas; //CALC calc; //OUTPUT output; // // int J,L,K,KK,KN,II,III,INC,NSET,NSC; long long N,M; double A,B,AA,BB,BBB,SN,XMIN,XMAX,WFMIN,DENG,ELTI,EA,XPREV; double DMOM[4]; double VB[4][3]; double ROTE[3]; // //NSET the alternative set numbers in the setting of exact initial state //DMOM(N) N=1,2,3 for x,y and z momentum sums of initial molecules //DENG the energy sum of the initial molecules //VB alternative sets of velocity components //ROTE alternative sets of rotational energy //EA entry area //INC counting increment //ELTI initial electronic temperature //XPREV the pevious x coordinate // //memset(DMOM,0.e00,sizeof(DMOM)); for(int i=0;i<4;i++) DMOM[i]=0.e00; DENG=0.e00; //set the number of molecules, divisions etc. based on stream 1 // calc->NMI=10000*calc->IMEG+2; //small changes in number for statistically independent runs geom->NDIV=calc->NMI/calc->MOLSC; //MOLSC molecules per division //WRITE (9,*) 'The number of divisions is',NDIV file_9<< "The number of divisions is "<<geom->NDIV<<endl; // geom->MDIV=geom->NDIV; geom->ILEVEL=0; // geom->i_allocate(geom->ILEVEL+1,geom->MDIV+1,geom->JDIV); // ALLOCATE (JDIV(0:ILEVEL,MDIV),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR JDIV ARRAY',ERROR // ENDIF // geom->DDIV=(geom->XB[2]-geom->XB[1])/double(geom->NDIV); geom->NCELLS=geom->NDIV; //WRITE (9,*) 'The number of sampling cells is',NCELLS file_9<<"The number of sampling cells is "<< geom->NCELLS<<endl; geom->NCIS=calc->MOLSC/calc->NMCC; geom->NCCELLS=geom->NCIS*geom->NDIV; //WRITE (9,*) 'The number of collision cells is',NCCELLS file_9<< "The number of collision cells is "<<geom->NCCELLS<<endl; // if(geom->IFX == 0) geom->XS=0.e00; // if(calc->ISECS == 0){ if(geom->IFX == 0) calc->FNUM=((geom->XB[2]-geom->XB[1])*gas->FND[1])/double(calc->NMI); if(geom->IFX == 1) calc->FNUM=PI*(pow(geom->XB[2],2)-pow(geom->XB[1],2))*gas->FND[1]/double(calc->NMI); if(geom->IFX == 2) calc->FNUM=1.3333333333333333333333e00*PI*(pow(geom->XB[2],3)-pow(geom->XB[1],3))*gas->FND[1]/double(calc->NMI); } else{ if(geom->IFX == 0) calc->FNUM=((geom->XS-geom->XB[1])*gas->FND[1]+(geom->XB[2]-geom->XS)*gas->FND[2])/double(calc->NMI); if(geom->IFX == 1) calc->FNUM=PI*((pow(geom->XS,2)-pow(geom->XB[1],2))*gas->FND[1]+(pow(geom->XB[2],2)-pow(geom->XS,2))*gas->FND[2])/double(calc->NMI); if(geom->IFX == 2) calc->FNUM=1.3333333333333333333333e00*PI*((pow(geom->XS,3)-pow(geom->XB[1],3))*gas->FND[1]+(pow(geom->XB[2],3)-pow(geom->XS,3))*gas->FND[2])/double(calc->NMI); } // calc->FNUM=calc->FNUM*calc->FNUMF; if(calc->FNUM < 1.e00) calc->FNUM=1.e00; // calc->FTIME=0.e00; // calc->TOTMOV=0.e00; calc->TOTCOL=0.e00; output->NDISSOC=0; //memset(calc->TCOL,0.e00,sizeof(**calc->TCOL));//calc->TCOL=0.e00; for(int i=0;i<gas->MSP+1;i++){ for(int j=0;j<gas->MSP+1;j++){ calc->TCOL[i][j]=0.e00; } } //memset(calc->TDISS,0.e00,sizeof(*calc->TDISS));//calc->TDISS=0.e00; //memset(calc->TRECOMB,0.e00,sizeof(*calc->TRECOMB));//calc->TRECOMB=0.e00; for(int i=0;i<gas->MSP+1;i++) calc->TDISS[i]=0.e00; for(int i=0;i<gas->MSP+1;i++) calc->TRECOMB[i]=0.e00; //gas->TREACG=0; //gas->TREACL=0; for(int i=0;i<5;i++){ for(int j=0;j<gas->MSP+1;j++){ gas->TREACG[i][j]=0; } } for(int i=0;i<5;i++){ for(int j=0;j<gas->MSP+1;j++){ gas->TREACL[i][j]=0; } } //memset(gas->TNEX,0.e00,sizeof(*gas->TNEX));//gas->TNEX=0.e00; for(int i=0;i<gas->MEX+1;i++) gas->TNEX[i]= 0.e00; for(N=1;N<=geom->NDIV;N++){ geom->JDIV[0][N]=-N; } // geom->d_allocate(5,geom->NCELLS+1,geom->CELL); geom->i_allocate(geom->NCELLS+1,geom->ICELL); geom->d_allocate(6,geom->NCCELLS+1,geom->CCELL); geom->i_allocate(4,geom->NCCELLS+1,geom->ICCELL); // ALLOCATE (CELL(4,NCELLS),ICELL(NCELLS),CCELL(5,NCCELLS),ICCELL(3,NCCELLS),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR CELL ARRAYS',ERROR // ENDIF // output->d_allocate(geom->NCELLS+1,output->COLLS); output->d_allocate(geom->NCELLS+1,output->WCOLLS); output->d_allocate(geom->NCELLS+1,output->CLSEP); output->d_allocate(gas->MNSR+1,output->SREAC); output->d_allocate(24,geom->NCELLS+1,output->VAR); output->d_allocate(13,geom->NCELLS+1,gas->MSP+1,output->VARSP); output->d_allocate(36+gas->MSP,3,output->VARS); output->d_allocate(10+gas->MSP,geom->NCELLS+1,gas->MSP+1,output->CS); output->d_allocate(9,3,gas->MSP+1,3,output->CSS); output->d_allocate(7,3,output->CSSS); // ALLOCATE (COLLS(NCELLS),WCOLLS(NCELLS),CLSEP(NCELLS),SREAC(MNSR),VAR(23,NCELLS),VARSP(0:12,NCELLS,MSP), & // VARS(0:35+MSP,2),CS(0:9+MSP,NCELLS,MSP),CSS(0:8,2,MSP,2),CSSS(6,2),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR SAMPLING ARRAYS',ERROR // ENDIF // if(gas->MMVM >= 0){ output->d_allocate(gas->MSP+1,gas->MMVM+1,151,output->VIBFRAC); output->d_allocate(gas->MSP+1,gas->MMVM+1,output->SUMVIB); // ALLOCATE (VIBFRAC(MSP,MMVM,0:150),SUMVIB(MSP,MMVM),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR RECOMBINATION ARRAYS',ERROR // ENDIF } // INITIALISE_SAMPLES(); // //Set the initial cells for(N=1;N<=geom->NCELLS;N++){ geom->CELL[2][N]=geom->XB[1]+double(N-1)*geom->DDIV; geom->CELL[3][N]=geom->CELL[2][N]+geom->DDIV; geom->CELL[1][N]=geom->CELL[2][N]+0.5e00*geom->DDIV; if(geom->IFX == 0) geom->CELL[4][N]=geom->CELL[3][N]-geom->CELL[2][N]; //calculation assumes unit cross-section if(geom->IFX == 1) geom->CELL[4][N]=PI*(pow(geom->CELL[3][N],2)-pow(geom->CELL[2][N],2)); //assumes unit length of full cylinder if(geom->IFX == 2) geom->CELL[4][N]=1.33333333333333333333e00*PI*(pow(geom->CELL[3][N],3)-pow(geom->CELL[2][N],3)); //flow is in the full sphere geom->ICELL[N]=geom->NCIS*(N-1); for(M=1;M<=geom->NCIS;M++){ L=geom->ICELL[N]+M; XMIN=geom->CELL[2][N]+double(M-1)*geom->DDIV/double(geom->NCIS); XMAX=XMIN+geom->DDIV/double(geom->NCIS); if(geom->IFX == 0) geom->CCELL[1][L]=XMAX-XMIN; if(geom->IFX == 1) geom->CCELL[1][L]=PI*(pow(XMAX,2)-pow(XMIN,2)); //assumes unit length of full cylinder if(geom->IFX == 2) geom->CCELL[1][L]=1.33333333333333333333e00*PI*(pow(XMAX,3)-pow(XMIN,3)); //flow is in the full sphere geom->CCELL[2][L]=0.e00; geom->ICCELL[3][L]=N; } output->VAR[11][N]=gas->FTMP[1]; output->VAR[8][N]=gas->FTMP[1]; } // if(geom->IWF == 0) geom->AWF=1.e00; if(geom->IWF == 1){ //FNUM must be reduced to allow for the weighting factors A=0.e00; B=0.e00; for(N=1;N<=geom->NCELLS;N++){ A=A+geom->CELL[4][N]; B=B+geom->CELL[4][N]/(1.0+geom->WFM*pow(geom->CELL[1][N],geom->IFX)); } geom->AWF=A/B; calc->FNUM=calc->FNUM*B/A; } // //WRITE (9,*) 'FNUM is',FNUM file_9<<"FNUM is "<<calc->FNUM<<endl; // //set the information on the molecular species // A=0.e00; B=0.e00; for(L=1;L<=gas->MSP;L++){ A=A+gas->SP[5][L]*gas->FSP[L][1]; B=B+(3.0+gas->ISPR[1][L])*gas->FSP[L][1]; gas->VMP[L][1]=sqrt(2.e00*BOLTZ*gas->FTMP[1]/gas->SP[5][L]); if((geom->ITYPE[2]== 0) || (calc->ISECS == 1)) gas->VMP[L][2]=sqrt(2.e00*BOLTZ*gas->FTMP[2]/gas->SP[5][L]); calc->VNMAX[L]=3.0*gas->VMP[L][1]; if(L == 1) gas->VMPM=gas->VMP[L][1]; else if(gas->VMP[L][1] > gas->VMPM) gas->VMPM=gas->VMP[L][1]; } //WRITE (9,*) 'VMPM =',VMPM file_9<< "VMPM = "<<gas->VMPM<<endl; gas->FDEN=A*gas->FND[1]; gas->FPR=gas->FND[1]*BOLTZ*gas->FTMP[1]; gas->FMA=gas->VFX[1]/sqrt((B/(B+2.e00))*BOLTZ*gas->FTMP[1]/A); //set the molecular properties for collisions between unlike molecles //to the average of the molecules for(L=1;L<=gas->MSP;L++){ for(M=1;M<=gas->MSP;M++){ gas->SPM[4][L][M]=0.5e00*(gas->SP[1][L]+gas->SP[1][M]); gas->SPM[3][L][M]=0.5e00*(gas->SP[3][L]+gas->SP[3][M]); gas->SPM[5][L][M]=0.5e00*(gas->SP[2][L]+gas->SP[2][M]); gas->SPM[1][L][M]=gas->SP[5][L]*(gas->SP[5][M]/(gas->SP[5][L]+gas->SP[5][M])); gas->SPM[2][L][M]=0.25e00*PI*pow((gas->SP[1][L]+gas->SP[1][M]),2); AA=2.5e00-gas->SPM[3][L][M]; A=tgamma(AA); gas->SPM[6][L][M]=1.e00/A; gas->SPM[8][L][M]=0.5e00*(gas->SP[4][L]+gas->SP[4][M]); if((gas->ISPR[1][L] > 0) && (gas->ISPR[1][M] > 0)) gas->SPM[7][L][M]=(gas->SPR[1][L]+gas->SPR[1][M])*0.5e00; if((gas->ISPR[1][L] > 0) && (gas->ISPR[1][M] == 0)) gas->SPM[7][L][M]=gas->SPR[1][L]; if((gas->ISPR[1][M] > 0) && (gas->ISPR[1][L] == 0)) gas->SPM[7][L][M]=gas->SPR[1][M]; } } if(gas->MSP == 1){ //set unscripted variables for the simple gas case gas->RMAS=gas->SPM[1][1][1]; gas->CXSS=gas->SPM[2][1][1]; gas->RGFS=gas->SPM[6][1][1]; } // for(L=1;L<=gas->MSP;L++){ gas->CR[L]=0.e00; for(M=1;M<=gas->MSP;M++){ //set the equilibrium collision rates gas->CR[L]=gas->CR[L]+2.e00*SPI*pow(gas->SPM[4][L][M],2)*gas->FND[1]*gas->FSP[M][1]*pow((gas->FTMP[1]/gas->SPM[5][L][M]),(1.0-gas->SPM[3][L][M]))*sqrt(2.0*BOLTZ*gas->SPM[5][L][M]/gas->SPM[1][L][M]); } } A=0.e00; for(L=1;L<=gas->MSP;L++) A=A+gas->FSP[L][1]*gas->CR[L]; gas->CTM=1.e00/A; //WRITE (9,*) 'Collision time in the stream is',CTM file_9<< "Collision time in the stream is "<<gas->CTM; // for(L=1;L<=gas->MSP;L++){ gas->FP[L]=0.e00; for(M=1;M<=gas->MSP;M++){ gas->FP[L]=gas->FP[L]+PI*pow(gas->SPM[4][L][M],2)*gas->FND[1]*gas->FSP[M][1]*pow((gas->FTMP[1]/gas->SPM[5][L][M]),(1.0-gas->SPM[3][L][M]))*sqrt(1.e00+gas->SP[5][L]/gas->SP[5][M]); } gas->FP[L]=1.e00/gas->FP[L]; } gas->FPM=0.e00; for(L=1;L<=gas->MSP;L++) gas->FPM=gas->FPM+gas->FSP[L][1]*gas->FP[L]; //WRITE (9,*) 'Mean free path in the stream is',FPM file_9<<"Mean free path in the stream is "<<gas->FPM<<endl; // calc->TNORM=gas->CTM; if(calc->ICLASS == 1) calc->TNORM= (geom->XB[2]-geom->XB[1])/gas->VMPM; //there may be alternative definitions // //set the initial time step calc->DTM=gas->CTM*calc->CPDTM; // if(fabs(gas->VFX[1]) > 1.e-6) A=(0.5e00*geom->DDIV/gas->VFX[1])*calc->TPDTM; else A=0.5e00*geom->DDIV/gas->VMPM; if(geom->IVB == 1){ B=0.25e00*geom->DDIV/(fabs(geom->VELOB)+gas->VMPM); if(B < A) A=B; } if(calc->DTM > A) calc->DTM=A; // calc->DTM=0.1e00*calc->DTM; //OPTIONAL MANUAL ADJUSTMENT that is generally used with a fixed time step (e.g for making x-t diagram) // calc->DTSAMP=calc->SAMPRAT*calc->DTM; calc->DTOUT=calc->OUTRAT*calc->DTSAMP; calc->TSAMP=calc->DTSAMP; calc->TOUT=calc->DTOUT; calc->ENTMASS=0.0; // //WRITE (9,*) 'The initial value of the overall time step is',DTM file_9<< "The initial value of the overall time step is "<<calc->DTM<<endl; // //initialise cell quantities associated with collisions // for(N=1;N<=geom->NCCELLS;N++){ geom->CCELL[3][N]=calc->DTM/2.e00; geom->CCELL[4][N]=2.e00*gas->VMPM*gas->SPM[2][1][1]; calc->RANF=((double)rand()/(double)RAND_MAX); // RANDOM_NUMBER(RANF) geom->CCELL[2][N]=calc->RANF; geom->CCELL[5][N]=0.e00; } // //set the entry quantities // for(K=1;K<=2;K++){ if((geom->ITYPE[K] == 0) || ((K == 2) && (geom->ITYPE[K] == 4))){ if(geom->IFX == 0) EA=1.e00; if(geom->IFX == 1) EA=2.e00*PI*geom->XB[K]; if(geom->IFX == 2) EA=4.e00*PI*pow(geom->XB[K],2); for(L=1;L<=gas->MSP;L++){ if(K == 1) SN=gas->VFX[1]/gas->VMP[L][1]; if(K == 2) SN=-gas->VFX[2]/gas->VMP[L][2]; AA=SN; A=1.e00+erf(AA); BB=exp(-pow(SN,2)); gas->ENTR[3][L][K]=SN; gas->ENTR[4][L][K]=SN+sqrt(pow(SN,2)+2.e00); gas->ENTR[5][L][K]=0.5e00*(1.e00+SN*(2.e00*SN-gas->ENTR[4][L][K])); gas->ENTR[6][L][K]=3.e00*gas->VMP[L][K]; B=BB+SPI*SN*A; gas->ENTR[1][L][K]=EA*gas->FND[K]*gas->FSP[L][K]*gas->VMP[L][K]*B/(calc->FNUM*2.e00*SPI); gas->ENTR[2][L][K]=0.e00; } } } // //Set the uniform stream // molecs->MNM=1.1e00*calc->NMI; // if(gas->MMVM > 0){ molecs->d_allocate(calc->NCLASS+1,molecs->MNM+1,molecs->PX); molecs->d_allocate(molecs->MNM+1,molecs->PTIM); molecs->d_allocate(molecs->MNM+1,molecs->PROT); molecs->i_allocate(molecs->MNM+1,molecs->IPCELL); molecs->i_allocate(molecs->MNM+1,molecs->IPSP); molecs->i_allocate(molecs->MNM+1,molecs->ICREF); molecs->i_allocate(molecs->MNM+1,molecs->IPCP); molecs->d_allocate(4,molecs->MNM+1,molecs->PV); molecs->i_allocate(gas->MMVM+1,molecs->MNM+1,molecs->IPVIB); molecs->d_allocate(molecs->MNM+1,molecs->PELE); // ALLOCATE (PX(NCLASS,MNM),PTIM(MNM),PROT(MNM),IPCELL(MNM),IPSP(MNM),ICREF(MNM),IPCP(MNM),PV(3,MNM), & // IPVIB(MMVM,MNM),PELE(MNM),STAT=ERROR) } else{ if(gas->MMRM > 0){ molecs->d_allocate(calc->NCLASS+1,molecs->MNM+1,molecs->PX); molecs->d_allocate(molecs->MNM+1,molecs->PTIM); molecs->d_allocate(molecs->MNM+1,molecs->PROT); molecs->i_allocate(molecs->MNM+1,molecs->IPCELL); molecs->i_allocate(molecs->MNM+1,molecs->IPSP); molecs->i_allocate(molecs->MNM+1,molecs->ICREF); molecs->i_allocate(molecs->MNM+1,molecs->IPCP); molecs->d_allocate(4,molecs->MNM+1,molecs->PV); molecs->d_allocate(molecs->MNM+1,molecs->PELE); // ALLOCATE (PX(NCLASS,MNM),PTIM(MNM),PROT(MNM),IPCELL(MNM),IPSP(MNM),ICREF(MNM),IPCP(MNM),PV(3,MNM),PELE(MNM),STAT=ERROR) } else{ molecs->d_allocate(calc->NCLASS+1,molecs->MNM+1,molecs->PX); molecs->d_allocate(molecs->MNM+1,molecs->PTIM); molecs->i_allocate(molecs->MNM+1,molecs->IPCELL); molecs->i_allocate(molecs->MNM+1,molecs->IPSP); molecs->i_allocate(molecs->MNM+1,molecs->ICREF); molecs->i_allocate(molecs->MNM+1,molecs->IPCP); molecs->d_allocate(4,molecs->MNM+1,molecs->PV); molecs->d_allocate(molecs->MNM+1,molecs->PELE); // ALLOCATE (PX(NCLASS,MNM),PTIM(MNM),IPCELL(MNM),IPSP(MNM),ICREF(MNM),IPCP(MNM),PV(3,MNM),PELE(MNM),STAT=ERROR) } } // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR MOLECULE ARRAYS',ERROR // ENDIF // molecs->NM=0; if(calc->IGS == 1){ cout<<"Setting the initial gas"<<endl; for(L=1;L<=gas->MSP;L++){ //memset(ROTE,0.0,sizeof(ROTE)); for(int i=0;i<3;i++) ROTE[i]=0.0; for(K=1;K<=calc->ISECS+1;K++){ if(calc->ISECS == 0){ //no secondary stream M=(double(calc->NMI)*gas->FSP[L][1]*geom->AWF); XMIN=geom->XB[1]; XMAX=geom->XB[2]; } else{ A=(pow(geom->XS,geom->JFX)-pow(geom->XB[1],geom->JFX))*gas->FND[1]+(pow(geom->XB[2],geom->JFX)-pow(geom->XS,geom->JFX))*gas->FND[2]; if(K == 1){ M=int(double(calc->NMI)*((pow(geom->XS,geom->JFX)-pow(geom->XB[1],geom->JFX))*gas->FND[1]/A)*gas->FSP[L][1]); XMIN=geom->XB[1]; XMAX=geom->XS; } else{ M=int(double(calc->NMI)*((pow(geom->XB[2],geom->JFX)-pow(geom->XS,geom->JFX))*gas->FND[2]/A)*gas->FSP[L][2]); XMIN=geom->XS; XMAX=geom->XB[2]; } } if((K == 1) || (calc->ISECS == 1)){ III=0; WFMIN=1.e00+geom->WFM*pow(geom->XB[1],geom->IFX); N=1; INC=1; if((K== 2) && (geom->JFX > 1)){ BBB=(pow(XMAX,geom->JFX)-pow(XMIN,geom->JFX))/double(M); XPREV=XMIN; } while(N < M){ if((geom->JFX == 1) || (K == 1)) A=pow((pow(XMIN,geom->JFX)+((double(N)-0.5e00)/double(M))*pow((XMAX-XMIN),geom->JFX)),(1.e00/double(geom->JFX))); else{ A=pow((pow(XPREV,geom->JFX)+BBB),(1.e00/double(geom->JFX))); XPREV=A; } if(geom->IWF == 0) B=1.e00; else{ B=WFMIN/(1.e00+geom->WFM*pow(A,geom->IFX)); if((B < 0.1e00) && (INC == 1)) INC=10; if((B < 0.01e00) && (INC == 10)) INC=100; if((B < 0.001e00) && (INC == 100)) INC=1000; if((B < 0.0001e00) && (INC == 1000)) INC=10000; } calc->RANF=((double)rand()/(double)RAND_MAX); // CALL RANDOM_NUMBER(RANF) if(B*double(INC) > calc->RANF){ molecs->NM=molecs->NM+1; molecs->PX[1][molecs->NM]=A; molecs->IPSP[molecs->NM]=L; molecs->PTIM[molecs->NM]=0.0; if(geom->IVB == 0) FIND_CELL_1D(molecs->PX[1][molecs->NM],molecs->IPCELL[molecs->NM],KK); if(geom->IVB == 1) FIND_CELL_MB_1D(molecs->PX[1][molecs->NM],molecs->IPCELL[molecs->NM],KK,molecs->PTIM[molecs->NM]); // for(NSET=1;NSET<=2;NSET++){ for(KK=1;KK<=3;KK++){ RVELC(A,B,gas->VMP[L][K]); if(A < B){ if(DMOM[KK] < 0.e00) BB=B; else BB=A; } else{ if(DMOM[KK] < 0.e00) BB=A; else BB=B; } VB[KK][NSET]=BB; } if(gas->ISPR[1][L] > 0) SROT(L,gas->FTMP[K],ROTE[NSET]); } A=(0.5e00*gas->SP[5][L]*(pow(VB[1][1],2)+pow(VB[2][1],2)+pow(VB[3][1],2))+ROTE[1])/(0.5e00*BOLTZ*gas->FTMP[K])-3.e00-double(gas->ISPR[1][L]); B=(0.5e00*gas->SP[5][L]*(pow(VB[1][2],2)+pow(VB[2][2],2)+pow(VB[3][2],2))+ROTE[2])/(0.5e00*BOLTZ*gas->FTMP[K])-3.e00-double(gas->ISPR[1][L]); if(A < B){ if(DENG < 0.e00) KN=2; else KN=1; } else{ if(DENG < 0.e00) KN=1; else KN=2; } for(KK=1;KK<=3;KK++){ molecs->PV[KK][molecs->NM]=VB[KK][KN]; DMOM[KK]=DMOM[KK]+VB[KK][KN]; } molecs->PV[1][molecs->NM]=molecs->PV[1][molecs->NM]+gas->VFX[K]; molecs->PV[2][molecs->NM]=molecs->PV[2][molecs->NM]+gas->VFY[K]; if(gas->ISPR[1][L] > 0) molecs->PROT[molecs->NM]=ROTE[KN]; // PROT(NM)=0.d00 //uncomment for zero initial rotational temperature (Figs. 6.1 and 6.2) if(KN == 1) DENG=DENG+A; if(KN == 2) DENG=DENG+B; if(gas->MMVM > 0){ if(gas->ISPV[L] > 0){ for(J=1;J<=gas->ISPV[L];J++) SVIB(L,gas->FVTMP[K],molecs->IPVIB[J][molecs->NM],J); } ELTI=gas->FVTMP[K]; if(gas->MELE > 1) SELE(L,ELTI,molecs->PELE[molecs->NM]); } } N=N+INC; } } } } // //WRITE (9,*) 'DMOM',DMOM //WRITE (9,*) 'DENG',DENG file_9<<"DMOM "<<DMOM<<endl; file_9<<"DENG "<<DENG<<endl; } // calc->NMI=molecs->NM; // //SPECIAL CODING FOR INITIATION OF COMBUSION IN H2-02 MIXTURE (FORCED IGNITION CASES in section 6.7) //set the vibrational levels of A% random molecules to 5 // A=0.05D00 // M=0.01D00*A*NM // DO N=1,M // CALL RANDOM_NUMBER(RANF) // K=INT(RANF*DFLOAT(NM))+1 // IPVIB(1,K)=5 // END DO // SAMPLE_FLOW(); OUTPUT_RESULTS(); calc->TOUT=calc->TOUT-calc->DTOUT; return; } void MOLECULES_ENTER_1D() { //molecules enter boundary at XB(1) and XB(2) and may be removed behind a wave //MOLECS molecs; //GAS gas; //CALC calc; //GEOM_1D geom; //OUTPUT output; // int K,L,M,N,NENT,II,J,JJ,KK,NTRY; double A,B,AA,BB,U,VN,XI,X,DX,DY,DZ; // //NENT number to enter in the time step // calc->ENTMASS=0.e00; // for(J=1;J<=2;J++){ //J is the end if((geom->ITYPE[J] == 0) || (geom->ITYPE[J] == 4)){ KK=1;//the entry surface will normally use the reference gas (main stream) properties if((J == 2) && (calc->ISECS == 1) && (geom->XB[2] > 0.e00)) KK=2; //KK is 1 for reference gas 2 for the secondary stream for(L=1;L<=gas->MSP;L++){ A=gas->ENTR[1][L][J]*calc->DTM+gas->ENTR[2][L][J]; if((geom->ITYPE[2] == 4) && (calc->ICN == 1)){ NENT=A; if(J == 1) calc->EME[L]=NENT; if(J == 2) { A=calc->ALOSS[L]-calc->EME[L]-calc->AJM[L]; calc->AJM[L]=0.e00; if(A < 0.e00){ calc->AJM[L]=-A; A=0.e00; } } } NENT=A; gas->ENTR[2][L][J]=A-NENT; if((geom->ITYPE[2] == 4) && (J == 2) && (calc->ICN == 1)) gas->ENTR[2][L][J]=0.e00; if(NENT > 0){ for(M=1;M<=NENT;M++){ if(molecs->NM >= molecs->MNM){ cout<< "EXTEND_MNM from MOLECULES_ENTER "<<endl; EXTEND_MNM(1.1); } molecs->NM=molecs->NM+1; AA=max(0.e00,gas->ENTR[3][L][J]-3.e00); BB=max(3.e00,gas->ENTR[3][L][J]+3.e00); II=0; while(II == 0){ calc->RANF=((double)rand()/(double)RAND_MAX); // CALL RANDOM_NUMBER(RANF) B=AA+(BB-AA)*calc->RANF; U=B-gas->ENTR[3][L][J]; A=(2.e00*B/gas->ENTR[4][L][J])*exp(gas->ENTR[5][L][J]-U*U); calc->RANF=((double)rand()/(double)RAND_MAX); // CALL RANDOM_NUMBER(RANF) if(A > calc->RANF) II=1; } molecs->PV[1][molecs->NM]=B*gas->VMP[L][KK]; if(J == 2) molecs->PV[1][molecs->NM]=-molecs->PV[1][molecs->NM]; // RVELC(molecs->PV[2][molecs->NM],molecs->PV[3][molecs->NM],gas->VMP[L][KK]); molecs->PV[2][molecs->NM]=molecs->PV[2][molecs->NM]+gas->VFY[J]; // if(gas->ISPR[1][L] > 0) SROT(L,gas->FTMP[KK],molecs->PROT[molecs->NM]); // if(gas->MMVM > 0){ for(K=1;K<=gas->ISPV[L];K++) SVIB(L,gas->FVTMP[KK],molecs->IPVIB[K][molecs->NM],K); } if(gas->MELE > 1) SELE(L,gas->FTMP[KK],molecs->PELE[molecs->NM]); // if(molecs->PELE[molecs->NM] > 0.e00) continue; //DEBUG // molecs->IPSP[molecs->NM]=L; //advance the molecule into the flow calc->RANF=((double)rand()/(double)RAND_MAX); // CALL RANDOM_NUMBER(RANF) XI=geom->XB[J]; DX=calc->DTM*calc->RANF*molecs->PV[1][molecs->NM]; if((geom->IFX == 0) || (J == 2)) X=XI+DX; if(J == 1){ //1-D move at outer boundary so molecule remains in flow if(geom->IFX > 0) DY=calc->DTM*calc->RANF*molecs->PV[2][molecs->NM]; DZ=0.e00; if(geom->IFX == 2) DZ=calc->DTM*calc->RANF*molecs->PV[3][molecs->NM]; if(geom->IFX > 0) AIFX(XI,DX,DY,DZ,X,molecs->PV[1][molecs->NM],molecs->PV[2][molecs->NM],molecs->PV[3][molecs->NM]); } molecs->PX[calc->NCLASS][molecs->NM]=X; molecs->PTIM[molecs->NM]=calc->FTIME; if(geom->IVB == 0) FIND_CELL_1D(molecs->PX[calc->NCLASS][molecs->NM],molecs->IPCELL[molecs->NM],JJ); if(geom->IVB == 1) FIND_CELL_MB_1D(molecs->PX[calc->NCLASS][molecs->NM],molecs->IPCELL[molecs->NM],JJ,molecs->PTIM[molecs->NM]); molecs->IPCP[molecs->NM]=0; if(geom->XREM > geom->XB[1]) calc->ENTMASS=calc->ENTMASS+gas->SP[5][L]; } } } if((geom->ITYPE[2] == 4) && (J==2) && (molecs->NM != calc->NMP) && (calc->ICN == 1)) continue; } } // //stagnation streamline molecule removal if(geom->XREM > geom->XB[1]){ calc->ENTMASS=geom->FREM*calc->ENTMASS; NTRY=0; calc->ENTMASS=calc->ENTMASS+calc->ENTREM; while((calc->ENTMASS > 0.e00) && (NTRY < 10000)){ NTRY=NTRY+1; if(NTRY == 10000){ cout<<"Unable to find molecule for removal"<<endl; calc->ENTMASS=0.e00; //memset(calc->VNMAX,0.e00,sizeof(*calc->VNMAX));//calc->VNMAX=0.e00; for(int i=0;i<gas->MSP+1;i++) calc->VNMAX[i]=0.e00; } calc->RANF=((double)rand()/(double)RAND_MAX); // CALL RANDOM_NUMBER(RANF) N=molecs->NM*calc->RANF+0.9999999e00; if(molecs->PX[calc->NCLASS][N] > geom->XREM){ // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); //IF (RANF < ((PX(N)-XREM)/(XB(2)-XREM))**2) THEN if(fabs(gas->VFY[1]) < 1.e-3) VN=sqrt(molecs->PV[2][N]*molecs->PV[2][N]+molecs->PV[3][N]*molecs->PV[3][N]); //AXIALLY SYMMETRIC STREAMLINE else VN=fabs(molecs->PV[3][N]); //TWO-DIMENSIONAL STREAMLINE L=molecs->IPSP[N]; if(VN > calc->VNMAX[L]) calc->VNMAX[L]=VN; // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); if(calc->RANF < VN/calc->VNMAX[L]){ REMOVE_MOL(N); calc->ENTMASS=calc->ENTMASS-gas->SP[5][L]; NTRY=0; } //END IF } } calc->ENTREM=calc->ENTMASS; } } void FIND_CELL_1D(double &X,int &NCC,int &NSC) { //find the collision and sampling cells at a givem location in a 0D or 1D case //MOLECS molecs; //GEOM_1D geom; //CALC calc; int N,L,M,ND; double FRAC,DSC; // //NCC collision cell number //NSC sampling cell number //X location //ND division number //DSC the ratio of the sub-division width to the division width // ND=(X-geom->XB[1])/geom->DDIV+0.99999999999999e00; // if(geom->JDIV[0][ND] < 0){ //the division is a level 0 (no sub-division) sampling cell NSC=-geom->JDIV[0][ND]; // IF (IFX == 0) NCC=geom->NCIS*(X-geom->CELL[2][NSC])/(geom->CELL[3][NSC]-geom->CELL[2][NSC])+0.9999999999999999e00; NCC=NCC+geom->ICELL[NSC]; // IF (NCC == 0) NCC=1 return; } else{ //the molecule is in a subdivided division FRAC=(X-geom->XB[1])/geom->DDIV-double(ND-1); M=ND; for(N=1;N<=geom->ILEVEL;N++){ DSC=1.e00/double(N+1); for(L=1;L<=2;L++){ //over the two level 1 subdivisions if(((L == 1) && (FRAC < DSC)) || ((L == 2) || (FRAC >= DSC))){ M=geom->JDIV[N-1][M]+L; //the address in JDIV if(geom->JDIV[N][M] < 0){ NSC=-geom->JDIV[N][M]; NCC=geom->NCIS*(X-geom->CELL[2][NSC])/(geom->CELL[3][NSC]-geom->CELL[2][NSC])+0.999999999999999e00; if(NCC == 0) NCC=1; NCC=NCC+geom->ICELL[NSC]; return; } } } FRAC=FRAC-DSC; } } file_9<<"No cell for molecule at x= "<<X<<endl; return ; } void FIND_CELL_MB_1D(double &X,int &NCC,int &NSC,double &TIM) { //find the collision and sampling cells at a givem location in a 0D or 1D case //when there is a moving boundary //MOLECS molecs; //GEOM_1D geom; //CALC calc; // // IMPLICIT NONE // int N,L,M,ND; double FRAC,DSC,A,B,C; // //NCC collision cell number //NSC sampling cell number //X location //ND division number //DSC the ratio of the sub-division width to the division width //TIM the time // A=(geom->XB[2]+geom->VELOB*TIM-geom->XB[1])/double(geom->NDIV); //new DDIV ND=(X-geom->XB[1])/A+0.99999999999999e00; B=geom->XB[1]+double(ND-1)*A; // //the division is a level 0 sampling cell NSC=-geom->JDIV[0][ND]; NCC=geom->NCIS*(X-B)/A+0.99999999999999e00; NCC=NCC+geom->ICELL[NSC]; //WRITE (9,*) 'No cell for molecule at x=',X file_9<< "No cell for molecule at x= "<<X<<endl; return; //return ; // } void RVELC(double &U,double &V,double &VMP) { //CALC calc; //generates two random velocity components U and V in an equilibrium //gas with most probable speed VMP //based on equations (4.4) and (4.5) double A,B; // // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); A=sqrt(-log(calc->RANF)); // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); B=DPI*calc->RANF; U=A*sin(B)*VMP; V=A*cos(B)*VMP; return; } void SROT(int &L,double &TEMP,double &ROTE) { //sets a typical rotational energy ROTE of species L //CALC calc; //GAS gas; // // IMPLICIT NONE // int I; double A,B,ERM; // if(gas->ISPR[1][L] == 2){ // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); ROTE=-log(calc->RANF)*BOLTZ*TEMP; //equation (4.8) } else{ A=0.5e00*gas->ISPR[1][L]-1.e00; I=0; while(I == 0){ // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); ERM=calc->RANF*10.e00; //there is an energy cut-off at 10 kT B=(pow((ERM/A),A))*exp(A-ERM); //equation (4.9) // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); if(B > calc->RANF) I=1; } ROTE=ERM*BOLTZ*TEMP; } return; } void SVIB(int &L,double &TEMP,int &IVIB, int &K) { //sets a typical vibrational state at temp. TEMP of mode K of species L //GAS gas; //CALC calc; // // IMPLICIT NONE // int N; // double TEMP; // int IVIB; // // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); N=-log(calc->RANF)*TEMP/gas->SPVM[1][K][L]; //eqn(4.10) //the state is truncated to an integer IVIB=N; } void SELE(int &L,double &TEMP, double &ELE) { //sets a typical electronic energy at temp. TEMP of species L //employs direct sampling from the Boltzmann distribution //GAS gas; //CALC calc; // // IMPLICIT NONE // int K,N; double EPF,A,B; double CTP[20]; // //ELE electronic energy of a molecule //EPF electronic partition function //CTP(N) contribution of electronic level N to the electronic partition function // if(TEMP > 0.1){ EPF=0.e00; for(N=1;N<=gas->NELL[L];N++) EPF=EPF+gas->QELC[1][N][L]*exp(-gas->QELC[2][N][L]/TEMP) ; // // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); // A=0.0; K=0; //becomes 1 when the energy is set N=0; //level while(K == 0){ N=N+1; A=A+gas->QELC[1][N][L]*exp(-gas->QELC[2][N][L]/TEMP); B=A/EPF; if(calc->RANF < B){ K=1; ELE=BOLTZ*gas->QELC[2][N][L]; } } } else ELE=0.e00; // } void CQAX(double &A,double &X,double &GAX) { //calculates the function Q(a,x)=Gamma(a,x)/Gamma(a) // // IMPLICIT NONE double G,DT,T,PV,V; int NSTEP,N; // G=tgamma(A); // if(X < 10.e00){ //direct integration NSTEP=100000; DT=X/double(NSTEP); GAX=0.e00; PV=0.e00; for(N=1;N<=NSTEP;N++){ T=double(N)*DT; V=exp(-T)*pow(T,(A-1)); GAX=GAX+(PV+V)*DT/2.e00; PV=V; } GAX=1.e00-GAX/G; } else{ //asymptotic formula GAX=pow(X,(A-1.e00))*exp(-X)*(1.0+(A-1.e00)/X+(A-1.e00)*(A-2.e00)/pow(X,2)+(A-1.e00)*(A-2.e00)*(A-3.e00)/pow(X,3)+(A-1.e00)*(A-2.e00)*(A-3.e00)*(A-4.e00)/pow(X,4)); GAX=GAX/G; } // return; } //***************************************************************************** // void LBS(double XMA,double XMB,double &ERM) { //selects a Larsen-Borgnakke energy ratio using eqn (11.9) // double PROB,RANF; int I,N; // //I is an indicator //PROB is a probability //ERM ratio of rotational to collision energy //XMA degrees of freedom under selection-1 //XMB remaining degrees of freedom-1 // I=0; while(I == 0){ // CALL RANDOM_NUMBER(RANF) RANF=((double)rand()/(double)RAND_MAX); ERM=RANF; if((XMA < 1.e-6) || (XMB < 1.e-6)){ // IF (XMA < 1.E-6.AND.XMB < 1.E-6) RETURN //above can never occur if one mode is translational if(XMA < 1.e-6) PROB=pow((1.e00-ERM),XMB); if(XMB < 1.e-6) PROB=pow((1.e00-ERM),XMA); } else PROB=pow(((XMA+XMB)*ERM/XMA),XMA)*pow(((XMA+XMB)*(1.e00-ERM)/XMB),XMB); // CALL RANDOM_NUMBER(RANF) RANF=((double)rand()/(double)RAND_MAX); if(PROB > RANF) I=1; } // return; } void REFLECT_1D(int &N,int J,double &X) { //reflects molecule N and samples the surface J properties //MOLECS molecs; //GAS gas; //GEOM_1D geom; //CALC calc; //OUTPUT output; // // IMPLICIT NONE // int L,K,M; double A,B,VMPS,DTR,XI,DX,DY,DZ,WF; // //VMPS most probable velocity at the surface temperature //DTR time remaining after molecule hits a surface // L=molecs->IPSP[N]; WF=1.e00; if(geom->IWF == 1) WF=1.e00+geom->WFM*pow(X,geom->IFX); output->CSS[0][J][L][1]=output->CSS[0][J][L][1]+1.e00; output->CSS[1][J][L][1]=output->CSS[1][J][L][1]+WF; output->CSS[2][J][L][1]=output->CSS[2][J][L][1]+WF*molecs->PV[1][N]*gas->SP[5][L]; output->CSS[3][J][L][1]=output->CSS[3][J][L][1]+WF*(molecs->PV[2][N]-gas->VSURF[J])*gas->SP[5][L]; output->CSS[4][J][L][1]=output->CSS[4][J][L][1]+WF*molecs->PV[3][N]*gas->SP[5][L]; A=pow(molecs->PV[1][N],2)+pow((molecs->PV[2][N]-gas->VSURF[J]),2)+pow(molecs->PV[3][N],2); output->CSS[5][J][L][1]=output->CSS[5][J][L][1]+WF*0.5e00*gas->SP[5][L]*A; if(gas->ISPR[1][L] > 0) output->CSS[6][J][L][1]=output->CSS[6][J][L][1]+WF*molecs->PROT[N]; if(gas->MELE > 1) output->CSS[8][J][L][1]=output->CSS[8][J][L][1]+WF*molecs->PELE[N]; if(gas->MMVM > 0){ if(gas->ISPV[L] > 0){ for(K=1;K<=gas->ISPV[L];K++) output->CSS[7][J][L][1]=output->CSS[7][J][L][1]+WF*double(molecs->IPVIB[K][N])*BOLTZ*gas->SPVM[1][K][L]; } } A=pow(molecs->PV[1][N],2)+pow(molecs->PV[2][N],2)+pow(molecs->PV[3][N],2); B=fabs(molecs->PV[1][N]); output->CSSS[1][J]=output->CSSS[1][J]+WF/B; output->CSSS[2][J]=output->CSSS[2][J]+WF*gas->SP[5][L]/B; output->CSSS[3][J]=output->CSSS[3][J]+WF*gas->SP[5][L]*molecs->PV[2][N]/B; //this assumes that any flow normal to the x direction is in the y direction output->CSSS[4][J]=output->CSSS[4][J]+WF*gas->SP[5][L]*A/B; if(gas->ISPR[1][L] > 0){ output->CSSS[5][J]=output->CSSS[5][J]+WF*molecs->PROT[N]/B; output->CSSS[6][J]=output->CSSS[6][J]+WF*gas->ISPR[1][L]/B; } // // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); if(gas->FSPEC[J] > calc->RANF){ //specular reflection X=2.e00*geom->XB[J]-X; molecs->PV[1][N]=-molecs->PV[1][N]; DTR=(X-geom->XB[J])/molecs->PV[1][N]; } else{ //diffuse reflection VMPS=sqrt(2.e00*BOLTZ*gas->TSURF[J]/gas->SP[5][L]); DTR=(geom->XB[J]-molecs->PX[1][N])/molecs->PV[1][N]; // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); molecs->PV[1][N]=sqrt(-log(calc->RANF))*VMPS; if(J == 2) molecs->PV[1][N]=-molecs->PV[1][N]; RVELC(molecs->PV[2][N],molecs->PV[3][N],VMPS); molecs->PV[2][N]=molecs->PV[2][N]+gas->VSURF[J]; if(gas->ISPR[1][L] > 0) SROT(L,gas->TSURF[J],molecs->PROT[N]); if(gas->MMVM > 0){ for(K=1;K<=gas->ISPV[L];K++) SVIB(L,gas->TSURF[J],molecs->IPVIB[K][N],K); } if(gas->MELE > 1) SELE(L,gas->TSURF[J],molecs->PELE[N]); } // output->CSS[2][J][L][2]=output->CSS[2][J][L][2]-WF*molecs->PV[1][N]*gas->SP[5][L]; output->CSS[3][J][L][2]=output->CSS[3][J][L][2]-WF*(molecs->PV[2][N]-gas->VSURF[J])*gas->SP[5][L]; output->CSS[4][J][L][2]=output->CSS[4][J][L][2]-WF*molecs->PV[3][N]*gas->SP[5][L]; A=pow(molecs->PV[1][N],2)+pow((molecs->PV[2][N]-gas->VSURF[J]),2)+pow(molecs->PV[3][N],2); output->CSS[5][J][L][2]=output->CSS[5][J][L][2]-WF*0.5e00*gas->SP[5][L]*A; if(gas->ISPR[1][L] > 0) output->CSS[6][J][L][2]=output->CSS[6][J][L][2]-WF*molecs->PROT[N]; if(gas->MELE > 1) output->CSS[8][J][L][2]=output->CSS[8][J][L][2]-WF*molecs->PELE[N]; if(gas->MMVM > 0){ if(gas->ISPV[L] > 0){ for(K=1;K<=gas->ISPV[L];K++) output->CSS[7][J][L][2]=output->CSS[7][J][L][2]-WF*double(molecs->IPVIB[K][N])*BOLTZ*gas->SPVM[1][K][L]; } } A=pow(molecs->PV[1][N],2)+pow(molecs->PV[2][N],2)+pow(molecs->PV[3][N],2); B=fabs(molecs->PV[1][N]); output->CSSS[1][J]=output->CSSS[1][J]+WF/B; output->CSSS[2][J]=output->CSSS[2][J]+WF*gas->SP[5][L]/B; output->CSSS[3][J]=output->CSSS[3][J]+WF*gas->SP[5][L]*molecs->PV[2][N]/B; //this assumes that any flow normal to the x direction is in the y direction output->CSSS[4][J]=output->CSSS[4][J]+WF*gas->SP[5][L]*A/B; if(gas->ISPR[1][L] > 0){ output->CSSS[5][J]=WF*output->CSSS[5][J]+molecs->PROT[N]/B; output->CSSS[6][J]=output->CSSS[6][J]+WF*gas->ISPR[1][L]/B; } // XI=geom->XB[J]; DX=DTR*molecs->PV[1][N]; DZ=0.e00; if(geom->IFX > 0) DY=DTR*molecs->PV[2][N]; if(geom->IFX == 2) DZ=DTR*molecs->PV[3][N]; if(geom->IFX == 0) X=XI+DX; if(geom->IFX > 0) AIFX(XI,DX,DY,DZ,X,molecs->PV[1][N],molecs->PV[2][N],molecs->PV[3][N]); // return; } void RBC(double &XI, double &DX, double &DY,double &DZ, double &R,double &S) { //calculates the trajectory fraction S from a point at radius XI with //note that the axis is in the y direction //--displacements DX, DY, and DZ to a possible intersection with a //--surface of radius R, IFX=1, 2 for cylindrical, spherical geometry //MOLECS molecs; //GAS gas; //GEOM_1D geom; //CALC calc; //OUTPUT output; // // IMPLICIT NONE // double A,B,C,DD,S1,S2; // DD=DX*DX+DZ*DZ; if(geom->IFX == 2) DD=DD+DY*DY; B=XI*DX/DD; C=(XI*XI-R*R)/DD; A=B*B-C; if(A >= 0.e00){ //find the least positive solution to the quadratic A=sqrt(A); S1=-B+A; S2=-B-A; if(S2 < 0.e00){ if(S1 > 0.e00) S=S1; else S=2.e00; } else if(S1 < S2) S=S1; else S=S2; } else S=2.e00; //setting S to 2 indicates that there is no intersection return; // } void AIFX(double &XI,double &DX, double &DY, double &DZ, double &X, double &U, double &V, double &W) { // //calculates the new radius and realigns the velocity components in //--cylindrical and spherical flows //MOLECS molecs; //GAS gas; //GEOM_1D geom; //CALC calc; //OUTPUT output; // // IMPLICIT NONE // //INTEGER :: double A,B,C,DR,VR,S; // if(geom->IFX == 1){ DR=DZ; VR=W; } else if(geom->IFX == 2){ DR=sqrt(DY*DY+DZ*DZ); VR=sqrt(V*V+W*W); } A=XI+DX; X=sqrt(A*A+DR*DR); S=DR/X; C=A/X; B=U; U=B*C+VR*S; W=-B*S+VR*C; if(geom->IFX == 2){ VR=W; // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); A=DPI*calc->RANF; V=VR*sin(A); W=VR*cos(A); } // return; // } void REMOVE_MOL(int &N) { //remove molecule N and replaces it by NM //MOLECS molecs; //CALC calc; //GEOM_1D geom; //GAS gas; // IMPLICIT NONE // int NC,M,K; //N the molecule number //M,K working integer // if(N != molecs->NM){ for(M=1;M<=calc->NCLASS;M++) molecs->PX[M][N]=molecs->PX[M][molecs->NM]; for(M=1;M<=3;M++) molecs->PV[M][N]=molecs->PV[M][molecs->NM]; if(gas->MMRM > 0) molecs->PROT[N]=molecs->PROT[molecs->NM]; molecs->IPCELL[N]=fabs(molecs->IPCELL[molecs->NM]); molecs->IPSP[N]=molecs->IPSP[molecs->NM]; molecs->IPCP[N]=molecs->IPCP[molecs->NM]; if(gas->MMVM > 0){ for(M=1;M<=gas->MMVM;M++) molecs->IPVIB[M][N]=molecs->IPVIB[M][molecs->NM]; } if(gas->MELE > 1) molecs->PELE[N]=molecs->PELE[molecs->NM]; molecs->PTIM[N]=molecs->PTIM[molecs->NM]; } molecs->NM=molecs->NM-1; // return; // } void INDEX_MOLS() { //index the molecules to the collision cells //MOLECS molecs; //CALC calc; //GEOM_1D geom; // IMPLICIT NONE // int N,M,K; // //N,M,K working integer // for(N=1;N<=geom->NCCELLS;N++) geom->ICCELL[2][N]=0; // if(molecs->NM != 0){ for(N=1;N<=molecs->NM;N++){ M=molecs->IPCELL[N]; geom->ICCELL[2][M]=geom->ICCELL[2][M]+1; } // M=0; for(N=1;N<=geom->NCCELLS;N++){ geom->ICCELL[1][N]=M; M=M+geom->ICCELL[2][N]; geom->ICCELL[2][N]=0; } // for(N=1;N<=molecs->NM;N++){ M=molecs->IPCELL[N]; geom->ICCELL[2][M]=geom->ICCELL[2][M]+1; K=geom->ICCELL[1][M]+geom->ICCELL[2][M]; molecs->ICREF[K]=N; } //cin.get(); // } return; } void SAMPLE_FLOW() { //sample the flow properties //MOLECS molecs; //CALC calc; //GEOM_1D geom; //GAS gas; //OUTPUT output; // // IMPLICIT NONE // int NC,NCC,LS,N,M,K,L,I,KV; double A,TE,TT,WF; // //NC the sampling cell number //NCC the collision cell number //LS the species code //N,M,K working integers //TE total translational energy // output->NSAMP=output->NSAMP+1; cout<<"Sample \t"<<output->NSAMP<<endl<<endl; //WRITE (9,*) NM,'Mols. at sample',NSAMP file_9<<molecs->NM<<" Mols. at sample "<<output->NSAMP<<endl; // for(N=1;N<=molecs->NM;N++){ NCC=molecs->IPCELL[N]; NC=geom->ICCELL[3][NCC]; WF=1.e00; if(geom->IWF == 1) WF=1.e00+geom->WFM*pow(molecs->PX[1][N],geom->IFX); if((NC > 0) && (NC <= geom->NCELLS)){ if(gas->MSP > 1) LS=fabs(molecs->IPSP[N]); else LS=1; output->CS[0][NC][LS]=output->CS[0][NC][LS]+1.e00; output->CS[1][NC][LS]=output->CS[1][NC][LS]+WF; for(M=1;M<=3;M++){ output->CS[M+1][NC][LS]=output->CS[M+1][NC][LS]+WF*molecs->PV[M][N]; output->CS[M+4][NC][LS]=output->CS[M+4][NC][LS]+WF*pow(molecs->PV[M][N],2); } if(gas->MMRM > 0) output->CS[8][NC][LS]=output->CS[8][NC][LS]+WF*molecs->PROT[N]; if(gas->MELE > 1) output->CS[9][NC][LS]=output->CS[9][NC][LS]+WF*molecs->PELE[N]; if(gas->MMVM > 0){ if(gas->ISPV[LS] > 0){ for(K=1;K<=gas->ISPV[LS];K++) output->CS[K+9][NC][LS]=output->CS[K+9][NC][LS]+WF*double(molecs->IPVIB[K][N]); } } } else{ cout<<"Illegal sampling cell "<<NC<<" "<<NCC<<" for MOL "<<N<<" at "<<molecs->PX[1][N]<<endl; return; } } // if(calc->FTIME > 0.5e00*calc->DTM) calc->TSAMP=calc->TSAMP+calc->DTSAMP; // return; } void ADAPT_CELLS_1D() { //adapt the sampling cells through the splitting of the divisions into successive levels //the collision cells are divisions of the sampling cells //MOLECS molecs; //GAS gas; //GEOM_1D geom; //CALC calc; //OUTPUT output; // // IMPLICIT NONE // int M,N,L,K,KK,I,J,JJ,MSEG,NSEG,NSEG1,NSEG2,MLEVEL; double A,B,DDE,DCRIT; int *KDIV,*NC; int **ISD; double *XMIN,*XMAX,*DRAT; // INTEGER, ALLOCATABLE, DIMENSION(:) :: KDIV,NC // INTEGER, ALLOCATABLE, DIMENSION(:,:) :: ISD // REAL(KIND=8), ALLOCATABLE, DIMENSION(:) :: XMIN,XMAX,DRAT // //DCRIT the number density ratio that causes a cell to be subdivided //KDIV(N) the number of divisions/subdivisions (cells or further subdivisions) at level N //DRAT(N) the contriburion to the density ratio of element N //NC(I) the number of sampling cells at level I //DDE the width of an element //MSEG the maximum number of segments (a segment is the size of the smallest subdivision //NSEG1 the (first segment-1) in the subdivision //NSEG2 the final segment in the subdivision //ISD(N,M) 0,1 for cell,subdivided for level N subdivision //MLEVEL The maximum desired level ILEVEL of subdivision (cellS are proportional to 2**ILEVEL) // DCRIT=1.5e00; //may be altered MLEVEL=2; //may be altered // //determine the level to which the divisions are to be subdivided // A=1.e00; for(N=1;N<=geom->NCELLS;N++) if(output->VAR[3][N]/gas->FND[1] > A) A=output->VAR[3][N]/gas->FND[1]; geom->ILEVEL=0; while(A > DCRIT){ geom->ILEVEL=geom->ILEVEL+1; A=A/2.e00; } if(geom->ILEVEL > MLEVEL) geom->ILEVEL=MLEVEL; //WRITE (9,*) 'ILEVEL =',ILEVEL file_9<<"ILEVEL = "<<geom->ILEVEL<<endl; NSEG=pow(2,geom->ILEVEL); MSEG=geom->NDIV*NSEG; // KDIV = new int[geom->ILEVEL+1]; DRAT = new double[MSEG+1]; NC = new int[geom->ILEVEL+1]; ISD = new int*[geom->ILEVEL+1]; for(int i =0; i< (geom->ILEVEL+1); ++i) ISD[i] = new int[MSEG+1]; // ALLOCATE (KDIV(0:ILEVEL),DRAT(MSEG),NC(0:ILEVEL),ISD(0:ILEVEL,MSEG),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR KDIV ARRAY',ERROR // ENDIF // DDE=(geom->XB[2]-geom->XB[1])/double(MSEG); for(N=1;N<=MSEG;N++){ A=geom->XB[1]+(double(N)-0.5e00)*DDE; FIND_CELL_1D(A,M,L); DRAT[N]=output->VAR[3][L]/(gas->FND[1]*double(NSEG)); } // //calculate the number of subdivisions at the various levels of subdivision KDIV=0; //also the number of sampling cells at each level NC=0; // for(N=1;N<=geom->NDIV;N++){ //divisions ISD=0; ISD[0][1]=1; KDIV[0]=KDIV[0]+1; // WRITE (9,*) 'DIVISION',N for(I=0;I<=geom->ILEVEL;I++){ //level of subdivision // WRITE (9,*) 'LEVEL',I J=pow(2,I); //number of possible subdivisions at this level JJ=NSEG/J; //number of segments in a subdivision for(M=1;M<=J;M++){ // WRITE (9,*) 'SUBDIVISION',M if(ISD[I][M] == 1){ NSEG1=(N-1)*NSEG+(M-1)*JJ+1; NSEG2=NSEG1+JJ-1; A=0.e00; // WRITE (9,*) 'NSEG RANGE',NSEG1,NSEG2 for(L=NSEG1;L<=NSEG2;L++) A=A+DRAT[L]; // WRITE (9,*) 'DENS CONTRIB',A if(A < DCRIT){ NC[I]=NC[I]+1; // WRITE (9,*) 'LEVEL',I,' CELLS TO', NC(I) } else{ KDIV[I+1]=KDIV[I+1]+2; // WRITE (9,*) 'LEVEL',I+1,' SUBDIVISIONS TO',KDIV(I+1) for(L=NSEG1-(N-1)*NSEG;L<=NSEG2-(N-1)*NSEG;L++) ISD[I+1][L]=1; } } } } } // //WRITE (9,*) 'KDIV',KDIV file_9<<"KDIV "<<KDIV<<endl; // //WRITE (9,*) 'NC',NC file_9<< "NC "<<NC<<endl; cin.get(); //WRITE (9,*) 'Number of divisions',NDIV file_9<<"Number of divisions "<<geom->NDIV<<endl; A=0; geom->NCELLS=0; for(N=0;N<=geom->ILEVEL;N++){ A=A+double(NC[N])/(pow(2.e00,N)); geom->NCELLS=geom->NCELLS+NC[N]; } //WRITE (9,*) 'Total divisions from sampling cells',A //WRITE (9,*) 'Adapted sampling cells',NCELLS file_9<< "Total divisions from sampling cells "<<A<<endl; file_9<< "Adapted sampling cells "<<geom->NCELLS<<endl; geom->NCCELLS=geom->NCELLS*geom->NCIS; //WRITE (9,*) 'Adapted collision cells',NCCELLS file_9<< "Adapted collision cells "<<geom->NCCELLS<<endl; // for (int i = 0; i < geom->ILEVEL+1; i++) { cudaFree(geom->JDIV[i]); //delete [] geom->JDIV[i]; } cudaFree(geom->JDIV); //delete [] geom->JDIV; // <- because they won't exist anymore after this for (int i = 0; i < 5; i++) { cudaFree(geom->CELL[i]); //delete [] geom->CELL[i]; } cudaFree(geom->CELL); //delete [] geom->CELL; // <- because they won't exist anymore after this cudaFree(geom->ICELL); //delete[] geom->ICELL; for (int i = 0; i < 6; i++) { cudaFree(geom->CCELL[i]); //delete [] geom->CCELL[i]; } cudaFree(geom->CCELL); //delete [] geom->CCELL; // <- because they won't exist anymore after this for (int i = 0; i < 4; i++) { cudaFree(geom->ICCELL[i]); //delete [] geom->ICCELL[i]; } cudaFree(geom->ICCELL); //delete [] geom->ICCELL; // <- because they won't exist anymore after this cudaFree(output->COLLS); //delete[] output->COLLS; cudaFree(output->WCOLLS); //delete[] output->WCOLLS; cudaFree(output->CLSEP); //delete[] output->CLSEP; for (int i = 0; i < 24; i++) { cudaFree(output->VAR[i]); //delete [] output->VAR[i]; } cudaFree(output->VAR); //delete [] output->VAR; // <- because they won't exist anymore after this for(int i = 0; i < 13; i++) { for(int j = 0; j < geom->NCELLS+1; j++) { cudaFree(output->VARSP[i][j]); //delete [] output->VARSP[i][j]; } cudaFree(output->VARSP[i]); //delete [] output->VARSP[i]; } cudaFree(output->VARSP); //delete [] output->VARSP; for(int i = 0; i < (10+gas->MSP); i++) { for(int j = 0; j < geom->NCELLS+1; j++) { cudaFree(output->CS[i][j]); //delete [] output->CS[i][j]; } cudaFree(output->CS[i]); //delete [] output->CS[i]; } cudaFree(output->CS); //delete [] output->CS; /*DEALLOCATE (JDIV,CELL,ICELL,CCELL,ICCELL,COLLS,WCOLLS,CLSEP,VAR,VARSP,CS,STAT=ERROR) IF (ERROR /= 0) THEN WRITE (*,*)'PROGRAM COULD NOT DEALLOCATE ARRAYS IN ADAPT',ERROR END IF*/ // for(N=0;N<=geom->ILEVEL;N++) if(KDIV[N] > geom->MDIV) geom->MDIV=KDIV[N]; // geom->i_allocate(geom->ILEVEL+1,geom->MDIV, geom->JDIV); // ALLOCATE (JDIV(0:ILEVEL,MDIV),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR JDIV ARRAY IN ADAPT',ERROR // ENDIF // geom->d_allocate(5,geom->NCELLS+1, geom->CELL); geom->i_allocate(geom->NCELLS+1, geom->ICELL); geom->d_allocate(6, geom->NCCELLS+1, geom->CCELL); geom->i_allocate(4, geom->NCCELLS+1,geom->ICCELL); XMIN= new double[geom->NCCELLS+1]; XMAX = new double[geom->NCCELLS+1]; // // ALLOCATE (CELL(4,NCELLS),ICELL(NCELLS),CCELL(5,NCCELLS),ICCELL(3,NCCELLS),XMIN(NCCELLS),XMAX(NCCELLS),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR CELL ARRAYS IN ADAPT',ERROR // ENDIF // output->d_allocate(geom->NCELLS+1,output->COLLS); output->d_allocate(geom->NCELLS+1, output->WCOLLS); output->d_allocate(geom->NCELLS+1, output->CLSEP); output->d_allocate(24, geom->NCELLS+1, output->VAR); output->d_allocate(13,geom->NCELLS+1,gas->MSP+1, output->VARSP); output->d_allocate(10+gas->MSP+1,geom->NCELLS+1,gas->MSP+1,output->CS); // ALLOCATE (COLLS(NCELLS),WCOLLS(NCELLS),CLSEP(NCELLS),VAR(23,NCELLS),VARSP(0:12,NCELLS,MSP),CS(0:9+MSP,NCELLS,MSP),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR SAMPLING ARRAYS IN ADAPT',ERROR // ENDIF // geom->NCCELLS=0; geom->NCELLS=0; // //set the JDIV arrays and the sampling cells at the various levels of subdivision KDIV=0; geom->JDIV=0; // for(N=1;N<=geom->NDIV;N++){ //divisions ISD=0; ISD[0][1]=1; KDIV[0]=KDIV[0]+1; for(I=0;I<=geom->ILEVEL;I++){ //level of subdivision J=pow(2,I); //number of possible subdivisions at this level JJ=NSEG/J; //number of segments in a subdivision for(M=1;M<=J;M++){ if(ISD[I][M] == 1){ NSEG1=(N-1)*NSEG+(M-1)*JJ+1; NSEG2=NSEG1+JJ-1; A=0.e00; for(L=NSEG1;L<=NSEG2;L++) A=A+DRAT[L]; if(A < DCRIT){ geom->NCELLS=geom->NCELLS+1; output->VAR[11][geom->NCELLS]=gas->FTMP[1]; XMIN[geom->NCELLS]=geom->XB[1]+double(NSEG1-1)*DDE; XMAX[geom->NCELLS]=XMIN[geom->NCELLS]+double(NSEG2-NSEG1+1)*DDE; //WRITE (9,*) NCELLS,I,' XMIN,XMAX',XMIN(NCELLS),XMAX(NCELLS) file_9<< geom->NCELLS<<" "<<I<<" XMIN,XMAX "<<XMIN[geom->NCELLS]<<" , "<<XMAX[geom->NCELLS]<<endl; geom->JDIV[I][KDIV[I]-(J-M)]=-geom->NCELLS; // WRITE (9,*) 'JDIV(',I,',',KDIV(I)-(J-M),')=',-NCELLS } else{ geom->JDIV[I][KDIV[I]-(J-M)]=KDIV[I+1]; // WRITE (9,*) 'JDIV(',I,',',KDIV(I)-(J-M),')=',KDIV(I+1) KDIV[I+1]=KDIV[I+1]+2; for(L=NSEG1-(N-1)*NSEG;L<=NSEG2-(N-1)*NSEG;L++) ISD[I+1][L]=1; } } } } } // //set the other quantities associated with the sampling cells and the collision cells // geom->NCCELLS=0; for(N=1;N<=geom->NCELLS;N++){ geom->CELL[1][N]=(XMIN[N]+XMAX[N])/2.e00; geom->CELL[2][N]=XMIN[N]; geom->CELL[3][N]=XMAX[N]; if(geom->IFX == 0) geom->CELL[4][N]=XMAX[N]-XMIN[N]; //calculation assumes unit cross-section if(geom->IFX == 1) geom->CELL[4][N]=PI*(pow(XMAX[N],2)-pow(XMIN[N],2)); if(geom->IFX == 2) geom->CELL[4][N]=1.33333333333333333333e00*PI*(pow(XMAX[N],3)-pow(XMIN[N],3)); geom->ICELL[N]=geom->NCCELLS; for(M=1;M<=geom->NCIS;M++){ geom->NCCELLS=geom->NCCELLS+1; geom->ICCELL[3][geom->NCCELLS]=N; geom->CCELL[1][geom->NCCELLS]=geom->CELL[4][N]/double(geom->NCIS); geom->CCELL[3][geom->NCCELLS]=calc->DTM/2.e00; geom->CCELL[4][geom->NCCELLS]=2.e00*gas->VMPM*gas->SPM[2][1][1]; // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); geom->CCELL[2][geom->NCCELLS]=calc->RANF; geom->CCELL[5][geom->NCCELLS]=calc->FTIME; } } // //assign the molecules to the cells // for(N=1;N<=molecs->NM;N++){ FIND_CELL_1D(molecs->PX[1][N],molecs->IPCELL[N],JJ); M=molecs->IPCELL[N]; } // //deallocate the local variables for (int i = 0; i < geom->ILEVEL+1; i++) { delete [] ISD[i]; } delete [] ISD; delete [] NC; delete[] KDIV; delete [] XMAX; delete [] XMIN; delete [] DRAT; /*DEALLOCATE (KDIV,NC,ISD,XMIN,XMAX,DRAT,STAT=ERROR) IF (ERROR /= 0) THEN WRITE (*,*)'PROGRAM COULD NOT DEALLOCATE LOCAL ARRAYS IN ADAPT',ERROR END IF*/ // return; } void EXTEND_MNM(double FAC) { // //the maximum number of molecules is increased by a specified factor //the existing molecules are copied TO disk storage //MOLECS molecs; //CALC calc; //GAS gas; // // IMPLICIT NONE // int M,N,MNMN; fstream file_7; // REAL :: FAC // //M,N working integers //MNMN extended value of MNM //FAC the factor for the extension MNMN=FAC*molecs->MNM; cout<< "Maximum number of molecules is to be extended from "<<molecs->MNM<<" to "<<MNMN<<endl; cout<< "( if the additional memory is available //// )"<<endl; file_7.open("EXTMOLS.SCR", ios::binary | ios::out); if(file_7.is_open()){ cout<<"EXTMOLS.SCR is opened"<<endl; } else{ cout<<"EXTMOLS.SCR not opened"<<endl; } cout<<"Start write to disk storage"<<endl; //OPEN (7,FILE='EXTMOLS.SCR',FORM='BINARY') //WRITE (*,*) 'Start write to disk storage' for(N=1;N<=molecs->MNM;N++){ if(gas->MMVM > 0){ file_7<<molecs->PX[calc->NCLASS][N]<<endl<<molecs->PTIM[N]<<endl<<molecs->PROT[N]<<endl; for(M=1;M<=3;M++) file_7<<molecs->PV[M][N]<<endl; file_7<<molecs->IPSP[N]<<endl<<molecs->IPCELL[N]<<endl<<molecs->ICREF[N]<<endl<<molecs->IPCP[N]<<endl; for(M=1;M<=gas->MMVM;M++) file_7<<molecs->IPVIB[M][N]<<endl; file_7<<molecs->PELE[N]<<endl;//WRITE (7) PX(NCLASS,N),PTIM(N),PROT(N),(PV(M,N),M=1,3),IPSP(N),IPCELL(N),ICREF(N),IPCP(N),(IPVIB(M,N),M=1,MMVM),PELE(N) } else{ if(gas->MMRM > 0){ file_7<<molecs->PX[calc->NCLASS][N]<<endl<<molecs->PTIM[N]<<endl<<molecs->PROT[N]<<endl; for(M=1;M<=3;M++) file_7<<molecs->PV[M][N]<<endl; file_7<<molecs->IPSP[N]<<endl<<molecs->IPCELL[N]<<endl<<molecs->ICREF[N]<<endl<<molecs->IPCP[N]<<endl<<molecs->PELE[N]<<endl;//WRITE (7) PX(NCLASS,N),PTIM(N),PROT(N),(PV(M,N),M=1,3),IPSP(N),IPCELL(N),ICREF(N),IPCP(N),PELE(N) } else{ file_7<<molecs->PX[calc->NCLASS][N]<<endl<<molecs->PTIM[N]<<endl; for(M=1;M<=3;M++) file_7<<molecs->PV[M][N]<<endl; file_7<<molecs->IPSP[N]<<endl<<molecs->IPCELL[N]<<endl<<molecs->ICREF[N]<<endl<<molecs->IPCP[N]<<endl<<molecs->PELE[N]<<endl;//WRITE (7) PX(NCLASS,N),PTIM(N),(PV(M,N),M=1,3),IPSP(N),IPCELL(N),ICREF(N),IPCP(N),PELE(N) } } } cout<<"Disk write completed"<<endl; // WRITE (*,*) 'Disk write completed' // CLOSE (7) file_7.close(); if(gas->MMVM > 0){ for(int i=0;i<calc->NCLASS+1;i++){ cudaFree(molecs->PX[i]); //delete [] molecs->PX[i]; } cudaFree(molecs->PX); //delete [] molecs->PX; cudaFree(molecs->PTIM); //delete [] molecs->PTIM; cudaFree(molecs->PROT); for(int i=0;i<4;i++){ cudaFree(molecs->PV[i]); //delete [] molecs->PV[i]; } cudaFree(molecs->PV); //delete [] molecs->PV; cudaFree(molecs->IPSP); cudaFree(molecs->IPCELL); cudaFree(molecs->ICREF); cudaFree(molecs->IPCP); cudaFree(molecs->PELE); for(int i=0;i<gas->MMVM;i++){ cudaFree(molecs->IPVIB[i]); //delete [] molecs->IPVIB[i]; } cudaFree(molecs->IPVIB); //delete molecs->IPVIB; // for(int i=0;i<calc->NCLASS+1;i++){ // delete [] molecs->PX[i]; // } // delete [] molecs->PX; // delete [] molecs->PTIM; // delete [] molecs->PROT; // for(int i=0;i<4;i++){ // delete [] molecs->PV[i]; // } // delete [] molecs->PV; // delete [] molecs->IPSP; // delete [] molecs->IPCELL; // delete [] molecs->ICREF; // delete [] molecs->IPCP; // delete [] molecs->PELE; // for(int i=0;i<gas->MMVM;i++){ // delete [] molecs->IPVIB[i]; // } // delete molecs->IPVIB; //DEALLOCATE (PX,PTIM,PROT,PV,IPSP,IPCELL,ICREF,IPCP,IPVIB,PELE,STAT=ERROR) } else{ if(gas->MMRM > 0){ for(int i=0;i<calc->NCLASS+1;i++){ cudaFree(molecs->PX[i]); //delete [] molecs->PX[i]; } cudaFree(molecs->PX); //delete [] molecs->PX; cudaFree(molecs->PTIM); //delete [] molecs->PTIM; cudaFree(molecs->PROT); for(int i=0;i<4;i++){ cudaFree(molecs->PV[i]); //delete [] molecs->PV[i]; } cudaFree(molecs->PV); //delete [] molecs->PV; cudaFree(molecs->IPSP); cudaFree(molecs->IPCELL); cudaFree(molecs->ICREF); cudaFree(molecs->IPCP); cudaFree(molecs->PELE); // delete [] molecs->IPSP; // delete [] molecs->IPCELL; // delete [] molecs->ICREF; // delete [] molecs->IPCP; // delete [] molecs->PELE;//DEALLOCATE (PX,PTIM,PV,IPSP,IPCELL,ICREF,IPCP,PELE,STAT=ERROR) // for(int i=0;i<calc->NCLASS+1;i++){ // delete [] molecs->PX[i]; // } // delete [] molecs->PX; // delete [] molecs->PTIM; // delete [] molecs->PROT; // for(int i=0;i<4;i++){ // delete [] molecs->PV[i]; // } // delete [] molecs->PV; // delete [] molecs->IPSP; // delete [] molecs->IPCELL; // delete [] molecs->ICREF; // delete [] molecs->IPCP; // delete [] molecs->PELE; //DEALLOCATE (PX,PTIM,PROT,PV,IPSP,IPCELL,ICREF,IPCP,PELE,STAT=ERROR) } else{ for(int i=0;i<calc->NCLASS+1;i++){ cudaFree(molecs->PX[i]); //delete [] molecs->PX[i]; } cudaFree(molecs->PX); //delete [] molecs->PX; cudaFree(molecs->PTIM); //delete [] molecs->PTIM; for(int i=0;i<4;i++){ cudaFree(molecs->PV[i]); //delete [] molecs->PV[i]; } cudaFree(molecs->PV); //delete [] molecs->PV; cudaFree(molecs->IPSP); cudaFree(molecs->IPCELL); cudaFree(molecs->ICREF); cudaFree(molecs->IPCP); cudaFree(molecs->PELE); // delete [] molecs->IPSP; // delete [] molecs->IPCELL; // delete [] molecs->ICREF; // delete [] molecs->IPCP; // delete [] molecs->PELE;//DEALLOCATE (PX,PTIM,PV,IPSP,IPCELL,ICREF,IPCP,PELE,STAT=ERROR) } } // IF (ERROR /= 0) THEN // WRITE (*,*)'PROGRAM COULD NOT DEALLOCATE MOLECULES',ERROR // ! STOP // END IF // ! if(gas->MMVM > 0){ molecs->d_allocate(calc->NCLASS+1,MNMN+1,molecs->PX); molecs->d_allocate(MNMN+1,molecs->PTIM); molecs->d_allocate(MNMN+1,molecs->PROT); molecs->d_allocate(4,MNMN+1,molecs->PV); molecs->i_allocate(MNMN+1,molecs->IPSP); molecs->i_allocate(MNMN+1,molecs->IPCELL); molecs->i_allocate(MNMN+1,molecs->ICREF); molecs->i_allocate(MNMN+1,molecs->IPCP); molecs->i_allocate(gas->MMVM+1,MNMN+1,molecs->IPVIB); molecs->d_allocate(MNMN+1,molecs->PELE); // ALLOCATE (PX(NCLASS,MNMN),PTIM(MNMN),PROT(MNMN),PV(3,MNMN),IPSP(MNMN),IPCELL(MNMN),ICREF(MNMN),IPCP(MNMN),IPVIB(MMVM,MNMN),PELE(MNMN),STAT=ERROR) } else{ if(gas->MMRM > 0){ molecs->d_allocate(calc->NCLASS+1,MNMN+1,molecs->PX); molecs->d_allocate(MNMN+1,molecs->PTIM); molecs->d_allocate(MNMN+1,molecs->PROT); molecs->d_allocate(4,MNMN+1,molecs->PV); molecs->i_allocate(MNMN+1,molecs->IPSP); molecs->i_allocate(MNMN+1,molecs->IPCELL); molecs->i_allocate(MNMN+1,molecs->ICREF); molecs->i_allocate(MNMN+1,molecs->IPCP); molecs->d_allocate(MNMN+1,molecs->PELE); // ALLOCATE (PX(NCLASS,MNMN),PTIM(MNMN),PROT(MNMN),PV(3,MNMN),IPSP(MNMN),IPCELL(MNMN),ICREF(MNMN),IPCP(MNMN),PELE(MNMN),STAT=ERROR) } else{ molecs->d_allocate(calc->NCLASS+1,MNMN+1,molecs->PX); molecs->d_allocate(MNMN+1,molecs->PTIM); molecs->d_allocate(4,MNMN+1,molecs->PV); molecs->i_allocate(MNMN+1,molecs->IPSP); molecs->i_allocate(MNMN+1,molecs->IPCELL); molecs->i_allocate(MNMN+1,molecs->ICREF); molecs->i_allocate(MNMN+1,molecs->IPCP); molecs->d_allocate(MNMN+1,molecs->PELE); // ALLOCATE (PX(NCLASS,MNMN),PTIM(MNMN),PV(3,MNMN),IPSP(MNMN),IPCELL(MNMN),ICREF(MNMN),IPCP(MNMN),PELE(MNMN),STAT=ERROR) } } // IF (ERROR /= 0) THEN // WRITE (*,*)'PROGRAM COULD NOT ALLOCATE SPACE FOR EXTEND_MNM',ERROR // ! STOP // END IF // ! //memset(molecs->PX,0.0,sizeof(**molecs->PX)); memset(molecs->PTIM,0.0,sizeof(*molecs->PTIM)); memset(molecs->PV,0.0,sizeof(**molecs->PV)); memset(molecs->IPSP,0,sizeof(*molecs->IPSP)); memset(molecs->IPCELL,0,sizeof(*molecs->IPCELL)); memset(molecs->ICREF,0,sizeof(*molecs->ICREF)); memset(molecs->IPCP,0,sizeof(*molecs->IPCP)); memset(molecs->PELE,0,sizeof(*molecs->PELE)); for(int i=0;i<calc->NCLASS+1;i++){ for(int j=0;j<MNMN+1;j++) molecs->PX[i][j]=0.0; } for(int i=0;i<4;i++){ for(int j=0;j<MNMN+1;j++) molecs->PV[i][j]=0.0; } for(int i=0;i<MNMN+1;i++){ molecs->PTIM[i]=0.0; molecs->IPSP[i]=0; molecs->IPCELL[i]=0; molecs->ICREF[i]=0; molecs->IPCP[i]=0; molecs->PELE[i]=0; } if(gas->MMRM > 0) { for(int i=0;i<MNMN+1;i++) molecs->PROT[i]=0.0; //memset(molecs->PROT,0.0,sizeof(*molecs->PROT)); } if(gas->MMVM > 0) { for(int i=0;i<gas->MMVM+1;i++){ for(int j=0;j<MNMN+1;j++) molecs->IPVIB[i][j]=0; } //memset(molecs->IPVIB,0,sizeof(**molecs->IPVIB)); } //restore the original molecules // OPEN (7,FILE='EXTMOLS.SCR',FORM='BINARY') // WRITE (*,*) 'Start read back from disk storage' file_7.open("EXTMOLS.SCR", ios::binary | ios::in); if(file_7.is_open()){ cout<<"EXTMOLS.SCR is opened"<<endl; } else{ cout<<"EXTMOLS.SCR not opened"<<endl; } for(N=1;N<=molecs->MNM;N++){ if(gas->MMVM > 0){ file_7>>molecs->PX[calc->NCLASS][N]>>molecs->PTIM[N]>>molecs->PROT[N]; for(M=1;M<=3;M++) file_7>>molecs->PV[M][N]; file_7>>molecs->IPSP[N]>>molecs->IPCELL[N]>>molecs->ICREF[N]>>molecs->IPCP[N]; for(M=1;M<=gas->MMVM;M++) file_7>>molecs->IPVIB[M][N]; file_7>>molecs->PELE[N];//READ (7) PX(NCLASS,N),PTIM(N),PROT(N),(PV(M,N),M=1,3),IPSP(N),IPCELL(N),ICREF(N),IPCP(N),(IPVIB(M,N),M=1,MMVM),PELE(N) } else{ if(gas->MMRM > 0){ file_7>>molecs->PX[calc->NCLASS][N]>>molecs->PTIM[N]>>molecs->PROT[N]; for(M=1;M<=3;M++) file_7>>molecs->PV[M][N]; file_7>>molecs->IPSP[N]>>molecs->IPCELL[N]>>molecs->ICREF[N]>>molecs->IPCP[N]>>molecs->PELE[N];//READ (7) PX(NCLASS,N),PTIM(N),PROT(N),(PV(M,N),M=1,3),IPSP(N),IPCELL(N),ICREF(N),IPCP(N),PELE(N) } else{ file_7>>molecs->PX[calc->NCLASS][N]>>molecs->PTIM[N]; for(M=1;M<=3;M++) file_7>>molecs->PV[M][N]; file_7>>molecs->IPSP[N]>>molecs->IPCELL[N]>>molecs->ICREF[N]>>molecs->IPCP[N]>>molecs->PELE[N];//READ (7) PX(NCLASS,N),PTIM(N),(PV(M,N),M=1,3),IPSP(N),IPCELL(N),ICREF(N),IPCP(N),PELE(N) } } } cout<<"Disk read completed"<<endl; // WRITE (*,*) 'Disk read completed' // CLOSE (7,STATUS='DELETE') file_7.close(); // molecs->MNM=MNMN; // return; } void DISSOCIATION() { //dissociate diatomic molecules that have been marked for dissociation by -ve level or -99999 for ground state //MOLECS molecs; //GAS gas; //CALC calc; // // IMPLICIT NONE // int K,KK,L,N,M,LS,MS,KV,IDISS; double A,B,C,EA,VRR,VR,RMM,RML; double VRC[4],VCM[4],VRCP[4]; // N=0; while(N < molecs->NM){ N=N+1; IDISS=0; L=molecs->IPSP[N]; if(gas->ISPV[L] > 0){ for(K=1;K<=gas->ISPV[L];K++){ M=molecs->IPVIB[K][N]; if(M < 0){ //dissociation calc->TDISS[L]=calc->TDISS[L]+1.e00; IDISS=1; } } if(IDISS == 1){ EA=molecs->PROT[N]; //EA is energy available for relative translational motion of atoms if(gas->MELE > 1) EA=EA+molecs->PELE[N]; if(molecs->NM >= molecs->MNM) EXTEND_MNM(1.1); molecs->NM=molecs->NM+1; //set center of mass velocity as that of molecule VCM[1]=molecs->PV[1][N]; VCM[2]=molecs->PV[2][N]; VCM[3]=molecs->PV[3][N]; molecs->PX[calc->NCLASS][molecs->NM]=molecs->PX[calc->NCLASS][N]; molecs->IPCELL[molecs->NM]=molecs->IPCELL[N]; LS=molecs->IPSP[N]; gas->TREACL[1][LS]=gas->TREACL[1][LS]-1; molecs->IPSP[molecs->NM]=gas->ISPVM[1][1][L]; MS=molecs->IPSP[molecs->NM]; molecs->IPSP[N]=gas->ISPVM[2][1][L]; LS=molecs->IPSP[N]; gas->TREACG[1][LS]=gas->TREACG[1][LS]+1; gas->TREACG[1][MS]=gas->TREACG[1][MS]+1; molecs->PTIM[molecs->NM]=molecs->PTIM[N]; VRR=2.e00*EA/gas->SPM[1][LS][MS]; VR=sqrt(VRR); RML=gas->SPM[1][LS][MS]/gas->SP[5][MS]; RMM=gas->SPM[1][LS][MS]/gas->SP[5][LS]; // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); B=2.e00*calc->RANF-1.e00; A=sqrt(1.e00-B*B); VRCP[1]=B*VR; // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); C=2.e00*PI*calc->RANF; VRCP[2]=A*cos(C)*VR; VRCP[3]=A*sin(C)*VR; for(KK=1;KK<=3;KK++){ molecs->PV[KK][N]=VCM[KK]+RMM*VRCP[KK]; molecs->PV[KK][molecs->NM]=VCM[KK]-RML*VRCP[KK]; } if((fabs(molecs->PV[1][N]) > 100000.e00) || (fabs(molecs->PV[1][molecs->NM]) > 100000.e00)) { cout<< "EXCESSIVE SPEED, DISS "<< N<< " "<<molecs->PV[1][N]<<" "<<molecs->NM<<" "<<molecs->PV[1][molecs->NM]<<endl; } //set any internal modes to the ground state if(gas->ISPV[LS] > 0){ for(KV=1;KV<=gas->ISPV[LS];KV++) molecs->IPVIB[KV][N]=0; } if(gas->ISPR[1][LS] > 0) molecs->PROT[N]=0.e00; if(gas->MELE > 1) molecs->PELE[N]=0.e00; if(gas->ISPV[MS] > 0){ for(KV=1;KV<=gas->ISPV[MS];KV++) molecs->IPVIB[KV][molecs->NM]=0; } if(gas->ISPR[1][MS] > 0) molecs->PROT[molecs->NM]=0.0; if(gas->MELE > 1) molecs->PELE[molecs->NM]=0.e00; } } } return; } //************************************************************************************ // void ENERGY(int I,double &TOTEN) { //calculate the total energy (all molecules if I=0, otherwise molecule I) //I>0 used for dianostic purposes only //MOLECS molecs; //GAS gas; //CALC calc; // // IMPLICIT NONE // int K,L,N,II,M,IV,KV,J; double TOTENI,TOTELE; // TOTEN=0.0; TOTELE=0; // if(I == 0){ for(N=1;N<=molecs->NM;N++){ if(molecs->IPCELL[N] > 0){ L=molecs->IPSP[N]; TOTENI=TOTEN; TOTEN=TOTEN+gas->SP[6][L]; TOTEN=TOTEN+0.5e00*gas->SP[5][L]*(pow(molecs->PV[1][N],2)+pow(molecs->PV[2][N],2)+pow(molecs->PV[3][N],2)); if(gas->ISPR[1][L] > 0) TOTEN=TOTEN+molecs->PROT[N]; if(gas->ISPV[L] > 0){ for(KV=1;KV<=gas->ISPV[L];KV++){ J=molecs->IPVIB[KV][N]; // IF (J <0) THEN // J=-J // IF (J == 99999) J=0 // END IF TOTEN=TOTEN+double(J)*BOLTZ*gas->SPVM[1][KV][L]; } } } if(gas->MELE > 1){ TOTEN=TOTEN+molecs->PELE[N]; TOTELE=TOTELE+molecs->PELE[N]; } if((TOTEN-TOTENI) > 1.e-16) cout<<"MOL "<<N<<" ENERGY "<<TOTEN-TOTENI<<endl; } // //WRITE (9,*) 'Total Energy =',TOTEN,NM //WRITE (*,*) 'Total Energy =',TOTEN,NM file_9<<"Total Energy = "<<setprecision(25)<<TOTEN<<"\t"<<molecs->NM<<endl; cout<<"Total Energy = "<<setprecision(20)<<TOTEN<<"\t"<<molecs->NM<<endl; // WRITE (*,*) 'Electronic Energy =',TOTELE } else{ N=I; if(molecs->IPCELL[N] > 0){ L=molecs->IPSP[N]; TOTEN=TOTEN+gas->SP[6][L]; TOTEN=TOTEN+0.5e00*gas->SP[5][L]*(pow(molecs->PV[1][N],2)+pow(molecs->PV[2][N],2)+pow(molecs->PV[3][N],2)); if(gas->ISPR[1][L] > 0) TOTEN=TOTEN+molecs->PROT[N]; if(gas->ISPV[L] > 0){ for(KV=1;KV<=gas->ISPV[L];KV++){ J=molecs->IPVIB[KV][N]; // IF (J <0) THEN // J=-J // IF (J == 99999) J=0 // END IF TOTEN=TOTEN+double(J)*BOLTZ*gas->SPVM[1][KV][L]; } } } } // return; // } void SETXT() { //generate TECPLOT files for displaying an x-t diagram of an unsteady flow //this employs ordered data, therefore the cells MUST NOT BE ADAPTED //N.B. some custom coding for particular problems // // //MOLECS molecs; //CALC calc; //GEOM_1D geom; //GAS gas; //OUTPUT output; // // IMPLICIT NONE // int N,M,IOUT; double A,C; double **VALINT; // REAL(KIND=8), ALLOCATABLE, DIMENSION(:,:) :: VALINT // //VALINT(N,M) the interpolated values at sampling cell M boundaries and extrapolated values at boundaries // N=1 distance // N=2 time // N=3 number density // N=4 radial velocity // N=5 pressure (nkT) // N=6 temperature // N=7 h2o fraction (Sec. 7.9 only) // //the variables in VALINT may be altered for particular problems // VALINT = new double*[7]; for(int i =0; i< 7; ++i) VALINT[i] = new double[geom->NCELLS+2]; // ALLOCATE (VALINT(6,NCELLS+1),STAT=ERROR) // //777 FORMAT(12G14.6) //24[] //Internal options IOUT=0; //0 for dimensioned output, 1 for non-dimensional output // A=1.e00; //dt/dt for selection of v velocity component in TECPLOT to draw particle paths as "streamlines" // if(calc->FTIME < 0.5e00*calc->DTM){ //Headings and zero time record // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR VALINT ARRAY',ERROR // ENDIF calc->NLINE=1; file_9<< "J in tecplot file = "<<calc->NLINE*(geom->NCELLS+1)<<endl; // WRITE (18,*) 'VARIABLES = "Distance","Time","n","u","p","T","H2O","A"' //for combustion wave output(Sec. 7.9) file_18<<"VARIABLES = 'Distance','Time','n','u','p','T','A' "<<endl; file_18<<"ZONE I= "<<geom->NCELLS+1<<", J= (set to number of output intervals+1), F=POINT"<<endl; // for(N=1;N<=geom->NCELLS+1;N++){ VALINT[1][N]=geom->XB[1]+(N-1)*geom->DDIV; //distance VALINT[1][N]=VALINT[1][N]; //time VALINT[2][N]=0.0; VALINT[3][N]=gas->FND[1]; VALINT[4][N]=0; VALINT[5][N]=gas->FND[1]*BOLTZ*gas->FTMP[1]; VALINT[6][N]=gas->FTMP[1]; // VALINT(7,N)=FSP(6,1) //FSP(6 for combustion wave if((VALINT[1][N] > geom->XS) && (calc->ISECS == 1)){ VALINT[3][N]=gas->FND[2]; VALINT[5][N]=gas->FND[2]*BOLTZ*gas->FTMP[2]; VALINT[6][N]=gas->FTMP[2]; // VALINT(7,N)=FSP(6,2) } if(IOUT == 1){ VALINT[3][N]=1.e00; VALINT[5][N]=1.e00; VALINT[6][N]=1.e00; } for(M=1;M<=6;M++) file_18<<VALINT[M][N]<<"\t";//WRITE (18,777) (VALINT(M,N),M=1,6),A file_18<<A<<endl; } } else{ calc->NLINE=calc->NLINE+1; cout<<"J in tecplot file = "<<calc->NLINE<<endl; if(geom->IVB == 0) C=geom->DDIV; if(geom->IVB == 1) C=(geom->XB[2]+geom->VELOB*calc->FTIME-geom->XB[1])/double(geom->NDIV); for(N=1;N<=geom->NCELLS+1;N++){ VALINT[1][N]=geom->XB[1]+(N-1)*C; VALINT[2][N]=calc->FTIME; if((N > 1) && (N < geom->NCELLS+1)){ VALINT[3][N]=0.5e00*(output->VAR[3][N]+output->VAR[3][N-1]); VALINT[4][N]=0.5e00*(output->VAR[5][N]+output->VAR[5][N-1]); VALINT[5][N]=0.5e00*(output->VAR[18][N]+output->VAR[18][N-1]); VALINT[6][N]=0.5e00*(output->VAR[11][N]+output->VAR[11][N-1]); // VALINT(7,N)=0.5D00*(VARSP(1,N,6)+VARSP(1,N-1,6)) //H2O fraction for Sec 7.9 } } for(N=3;N<=6;N++) VALINT[N][1]=0.5e00*(3.e00*VALINT[N][2]-VALINT[N][3]); // for(N=3;N<=6;N++) VALINT[N][geom->NCELLS+1]=0.5e00*(3.e00*VALINT[N][geom->NCELLS]-VALINT[N][geom->NCELLS-1]); // for(N=1;N<=geom->NCELLS+1;N++){ if(IOUT == 1){ VALINT[1][N]=(VALINT[1][N]-geom->XB[1])/(geom->XB[2]-geom->XB[1]); VALINT[2][N]=VALINT[2][N]/calc->TNORM; VALINT[3][N]=VALINT[3][N]/gas->FND[1]; VALINT[4][N]=VALINT[4][N]/gas->VMPM; VALINT[5][N]=VALINT[5][N]/(gas->FND[1]*BOLTZ*gas->FTMP[1]); VALINT[6][N]=VALINT[6][N]/gas->FTMP[1]; } for(M=1;M<=6;M++) file_18<<VALINT[M][N]<<"\t";//WRITE (18,777) (VALINT[M][N],M=1,6),A // file_18<<A<<endl; } } // return; } void MOLECULES_MOVE_1D() {// //molecule moves appropriate to the time step //for homogeneous and one-dimensional flows //(homogeneous flows are calculated as one-dimensional) //MOLECS molecs; //GAS gas; //GEOM_1D geom; //CALC calc; //OUTPUT output; // // IMPLICIT NONE // int N,L,M,K,NCI,J,II,JJ; double A,B,X,XI,XC,DX,DY,DZ,DTIM,S1,XM,R,TI,DTC,POB,UR,WFI,WFR,WFRI; // //N working integer //NCI initial cell time //DTIM time interval for the move //POB position of the outer boundary //TI initial time //DTC time interval to collision with surface //UR radial velocity component //WFI initial weighting factor //WFR weighting factor radius //WFRI initial weighting factor radius // if((geom->ITYPE[2] == 4) && (calc->ICN == 1)){ //memset(calc->ALOSS,0.e00,sizeof(*calc->ALOSS));//calc->ALOSS=0.e00; for(int i=0;i<gas->MSP+1;i++) calc->ALOSS[i]=0.e00; calc->NMP=molecs->NM; } // N=1; while(N <= molecs->NM){ // NCI=molecs->IPCELL[N]; if((calc->IMTS == 0) || (calc->IMTS == 2)) DTIM=calc->DTM; if(calc->IMTS == 1) DTIM=2.e00*geom->CCELL[3][NCI]; if(calc->FTIME-molecs->PTIM[N] > 0.5*DTIM){ WFI=1.e00; if(geom->IWF == 1) WFI=1.e00+geom->WFM*pow(molecs->PX[1][N],geom->IFX); II=0; //becomes 1 if a molecule is removed TI=molecs->PTIM[N]; molecs->PTIM[N]=TI+DTIM; calc->TOTMOV=calc->TOTMOV+1; // XI=molecs->PX[1][N]; DX=DTIM*molecs->PV[1][N]; X=XI+DX; // if(geom->IFX > 0){ DY=0.e00; DZ=DTIM*molecs->PV[3][N]; if(geom->IFX == 2) DY=DTIM*molecs->PV[2][N]; R=sqrt(X*X+DY*DY+DZ*DZ); } // if(geom->IFX == 0){ for(J=1;J<=2;J++){ // 1 for minimum x boundary, 2 for maximum x boundary if(II == 0){ if(((J == 1) && (X < geom->XB[1])) || ((J == 2) && (X > (geom->XB[2]+geom->VELOB*molecs->PTIM[N])))){ //molecule crosses a boundary if((geom->ITYPE[J] == 0) || (geom->ITYPE[J] == 3) || (geom->ITYPE[J] == 4)){ if(geom->XREM > geom->XB[1]){ L=molecs->IPSP[N]; calc->ENTMASS=calc->ENTMASS-gas->SP[5][L]; } if((geom->ITYPE[2] == 4) && (calc->ICN == 1)){ L=molecs->IPSP[N]; calc->ALOSS[L]=calc->ALOSS[L]+1.e00; } REMOVE_MOL(N); N=N-1; II=1; } // if(geom->ITYPE[J] == 1){ if((geom->IVB == 0) || (J == 1)){ X=2.e00*geom->XB[J]-X; molecs->PV[1][N]=-molecs->PV[1][N]; } else if((J == 2) && (geom->IVB == 1)){ DTC=(geom->XB[2]+TI*geom->VELOB-XI)/(molecs->PV[1][N]-geom->VELOB); XC=XI+molecs->PV[1][N]*DTC; molecs->PV[1][N]=-molecs->PV[1][N]+2.*geom->VELOB; X=XC+molecs->PV[1][N]*(DTIM-DTC); } } // if(geom->ITYPE[J] == 2) REFLECT_1D(N,J,X); // END IF } } } } else{ //cylindrical or spherical flow //check boundaries if((X <geom-> XB[1]) && (geom->XB[1] > 0.e00)){ RBC(XI,DX,DY,DZ,geom->XB[1],S1); if(S1 < 1.e00){ //intersection with inner boundary if(geom->ITYPE[1] == 2){//solid surface DX=S1*DX; DY=S1*DY; DZ=S1*DZ; AIFX(XI,DX,DY,DZ,X,molecs->PV[1][N],molecs->PV[2][N],molecs->PV[3][N]); REFLECT_1D(N,1,X); } else{ REMOVE_MOL(N); N=N-1; II=1; } } } else if((geom->IVB == 0) && (R > geom->XB[2])){ RBC(XI,DX,DY,DZ,geom->XB[2],S1); if(S1 < 1.e00){ //intersection with outer boundary if(geom->ITYPE[2] == 2){ //solid surface DX=S1*DX; DY=S1*DY; DZ=S1*DZ; AIFX(XI,DX,DY,DZ,X,molecs->PV[1][N],molecs->PV[2][N],molecs->PV[3][N]); X=1.001e00*geom->XB[2]; while(X > geom->XB[2]) REFLECT_1D(N,2,X); // END DO } else{ REMOVE_MOL(N); N=N-1; II=1; } } } else if((geom->IVB == 1) && (R > (geom->XB[2]+molecs->PTIM[N]*geom->VELOB))){ if(geom->IFX == 1) UR=sqrt(pow(molecs->PV[1][N],2)+pow(molecs->PV[2][N],2)); if(geom->IFX == 2) UR=sqrt(pow(molecs->PV[1][N],2)+pow(molecs->PV[2][N],2)+pow(molecs->PV[3][N],2)); DTC=(geom->XB[2]+TI*geom->VELOB-XI)/(UR-geom->VELOB); S1=DTC/DTIM; DX=S1*DX; DY=S1*DY; DZ=S1*DZ; AIFX(XI,DX,DY,DZ,X,molecs->PV[1][N],molecs->PV[2][N],molecs->PV[3][N]); molecs->PV[1][N]=-molecs->PV[1][N]+2.0*geom->VELOB; X=X+molecs->PV[1][N]*(DTIM-DTC); } else AIFX(XI,DX,DY,DZ,X,molecs->PV[1][N],molecs->PV[2][N],molecs->PV[3][N]); //DIAGNOSTIC if(II == 0){ if(X > geom->XB[2]+molecs->PTIM[N]*geom->VELOB){ //WRITE (*,*) N,calc->FTIME,X,geom->XB[2]+molecs->PTIM[N]*geom->VELOB; cout<<N<<" "<<calc->FTIME<<" "<<X<<" "<<(geom->XB[2]+molecs->PTIM[N]*geom->VELOB)<<endl; } } //Take action on weighting factors if((geom->IWF == 1) && (II == 0)){ WFR=WFI/(1.e00+geom->WFM*pow(X,geom->IFX)); L=0; WFRI=WFR; if(WFR >= 1.e00){ while(WFR >= 1.e00){ L=L+1; WFR=WFR-1.e00; } } // CALL RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); if(calc->RANF <= WFR) L=L+1; if(L == 0){ REMOVE_MOL(N); N=N-1; II=1; } L=L-1; if(L > 0){ for(K=1;K<=L;K++){ if(molecs->NM >= molecs->MNM) EXTEND_MNM(1.1); molecs->NM=molecs->NM+1; molecs->PX[1][molecs->NM]=X; for(M=1;M<=3;M++) molecs->PV[M][molecs->NM]=molecs->PV[M][N]; if(gas->MMRM > 0) molecs->PROT[molecs->NM]=molecs->PROT[N]; molecs->IPCELL[molecs->NM]=fabs(molecs->IPCELL[N]); molecs->IPSP[molecs->NM]=molecs->IPSP[N]; molecs->IPCP[molecs->NM]=molecs->IPCP[N]; if(gas->MMVM > 0){ for(M=1;M<=gas->MMVM;M++) molecs->IPVIB[M][molecs->NM]=molecs->IPVIB[M][N]; } molecs->PTIM[molecs->NM]=molecs->PTIM[N]; //+5.D00*DFLOAT(K)*DTM //note the possibility of a variable time advance that may take the place of the duplication buffer in earlier programs if(molecs->PX[1][molecs->NM] > geom->XB[2]+molecs->PTIM[molecs->NM]*geom->VELOB) //WRITE (*,*) 'DUP',NM,FTIME,PX(1,NM),XB(2)+PTIM(NM)*VELOB cout<<"DUP "<<molecs->NM<<" "<<calc->FTIME<<" "<<molecs->PX[1][molecs->NM]<<" "<<(geom->XB[2]+molecs->PTIM[molecs->NM]*geom->VELOB)<<endl; } } } } // if(II == 0){ molecs->PX[1][N]=X; if(molecs->PX[1][N] > geom->XB[1] && (molecs->PX[1][N] < geom->XB[2])) continue; else{ cout<< N<<" OUTSIDE FLOWFIELD AT "<<molecs->PX[1][N]<<" VEL "<<molecs->PV[1][N]<<endl; REMOVE_MOL(N); N=N-1; II=1; } } // if(II == 0){ if(geom->IVB == 0) FIND_CELL_1D(molecs->PX[1][N],molecs->IPCELL[N],JJ); if(geom->IVB == 1) FIND_CELL_MB_1D(molecs->PX[1][N],molecs->IPCELL[N],JJ,molecs->PTIM[N]); } // } // N=N+1; } // return; } void READ_RESTART() { //MOLECS molecs; //GEOM_1D geom; //GAS gas; //CALC calc; //OUTPUT output; // IMPLICIT NONE // fstream file_7; int ZCHECK; // // 101 CONTINUE _101: file_7.open("PARAMETERS.DAT", ios::in | ios::binary); if(file_7.is_open()){ cout<<"PARAMETERS.DAT opened successfully"<<endl; file_7>>geom->NCCELLS>>geom->NCELLS>>gas->MMRM>>gas->MMVM>>molecs->MNM>>gas->MNSR>>gas->MSP>>geom->ILEVEL>>geom->MDIV>>gas->MMEX>>gas->MEX>>gas->MELE>>gas->MVIBL>>calc->NCLASS; file_7.close(); } else{ cout<<"PARAMETERS.DAT not opening"<<endl; goto _101; } //cout<<geom->NCCELLS<<endl<<geom->NCELLS<<endl<<gas->MMRM<<endl<<gas->MMVM<<endl<<molecs->MNM<<endl; // OPEN (7,FILE='PARAMETERS.DAT',FORM='BINARY',ERR=101) // READ (7) NCCELLS,NCELLS,MMRM,MMVM,MNM,MNSR,MSP,ILEVEL,MDIV,MMEX,MEX,MELE,MVIBL,NCLASS // CLOSE(7) // if(gas->MMVM > 0){ molecs->d_allocate(calc->NCLASS+1,molecs->MNM+1,molecs->PX); molecs->d_allocate(molecs->MNM+1,molecs->PTIM); molecs->d_allocate(molecs->MNM+1,molecs->PROT); molecs->i_allocate(molecs->MNM+1,molecs->IPCELL); molecs->i_allocate(molecs->MNM+1,molecs->IPSP); molecs->i_allocate(molecs->MNM+1,molecs->ICREF); molecs->i_allocate(molecs->MNM+1,molecs->IPCP); molecs->d_allocate(4,molecs->MNM+1,molecs->PV); molecs->i_allocate(gas->MMVM+1,molecs->MNM+1,molecs->IPVIB); molecs->d_allocate(molecs->MNM+1,molecs->PELE); // ALLOCATE (PX(NCLASS,MNM),PTIM(MNM),PROT(MNM),IPCELL(MNM),IPSP(MNM),ICREF(MNM),IPCP(MNM),PV(3,MNM), & // IPVIB(MMVM,MNM),PELE(MNM),STAT=ERROR) } else{ if(gas->MMRM > 0){ molecs->d_allocate(calc->NCLASS+1,molecs->MNM+1,molecs->PX); molecs->d_allocate(molecs->MNM+1,molecs->PTIM); molecs->d_allocate(molecs->MNM+1,molecs->PROT); molecs->i_allocate(molecs->MNM+1,molecs->IPCELL); molecs->i_allocate(molecs->MNM+1,molecs->IPSP); molecs->i_allocate(molecs->MNM+1,molecs->ICREF); molecs->i_allocate(molecs->MNM+1,molecs->IPCP); molecs->d_allocate(4,molecs->MNM+1,molecs->PV); molecs->d_allocate(molecs->MNM+1,molecs->PELE); // ALLOCATE (PX(NCLASS,MNM),PTIM(MNM),PROT(MNM),IPCELL(MNM),IPSP(MNM),ICREF(MNM),IPCP(MNM),PV(3,MNM),PELE(MNM),STAT=ERROR) } else{ molecs->d_allocate(calc->NCLASS+1,molecs->MNM+1,molecs->PX); molecs->d_allocate(molecs->MNM+1,molecs->PTIM); molecs->i_allocate(molecs->MNM+1,molecs->IPCELL); molecs->i_allocate(molecs->MNM+1,molecs->IPSP); molecs->i_allocate(molecs->MNM+1,molecs->ICREF); molecs->i_allocate(molecs->MNM+1,molecs->IPCP); molecs->d_allocate(4,molecs->MNM+1,molecs->PV); molecs->d_allocate(molecs->MNM+1,molecs->PELE); // ALLOCATE (PX(NCLASS,MNM),PTIM(MNM),IPCELL(MNM),IPSP(MNM),ICREF(MNM),IPCP(MNM),PV(3,MNM),PELE(MNM),STAT=ERROR) } } // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR MOLECULE ARRAYS',ERROR // ENDIF // geom->i_allocate(geom->ILEVEL+1,geom->MDIV+1,geom->JDIV); // ALLOCATE (JDIV(0:ILEVEL,MDIV),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR JDIV ARRAY',ERROR // ENDIF geom->d_allocate(5,geom->NCELLS+1,geom->CELL); geom->i_allocate(geom->NCELLS+1,geom->ICELL); geom->d_allocate(6,geom->NCCELLS+1,geom->CCELL); geom->i_allocate(4,geom->NCCELLS+1,geom->ICCELL); // ALLOCATE (CELL(4,NCELLS),ICELL(NCELLS),CCELL(5,NCCELLS),ICCELL(3,NCCELLS),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR CELL ARRAYS',ERROR // ENDIF output->d_allocate(geom->NCELLS+1,output->COLLS); output->d_allocate(geom->NCELLS+1,output->WCOLLS); output->d_allocate(geom->NCELLS+1,output->CLSEP); output->d_allocate(gas->MNSR+1,output->SREAC); output->d_allocate(24,geom->NCELLS+1,output->VAR); output->d_allocate(13,geom->NCELLS+1,gas->MSP+1,output->VARSP); output->d_allocate(36+gas->MSP,3,output->VARS); output->d_allocate(10+gas->MSP,geom->NCELLS+1,gas->MSP+1,output->CS); output->d_allocate(9,3,gas->MSP+1,3,output->CSS); output->d_allocate(7,3,output->CSSS); // ALLOCATE (COLLS(NCELLS),WCOLLS(NCELLS),CLSEP(NCELLS),SREAC(MNSR),VAR(23,NCELLS), & // VARSP(0:12,NCELLS,MSP),VARS(0:35+MSP,2),CS(0:9+MSP,NCELLS,MSP),CSS(0:8,2,MSP,2),CSSS(6,2),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR SAMPLING ARRAYS',ERROR // ENDIF // if(gas->MMVM >= 0){ output->d_allocate(gas->MSP+1,gas->MMVM+1,151,output->VIBFRAC); output->d_allocate(gas->MSP+1,gas->MMVM+1,output->SUMVIB); // ALLOCATE (VIBFRAC(MSP,MMVM,0:150),SUMVIB(MSP,MMVM),STAT=ERROR) // IF (ERROR /= 0) THEN // WRITE (*,*) 'PROGRAM COULD NOT ALLOCATE SPACE FOR RECOMBINATION ARRAYS',ERROR // ENDIF } // ALLOCATE_GAS(); // //102 CONTINU _102: file_7.open("RESTART.DAT", ios::in | ios::binary); if(file_7.is_open()){ cout<<"RESTART.DAT opened successfully"<<endl; /*file_7>>calc->AJM>>calc->ALOSS>>output->AVDTM>>BOLTZ>>geom->CCELL>>geom->CELL>>output->CLSEP>>output->COLLS>>calc->CPDTM>>gas->CR>>output->CS>>output->CSS>>output->CSSS>>gas->CTM>>gas->CXSS>>geom->DDIV>>DPI>>calc->DTM>>calc->DTSAMP>>calc->DTOUT>>calc->EME>>calc->ENTMASS>>gas->ENTR>>calc->ENTREM>>calc->ERROR>>gas->ERS>>gas->FDEN>>gas->FMA>>gas->FND>>calc->FNUM>>calc->FRACSAM>>gas->FSP>>gas->FP>>gas->FPM>>gas->FPR>>geom->FREM>>gas->FSPEC>>gas->FTMP>>calc->FTIME>>gas->FVTMP>>geom->ICCELL>>geom->ICELL>>calc->ICLASS>>calc->ICN>>molecs->ICREF>>geom->IFX>>gas->IGAS>>calc->IMTS>>molecs->IPCELL>>molecs->IPCP>>molecs->IPSP>>molecs->IPVIB>>calc->IREM>>calc->ISAD>>calc->ISECS>>calc->ISF>>gas->ISPEX>>gas->ISPR>>gas->ISPRC>>gas->ISPRK>>gas->ISPV>>gas->ISPVM>>gas->ISRCD>>geom->ITYPE>>geom->IVB>>geom->IWF>>geom->JDIV>>gas->LIS>>gas->LRS>>calc->MOLSC>>calc->MVER>>geom->NCCELLS>>geom->NCELLS>>geom->NCIS>>geom->NDIV>>gas->NELL>>gas->NEX>>calc->NLINE>>molecs->NM>>output->NMISAMP>>calc->NNC>>output->NOUT>>output->NSAMP>>gas->NSLEV>>gas->NSPEX>>calc->NREL>>calc->NVER>>molecs->PELE>>PI>>molecs->PROT>>molecs->PTIM>>molecs->PV>>molecs->PX>>gas->QELC>>gas->RGFS>>gas->RMAS>>gas->SLER>>gas->SP>>gas->SPEX>>SPI>>gas->SPM>>gas->SPR>>gas->SPRC>>gas->SPREX>>gas->SPRP>>gas->SPRT>>gas->SPV>>gas->SPVM>>output->SREAC>>output->SUMVIB>>calc->TCOL>>calc->TDISS>>calc->TRECOMB>>output->TISAMP>>calc->TPOUT>>calc->TREF>>calc->TLIM>>calc->TOTCOL>>calc->TOTMOV>>gas->TREACG>>gas->TREACL>>calc->TOUT>>calc->TPDTM>>calc->TREF>>calc->TSAMP>>gas->TSURF>>output->VAR>>output->VARS>>output->VARSP>>geom->VELOB>>gas->VFX>>gas->VFY>>output->VIBFRAC>>gas->VMP>>gas->VMPM>>calc->VNMAX>>gas->VSURF>>output->WCOLLS>>geom->WFM>>geom->XB>>geom->XREM>>output->XVELS>>output->YVELS>>gas->TNEX>>ZCHECK>>endl;*/ file_7.read((char*)&calc,sizeof(calc)); file_7.read((char*)&molecs,sizeof(molecs)); file_7.read((char*)&gas,sizeof(gas)); file_7.read((char*)&geom,sizeof(geom)); file_7.read((char*)&output,sizeof(output)); file_7.close(); } else{ cout<<"Restart.DAT not opening"<<endl; goto _102; } // OPEN (7,FILE='RESTART.DAT',FORM='BINARY',ERR=102) // READ (7) AJM,ALOSS,AVDTM,BOLTZ,CCELL,CELL,CLSEP,COLLS, & // CPDTM,CR,CS,CSS,CSSS,CTM,CXSS,DDIV,DPI,DTM,DTSAMP,DTOUT,EME, & // ENTMASS,ENTR,ENTREM,ERROR,ERS,FDEN,FMA,FND,FNUM,FRACSAM,FSP,FP,FPM,FPR,FREM,FSPEC, & // FTMP,FTIME,FVTMP,ICCELL,ICELL,ICLASS,ICN,ICREF,IFX,IGAS,IMTS,IPCELL,IPCP, & // IPSP,IPVIB,IREM,ISAD,ISECS,ISF,ISPEX,ISPR,ISPRC,ISPRK,ISPV,ISPVM,ISRCD,ITYPE,IVB,IWF, & // JDIV,LIS,LRS,MOLSC,MVER,NCCELLS,NCELLS, & // NCIS,NDIV,NELL,NEX,NLINE,NM,NMISAMP,NNC,NOUT,NSAMP,NSLEV,NSPEX,NREL,NVER,PELE,PI,PROT,PTIM,PV,PX, & // QELC,RGFS,RMAS,SLER,SP,SPEX,SPI,SPM,SPR,SPRC,SPREX,SPRP,SPRT,SPV,SPVM,SREAC,SUMVIB, & // TCOL,TDISS,TRECOMB,TISAMP,TPOUT,TREF,TLIM,TOTCOL,TOTMOV, & // TREACG,TREACL,TOUT,TPDTM,TREF,TSAMP,TSURF,VAR,VARS,VARSP,VELOB,VFX,VFY,VIBFRAC,VMP, & // VMPM,VNMAX,VSURF,WCOLLS,WFM,XB,XREM,XVELS,YVELS,TNEX,ZCHECK // // // CLOSE(7) // if(ZCHECK != 1234567){ file_9<<molecs->NM<<" Molecules, Check integer = "<<ZCHECK<<endl; //WRITE (9,*) NM,' Molecules, Check integer =',ZCHECK return ; } else file_9<<"Restart file read, Check integer= "<<ZCHECK<<endl; //WRITE (9,*) 'Restart file read, Check integer=',ZCHECK // return; // } //***************************************************************************** void WRITE_RESTART() { //MOLECS molecs; //GEOM_1D geom; //GAS gas; //CALC calc; //OUTPUT output; // IMPLICIT NONE // int ZCHECK; // fstream file_7; ZCHECK=1234567; // //101 CONTINUE _101: file_7.open("PARAMETERS.DAT", ios::out | ios::binary); if(file_7.is_open()){ file_7<<geom->NCCELLS<<endl<<geom->NCELLS<<endl<<gas->MMRM<<endl<<gas->MMVM<<endl<<molecs->MNM<<endl<<gas->MNSR<<endl<<gas->MSP<<endl<<geom->ILEVEL<<endl<<geom->MDIV<<endl<<gas->MMEX<<endl<<gas->MEX<<endl<<gas->MELE<<endl<<gas->MVIBL<<endl<<calc->NCLASS<<endl; file_7.close(); } else{ cout<<"Parameters.DAT file not opening(write)"<<endl; goto _101; } // OPEN (7,FILE='PARAMETERS.DAT',FORM='BINARY',ERR=101) // WRITE (7) NCCELLS,NCELLS,MMRM,MMVM,MNM,MNSR,MSP,ILEVEL,MDIV,MMEX,MEX,MELE,MVIBL,NCLASS // CLOSE(7) // // 102 CONTINUE _102: file_7.open("RESTART.DAT", ios::out | ios::binary); if(file_7.is_open()){ /*file_7<<calc->AJM<<calc->ALOSS<<output->AVDTM<<BOLTZ<<geom->CCELL<<geom->CELL<<output->CLSEP<<output->COLLS<<calc->CPDTM<<gas->CR<<output->CS<<output->CSS<<output->CSSS<<gas->CTM<<gas->CXSS<<geom->DDIV<<DPI<<calc->DTM<<calc->DTSAMP<<calc->DTOUT<<calc->EME<<calc->ENTMASS<<gas->ENTR<<calc->ENTREM<<calc->ERROR<<gas->ERS<<gas->FDEN<<gas->FMA<<gas->FND<<calc->FNUM<<calc->FRACSAM<<gas->FSP<<gas->FP<<gas->FPM<<gas->FPR<<geom->FREM<<gas->FSPEC<<gas->FTMP<<calc->FTIME<<gas->FVTMP<<geom->ICCELL<<geom->ICELL<<calc->ICLASS<<calc->ICN<<molecs->ICREF<<geom->IFX<<gas->IGAS<<calc->IMTS<<molecs->IPCELL<<molecs->IPCP<<molecs->IPSP<<molecs->IPVIB<<calc->IREM<<calc->ISAD<<calc->ISECS<<calc->ISF<<gas->ISPEX<<gas->ISPR<<gas->ISPRC<<gas->ISPRK<<gas->ISPV<<gas->ISPVM<<gas->ISRCD<<geom->ITYPE<<geom->IVB<<geom->IWF<<geom->JDIV<<gas->LIS<<gas->LRS<<calc->MOLSC<<calc->MVER<<geom->NCCELLS<<geom->NCELLS<<geom->NCIS<<geom->NDIV<<gas->NELL<<gas->NEX<<calc->NLINE<<molecs->NM<<output->NMISAMP<<calc->NNC<<output->NOUT<<output->NSAMP<<gas->NSLEV<<gas->NSPEX<<calc->NREL<<calc->NVER<<molecs->PELE<<PI<<molecs->PROT<<molecs->PTIM<<molecs->PV<<molecs->PX<<gas->QELC<<gas->RGFS<<gas->RMAS<<gas->SLER<<gas->SP<<gas->SPEX<<SPI<<gas->SPM<<gas->SPR<<gas->SPRC<<gas->SPREX<<gas->SPRP<<gas->SPRT<<gas->SPV<<gas->SPVM<<output->SREAC<<output->SUMVIB<<calc->TCOL<<calc->TDISS<<calc->TRECOMB<<output->TISAMP<<calc->TPOUT<<calc->TREF<<calc->TLIM<<calc->TOTCOL<<calc->TOTMOV<<gas->TREACG<<gas->TREACL<<calc->TOUT<<calc->TPDTM<<calc->TREF<<calc->TSAMP<<gas->TSURF<<output->VAR<<output->VARS<<output->VARSP<<geom->VELOB<<gas->VFX<<gas->VFY<<output->VIBFRAC<<gas->VMP<<gas->VMPM<<calc->VNMAX<<gas->VSURF<<output->WCOLLS<<geom->WFM<<geom->XB<<geom->XREM<<output->XVELS<<output->YVELS<<gas->TNEX<<ZCHECK<<endl;*/ file_7.write((char*)&calc,sizeof(calc)); file_7.write((char*)&molecs,sizeof(molecs)); file_7.write((char*)&gas,sizeof(gas)); file_7.write((char*)&geom,sizeof(geom)); file_7.write((char*)&output,sizeof(output)); file_7.close(); } else{ cout<<"Restart.DAT file not opening(write)"<<endl; goto _101; } // OPEN (7,FILE='RESTART.DAT',FORM='BINARY',ERR=102) // WRITE (7)AJM,ALOSS,AVDTM,BOLTZ,CCELL,CELL,CLSEP,COLLS, & // CPDTM,CR,CS,CSS,CSSS,CTM,CXSS,DDIV,DPI,DTM,DTSAMP,DTOUT,EME, & // ENTMASS,ENTR,ENTREM,ERROR,ERS,FDEN,FMA,FND,FNUM,FRACSAM,FSP,FP,FPM,FPR,FREM,FSPEC, & // FTMP,FTIME,FVTMP,ICCELL,ICELL,ICLASS,ICN,ICREF,IFX,IGAS,IMTS,IPCELL,IPCP, & // IPSP,IPVIB,IREM,ISAD,ISECS,ISF,ISPEX,ISPR,ISPRC,ISPRK,ISPV,ISPVM,ISRCD,ITYPE,IVB,IWF, & // JDIV,LIS,LRS,MOLSC,MVER,NCCELLS,NCELLS, & // NCIS,NDIV,NELL,NEX,NLINE,NM,NMISAMP,NNC,NOUT,NSAMP,NSLEV,NSPEX,NREL,NVER,PELE,PI,PROT,PTIM,PV,PX, & // QELC,RGFS,RMAS,SLER,SP,SPEX,SPI,SPM,SPR,SPRC,SPREX,SPRP,SPRT,SPV,SPVM,SREAC,SUMVIB, & // TCOL,TDISS,TRECOMB,TISAMP,TPOUT,TREF,TLIM,TOTCOL,TOTMOV, & // TREACG,TREACL,TOUT,TPDTM,TREF,TSAMP,TSURF,VAR,VARS,VARSP,VELOB,VFX,VFY,VIBFRAC,VMP, & // VMPM,VNMAX,VSURF,WCOLLS,WFM,XB,XREM,XVELS,YVELS,TNEX,ZCHECK // // // CLOSE(7) // file_9<<"Restart files written"<<endl; //WRITE (9,*) 'Restart files written' // return; } void OUTPUT_RESULTS() { //--calculate the surface and flowfield properties //--generate TECPLOT files for displaying these properties //--calculate collisiion rates and flow transit times and reset time intervals //--add molecules to any flow plane molecule output files //CALC calc; //MOLECS molecs; //GAS gas; //OUTPUT output; //GEOM_1D geom; fstream file_3; fstream file_10; fstream file_7; int IJ,J,JJ,K,L,LL,M,N,NN,NMCR,CTIME,II; long long NNN; double AS,AT,C1,C2,C3,C4,C5,C6,C7,C8,C9; double A,B,C,SDTM,SMCR,DOF,AVW,UU,VDOFM,TVIBM,VEL,DTMI,TT; //dout double SUM[14]; double SUMS[10][3]; double *TVIB,*VDOF,*PPA,*TEL,*ELDOF,*SDOF,*CDTM; double **TV,**THCOL; double ***DF; int *NMS; // REAL(KIND=8), ALLOCATABLE, DIMENSION(:) :: TVIB,VDOF,PPA,TEL,ELDOF,SDOF,CDTM // REAL(KIND=8), ALLOCATABLE, DIMENSION(:,:) :: TV,THCOL // REAL(KIND=8), ALLOCATABLE, DIMENSION(:,:,:) :: DF // INTEGER, ALLOCATABLE, DIMENSION(:) :: NMS //INTEGER, ALLOCATABLE, DIMENSION(:,:) :: string F,E; //--CTIME computer time (microseconds) //--SUMS(N,L) sum over species of CSS(N,J,L,M) for surface properties // //--For flowfield properties,where <> indicates sampled sum //--SUM(0) the molecular number sum over all species //--SUM(1) the weighted number sum over all species //--SUM(2) the weighted sum of molecular masses //--SUM(3),(4),(5) the weighted sum over species of m*<u>,<v>,<w> //--SUM(6) the weighted sum over species of m*(<u**2>+<v**2>+<w**2>) //--SUM(7) the weighted sum over species of <u**2>+<v**2>+<w**2> //--SUM(8) the weighted sum of rotational energy //--SUM(9) the weighted sum of rotational degrees of freedom //--SUM(10) the weighted sum over species of m*<u**2> //--SUM(11) the weighted sum over species of m*<v**2> //--SUM(12) sum over species of m*<w**2> //--SUM(13) the weighted sum of electronic energy //--UU velocity squared //--DOF degrees of freedom //--AVW the average value of the viscosity-temperature exponent //--DVEL velocity difference //--TVEL thermal speed //--SMCR sum of mcs/mfp over cells //--NMCR number in the sum //--VDOFM effective vibrational degrees of freedom of mixture //--TVIB(L) //--VDOF(L) //--TV(K,L) the temperature of vibrational mode K of species L //--PPA particles per atom //--NMS number per species //--SDOF(L) total degrees of freedom for species L // // //--calculate the flowfield properties in the cells //dout TV = new double*[gas->MMVM+1]; for(int i =0; i< gas->MMVM+1; ++i) TV[i] = new double[gas->MSP+1]; TVIB = new double[gas->MSP+1]; DF = new double **[geom->NCELLS+1]; for (int i = 0; i < geom->NCELLS+1; ++i) { DF[i] = new double *[gas->MMVM+1]; for (int j = 0; j < gas->MMVM+1; ++j) DF[i][j] = new double [gas->MSP+1]; } VDOF= new double[gas->MSP+1]; TEL = new double[gas->MSP+1]; ELDOF = new double[gas->MSP+1]; PPA = new double[gas->MSP+1]; NMS = new int[gas->MSP+1]; THCOL = new double*[gas->MSP+1]; for(int i =0; i< gas->MSP+1; ++i) THCOL[i] = new double[gas->MSP+1]; SDOF = new double[gas->MSP+1]; CDTM = new double[geom->NCELLS+1]; // ALLOCATE (TV(MMVM,MSP),TVIB(MSP),DF(NCELLS,MMVM,MSP),VDOF(MSP),TEL(MSP),ELDOF(MSP),PPA(MSP),NMS(MSP),THCOL(MSP,MSP) & // ,SDOF(MSP),CDTM(NCELLS),STAT=ERROR) // if(calc->ERROR!=0) // { // cout<<"ROGRAM COULD NOT ALLOCATE OUTPUT VARIABLES"<<calc->ERROR<<endl; // } if(calc->FTIME>0.5e00*calc->DTM) { output->NOUT+=1; if(output->NOUT>9999) output->NOUT=output->NOUT-9999; cout<<"Generating files for output interval"<<output->NOUT<<endl; if(calc->ISF==0) { //dout //OPEN (3,FILE='DS1OUT.DAT') file_3.open("DS1OUT.DAT" , ios::out); if(file_3.is_open()){ cout<<"DS1OUT.DAT is opened"<<endl; } else{ cout<<"DS1OUT.DAT not opened"<<endl; } //F='DS';//E//'.OUT' } else { //--the files are DS1n.DAT, where n is a four digit integer equal to NOUT //dout //500 FORMAT(I5) //ENCODE(5,500,E) 10000+NOUT int a=output->NOUT+10000; E=to_string(a); F="DS" + E + "OUT.DAT"; //dout //file_3.open(F.c_str(), ios::out|ios::binary); if(file_3.is_open()){ cout<<F<<" is opened"<<endl; } else{ cout<<F<<" not opened"<<endl; } //OPEN (3,FILE=F) } } //dout //memset(output->VAR,0.e00,sizeof(**output->VAR)); for(int i=0;i<24;i++){ for(int j=0;j<geom->NCELLS+1;j++) output->VAR[i][j]=0.e00; } if(geom->IFX==0) A=calc->FNUM/(calc->FTIME-output->TISAMP); for(JJ=1;JJ<=2;JJ++) { if(geom->IFX==1) A=calc->FNUM/(2.e00*PI*geom->XB[JJ])*(calc->FTIME-output->TISAMP); if(geom->IFX==2) A=calc->FNUM/(4.e00*PI*geom->XB[JJ])*geom->XB[JJ]*(calc->FTIME-output->TISAMP); //--JJ=1 for surface at XB(1), JJ=2 for surface at XB(2) if(geom->ITYPE[JJ]==2) { //dout //memset(SUMS,0.e00,sizeof(SUMS)); for(int i=0;i<10;i++){ for(int j=0;j<3;j++) SUMS[i][j]=0.e00; } for( L=1;L<=gas->MSP;L++) { for(J=0;J<=8;J++) { for(IJ=1;IJ<=2;IJ++) { SUMS[J][IJ]=SUMS[J][IJ]+output->CSS[J][JJ][L][IJ]; } } } output->VARS[0][JJ]=SUMS[0][1]; output->VARS[1][JJ]=SUMS[1][1]; output->VARS[2][JJ]=SUMS[1][2]; output->VARS[3][JJ]=SUMS[1][1]*A; output->VARS[4][JJ]=SUMS[1][2]*A; output->VARS[5][JJ]=SUMS[2][1]*A; output->VARS[6][JJ]=SUMS[2][2]*A; output->VARS[7][JJ]=SUMS[3][1]*A; output->VARS[8][JJ]=SUMS[3][2]*A; output->VARS[9][JJ]=SUMS[4][1]*A; output->VARS[10][JJ]=SUMS[4][2]*A; output->VARS[11][JJ]=SUMS[5][1]*A; output->VARS[12][JJ]=SUMS[5][2]*A; output->VARS[13][JJ]=SUMS[6][1]*A; output->VARS[14][JJ]=SUMS[6][2]*A; output->VARS[15][JJ]=SUMS[7][1]*A; output->VARS[16][JJ]=SUMS[7][2]*A; output->VARS[33][JJ]=SUMS[8][1]*A; output->VARS[34][JJ]=SUMS[8][2]*A; // VARS(17,JJ)=SUMS(9,1)*A //--SURFACE REACTIONS NOT YET IMPLEMENTED // VARS(18,JJ)=SUMS(9,2)*A if(output->CSSS[1][JJ]>1.e-6) { output->VARS[19][JJ]=output->CSSS[3][JJ]/output->CSSS[2][JJ]; ////--n.b. must be modified to include second component in 3D output->VARS[20][JJ]=(output->CSSS[4][JJ]-output->CSSS[2][JJ]*output->VARS[19][JJ]*output->VARS[19][JJ])/(output->CSSS[1][JJ]*3.e00*BOLTZ)-gas->TSURF[JJ]; output->VARS[19][JJ]=output->VARS[19][JJ]-gas->VSURF[JJ]; if(output->CSSS[6][JJ]>1.e-6) { output->VARS[21][JJ]=(2.e000/BOLTZ)*(output->CSSS[5][JJ]/output->CSSS[6][JJ])-gas->TSURF[JJ]; } else { output->VARS[21][JJ]=0.e00; } } else { output->VARS[19][JJ]=0.e00; output->VARS[20][JJ]=0.e00; output->VARS[21][JJ]=0.e00; } output->VARS[22][JJ]=(SUMS[2][1]+SUMS[2][2])*A; output->VARS[23][JJ]=(SUMS[3][1]+SUMS[3][2])*A; output->VARS[24][JJ]=(SUMS[4][1]+SUMS[4][2])*A; output->VARS[25][JJ]=(SUMS[5][1]+SUMS[5][2])*A; output->VARS[26][JJ]=(SUMS[6][1]+SUMS[6][2])*A; output->VARS[27][JJ]=(SUMS[7][1]+SUMS[7][2])*A; output->VARS[28][JJ]=(SUMS[9][1]+SUMS[9][2])*A; output->VARS[29][JJ]=output->VARS[11][JJ]+output->VARS[13][JJ]+output->VARS[15][JJ]+output->VARS[33][JJ]; output->VARS[30][JJ]=output->VARS[12][JJ]+output->VARS[14][JJ]+output->VARS[16][JJ]+output->VARS[34][JJ]; output->VARS[31][JJ]=output->VARS[29][JJ]+output->VARS[30][JJ]; output->VARS[35][JJ]=output->VARS[33][JJ]+output->VARS[34][JJ]; for(L=1;gas->MSP;L++) { if(SUMS[1][1]>0) { output->VARS[35+L][JJ]=100*output->CSS[1][JJ][L][1]/SUMS[1][1]; } else { output->VARS[35+L][JJ]=0.0; } } } } //output->VARSP=0; for(int i=0;i<13;i++){ for(int j=0;j<geom->NCELLS+1;j++){ for(int k=0;k<gas->MSP+1;k++) output->VARSP[i][j][k]=0; } } SMCR=0; NMCR=0; for(N=1;N<=geom->NCELLS;N++) { if(N==120) { continue; } A=calc->FNUM/(geom->CELL[4][N])*output->NSAMP; if(geom->IVB==1) A=A*pow((geom->XB[2]-geom->XB[1])/(geom->XB[2]+geom->VELOB*0.5e00*(calc->FTIME-output->TISAMP)-geom->XB[1]),geom->IFX+1); //--check the above for non-zero XB(1) //dout //memset(SUM,0,sizeof(SUM)); for(int i=0;i<14;i++) SUM[i]=0; NMCR+=1; for(L=1;L<=gas->MSP;L++) { SUM[0]=SUM[0]+output->CS[0][N][L]; SUM[1]=SUM[1]+output->CS[1][N][L]; SUM[2]=SUM[2]+gas->SP[5][L]*output->CS[0][N][L]; for(K=1;K<=3;K++) { SUM[K+2]=SUM[K+2]+gas->SP[5][L]*output->CS[K+1][N][L]; if(output->CS[1][N][L]>1.1e00) { output->VARSP[K+1][N][L]=output->CS[K+4][N][L]/output->CS[1][N][L]; //--VARSP(2,3,4 are temporarily the mean of the squares of the velocities output->VARSP[K+8][N][L]=output->CS[K+1][N][L]/output->CS[1][N][L]; } } SUM[6]=SUM[6]+gas->SP[5][L]*(output->CS[5][N][L]+output->CS[6][N][L]+output->CS[7][N][L]); SUM[10]=SUM[10]+gas->SP[5][L]*output->CS[5][N][L]; SUM[12]=SUM[11]+gas->SP[5][L]*output->CS[6][N][L]; SUM[12]=SUM[12]+gas->SP[5][L]*output->CS[7][N][L]; SUM[13]=SUM[13]+output->CS[9][N][L]; if(output->CS[1][N][L]>0.5e00) SUM[7]=SUM[7]+output->CS[5][N][L]+output->CS[6][N][L]+output->CS[7][N][L]; if(gas->ISPR[1][L]>0) { SUM[8]=SUM[8]+output->CS[8][N][L]; SUM[9]=SUM[9]+output->CS[1][N][L]*gas->ISPR[1][L]; } } AVW=0; for(L=1;L<=gas->MSP;L++) { output->VARSP[0][N][L]=output->CS[1][N][L]; output->VARSP[1][N][L]=0.e00; output->VARSP[6][N][L]=0.0; output->VARSP[7][N][L]=0.0; output->VARSP[8][N][L]=0.0; if(SUM[1]>0.1) { output->VARSP[1][N][L]=output->CS[1][N][L]/SUM[1]; AVW=AVW+gas->SP[3][L]*output->CS[1][N][L]/SUM[1]; if(gas->ISPR[1][L]>0 && output->CS[1][N][L]>0.5) output->VARSP[6][N][L]=(2.e00/BOLTZ)*output->CS[8][N][L]/((double)(gas->ISPR[1][L])*output->CS[1][N][L]); } output->VARSP[5][N][L]=0; for(K=1;K<=3;K++) { output->VARSP[K+1][N][L]=(gas->SP[5][L]/BOLTZ)*(output->VARSP[K+1][N][L]-pow(output->VARSP[K+8][N][L],2)); output->VARSP[5][N][L]=output->VARSP[5][N][L]+output->VARSP[K+1][N][L]; } output->VARSP[5][N][L]=output->VARSP[5][N][L]/3.e00; output->VARSP[8][N][L]=(3.e00*output->VARSP[5][N][L]+(double)gas->ISPR[1][L]*output->VARSP[6][N][L])/(3.e00+(double)(gas->ISPR[1][L])); } if(geom->IVB==0) output->VAR[1][N]=geom->CELL[1][N]; if(geom->IVB==1) { C=(geom->XB[2]+geom->VELOB*calc->FTIME-geom->XB[1])/(double)(geom->NDIV); //new DDIV output->VAR[1][N]=geom->XB[1]+((double)(N-1)+0.5)*C; } output->VAR[2][N]=SUM[0]; if(SUM[1]>0.5) { output->VAR[3][N]=SUM[1]*A;//--number density Eqn. (4.28) output->VAR[4][N]=output->VAR[3][N]*SUM[2]/SUM[1]; //--density Eqn. (4.29) output->VAR[5][N]=SUM[3]/SUM[2];//--u velocity component Eqn. (4.30) output->VAR[6][N]=SUM[4]/SUM[2]; //--v velocity component Eqn. (4.30) output->VAR[7][N]=SUM[5]/SUM[2]; //--w velocity component Eqn. (4.30) UU= pow(output->VAR[5][N],2)+pow(output->VAR[6][N],2)+pow(output->VAR[7][N],2); if(SUM[1]>1) { output->VAR[8][N]=(fabs(SUM[6]-SUM[2]*UU))/(3.e00*BOLTZ*SUM[1]); //Eqn. (4.39) //--translational temperature output->VAR[19][N]=fabs(SUM[10]-SUM[2]*pow(output->VAR[5][N],2))/(BOLTZ*SUM[1]); output->VAR[20][N]=fabs(SUM[11]-SUM[2]*pow(output->VAR[6][N],2))/(BOLTZ*SUM[1]); output->VAR[21][N]=fabs(SUM[12]-SUM[2]*pow(output->VAR[7][N],2))/(BOLTZ*SUM[1]); } else { output->VAR[8][N]=1.0; output->VAR[19][N]=1.0; output->VAR[20][N]=1.0; output->VAR[21][N]=1.0; } if(SUM[9]>0.1e00) { output->VAR[9][N]=(2.e00/BOLTZ)*SUM[8]/SUM[9]; ////--rotational temperature Eqn. (4.36) } else output->VAR[9][N]=0.0; output->VAR[10][N]=gas->FTMP[1]; ////vibration default DOF=(3.e00+SUM[9])/SUM[1]; output->VAR[11][N]=(3.0*output->VAR[8][N]+(SUM[9]/SUM[1]))*output->VAR[9][N]/DOF; //--overall temperature based on translation and rotation output->VAR[18][N]=output->VAR[3][N]*BOLTZ*output->VAR[8][N]; //--scalar pressure (now (from V3) based on the translational temperature) if(gas->MMVM>0) { for(L=1;L<=gas->MSP;L++) { VDOF[L]=0.0; //dout if(gas->ISPV[L] > 0) { for(K=1;K<=gas->ISPV[L];K++) { if(output->CS[K+9][N][L]<BOLTZ) { TV[K][L]=0.0; DF[N][K][L]=0.0; } else { TV[K][L]=gas->SPVM[1][K][L]/log(1.0+output->CS[1][N][L]/output->CS[K+9][N][L]) ;//--Eqn.(4.45) DF[N][K][L]=2.0*(output->CS[K+9][N][L]/output->CS[1][N][L])*log(1.0+output->CS[1][N][L]/output->CS[K+9][N][L]); //--Eqn. (4.46) } VDOF[L]=VDOF[L]+DF[N][K][L]; } //memset(TVIB,0.0,sizeof(*TVIB)); for(int i=0;i<gas->MSP+1;i++) TVIB[i]=0.0; for(K=1;K<=gas->ISPV[L];K++) { if(VDOF[L]>1.e-6) { TVIB[L]=TVIB[L]+TV[K][L]*DF[N][K][L]/VDOF[L]; } else TVIB[L]=gas->FVTMP[1]; } } else { TVIB[L]=calc->TREF; VDOF[L]=0.0; } output->VARSP[7][N][L]=TVIB[L]; } VDOFM=0.0; TVIBM=0.0; A=0.e00; for(L=1;L<=gas->MSP;L++) { //dout if(gas->ISPV[L] > 0) { A=A+output->CS[1][N][L]; } } for(L=1;L<=gas->MSP;L++) { //dout if(gas->ISPV[L] > 0) { VDOFM=VDOFM+VDOF[L]-output->CS[1][N][L]/A; TVIBM=TVIBM+TVIB[L]-output->CS[1][N][L]/A; } } output->VAR[10][N]=TVIBM; } for(L=1;L<=gas->MSP;L++) { if(output->VARSP[0][N][L]>0.5) { //--convert the species velocity components to diffusion velocities for(K=1;K<=3;K++) { output->VARSP[K+8][N][L]=output->VARSP[K+8][N][L]-output->VAR[K+4][N]; } if(gas->MELE>1) { //--calculate the electronic temperatures for the species //memset(ELDOF,0.e00,sizeof(*ELDOF)); for(int i=0;i<gas->MSP+1;i++) ELDOF[i] = 0.e00; //dout //memset(TEL,0.e00,sizeof(*TEL)); for(int i=0;i<gas->MSP+1;i++) TEL[i] = 0.e00; if(gas->MELE>1) { A=0.e00; B=0.e00; for(M=1;M<=gas->NELL[L];M++) { if(output->VARSP[5][N][L]>1.e00) { C=gas->QELC[2][M][L]/output->VARSP[5][N][L]; A=A+gas->QELC[1][M][L]*exp(-C); B=B+gas->QELC[1][M][L]*C*exp(-C); } } if(B>1.e-10) { TEL[L]=output->CS[9][N][L]/output->CS[1][N][L]/(BOLTZ*B/A); } else TEL[L]=output->VAR[11][N]; output->VARSP[12][N][L]=TEL[L]; ELDOF[L]=0.e00; if(output->VARSP[5][N][L]>1.e00) ELDOF[L]=2.e00*output->CS[9][N][L]/output->CS[1][N][L]/(BOLTZ*output->VARSP[5][N][L]); if(ELDOF[L]<0.01) { output->VARSP[12][N][L]=output->VAR[11][N]; } } else { ELDOF[L]=0.0; } } } else { for(K=8;K<=12;K++) { output->VARSP[K][N][L]=0.e00; } } } //--set the overall electronic temperature if(gas->MELE>1) { C=0.e00; for(L=1;L<=gas->MSP;L++) { if(ELDOF[L]>1.e-5) C=C+output->CS[1][N][L]; } if(C>0.e00) { A=0.e00; B=0.e00; for(L=1;L<=gas->MSP;L++) { if(ELDOF[L]>1.e-5) { A=A+output->VARSP[12][N][L]*output->CS[1][N][L]; B=B+output->CS[1][N][L]; } } output->VAR[22][N]=A/B; } else{ output->VAR[22][N]=output->VAR[11][N]; } } else{ output->VAR[22][N]=gas->FTMP[1]; } if(gas->MMVM>0) { //--set the overall temperature and degrees of freedom for the individual species for(L=1;L<=gas->MSP;L++) { if(gas->MELE>1){ SDOF[L]=3.e00+gas->ISPR[1][L]+VDOF[L]+ELDOF[L]; output->VARSP[8][N][L]=(3.0*output->VARSP[5][N][L]+gas->ISPR[1][L]*output->VARSP[6][N][L]+VDOF[L]*output->VARSP[7][N][L]+ELDOF[L]*output->VARSP[12][N][L])/SDOF[L]; } else{ SDOF[L]=3.e00+gas->ISPR[1][L]+VDOF[L]+ELDOF[L]; output->VARSP[8][N][L]=(3.0*output->VARSP[5][N][L]+gas->ISPR[1][L]*output->VARSP[6][N][L]+VDOF[L]*output->VARSP[7][N][L])/SDOF[L]; } } //--the overall species temperature now includes vibrational and electronic excitation //--the overall gas temperature can now be set A=0.e00; B=0.e00; for(L=1;L<=gas->MSP;L++) { A=A+SDOF[L]+output->VARSP[8][N][L]*output->CS[1][N][L]; B=B+SDOF[L]*output->CS[1][N][L]; } output->VAR[11][N]=A/B; } VEL=sqrt(pow(output->VAR[5][N],2)+pow(output->VAR[6][N],2)+pow(output->VAR[7][N],2)); output->VAR[12][N]=VEL/sqrt((DOF+2.e00)*output->VAR[11][N]*(SUM[1]*BOLTZ/SUM[2]))/DOF; //--Mach number output->VAR[13][N]=SUM[0]/output->NSAMP; ////--average number of molecules in cell //dout if(output->COLLS[N] > 2.0) { output->VAR[14][N]=0.5e00*(calc->FTIME-output->TISAMP)*(SUM[1]/output->NSAMP)/output->WCOLLS[N]; //--mean collision time output->VAR[15][N]=0.92132e00*sqrt(fabs(SUM[7]/SUM[1]-UU))*output->VAR[14][N]; //--mean free path (based on r.m.s speed with correction factor based on equilibrium) output->VAR[16][N]=output->CLSEP[N]/(output->COLLS[N]*output->VAR[15][N]); } else{ output->VAR[14][N]=1.e10; output->VAR[15][N]=1.e10/output->VAR[3][N]; //--m.f.p set by nominal values } } else { for(L=3;L<=22;L++) { output->VAR[L][N]=0.0; } } output->VAR[17][N]=VEL; } if(calc->FTIME>0.e00*calc->DTM) { if(calc->ICLASS==1){ if(geom->IFX==0) file_3<<"DSMC program for a one-dimensional plane flow"<<endl;//WRITE (3,*) 'DSMC program for a one-dimensional plane flow'; if(geom->IFX==1) file_3<<"DSMC program for a cylindrical flow"<<endl;//WRITE (3,*) 'DSMC program for a one-dimensional plane flow'; if(geom->IFX==2) file_3<<"DSMC program for a spherical flow"<<endl;//WRITE (3,*) 'DSMC program for a one-dimensional plane flow'; } file_3<<endl;//WRITE (3,*) file_3<<"Interval "<<output->NOUT<<" Time "<<calc->FTIME<< " with "<<output->NSAMP<<" samples from "<<output->TISAMP<<endl; //WRITE (3,*) 'Interval',output->NOUT,'Time ',calc->FTIME, ' with',output->NSAMP,' samples from',output->TISAMP //990 FORMAT(I7,G13.5,I7,G13.5) //Dout NNN=calc->TOTMOV; cout<<"TOTAL MOLECULES = "<< molecs->NM<<endl; //dout //NMS=0; for(int i=0;i<gas->MSP+1;i++) NMS[i]=0; for(N=1;N<=molecs->NM;N++) { M=molecs->IPSP[N]; NMS[M]+=1; } file_3<<"Total simulated molecules = "<<molecs->NM<<endl; for(N=1;N<=gas->MSP;N++) { cout<< " SPECIES "<<N<<" TOTAL = "<<NMS[N]<<endl; file_3<<"Species "<<N<<" total = "<<NMS[N]<<endl; } if(gas->MEX>0) { ENERGY(0,A); for(N=1;N<=gas->MSP;N++) { if(gas->ISPV[N]>0){ file_9<< "SP "<<N<<" DISSOCS "<<calc->TDISS[N]<<" RECOMBS "<<calc->TRECOMB[N]<<endl; cout<<"SP"<<N<<"DISSOCS"<<calc->TDISS[N]<<" RECOMBS "<<calc->TRECOMB[N]<<endl; file_3<<"SP "<<N<<" DISSOCS "<<calc->TDISS[N]<<" RECOMBS "<<calc->TRECOMB[N]<<endl; } } for(N=1;N<=gas->MSP;N++) { cout<<"EX,C reaction"<<N<<" number"<<gas->TNEX[N]<<endl; file_9<<"EX,C reaction "<<N<<" number "<<gas->TNEX[N]<<endl; file_3<<"EX,C reaction "<<N<<" number "<<gas->TNEX[N]<<endl; } } file_3<<"Total molecule moves = "<<NNN<<endl; //dout NNN=calc->TOTCOL; file_3<<"Total collision events = "<<NNN<<endl; // file_3<<"Species dependent collision numbers in current sample"<<endl; for(N=1;N<=gas->MSP;N++) { if(gas->IGAS!=8){ for(M=1;M<=gas->MSP;M++) file_3<<calc->TCOL[N][M]<<"\t"; file_3<<endl; //WRITE(3,901) (calc->TCOL[N][M],M=1,gas->MSP); } if(gas->IGAS==8){ for(M=1;M<=gas->MSP;M++) file_3<<calc->TCOL[N][M]<<"\t"; file_3<<endl; // WRITE(3,902) (calc->TCOL[N][M],M=1,gas->MSP); } } //Dout //901 FORMAT(5G13.5) //902 FORMAT(8G13.5) //dout CTIME=clock(); file_3<<"Computation time "<<(double)CTIME/1000.0<< "seconds"<<endl; file_3<<"Collision events per second "<<(calc->TOTCOL-calc->TOTCOLI)*1000.e00/(double)CTIME<<endl; file_3<<"Molecule moves per secon "<<(calc->TOTMOV-calc->TOTMOVI)*1000.e00/(double)CTIME<<endl; if(calc->ICLASS==0&& gas->MMVM==0&&calc->ISF==0){ //--a homogeneous gas with no vibratioal modes - assume that it is a collision test run //******PRODUCES DATA FOR TABLES 6.1 AND 6.2 IN SECTION 6.2******* // A=0.e00; B=0.e00; C=0.e00; for(N=1;N<=geom->NCCELLS;N++) { A+=geom->CCELL[5][N]; B+=geom->CCELL[4][N]; C+=geom->CCELL[3][N]; } file_3<<"Overall time step "<<calc->DTM<<endl; file_3<<"Molecules per collision cell "<<(double)(molecs->NM)/(double)(geom->NCCELLS)<<endl; file_3<<"Mean cell time ratio "<< A/((double)(geom->NCCELLS)*calc->FTIME)<<endl; file_3<<"Mean value of cross-section and relative speed "<<B/(double)(geom->NCCELLS)<<endl; file_3<<"Mean half collision cell time step "<<C/(double)(geom->NCCELLS)<<endl; if(gas->MSP==1){ A=2.e00*SPI*output->VAR[3][1] *(pow(gas->SP[1][1],2))*sqrt(4.e00*BOLTZ*gas->SP[2][1]/gas->SP[5][1])*pow((output->VAR[11][1])/gas->SP[2][1],(1.e00-gas->SP[3][1])); //--Eqn. (2.33) for equilibhrium collision rate file_3<<"Coll. rate ratio to equilib "<<calc->TCOL[1][1]/((double)(molecs->NM)*(calc->FTIME-output->TISAMP))/A<<endl; } else{ file_3<<"Species collision rate ratios to equilibrium"<<endl; for(N=1;N<=gas->MSP;N++){ file_3<<"Collision rate for species "<<N<<endl; for(M=1;M<=gas->MSP;M++) { THCOL[N][M]=2.e00*(1.e00/SPI)*output->VAR[3][1]*output->VARSP[1][1][M]*gas->SPM[2][N][M]*sqrt(2.e00*BOLTZ*gas->SPM[5][N][M]/gas->SPM[1][N][M])*pow(output->VAR[11][1]/gas->SPM[5][N][M],1.e00-gas->SPM[3][N][M]); //--Eqn. (2.36) for equilibhrium collision rate of species N with species M file_3<<"with species "<<M<<" "<<calc->TCOL[N][M]/((double)(molecs->NM)*gas->FSP[N][1]*(calc->FTIME-output->TISAMP))/THCOL[N][M]<<endl; } } file_3<<endl; for(N=1;N<=gas->MSP;N++){ file_3<<"Collision numbers for species "<<N<<endl; for(M=1;M<=gas->MSP;M++){ file_3<<"with species "<<M<<" "<<calc->TCOL[N][M]<<endl; } } } } file_3<<endl; if(geom->ITYPE[1]==2|| geom->ITYPE[2]==1) file_3<<"Surface quantities"<<endl; for(JJ=1;JJ<=2;JJ++) { if(geom->ITYPE[JJ]==2){ file_3<<endl; file_3<<"Surface at "<<geom->XB[JJ]<<endl; file_3<<"Incident sample "<<output->VARS[0][JJ]<<endl; file_3<<"Number flux "<<output->VARS[3][JJ]<<" /sq m/s"<<endl; file_3<<"Inc pressure "<<output->VARS[5][JJ]<<" Refl pressure "<<output->VARS[6][JJ]<<endl; file_3<<"Pressure "<< output->VARS[5][JJ]+output->VARS[6][JJ]<<" N/sq m"<<endl; file_3<<"Inc y shear "<<output->VARS[7][JJ]<<" Refl y shear "<<output->VARS[8][JJ]<<endl; file_3<<"Net y shear "<<output->VARS[7][JJ]-output->VARS[8][JJ]<<" N/sq m"<<endl; file_3<<"Net z shear "<<output->VARS[9][JJ]-output->VARS[10][JJ]<<" N/sq m"<<endl; file_3<<"Incident translational heat flux "<<output->VARS[11][JJ]<<" W/sq m"<<endl; if(gas->MMRM>0) file_3<<"Incident rotational heat flux "<<output->VARS[13][JJ]<<" W/sq m"<<endl; if(gas->MMVM>0) file_3<<"Incident vibrational heat flux "<<output->VARS[15][JJ]<<" W/sq m"<<endl; if(gas->MELE>1) file_3<<"Incident electronic heat flux "<<output->VARS[33][JJ]<<" W/sq m"<<endl; file_3<<"Total incident heat flux "<<output->VARS[29][JJ]<<" W/sq m"<<endl; file_3<<"Reflected translational heat flux "<<output->VARS[12][JJ]<<" W/sq m"<<endl; if(gas->MMRM>0) file_3<<"Reflected rotational heat flux "<<output->VARS[14][JJ]<<" W/sq m"<<endl; if(gas->MMVM>0) file_3<<"Reflected vibrational heat flux "<<output->VARS[16][JJ]<<" W/sq m"<<endl; if(gas->MELE>1) file_3<<"Reflected electronic heat flux "<<output->VARS[34][JJ]<<" W/sq m"<<endl; file_3<<"Total reflected heat flux "<<output->VARS[30][JJ]<<" W/sq m"<<endl; file_3<<"Net heat flux "<<output->VARS[31][JJ]<<" W/sq m"<<endl; file_3<<"Slip velocity (y direction) "<<output->VARS[19][JJ]<<" m/s"<<endl; file_3<<"Translational temperature slip"<<output->VARS[20][JJ]<<" K"<<endl; if(gas->MMRM>0) file_3<<"Rotational temperature slip "<<output->VARS[21][JJ]<<" K"<<endl; if(gas->MSP>1) { for(L=1;L<=gas->MSP;L++) { file_3<<"Species "<<L<<" percentage "<<output->VARS[L+35][JJ]<<endl; } } } } file_3<<endl; //PPA=0; for(int i=0;i<gas->MSP+1;i++) PPA[i]=0; for(N=1;N<=geom->NCELLS;N++) { for(M=1;M<=gas->MSP;M++){ PPA[M]=PPA[M]+output->VARSP[0][N][M]; } } // WRITE (*,*) //cin.get(); if(gas->MSP>1) { file_3<<"GAINS FROM REACTIONS"<<endl; file_3<<" Dissoc. Recomb. Endo. Exch. Exo. Exch."<<endl; for(M=1;M<=gas->MSP;M++){ file_3<<" SPECIES "<<M<<" "<<gas->TREACG[1][M]<<" "<<gas->TREACG[2][M]<<" "<<gas->TREACG[3][M]<<" "<<gas->TREACG[4][M]<<endl; } file_3<<endl; file_3<<"LOSSES FROM REACTIONS"<<endl; file_3<<" Dissoc. Recomb. Endo. Exch. Exo. Exch."<<endl; for(M=1;M<=gas->MSP;M++){ file_3<<" SPECIES "<<M<<" "<<gas->TREACL[1][M]<<" "<<gas->TREACL[2][M]<<" "<<gas->TREACL[3][M]<<" "<<gas->TREACL[4][M]<<endl; } file_3<<endl; file_3<<"TOTALS"<<endl; for(M=1;M<=gas->MSP;M++){ file_3<<" SPECIES "<<M<<" GAINS "<<gas->TREACG[1][M]+gas->TREACG[2][M]+gas->TREACG[3][M]+gas->TREACG[4][M]<<" LOSSES "<<gas->TREACL[1][M]+gas->TREACL[2][M]+gas->TREACL[3][M]+gas->TREACL[4][M]<<endl; } } file_3<<endl; file_3<<"Flowfield properties "<<endl; file_3<< output->NSAMP<<" Samples"<<endl; file_3<<"Overall gas"<<endl; file_3<<"Cell x coord. Sample Number Dens. Density u velocity v velocity w velocity Trans. Temp. Rot. Temp. Vib. Temp. El. Temp. Temperature Mach no. Mols/cell m.c.t m.f.p mcs/mfp speed Pressure TTX TTY TTZ Species Fractions "<<endl; for(N=1;N<=geom->NCELLS;N++) { file_3<< N<<" "; for(M=1;M<=10;M++){ file_3<<output->VAR[M][N]<<" "; } file_3<<output->VAR[22][N]<<" "; for(M=11;M<=21;M++){ file_3<<output->VAR[M][N]<<" "; } for(L=1;M<=gas->MSP;M++){ file_3<<output->VARSP[1][N][L]<<" "; } file_3<<endl; } file_3<<"Individual molecular species"<<endl; for(L=1;L<=gas->MSP;L++){ file_3<<"Species "<<L<<endl; file_3<<"Cell x coord. Sample Percentage Species TTx Species TTy Species TTz Trans. Temp. Rot. Temp. Vib. Temp. Spec. Temp u Diff. Vel. v Diff. Vel. w. Diff. Vel. Elec. Temp."<<endl; for(N=1;N<=geom->NCELLS;N++){ file_3<< N<<" "<<output->VAR[1][N]<<" "; for(M=0;M<=12;M++) file_3<<output->VARSP[M][N][L]<<" "; file_3<<endl; } } //dout //999 FORMAT (I5,30G13.5) //998 FORMAT (G280.0) // 997 FORMAT (G188.0) // CLOSE (3) file_3.close(); } if(calc->ICLASS==0 && calc->ISF==1){ //--a homogeneous gas and the "unsteady sampling" option has been chosen-ASSUME THAT IT IS A RELAXATION TEST CASE FOR SECTION 6.2 INITIALISE_SAMPLES(); //write a special output file for internal temperatures and temperature versus collision number //dout file_10.open("RELAX.DAT", ios::app | ios::out); if(file_10.is_open()){ cout<<"RELAX.DAT is opened"<<endl; } else{ cout<<"RELAX.DAT not opened"<<endl; } // OPEN (10,FILE='RELAX.DAT',ACCESS='APPEND') A=2.0*calc->TOTCOL/molecs->NM; //--mean collisions //--VAR(11,N) //--overall //--VAR(8,N) //--translational //--VAR(9,N) //--rotational //--VAR(10,N) //--vibrational //--VAR(22,N) //--electronic file_10<<setw(15)<<A<<setw(15)<<output->VAR[8][1]<<setw(15)<<output->VAR[9][1]<<setw(15)<<output->VAR[8][1]-output->VAR[9][1]<<endl; //file_10<<A<<"\t"<<output->VAR[11][1]<<"\t"<<output->VAR[8][1]<<"\t"<<output->VAR[9][1]<<"\t"<<output->VAR[10][1]<<"\t"<<output->VAR[22][1]<<endl; //file_10<<A<<"\t"<<output->VAR[8][1]<<"\t"<<output->VAR[9][1]<<"\t"<<output->VAR[8][1]-output->VAR[9][1]<<endl; // WRITE (10,950) A,VAR(8,1),VAR(9,1),VAR(8,1)-VAR(9,1) //--Generates output for Figs. 6.1 and 6.2 // WRITE (10,950) A,VAR(11,1),VAR(8,1),VAR(9,1),VAR(10,1),VAR(22,1) //--Generates output for modal temperatures in Figs. 6.3, 6.5 + // WRITE (10,950) A,0.5D00*(VAR(8,1)+VAR(9,1)),VAR(10,1),0.5D00*(VAR(8,1)+VAR(9,1))-VAR(10,1) //--Generates output for Figs. 6.4 // //--VARSP(8,N,L) //--overall temperature of species L // WRITE (10,950) A,VARSP(8,1,3),VARSP(8,1,2),VARSP(8,1,5),VARSP(8,1,4),A //--output for Fig 6.17 // CLOSE (10) file_10.close(); } //dout // 950 FORMAT (6G13.5) if(gas->IGAS==8||gas->IGAS==6||gas->IGAS==4) { //--Write a special output file for the composition of a reacting gas as a function of time //dout //OPEN (10,FILE='COMPOSITION.DAT',ACCESS='APPEND') file_10.open("COMPOSITION.DAT", ios::app | ios::out); if(file_10.is_open()){ cout<<"COMPOSITION.DAT is opened"<<endl; } else{ cout<<"COMPOSITION.DAT not opened"<<endl; } AS=molecs->NM; //dout AT=calc->FTIME*1.e6; if (gas->IGAS == 4) file_10<< AT <<" "<<(double)(NMS[1])/1000000<<" "<<A<<" "<<output->VAR[11][1]<<endl; //--Data for fig if (gas->IGAS == 8) file_10<<AT<<" "<<NMS[1]/AS<<" "<<NMS[2]/AS<<" "<<NMS[3]/AS<<" "<<NMS[4]/AS<<" "<<NMS[5]/AS<<" "<<NMS[6]/AS<<" "<<NMS[7]/AS<<" "<<NMS[8]/AS<<" "<<output->VAR[11][1]<<endl; if (gas->IGAS == 6) file_10<<AT<<" "<<NMS[1]/AS<<" "<<NMS[2]/AS<<" "<<NMS[3]/AS<<" "<<NMS[4]/AS<<" "<<NMS[5]/AS<<" "<<output->VAR[11][1]<<endl; //dout // 888 FORMAT(10G13.5) file_10.close(); } if(calc->FTIME>0.5e00*calc->DTM){ // //--reset collision and transit times etc. // cout<<"Output files written "<<endl; DTMI=calc->DTM; if(calc->IMTS<2){ if(calc->ICLASS>0) calc->DTM*=2; //--this makes it possible for DTM to increase, it will be reduced as necessary for(NN=1;NN<=geom->NCELLS;NN++) { CDTM[NN]=calc->DTM; B=geom->CELL[3][NN]-geom->CELL[2][NN] ;//--sampling cell width if(output->VAR[13][NN]>20.e00){ //consider the local collision rate CDTM[NN]=output->VAR[14][NN]*calc->CPDTM; //look also at sampling cell transit time based on the local flow speed A=(B/(fabs(output->VAR[5][NN])))*calc->TPDTM; if(A<CDTM[NN]) CDTM[NN]=A; } else{ //-- base the time step on a sampling cell transit time at the refence vmp A=calc->TPDTM*B/gas->VMPM; if(A<CDTM[NN]) CDTM[NN]=A; } if(CDTM[NN]<calc->DTM) calc->DTM=CDTM[NN]; } } else { //dout //memset(CDTM, calc->DTM, sizeof(*CDTM)); for(int i=0;i<geom->NCELLS+1;i++) CDTM[i]= calc->DTM; //CDTM=calc->DTM; } for(N=1;N<=geom->NCELLS;N++){ NN=geom->ICCELL[3][N]; geom->CCELL[3][N]=0.5*CDTM[NN]; } file_9<<"DTM changes from "<<DTMI<<" to "<<calc->DTM<<endl; calc->DTSAMP=calc->DTSAMP*calc->DTM/DTMI; calc->DTOUT=calc->DTOUT*calc->DTM/DTMI; } else { INITIALISE_SAMPLES(); } if(calc->ICLASS==1&& calc->ISF==1) { //************************************************************************* //--write TECPLOT data files for x-t diagram (unsteady calculation only) //--comment out if not needed //dout file_18.open("DS1xt.DAT", ios::app | ios::out); if(file_18.is_open()){ cout<<"DS1xt.DAT is opened"<<endl; } else cout<<"DS1xt.DAT not opened"<<endl; // OPEN (18,FILE='DS1xt.DAT',ACCESS='APPEND') //--make sure that it is empty at the stary of the run SETXT(); // CLOSE (18) file_18.close(); //************************************************************************** } //WRITE (19,*) calc->FTIME,-output->VARS[5][1],-output->VARS[5][1]-output->VARS[6][1] file_7.open("PROFILE.DAT" , ios::out); if(file_7.is_open()){ cout<<"PROFILE.DAT is opened"<<endl; } else cout<<"PROFILE.DAT not opened"<<endl; // OPEN (7,FILE='PROFILE.DAT',FORM='FORMATTED') // //OPEN (8,FILE='ENERGYPROF.DAT',FORM='FORMATTED') // // 995 FORMAT (22G13.5) // 996 FORMAT (12G14.6) for(N=1;N<=geom->NCELLS;N++) { // //--the following line is the default output // WRITE (7,995) VAR(1,N),VAR(4,N),VAR(3,N),VAR(11,N),VAR(18,N),VAR(5,N),VAR(12,N),VAR(8,N),VAR(9,N),VAR(10,N),VAR(22,N), & // (VARSP(8,N,M),M=1,MSP),(VARSP(1,N,M),M=1,MSP) // //--calculate energies per unit mass (employed for re-entry shock wave in Section 7.5) C1=0.5e00*pow(output->VAR[5][N],2); //--Kinetic C2=0.e00; //--Thermal C3=0.e00; //--Rotational C4=0.e00; //--Vibrational C5=0.e00; //--Electronic C6=0.e00; //--Formation for(L=1;L<=gas->MSP;L++) { // C2=C2+3.D00*BOLTZ*VARSP(5,N,L)*VARSP(1,N,L)/SP(5,L) A=(output->CS[1][N][L]/output->VARSP[1][N][L])*gas->SP[5][L]; if(output->CS[1][N][L]>0.5e00){ C2=C2+0.5e00*(output->CS[5][N][L]+output->CS[6][N][L]+output->CS[7][N][L])*gas->SP[5][L]/A; if(gas->ISPR[1][L]>0) C3=C3+output->CS[8][N][L]; if(gas->ISPV[L]>0) C4=C4+output->CS[10][N][L]*BOLTZ*gas->SPVM[1][1][L]/A; if(gas->NELL[L]>1) C5=C5+output->CS[9][N][L]/A; C6=C6+gas->SP[6][L]*output->CS[1][N][L]/A; } } C2=C2-C1; // A=0.5D00*VFX(1)**2+2.5D00*BOLTZ*FTMP(1)/(0.75*SP(5,2)+0.25*SP(5,1)) C7=C1+C2+C3+C4+C5+C6; // // WRITE (8,995) VAR(1,N),C1/A,C2/A,C3/A,C4/A,C5/A,C6/A,C7/A // //--the following lines are for normalised shock wave output in a simple gas (Sec 7.3) C1=gas->FND[2]-gas->FND[1]; C2=gas->FTMP[2]-gas->FTMP[1]; file_7<<output->VAR[1][N]<<" "<<output->VAR[2][N]<<" "<<(0.5*(output->VAR[20][N]+output->VAR[21][N])-gas->FTMP[1])/C2<<" "<<(output->VAR[19][N]-gas->FTMP[1])/C2<<" "<<(output->VAR[11][N]-gas->FTMP[1])/C2<<" "<<(output->VAR[3][N]-gas->FND[1])/C1<<endl; //--the following replaces sample size with density //C3=0.D00 //DO L=1,MSP // C3=C3+FND(1)*FSP(L,1)*SP(5,L) //--upstream density //END DO //C4=0.D00 //DO L=1,MSP // C4=C4+FND(2)*FSP(L,2)*SP(5,L) //--upstream density //END DO // // WRITE (7,996) VAR(1,N),(VAR(4,N)-C3)/(C4-C3),(0.5*(VAR(20,N)+VAR(21,N))-FTMP(1))/C2,(VAR(19,N)-FTMP(1))/C2,(VAR(11,N)-FTMP(1))/C2, & // (VAR(3,N)-FND(1))/C1 //--the following lines is for a single species in a gas mixture // C1=C1*FSP(3,1) // WRITE (7,996) VAR(1,N),VARSP(1,N,3),(0.5*(VARSP(3,N,3)+VARSP(4,N,3))-FTMP(1))/C2,(VARSP(2,N,3)-FTMP(1))/C2,(VARSP(5,N,3)-FTMP(1))/C2,(VAR(3,N)*VARSP(1,N,3)-FND(1)*FSP(3,1))/C1 // //--the following line is for Couette flow (Sec 7.4) // WRITE (7,996) VAR(1,N),VAR(2,N),VAR(5,N),VAR(6,N),VAR(7,N),VAR(11,N) //--the following line is for the breakdown of equilibrium in expansions (Sec 7.10) // WRITE (7,996) VAR(1,N),VAR(2,N),VAR(12,N),VAR(4,N),VAR(5,N),VAR(8,N),VAR(9,N),VAR(10,N),VAR(11,N),VAR(19,N),VAR(20,N),VAR(21,N) // } if(calc->ISF==1) INITIALISE_SAMPLES(); // CLOSE(7) file_7.close(); // //--deallocate local variables // //dout for(int i=0;i<gas->MMVM+1;i++){ delete [] TV[i]; } delete [] TV; delete [] TVIB; delete [] VDOF; for(int i=0;i<gas->MSP+1;i++){ delete [] THCOL[i]; } delete [] THCOL; // DEALLOCATE (TV,TVIB,VDOF,THCOL,STAT=ERROR) // if(calc->ERROR) // cout<<"PROGRAM COULD NOT DEALLOCATE OUTPUT VARIABLES"<<calc->ERROR; calc->TOUT=calc->TOUT+calc->DTOUT; return; } void COLLISIONS() { //CALC calc; //MOLECS molecs; //GAS gas; //OUTPUT output; //GEOM_1D geom; start= clock(); double duration; int N,NN,M,MM,L,LL,K,KK,KT,J,I,II,III,NSP,MAXLEV,IV,NSEL,KV,LS,MS,KS,JS,IIII,LZ,KL,IS,IREC,NLOOP,IA,IDISS,IEX,NEL,NAS,NPS, JJ,LIMLEV,KVV,KW,INIL,INIM,JI,LV,IVM,NMC,NVM,LSI,JX,MOLA,KR,JKV,NSC,KKV,IAX,NSTEP,NTRY,NLEVEL,NSTATE,IK,NK,MSI ; double A,AA,AAA,AB,B,BB,BBB,ABA,ASEL,DTC,SEP,VR,VRR,ECT,EVIB,ECC,ZV,ERM,C,OC,SD,D,CVR,PROB,RML,RMM,ECTOT,ETI,EREC,ET2, XMIN,XMAX,WFC,CENI,CENF,VRRT,EA,DEN,E1,E2,VRI,VRA ; double VRC[4],VCM[4],VRCP[4],VRCT[4]; // //N,M,K working integer // //LS,MS,KS,JS molecular species // //VRC components of the relative velocity // //RML,RMM molecule mass parameters // //VCM components of the center of mass velocity // //VRCP post-collision components of the relative velocity // //SEP the collision partner separation // //VRR the square of the relative speed // //VR the relative speed // //ECT relative translational energy // //EVIB vibrational energy // //ECC collision energy (rel trans +vib) // //MAXLEV maximum vibrational level // //ZV vibration collision number // //SDF the number of degrees of freedom associated with the collision // //ERM rotational energy // //NSEL integer number of selections // //NTRY number of attempts to find a second molecule // //CVR product of collision cross-section and relative speed // //PROB a probability // //KT third body molecule code // //ECTOT energy added at recmbination // //IREC initially 0, becomes 1 of a recombination occurs // //WFC weighting factor in the cell // //IEX is the reaction that occurs (1 if only one is possible) // //EA activation energy // //NPS the number of possible electronic states // //NAS the number of available electronic states //cout<<"START COLLISIONS"<<endl; // dout cout<<geom->XB[1]<<" "<<geom->XB[2]<<endl; for( N=1;N<=geom->NCCELLS;N++) { if((calc->FTIME-geom->CCELL[5][N])>geom->CCELL[3][N]) { // cout<<N <<" "<<geom->CCELL[3][N]<<endl; DTC=2.e00*geom->CCELL[3][N]; //calculate collisions appropriate to time DTC if(geom->ICCELL[2][N]>1) { //no collisions calculated if there are less than two molecules in collision cell NN=geom->ICCELL[3][N]; WFC=1.e00; if(geom->IWF==1 && geom->IVB==0) { //dout WFC=1.e00+geom->WFM*pow(geom->CELL[1][NN],geom->IFX); } geom->CCELL[5][N]=geom->CCELL[5][N]+DTC; if(geom->IVB==0) { AAA=geom->CCELL[1][N]; } if(geom->IVB==1) { C=(geom->XB[2]+geom->VELOB*calc->FTIME-geom->XB[1])/(double)(geom->NDIV*geom->NCIS); //dout XMIN=geom->XB[1]+(double)(N-1)*C; XMAX=XMIN+C; //dout WFC=1.e00+geom->WFM*pow((0.5e00*(XMIN+XMAX)),geom->IFX); if(geom->IFX==0) { AAA=XMAX-XMIN; } if(geom->IFX==1) { AAA=PI*(pow(XMAX,2)-pow(XMIN,2)); //assumes unit length of full cylinder } if(geom->IFX==2) { AAA=1.33333333333333333333e00*PI*(pow(XMAX,3)-pow(XMIN,3)); //flow is in the full sphere } } //these statements implement the N(N-1) scheme ASEL=0.5e00*geom->ICCELL[2][N]*(geom->ICCELL[2][N]-1)*WFC*calc->FNUM*geom->CCELL[4][N]*DTC/AAA+geom->CCELL[2][N]; NSEL=ASEL; //dout geom->CCELL[2][N]=ASEL-(double)(NSEL); if(NSEL>0) { I=0; //counts the number of selections KL=0; //becomes 1 if it is the last selection IIII=0; //becomes 1 if there is a recombination for(KL=1;KL<=NSEL;KL++) { I=I+1; III=0; //becomes 1 if there is no valid collision partner if(geom->ICCELL[2][N]==2) { K=1+geom->ICCELL[1][N]; //dout L=molecs->ICREF[K]; K=2+geom->ICCELL[1][N]; //dout M=molecs->ICREF[K]; if(M==molecs->IPCP[L]) { III=1; geom->CCELL[5][N]=geom->CCELL[5][N]-DTC; } } else { //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); K=(int)(calc->RANF*(double)(geom->ICCELL[2][N]))+geom->ICCELL[1][N]+1; //dout L=molecs->ICREF[K]; //one molecule has been selected at random if(calc->NNC==0) { //select the collision partner at random M=L; NTRY=0; while(M==L) { //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); K=(int)(calc->RANF*(double)(geom->ICCELL[2][N]))+geom->ICCELL[1][N]+1; M=molecs->ICREF[K]; if(M==molecs->IPCP[L]) { if(NTRY<5*geom->ICCELL[2][N]) { M=L; } else { III = 1; geom->CCELL[5][N]=geom->CCELL[5][N]-DTC/ASEL; M=L+1; } } } } else { //elect the nearest from the total number (< 30) or a random 30 if(geom->ICCELL[2][N]<30) { LL=geom->ICCELL[2][N]; } else { LL=30; } SEP=1.0e10; M=0; for(J=1;J<=LL;J++) { if(LL<30) { K=J+geom->ICCELL[1][N]; } else { // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); K=(int)(calc->RANF*(double)(geom->ICCELL[2][N]))+geom->ICCELL[1][N]+1; } MM=molecs->ICREF[K]; if(MM != L) { //exclude the already selected molecule if(MM != molecs->IPCP[L]) { //exclude the previous collision partner //dout A=fabs(molecs->PX[1][L]-molecs->PX[1][MM]); if(A<SEP&& A>1.e-8*geom->DDIV) { M=MM; SEP=A; } } } } } } if(III==0) { for(KK=1;KK<=3;KK++) { VRC[KK]=molecs->PV[KK][L]-molecs->PV[KK][M]; } VRR=VRC[1]*VRC[1]+VRC[2]*VRC[2]+VRC[3]*VRC[3]; VR=sqrt(VRR); VRI=VR; //Simple GAs if(gas->MSP==1) { //dout CVR=VR*gas->CXSS*pow(2.e00*BOLTZ*gas->SP[2][1]/(gas->RMAS*VRR),(gas->SP[3][1]-0.5e00))*gas->RGFS; if(CVR>geom->CCELL[4][N]) { geom->CCELL[4][N]=CVR; } //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); if(calc->RANF<CVR/geom->CCELL[4][N]) { // the collision occurs if(M==molecs->IPCP[L]&& L==molecs->IPCP[M]) { file_9<<"Duplicate collision"<<endl; } calc->TOTCOL=calc->TOTCOL+1.e00; calc->TCOL[1][1]=calc->TCOL[1][1]+2.e00; output->COLLS[NN]=output->COLLS[NN]+1.e000; output->WCOLLS[NN]=output->WCOLLS[NN]+WFC; //dout SEP=fabs(molecs->PX[1][L]-molecs->PX[1][M]); output->CLSEP[NN]=output->CLSEP[NN]+SEP; if(gas->ISPR[1][1]>0) { //Larsen-Borgnakke serial redistribution ECT=0.5e00*gas->RMAS*VRR; for(NSP=1;NSP<=2;NSP++) { //consider the molecules in turn if(NSP==1) { K=L; } else { K=M; } if(gas->MMVM>0) { if(gas->ISPV[1]>0) { for(KV=1;KV<=gas->ISPV[1];KV++) { EVIB=(double)(molecs->IPVIB[KV][K]*BOLTZ*gas->SPVM[1][KV][1]); ECC=ECT+EVIB; if(gas->SPVM[3][KV][1]>0.0) { MAXLEV=ECC/(BOLTZ*gas->SPVM[1][KV][1]); B=gas->SPVM[4][KV][1]/gas->SPVM[3][KV][1]; //Tdiss/Tref A= gas->SPVM[4][KV][1]/output->VAR[8][NN] ;//Tdiss/Ttrans //ZV=(A**SPM(3,1,1))*(SPVM(3,KV,1)*(B**(-SPM(3,1,1))))**(((A**0.3333333D00)-1.D00)/((B**0.33333D00)-1.D00)) ZV=pow(A,gas->SPM[3][1][1])*pow(gas->SPVM[3][KV][1]*pow(B,-gas->SPM[3][1][1]),((pow(A,0.3333333e00)-1e00)/(pow(B,33333e00)-1.e00))); } else { ZV=gas->SPVM[2][KV][1]; MAXLEV=ECC/(BOLTZ*gas->SPVM[1][KV][1])+1; } //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); if(1.e00/ZV>calc->RANF) { II=0; while(II==0) { //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); IV=calc->RANF*(MAXLEV+0.99999999e00); molecs->IPVIB[KV][K]=IV; EVIB=(double)(IV)*BOLTZ; if(EVIB<ECC) { PROB=pow((1.e00-EVIB/ECC),(1.5e00-gas->SPM[3][KV][1])); //PROB is the probability ratio of eqn (3.28) //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); if(PROB>calc->RANF) II=1; } } ECT=ECC-EVIB; } } } } //now rotation of this molecule //dout if(gas->ISPR[1][1] > 0) { if(gas->ISPR[2][1]==0) { B=1.e00/gas->SPR[1][1]; } else //use molecule rather than mean value { B=1.e00/(gas->SPR[1][1]+gas->SPR[2][1]*output->VAR[8][NN]+gas->SPR[3][1]*pow(output->VAR[8][NN],2)); } //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); if(B>calc->RANF) { ECC=ECT +molecs->PROT[K]; if(gas->ISPR[1][1]==2) { //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); ERM=1.e00-pow(calc->RANF,1.e00/(2.5e00-gas->SP[3][1])); //eqn(5.46) } else { //dout LBS(0.5e00*gas->ISPR[1][1]-1.e00,1.5e00-gas->SP[3][1],ERM); } molecs->PROT[K]=ERM*ECC; ECT=ECC-molecs->PROT[K]; } } } //adjust VR for the change in energy; VR=sqrt(2.e00*ECT/gas->SPM[1][1][1]); } //end of L-B redistribution for(KK=1;KK<=3;KK++) { VCM[KK]=0.5e00*(molecs->PV[KK][L]+molecs->PV[KK][M]); } //dout if(fabs(gas->SP[4][1]-1.0) < 0.001) { //use the VHS logic //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); B=2.e00*calc->RANF-1.e00; //B is the cosine of a random elevation angle A=sqrt(1.e00-B*B); VRCP[1]=B*VR; //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); C=2.e00*PI*calc->RANF; //C is a random azimuth angle //dout VRCP[2]=A*cos(C)*VR; VRCP[3]=A*sin(C)*VR; } else { //use the VSS logic //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); B=2.e00*(pow(calc->RANF,gas->SP[4][1]))-1.e00; //B is the cosine of the deflection angle for the VSS model (Eqn. 11.8) of Bird(1994)) A=sqrt(1.e00-B*B); //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); C=2.e00*PI*calc->RANF; //dout OC=(double)cos(C); SD=(double)sin(C); D=sqrt(pow(VRC[2],2)+pow(VRC[3],2)); VRA=VR/VRI; VRCP[1]=(B*VRC[1]+A*SD*D)*VRA; VRCP[2]=(B*VRC[2]+A*(VRI*VRC[3]*OC-VRC[1]*VRC[2]*SD)/D)*VRA; VRCP[3]=(B*VRC[2]+A*(VRI*VRC[2]*OC-VRC[1]*VRC[3]*SD)/D)*VRA; //the post-collision rel. velocity components are based on eqn (3.18) } for(KK=1;KK<=3;KK++) { molecs->PV[KK][L]=VCM[KK]+0.5e00*VRCP[KK]; molecs->PV[KK][M]=VCM[KK]-0.5e00*VRCP[KK]; } molecs->IPCP[L]=M; molecs->IPCP[M]=L; } } //collision occurrence else { //Gas Mixture LS=fabs(molecs->IPSP[L]); MS=fabs(molecs->IPSP[M]); CVR=VR*gas->SPM[2][LS][MS]*pow(((2.e00*BOLTZ*gas->SPM[5][LS][MS])/((gas->SPM[1][LS][MS])*VRR)),(gas->SPM[3][LS][MS]-0.5e00))*gas->SPM[6][LS][MS]; if(CVR>geom->CCELL[4][N]) { geom->CCELL[4][N]=CVR; } //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); if(calc->RANF<CVR/geom->CCELL[4][N] && molecs->IPCELL[L]>0 && molecs->IPCELL[M]>0) { //the collision occurs (-ve IPCELL indicates recombined molecule marled for removal) if(M==molecs->IPCP[L] && L==molecs->IPCP[M]) { file_9<<"Duplicate collision"; } calc->TOTCOL=calc->TOTCOL+1.e00; calc->TCOL[LS][MS]=calc->TCOL[LS][MS]+1.e00; calc->TCOL[MS][LS]=calc->TCOL[MS][LS]+1.e00; output->COLLS[NN]=output->COLLS[NN]+1.e00; output->WCOLLS[NN]=output->WCOLLS[NN]+WFC; SEP=fabs(molecs->PX[1][L]-molecs->PX[1][M]); output->CLSEP[NN]=output->CLSEP[NN]+SEP; RML=gas->SPM[1][LS][MS]/gas->SP[5][MS]; RMM=gas->SPM[1][LS][MS]/gas->SP[5][LS]; for(KK=1;KK<=3;KK++) { VCM[KK]=RML*molecs->PV[KK][L]+RMM*molecs->PV[KK][M]; } IDISS=0; IREC=0; IEX=0; //check for dissociation if(gas->ISPR[1][LS]>0 || gas->ISPR[1][MS]>0) { ECT=0.5e00*gas->SPM[1][LS][MS]*VRR; for(NSP=1;NSP<=2;NSP++) { if(NSP==1) { K=L; KS=LS; JS=MS; } else { K=M ; KS=MS ; JS=LS; } if(gas->MMVM>0) { if(gas->ISPV[KS]>0) { for(KV=1;KV<=gas->ISPV[KS];KV++) { if(molecs->IPVIB[KV][K]>=0 && IDISS==0) { //do not redistribute to a dissociating molecule marked for removal EVIB=(double)(molecs->IPVIB[KV][K]*BOLTZ*gas->SPVM[1][KV][KS]); ECC=ECT+EVIB; MAXLEV=ECC/(BOLTZ*gas->SPVM[1][KV][KS]); LIMLEV=gas->SPVM[4][KV][KS]/gas->SPVM[1][KV][KS]; if(MAXLEV > LIMLEV) { //dissociation occurs subject to reduction factor - reflects the infinity of levels past the dissociation limit //dout // RANDOM_NUMBER(RANF) calc->RANF=((double)rand()/(double)RAND_MAX); if(calc->RANF<gas->SPVM[5][KV][KS]) { IDISS=1; LZ=molecs->IPVIB[KV][K]; output->NDISSL[LZ]=output->NDISSL[LZ]+1; ECT=ECT-BOLTZ*gas->SPVM[4][KV][KS]+EVIB; //adjust VR for the change in energy VRR=2.e00*ECT/gas->SPM[1][LS][MS]; VR=sqrt(VRR); molecs->IPVIB[KV][K]=-1; //a negative IPVIB marks a molecule for dissociation } } } } } } } } IEX=0; //becomes the reaction number if a reaction occurs IREC=0; //becomes 1 if a recombination occurs if(IDISS==0) { //dissociation has not occurred //consider possible recombinations if(gas->ISPRC[LS][MS]>0 && geom->ICCELL[2][N]>2) { //possible recombination using model based on collision volume for equilibrium KT=L; //NTRY=0 while(KT==L||KT==M) { NTRY+=1; // if(NTRY>100) // { // cout>>"NTRY 3rd body"<<NTRY; // } //RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX);\ K=(int)(calc->RANF*(double)(geom->ICCELL[2][N]))+geom->ICCELL[1][N]+1; KT=molecs->ICREF[K]; } KS=molecs->IPSP[KT]; //the potential third body is KT OF species KS AA=(PI/6.e00)*pow((gas->SP[1][LS]+gas->SP[1][MS]+gas->SP[1][KS]),3); //reference volume BB=AA*gas->SPRC[1][LS][MS][KS]*pow(output->VAR[8][NN]/gas->SPVM[1][gas->ISPRK[LS][MS]][gas->ISPRC[LS][MS]],gas->SPRC[2][LS][MS][KS]);//collision volume B=BB*geom->ICCELL[2][N]*calc->FNUM/AAA; if(B>1.e00) { cout<<"THREE BODY PROBABILITY"<<B; //for low density flows in which three-body collisions are very rare, it is advisable to consider recombinations in only a small //fraction of collisions and to increase the pribability by the inverse of this fraction. This message provides a warning if this //factor has been set to an excessively large value } //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); if(calc->RANF<B) { IREC=1; calc->TRECOMB[gas->ISPRC[LS][MS]]=calc->TRECOMB[gas->ISPRC[LS][MS]]+1.e00; //the collision now becomes a collision between these with L having the center of mass velocity A=0.5e00*gas->SPM[1][LS][MS]*VRR ;//the relative energy of the recombining molecules if(gas->ISPR[1][LS]>0) A=A+molecs->PROT[L]; if(gas->MELE>1) A=A+molecs->PELE[L]; if(gas->ISPV[LS]>0) { for(KVV=1;KVV<=gas->ISPV[LS];KVV++) { JI=molecs->IPVIB[KVV][L]; if(JI<0) JI=-JI; if(JI==99999) JI=0; A=A+(double)(JI)*BOLTZ*gas->SPVM[1][KVV][LS]; } } if(gas->ISPR[1][MS]>0) A+=molecs->PROT[M]; if(gas->MELE>1) A=A+molecs->PELE[M]; if(gas->ISPV[MS]>0) { for(KVV=1;KVV<=gas->ISPV[MS];KVV++) { JI=molecs->IPVIB[KVV][M]; if(JI<0) JI=-JI; if(JI==99999) JI=0; A=A+(double)(JI)*BOLTZ*gas->SPVM[1][KVV][MS]; } } gas->TREACL[2][LS]=gas->TREACL[2][LS]-1; gas->TREACL[2][MS]=gas->TREACL[2][MS]-1; LSI=LS; MSI=MS; LS=gas->ISPRC[LS][MS]; molecs->IPSP[L]=LS; //any additional vibrational modes must be set to zero IVM=gas->ISPV[LSI]; NMC=molecs->IPSP[L]; NVM=gas->ISPV[NMC]; if(NVM>IVM) { for(KV=IVM+1;KV<=NVM;KV++) { molecs->IPVIB[KV][L]=0; } } if(gas->MELE>1) molecs->PELE[KV]=0.e00; molecs->IPCELL[M]=-molecs->IPCELL[M]; //recombining molecule M marked for removal M=KT; //third body molecule is set as molecule M MS=KS; gas->TREACG[2][LS]=gas->TREACG[2][LS]+1; if(gas->ISPR[1][LS]>0) { molecs->PROT[L]=0.e00; } if(gas->MELE>1) molecs->PELE[L]=0.e00; if(gas->ISPV[LS]>0) { for(KVV=1;KVV<=gas->ISPV[LS];KVV++) { if(molecs->IPVIB[KVV][L]<0) { molecs->IPVIB[KVV][L]=-99999; } else { molecs->IPVIB[KVV][L]=0; } } } if(gas->ISPR[1][MS]>0) { molecs->PROT[M]=molecs->PROT[KT]; } if(gas->MELE>1) molecs->PELE[M]=molecs->PELE[KT]; if(gas->ISPV[MS]>0) { for(KVV=1;KVV<=gas->ISPV[MS];KVV++) { molecs->IPVIB[KVV][M]=molecs->IPVIB[KVV][KT]; } } ECTOT=A+gas->SPVM[4][1][LS]*BOLTZ ; //the energy added to this collision for(KK=1;KK<=3;KK++) { molecs->PV[KK][L]=VCM[KK]; } for(KK=1;KK<=3;KK++) { VRC[KK]=molecs->PV[KK][L]-molecs->PV[KK][M]; } VRR=VRC[1]*VRC[1]+VRC[2]*VRC[2]+VRC[3]*VRC[3]; ECT=0.5e00*gas->SPM[1][LS][MS]*VRR*ECTOT; //set the vibrational energy of the recombined molecule L to enforce detailed balance IK=-1; NK=-1; //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); //NTRY=0; while(IK<0) { // NTRY+=1; // if(NTRY>100) // cout<<"NTRY VibEn"<<NTRY; NK=NK+1; BB=(output->VAR[8][NN]-gas->SPRT[1][LSI][MSI])*(gas->SPRP[2][LSI][MSI][NK]-gas->SPRP[1][LSI][MSI][NK])/(gas->SPRT[2][LSI][MSI]-gas->SPRT[1][LSI][MSI])-gas->SPRP[1][LSI][MSI][NK]; if(calc->RANF<BB) IK=NK; } molecs->IPVIB[1][L]=IK; ECT=ECT-(double)(IK)*BOLTZ*gas->SPVM[1][gas->ISPRK[LSI][MSI]][LS]; VRR=2.e00*ECT/gas->SPM[1][LS][MS]; VR=sqrt(VRR); RML=gas->SPM[1][LS][MS]/gas->SP[5][MS]; RMM=gas->SPM[1][LS][MS]/gas->SP[5][LS]; for(KK=1;KK<=3;KK++) { VCM[KK]=RML*molecs->PV[KK][L]+RMM*molecs->PV[KK][M]; } } } //consider exchange and chain reactions if(gas->NSPEX[LS][MS]>0 && IREC==0 && IDISS==0) { //possible exchange reaction //memset(gas->PSF,0.e00,sizeof(*gas->PSF));//gas->PSF=0.e00; //PSF(MMEX) PSF is the probability that this reaction will occur in this collision for(int i=0;i<gas->MMEX+1;i++) gas->PSF[i]=0.e00; for(JJ=1;JJ<=gas->NSPEX[LS][MS];JJ++) { if(LS==gas->ISPEX[JJ][1][LS][MS]) { K=L; KS=LS;JS=MS; } else { K=M; KS=MS; JS=LS; } //the pre-collision molecule that splits is K of species KS if(gas->SPEX[3][JJ][LS][MS]<0.e00) KV=gas->ISPEX[JJ][5][LS][MS]; if(gas->SPEX[3][JJ][LS][MS]>0.e00) { KV=gas->ISPEX[JJ][7][LS][MS]; } JI=molecs->IPVIB[KV][K]; if(JI<0) JI=-JI; if(JI==99999) JI=0; ECC=0.5e00*gas->SPM[1][LS][MS]*VRR+(double)(JI)*BOLTZ*gas->SPVM[1][KV][KS]; if(gas->SPEX[3][JJ][KS][JS]>0.e00) { //reverse exothermic reaction gas->PSF[JJ]=(gas->SPEX[1][JJ][KS][JS]*pow(output->VAR[8][NN]/273.e00,gas->SPEX[2][JJ][KS][JS]))*exp(-gas->SPEX[6][JJ][KS][JS]/(BOLTZ*output->VAR[8][NN])); } else { //forward endothermic reaction MAXLEV=ECC/(BOLTZ*gas->SPVM[1][KV][KS]); EA=fabs(gas->SPEX[3][JJ][KS][JS]); //temporarily just the heat of reaction; if(ECC>EA) { //the collision energy must exceed the heat of reaction EA=EA+gas->SPEX[6][JJ][KS][JS]; //the activation energy now includes the energy barrier DEN=0.e00; for(IAX=0;IAX<=MAXLEV;IAX++) { DEN=DEN+pow((1.e00-(double)(IAX)*BOLTZ*gas->SPVM[1][KV][KS]/ECC),(1.5e00-gas->SPM[3][KS][JS])); } gas->PSF[JJ]=(double)(gas->ISPEX[JJ][6][LS][MS])*pow((1.e00-EA/ECC),(1.5e00-gas->SPM[3][KS][JS]))/DEN; } } } if(gas->NSPEX[LS][MS]>1) { BB=0.e00; for(JJ=1;JJ<=gas->NSPEX[LS][MS];JJ++) { BB=BB+gas->PSF[JJ]; } //BB is the sum of the probabilities //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); if(BB>calc->RANF) { BB=0.e00; IEX=0; JJ=0; //NTRY=0; while(JJ<gas->NSPEX[LS][MS]&& IEX==0) { // NTRY=NTRY+1; // if(NTRY>100) // { // cout<<"NTRY find IEX"<<NTRY; // } JJ+=1; BB+=gas->PSF[JJ]; if(BB>calc->RANF) IEX=JJ; } } } else { //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); IEX=0; if(gas->PSF[1]>calc->RANF) IEX=1; } if(IEX>0) { //exchange or chain reaction occurs JX=gas->NEX[IEX][LS][MS]; //cout<<"Reaction"<<JX; gas->TNEX[JX]=gas->TNEX[JX]+1.e00; //cout<<IEX<<L<<M<<LS<<MS; molecs->IPSP[L]=gas->ISPEX[IEX][3][LS][MS]; //L is now the new molecule that splits molecs->IPSP[M]=gas->ISPEX[IEX][4][LS][MS]; LSI=LS; MSI=MS; //any additional vibrational modes must be set to zero IVM=gas->ISPV[LS]; NMC=molecs->IPCP[L]; NVM=gas->ISPV[NMC]; if(NVM>IVM) { for(KV=IVM+1;KV<=NVM;KV++) { molecs->IPVIB[KV][L]=0; } } IVM=gas->ISPV[MS]; NMC=molecs->IPCP[M]; NVM=gas->ISPV[NMC]; if(NVM>IVM) { for(KV=IVM+1;KV<=NVM;KV++) { molecs->IPVIB[KV][M]=0; } } //put all pre-collision energies into the relative translational energy and adjust for the reaction energy ECT=0.5e00*gas->SPM[1][LS][MS]*VRR; if(gas->ISPR[1][LS]>0) ECT=ECT+molecs->PROT[L]; if(gas->MELE>1) ECT=ECT+molecs->PELE[L]; if(gas->ISPV[LS]>0) { for(KV=1;KV<=gas->ISPV[LS];KV++) { JI=molecs->IPVIB[KV][L]; if(JI<0) JI=-JI; if(JI==99999) JI=0; ECT=ECT+(double)(JI)*BOLTZ*gas->SPVM[1][KV][LS]; } } if(gas->ISPR[1][MS]>0) ECT=ECT+molecs->PROT[M]; if(gas->MELE>1) ECT=ECT+molecs->PELE[M]; if(gas->ISPV[MS]>0) { for(KV=1;KV<=gas->ISPV[MS];KV++) { JI=molecs->IPVIB[KV][M]; if(JI<0) JI=-JI; if(JI==99999) JI=0; ECT=ECT+(double)(JI)*BOLTZ*gas->SPVM[1][KV][MS]; } } ECT=ECT+gas->SPEX[3][IEX][LS][MS]; if(ECT<0.0) { cout<<"-VE ECT "<<ECT<<endl; cout<<"REACTION "<<JJ<<" BETWEEN "<<LS<<" "<<MS<<endl; //dout cin.get(); return ; } if(gas->SPEX[3][IEX][LS][MS]<0.e00) { gas->TREACL[3][LS]=gas->TREACL[3][LS]-1; gas->TREACL[3][MS]=gas->TREACL[3][MS]-1; LS=molecs->IPSP[L] ; MS=molecs->IPSP[M] ; gas->TREACG[3][LS]=gas->TREACG[3][LS]+1; gas->TREACG[3][MS]=gas->TREACG[3][MS]+1; } else { gas->TREACL[4][LS]=gas->TREACL[4][LS]-1; gas->TREACL[4][MS]=gas->TREACL[4][MS]-1; LS=molecs->IPSP[L] ; MS=molecs->IPSP[M] ; gas->TREACG[4][LS]=gas->TREACG[4][LS]+1; gas->TREACG[4][MS]=gas->TREACG[4][MS]+1; } RML=gas->SPM[1][LS][MS]/gas->SP[5][MS]; RMM=gas->SPM[1][LS][MS]/gas->SP[5][LS]; //calculate the new VRR to match ECT using the new molecular masses VRR=2.e00*ECT/gas->SPM[1][LS][MS]; if(gas->ISPV[LS]>0) { for(KV=1;gas->ISPV[LS];KV++) { if(molecs->IPVIB[KV][L]<0) { molecs->IPVIB[KV][L]=-99999; } else { molecs->IPVIB[KV][L]=0; } } } if(gas->ISPR[1][LS]>0) molecs->PROT[L]=0; if(gas->MELE>1) molecs->PELE[L]=0.e00; if(gas->ISPV[MS]>0) { for(KV=1;gas->ISPV[MS];KV++) { if(molecs->IPVIB[KV][M]<0) { molecs->IPVIB[KV][M]=-99999; } else { molecs->IPVIB[KV][M]=0; } } } if(gas->ISPR[1][MS]>0) molecs->PROT[M]=0; if(gas->MELE>1) molecs->PELE[M]=0.e00; //set vibrational level of product molecule in exothermic reaction to enforce detailed balance if(gas->SPEX[3][IEX][LSI][MSI]>0.e00) { //exothermic exchange or chain reaction IK=-1; //becomes 0 when the level is chosen NK=-1; //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); //NTRY=0; while(IK<0) { // NTRY=NTRY+1; // if(NTRY>100) // { // cout>>"NTRY VibProd"<<NTRY<<endl; // } NK=NK+1; BB=(output->VAR[8][NN]-gas->SPEX[4][IEX][LSI][MSI])* (gas->SPREX[2][IEX][LSI][MSI][NK]-gas->SPREX[1][IEX][LSI][MSI][NK])/(gas->SPEX[5][IEX][LSI][MSI]-gas->SPEX[4][IEX][LSI][MSI])+gas->SPREX[1][IEX][LSI][MSI][NK]; if(calc->RANF<BB) IK=NK; } if(gas->NSLEV[1][LS]>0) { IK+=gas->NSLEV[1][LS]; gas->NSLEV[1][LS]=0; } KV=gas->ISPEX[IEX][7][LSI][MSI]; molecs->IPVIB[KV][L]=IK; EVIB=(double)(IK)*BOLTZ*gas->SPVM[1][KV][LS]; ECT=ECT-EVIB; if(ECT<0.e00) { //NTRY=0; while(ECT<0.e00) { //NTRY+=1; // if(NTRY>100) // cout<<"NTRY ECT<0"<<NTRY<<endl; molecs->IPVIB[KV][L]=molecs->IPVIB[KV][L]-1; gas->NSLEV[1][LS]+=1; ECT=ECT+BOLTZ*gas->SPVM[1][KV][LS]; } } } else { //for endothermic reaction, select vibration from vib. dist. at macroscopic temperature //normal L-B selection would be from the excessively low energy after the endo. reaction KV=gas->ISPEX[IEX][5][LS][MS]; //dout SVIB(LS,output->VAR[8][NN],IK,KV); if(gas->NSLEV[2][LS]>0) { IK=IK+gas->NSLEV[2][LS]; gas->NSLEV[2][LS]=0; } molecs->IPVIB[KV][L]=IK; EVIB=(double)(IK)*BOLTZ*gas->SPVM[1][KV][LS]; ECT=ECT-EVIB; if(ECT<0.e00) { //NTRY=0; while(ECT<0.e00) { //NTRY+=1; molecs->IPVIB[KV][L]-=1; gas->NSLEV[2][LS]+=1; ECT=ECT+BOLTZ*gas->SPVM[1][KV][LS]; // if(NTRY>100) // { //cout<<"NTRY ECT<0#2"<<NTRY<<endl; // molecs->IPVIB[KV][L]=0; // ECT+=EVIB; // gas->NSLEV[2][LS]=0; // } } } } //set rotational energy of molecule L to equilibrium at the macroscopic temperature SROT(LS,output->VAR[8][NN],molecs->PROT[L]); if(gas->SLER[LS]>1.e-21) { molecs->PROT[L]+=gas->SLER[LS]; gas->SLER[LS]=1.e-21; } ECT-=molecs->PROT[L]; ABA=molecs->PROT[L]; if(ECT<0.e00) { //NTRY=0; while(ECT<0.e00) { //NTRY+=1; BB=0.5e00*molecs->PROT[L]; gas->SLER[LS]+=BB; molecs->PROT[L]=BB; ECT+=BB; // if(NTRY>100) // { // cout<<"NTRY ECT<0#3"<<NTRY<<L<<endl; // ECT+=ABA; // molecs->PROT[L]=0; // gas->SLER[LS]=1.e-21; // } } } //calculate the new VRR to match ECT using the new molecular masses VRR=2.e00*ECT/gas->SPM[1][LS][MS]; } } } //end of reactions other than the deferred dissociation action in the DISSOCIATION subroutine if(IREC==0 && IDISS==0) { //recombined redistribution already made and there is a separate subroutine for dissociation //Larsen-Borgnakke serial redistribution ECT=0.5e00*gas->SPM[1][LS][MS]*VRR; for(NSP=1;NSP<=2;NSP++) { if(NSP==1) { K=L;KS=LS;JS=MS; } else { K=M; KS=MS; JS=LS; } //now electronic energy for this molecule if(gas->MELE>1) { B=1.e00/gas->QELC[3][1][KS]; //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); if(B>calc->RANF) { NPS=0; ECC=ECT+molecs->PELE[K]; if(gas->NELL[KS]==1){ NPS=gas->QELC[1][1][KS]; //number of possible states is at least the degeneracy of the ground state } if(gas->NELL[KS]>1) { for(NEL=1;NEL<=gas->NELL[KS];NEL++) { if(ECC>BOLTZ*gas->QELC[2][NEL][KS]) NPS=NPS+gas->QELC[1][NEL][KS]; } II=0; //NTRY=0; while(II==0) { //NTRY+=1; // if(NTRY>100) // cout<<"NTRY ElecEn"<<NTRY<<endl; //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); NSTATE=ceil(calc->RANF*NPS);//random state, now determine the energy level NAS=0; NLEVEL=-1; for(NEL=1;NEL<=gas->NELL[KS];NEL++) { NAS= NAS+gas->QELC[1][NEL][KS]; if(NSTATE<=NAS && NLEVEL<0) NLEVEL=NEL; } //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); if((1.e00/(B*gas->QELC[3][NLEVEL][KS]))<calc->RANF) { II=1; } else { if(ECC>BOLTZ*gas->QELC[2][NLEVEL][KS]) { PROB=pow(1.e00-BOLTZ*gas->QELC[2][NLEVEL][KS]/ECC,(1.5e00-gas->SPM[3][KS][JS])); //dout // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); if(PROB>calc->RANF) { II=1; molecs->PELE[K]=BOLTZ*gas->QELC[2][NLEVEL][KS]; } } } } ECT=ECC-molecs->PELE[K]; } } } //now the vibrational energy for this molecule if(gas->MMVM>0 && IEX==0) { if(gas->ISPV[KS]>0) { for(KV=1;KV<=gas->ISPV[KS];KV++) { if(molecs->IPVIB[KV][K]>=0 && IDISS==0) //do not redistribute to a dissociating molecule marked for removal { EVIB=(double)(molecs->IPVIB[KV][K])*BOLTZ*gas->SPVM[1][KV][KS]; ECC=ECT+EVIB; MAXLEV=ECC/(BOLTZ*gas->SPVM[1][KV][KS]); if(gas->SPVM[3][KV][KS]>0.0) { B=gas->SPVM[4][KV][KS]/gas->SPVM[3][KV][KS]; A=gas->SPVM[4][KV][KS]/output->VAR[8][NN]; ZV = pow(A,gas->SPM[3][KS][JS])*pow((gas->SPVM[2][KV][KS]*pow(B,-gas->SPM[3][KS][JS])),((pow(A,0.3333333e00)-1.e00)/(pow(B,0.33333e00)-1.e00))); } else ZV=gas->SPVM[2][KV][KS]; // RANDOM_NUMBER(RANF) //dout calc->RANF=((double)rand()/(double)RAND_MAX); if(1.e00/ZV>calc->RANF ||IREC==1) { II=0; NSTEP=0; while(II==0 && NSTEP<100000) { NSTEP+=1; if(NSTEP>99000) { cout<<NSTEP<<" "<<ECC<<" "<<MAXLEV<<endl; //dout return ; } // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); IV=calc->RANF*(MAXLEV+0.99999999e00); molecs->IPVIB[KV][K]=IV; EVIB=(double)(IV)*BOLTZ*gas->SPVM[1][KV][KS]; if(EVIB<ECC) { PROB=pow(1.e00-EVIB/ECC,1.5e00-gas->SPVM[3][KS][JS]); //PROB is the probability ratio of eqn (3.28) // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); if(PROB>calc->RANF) II=1; } } ECT=ECC-EVIB; } } } } } //now rotation of this molecule //dout if(gas->ISPR[1][KS] > 0) { if(gas->ISPR[2][KS]==0 && gas->ISPR[2][JS]==0) { B=1.e00/gas->SPM[7][KS][JS]; } else B=1.e00/(gas->SPR[1][KS])+gas->SPR[2][KS]*output->VAR[8][NN]+gas->SPR[3][KS]*pow(output->VAR[8][NN],2); // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); if(B>calc->RANF|| IREC==1) { ECC=ECT+molecs->PROT[K]; if(gas->ISPR[1][KS]==2) { // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); ERM=1.e00-pow(calc->RANF,(1.e00/(2.5e00-gas->SPM[3][KS][JS])));//eqn(5.46) } else LBS(0.5e00*gas->ISPR[1][KS]-1.e00,1.5e00-gas->SPM[3][KS][JS],ERM); molecs->PROT[K]=ERM*ECC; ECT=ECC-molecs->PROT[K]; } } } //adjust VR for the change in energy VR=sqrt(2.e00*ECT/gas->SPM[1][LS][MS]); }//end of L-B redistribution if(fabs(gas->SPM[8][LS][MS]-1.0)<0.001) { //use the VHS logic // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); B=2.e00*calc->RANF-1.e00; //B is the cosine of a random elevation angle A=sqrt(1.e00-B*B); VRCP[1]=B*VR; // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); C=2.e00*PI*calc->RANF; //C is a random azimuth angle; VRCP[2]=A*(double)cos(C)*VR; VRCP[3]=A*(double)sin(C)*VR; } else { //use the VSS logic //the VRCP terms do not allow properly for the change in VR - see new book !STILL TO BE FIXED VRA=VR/VRI; // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); B=2.e00*pow(calc->RANF,gas->SP[4][1])-1.e00; // B is the cosine of the deflection angle for the VSS model A=sqrt(1.e00-B*B); // RANDOM_NUMBER(RANF); calc->RANF=((double)rand()/(double)RAND_MAX); C=2.e00*PI*calc->RANF; OC=(double)cos(C); SD=(double)sin(C); D=sqrt(pow(VRC[2],2)+pow(VRC[3],2)); VRCP[1]=(B*VRC[1]+A*SD*D)*VRA; VRCP[2]=(B*VRC[2]+A*(VRI*VRC[3]*OC-VRC[1]*VRC[2]*SD)/D)*VRA; VRCP[3]=(B*VRC[3]+A*(VRI*VRC[2]*OC+VRC[1]*VRC[3]*SD)/D)*VRA; //the post-collision rel. velocity components are based on eqn (3.18) } for(KK=1;KK<=3;KK++) { molecs->PV[KK][L]=VCM[KK]+RMM*VRCP[KK]; molecs->PV[KK][M]=VCM[KK]-RMM*VRCP[KK]; } molecs->IPCP[L]=M; molecs->IPCP[M]=L; //call energy(0,E2) // ! IF (Dfabs(E2-E1) > 1.D-14) read(*,*) }////collision occurrence } }//separate simplegas / mixture coding } } } } }//remove any recombined atoms duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC; std::cout<<"printf: "<< duration <<'\n'; for(N=1;N<=molecs->NM;N++) { if(molecs->IPCELL[N]<0) REMOVE_MOL(N); } return; }
1,487
#include <cstdio> #include <stdio.h> int main(void) { int a[100000]; int b[100000]; int *ary1; int *ary2; int *ary3; for(int i=0;i<100000;i++) { a[i] = i; } cudaMalloc((void**)&ary1 , 100000*sizeof(int)); cudaMalloc((void**)&ary2 , 100000*sizeof(int)); cudaMalloc((void**)&ary3 , 100000*sizeof(int)); cudaMemcpy(ary2, a, 100000*sizeof(int),cudaMemcpyHostToDevice); cudaMemcpy(ary1, a, 100000*sizeof(int),cudaMemcpyHostToDevice); for(int i=0;i<100000;i++) { ary3[i] = ary1[i] + ary2[i]; } cudaMemcpy(b, ary3 ,100000*sizeof(int),cudaMemcpyDeviceToHost); for(int i =0; i < 100000; i++) { if(i/500 ==0) { printf("%d ",i); } } cudaFree(ary1); cudaFree(ary2); cudaFree(ary3); return 0; }
1,488
#include <stdio.h> #include "cuda.h" #include "cuda_runtime.h" #define get_idx() (threadIdx.x) __global__ void sum(float *x) { int idx = get_idx(); x[idx] += 1; } int main() { int N = 32; int nbytes = N * sizeof(float); float *dx = NULL, *hx = NULL; /* allocate GPU memory */ cudaMalloc((void **)&dx, nbytes); if (dx == NULL) { printf("couldn't allocate GPU memory"); return -1; } /* allocate CPU memory */ hx = (float*) malloc(nbytes); //cudaMalloc((void **)&hx, nbytes); if (hx == NULL) { printf("couldn't allocate CPU memory"); return -2; } /* init */ printf("hx original: \n"); for (int i = 0; i < N; i++) { hx[i] = i; printf("%g\n", hx[i]); } /* copy data to GPU */ cudaMemcpy(dx, hx, nbytes, cudaMemcpyHostToDevice); /* call GPU */ sum <<<1, N>>> (dx); /* let GPU finish */ cudaThreadSynchronize(); /* copy data from GPU */ cudaMemcpy(hx, dx, nbytes, cudaMemcpyDeviceToHost); for (int i = 0; i < N; i++) { printf("%g\n", hx[i]); } return 0; }
1,489
#include "includes.h" __global__ void gray(unsigned char *In, unsigned char *Out,int Row, int Col){ int row = blockIdx.y*blockDim.y+threadIdx.y; int col = blockIdx.x*blockDim.x+threadIdx.x; if((row < Col) && (col < Row)){ Out[row*Row+col] = In[(row*Row+col)*3+2]*0.299 + In[(row*Row+col)*3+1]*0.587+ In[(row*Row+col)*3]*0.114; } }
1,490
#include <stdio.h> static __global__ void generateFilter(float* filter, float lambda, float theta, float psi, float sigma, float gamma, int2 center, int2 size) { int xCoord = blockIdx.x * blockDim.x + threadIdx.x; int yCoord = blockIdx.y * blockDim.y + threadIdx.y; float x = xCoord - center.x; float y = yCoord - center.y; float xPrime = x * cos(theta) + y * sin(theta); float yPrime = -x * sin(theta) + y * cos(theta); float harmonic = 2.0 * M_PI * xPrime / lambda + psi; float exponential = -(xPrime * xPrime + gamma * gamma * yPrime * yPrime) / (2.0 * sigma * sigma); filter[yCoord * size.x + xCoord] = exp(exponential) * cos(harmonic); } static __global__ void gaussianKernel(float* filter, float theta, float sigma, float gamma, int2 center, int2 size) { int xCoord = blockIdx.x * blockDim.x + threadIdx.x; int yCoord = blockIdx.y * blockDim.y + threadIdx.y; float x = xCoord - center.x; float y = yCoord - center.y; float xPrime = x * cos(theta) + y * sin(theta); float yPrime = -x * sin(theta) + y * cos(theta); float exponent = -(xPrime * xPrime + gamma * gamma * yPrime * yPrime) / (2.0 * sigma * sigma); filter[yCoord * size.x + xCoord] = exp(exponent) / (2.0 * M_PI * sigma * sigma); } extern "C" void gaussian(float* filter, float theta, float sigma, float gamma, int2 center, int2 size) { int filterSize = size.x; dim3 blockDim(64, 64); dim3 gridDim(filterSize / 64, filterSize / 64); gaussianKernel<<<blockDim, gridDim>>>(filter, theta, sigma, gamma, center, size); } static __global__ void harmonicKernel(float* filter, float theta, float lambda, float psi, int2 center, int2 size) { int xCoord = blockIdx.x * blockDim.x + threadIdx.x; int yCoord = blockIdx.y * blockDim.y + threadIdx.y; float x = xCoord - center.x; float y = yCoord - center.y; float xPrime = x * cos(theta) + y * sin(theta); float angle = 2.0 * M_PI * xPrime / lambda + psi; filter[(yCoord * size.x + xCoord) * 2] = cos(angle); filter[(yCoord * size.x + xCoord) * 2 + 1] = sin(angle); } extern "C" void harmonic(float* filter, float theta, float lambda, float psi, int2 center, int2 size) { int filterSize = size.x; dim3 blockDim(64, 64); dim3 gridDim(filterSize / 64, filterSize / 64); harmonicKernel<<<blockDim, gridDim>>>(filter, theta, lambda, psi, center, size); } static __global__ void multiplyRealComplexKernel(float* real, float* complex, float* result) { int realIndex = blockIdx.x * blockDim.x + threadIdx.x; int complexIndex = realIndex * 2; result[complexIndex] = real[realIndex] * complex[complexIndex]; result[complexIndex + 1] = real[realIndex] * complex[complexIndex + 1]; //result[complexIndex] = real[realIndex]; //result[complexIndex + 1] = 0; } extern "C" void multiplyRealComplex(float* real, float* complex, float* result, int numElements) { multiplyRealComplexKernel<<<numElements / 32, 32>>>(real, complex, result); } static __global__ void multiplyComplexComplexKernel(float* a, float* b, float* result) { int realIndex = (blockIdx.x * blockDim.x + threadIdx.x) * 2; int imagIndex = realIndex + 1; float areal = a[realIndex]; float acomplex = a[imagIndex]; float breal = b[realIndex]; float bcomplex = b[imagIndex]; result[realIndex] = (areal * breal) - (acomplex * bcomplex); result[imagIndex] = (areal * bcomplex) + (breal * acomplex); //result[realIndex] = breal; //result[imagIndex] = bcomplex; } extern "C" void multiplyComplexComplex(float* a, float* b, float* result, int numElements) { multiplyComplexComplexKernel<<<numElements / 64, 64>>>(a, b, result); } static __global__ void centerKernel(float* data, int2 size) { uint xCoord = blockIdx.x * blockDim.x + threadIdx.x; uint yCoord = blockIdx.y * blockDim.y + threadIdx.y; if ((xCoord + yCoord) & 1u) //if ((xCoord + yCoord) % 2 == 1) { data[(yCoord * size.x + xCoord) * 2] *= -1; data[(yCoord * size.x + xCoord) * 2 + 1] *= -1; } } extern "C" void center(float* data, int2 size) { dim3 blockDim(32, 32); dim3 gridDim(size.x / 32, size.y / 32); centerKernel<<<blockDim, gridDim>>>(data, size); } static __global__ void complexToMagnitudeKernel(float* complex, float* magnitude) { int realIndex = blockIdx.x * blockDim.x + threadIdx.x; int complexIndex = realIndex * 2; float real = complex[complexIndex]; float imag = complex[complexIndex + 1]; magnitude[realIndex] = sqrt(real * real + imag * imag) * 0.5; } extern "C" void complexToMagnitude(float* complex, float* magnitude, int numElements) { complexToMagnitudeKernel<<<32, numElements / 32>>>(complex, magnitude); } static __global__ void complexToRealKernel(float* complex, float* real) { int realIndex = blockIdx.x * blockDim.x + threadIdx.x; int complexIndex = realIndex * 2; real[realIndex] = complex[complexIndex]; } extern "C" void complextoReal(float* complex, float* real, int numElements) { complexToRealKernel<<<32, numElements / 32>>>(complex, real); } static __global__ void realToComplexKernel(float* real, float* complex) { int realIndex = blockIdx.x * blockDim.x + threadIdx.x; int complexIndex = realIndex * 2; complex[complexIndex] = real[realIndex]; complex[complexIndex + 1] = 0.0; } extern "C" void realToComplex(float* real, float* complex, int numElements) { realToComplexKernel<<<32, numElements / 32>>>(real, complex); } //takes the absolute difference and normalizes assuming that the range is [0,512] static __global__ void differenceImagesKernel(float* a, float* b, float* result, float scale) { int index = (blockIdx.x * blockDim.x + threadIdx.x)*2; //result[index] = abs( a[index] - b[index] ) * (1.0 / 512.0) * scale; //result[index] = abs( a[index] - b[index] ) * (1.0 / 255.0) * scale; result[index] = abs( a[index] - b[index] ) * (1.0f / 255.0f); //result[index] = abs( a[index]); result[index + 1] = 0.0f; } extern "C" void differenceImages(float* a, float* b, float* result, int numElements) { differenceImagesKernel<<<numElements / 64, 64>>>(a, b, result, (1.0f / (float)numElements)); } static __global__ void computeAveragesKernel(float* a, float* result, int2 size, int2 pSize, int2 offset, float scale) { extern __shared__ float tmpArr[]; float total = 0.0f; int tmpArrIndex = threadIdx.x; int startIndex = 2*( pSize.x * (offset.y + size.y / gridDim.y * blockIdx.y + threadIdx.x) + offset.x + (size.x / gridDim.x * blockIdx.x) ); int endIndex = startIndex + 2*(size.x / gridDim.x); for(int i=startIndex; i<endIndex; i+=2) //total += a[i]; total += abs(a[i]); // Save partial average tmpArr[tmpArrIndex] = total / (float)(size.x / gridDim.x); __syncthreads(); if( threadIdx.x == 0 ) { int tmpArrSize = blockDim.x; total = 0.0f; for(int i=0; i<tmpArrSize; i++) { total += tmpArr[i]; } // Save average of partial averages //the index is for the smaller result grid float r = total * scale / (float)tmpArrSize; result[gridDim.x*blockIdx.y + blockIdx.x] = r < 0.0f? 0.0f : r > 1.0f? 1.0f: r; //result[gridDim.x*blockIdx.y + blockIdx.x] = 0.5f + 0.5f * scale * total / (float)tmpArrSize; } } static __global__ void computeMinMaxKernel(float* a, float* minMax, int2 divFactor) { extern __shared__ float tmpMinMaxArr[]; int index = threadIdx.x * divFactor.x; int endIndex = index + divFactor.x; float min = a[index]; float max = min; for(int i = index; i<endIndex; ++i) { if( a[i] < min ) min = a[i]; if( a[i] > max ) max = a[i]; } tmpMinMaxArr[threadIdx.x*2] = min; tmpMinMaxArr[threadIdx.x*2+1] = max; __syncthreads(); if( threadIdx.x == 0 ) { min = tmpMinMaxArr[0]; max = min; for(int i = 0; i<blockDim.x*2; ++i) { if( tmpMinMaxArr[i] < min ) min = tmpMinMaxArr[i]; if( tmpMinMaxArr[i] > max ) max = tmpMinMaxArr[i]; } minMax[0] = min / 256.0; minMax[1] = max / 256.0; } } static __global__ void computeMinMaxKernel2(float* a, float* minMax, int2 offset, int2 imageSize, int2 paddedSize) { extern __shared__ float tmpMinMaxArr[]; int index = ((threadIdx.x + offset.y) * paddedSize.x + offset.x) * 2; int endIndex = index + imageSize.x * 2; float min = a[index]; float max = min; for(int i = index; i<endIndex; i+=2) { if( a[i] < min ) min = a[i]; if( a[i] > max ) max = a[i]; } tmpMinMaxArr[threadIdx.x*2] = min; tmpMinMaxArr[threadIdx.x*2+1] = max; __syncthreads(); if( threadIdx.x == 0 ) { min = tmpMinMaxArr[0]; max = min; for(int i = 0; i<blockDim.x*2; ++i) { if( tmpMinMaxArr[i] < min ) min = tmpMinMaxArr[i]; if( tmpMinMaxArr[i] > max ) max = tmpMinMaxArr[i]; } minMax[0] = min / 256.0 / 256.0; minMax[1] = max / 256.0 / 256.0; } } static __global__ void normalizeAveragesKernel(float* result, float* minMax) { int index = blockIdx.x * blockDim.x + threadIdx.x; result[index] = (result[index] - minMax[0]) / (minMax[1] - minMax[0]); } extern "C" void computeProbabilities(float* a, float* result, int2 divFactor, int2 size, int2 pSize, int2 offset) { printf("%d %d\n", pSize.x, pSize.y); int threadsPerBlock = size.y / divFactor.y; dim3 gridDim(divFactor.x, divFactor.y); // Compute the averages for each of the regions int sharedMemSize = sizeof(float) * size.y / divFactor.y; static float globalMin = 10e100; static float globalMax = -10e100; static float uselessAverage = 0.0f; static int count = 0; #if 0 // print values to be averaged float* vals = new float[pSize.x * pSize.y * 2]; cudaMemcpy(vals, a, sizeof(float) * pSize.x * pSize.y * 2, cudaMemcpyDeviceToHost); for(int i=0; i<pSize.x * pSize.y; i+=2) if( vals[i] > 20000.0f ) printf("val[%d]: %f\n", i, vals[i]); #endif #if 0 // print averages { // Calculate averages on host (for comparison) float* h = new float[divFactor.x * divFactor.y]; float* vals = new float[pSize.x * pSize.y * 2]; int blockStride = size.x / divFactor.x; int blockHeight = size.y / divFactor.y; // int valsPerRegion = size.x / divFactor.x * size.y / divFactor.y; cudaMemcpy(vals, a, sizeof(float) * pSize.x * pSize.y * 2, cudaMemcpyDeviceToHost); for(int i=0; i<divFactor.x; ++i) for(int j=0; j<divFactor.y; ++j) { int startIndex = pSize.x * offset.y + offset.x; startIndex += pSize.x * blockHeight * j; startIndex += blockStride * i; startIndex *= 2; int hIndex = divFactor.x * j + i; h[hIndex] = 0.0f; float pAvg = 0.0f; for(int k=0; k<blockHeight; ++k) { // Calculate and save partial average pAvg = 0.0f; for(int z=0; z<blockStride*2; z+=2) { pAvg += vals[startIndex + z]; } startIndex += 2 * pSize.x; h[hIndex] += pAvg / (float) blockStride; } // Calculate average of partial averages h[hIndex] /= (float)blockHeight; } float* tmp = new float[divFactor.x * divFactor.y]; cudaMemcpy(tmp, result, sizeof(float)*divFactor.x*divFactor.y, cudaMemcpyDeviceToHost); // print out to compare: averages w/ CUDA and averages on Host (CPU) for(int i=0; i<divFactor.x*divFactor.y; ++i) printf("Avg[%d]: %f : %f %s\n", i, tmp[i], h[i], (tmp[i]==h[i]?"":"**MISMATCH**") ); printf("\n"); delete tmp; delete h; delete vals; } #endif // Compute the min/max of the averages float* minMax; cudaMalloc((void**)&minMax, sizeof(float)*2); //sharedMemSize = sizeof(float)*divFactor.y*2; //computeMinMaxKernel<<<1, divFactor.y, sharedMemSize>>>(result, minMax, divFactor); sharedMemSize = sizeof(float)*size.y*2; //computeMinMaxKernel<<<1, size.y, sharedMemSize>>>(a, minMax, size); computeMinMaxKernel2<<<1, size.y, sharedMemSize>>>(a, minMax, offset, size, pSize); #if 1 // print min/max float shittyScalar; { //float* avgs = new float[divFactor.x * divFactor.y]; //cudaMemcpy(avgs, result, sizeof(float)*divFactor.x*divFactor.y, cudaMemcpyDeviceToHost); //int vals = divFactor.x * divFactor.y; //float min = avgs[0]; //float max = avgs[0]; //for(int i=0; i<vals; ++i) //{ // if( avgs[i] < min ) min = avgs[i]; // if( avgs[i] > max ) max = avgs[i]; //} float tmp[2]; cudaMemcpy( tmp, minMax, sizeof(float)*2, cudaMemcpyDeviceToHost); //printf("%f %f\n", tmp[0], tmp[1]); globalMin = tmp[0] < globalMin? tmp[0]: globalMin; globalMax = tmp[1] > globalMax? tmp[1]: globalMax; shittyScalar = tmp[1] / uselessAverage; uselessAverage = (uselessAverage * count + tmp[1]) / (count + 1); ++count; printf("%f %f\n", globalMin, globalMax); tmp[0] = globalMin; tmp[1] = globalMax; cudaMemcpy(minMax, tmp, sizeof(float) * 2, cudaMemcpyHostToDevice); //printf("Min/Max: %f / %f : %f %f %s\n\n", tmp[0], tmp[1], min, max, // (tmp[0]==min&&tmp[1]==max?"":"**MISMATCH**") ); //delete avgs; } #endif // Normalize each average based on min/max of the averages int nBlocks, blockSize; if( divFactor.x * divFactor.y < 4 ) { nBlocks = 1; blockSize = divFactor.x * divFactor.y; } else // assuming that divFactor.x * divFactor.y is divisible by 4 { nBlocks = divFactor.x * divFactor.y / 4; blockSize = divFactor.x * divFactor.y / nBlocks; } computeAveragesKernel<<<gridDim, threadsPerBlock, sharedMemSize>>>(a, result, size, pSize, offset, 1.0f / 256.0f / 256.0f); //normalizeAveragesKernel<<<nBlocks, blockSize>>>(result, minMax); cudaFree(minMax); }
1,491
#include<cuda_runtime.h> #include<stdio.h> __device__ float devData; __global__ void checkGlobalVariable(){ printf("Device: the value of the global variable is %f\n", devData); devData += 2.0f; } int main(){ float value = 3.14f; // cudaMemcpyToSymbol(devData, &value, sizeof(float)); float *dptr = NULL; cudaGetSymbolAddress((void**)&dptr, devData); // Symbol不是地址,本句获取其全局地址 cudaMemcpy(dptr, &value, sizeof(float), cudaMemcpyHostToDevice); printf("Host: copied %f to the global variable\n", value); checkGlobalVariable<<<1, 1>>>(); cudaMemcpyFromSymbol(&value, devData, sizeof(float)); printf("Host: the value changed by the kernel to %f\n", value); cudaDeviceReset(); return EXIT_SUCCESS; }
1,492
#include "includes.h" __global__ void bcnn_op_cuda_relu_grad_kernel(int n, float *x, float *dx) { int i = (blockIdx.x + blockIdx.y * gridDim.x) * blockDim.x + threadIdx.x; if (i < n) { dx[i] *= ((float)(x[i] > 0)); } return; }
1,493
#include <stdio.h> #include <stdlib.h> #include <math.h> //CUDA kernel __global__ void vecAdd(float *a, float *b, float *c, int n) { int id = blockIdx.x * blockDim.x + threadIdx.x; // ensure we are within bounds if (id<n) c[id] = a[id] + b[id]; } int main( int argc, char* argv[]) { // vector size int n = 2000; // device input/output vectors float *d_a; float *d_b; float *d_c; // size, in bytes, of each vector size_t bytes = n*sizeof(float); float *h_a = (float*)malloc(bytes); float *h_b = (float*)malloc(bytes); float *h_c = (float*)malloc(bytes); // allocate memory for each vector on GPU cudaMalloc(&d_a, bytes); cudaMalloc(&d_b, bytes); cudaMalloc(&d_c, bytes); int i; // initialize vectors for (i=0; i< n; i++) { h_a[i] = sin(i)*sin(i); h_b[i] = cos(i)*cos(i); } cudaMemcpy(d_a, h_a, bytes, cudaMemcpyHostToDevice); cudaMemcpy(d_b, h_b, bytes, cudaMemcpyHostToDevice); // number of threads in each thread block int blockSize = 1024; // number of thread blocks in grid int gridSize = (int) ceil((float)n/blockSize); //kernel execute vecAdd<<<gridSize, blockSize>>>(d_a, d_b, d_c, n); //copy array back cudaMemcpy(h_c, d_c, bytes, cudaMemcpyDeviceToHost); float sum = 0; for(i=0; i<n; i++) { sum += h_c[i]; printf("%0.2f\n", h_c[i]); } printf("final result: %f\n", sum/(float)n); cudaFree(d_a); cudaFree(d_b); cudaFree(d_c); free(h_a); free(h_b); free(h_c); return 0; }
1,494
#include <stdio.h> __global__ void printValue( int *value) { printf("value %d\n",value[0]); printf("value %d\n",value[1]); } void hostFunction(){ int *value; cudaMallocManaged(&value, 2 * sizeof(int)); value[0]=1; value[1]=2; printValue<<< 1, 1 >>>(value); cudaDeviceSynchronize(); cudaFree(value); } int main() { hostFunction(); return 0; }
1,495
#include <stdio.h> #include <cuda_runtime.h> __global__ void kernel(void) { printf("GPU bockIdx %i threadIdx %i: Hello World!\n", blockIdx.x, threadIdx.x); } int main(int argc, char* argv[]) { kernel <<<6,2>>>(); cudaDeviceSynchronize(); return 0; }
1,496
#include <cuda.h> #include <cuda_runtime.h> #include <stdio.h> int main(int argc, char **argv) { double *buf_d = NULL; fprintf(stderr, "Allocating...\n"); cudaMalloc((void **) &buf_d, sizeof(double) * 1024); fprintf(stderr, "Allocating DONE.\n"); return 0; }
1,497
//Matrix Multiplication #include <stdio.h> #include <stdlib.h> #define BLOCK_SIZE 2 #define GRID_SIZE 2 #define N GRID_SIZE * BLOCK_SIZE __global__ void MatrixMul(float *A, float *B, float *C, int n) { // Each thread computes a single element of C int row = blockIdx.y*blockDim.y + threadIdx.y; int col = blockIdx.x*blockDim.x + threadIdx.x; float sum = 0; for (int i = 0; i < n; ++i) { sum += (A[row*n + i] * B[i*n + col]); } C[row*n + col] = sum; printf("\n Block[%d][%d] : Thread[%d][%d] : Product = %.2f\n", blockIdx.x, blockIdx.y, threadIdx.x, threadIdx.y, sum); } int main() { // Perform matrix multiplication C = A*B // where A, B and C are NxN matrices // Restricted to matrices where N = GRID_SIZE*BLOCK_SIZE; float *hA, *hB, *hC; float *dA, *dB, *dC; int size = N * N * sizeof(float); printf("Matrix Multiplcation:-->\n"); printf("Matrix size: %d x %d\n", N,N); // Allocate memory on the host hA = (float *) malloc(size); hB = (float *) malloc(size); hC = (float *) malloc(size); // Initialize matrices on the host for (int j = 0; j<N; j++){ for (int i = 0; i<N; i++){ hA[j*N + i] = 3; hB[j*N + i] = 2; } } printf("Matrix 1:\n"); for (int j = 0; j<N; j++){ for (int i = 0; i<N; i++){ printf("%.2f ", hA[j*N + i]); } printf("\n"); } printf("\nMatrix 2:\n"); for (int j = 0; j<N; j++){ for (int i = 0; i<N; i++){ printf("%.2f ", hB[j*N + i]); } printf("\n"); } // Allocate memory on the device cudaMalloc(&dA, size); cudaMalloc(&dB, size); cudaMalloc(&dC, size); dim3 threadBlock(BLOCK_SIZE, BLOCK_SIZE); dim3 grid(GRID_SIZE, GRID_SIZE); // Copy matrices from the host to device cudaMemcpy(dA, hA, size, cudaMemcpyHostToDevice); cudaMemcpy(dB, hB, size, cudaMemcpyHostToDevice); //Execute the matrix multiplication kernel printf("\n Kernel Launch with Gird of size (%dx%d) and Block of size (%dx%d)\n", GRID_SIZE, GRID_SIZE, BLOCK_SIZE, BLOCK_SIZE); MatrixMul <<<grid, threadBlock >>>(dA, dB, dC, N); // Now copy the GPU result back to CPU cudaMemcpy(hC, dC, size, cudaMemcpyDeviceToHost); printf("\nThe Product of Matrix A and B is:\n"); for (int j = 0; j<N; j++){ for (int i = 0; i<N; i++){ printf("%.2f ", hC[j*N + i]); } printf("\n"); } return 0; }
1,498
#include "CudaEuler.cuh" #include <stdio.h> __device__ int modulo(int a, int b){ int r = a%b; return r< 0 ? r + b : r; } __global__ void CudaCalculateDerivative(inttype N, fptype rate, fptype* derivative, fptype* mass, fptype* val, inttype* ia, inttype* ja, inttype* map, inttype offset) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < N; i+= stride ){ int i_r = map[i+offset]; fptype dr = 0.; for(unsigned int j = ia[i]; j < ia[i+1]; j++){ int j_m = map[ja[j]+offset]; dr += val[j]*mass[j_m]; } dr -= mass[i_r]; derivative[i_r] += rate*dr; } } __global__ void CudaSingleTransformStep(inttype N, fptype* derivative, fptype* mass, fptype* val, inttype* ia, inttype* ja, inttype* map, inttype offset) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < N; i+= stride ){ int i_r = map[i+offset]; fptype dr = 0.; for(unsigned int j = ia[i]; j < ia[i+1]; j++){ int j_m = map[ja[j]+offset]; dr += val[j]*mass[j_m]; } dr -= mass[i_r]; derivative[i_r] += dr; } } // Performing this calculation per iteration doubles the simulation time. // This function shouldn't be used in that way but it a good example in case you want to // include some kind of variable efficacy. __global__ void CudaCalculateGridEfficacies(inttype N, fptype efficacy, fptype grid_cell_width, fptype* stays, fptype* goes, int* offset1s, int* offset2s) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < N; i+= stride ){ inttype ofs = (inttype)abs(efficacy / grid_cell_width); fptype g = (fptype)fabs(efficacy / grid_cell_width) - ofs; fptype s = 1.0 - g; int o1 = efficacy > 0 ? ofs : -ofs; int o2 = efficacy > 0 ? (ofs+1) : (ofs-1); stays[modulo(i+o1,N)] = s; goes[modulo(i+o2,N)] = g; offset1s[modulo(i+o1,N)] = -o1; offset2s[modulo(i+o2,N)] = -o2; } } // As above, this function should not be used per iteration as the efficacy doesn't // change during simulation. __global__ void CudaCalculateGridEfficaciesWithConductance(inttype N, fptype efficacy, fptype grid_cell_width, fptype* cell_vs, fptype cond_stable, fptype* stays, fptype* goes, int* offset1s, int* offset2s, inttype vs_offset) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < N; i+= stride ){ // WARNING! If the offset changes from, say, 0 and 1 to 1 and 2 along // a strip (due to changing V), there will be an overwrite of goes and stays // which will lead to mass loss. // Solution must be to allow multiple stays and goes into each cell. There // should be a github bug report for this. fptype eff = efficacy * (cell_vs[i + vs_offset] - cond_stable); inttype ofs = (inttype)abs(eff / grid_cell_width); fptype g = (fptype)fabs(eff / grid_cell_width) - ofs; fptype s = 1.0 - g; int o1 = efficacy > 0 ? ofs : -ofs; int o2 = efficacy > 0 ? (ofs+1) : (ofs-1); stays[modulo(i+o1,N)] = s; goes[modulo(i+o2,N)] = g; offset1s[modulo(i+o1,N)] = -o1; offset2s[modulo(i+o2,N)] = -o2; } } __global__ void CudaCalculateGridDerivative(inttype N, fptype rate, fptype stays, fptype goes, int offset_1, int offset_2, fptype* derivative, fptype* mass, inttype offset) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < N; i+= stride ){ int io = i+offset; fptype dr = 0.; dr += stays*mass[(modulo(io+offset_1,N))+offset]; dr += goes*mass[(modulo(io+offset_2,N))+offset]; dr -= mass[io]; derivative[io] += rate*dr; } } __global__ void CudaCalculateGridDerivativeWithEfficacy(inttype N, fptype rate, fptype* stays, fptype* goes, int* offset_1, int* offset_2, fptype* derivative, fptype* mass, inttype offset) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < N; i+= stride ){ int io = i+offset; fptype dr = 0.; dr += stays[i]*mass[(modulo(io+offset_1[i],N))+offset]; dr += goes[i]*mass[(modulo(io+offset_2[i],N))+offset]; dr -= mass[io]; derivative[io] += rate*dr; } } __global__ void EulerStep(inttype N, fptype* derivative, fptype* mass, fptype timestep) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < N; i+= stride ){ mass[i] += derivative[i]*timestep; } } __global__ void CheckDerivativeEqualsZero(inttype N, fptype* derivative) { fptype total = 0.; for (int i = 0; i < N; i++){ total += derivative[i]; printf("add : %i %f : %f\n", i, derivative[i], total); } printf("data : %f\n", total); } __global__ void MapReversal(unsigned int n_reversal, unsigned int* rev_from, unsigned int* rev_to, fptype* rev_alpha, fptype* mass, unsigned int* map) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < n_reversal; i+= stride){ fptype m = mass[map[rev_from[i]]]; mass[map[rev_from[i]]] = 0.; mass[map[rev_to[i]]] += m; } } __global__ void MapResetToRefractory(unsigned int n_reset, unsigned int* res_from, fptype* mass, unsigned int* map, fptype* refactory_mass){ int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < n_reset; i += stride){ refactory_mass[i] = mass[map[res_from[i]]]; } } __global__ void MapResetShiftRefractory(unsigned int n_reset, fptype* refactory_mass, inttype offset){ int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = offset+index; i < offset+n_reset; i+=stride){ refactory_mass[i+n_reset] = refactory_mass[i]; } } __global__ void MapResetThreaded(unsigned int n_reset, fptype* mass, fptype* refactory_mass, inttype ref_offset, unsigned int* rev_to, fptype* rev_alpha, inttype* rev_offsets, inttype* rev_counts, unsigned int* map, fptype proportion){ int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < n_reset; i+= stride ){ int i_r = map[rev_to[i]]; fptype dr = 0.; for(unsigned int j = rev_offsets[i]; j < rev_offsets[i]+rev_counts[i]; j++){ dr += rev_alpha[j]*refactory_mass[ref_offset+j]*proportion; } mass[i_r] += dr; } } __global__ void GetResetMass(unsigned int n_reset, fptype* sum, fptype* refactory_mass, fptype* rev_alpha, inttype* rev_offsets, inttype* rev_counts){ int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < n_reset; i+= stride ){ fptype dr = 0.; for(unsigned int j = rev_offsets[i]; j < rev_offsets[i]+rev_counts[i]; j++){ dr += rev_alpha[j]*refactory_mass[j]; } sum[i] = dr; } } __global__ void SumReset(unsigned int n_sum, fptype* sum, fptype* rate){ extern __shared__ fptype sdata[]; // each thread loads one element from global to shared mem unsigned int tid = threadIdx.x; unsigned int i = blockIdx.x*blockDim.x + threadIdx.x; if(i >= n_sum){ sdata[tid] = 0.; return; } sdata[tid] = sum[i]; __syncthreads(); // do reduction in shared mem for (unsigned int s=blockDim.x/2; s>0; s>>=1) { if (tid < s) { sdata[tid] += sdata[tid + s]; } __syncthreads(); } // write result for this block to global mem if (tid == 0) { rate[blockIdx.x] = sdata[0]; } } __global__ void ResetFinishThreaded(inttype n_reset, inttype* res_from, fptype* mass, inttype* map){ int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < n_reset; i+= stride){ mass[map[res_from[i]]] = 0.; } } __global__ void Remap(int N, unsigned int* i_1, unsigned int t, unsigned int *map, unsigned int* first, unsigned int* length) { unsigned int i_start = *i_1; int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < N; i+= stride) if (i >= i_start) map[i] = modulo((i - t - first[i]),length[i]) + first[i]; } __global__ void CudaClearDerivative(inttype N, fptype* dydt, fptype* mass){ int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < N; i+= stride) dydt[i] = 0.; }
1,499
#include <stdio.h> #include <stdlib.h> #include <cuda.h> __global__ void Add(int *a, int *b, int* c) { *c = *a + *b; } int main() { // Host numbers int hostA; int hostB; int hostC; // Device numbers int* devA; int* devB; int* devC; // Allocate memory for device numbers cudaError_t err = cudaMalloc((void**)&devA, sizeof(int)); if (err != cudaSuccess) { printf("Failed to alloc memory for A, err: %s\n", cudaGetErrorString(err)); } err = cudaMalloc((void**)&devB, sizeof(int)); if (err != cudaSuccess) { printf("Failed to alloc memory for B, err: %s\n", cudaGetErrorString(err)); } err = cudaMalloc((void**)&devC, sizeof(int)); if (err != cudaSuccess) { printf("Failed to alloc memory for C, err: %s\n", cudaGetErrorString(err)); } hostA = 10; hostB = 100; // Copy host values to device cudaMemcpy(devA, &hostA, sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(devB, &hostB, sizeof(int), cudaMemcpyHostToDevice); // Add on device Add<<<1,1>>>(devA, devB, devC); // Copy the result back to host cudaMemcpy(&hostC, devC, sizeof(int), cudaMemcpyDeviceToHost); // Deallocate memory cudaFree(devA); cudaFree(devB); cudaFree(devC); printf("A: %d, B: %d, C = A + B: %d\n", hostA, hostB, hostC); return 0; }
1,500
#include "includes.h" __global__ void blur( float * input, float * output, int height, int width) { int x = blockIdx.x * blockDim.x + threadIdx.x; int y = blockIdx.y * blockDim.y + threadIdx.y; if(x<height && y<width) { for(int k=0;k<3;k++) { float sum=0; int count=0; for(int i=x-BLUR_SIZE; i<= x+BLUR_SIZE; i++) { for(int j= y-BLUR_SIZE; j<=y+BLUR_SIZE;j++) { if(i>=0 && i<height && j>=0 && j<width) { count++; sum+=input[3*(i*width+j)+k]; } } } output[3*(x*width+y)+k]=sum/count; } } else return ; }