index
int64
0
0
repo_id
stringclasses
93 values
file_path
stringlengths
15
128
content
stringlengths
14
7.05M
0
ALLM
ALLM/CF/driver.cpp
#include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <stdlib.h> #include <mpi.h> #include "driver.h" extern "C" { void initmat(mat * Amat){ Amat->iv = NULL; Amat->jv = NULL; Amat->vv = NULL; Amat->m = 0; Amat->nnz = 0; } void driver_mat(mat * inA, mat * outX, parameters * inParams){ printf(" nnz %d \n", inA->nnz); for(int k =0; k<inA->nnz; ++k){ printf("%d \n", k); outX->iv[k] = inA->iv[k]; printf("%d \n", k); printf(" iv %d \n", inA->iv[k]); outX->jv[k] = inA->jv[k]; outX->vv[k] = inA->vv[k] + inParams->alpha*inA->vv[k]; } } void driver_mat_mpi(mat * inA, mat * outX, parameters * inParams){ int rank; //MPI_Fint fcomm; //fcomm = inParams->comm; //MPI_Comm comm; //comm = MPI_Comm_f2c(fcomm); if(inParams->fcomm != -1){ (inParams->comm) = MPI_Comm_f2c((inParams->fcomm)); printf("fcomm %d \n ", inParams->fcomm); } MPI_Comm_rank(inParams->comm, &rank); printf(" nnz %d \n", inA->nnz); for(int k =0; k<inA->nnz; ++k){ printf("%d \n", k); outX->iv[k] = inA->iv[k]; printf("%d \n", k); printf(" iv %d \n", inA->iv[k]); outX->jv[k] = inA->jv[k]; if(k==rank){ outX->vv[k] = rank*inA->vv[k] + rank*inParams->alpha*inA->vv[k]; } else{ outX->vv[k] = rank; } } } } /*int main(){ const int m = 2; const int nnz = 2; int * a_i = (int *) malloc(nnz * sizeof(int)); int * a_j = (int *) malloc(nnz * sizeof(int)); double * a_v = (double *) malloc(nnz * sizeof(double)); a_i[0]=0;a_j[0]=0;a_v[0]=1; a_i[1]=1;a_j[1]=1;a_v[1]=1; mat A; initmat(&A); A.m=m;A.nnz=nnz; A.iv=a_i;A.jv=a_j;A.vv=a_v; int * x_i = (int *) malloc(nnz * sizeof(int)); int * x_j = (int *) malloc(nnz * sizeof(int)); double * x_v = (double *) malloc(nnz * sizeof(double)); x_i[0]=0;x_j[0]=0;x_v[0]=0; x_i[1]=0;x_j[1]=0;x_v[1]=0; mat X; initmat(&X); X.m=m;X.nnz=nnz; X.iv=x_i;X.jv=x_j;X.vv=x_v; parameters params; params.alpha = 2.0; params.comm = 0; driver_mat(&A, &X, &params); printf("A:\n"); for(int k = 0; k < nnz; ++k){ printf("%lf ", a_v[k]); } printf("\n"); printf("X:\n"); for(int k = 0; k < nnz; ++k){ printf("%lf ", x_v[k]); } printf("\n"); free(a_i); free(a_j); free(a_v); free(x_i); free(x_j); free(x_v); return 0; }*/
0
ALLM
ALLM/CF/driver.h
#if defined __cplusplus using Scalar = double; using Primary = double; #else typedef double Scalar; typedef double Primary; #endif typedef struct{ int * iv; int * jv; Scalar * vv; int m; int nnz; //int storage; //int symmetry; } mat; typedef struct{ Scalar alpha; MPI_Comm comm; MPI_Fint fcomm; } parameters; #if defined __cplusplus extern "C" { #endif void initmat(mat * Amat); void driver_mat(mat * inA, mat * outX, parameters * inParams); void driver_mat_mpi(mat * inA, mat * outX, parameters * inParams); #if defined __cplusplus } #endif
0
ALLM
ALLM/C_SUJET1/nbody.c
#include <stdio.h> #include <math.h> #include <stdlib.h> // drand48 #include <omp.h> #define DUMP struct ParticleType { float x, y, z; float vx, vy, vz; }; void MoveParticles(const int nParticles, struct ParticleType* const particle, const float dt) { // Loop over particles that experience force for (int i = 0; i < nParticles; i++) { // Components of the gravity force on particle i float Fx = 0, Fy = 0, Fz = 0; // Loop over particles that exert force for (int j = 0; j < nParticles; j++) { // No self interaction if (i != j) { // Avoid singularity and interaction with self const float softening = 1e-20; // Newton's law of universal gravity const float dx = particle[j].x - particle[i].x; const float dy = particle[j].y - particle[i].y; const float dz = particle[j].z - particle[i].z; const float drSquared = dx*dx + dy*dy + dz*dz + softening; const float drPower32 = pow(drSquared, 3.0/2.0); // Calculate the net force Fx += dx / drPower32; Fy += dy / drPower32; Fz += dz / drPower32; } } // Accelerate particles in response to the gravitational force particle[i].vx += dt*Fx; particle[i].vy += dt*Fy; particle[i].vz += dt*Fz; } // Move particles according to their velocities // O(N) work, so using a serial loop for (int i = 0 ; i < nParticles; i++) { particle[i].x += particle[i].vx*dt; particle[i].y += particle[i].vy*dt; particle[i].z += particle[i].vz*dt; } } void dump(int iter, int nParticles, struct ParticleType* particle) { char filename[64]; snprintf(filename, 64, "output_%d.txt", iter); FILE *f; f = fopen(filename, "w+"); int i; for (i = 0; i < nParticles; i++) { fprintf(f, "%e %e %e %e %e %e\n", particle[i].x, particle[i].y, particle[i].z, particle[i].vx, particle[i].vy, particle[i].vz); } fclose(f); } // Initialize random number generator and particles: void init_rand(int nParticles, struct ParticleType* particle){ srand48(0x2020); for (int i = 0; i < nParticles; i++) { particle[i].x = 2.0*drand48() - 1.0; particle[i].y = 2.0*drand48() - 1.0; particle[i].z = 2.0*drand48() - 1.0; particle[i].vx = 2.0*drand48() - 1.0; particle[i].vy = 2.0*drand48() - 1.0; particle[i].vz = 2.0*drand48() - 1.0; } } // Initialize (no random generator) particles void init_norand(int nParticles, struct ParticleType* particle){ const float a=127.0/nParticles; for (int i = 0; i < nParticles; i++) { particle[i].x = i*a;//2.0*drand48() - 1.0; particle[i].y = i*a;//2.0*drand48() - 1.0; particle[i].z = 1.0;//2.0*drand48() - 1.0; particle[i].vx = 0.5;//2.0*drand48() - 1.0; particle[i].vy = 0.5;//2.0*drand48() - 1.0; particle[i].vz = 0.5;//2.0*drand48() - 1.0; } } int main(const int argc, const char** argv) { // Problem size and other parameters const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384); // Duration of test const int nSteps = (argc > 2)?atoi(argv[2]):10; // Particle propagation time step const float dt = 0.0005f; struct ParticleType* particle = malloc(nParticles*sizeof(struct ParticleType)); // Initialize random number generator and particles //init_rand(nParticles, particle); // Initialize (no random generator) particles init_norand(nParticles, particle); // Perform benchmark printf("\nPropagating %d particles using 1 thread...\n\n", nParticles ); double rate = 0, dRate = 0; // Benchmarking data const int skipSteps = 3; // Skip first iteration (warm-up) printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); for (int step = 1; step <= nSteps; step++) { const double tStart = omp_get_wtime(); // Start timing MoveParticles(nParticles, particle, dt); const double tEnd = omp_get_wtime(); // End timing const float HztoInts = ((float)nParticles)*((float)(nParticles-1)) ; const float HztoGFLOPs = 20.0*1e-9*((float)(nParticles))*((float)(nParticles-1)); if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); #ifdef DUMP dump(step, nParticles, particle); #endif } rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); free(particle); return 0; }
0
ALLM
ALLM/C_SUJET1/nbody_aos.cu
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <math.h> #include <omp.h> #include <cuda.h> #include <cuda_runtime.h> #include <cuda_profiler_api.h> #define nPart 16384 #define THREADS_PER_BLOCK 256 #define DUMP //------------------------------------------------------------------------------------------------------------------------- //struct ParticleType{ // float x, y, z, vx, vy, vz; //}; struct ParticleType{ float x[nPart],y[nPart],z[nPart]; float vx[nPart],vy[nPart],vz[nPart]; }; //------------------------------------------------------------------------------------------------------------------------- //CUDA VERSION: __global__ void MoveParticles_CUDA(const int nParticles, struct ParticleType* const particle){ // Particle propagation time step const float dt = 0.0005f; int i = threadIdx.x + blockIdx.x * blockDim.x; if(i<nParticles){ float Fx=0.,Fy=0.,Fz=0.; for(int j = 0; j< nParticles; j++){ //no self interaction: if(i != j){ //avoid singularity and interaction with self: const float softening = 1e-20; //Newton's law of universal gravity: const float dx = particle->x[j] - particle->x[i]; const float dy = particle->y[j] - particle->y[i]; const float dz = particle->z[j] - particle->z[i]; const float drSquared = dx*dx + dy*dy + dz*dz + softening; const float drPower32 = pow(drSquared, 3.0/2.0); //Calculate the net force: Fx += dx / drPower32; Fy += dy / drPower32; Fz += dz / drPower32; }//fi i!=j }//j loop //Accelerate particles in response to the gravitational force: particle->vx[i] += dt*Fx; particle->vy[i] += dt*Fy; particle->vz[i] += dt*Fz; } }//fct MoveParticles_CUDA //------------------------------------------------------------------------------------------------------------------------- // Initialize random number generator and particles: void init_rand(int nParticles, struct ParticleType* particle){ srand48(0x2020); for (int i = 0; i < nParticles; i++) { particle->x[i] = 2.0*drand48() - 1.0; particle->y[i] = 2.0*drand48() - 1.0; particle->z[i] = 2.0*drand48() - 1.0; particle->vx[i] = 2.0*drand48() - 1.0; particle->vy[i] = 2.0*drand48() - 1.0; particle->vz[i] = 2.0*drand48() - 1.0; } } //------------------------------------------------------------------------------------------------------------------------- // Initialize (no random generator) particles void init_norand(int nParticles, struct ParticleType* const particle){ const float a=127.0/nParticles; for (int i = 0; i < nParticles; i++) { particle->x[i] = i*a;//2.0*drand48() - 1.0; particle->y[i] = i*a;//2.0*drand48() - 1.0; particle->z[i] = 1.0;//2.0*drand48() - 1.0; particle->vx[i] = 0.5;//2.0*drand48() - 1.0; particle->vy[i] = 0.5;//2.0*drand48() - 1.0; particle->vz[i] = 0.5;//2.0*drand48() - 1.0; } } //------------------------------------------------------------------------------------------------------------------------- void dump(int iter, int nParticles, struct ParticleType* particle) { char filename[64]; snprintf(filename, 64, "output_%d.txt", iter); FILE *f; f = fopen(filename, "w+"); int i; for (i = 0; i < nParticles; i++) { fprintf(f, "%e %e %e %e %e %e\n", particle->x[i], particle->y[i], particle->z[i], particle->vx[i], particle->vy[i], particle->vz[i]); } fclose(f); } //------------------------------------------------------------------------------------------------------------------------- int main(const int argc, const char** argv) { // Problem size and other parameters // const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384); const int nParticles=nPart; // Duration of test const int nSteps = (argc > 2)?atoi(argv[2]):10; // Particle propagation time step const float ddt = 0.0005f; //------------------------------------------------------------------------------------------------------------------------- //DEFINE SIZE: int SIZE = sizeof(struct ParticleType); //------------------------------------------------------------------------------------------------------------------------- //DECLARATION & ALLOC particle ON HOST: struct ParticleType* particle = (struct ParticleType*) malloc(SIZE); //------------------------------------------------------------------------------------------------------------------------- // Initialize random number generator and particles srand48(0x2020); //Initialize random number generator and particles //init_rand(nParticles, particle); // Initialize (no random generator) particles init_norand(nParticles, particle); //------------------------------------------------------------------------------------------------------------------------- // Perform benchmark printf("\nPropagating %d particles using %d thread...\n\n", 128 ,nParticles ); double rate = 0, dRate = 0; // Benchmarking data const int skipSteps = 3; // Skip first iteration (warm-up) printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); //------------------------------------------------------------------------------------------------------------------------- cudaProfilerStart(); //------------------------------------------------------------------------------------------------------------------------- struct ParticleType *particle_cuda; cudaMalloc((void **)&particle_cuda, SIZE); //------------------------------------------------------------------------------------------------------------------------- // cudaMemcpy(particle_cuda, particle, SIZE, cudaMemcpyHostToDevice); //------------------------------------------------------------------------------------------------------------------------- for (int step = 1; step <= nSteps; step++) { const double tStart = omp_get_wtime(); // Start timing cudaMemcpy(particle_cuda, particle, SIZE, cudaMemcpyHostToDevice); MoveParticles_CUDA<<<nParticles/THREADS_PER_BLOCK,THREADS_PER_BLOCK>>>(nParticles, particle_cuda); cudaMemcpy(particle, particle_cuda, SIZE, cudaMemcpyDeviceToHost);//need to do? const double tEnd = omp_get_wtime(); // End timing // Move particles according to their velocities // O(N) work, so using a serial loop for (int i = 0 ; i < nParticles; i++) { particle->x[i] += particle->vx[i]*ddt; particle->y[i] += particle->vy[i]*ddt; particle->z[i] += particle->vz[i]*ddt; } const float HztoInts = ((float)nParticles)*((float)(nParticles-1)) ; const float HztoGFLOPs = 20.0*1e-9*((float)(nParticles))*((float)(nParticles-1)); if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); #ifdef DUMP dump(step, nParticles, particle); #endif } cudaFree(particle_cuda); //------------------------------------------------------------------------------------------------------------------------- cudaProfilerStop(); //------------------------------------------------------------------------------------------------------------------------- rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); free(particle); return 0; }
0
ALLM
ALLM/C_SUJET1/nbody_cuda.cu
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <math.h> #include <omp.h> #include <cuda.h> #include <cuda_runtime.h> #include <cuda_profiler_api.h> #define THREADS_PER_BLOCK 128 #define DUMP //------------------------------------------------------------------------------------------------------------------------- struct ParticleType{ float x, y, z, vx, vy, vz; }; //------------------------------------------------------------------------------------------------------------------------- //CUDA VERSION: __global__ void MoveParticles_CUDA(const int nParticles, struct ParticleType* const particle){ // Particle propagation time step const float dt = 0.0005f; float Fx = 0.0, Fy = 0.0, Fz = 0.0; int i = threadIdx.x + blockIdx.x * blockDim.x; if(i<nParticles){ for(int j = 0; j< nParticles; j++){ //no self interaction: if(i != j){ //avoid singularity and interaction with self: const float softening = 1e-20; //Newton's law of universal gravity: const float dx = particle[j].x - particle[i].x; const float dy = particle[j].y - particle[i].y; const float dz = particle[j].z - particle[i].z; const float drSquared = dx*dx + dy*dy + dz*dz + softening; const float drPower32 = pow(drSquared, 3.0/2.0); //Calculate the net force: Fx += dx / drPower32; Fy += dy / drPower32; Fz += dz / drPower32; }//fi i!=j }//j loop //Accelerate particles in response to the gravitational force: particle[i].vx += dt*Fx; particle[i].vy += dt*Fy; particle[i].vz += dt*Fz; } }//fct MoveParticles_CUDA //------------------------------------------------------------------------------------------------------------------------- // Initialize random number generator and particles: void init_rand(int nParticles, struct ParticleType* particle){ srand48(0x2020); for (int i = 0; i < nParticles; i++) { particle[i].x = 2.0*drand48() - 1.0; particle[i].y = 2.0*drand48() - 1.0; particle[i].z = 2.0*drand48() - 1.0; particle[i].vx = 2.0*drand48() - 1.0; particle[i].vy = 2.0*drand48() - 1.0; particle[i].vz = 2.0*drand48() - 1.0; } } //------------------------------------------------------------------------------------------------------------------------- // Initialize (no random generator) particles void init_norand(int nParticles, struct ParticleType* particle){ const float a=127.0/nParticles; for (int i = 0; i < nParticles; i++) { particle[i].x = i*a;//2.0*drand48() - 1.0; particle[i].y = i*a;//2.0*drand48() - 1.0; particle[i].z = 1.0;//2.0*drand48() - 1.0; particle[i].vx = 0.5;//2.0*drand48() - 1.0; particle[i].vy = 0.5;//2.0*drand48() - 1.0; particle[i].vz = 0.5;//2.0*drand48() - 1.0; } } //------------------------------------------------------------------------------------------------------------------------- void dump(int iter, int nParticles, struct ParticleType* particle) { char filename[64]; snprintf(filename, 64, "output_%d.txt", iter); FILE *f; f = fopen(filename, "w+"); int i; for (i = 0; i < nParticles; i++) { fprintf(f, "%e %e %e %e %e %e\n", particle[i].x, particle[i].y, particle[i].z, particle[i].vx, particle[i].vy, particle[i].vz); } fclose(f); } //------------------------------------------------------------------------------------------------------------------------- int main(const int argc, const char** argv) { // Problem size and other parameters const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384); // Duration of test const int nSteps = (argc > 2)?atoi(argv[2]):10; // Particle propagation time step const float ddt = 0.0005f; //------------------------------------------------------------------------------------------------------------------------- //DEFINE SIZE: int SIZE = nParticles * sizeof(struct ParticleType); //------------------------------------------------------------------------------------------------------------------------- //DECLARATION & ALLOC particle ON HOST: struct ParticleType* particle = (struct ParticleType*) malloc(SIZE); //------------------------------------------------------------------------------------------------------------------------- // Initialize random number generator and particles srand48(0x2020); // Initialize random number generator and particles //init_rand(nParticles, particle); // Initialize (no random generator) particles init_norand(nParticles, particle); //------------------------------------------------------------------------------------------------------------------------- // Perform benchmark printf("\nPropagating %d particles using 1 thread...\n\n", nParticles ); double rate = 0, dRate = 0; // Benchmarking data const int skipSteps = 3; // Skip first iteration (warm-up) printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); //------------------------------------------------------------------------------------------------------------------------- cudaProfilerStart(); //------------------------------------------------------------------------------------------------------------------------- struct ParticleType *particle_cuda; cudaMalloc((void **)&particle_cuda, SIZE); //------------------------------------------------------------------------------------------------------------------------- cudaMemcpy(particle_cuda, particle, SIZE, cudaMemcpyHostToDevice); //------------------------------------------------------------------------------------------------------------------------- for (int step = 1; step <= nSteps; step++) { const double tStart = omp_get_wtime(); // Start timing cudaMemcpy(particle_cuda, particle, SIZE, cudaMemcpyHostToDevice); MoveParticles_CUDA<<<nParticles/THREADS_PER_BLOCK,THREADS_PER_BLOCK>>>(nParticles, particle_cuda); cudaMemcpy(particle, particle_cuda, SIZE, cudaMemcpyDeviceToHost);//need to do? const double tEnd = omp_get_wtime(); // End timing // Move particles according to their velocities // O(N) work, so using a serial loop for (int i = 0 ; i < nParticles; i++) { particle[i].x += particle[i].vx*ddt; particle[i].y += particle[i].vy*ddt; particle[i].z += particle[i].vz*ddt; } const float HztoInts = ((float)nParticles)*((float)(nParticles-1)) ; const float HztoGFLOPs = 20.0*1e-9*((float)(nParticles))*((float)(nParticles-1)); if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); #ifdef DUMP dump(step, nParticles, particle); #endif } cudaFree(particle_cuda); //------------------------------------------------------------------------------------------------------------------------- cudaProfilerStop(); //------------------------------------------------------------------------------------------------------------------------- rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); free(particle); return 0; }
0
ALLM
ALLM/C_SUJET1/nbody_omp.c
#include <stdio.h> #include <math.h> #include <stdlib.h> // drand48 #include <omp.h> #define DUMP struct ParticleType { float x, y, z; float vx, vy, vz; }; void MoveParticles(const int nParticles, struct ParticleType* const particle, const float dt) { int i,j; float Fx,Fy,Fz; // Loop over particles that experience force #pragma omp parallel for private(j) for (i = 0; i < nParticles; i++) { // Components of the gravity force on particle i Fx = 0, Fy = 0, Fz = 0; // Loop over particles that exert force for (j = 0; j < nParticles; j++) { // No self interaction //if (i != j) { // Avoid singularity and interaction with self const float softening = 1e-20; // Newton's law of universal gravity const float dx = particle[j].x - particle[i].x; const float dy = particle[j].y - particle[i].y; const float dz = particle[j].z - particle[i].z; const float drSquared = dx*dx + dy*dy + dz*dz + softening; const float drPower32 = pow(drSquared, 3.0/2.0); // Calculate the net force Fx += dx / drPower32; Fy += dy / drPower32; Fz += dz / drPower32; //} } // Accelerate particles in response to the gravitational force particle[i].vx += dt*Fx; particle[i].vy += dt*Fy; particle[i].vz += dt*Fz; } // Move particles according to their velocities // O(N) work, so using a serial loop #pragma omp parallel for for (int i = 0 ; i < nParticles; i++) { particle[i].x += particle[i].vx*dt; particle[i].y += particle[i].vy*dt; particle[i].z += particle[i].vz*dt; } } void dump(int iter, int nParticles, struct ParticleType* particle) { char filename[64]; snprintf(filename, 64, "output_%d.txt", iter); FILE *f; f = fopen(filename, "w+"); int i; for (i = 0; i < nParticles; i++) { fprintf(f, "%e %e %e %e %e %e\n", particle[i].x, particle[i].y, particle[i].z, particle[i].vx, particle[i].vy, particle[i].vz); } fclose(f); } // Initialize random number generator and particles: void init_rand(int nParticles, struct ParticleType* particle){ srand48(0x2020); #pragma omp parallel for for (int i = 0; i < nParticles; i++) { particle[i].x = 2.0*drand48() - 1.0; particle[i].y = 2.0*drand48() - 1.0; particle[i].z = 2.0*drand48() - 1.0; particle[i].vx = 2.0*drand48() - 1.0; particle[i].vy = 2.0*drand48() - 1.0; particle[i].vz = 2.0*drand48() - 1.0; } } // Initialize (no random generator) particles void init_norand(int nParticles, struct ParticleType* particle){ const float a=127.0/nParticles; #pragma omp parallel for for (int i = 0; i < nParticles; i++) { particle[i].x = i*a;//2.0*drand48() - 1.0; particle[i].y = i*a;//2.0*drand48() - 1.0; particle[i].z = 1.0;//2.0*drand48() - 1.0; particle[i].vx = 0.5;//2.0*drand48() - 1.0; particle[i].vy = 0.5;//2.0*drand48() - 1.0; particle[i].vz = 0.5;//2.0*drand48() - 1.0; } } int main(const int argc, const char** argv) { // Problem size and other parameters const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384); // Duration of test const int nSteps = (argc > 2)?atoi(argv[2]):10; // Particle propagation time step const float dt = 0.0005f; struct ParticleType* particle = malloc(nParticles*sizeof(struct ParticleType)); // Initialize random number generator and particles //init_rand(nParticles, particle); // Initialize (no random generator) particles init_norand(nParticles, particle); // Perform benchmark printf("\nPropagating %d particles using 1 thread...\n\n", nParticles ); double rate = 0, dRate = 0; // Benchmarking data const int skipSteps = 3; // Skip first iteration (warm-up) printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); for (int step = 1; step <= nSteps; step++) { const double tStart = omp_get_wtime(); // Start timing MoveParticles(nParticles, particle, dt); const double tEnd = omp_get_wtime(); // End timing const float HztoInts = ((float)nParticles)*((float)(nParticles-1)) ; const float HztoGFLOPs = 20.0*1e-9*((float)(nParticles))*((float)(nParticles-1)); if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); #ifdef DUMP dump(step, nParticles, particle); #endif } rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); free(particle); return 0; }
0
ALLM
ALLM/C_SUJET1/openacc.c
#include <stdio.h> #include <math.h> #include <stdlib.h> // drand48 #include <omp.h> #define DUMP struct ParticleType { float x, y, z; float vx, vy, vz; }; void MoveParticles(const int nParticles, struct ParticleType* const particle, const float dt) { int i,j; float Fx,Fy,Fz; // Loop over particles that experience force #pragma parallel loop//acc kernels async(2) wait(1) for (i = 0; i < nParticles; i++) { // Components of the gravity force on particle i Fx = 0, Fy = 0, Fz = 0; // Loop over particles that exert force //#pragma acc parallel loop independent reduction(+:Fx,Fy,Fz) for (j = 0; j < nParticles; j++) { // No self interaction // Avoid singularity and interaction with self const float softening = 1e-20; // Newton's law of universal gravity const float dx = particle[j].x - particle[i].x; const float dy = particle[j].y - particle[i].y; const float dz = particle[j].z - particle[i].z; const float drSquared = dx*dx + dy*dy + dz*dz + softening; const float drPower32 = pow(drSquared, 3.0/2.0); // Calculate the net force Fx += dx / drPower32; Fy += dy / drPower32; Fz += dz / drPower32; } // Accelerate particles in response to the gravitational force particle[i].vx += dt*Fx; particle[i].vy += dt*Fy; particle[i].vz += dt*Fz; } // Move particles according to their velocities // O(N) work, so using a serial loop for (int i = 0 ; i < nParticles; i++) { particle[i].x += particle[i].vx*dt; particle[i].y += particle[i].vy*dt; particle[i].z += particle[i].vz*dt; } } void dump(int iter, int nParticles, struct ParticleType* particle) { char filename[64]; snprintf(filename, 64, "output_%d.txt", iter); FILE *f; f = fopen(filename, "w+"); int i; for (i = 0; i < nParticles; i++) { fprintf(f, "%e %e %e %e %e %e\n", particle[i].x, particle[i].y, particle[i].z, particle[i].vx, particle[i].vy, particle[i].vz); } fclose(f); } // Initialize random number generator and particles: void init_rand(int nParticles, struct ParticleType* particle){ srand48(0x2020); for (int i = 0; i < nParticles; i++) { particle[i].x = 2.0*drand48() - 1.0; particle[i].y = 2.0*drand48() - 1.0; particle[i].z = 2.0*drand48() - 1.0; particle[i].vx = 2.0*drand48() - 1.0; particle[i].vy = 2.0*drand48() - 1.0; particle[i].vz = 2.0*drand48() - 1.0; } } // Initialize (no random generator) particles void init_norand(int nParticles, struct ParticleType* particle){ const float a=127.0/nParticles; for (int i = 0; i < nParticles; i++) { particle[i].x = i*a;//2.0*drand48() - 1.0; particle[i].y = i*a;//2.0*drand48() - 1.0; particle[i].z = 1.0;//2.0*drand48() - 1.0; particle[i].vx = 0.5;//2.0*drand48() - 1.0; particle[i].vy = 0.5;//2.0*drand48() - 1.0; particle[i].vz = 0.5;//2.0*drand48() - 1.0; } } int main(const int argc, const char** argv) { // Problem size and other parameters const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384); // Duration of test const int nSteps = (argc > 2)?atoi(argv[2]):10; // Particle propagation time step const float dt = 0.0005f; struct ParticleType* particle = malloc(nParticles*sizeof(struct ParticleType)); // Initialize random number generator and particles //init_rand(nParticles, particle); // Initialize (no random generator) particles init_norand(nParticles, particle); // Perform benchmark printf("\nPropagating %d particles using 1 thread...\n\n", nParticles ); double rate = 0, dRate = 0; // Benchmarking data const int skipSteps = 3; // Skip first iteration (warm-up) printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); #pragma acc data copyin(particle[0:nParticles],dt) for (int step = 1; step <= nSteps; step++) { const double tStart = omp_get_wtime(); // Start timing #pragma acc update host(particle[0:nParticles]) MoveParticles(nParticles, particle, dt); #pragma acc update device(particle[0:nParticles]) const double tEnd = omp_get_wtime(); // End timing const float HztoInts = ((float)nParticles)*((float)(nParticles-1)) ; const float HztoGFLOPs = 20.0*1e-9*((float)(nParticles))*((float)(nParticles-1)); if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); #ifdef DUMP dump(step, nParticles, particle); #endif } rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); free(particle); }
0
ALLM
ALLM/GOL/RGOL.R
library('foreach') library('ggplot2') library('animation') library('reshape2') library('anim.plots') #install.packages("FFmpeg") #install.ffmpeg() #oopts = if (.Platform$OS.type == "windows") { #ani.options(ffmpeg = "ffmpeg/bin/ffmpeg.exe") #} #ffmpeg -i animated.gif -movflags faststart -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" video.mp4 #ffmpeg -i GOL.mp4 -r 160 -filter:v "setpts=0.25*PTS" GOL_speed.mp4 # args: args = commandArgs(trailingOnly=TRUE) # test if there is at least one argument: if not, return an error if (length(args)==0) { stop("At least one argument must be supplied (input file).n", call.=FALSE) } rep = paste("./",args[1],sep="") data = paste(rep,args[2],sep="/") out = paste(rep,args[1],sep="/") outmp4 = paste(out,"mp4",sep=".") outmp4speed = paste(paste(out,"speed",sep="_"),"mp4",sep=".") outgif = paste(out,"gif",sep=".") cmdmp4 = paste(paste(paste("ffmpeg -i",outmp4,sep=" "),"-r 8 -filter:v setpts=0.025*PTS",sep=" "),outmp4speed,sep=" ") cmdgif = paste(paste(paste("ffmpeg -i",outmp4speed,sep=" "),"-vf fps=5,scale=450:-1",sep=" "),outgif,sep=" ") print(data) print(out) print(outmp4) print(outmp4speed) print(cmdmp4) print(outgif) print(cmdgif) # Converts the current grid (matrix) to a ggplot2 image grid_to_ggplot <- function(subgrid) { subgrid$V <- factor(ifelse(subgrid$V, "Alive", "Dead")) #print(subgrid) p <- ggplot(subgrid, aes(x = J, y = I, z = V, color = V)) p <- p + geom_tile(aes(fill = V)) p + scale_fill_manual(values = c("Dead" = "blue", "Alive" = "red")) } grid = read.csv(data) grid2 = subset(grid, grid$T==110) saveVideo({ for(i in 0:160){ if(i<=110){ subgrid = subset(grid, grid$T==i);print(i)} else{subgrid = grid2;print(i)} grid_ggplot <- grid_to_ggplot(subgrid) print(grid_ggplot) } }, video.name = outmp4, clean = TRUE) #saveVideo({ #for(i in 0:160){ # subgrid = subset(grid, grid$T==i) # print(i) # grid_ggplot <- grid_to_ggplot(subgrid) # print(grid_ggplot) #} #}, video.name = outmp4, clean = TRUE) #system("ffmpeg -i GOL.mp4 -r 8 -filter:v setpts=0.025*PTS GOL_speed.mp4") system(cmdmp4, intern=TRUE) #system("ffmpeg -i GOL_speed.mp4 -vf fps=5,scale=450:-1 GOL_speed.gif") system(cmdgif, intern=TRUE)
0
ALLM
ALLM/GOL/main.cc
#include "GOL.h" #include <bits/stdc++.h> #include <cstdio> // g++ -std=c++17 -pg -g -O0 -Wall ex6v3.cpp -o run // valgrind --leak-check=yes ./run // gprof -l run *.out > analysis.txt using namespace std; #ifdef CASE #define GENREP() ((CASE==0)?("Random"):((CASE==1)?("Clown"):((CASE==2)?("Canon"):("Custom")))) #endif int main(int argc, char *argv[], char *envp[]){ // Display each command-line argument. cout << "\nCommand-line arguments:\n"; for( int count = 0; count < argc; count++ ){ cout << " argv[" << count << "] " << argv[count] << "\n"; } /*for( int i = 0; envp[i]!=NULL; i++ ){ cout << " envp[" << i << "] " << envp[i] << "\n"; }*/ string UserChoice; string InitFile; int dimi=100, dimj=90; if(CASE>2){ UserChoice = argv[1]; if(argv[2] != NULL){InitFile = argv[2];}else{InitFile = "mat.txt";} }else{UserChoice = GENREP();} cout<<" CASE "<<GENREP()<<" UserChoice "<<UserChoice<<"\n"; int iterationNB = 160; GOL game(dimi, dimj, UserChoice, InitFile); //GOL* game(0); //game = new GOL(dimi, dimj, UserChoice, InitFile); game.initialisation(); game.saveSolution(0); for(int ite = 1; ite<iterationNB+1; ite++){ game.play(); game.saveSolution(ite); } //delete game; //game = 0; return 0; }
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/Code_Dirichlet_LAST/main.f90
!----------------------------------- ! MAIN : PROGRAMME PRINCIPAL !----------------------------------- Program main !-------------modules-----------------! USE mpi use mod_parametres use mod_charge use mod_comm use mod_sol use mod_fonctions use mod_gradconj use mod_matsys !--------------------------------------! Implicit None !REAL POUR CONNAITRE LE TEMPS D'EXECUTION TOTAL ET DE CERTAINES SUBROUTINES REAL(PR) :: TPS1, TPS2, MAX_TPS REAL(PR) :: MINU, MAXU REAL(PR) :: RED_MINU, RED_MAXU REAL(PR) :: RED_SUMC, MAXC, TPSC1, TPSC2 REAL(PR) :: STA, STB, STM !------------INIT REGION PARA-----------------! !********* DEBUT REGION PARA: CALL MPI_INIT(stateinfo) !INITIALISATION DU //LISME CALL MPI_COMM_RANK(MPI_COMM_WORLD,rang,stateinfo) !ON RECUPERE LES RANGS !AU SEIN DE L'ENSEMBLE MPI_COMM_WORLD CALL MPI_COMM_SIZE(MPI_COMM_WORLD,Np,stateinfo) !ET LE NOMBRE DU PROCESSUS !---------------------------------------------! !******** READ USERCHOICE FOR CT AND SHARE IT WITH OTHER PROCESS IF(rang==0)THEN Print*,"______RESOLUTION DE L'ÉQUATION : DD SCHWARZ ADDITIVES //______" !---initialisation des variables cas test------------- Print*,"Donnez le cas test (1,2 ou 3):" Read*,CT PRINT*," POUR VISUALISATION ENTREZ 1, SINON 0" read*,sysmove END IF CALL MPI_BCAST(CT,1,MPI_INTEGER,0,MPI_COMM_WORLD,stateinfo) CALL MPI_BCAST(sysmove,1,MPI_INTEGER,0,MPI_COMM_WORLD,stateinfo) TPS1=MPI_WTIME() !******** COMPUTE SOME MATRIX_G DATA & GEO TIME DATA nnz_g=5*Na_g-2*Nx_g-2*Ny_g !nb d'elt non nul dans la matrice A_g IF(rang==0)THEN print*,"Nombre éléments non nuls du domaine A_g non DD ADDITIVE : nnz_g=",nnz_g print*,'Nombre de ligne Nx_g, colonne Ny_g de A_g',Nx_g,Ny_g Print*,"Lx=",Lx Print*,"Ly=",Ly Print*,"D=",D Print*," " Print*,"dx=",dx Print*,"dy=",dy Print*,"dt",dt Print*,"Tfinal=",Tf,"secondes" Print*," " print*,"alpha=",alpha print*,"beta=",beta print*,"gamma=",gamma Print*," " END IF !******* SET UP ONE TAG FILE NAMED TAG TO i/o: TAG=10+rang WRITE(rank,fmt='(1I3)')rang !WATCH OUT IF rang>999 !******* COMPUTE SIZE OF LOCAL DD OVER LOCAL MATRIX A_l SIZE OPEN(TAG,file='CHARGE/CHARGE'//trim(adjustl(rank))//'.dat') CALL MODE1(rang, Np, S1, S2, it1, itN)!-->DISTRIBUTION DE LA CHARGE PAR PROCESS S1_old = S1; S2_old = S2; it1_old = it1; itN_old = itN WRITE(TAG,*)'AVANT OVERLAP', S1, S2, it1, itN CALL CHARGE_OVERLAP(Np, rang, S1, S2, it1, itN)!-->MODIFICATION DE LA CHARGE EN FONCTION DE L'OVERLAP WRITE(TAG,*)'APRES OVERLAP', S1, S2, it1, itN !SET SIZE OF MATRICES AND INTEGER CONTROL SIZE: Nx_l = S2 - S1 + 1; Ny_l = Ny_g; Na_l = Nx_l * Ny_l nnz_l = 5 * Na_l - 2 * Nx_l - 2 * Ny_l crtl_nnz_l = (Nx_l*Ny_l) + 2 * (Nx_l) * (Ny_l - 1) + 2 * (Nx_l - 1) * (Ny_l) WRITE(TAG,*)'Nxl,Ny_l,Na_l', Nx_l, Ny_l, Na_l WRITE(TAG,*)'nnz_l,crtl_nnz_l', nnz_l,crtl_nnz_l CLOSE(TAG) !COMPUTE SIZE D,C AND CRTL_L_nnz: D_rows = Ny_l; D_nnz = D_rows+2*(D_rows-1) C_rows = Ny_l; C_nnz = C_rows crtl_L1_nnz = D_nnz+C_nnz crtl_L2_nnz = (Nx_l-2)*(D_nnz+2*C_nnz) crtl_L3_nnz = D_nnz+C_nnz sum_crtl_L_nnz = crtl_L1_nnz+crtl_L2_nnz+crtl_L3_nnz crtl_L1_nnz_Nxl_EQV_1 = D_nnz IF(Nx_l > 1)THEN IF(crtl_nnz_l/=nnz_l .AND. nnz_l/=sum_crtl_L_nnz)THEN PRINT*,'ERROR,RANG=',rang,'Local Matrix A_l.rows,A_l.cols',Nx_l,Ny_l,nnz_l,& &'A_l_nnz,crtl_nnz_l,sum_crtl_L_nnz',nnz_l,crtl_nnz_l,sum_crtl_L_nnz GOTO 9999 END IF ELSE IF(Nx_l == 1)THEN IF(crtl_nnz_l/=nnz_l .AND. nnz_l/=crtl_L1_nnz_Nxl_EQV_1)THEN PRINT*,'ERROR,RANG=',rang,'Local Matrix A_l.rows,A_l.cols',Nx_l,Ny_l,nnz_l,& &'A_l_nnz,crtl_nnz_l,crtl_L1_nnz_Nxl_EQV_1',nnz_l,crtl_nnz_l,crtl_L1_nnz_Nxl_EQV_1 GOTO 9999 END IF END IF !******* COMPUTE CARTESIAN GRID OVER PROCESS i.e CHARGE APPLY TO X,Y,T IF(Np/=1)THEN CALL param_para(rang,Np,S1,S2,Ny_l,X,Y,T) ELSE CALL param(X,Y,T) PRINT*,'NBR PROCESS = 1' END IF !****** ALLOCATE Uo ET U ALLOCATE(U(it1:itN),Uo(it1:itN)) Uo=1._PR !-->CI pour le gradient conjugué U=1._PR !-->vecteur solution initialisé call WR_U(U,0)!-->SAVE SOL CALL matsys_v2(nnz_l,Nx_l,Ny_l,AA,IA,JA)!-->on construit A OPEN(TAG,file='MAT_VIZU/matrice_A_'//trim(adjustl(rank))//'.dat')!-->POUR VISUALISER LES MATRICES DO i=1,nnz_l WRITE(TAG,*)AA(i),IA(i),JA(i) END DO CLOSE(TAG) ALLOCATE(F(it1:itN))!-->SECOND MEMBRE:F=Uo+dt*SOURCE_FUNCTION+CL ALLOCATE(UG(it1-Ny_g:it1-1),UD(itN+1:itN+Ny_g))!-->VECTEURS POUR ECHANGER LES PARTIES IMMERGEES UG = 0.0_PR; UD = 0.0_PR!-->INITITALISATION !---boucle principale (résolution systeme) et ecriture a chaque itération--- Print*,"----------DÉBUT DU CALCUL DE LA SOLUTION------------" Pivot=(Np-mod(Np,2))/2!-->PIVOT DE COMMUNICATION POUR COMM_PTOP_2WAY: RED_SUMC = 0.0_PR IF(Np>1)THEN timeloop:Do i=1,Nt!BOUCLE EN TEMPS err = 1.0_PR; step = 1; Norm2 = 0.0_PR !STA = MPI_WTIME() schwarzloop:DO WHILE(err>err_LIM .OR. step<3)!BOUCLE POUR LA CONVERGENCE DE SCHWARZ step = step +1 Norm1 = Norm2 call vectsource_FULL(CT,U,UG,UD,S1,S2,X,Y,T(i),F)!CALCUL DU SECOND MEMBRE call MOD_gradconj_SPARSE(AA,IA,JA,f,Uo,U,res,k,it1,itN)!RESOLUTION DU SYSTEME !call BICGSTAB(it1,itN,AA,IA,JA,U,F,0.0000000001_PR) !call MOD_jacobi_SPARSE(AA,IA,JA,F,Uo,U,res,k) TPSC1 = MPI_WTIME() call COMM_PTOP(U,UG,UD)!COMMUNICATION DE LA SOLUTION AUX FRONTIERES IMMERGEES !call COMM_PTOP_2WAY(U,UG,UD)!-->une petite reduction du temps des communications(pour Np>=5) TPSC2 = MPI_WTIME() RED_SUMC = RED_SUMC + (TPSC2-TPSC1) Uo=U !SWAP if(rang==0)then!CALCUL DE LA NORME 2 SUR LES PARTIES CORRESPONDANT AUX FRONTIERES IMMERGEE DU VECTEURS SOLUTION C1 = DOT_PRODUCT(U(itN-Ny_l+1:itN),U(itN-Ny_l+1:itN)) else if(rang==Np-1)then C1 = DOT_PRODUCT(U(it1:it1+Ny_l-1),U(it1:it1+Ny_l-1)) else C1 = DOT_PRODUCT(U(it1:it1+Ny_l-1),U(it1:it1+Ny_l-1))+DOT_PRODUCT(U(itN-Ny_l+1:itN),U(itN-Ny_l+1:itN)) end if !POSSIBILITE DE FAIRE CE CALCUL SUR TOUT LE DOMAINE APRES OVERLAP OU BIEN AVANT OVERLAP: !C1 = DOT_PRODUCT(U(it1:itN),U(it1:itN)) !C1 = DOT_PRODUCT(U(it1_old:itN_old),U(it1_old:itN_old)) Call MPI_ALLREDUCE(C1,Norm2,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,stateinfo) Norm2 = SQRT(Norm2)!CALCUL DE LA NORME 2 err = abs(Norm1-Norm2)!CALCUL DE L'ERREUR END DO schwarzloop !STB = MPI_WTIME() if(mod(i,10)==0)then print*,'it temps',i end if End Do timeloop !CALL MPI_ALLREDUCE(STB-STA,STM,1,MPI_DOUBLE,MPI_MAX,MPI_COMM_WORLD,stateinfo) !PRINT*,'STM',STM,'STEP',STEP ELSE IF(Np==1)THEN Do i=1,Nt call vectsource_FULL(CT,U,UG,UD,S1,S2,X,Y,T(i),F) call MOD_gradconj_SPARSE(AA,IA,JA,f,Uo,U,res,k,it1,itN) !call MOD_jacobi_SPARSE(AA,IA,JA,F,Uo,U,res,k) Uo=U !SWAP if(mod(i,10)==0)then print*,'it temps',i end if End Do END IF !SAVE SOL : call WR_U(U,Nt) DEALLOCATE(UG,UD) !WRITE SOL EXACTE: IF(CT < 3)THEN call UEXACT(U,CT) END IF RED_MINU = minval(U) RED_MAXU = maxval(U) !POUR LES TEMPS DE CALCULS: CALL MPI_ALLREDUCE(RED_MINU,MINU,1,MPI_DOUBLE_PRECISION,MPI_MIN,MPI_COMM_WORLD,stateinfo) CALL MPI_ALLREDUCE(RED_MAXU,MAXU,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) if(Np>1)then CALL MPI_ALLREDUCE(RED_SUMC,MAXC,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) end if DEALLOCATE(U,Uo,X,Y,T,AA,IA,JA,F) TPS2=MPI_WTIME() CALL MPI_ALLREDUCE(TPS2-TPS1,MAX_TPS,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) IF(rang==0)THEN PRINT*,'TEMPS CALCUL=',MAX_TPS,' TEMPS COMM=',MAXC END IF CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) IF(crtl_nnz_l == nnz_l)THEN GOTO 6666 END IF 9999 PRINT*,rang,'GOTO9999crtl_nnz_l /= nnz_l ERROR',crtl_nnz_l,nnz_l 6666 PRINT*,rang,'GOTO6666NEXT INSTRUCTION IS MPI_FINALIZE',crtl_nnz_l,nnz_l !---ecriture solution finale-------------------------- call CONCAT_VIZU_ONLY_Nt(sysmove,MINU,MAXU) CALL MPI_FINALIZE(stateinfo) Print*,"------------------CALCUL TERMINÉ--------------------" !---------------------------------------------- CONTAINS Subroutine CONCAT_VIZU(sysmove) Integer, Intent(INOUT):: sysmove CHARACTER(LEN=3):: NNT CHARACTER(LEN=1)::ESPACE CHARACTER(LEN=20)::NFILE,OUT_FILE INTEGER::i !VIZUALISATION SEQUENTIELLE: ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE RANG DIFFERENTS DANS UN FICHIER IF(rang==0.AND.sysmove==1)THEN ESPACE=' ' DO i=0,Nt WRITE(NNT,fmt='(1I3)')i; NFILE='U_ME*'//'_T'//trim(adjustl(NNT));OUT_FILE='UT_'//trim(adjustl(NNT))//'.dat' !ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE RANG DIFFERENTS DANS UN FICHIER CALL system('cat SOL_NUMERIQUE/'//NFILE//' >> SOL_NUMERIQUE/'//OUT_FILE) CALL system('rm SOL_NUMERIQUE/'//NFILE) OPEN(20,file='SOL_NUMERIQUE/'//OUT_FILE,position='append') SELECT CASE(CT)!ICI IL FAUT RAJOUTER LES POINTS AUX COINS DU DOMAINES CASE(1) WRITE(20,*)0.0d0,0.0d0,0.0d0;WRITE(20,*)Lx,0.0d0,0.0d0 WRITE(20,*)0.0d0,Ly,0.0d0;WRITE(20,*)Lx,Ly,0.0d0 CASE(2) WRITE(20,*)0.0d0,0.0d0,1.0d0;WRITE(20,*)Lx,0.0d0,1.0d0+sin(Lx) WRITE(20,*)0.0d0,Ly,cos(Ly);WRITE(20,*)Lx,Ly,cos(Ly)+sin(Lx) CASE(3) WRITE(20,*)0.0d0,0.0d0,0.5d0;WRITE(20,*)Lx,0.0d0,0.5d0!TEMPERATURES IMPOSEES DIFFERENTES, ON MOYENNE:((G+H)/2) WRITE(20,*)0.0d0,Ly,0.5d0;WRITE(20,*)Lx,Ly,0.5d0 END SELECT WRITE(20,fmt='(1A1)')ESPACE WRITE(20,fmt='(1A1)')ESPACE CLOSE(20) !ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE TEMPS DIFFERENTS DANS UN FICHIER CALL system('cat SOL_NUMERIQUE/'//OUT_FILE//' >> SOL_NUMERIQUE/U.dat') CALL system('rm SOL_NUMERIQUE/'//OUT_FILE) END DO !A LA FIN, IL RESTE UN FICHIER OU LA SOLUTION EN TEMPS EST SOUS FORME D'INDEX GNUPLOT !ON APPELLE LA SUBROUTIEN DE VISUALISATION: CALL VIZU_SOL_NUM(CT) END IF End Subroutine CONCAT_VIZU Subroutine CONCAT_VIZU_ONLY_Nt(sysmove,MINU,MAXU) Integer, Intent(INOUT):: sysmove REAL(PR), Intent(IN) :: MINU, MAXU CHARACTER(LEN=3):: NNT CHARACTER(LEN=1)::ESPACE CHARACTER(LEN=20)::NFILE,OUT_FILE INTEGER::i !VIZUALISATION SEQUENTIELLE: ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE RANG DIFFERENTS DANS UN FICHIER IF(rang==0.AND.sysmove==1)THEN ESPACE=' ' DO i=Nt,Nt WRITE(NNT,fmt='(1I3)')i; NFILE='U_ME*'//'_T'//trim(adjustl(NNT));OUT_FILE='UT_'//trim(adjustl(NNT))//'.dat' !ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE RANG DIFFERENTS DANS UN FICHIER CALL system('cat SOL_NUMERIQUE/'//NFILE//' >> SOL_NUMERIQUE/'//OUT_FILE) CALL system('rm SOL_NUMERIQUE/'//NFILE) OPEN(20,file='SOL_NUMERIQUE/'//OUT_FILE,position='append') SELECT CASE(CT)!ICI IL FAUT RAJOUTER LES POINTS AUX COINS DU DOMAINES CASE(1) WRITE(20,*)0.0d0,0.0d0,0.0d0;WRITE(20,*)Lx,0.0d0,0.0d0 WRITE(20,*)0.0d0,Ly,0.0d0;WRITE(20,*)Lx,Ly,0.0d0 CASE(2) WRITE(20,*)0.0d0,0.0d0,1.0d0;WRITE(20,*)Lx,0.0d0,1.0d0+sin(Lx) WRITE(20,*)0.0d0,Ly,cos(Ly);WRITE(20,*)Lx,Ly,cos(Ly)+sin(Lx) CASE(3) WRITE(20,*)0.0d0,0.0d0,0.5d0;WRITE(20,*)Lx,0.0d0,0.5d0!TEMPERATURES IMPOSEES DIFFERENTES, ON MOYENNE:((G+H)/2) WRITE(20,*)0.0d0,Ly,0.5d0;WRITE(20,*)Lx,Ly,0.5d0 END SELECT WRITE(20,fmt='(1A1)')ESPACE WRITE(20,fmt='(1A1)')ESPACE CLOSE(20) !ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE TEMPS DIFFERENTS DANS UN FICHIER CALL system('cat SOL_NUMERIQUE/'//OUT_FILE//' >> SOL_NUMERIQUE/U.dat') CALL system('rm SOL_NUMERIQUE/'//OUT_FILE) END DO !A LA FIN, IL RESTE UN FICHIER OU LA SOLUTION EN TEMPS EST SOUS FORME D'INDEX GNUPLOT !ON APPELLE LA SUBROUTIEN DE VISUALISATION: !CALL VIZU_SOL_NUM(CT) CALL VIZU_SOL_NUM_ONLY_Nt(CT,MINU,MAXU) END IF End Subroutine CONCAT_VIZU_ONLY_Nt End Program main
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/Code_Dirichlet_LAST/mod_charge.f90
module mod_charge use mod_parametres Implicit None CONTAINS !************************** !^ y Ny !| !| !| !1---------> x Nx !************************* !SE BASE SUR LA CHARGE EN X POUR CALCULER LA CHARGE TOTALE(GLOBALE) !INDUIT POUR MOD(DIM,Np)/=0 UNE DIFFERENCE DE CHARGE = A Ny ENTRE 2 PROCS !UTILISABLE POUR Np<=INTER_X Subroutine MODE1(rang, Np, S1, S2, it1, itN) Integer, Intent(IN) :: rang, Np Integer, Intent(OUT) :: S1, S2,it1, itN !CHARGE EN X : CALL CHARGE_X(rang, Np, S1, S2) !CHARGE TOT : CALL CHARGE_TOT(S1, S2, it1, itN) End Subroutine MODE1 !REPARTITION CLASSIQUE DE LA CHARGE EN X Subroutine CHARGE_X(rang, Np, S1,S2) Integer, Intent(IN) :: rang, Np Integer, Intent(OUT) :: S1, S2 REAL :: CO_RE !COEFFICIANT DE REPARTITION IF(Np == 1)THEN S1 = 1; S2 = Nx_g ELSE CO_RE=(Nx_g)/(Np) If(rang < mod(Nx_g,Np))Then S1 = rang*(CO_RE+1) + 1; S2 = (rang+1) * (CO_RE+1) Else S1 = 1 + mod(Nx_g,Np) + rang*CO_RE; S2 = S1+CO_RE-1 End If END IF End Subroutine CHARGE_X !CHARGE TOTALE SUR LA NUMEROTATION GLOBALE Subroutine CHARGE_TOT(S1, S2, it1, itN) Integer, Intent(IN) :: S1, S2 Integer, Intent(OUT) :: it1, itN it1 = (S1-1)*Ny_g+1; itN = S2*Ny_g End Subroutine CHARGE_TOT !RE-COMPUTE CHARGE WITH OVERLAP Subroutine CHARGE_OVERLAP(Np, rang, S1, S2, it1, itN) Implicit None Integer, Intent(IN) ::Np, rang Integer, Intent(INOUT) ::S1, S2, it1, itN !Le (-1) sur overlap pour retirer la frontiere !immergée qui passe en CL !WE PUT A Ny_g BECAUSE Ny_l == Ny_g and Ny_l is defined after this subroutine !Also Because IT'S a 1D DD !IF WE WANT TO SET UP A 2D DD I WILL NEED DO REPLACE Ny_g BY Ny_l !AND MAKE OTHER MODIFICATION IF(rang == 0)THEN S2 = S2 + (overlap-1) itN = itN + (overlap-1) * Ny_g ELSE IF(rang == Np-1)THEN S1 = S1 - (overlap-1) it1 = it1 - (overlap-1) * Ny_g ELSE S1 = S1 - (overlap-1) S2 = S2 + (overlap-1) it1 = it1 - (overlap-1) * Ny_g itN = itN + (overlap-1) * Ny_g END IF End Subroutine CHARGE_OVERLAP end module mod_charge
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/Code_Dirichlet_LAST/mod_comm.f90
module mod_comm use mpi use mod_parametres Implicit None CONTAINS ! UG et UD les parties du vecteur solution U Correspondant à/aux frontière(s) ! immergée(s). Subroutine COMM_PTOP(U,UG,UD) Real(PR), DImension(it1:itN), Intent(IN):: U Real(PR), DImension(it1-Ny_g:it1-1), Intent(INOUT):: UG Real(PR), DImension(itN+1:itN+Ny_g), Intent(INOUT):: UD Integer:: A, B, C, D, iD1, iD2, iG1, iG2 B = itN - 2*(overlap-1)*Ny_g; A = B - (Ny_g-1) C = it1 +2*(overlap-1)*Ny_g; D = C + (Ny_g-1) iD1 = itN + 1; iD2 = itN + Ny_g iG1 = it1 - Ny_g; iG2 = it1 -1 IF(rang == 0)THEN ! rang tag channel CALL MPI_SEND(U(A:B),Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(UD(iD1:iD2),Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) ELSE IF(rang > 0 .AND. rang<Np-1)THEN CALL MPI_RECV(UG(iG1:iG2),Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) CALL MPI_SEND(U(C:D),Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(U(A:B),Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(UD(iD1:iD2),Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) ELSE IF(rang == Np-1)THEN CALL MPI_RECV(UG(iG1:iG2),Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) CALL MPI_SEND(U(C:D),Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) END IF End Subroutine COMM_PTOP Subroutine COMM_PTOP_2WAY(U,UG,UD) Real(PR), DImension(it1:itN), Intent(IN):: U Real(PR), DImension(it1-Ny_g:it1-1), Intent(INOUT):: UG Real(PR), DImension(itN+1:itN+Ny_g), Intent(INOUT):: UD Integer:: A, B, C, D, iD1, iD2, iG1, iG2 B = itN - 2*(overlap-1)*Ny_g; A = B - (Ny_g-1) C = it1 +2*(overlap-1)*Ny_g; D = C + (Ny_g-1) iD1 = itN + 1; iD2 = itN + Ny_g iG1 = it1 - Ny_g; iG2 = it1 -1 IF(rang == 0)THEN ! rang tag channel CALL MPI_SEND(U(A:B),Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(UD(iD1:iD2),Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) ELSE IF(rang > 0 .AND. rang<Pivot)THEN CALL MPI_RECV(UG(iG1:iG2),Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) CALL MPI_SEND(U(C:D),Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(U(A:B),Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(UD(iD1:iD2),Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) ELSE IF(rang >= Pivot .AND. rang < Np-1)THEN CALL MPI_RECV(UD(iD1:iD2),Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) CALL MPI_SEND(U(A:B),Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(U(C:D),Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(UG(iG1:iG2),Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) ELSE IF(rang == Np-1)THEN CALL MPI_SEND(U(C:D),Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(UG(iG1:iG2),Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) END IF End Subroutine COMM_PTOP_2WAY end module mod_comm
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/Code_Dirichlet_LAST/mod_fonctions.f90
!--------------------------------------------- ! CE MODULE CONTIENT LES FONCTIONS ! DES TERMES SOURCES DE L'EQUATION !--------------------------------------------- Module mod_fonctions !---modules------------------- use mod_parametres !----------------------------- Implicit None Contains !CT --> tag pour moduler les fct suivant le CAS test !(x,y,t) --> coordonnees espace et le temps !---fonction f premier exemple(terme source)--- Real(PR) Function f1(CT,x,y,t) Integer, Intent(In) :: CT Real(PR), Intent(In) :: x, y, t f1 = 0.0_PR If ( CT == 1 ) Then f1 = 2._PR * (y*(1._PR-y)+x*(1._PR-x)) Else IF ( CT == 2 ) Then f1 = sin(x) + cos(y) Else If ( CT == 3 ) Then f1 = exp(-((x-(Lx/2._PR))**2._PR)) * exp(-((y-(Ly/2._PR))**2._PR))& *cos((pi/2._PR)*t) End If End Function f1 !---------------------------------------------- !---fonction g premier exemple( bords haut/bas)-Conditions limites Real(PR) Function g1(CT,x,y,t) Integer, Intent(In) :: CT Real(PR), Intent(In) :: x,y,t g1 = 0.0_PR If ( CT == 1 ) Then g1 = 0._PR Else IF ( CT == 2 ) Then g1 = sin(x) + cos(y) Else If ( CT == 3 ) Then g1 = 0._PR End If End Function g1 !---------------------------------------------- !---function h premier exemple(bord gauche/droite)-Condition Limites Real(PR) Function h1(CT,x,y,t) Integer, Intent(In) :: CT Real(PR), Intent(In) :: x,y,t h1 = 0.0_PR If ( CT == 1 ) Then h1 = 0._PR Else IF ( CT == 2 ) Then h1 = sin(x) + cos(y) Else If ( CT == 3 ) Then h1 = 1._PR End If End Function h1 !---Fonctions donnant les vecteurs Xi,Yj,Tn--------------- !Pour discretiser espace et le temps: !verision sequentiel Subroutine param(X,Y,T) Implicit None !---variables------------------------- real(PR), Dimension(:), Allocatable, Intent(InOut) :: X real(PR), Dimension(:), Allocatable, Intent(InOut) :: Y real(PR), Dimension(:), Allocatable, Intent(InOut) :: T Integer :: i !------------------------------------- ALLOCATE(Y(0:Ny_g+1),T(0:Nt+1),X(0:Nx_g+1)) Do i=0,Ny_g+1 Y(i)=i*dy End Do Do i=0,Nt+1 T(i)=i*dt End Do DO i=0,Nx_g+1 X(i)=i*dx END DO LBX = lbound(X,1) UBX = ubound(X,1) End Subroutine param !version parallele: Subroutine param_para(rang,Np,S1,S2,Ny_l,X,Y,T) Implicit None !---variables------------------------- Integer, Intent(IN) :: rang, Np, S1, S2, Ny_l real(PR), Dimension(:), Allocatable, Intent(InOut) :: X real(PR), Dimension(:), Allocatable, Intent(InOut) :: Y real(PR), Dimension(:), Allocatable, Intent(InOut) :: T Integer :: i !------------------------------------- ALLOCATE(Y(0:Ny_l+1),T(0:Nt+1)) Do i=0,Ny_l+1 Y(i)=i*dy End Do Do i=0,Nt+1 T(i)=i*dt End Do IF(rang == 0)THEN ALLOCATE(X(S1-1:S2)) Do i=S1-1,S2 X(i)=i*dx End Do ELSE IF(rang == Np-1)THEN ALLOCATE(X(S1:S2+1)) DO i=S1,S2+1 X(i)=i*dx END DO ELSE ALLOCATE(X(S1:S2)) DO i=S1,S2 X(i)=i*dx END DO END IF LBX = lbound(X,1) UBX = ubound(X,1) End Subroutine param_para !------------------------------------------------------------- End Module mod_fonctions
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/Code_Dirichlet_LAST/mod_gradconj.f90
!----------------------------------------- ! CE MODULE CONTIENT LE GRADIENT CONJUGUÉ ! EN PLEIN ET EN CREUX (FORMAT COORDONNES) !----------------------------------------- Module mod_gradconj !---modules---------------- use mod_parametres use mod_fonctions !-------------------------- Implicit None Contains !---GRADIENT CONJUGUÉ POUR UNE MATRICE A PLEINE--------- Subroutine gradconj(A,b,x0,x,beta,k,n) !---variables------------------------------------ Integer, Intent(In) :: n !taille vecteur solution (=taille de la matrice carrée) Real(PR), Dimension(:,:), Intent(In) :: A !matrice à inverser Real(PR), Dimension(:), Intent(In) :: b,x0 ! b second membre, x0 CI Real(PR), Dimension(:), Intent(Out) :: x !solution finale Real(PR), Intent(Out) :: beta !norme du résidu Real(PR), Dimension(:), Allocatable :: p,z,r1,r2 Real(PR) :: alpha,gamma,eps Integer, Intent(Out) :: k !nb d'itération pr convergence Integer :: kmax !------------------------------------------------- eps=0.01_PR kmax=150 Allocate(p(n),z(n),r1(n),r2(n)) r1=b-matmul(A,x0) p=r1 beta=sqrt(sum(r1*r1)) k=0 Do While (beta>eps .and. k<=kmax) z=matmul(A,p) alpha=dot_product(r1,r1)/dot_product(z,p) x=x+alpha*p r2=r1-alpha*z gamma=dot_product(r2,r2)/dot_product(r1,r1) p=r2+gamma*p beta=sqrt(sum(r1*r1)) k=k+1 r1=r2 End Do If (k>kmax) then Print*,"Tolérance non atteinte:",beta End If Deallocate(p,z,r1,r2) End Subroutine gradconj !---------------------------------------------------- !---GRADIENT CONJUGUÉ POUR MATRICE CREUSE AU FORMAT COORDONNÉES----- !---A PARALLELISER : PRODUIT MATRICE/VECTEUR + PRODUIT SCALAIRE Subroutine gradconj_SPARSE(AA,IA,JA,F,x0,x,b,k,n) Implicit None !---variables --------------------------------------- Integer, Intent(In) :: n !taille vecteur solution Real(PR), Dimension(:), Intent(In) :: AA Integer, Dimension(:), Intent(In) :: IA,JA Real(PR), Dimension(:), Intent(In) :: f,x0 !f=vect source , x0=CI Real(PR), Dimension(:), Intent(InOut) :: x !solution finale Real(PR), Intent(Out) :: b !norme du résidu Real(PR), Dimension(:), Allocatable :: p,z,r1,r2 Real(PR) :: a,g,eps Integer, Intent(Out) :: k !nb d'itérations pour convergence Integer :: kmax !nb d'itérations max !----------------------------------------------------- eps=0.01_PR kmax=1500 Allocate(p(n),z(n),r1(n),r2(n)) !---paralléliser------------------------ r1=f-MatVecSPARSE(AA,IA,JA,x0) !------------------------------------- p=r1 b=sqrt(sum(r1*r1)) k=0 Do While (b>eps .and. k<=kmax) !---paralléliser------------------ z=MatVecSPARSE(AA,IA,JA,p) !--------------------------------- a=dot_product(r1,r1)/dot_product(z,p) x=x+a*p r2=r1-a*z g=dot_product(r2,r2)/dot_product(r1,r1) p=r2+g*p b=sqrt(sum(r1*r1)) k=k+1 r1=r2 End Do If (k>kmax) then Print*,"Tolérance non atteinte:",b End If Deallocate(p,z,r1,r2) End Subroutine gradconj_SPARSE !-------------------------------------------------------------- !---FONCTION PRODUIT MATxVEC EN SPARSE------------------------- Function MatVecSPARSE(AA,IA,JA,x) Result(y) !Produit MatriceSPARSE.vecteur plein (x) retourne vecteur plein(y) !---variables------------------------------------------ Real(PR), Dimension(:), Intent(In) :: AA,x Integer, Dimension(:), Intent(In) :: IA,JA Real(PR), Dimension(Size(x)) :: y Integer :: i,n,nnz !-------------------------------------------------------- n=Size(x,1) nnz=Size(AA,1) y(1:n)=0._PR Do i=1,nnz if (IA(i)==0) then print*,"element IA nul pour i =",i end if y(IA(i))=y(IA(i))+AA(i)*x(JA(i)) End Do End Function MatVecSPARSE !--------------------------------------------------------------- !GC COO FORMAT BUILD FOR global numerotation over x Subroutine MOD_gradconj_SPARSE(AA,IA,JA,f,x0,x,b,k,it1,itN) Implicit None !---variables --------------------------------------- Integer, Intent(In) :: it1,itN !taille vecteur solution Real(PR), Dimension(:), Intent(In) :: AA Integer, Dimension(:), Intent(In) :: IA,JA Real(PR), Dimension(it1:itN), Intent(In) :: f,x0 !f=vect source , x0=CI Real(PR), Dimension(it1:itN), Intent(InOut) :: x !solution finale Real(PR), Intent(Out) :: b !norme du résidu Real(PR), Dimension(:), Allocatable :: p,z,r1,r2 Real(PR) :: a,g,eps Integer, Intent(Out) :: k !nb d'itérations pour convergence Integer :: kmax !nb d'itérations max !----------------------------------------------------- eps=0.0000000001_PR kmax=2*Na_l!1500 Allocate(p(it1:itN),z(it1:itN),r1(it1:itN),r2(it1:itN)) !---paralléliser------------------------ r1=f-MOD_MatVecSPARSE(AA,IA,JA,x0,it1,itN) !------------------------------------- p=r1 b=sqrt(sum(r1*r1)) k=0 Do While (b>eps .and. k<=kmax) !---paralléliser------------------ z=MOD_MatVecSPARSE(AA,IA,JA,p,it1,itN) !--------------------------------- a=dot_product(r1,r1)/dot_product(z,p) x=x+a*p r2=r1-a*z g=dot_product(r2,r2)/dot_product(r1,r1) p=r2+g*p b=sqrt(sum(r1*r1)) k=k+1 r1=r2 !PRINT*,'k,b',k,b End Do If (k>kmax) then Print*,"Tolérance non atteinte:",b End If Deallocate(p,z,r1,r2) End Subroutine MOD_gradconj_SPARSE !-------------------------------------------------------------- !---FONCTION PRODUIT MATxVEC EN SPARSE------------------------- Function MOD_MatVecSPARSE(AA,IA,JA,x,it1,itN) Result(y) !Produit MatriceSPARSE.vecteur plein (x) retourne vecteur plein(y) !---variables------------------------------------------ INTEGER,INTENT(IN)::it1,itN Real(PR), Dimension(:), Intent(In) :: AA Real(PR), Dimension(it1:itN), Intent(In) ::x Integer, Dimension(:), Intent(In) :: IA,JA Real(PR), Dimension(it1:itN) :: y Integer :: i,n,nnz,val !-------------------------------------------------------- n=Size(x,1) !PRINT*,'***',n,itN-it1+1 nnz=Size(AA,1) y(it1:itN)=0._PR val=(it1-1) Do i=1,nnz if (IA(i)==0) then print*,"element IA nul pour i =",i end if !PRINT*,i,IA(i),val+IA(i),JA(i),val+JA(i),x(val+JA(i)) y(val+IA(i))=y(val+IA(i))+AA(i)*x(val+JA(i)) End Do End Function MOD_MatVecSPARSE !--------------------------------------------------------------- Subroutine MOD_jacobi_SPARSE(AA,IA,JA,F,x0,x,resnorm,k) !-----variables--------------------- Real(PR), Dimension(nnz_l), Intent(In) :: AA Integer, Dimension(nnz_l), Intent(In) :: IA,JA Real(PR), Dimension(it1:itN), Intent(InOut) :: F,x0 !f=vect source , x0=CI Real(PR), Dimension(it1:itN), Intent(InOut) :: x !solution finale Real(PR), Intent(Out) :: resnorm !norme du résidu Real(PR), Dimension(:), Allocatable :: r Real(PR) :: eps,somme Integer, Intent(InOut) :: k !nb d'itérations pour convergence Integer :: kmax,pp,val,ii,borne !nb d'itérations max ALLOCATE(r(it1:itN)) borne=nnz_l+1 x=x0 eps = 0.0000000001_PR kmax = 2*Na_l*Na_l r = F-MOD_MatVecSPARSE(AA,IA,JA,x0,it1,itN) !résidu initial resnorm = sqrt(sum(r*r)) !norme 2 du résidu k = 0 !initialisation itération boucle_resolution: Do While ((resnorm>eps) .and. (k<kmax)) k=k+1 !on calcule xi^k+1=(1/aii)*(bi-sum(j=1,n;j/=i)aij*xj^k) x0=0._PR pp=1;val=it1-1 boucle_xi: Do ii=1,Na_l !calcul de la somme des aij*xj^k pour j=1,n;j/=i somme = 0.0_PR; !!$ if(rang==0)then !!$ PRINT*,'ii,pp,k,nnz_l,ubound IA',ii,pp,k,nnz_l,ubound(IA,1),nnz_l+1 !!$ end if DO WHILE((pp<borne) .AND. (ii==IA(pp))) IF (IA(pp) /= JA(pp)) THEN somme= somme + x(val+JA(pp)) * AA(pp) END IF !!$ if(rang==0)then !!$ PRINT*,'ii,pp,IA(pp),JA(pp),AA(pp),x(JA(pp))',ii,pp,IA(pp),JA(pp),AA(pp),x(val+JA(pp)) !!$ end if pp=pp+1 !PRINT*,'pp',pp if(pp==borne)then !because the do while check both pp<borne and ii==IA(pp),maybe due to makefile ! he should break when pp>=borne and don't check ii==IA(pp) GOTO 7777 end if END DO !calcul du nouveau xi 7777 x0(val+ii)=(1._PR/alpha)*(F(val+ii)-somme) x0(val+ii)=(1._PR/alpha)*(F(val+ii)-somme)!;print*,'t',rang End Do boucle_xi x=x0 !on calcule le nouveau résidu r = F - MOD_MatVecSPARSE(AA,IA,JA,x,it1,itN) ! calcul de la norme 2 du résidu resnorm = sqrt(sum(r*r)) !print*,resnorm,k End Do boucle_resolution If (k>kmax) then Print*,"Tolérance non atteinte:",resnorm End If DEALLOCATE(r) End Subroutine MOD_jacobi_SPARSE Subroutine BICGSTAB(it1,itN,AA,IA,JA,x,b,eps) Implicit None Integer, intent(IN) :: it1, itN Real(PR), Dimension(:), intent(IN) :: AA Integer, Dimension(:), intent(IN) :: IA, JA Real(PR), Dimension(:), intent(INOUT) :: x Real(PR), Dimension(:), intent(IN) :: b Real(PR), intent(IN) :: eps Real(PR), Dimension(it1:itN) :: r0, v, p ,r, h, s, t Real(PR) :: rho_i, rho_im1, alpha_CG, w, beta_cg Real(PR) :: omega Real(PR) :: beta Integer :: k, kmax kmax = 2*Na_l*Na_l omega = 1.0_PR r0 = b -MOD_MatVecSPARSE(AA, IA, JA, x, it1, itN) r = r0 rho_im1 = 1.0_PR; alpha_CG = 1.0_PR; w = 1.0_PR v = 0.0_PR; p = 0.0_PR k = 0 beta = SQRT(DOT_PRODUCT(r0,r0)) DO WHILE(beta>eps.AND.k<kmax) rho_i = DOT_PRODUCT(r0,r) beta_CG = (rho_i/rho_im1)*(alpha_CG/w) p = r + beta_CG*(p-v*w) v = MOD_MatVecSPARSE(AA,IA,JA,p,it1,itN) alpha_CG = rho_i/DOT_PRODUCT(r0,v) h = x + p*alpha_CG s = r - v*alpha_CG t = MOD_MatVecSPARSE(AA,IA,JA,s,it1,itN) w = DOT_PRODUCT(t,s)/DOT_PRODUCT(t,t) x = h + s*w r = s - t*w beta = DOT_PRODUCT(r,r) rho_im1 = rho_i k = k+1 END DO !PRINT*,'kmax,k',kmax,k End Subroutine BICGSTAB End Module mod_gradconj
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/Code_Dirichlet_LAST/mod_matsys.f90
!---------------------------------------------------- ! CE MODULE CONTIENT LA CONSTRUCTION DE LA MATRICE A ! ET LE VECTEUR SOURCE F !---------------------------------------------------- Module mod_matsys !---modules------------------- Use mod_parametres Use mod_fonctions Use mod_gradconj !----------------------------- Implicit None Contains !--- SUBROUTINE QUI CONSTRUIT LA MATRICE A : UN SEUL APPEL ---------------------- !--- COO FORMAT: AA contient elements non nuls, IA et JA numéro de la ligne, colonne !--- de element non nul. Subroutine matsys_v2(nnz,Nx_l,Ny_l,AA,IA,JA) Integer, Intent(IN) ::nnz,Nx_l,Ny_l Real(PR), Dimension(:), Allocatable, Intent(Out) :: AA Integer, Dimension(:), Allocatable, Intent(Out) :: IA,JA Integer :: k, mul2, d1, d2, mul1 k = 1; mul2 = Nx_l*Ny_l; mul1 = Ny_l*(Nx_l-1)+1 ALLOCATE(AA(nnz),IA(nnz),JA(nnz)) !L1----------------------------------------------------------- IF(Nx_l > 1)THEN CALL L1(Ny_l,nnz,k,AA,IA,JA) !CRTL nnz_L1 IF(k /= crtl_L1_nnz)THEN PRINT*,'ERROR L1_nnz','RANG',rang,'k_L1',k,'/=','crtl_L1_nnz',crtl_L1_nnz AA=0._PR;IA=0;JA=0 END IF ELSE IF(Nx_l == 1)THEN CALL L1_NXL_eqv_1(Ny_l,nnz,k,AA,IA,JA) IF(k /= crtl_L1_nnz_Nxl_EQV_1)THEN PRINT*,'ERROR L1_nnz','RANG',rang,'k_L1',k,'/=','crtl_L1_nnz_Nxl_EQV_1',crtl_L1_nnz_Nxl_EQV_1 AA=0._PR;IA=0;JA=0 END IF END IF !L2----------------------------------------------------------- IF(Nx_l>2)THEN d1 = Ny_l+1; d2 = 2*Ny_l CALL L2(Nx_l,Ny_l,nnz,d1,d2,k,AA,IA,JA) IF(k /= crtl_L1_nnz + crtl_L2_nnz)THEN PRINT*,'ERROR L2_nnz','RANG',rang,'k_L2',k-crtl_L1_nnz,'/=','crtl_L2_nnz',crtl_L2_nnz AA=0._PR;IA=0;JA=0 END IF END IF !L3----------------------------------------------------------- IF(Nx_l>1)THEN CALL L3(mul1,mul2,Ny_l,nnz,k,AA,IA,JA) PRINT*,'rang',rang,'k',k,'FIN L3' IF(k /= sum_crtl_L_nnz)THEN PRINT*,'ERROR L3_nnz','RANG',rang,'k_L3',k-crtl_L1_nnz-crtl_L2_nnz,'/=','crtl_L3_nnz',crtl_L3_nnz AA=0._PR;IA=0;JA=0 END IF END IF END Subroutine matsys_v2 Subroutine L1_NXL_eqv_1(Ny_l,nnz,k,AA,IA,JA) INTEGER,INTENT(IN)::Ny_l,nnz INTEGER,INTENT(INOUT)::k Real(PR), Dimension(nnz), Intent(Out) :: AA Integer, Dimension(nnz), Intent(Out) :: IA,JA Integer::d !ONLY WHEN A PROCES GOT Nx_l==1 DO d = 1, Ny_l IF(d == 1)THEN AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 ELSE IF(d>1 .AND. d<Ny_l)THEN k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 ELSE IF(d == Ny_l)THEN k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d END IF END DO End Subroutine L1_NXL_eqv_1 Subroutine L1(Ny_l,nnz,k,AA,IA,JA) INTEGER,INTENT(IN)::Ny_l,nnz INTEGER,INTENT(INOUT)::k Real(PR), Dimension(nnz), Intent(Out) :: AA Integer, Dimension(nnz), Intent(Out) :: IA,JA Integer::d,hit DO d = 1, Ny_l IF(d == 1)THEN AA(k)=alpha; IA(k)=d; JA(k)=d DO hit = d+1, d+Ny_l, Ny_l-1 IF(hit == d+1)THEN k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=hit ELSE k=k+1; AA(k)=beta; IA(k)=d; JA(k)=hit END IF END DO ELSE IF(d>1 .AND. d<Ny_l)THEN k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l ELSE IF(d == Ny_l)THEN DO hit = d-1, d IF(hit == d-1)THEN k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=hit ELSE k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=hit END IF END DO k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l END IF END DO End Subroutine L1 SUBROUTINE TRACK(k,d) INTEGER,INTENT(INOUT)::k,d IF(rang==0)THEN PRINT*,'RANG',rang,'TRACK k,d',k,d END IF END SUBROUTINE TRACK Subroutine L2(Nx_l,Ny_l,nnz,d1,d2,k,AA,IA,JA) Integer, Intent(IN) :: Nx_l, Ny_l, nnz Integer, Intent(INOUT) :: d1, d2, k Real(PR), Dimension(nnz), Intent(Out) :: AA Integer, Dimension(nnz), Intent(Out) :: IA,JA INTEGER :: i, d DO i = 1, Nx_l-2 DO d = d1,d2 IF(d == d1)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l ELSE IF(d>d1 .AND. d<d2)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l ELSE IF(d == d2)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l END IF END DO d1 = d2+1; d2=d2+Ny_l END DO End Subroutine L2 Subroutine L3(mul1,mul2,Ny_l,nnz,k,AA,IA,JA) Integer, Intent(IN) :: mul1, mul2, Ny_l, nnz Integer, Intent(INOUT) :: k Real(PR), Dimension(nnz), Intent(Out) :: AA Integer, Dimension(nnz), Intent(Out) :: IA,JA INTEGER :: d DO d = mul1, mul2 IF(d == mul1)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 ELSE IF(d>mul1 .AND. d<mul2)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 ELSE IF(d == mul2)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d END IF END DO End Subroutine L3 !--------SUBROUTINE DU SECOND MEMBRE EN FONCTION DE L'ITERATION N ET DU VECTEUR U-------- !--------ET DES CONDITIONS AUX LIMITES Subroutine vectsource(CT,U,S1,S2,X,Y,T,F) Implicit None !---variables---------------------------------- Integer, Intent(In) :: CT, S1, S2 Real(PR), Dimension(it1:itN), Intent(In) :: U Real(PR), Dimension(LBX:UBX), Intent(IN) :: X Real(PR), Dimension(0:Ny_g+1), Intent(IN) :: Y !BECAUSE DD 1D => Ny_l == Ny_g Real(PR), Intent(IN) :: T Real(PR), Dimension(it1:itN), Intent(INOUT) :: F Integer :: i,j,k DO i = S1, S2 DO j = 1, Ny_g k = j + (i-1)*Ny_g F(k) = dt * f1(CT,X(i),Y(j),T) IF(i == 1)THEN F(k) = F(k) - h1(CT,X(i-1),Y(j),T)*beta ELSE IF(i == Nx_g)THEN F(k) = F(k) - h1(CT,X(i+1),Y(j),T)*beta END IF IF(j == 1)THEN F(k) = F(k) - g1(CT,X(i),Y(j-1),T)*gamma ELSE IF(j == Ny_g)THEN F(k) = F(k) - g1(CT,X(i),Y(j+1),T)*gamma END IF END DO END DO F = F +U End Subroutine vectsource !DANS LE CAS DE LA DECOMPOSITION DE DOMAINE: Subroutine vectsource_FULL(CT,U,UG,UD,S1,S2,X,Y,T,F) Implicit None !---variables---------------------------------- Integer, Intent(In) :: CT, S1, S2 Real(PR), Dimension(it1:itN), Intent(In) :: U Real(PR), Dimension(it1-Ny_g:it1-1), Intent(In) :: UG Real(PR), Dimension(itN+1:itN+Ny_g), Intent(In) :: UD Real(PR), Dimension(LBX:UBX), Intent(IN) :: X Real(PR), Dimension(0:Ny_g+1), Intent(IN) :: Y !BECAUSE DD 1D => Ny_l == Ny_g Real(PR), Intent(IN) :: T Real(PR), Dimension(it1:itN), Intent(INOUT) :: F Integer :: i,j,k DO i = S1, S2 DO j = 1, Ny_g k = j + (i-1)*Ny_g F(k) = dt * f1(CT,X(i),Y(j),T) IF(i == 1)THEN F(k) = F(k) - h1(CT,X(i-1),Y(j),T)*beta ELSE IF(i == S1 )THEN !.AND. rang /= 0)THEN not needed with the current order if... else if F(k) = F(k) - beta * UG(k-Ny_g) !CL dirichlet frontiere immergee ELSE IF(i == Nx_g)THEN !PRINT*,'RANG',rang,'it1,itN',it1,itN,'LBX,UBX',lbound(X,1),UBOUND(X,1),'k',k,'i,j',i,j F(k) = F(k) - h1(CT,X(i+1),Y(j),T)*beta ELSE IF(i == S2)THEN !.AND. rang /= Np-1)THEN not needed with the current order else if... else if F(k) = F(k) - beta * UD(k+Ny_g) !CL dirichlet frontiere immergee END IF IF(j == 1)THEN F(k) = F(k) - g1(CT,X(i),Y(j-1),T)*gamma ELSE IF(j == Ny_g)THEN F(k) = F(k) - g1(CT,X(i),Y(j+1),T)*gamma END IF END DO END DO F = F +U End Subroutine vectsource_FULL End Module mod_matsys !!$DO d = 1, Ny_l !!$ IF(d == 1)THEN !!$ AA(k)=alpha; IA(k)=d; JA(k)=d !!$ DO hit = d+1, d+Ny_l, Ny_l-1 !!$ IF(hit == d+1)THEN !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=hit !!$ ELSE !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=hit !!$ END IF !!$ END DO !!$ ELSE IF(d>1 .AND. d<Ny_l)THEN !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 !!$ k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l !!$ ELSE IF(d == Ny_l)THEN !!$ DO hit = d-1, d !!$ IF(hit == d-1)THEN !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=hit !!$ ELSE !!$ k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=hit !!$ END IF !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l !!$ END DO !!$ END IF !!$ END DO !!$IF(Nx_l>2)THEN !!$ d1 = Ny_l+1; d2 = 2*Ny_l !!$ DO i = 1, Nx_l-2 !!$ DO d = d1,d2 !!$ IF(d == d1)THEN !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l !!$ k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l !!$ ELSE IF(d>d1 .AND. d<d2)THEN !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 !!$ k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l !!$ ELSE IF(d == d2)THEN !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 !!$ k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l !!$ END IF !!$ END DO !!$ d1 = d2+1; d2=d2+Ny_l !!$ END DO !!$ END IF !!$Subroutine matsys(nnz,AA,IA,JA) !!$ Integer, Intent(In) :: nnz !!$ Real(PR), Dimension(:), Allocatable, Intent(Out) :: AA !!$ Integer, Dimension(:), Allocatable, Intent(Out) :: IA,JA !!$ Integer :: i,j,k !!$ k=1 !!$ Allocate(AA(nnz),IA(nnz),JA(nnz)) !!$ Do i=1,na !!$ Do j=1,na !!$ If (i==j) Then !diagonale principale !!$ AA(k)=alpha !!$ IA(k)=i !!$ JA(k)=j !!$ k=k+1 !!$ ElseIf ((i==j-1) .and. (modulo(i,nx)/=0)) Then !diagonale sup !!$ AA(k)=beta !!$ IA(k)=i !!$ JA(k)=j !!$ k=k+1 !!$ ElseIf ((i==j+1) .and. (i/=1) .and. (modulo(j,ny)/=0)) Then !diagonale inf !!$ AA(k)=beta !!$ IA(k)=i !!$ JA(k)=j !!$ k=k+1 !!$ ElseIf (j==ny+i) Then !diagonale la plus a droite !!$ AA(k)=gamma !!$ IA(k)=i !!$ JA(k)=j !!$ k=k+1 !!$ ElseIf (i==j+nx) Then !diagonale la plus a gauche !!$ AA(k)=gamma !!$ IA(k)=i !!$ JA(k)=j !!$ k=k+1 !!$ End If !!$ End Do !!$ End Do !!$End Subroutine matsys
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/Code_Dirichlet_LAST/mod_parametres.f90
!----------------------------------------------- ! CE MODULE CONTIENT LES PARAMETRES DU PROBLEME !----------------------------------------------- Module mod_parametres USE mpi Implicit None !---Précision des calculs ------------------- Integer, Parameter :: PR=8 !simple précision !-------------------------------------------- !---Parametres géométriques----------------- Real(PR), Parameter :: Lx=1._PR !Longueur de la barre Real(PR), Parameter :: Ly=1._PR !Largeur de la barre Real(PR), Parameter :: D=1._PR !Coefficient de diffusion !-------------------------------------------- !PARAMETRE DE VISUALISATION: INTEGER :: sysmove !---Parametres numériques------------------- !g means global Domain GLobal matrix WITHOUT DD ADDITIVE !l means local Domain local matrix Integer :: nnz_g Integer, Parameter :: Nx_g=200 !lig nes de A (discrétisation en x) Integer, Parameter :: Ny_g=100 !colonnes de A (discrétisation en y) Integer, Parameter :: Na_g=Nx_g*Ny_g !taille de la matrice A Integer, Parameter :: Nt=30 !discrétisation du temps Real(PR), Parameter :: dx=1._PR/(Real(Nx_g)+1) ! pas en x Real(PR), Parameter :: dy=1._PR/(Real(Ny_g)+1) ! pas en y Real(PR), Parameter :: Tf=2.0_PR !temps final de la simulation Real(PR), Parameter :: dt=Tf/(Real(Nt)) !pas de temps Real(PR), Parameter :: pi=4._PR*atan(1._PR) !---------------------------------------------------------------------------------------------------------------- Real(PR), Parameter :: alpha =1._PR+(2._PR*D*dt/(dx**2._PR))+(2._PR*D*dt/(dy**2._PR)) ! Real(PR), Parameter :: beta = (-D*dt)/(dx**2._PR) !AL ! CF coefficients matrice Real(PR), Parameter :: gamma =(-D*dt)/(dy**2._PR) !AP !---------------------------------------------------------------------------------------------------------------- !------------------------------------------- !---PARAMETRES MPI-------------------------- INTEGER ::rang,Pivot INTEGER ::Np INTEGER ::stateinfo INTEGER,DIMENSION(MPI_STATUS_SIZE)::status CHARACTER(LEN=3) ::rank INTEGER ::TAG !FOR TAG FILE !------------------------------------------ !---DEFINE INTERVALLE SUIVANT Y PAR PROCS------ INTEGER ::S1_old, S2_old, it1_old, itN_old !avant call charge_overlap INTEGER ::S1 INTEGER ::S2 !=> X_i^(rang) \in [|S1;S2|] INTEGER ::it1 INTEGER ::itN !=> P(OMEGA^(rang)) \in [|it1;itN|] !INTEGER ::overlapd !INTEGER ::overlapg INTEGER,PARAMETER::overlap=1 INTEGER ::Na_l !NBR rows or cols in local matrix !na_loc == (S2-S1+1)*Ny INTEGER ::Nx_l !Nx local will be set to S2-S1+1 INTEGER ::Ny_l INTEGER ::nnz_l !nbr de non zero in local matrix INTEGER ::crtl_nnz_l !control de nnz !since a A_l matrix local is made by block D AND C such: !avec s=alpha, x=gamma et v=beta: ![D][C][0][0] ! |s x 0 0| ! |v 0 0 0| ! A_l.rows=Nx_l*Ny_l=A_l.cols ![C][D][C][0] ![D]=|x s x 0| ![C]=|0 v 0 0| ! D.rows=D.cols=Ny_l ![0][C][D][C] ! |0 x s x| ! |0 0 v 0| ! C.cols=C.rows=Ny_l ![0][0][C][D] ! |0 0 x s| ! |0 0 0 v| !We got (Nx_l) [D] block & (Nx_l-1) [C] upper block !& (Nx_l-1) [C] lower block !SUCH THAT crtl_nnz_l=(Nx_l*Ny_l) + 2 * (Nx_l) * (Ny_l - 1) + 2 * (Nx_l - 1) * (Ny_l) INTEGER ::D_rows !will be set to Ny_l INTEGER ::D_nnz !will be set to D_rows+2*(D_rows-1) INTEGER ::C_rows !will be set to Ny_l INTEGER ::C_nnz !will be set to C_rows ! WE DEFINE a control nnz_l parameter over L1, L2, L3 such that: !|[D][C][0][0]| = [L1] INTEGER ::crtl_L1_nnz !will be set to D_nnz+C_nnz !|[C][D][C][0]| = [L2] !|[0][C][D][C]| INTEGER ::crtl_L2_nnz !will be set to (Nx_l-2)*(D_nnz+2*C_nnz) !|[0][0][C][D]| = [L3] INTEGER ::crtl_L3_nnz !will be set to D_nnz+C_nnz !SUCH THAT THE RELATION (*) NEED TO BE .TRUE.: !(*)crtl_L1_nnz+crtl_L2_nnz+crtl_L3_nnz = crtl_nnz_l = nnz_l INTEGER ::sum_crtl_L_nnz !sum of crtl_Li_nnz !DANS LE CAS OU Nx_l == 1: INTEGER :: crtl_L1_nnz_Nxl_EQV_1 ! will be set to D_nnz !---variables---------------------------------! Real(PR), Dimension(:), Allocatable :: X Real(PR), Dimension(:), Allocatable :: Y !Ny_g+2 Real(PR), Dimension(:), Allocatable :: T !Nt+2 Real(PR), Dimension(:), Allocatable :: AA Integer, Dimension(:), Allocatable :: IA,JA Real(PR), Dimension(:), Allocatable :: U,Uo,F !Na_l Real(Pr), Dimension(:), Allocatable :: UG, UD ! CL FROM BORDER IMMERGEE need to be set at zero Real(PR) :: res,t1,t2 !résidu du grandconj Integer :: k,i,j,it,CT INTEGER ::LBX !init in mod_fonctions, para_param INTEGER ::UBX !VARIABLES POUR LA BOUCLE SCHWARZ, CONVERGENCE DD: REAL(PR) :: Norm1, Norm2, C1, err REAL(PR), PARAMETER :: err_LIM = 0.0000000001_PR INTEGER :: step End Module mod_parametres
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/Code_Dirichlet_LAST/mod_sol.f90
module mod_sol use mpi use mod_parametres IMPLICIT NONE !*** MODULE ModSOL POUR DONNER LA SOLUTION EXACTE ET !*** POUR GERER L'ENREGISTREMENT DE LA SOLUTION DANS DES FICHIERS !*** SUBROUTINE POUR APPELLER UN SCRIPT GNUPLOT POUR LA VISUALISATION CONTAINS SUBROUTINE UEXACT(U,userchoice)!userchoice==CT INTEGER,INTENT(INOUT)::userchoice REAL(PR),DIMENSION(it1:itN),INTENT(IN)::U REAL(PR),DIMENSION(:),ALLOCATABLE::UEXA,DIFF REAL(PR)::ErrN2_RED,ErrN2,Ninf_RED,Ninf CHARACTER(len=3)::CAS!rank,CAS !INITIALISATION DE UEXA SUIVANT LE CAS SOURCE ALLOCATE(UEXA(it1:itN)) WRITE(CAS,fmt='(1I3)')userchoice OPEN(TAG,file='EXACTE_ERREUR/SOL_EXACTE_CAS'//trim(adjustl(CAS))//'_ME'//trim(adjustl(rank))//'.dat') SELECT CASE(userchoice) CASE(1)!F1 DO i=S1,S2 DO j=1,Ny_g k=j+(i-1)*Ny_g UEXA(k)=X(i)*(1-X(i))*Y(j)*(1-Y(j)) WRITE(TAG,*)X(i),Y(j),UEXA(k) END DO END DO CASE(2)!F2 DO i=S1,S2 DO j=1,Ny_g k=j+(i-1)*Ny_g UEXA(k)=sin(X(i))+cos(Y(j)) WRITE(TAG,*)X(i),Y(j),UEXA(k) END DO END DO CASE DEFAULT!F3 PAS DE SOL EXACTE PRINT*,'PAS DE SOLUTION EXACTE POUR CE CAS (F3)' END SELECT CLOSE(TAG) !SUR LE DOMAINE [|S1;S2|]x[|1;Ny_g|]: !ERREUR NORME_2: ALLOCATE(DIFF(it1:itN)) DIFF=UEXA-U(it1:itN) ErrN2_RED=DOT_PRODUCT(DIFF,DIFF) CALL MPI_ALLREDUCE(ErrN2_RED,ErrN2,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,stateinfo) ErrN2=SQRT(ErrN2) !ERREUR NORME INFINIE Ninf_RED=MAXVAL(ABS(UEXA(it1:itN)-U(it1:itN))) CALL MPI_ALLREDUCE(Ninf_RED,Ninf,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) PRINT*,'PAR DOMAINE: ','ERREUR NORME 2 :=',ErrN2,' ERREUR NORME INFINIE :=',Ninf OPEN(TAG,file='EXACTE_ERREUR/ErrABSOLUE_PAR_DOMAINE'//trim(adjustl(CAS))//'_ME'//trim(adjustl(rank))//'.dat') DO i=S1,S2 DO j=1,Ny_g!GAP(i,1),GAP(i,2) k=j+(i-1)*Ny_g!Ny_g WRITE(TAG,*)X(i),Y(j),-DIFF(k) END DO END DO CLOSE(TAG) !SUR LE DOMAINE [|S1_old;S2_old|]x[|1;Ny_g|]: ErrN2_RED=0.0_PR; ErrN2=0.0_PR; Ninf_RED=0.0_PR; Ninf=0.0_PR !DIFF(it1_old:itN_old)=UEXA(it1_old:itN_old)-U(it1_old:itN_old) ErrN2_RED=DOT_PRODUCT(DIFF(it1_old:itN_old),DIFF(it1_old:itN_old)) CALL MPI_ALLREDUCE(ErrN2_RED,ErrN2,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,stateinfo) ErrN2=SQRT(ErrN2) Ninf_RED=MAXVAL(ABS(UEXA(it1_old:itN_old)-U(it1_old:itN_old))) CALL MPI_ALLREDUCE(Ninf_RED,Ninf,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) PRINT*,'SUR [|S1old;S2old|]: ','ERREUR NORME 2 :=',ErrN2,' ERREUR NORME INFINIE :=',Ninf OPEN(TAG,file='EXACTE_ERREUR/ErrABSOLUE_oldDD'//trim(adjustl(CAS))//'_ME'//trim(adjustl(rank))//'.dat') DO i=S1_old,S2_old DO j=1,Ny_g!GAP(i,1),GAP(i,2) k=j+(i-1)*Ny_g!Ny_g WRITE(TAG,*)X(i),Y(j),-DIFF(k) END DO END DO CLOSE(TAG) DEALLOCATE(DIFF,UEXA) END SUBROUTINE UEXACT SUBROUTINE WR_U(U,IT_TEMPS) INTEGER,INTENT(IN)::IT_TEMPS REAL(PR),DIMENSION(it1_old:itN_old),INTENT(INOUT)::U CHARACTER(len=3)::CAS CHARACTER(len=3)::Ntps INTEGER::i,j WRITE(CAS,fmt='(1I3)')CT;WRITE(Ntps,fmt='(1I3)')IT_TEMPS OPEN(10+rang,file='SOL_NUMERIQUE/U_ME'//trim(adjustl(rank))& //'_T'//trim(adjustl(Ntps))) SELECT CASE(CT) CASE(1) DO i=S1_old,S2_old DO j=1,Ny_g k=j+(i-1)*Ny_g IF(i-1==0)THEN WRITE(10+rang,*)0.0_PR,Y(j),0.0_PR END IF IF(i+1==Nx_g+1)THEN WRITE(10+rang,*)Lx,Y(j),0.0_PR END IF IF(j-1==0)THEN WRITE(10+rang,*)X(i),0.0_PR,0.0_PR END IF IF(j+1==Ny_g+1)THEN WRITE(10+rang,*)X(i),Ly,0.0_PR END IF WRITE(10+rang,*)X(i),Y(j),U(k) END DO END DO CASE(2) DO i=S1_old,S2_old DO j=1,Ny_g k=j+(i-1)*Ny_g IF(i==1)THEN!BC OUEST (H) WRITE(10+rang,*)0.0_PR,Y(j),cos(Y(j)) END IF IF(i==Nx_g)THEN!BC EST (H) WRITE(10+rang,*)Lx,Y(j),cos(Y(j))+sin(Lx) END IF IF(j==1)THEN!BC SUD (G) WRITE(10+rang,*)X(i),0.0_PR,1.0_PR+sin(X(i)) END IF IF(j==Ny_g)THEN!BC NORD (G) WRITE(10+rang,*)X(i),Ly,cos(Ly)+sin(X(i)) END IF WRITE(10+rang,*)X(i),Y(j),U(k) END DO END DO CASE(3) DO i=S1_old,S2_old DO j=1,Ny_g k=j+(i-1)*Ny_g IF(i-1==0)THEN!BC OUEST OU EST (H) WRITE(10+rang,*)0.0_PR,Y(j),1.0_PR END IF IF(i+1==Nx_g+1)THEN!BC OUEST OU EST (H) WRITE(10+rang,*)Lx,Y(j),1.0_PR END IF IF(j-1==0)THEN!BC SUD OU NORD (G) WRITE(10+rang,*)X(i),0.0_PR,0.0_PR END IF IF(j+1==Ny_g+1)THEN!BC SUD OU NORD (G) WRITE(10+rang,*)X(i),Ly,0.0_PR END IF WRITE(10+rang,*)X(i),Y(j),U(k) END DO END DO END SELECT CLOSE(10+rang) END SUBROUTINE WR_U SUBROUTINE VIZU_SOL_NUM(userchoice)!sequentiel call by proc 0 at the end INTEGER,INTENT(INOUT)::userchoice CHARACTER(LEN=12)::VIZU INTEGER::vi1,vi2 VIZU='VIZU_PLT.plt' PRINT*,'*****************************************************************************************' PRINT*,'************** VISUALISATION SOLUTION POUR LE CAS #',userchoice,' ***********************' PRINT*,'*****************************************************************************************' PRINT*,'************* SACHANT QUE DT=',dt,'ET ITMAX=',Nt,':' PRINT*,'*****************************************************************************************' PRINT*,'** ENTREZ LE NUMERO DE L''ITERATION A LAQUELLE VOUS VOULEZ COMMENCER LA VISUALISATION **' READ*,vi1 PRINT*,'*****************************************************************************************' PRINT*,'*****************************************************************************************' PRINT*,'*** ENTREZ LE NUMERO DE L''ITERATION A LAQUELLE VOUS VOULEZ STOPPER LA VISUALISATION ***' READ*,vi2 PRINT*,'*****************************************************************************************' PRINT*,'*****************************************************************************************' OPEN(50,file=VIZU) SELECT CASE(userchoice) CASE(1) WRITE(50,*)'set cbrange[0:1]' CASE(2) WRITE(50,*)'set cbrange[0.8:2]' CASE(3) WRITE(50,*)'set cbrange[0:1]' END SELECT WRITE(50,*)'set dgrid3d,',Nx_g+2,',',Ny_g+2; WRITE(50,*)'set hidden3d'; WRITE(50,*)'set pm3d' WRITE(50,*)'do for [i=',vi1,':',vi2,']{splot ''SOL_NUMERIQUE/U.dat'' index i u 1:2:3 with pm3d at sb}' CLOSE(50) call system('gnuplot -p VIZU_PLT.plt') END SUBROUTINE VIZU_SOL_NUM SUBROUTINE VIZU_SOL_NUM_ONLY_Nt(userchoice,MINU,MAXU)!sequentiel call by proc 0 at the end INTEGER,INTENT(INOUT) :: userchoice REAL(PR),INTENT(IN) :: MINU, MAXU CHARACTER(LEN=12)::VIZU VIZU='VIZU_PLT.plt' PRINT*,'*****************************************************************************************' PRINT*,'************** VISUALISATION SOLUTION POUR LE CAS #',userchoice,' ***********************' PRINT*,'*****************************************************************************************' PRINT*,'************* SACHANT QUE DT=',dt,'ET ITMAX=',Nt,':' PRINT*,'*****************************************************************************************' PRINT*,'** VISUALISATION AU TEMPS FINAL **' PRINT*, (Nt)*dt,' secondes' PRINT*,'*****************************************************************************************' OPEN(50,file=VIZU) SELECT CASE(userchoice) CASE(1) WRITE(50,*)'set cbrange[',MINU,':',MAXU,']' CASE(2) WRITE(50,*)'set cbrange[',MINU,':',MAXU,']' CASE(3) WRITE(50,*)'set cbrange[',MINU,':',MAXU,']' END SELECT WRITE(50,*)'set dgrid3d,',Nx_g+2,',',Ny_g+2; WRITE(50,*)'set hidden3d'; WRITE(50,*)'set pm3d' WRITE(50,*)'splot ''SOL_NUMERIQUE/U.dat'' u 1:2:3 with pm3d at sb' CLOSE(50) call system('gnuplot -p VIZU_PLT.plt') END SUBROUTINE VIZU_SOL_NUM_ONLY_Nt end module mod_sol
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/DD_Neuman_TRUE_LAST/main.f90
!----------------------------------- ! MAIN : PROGRAMME PRINCIPAL !----------------------------------- Program main !-------------modules-----------------! USE mpi use mod_parametres use mod_charge use mod_comm use mod_sol use mod_fonctions use mod_gradconj use mod_gmres use mod_matsys !--------------------------------------! Implicit None INTEGER :: DIMKRYLOV INTEGER :: ILOOP !VARIABLES POUR SAVE LE TEMPS DE CALCUL: REAL(PR) :: TPS1, TPS2, MAX_TPS REAL(PR) :: MINU, MAXU REAL(PR) :: RED_MINU, RED_MAXU REAL(PR) :: RED_SUMC, MAXC, TPSC1, TPSC2 REAL(PR) :: STA, STB, STM !------------INIT REGION PARA-----------------! !********* DEBUT REGION PARA: CALL MPI_INIT(stateinfo) !INITIALISATION DU //LISME CALL MPI_COMM_RANK(MPI_COMM_WORLD,rang,stateinfo) !ON RECUPERE LES RANGS !AU SEIN DE L'ENSEMBLE MPI_COMM_WORLD CALL MPI_COMM_SIZE(MPI_COMM_WORLD,Np,stateinfo) !ET LE NOMBRE DU PROCESSUS !---------------------------------------------! !******** READ USERCHOICE FOR CT AND SHARE IT WITH OTHER PROCESS IF(rang==0)THEN CALL SYSTEM('make cleanREP') Print*,"______RESOLUTION DE L'ÉQUATION : DD SCHWARZ ADDITIVES //______" !---initialisation des variables cas test------------- Print*,"Donnez le cas test (1,2 ou 3):" Read*,CT PRINT*," POUR VISUALISATION ENTREZ 1, SINON 0" read*,sysmove END IF CALL MPI_BCAST(CT,1,MPI_INTEGER,0,MPI_COMM_WORLD,stateinfo) CALL MPI_BCAST(sysmove,1,MPI_INTEGER,0,MPI_COMM_WORLD,stateinfo) TPS1=MPI_WTIME() !******** COMPUTE SOME MATRIX_G DATA & GEO TIME DATA nnz_g=5*Na_g-2*Nx_g-2*Ny_g !nb d'elt non nul dans la matrice A_g IF(rang==0)THEN print*,"Nombre éléments non nuls du domaine A_g non DD ADDITIVE : nnz_g=",nnz_g print*,'Nombre de ligne Nx_g, colonne Ny_g de A_g',Nx_g,Ny_g Print*,"Lx=",Lx Print*,"Ly=",Ly Print*,"D=",D Print*," " Print*,"dx=",dx Print*,"dy=",dy Print*,"dt",dt Print*,"Tfinal=",Tf,"secondes" Print*," " print*,"alpha=",alpha print*,"beta=",beta print*,"gamma=",gamma Print*," " END IF !******* SET UP ONE TAG FILE NAMED TAG TO i/o: TAG=10+rang WRITE(rank,fmt='(1I3)')rang !WATCH OUT IF rang>999 !******* COMPUTE SIZE OF LOCAL DD OVER LOCAL MATRIX A_l SIZE: OPEN(TAG,file='CHARGE/CHARGE'//trim(adjustl(rank))//'.dat') CALL MODE1(rang, Np, S1, S2, it1, itN)!-->DISTRIBUTION DE LA CHARGE PAR PROCESSUS S1_old = S1; S2_old = S2; it1_old = it1; itN_old = itN WRITE(TAG,*)'AVANT OVERLAP', S1, S2, it1, itN CALL CHARGE_OVERLAP(Np, rang, S1, S2, it1, itN)!-->MODIFICATION DE LA CHARGE POUR DIRICHLET WRITE(TAG,*)'APRES OVERLAP DIRICHLET', S1, S2, it1, itN CALL CHARGE_NEUMAN(it1, itN, rang, Np, S1, S2)!-->MODIFICATION DE LA CHARGE CALCULEE PAR (CHARGE_OVERLAP) POUR NEUMANN WRITE(TAG,*)'OVERLAP FINAL NEUMAN', S1, S2, it1, itN Nx_l = S2 - S1 + 1; Ny_l = Ny_g; Na_l = Nx_l * Ny_l nnz_l = 5 * Na_l - 2 * Nx_l - 2 * Ny_l crtl_nnz_l = (Nx_l*Ny_l) + 2 * (Nx_l) * (Ny_l - 1) + 2 * (Nx_l - 1) * (Ny_l) WRITE(TAG,*)'Nxl,Ny_l,Na_l', Nx_l, Ny_l, Na_l WRITE(TAG,*)'nnz_l,crtl_nnz_l', nnz_l,crtl_nnz_l CLOSE(TAG) !CALCUL DES DIMMENSIONS DES MATRICES: D_rows = Ny_l; D_nnz = D_rows+2*(D_rows-1) C_rows = Ny_l; C_nnz = C_rows crtl_L1_nnz = D_nnz+C_nnz crtl_L2_nnz = (Nx_l-2)*(D_nnz+2*C_nnz) crtl_L3_nnz = D_nnz+C_nnz sum_crtl_L_nnz = crtl_L1_nnz+crtl_L2_nnz+crtl_L3_nnz crtl_L1_nnz_Nxl_EQV_1 = D_nnz !test pour la verification du nombre de non zero des matrices locales: IF(Nx_l > 1)THEN IF(crtl_nnz_l/=nnz_l .AND. nnz_l/=sum_crtl_L_nnz)THEN PRINT*,'ERROR,RANG=',rang,'Local Matrix A_l.rows,A_l.cols',Nx_l,Ny_l,nnz_l,& &'A_l_nnz,crtl_nnz_l,sum_crtl_L_nnz',nnz_l,crtl_nnz_l,sum_crtl_L_nnz GOTO 9999 END IF ELSE IF(Nx_l == 1)THEN IF(crtl_nnz_l/=nnz_l .AND. nnz_l/=crtl_L1_nnz_Nxl_EQV_1)THEN PRINT*,'ERROR,RANG=',rang,'Local Matrix A_l.rows,A_l.cols',Nx_l,Ny_l,nnz_l,& &'A_l_nnz,crtl_nnz_l,crtl_L1_nnz_Nxl_EQV_1',nnz_l,crtl_nnz_l,crtl_L1_nnz_Nxl_EQV_1 GOTO 9999 END IF END IF !******* COMPUTE CARTESIAN GRID OVER PROCESS i.e CHARGE APPLY TO X,Y,T IF(Np/=1)THEN CALL param_para(rang,Np,S1,S2,Ny_l,X,Y,T) ELSE CALL param(X,Y,T) PRINT*,'EN SEQUENTIEL' END IF !****** ALLOCATE Uo ET U ALLOCATE(U(it1:itN),Uo(it1:itN)) Uo = 1._PR !CI pour le gradient conjugué U = 1._PR !vecteur solution initialisé !SAVE SOL : call WR_U(U,0) CALL matsys_v2(nnz_l,Nx_l,Ny_l,AA,IA,JA)!-->on construit A au format COO (AA,IA,JA) OPEN(TAG,file='MAT_VIZU/matrice_A_'//trim(adjustl(rank))//'.dat')!-->POUR VISUALISER LES MATRICES DO i=1,nnz_l WRITE(TAG,*)AA(i),IA(i),JA(i) END DO CLOSE(TAG) ALLOCATE(F(it1:itN))!-->SECOND MEMBRE ALLOCATE(UG(LBUG:UBUG),UD(LBUD:UBUD)) UG = 0.0_PR; UD = 0.0_PR !-->INITITALISATION !---boucle principale (résolution systeme) et ecriture a chaque itération--- Print*,"----------DÉBUT DU CALCUL DE LA SOLUTION------------" Pivot=(Np-mod(Np,2))/2 !-->!PIVOT DE COMMUNICATION: RED_SUMC = 0.0_PR DIMKRYLOV = 5!Na_l-5 IF(Np>1)THEN boucle_temps:Do ILOOP=1,Nt !-->BOUCLE EN TEMPS err = 1.0_PR; step = 1; Norm2 = 0.0_PR !STA = MPI_WTIME() boucle_CV_SWHARZ:Do while(err>err_LIM .OR. step<3)!-->BOUCLE POUR CONVERGENCE DE SCHWARZ step = step +1 Norm1 = Norm2 !Norm2 = 0.0_PR call vectsource_FULL(CT,U,UG,UD,S1,S2,X,Y,T(ILOOP),F)!-->SECOND MEMBRE F=Uo+dt*SOURCE_TERME+CL !call MOD_gradconj_SPARSE(AA,IA,JA,f,Uo,U,res,k,it1,itN) !call MOD_jacobi_SPARSE(AA,IA,JA,F,Uo,U,res,k) call BICGSTAB(it1, itN, AA, IA, JA, U, F, 0.0000000001_PR)! solver le plus adapté au PB !call GMres_COO(AA,IA,JA,F,Uo,U,res,k,Na_l,it1,itN,DIMKRYLOV)! mal interfacé TPSC1 = MPI_WTIME() !CALL COMM_PTOP_2WAY(U,UG,UD)!-->UNE PETITE REDUCTION DU TEMPS DE COMMUNICATION(NP>=5) call COMM_PTOP(U,UG,UD)!-->COMMUNICATION DES FRONTIERES "IMMERGEE" TPSC2 = MPI_WTIME() RED_SUMC = RED_SUMC + (TPSC2-TPSC1) Uo=U !-->SWAP !POUR LE CALCUL DE L'ERREUR DE SCHWARZ(C1,Nomr1,Norm2,err): if(rang==0)then C1 = DOT_PRODUCT(U(itN-Ny_l+1:itN),U(itN-Ny_l+1:itN)) else if(rang==Np-1)then C1 = DOT_PRODUCT(U(it1:it1+Ny_l-1),U(it1:it1+Ny_l-1)) else C1 = DOT_PRODUCT(U(it1:it1+Ny_l-1),U(it1:it1+Ny_l-1)) +DOT_PRODUCT(U(itN-Ny_l+1:itN),U(itN-Ny_l+1:itN)) end if !C1 = DOT_PRODUCT(U(it1:itN),U(it1:itN))!-->AUTRE METHODE POUR LE CALCUL DE C1 Call MPI_ALLreduce(C1,Norm2,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,stateinfo) Norm2 = SQRT(Norm2) err = abs(Norm1-Norm2) !PRINT*,'err=',err,'step',step,'Norm2',Norm2,'Norm1',Norm1 END DO boucle_CV_SWHARZ !STB = MPI_WTIME() if(mod(ILOOP,10)==0)then Print*,'IT TEMPS',ILOOP end if End DO boucle_temps !CALL MPI_ALLREDUCE(STB-STA,STM,1,MPI_DOUBLE,MPI_MAX,MPI_COMM_WORLD,stateinfo) !PRINT*,'STM',STM,'STEP',STEP ELSE IF(Np==1)THEN bboucle_temps:Do ILOOP=1,Nt call vectsource_FULL(CT,U,UG,UD,S1,S2,X,Y,T(ILOOP),F) !call MOD_gradconj_SPARSE(AA,IA,JA,f,Uo,U,res,k,it1,itN) !call MOD_jacobi_SPARSE(AA,IA,JA,F,Uo,U,res,k) call BICGSTAB(it1, itN, AA, IA, JA, U, F, 0.000000000001_PR) !call GMres_COO(AA,IA,JA,F,Uo,U,res,k,Na_l,it1,itN,DIMKRYLOV) Uo=U !SWAP if(mod(ILOOP,10)==0)then Print*,'IT TEMPS',ILOOP end if End DO bboucle_temps END IF !---------------------------------------------- !SAVE SOL : call WR_U(U,Nt) DEALLOCATE(UG,UD) !WRITE SOL EXACTE: IF(CT<3)THEN call UEXACT(U,CT) END IF RED_MINU = minval(U) RED_MAXU = maxval(U) CALL MPI_ALLREDUCE(RED_MINU,MINU,1,MPI_DOUBLE_PRECISION,MPI_MIN,MPI_COMM_WORLD,stateinfo) CALL MPI_ALLREDUCE(RED_MAXU,MAXU,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) if(Np>1)then CALL MPI_ALLREDUCE(RED_SUMC,MAXC,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) end if DEALLOCATE(U,Uo,X,Y,T,AA,IA,JA,F) TPS2=MPI_WTIME() CALL MPI_ALLREDUCE(TPS2-TPS1,MAX_TPS,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) IF(rang==0)THEN PRINT*,'TEMPS CALCUL=',MAX_TPS,' TEMPS COMM=',MAXC END IF CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) IF(crtl_nnz_l == nnz_l)THEN GOTO 6666 END IF 9999 PRINT*,rang,'GOTO9999crtl_nnz_l /= nnz_l ERROR',crtl_nnz_l,nnz_l 6666 PRINT*,rang,'GOTO6666NEXT INSTRUCTION IS MPI_FINALIZE',crtl_nnz_l,nnz_l !---ecriture solution finale-------------------------- !call CONCAT_VIZU(sysmove) call CONCAT_VIZU_ONLY_Nt(sysmove,MINU,MAXU) CALL MPI_FINALIZE(stateinfo) CONTAINS Subroutine CONCAT_VIZU(sysmove) Integer, Intent(INOUT):: sysmove CHARACTER(LEN=3):: NNT CHARACTER(LEN=1)::ESPACE CHARACTER(LEN=20)::NFILE,OUT_FILE INTEGER::i !VIZUALISATION SEQUENTIELLE: ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE RANG DIFFERENTS DANS UN FICHIER IF(rang==0.AND.sysmove==1)THEN ESPACE=' ' DO i=Nt,Nt!0,Nt WRITE(NNT,fmt='(1I3)')i; NFILE='U_ME*'//'_T'//trim(adjustl(NNT));OUT_FILE='UT_'//trim(adjustl(NNT))//'.dat' !ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE RANG DIFFERENTS DANS UN FICHIER CALL system('cat SOL_NUMERIQUE/'//NFILE//' >> SOL_NUMERIQUE/'//OUT_FILE) CALL system('rm SOL_NUMERIQUE/'//NFILE) OPEN(20,file='SOL_NUMERIQUE/'//OUT_FILE,position='append') SELECT CASE(CT)!ICI IL FAUT RAJOUTER LES POINTS AUX COINS DU DOMAINES CASE(1) WRITE(20,*)0.0d0,0.0d0,0.0d0;WRITE(20,*)Lx,0.0d0,0.0d0 WRITE(20,*)0.0d0,Ly,0.0d0;WRITE(20,*)Lx,Ly,0.0d0 CASE(2) WRITE(20,*)0.0d0,0.0d0,1.0d0;WRITE(20,*)Lx,0.0d0,1.0d0+sin(Lx) WRITE(20,*)0.0d0,Ly,cos(Ly);WRITE(20,*)Lx,Ly,cos(Ly)+sin(Lx) CASE(3) WRITE(20,*)0.0d0,0.0d0,0.5d0;WRITE(20,*)Lx,0.0d0,0.5d0!TEMPERATURES IMPOSEES DIFFERENTES, ON MOYENNE:((G+H)/2) WRITE(20,*)0.0d0,Ly,0.5d0;WRITE(20,*)Lx,Ly,0.5d0 END SELECT WRITE(20,fmt='(1A1)')ESPACE WRITE(20,fmt='(1A1)')ESPACE CLOSE(20) !ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE TEMPS DIFFERENTS DANS UN FICHIER CALL system('cat SOL_NUMERIQUE/'//OUT_FILE//' >> SOL_NUMERIQUE/U.dat') CALL system('rm SOL_NUMERIQUE/'//OUT_FILE) END DO !A LA FIN, IL RESTE UN FICHIER OU LA SOLUTION EN TEMPS EST SOUS FORME D'INDEX GNUPLOT !ON APPELLE LA SUBROUTIEN DE VISUALISATION: CALL VIZU_SOL_NUM(CT) END IF End Subroutine CONCAT_VIZU Subroutine CONCAT_VIZU_ONLY_Nt(sysmove,MINU,MAXU) Integer, Intent(INOUT):: sysmove REAL(PR), Intent(IN) :: MINU, MAXU CHARACTER(LEN=3):: NNT CHARACTER(LEN=1)::ESPACE CHARACTER(LEN=20)::NFILE,OUT_FILE INTEGER::i !VIZUALISATION SEQUENTIELLE: ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE RANG DIFFERENTS DANS UN FICHIER IF(rang==0.AND.sysmove==1)THEN ESPACE=' ' DO i=Nt,Nt WRITE(NNT,fmt='(1I3)')i; NFILE='U_ME*'//'_T'//trim(adjustl(NNT));OUT_FILE='UT_'//trim(adjustl(NNT))//'.dat' !ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE RANG DIFFERENTS DANS UN FICHIER CALL system('cat SOL_NUMERIQUE/'//NFILE//' >> SOL_NUMERIQUE/'//OUT_FILE) CALL system('rm SOL_NUMERIQUE/'//NFILE) OPEN(20,file='SOL_NUMERIQUE/'//OUT_FILE,position='append') SELECT CASE(CT)!ICI IL FAUT RAJOUTER LES POINTS AUX COINS DU DOMAINES CASE(1) WRITE(20,*)0.0d0,0.0d0,0.0d0;WRITE(20,*)Lx,0.0d0,0.0d0 WRITE(20,*)0.0d0,Ly,0.0d0;WRITE(20,*)Lx,Ly,0.0d0 CASE(2) WRITE(20,*)0.0d0,0.0d0,1.0d0;WRITE(20,*)Lx,0.0d0,1.0d0+sin(Lx) WRITE(20,*)0.0d0,Ly,cos(Ly);WRITE(20,*)Lx,Ly,cos(Ly)+sin(Lx) CASE(3) WRITE(20,*)0.0d0,0.0d0,0.5d0;WRITE(20,*)Lx,0.0d0,0.5d0!TEMPERATURES IMPOSEES DIFFERENTES, ON MOYENNE:((G+H)/2) WRITE(20,*)0.0d0,Ly,0.5d0;WRITE(20,*)Lx,Ly,0.5d0 END SELECT WRITE(20,fmt='(1A1)')ESPACE WRITE(20,fmt='(1A1)')ESPACE CLOSE(20) !ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE TEMPS DIFFERENTS DANS UN FICHIER CALL system('cat SOL_NUMERIQUE/'//OUT_FILE//' >> SOL_NUMERIQUE/U.dat') CALL system('rm SOL_NUMERIQUE/'//OUT_FILE) END DO !A LA FIN, IL RESTE UN FICHIER OU LA SOLUTION EN TEMPS EST SOUS FORME D'INDEX GNUPLOT !ON APPELLE LA SUBROUTIEN DE VISUALISATION: !CALL VIZU_SOL_NUM(CT) CALL VIZU_SOL_NUM_ONLY_Nt(CT,MINU,MAXU) END IF End Subroutine CONCAT_VIZU_ONLY_Nt End Program main
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/DD_Neuman_TRUE_LAST/mod_charge.f90
module mod_charge use mod_parametres Implicit None CONTAINS !************************** !^ y Ny !| !| !| !1---------> x Nx !************************* !SE BASE SUR LA CHARGE EN X POUR CALCULER LA CHARGE TOTALE(GLOBALE) !INDUIT POUR MOD(DIM,Np)/=0 UNE DIFFERENCE DE CHARGE = A Ny ENTRE 2 PROCS !UTILISABLE POUR Np<=INTER_X Subroutine MODE1(rang, Np, S1, S2, it1, itN) Integer, Intent(IN) :: rang, Np Integer, Intent(OUT) :: S1, S2,it1, itN !CHARGE EN X : CALL CHARGE_X(rang, Np, S1, S2) !CHARGE TOT : CALL CHARGE_TOT(S1, S2, it1, itN) End Subroutine MODE1 !REPARTITION CLASSIQUE DE LA CHARGE EN X Subroutine CHARGE_X(rang, Np, S1,S2) Integer, Intent(IN) :: rang, Np Integer, Intent(OUT) :: S1, S2 REAL :: CO_RE !COEFFICIANT DE REPARTITION IF(Np == 1)THEN S1 = 1; S2 = Nx_g ELSE CO_RE=(Nx_g)/(Np) If(rang < mod(Nx_g,Np))Then S1 = rang*(CO_RE+1) + 1; S2 = (rang+1) * (CO_RE+1) Else S1 = 1 + mod(Nx_g,Np) + rang*CO_RE; S2 = S1+CO_RE-1 End If END IF End Subroutine CHARGE_X !CHARGE TOTALE SUR LA NUMEROTATION GLOBALE Subroutine CHARGE_TOT(S1, S2, it1, itN) Integer, Intent(IN) :: S1, S2 Integer, Intent(OUT) :: it1, itN it1 = (S1-1)*Ny_g+1; itN = S2*Ny_g End Subroutine CHARGE_TOT !RE-COMPUTE CHARGE WITH OVERLAP Subroutine CHARGE_OVERLAP(Np, rang, S1, S2, it1, itN) Implicit None Integer, Intent(IN) ::Np, rang Integer, Intent(INOUT) ::S1, S2, it1, itN !Le (-1) sur overlap pour retirer la frontiere !immergée qui passe en CL !WE PUT A Ny_g BECAUSE Ny_l == Ny_g and Ny_l is defined after this subroutine !Also Because IT'S a 1D DD !IF WE WANT TO SET UP A 2D DD I WILL NEED DO REPLACE Ny_g BY Ny_l !AND MAKE OTHER MODIFICATION IF(rang == 0)THEN S2 = S2 + (overlap-1) itN = itN + (overlap-1) * Ny_g ELSE IF(rang == Np-1)THEN S1 = S1 - (overlap-1) it1 = it1 - (overlap-1) * Ny_g ELSE S1 = S1 - (overlap-1) S2 = S2 + (overlap-1) it1 = it1 - (overlap-1) * Ny_g itN = itN + (overlap-1) * Ny_g END IF End Subroutine CHARGE_OVERLAP subroutine CHARGE_NEUMAN(it1, itN, rang, Np, S1, S2) implicit none Integer, Intent(IN) :: rang, Np Integer, Intent(INOUT) :: it1, itN, S1, S2 if (rang==0) then itN = itN+Ny_g S2=S2+1 else if (rang==Np-1) then it1 = it1-Ny_g S1=S1-1 else it1 = it1-Ny_g itN = itN+Ny_g S1=S1-1 S2=S2+1 end if end subroutine CHARGE_NEUMAN end module mod_charge
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/DD_Neuman_TRUE_LAST/mod_comm.f90
module mod_comm use mpi use mod_parametres Implicit None CONTAINS Subroutine COMM_PTOP(U,UG,UD) Real(PR), Dimension(it1:itN), Intent(IN):: U Real(PR), Dimension(LBUG:UBUG), Intent(INOUT):: UG Real(PR), Dimension(LBUD:UBUD), Intent(INOUT):: UD IF(rang == 0)THEN ! rang tag channel CALL MPI_SEND(U(A:B),2*Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(UD(LBUD:UBUD),2*Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) ELSE IF(rang > 0 .AND. rang<Np-1)THEN CALL MPI_RECV(UG(LBUG:UBUG),2*Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) CALL MPI_SEND(U(C:DD),2*Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(U(A:B),2*Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(UD(LBUD:UBUD),2*Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) ELSE IF(rang == Np-1)THEN CALL MPI_RECV(UG(LBUG:UBUG),2*Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) CALL MPI_SEND(U(C:DD),2*Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) END IF End Subroutine COMM_PTOP Subroutine COMM_PTOP_2WAY(U,UG,UD) Real(PR), Dimension(it1:itN), Intent(IN):: U Real(PR), Dimension(LBUG:UBUG), Intent(INOUT):: UG Real(PR), Dimension(LBUD:UBUD), Intent(INOUT):: UD IF(rang == 0)THEN ! rang tag channel CALL MPI_SEND(U(A:B),2*Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(UD(LBUD:UBUD),2*Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) ELSE IF(rang > 0 .AND. rang<Pivot)THEN CALL MPI_RECV(UG(LBUG:UBUG),2*Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) CALL MPI_SEND(U(C:DD),2*Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(U(A:B),2*Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(UD(LBUD:UBUD),2*Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) ELSE IF(rang >= Pivot .AND. rang < Np-1)THEN CALL MPI_RECV(UD(LBUD:UBUD),2*Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) CALL MPI_SEND(U(A:B),2*Ny_g,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(U(C:DD),2*Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(UG(LBUG:UBUG),2*Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) ELSE IF(rang == Np-1)THEN CALL MPI_SEND(U(C:DD),2*Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(UG(LBUG:UBUG),2*Ny_g,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) END IF End Subroutine COMM_PTOP_2WAY end module mod_comm
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/DD_Neuman_TRUE_LAST/mod_constr_mat.f90
module mod_constr_mat use mod_parametres implicit none !-->set a_neuman=1.0_PR et b_neuman=0.0000001_PR pour retrouver les mêmes ordres de grandeurs des erreurs L2 qu'avec le sequentiel ou dirichlet Real(PR), Parameter :: a_neuman = 0.5_PR Real(PR), Parameter :: b_neuman = 0.5_PR REAL(PR), Parameter :: c_neuman = a_neuman/b_neuman Real(PR), Parameter :: alpha_neuman_H = 1._PR -2._PR*beta -2._PR*gamma +((D*dt*a_neuman)/(dx*b_neuman)) +beta ! Les coefficients alpha changent pour les Ny première ! et/ou dernières lignes des matrices dans le cas des CLs de Neuman Real(PR), Parameter :: alpha_neuman_B = 1._PR -2._PR*beta -2._PR*gamma +((D*dt*a_neuman)/(dx*b_neuman)) +beta contains Subroutine L1_NXL_eqv_1(Ny_l,nnz,k,AA,IA,JA) INTEGER,INTENT(IN)::Ny_l,nnz INTEGER,INTENT(INOUT)::k Real(PR), Dimension(nnz), Intent(Out) :: AA Integer, Dimension(nnz), Intent(Out) :: IA,JA Integer::d !ONLY WHEN A PROCES GOT Nx_l==1 DO d = 1, Ny_l IF(d == 1)THEN AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 ELSE IF(d>1 .AND. d<Ny_l)THEN k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 ELSE IF(d == Ny_l)THEN k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d END IF END DO End Subroutine L1_NXL_eqv_1 Subroutine L1(Ny_l,nnz,k,AA,IA,JA) INTEGER,INTENT(IN)::Ny_l,nnz INTEGER,INTENT(INOUT)::k Real(PR), Dimension(nnz), Intent(Out) :: AA Integer, Dimension(nnz), Intent(Out) :: IA,JA Integer::d,hit DO d = 1, Ny_l IF(d == 1)THEN AA(k)=alpha; IA(k)=d; JA(k)=d DO hit = d+1, d+Ny_l, Ny_l-1 IF(hit == d+1)THEN k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=hit ELSE k=k+1; AA(k)=beta; IA(k)=d; JA(k)=hit END IF END DO ELSE IF(d>1 .AND. d<Ny_l)THEN k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l ELSE IF(d == Ny_l)THEN DO hit = d-1, d IF(hit == d-1)THEN k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=hit ELSE k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=hit END IF END DO k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l END IF END DO End Subroutine L1 SUBROUTINE TRACK(k,d) INTEGER,INTENT(INOUT)::k,d IF(rang==0)THEN PRINT*,'RANG',rang,'TRACK k,d',k,d END IF END SUBROUTINE TRACK Subroutine L2(Nx_l,Ny_l,nnz,d1,d2,k,AA,IA,JA) Integer, Intent(IN) :: Nx_l, Ny_l, nnz Integer, Intent(INOUT) :: d1, d2, k Real(PR), Dimension(nnz), Intent(Out) :: AA Integer, Dimension(nnz), Intent(Out) :: IA,JA INTEGER :: i, d DO i = 1, Nx_l-2 DO d = d1,d2 IF(d == d1)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l ELSE IF(d>d1 .AND. d<d2)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l ELSE IF(d == d2)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l END IF END DO d1 = d2+1; d2=d2+Ny_l END DO End Subroutine L2 Subroutine L3(mul1,mul2,Ny_l,nnz,k,AA,IA,JA) Integer, Intent(IN) :: mul1, mul2, Ny_l, nnz Integer, Intent(INOUT) :: k Real(PR), Dimension(nnz), Intent(Out) :: AA Integer, Dimension(nnz), Intent(Out) :: IA,JA INTEGER :: d DO d = mul1, mul2 IF(d == mul1)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 ELSE IF(d>mul1 .AND. d<mul2)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 ELSE IF(d == mul2)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d END IF END DO End Subroutine L3 Subroutine L1_Neuman(Ny_l,nnz,k,AA,IA,JA) IMPLICIT NONE INTEGER,INTENT(IN)::Ny_l,nnz INTEGER,INTENT(INOUT)::k Real(PR), Dimension(nnz), Intent(Out) :: AA Integer, Dimension(nnz), Intent(Out) :: IA,JA Integer::d,hit DO d = 1, Ny_l IF(d == 1)THEN AA(k)=alpha_neuman_H IA(k)=d JA(k)=d DO hit = d+1, d+Ny_l, Ny_l-1 IF(hit == d+1)THEN k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=hit ELSE k=k+1; AA(k)=beta; IA(k)=d; JA(k)=hit END IF END DO ELSE IF(d>1 .AND. d<Ny_l)THEN k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha_neuman_H; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l ELSE IF(d == Ny_l)THEN DO hit = d-1, d IF(hit == d-1)THEN k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=hit ELSE k=k+1; AA(k)=alpha_neuman_H; IA(k)=d; JA(k)=hit END IF END DO k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l END IF END DO End Subroutine L1_Neuman Subroutine L3_neuman(mul1,mul2,Ny_l,nnz,k,AA,IA,JA) IMPLICIT NONE Integer, Intent(IN) :: mul1, mul2, Ny_l, nnz Integer, Intent(INOUT) :: k Real(PR), Dimension(nnz), Intent(Out) :: AA Integer, Dimension(nnz), Intent(Out) :: IA,JA INTEGER :: d DO d = mul1, mul2 IF(d == mul1)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=alpha_neuman_B; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 ELSE IF(d>mul1 .AND. d<mul2)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha_neuman_B; IA(k)=d; JA(k)=d k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 ELSE IF(d == mul2)THEN k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 k=k+1; AA(k)=alpha_neuman_B; IA(k)=d; JA(k)=d END IF END DO End Subroutine L3_neuman end module mod_constr_mat
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/DD_Neuman_TRUE_LAST/mod_fonctions.f90
!--------------------------------------------- ! CE MODULE CONTIENT LES FONCTIONS ! DES TERMES SOURCES DE L'EQUATION !--------------------------------------------- Module mod_fonctions !---modules------------------- use mod_parametres !----------------------------- Implicit None Contains !---fonction f premier exemple(terme source)--- Real(PR) Function f1(CT,x,y,t) Integer, Intent(In) :: CT Real(PR), Intent(In) :: x,y,t f1 = 0.0_PR If (CT==1) Then f1=2._PR*(y*(1._PR-y)+x*(1._PR-x)) Else IF (CT==2) Then f1=sin(x)+cos(y) Else If (CT==3) Then f1=exp(-((x-(Lx/2._PR))**2._PR))*exp(-((y-(Ly/2._PR))**2._PR))& *cos((pi/2._PR)*t) End If End Function f1 !---------------------------------------------- !---fonction g premier exemple( bords haut/bas)- Real(PR) Function g1(CT,x,y,t) Integer, Intent(In) :: CT Real(PR), Intent(In) :: x,y,t g1 = 0.0_PR If (CT==1) Then g1=0._PR Else IF (CT==2) Then g1=sin(x)+cos(y) Else If (CT==3) Then g1=0._PR End If End Function g1 !---------------------------------------------- !---function h premier exemple(bord gauche/droite) Real(PR) Function h1(CT,x,y,t) Integer, Intent(In) :: CT Real(PR), Intent(In) :: x,y,t h1 = 0.0_PR If (CT==1) Then h1=0._PR Else IF (CT==2) Then h1=sin(x)+cos(y) Else If (CT==3) Then h1=1._PR End If End Function h1 !---Fonctions donnant les vecteurs Xi,Yj,Tn--------------- Subroutine param(X,Y,T) Implicit None !---variables------------------------- real(PR), Dimension(:), Allocatable, Intent(InOut) :: X real(PR), Dimension(:), Allocatable, Intent(InOut) :: Y real(PR), Dimension(:), Allocatable, Intent(InOut) :: T Integer :: i !------------------------------------- ALLOCATE(Y(0:Ny_g+1),T(0:Nt+1),X(0:Nx_g+1)) Do i=0,Ny_g+1 Y(i)=i*dy End Do Do i=0,Nt+1 T(i)=i*nt End Do DO i=0,Nx_g+1 X(i)=i*dx END DO !SET VARIABLES SIZE USED MANY TIMES !FOR x VECTOR: LBX = lbound(X,1) ; UBX = ubound(X,1) !FOR UD AND UG VECTORS TO RECV: LBUD = itN+1-2*Ny_g ; UBUD = itN LBUG = it1 ; UBUG = it1-1+2*Ny_g !FOR VECTOR SIZE TO SEND: A = (itN - 2*overlap*Ny_g) +1; B = A + 2*Ny_g -1 DD = (it1 + 2*overlap*Ny_g) -1; C = DD - 2*Ny_g +1 End Subroutine param Subroutine param_para(rang,Np,S1,S2,Ny_l,X,Y,T) Implicit None !---variables------------------------- Integer, Intent(IN) :: rang, Np, S1, S2, Ny_l real(PR), Dimension(:), Allocatable, Intent(InOut) :: X real(PR), Dimension(:), Allocatable, Intent(InOut) :: Y real(PR), Dimension(:), Allocatable, Intent(InOut) :: T Integer :: i !------------------------------------- ALLOCATE(Y(0:Ny_l+1),T(0:Nt+1)) Do i=0,Ny_l+1 Y(i)=i*dy End Do Do i=0,Nt+1 T(i)=i*nt End Do IF(rang == 0)THEN ALLOCATE(X(S1-1:S2)) Do i=S1-1,S2 X(i)=i*dx End Do ELSE IF(rang == Np-1)THEN ALLOCATE(X(S1:S2+1)) DO i=S1,S2+1 X(i)=i*dx END DO ELSE ALLOCATE(X(S1:S2)) DO i=S1,S2 X(i)=i*dx END DO END IF !SET VARIABLES SIZE USED MANY TIMES !FOR x VECTOR: LBX = lbound(X,1) ; UBX = ubound(X,1) !FOR UD AND UG VECTORS TO RECV: LBUD = itN+1-2*Ny_g ; UBUD = itN LBUG = it1 ; UBUG = it1-1+2*Ny_g !FOR VECTOR SIZE TO SEND: A = (itN - 2*overlap*Ny_g) +1; B = A + 2*Ny_g -1 DD = (it1 + 2*overlap*Ny_g) -1; C = DD - 2*Ny_g +1 End Subroutine param_para !------------------------------------------------------------- End Module mod_fonctions
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/DD_Neuman_TRUE_LAST/mod_gmres.f90
module mod_gmres USE mod_parametres USE mod_fonctions Implicit None Contains !---FONCTION PRODUIT MATxVEC EN SPARSE------------------------- Function MatVecSPARSE(AA,IA,JA,x) Result(y) Implicit None !Produit MatriceSPARSE.vecteur plein (x) retourne vecteur plein(y) !---variables------------------------------------------ Real(PR), Dimension(:), Intent(In) :: AA,x Integer, Dimension(:), Intent(In) :: IA,JA Real(PR), Dimension(Size(x)) :: y Integer :: i,n,nnz !-------------------------------------------------------- n=Size(x,1) nnz=Size(AA,1) y(1:n)=0._PR Do i=1,nnz if (IA(i)==0) then !print*,"element IA nul pour i =",i end if y(IA(i))=y(IA(i))+AA(i)*x(JA(i)) End Do End Function MatVecSPARSE !--------------------------------------------------------------- !---FONCTION PRODUIT MATxVEC EN SPARSE------------------------- Function COL_MatVecSPARSE(AA,IA,JA,x,dim) Result(y) Implicit None !Produit MatriceSPARSE.vecteur plein (x) retourne vecteur plein(y) !---variables------------------------------------------ Integer, Intent(IN) :: dim Real(PR), Dimension(:), Intent(In) :: AA Real(PR), Dimension(1:dim,1), Intent(In) :: x Integer, Dimension(:), Intent(In) :: IA,JA Real(PR), Dimension(dim) :: y Integer :: i,nnz !-------------------------------------------------------- !n=Size(x,1) nnz=Size(AA,1) y(1:dim)=0._PR Do i=1,nnz if (IA(i)==0) then !print*,"element IA nul pour i =",i end if y(IA(i))=y(IA(i))+AA(i)*x(JA(i),1) End Do End Function COL_MatVecSPARSE !--------------------------------------------------------------- Subroutine GMres_COO(AA,IA,JA,f,x0,x,b,k,dim,it1,itN,DIMKRYLOV) Implicit None !-----Variables: dim = Na_l Integer, Intent(IN) :: dim, it1, itN, DIMKRYLOV Real(PR), Dimension(:), Intent(In) :: AA Integer, Dimension(:), Intent(In) :: IA,JA Real(PR), Dimension(it1:itN), Intent(In) :: f,x0 !f=vect source , x0=CI Real(PR), Dimension(it1:itN), Intent(InOut) :: x !solution finale Real(PR), Intent(Out) :: b !norme du résidu Integer, Intent(Out) :: k !nb d'itérations pour convergence Integer :: m ! m = DIMKRYLOV Integer :: kmax !nb d'itérations max Real(PR) ::beta !norm2 de r Real(PR) :: eps !tol solver ! Rescale: Bufferx(1:dim) = x(it1:itN) so natural dot_product Real(PR), Dimension(:), Allocatable :: Bufferx0, Bufferx, Bufferf !---- Vectors & Matrix used for GMres: Real(PR),dimension(1:dim,1:DIMKRYLOV+1)::Vm !Real(PR),dimension(1:m+1,1:m)::Hm_ Real(PR),dimension(:,:),allocatable::Hm_ Real(PR),dimension(1:DIMKRYLOV+1,1:DIMKRYLOV)::Rm_ Real(PR),dimension(1:DIMKRYLOV+1,1:DIMKRYLOV+1)::Qm_ Real(PR),dimension(1:dim,1:DIMKRYLOV)::FF !Vm+1.Hm_ Real(PR),dimension(1:DIMKRYLOV+1)::gm_ Real(PR),dimension(1:DIMKRYLOV)::y !sol de Rm.y=gm Real(PR),dimension(1:dim)::Vmy Real(PR),dimension(1:dim)::AX Real(PR),dimension(1:dim)::z,p,r Allocate(Bufferx0(1:itN-it1+1)) Bufferx0(1:dim) = x0(it1:itN) Allocate(Bufferx(1:itN-it1+1)) Bufferx(1:dim) = x(it1:itN) Allocate(Bufferf(1:itN-it1+1)) Bufferf(1:dim) = f(it1:itN) m = DIMKRYLOV beta=0.0_PR k=0 !**INITIALISATION DE ro=b-AXo:MatVecSPARSE(AA,IA,JA,x) r=Bufferf-MatVecSPARSE(AA,IA,JA,Bufferx0) beta = DOT_PRODUCT(r,r) beta = sqrt(beta) eps = 0.00001_PR kmax = dim**2 boucle_eps_kmax:DO WHILE(beta>eps .AND. k<kmax) !Construction DE LA BASE Vm et de Hm_ ALLOCATE(Hm_(1:m+1,1:m)) CALL arnoldi_reortho(dim,m,AA,IA,JA,r,beta,Vm,Hm_) !Decomposion QR de Hm_ pour avoir Qm_ et Rm_ Rm_ = Hm_ DEALLOCATE(Hm_) CALL givens_QR_opt2(dim,m,Rm_,Qm_) !CALL givens_QR_opt(dim,m,Hm_,Qm_,Rm_) !Setup gm_ = transpose(Qm_). beta*e1 gm_LOOP:DO i = 1,m+1 gm_(i) = beta * Qm_(1,i) END DO gm_LOOP !Resolution DE Rm.y=gm où Rm=Rm_(1:m,:)et gm= gm_(1:m) y(m)=gm_(m)/Rm_(m,m) moindrecarre:do j=m-1,1,-1 y(j)=gm_(j) do c=j+1,m y(j)=y(j)-Rm_(j,c)*y(c) end do y(j)=y(j)/Rm_(j,j) end do moindrecarre !Calcul de Vmy Vmy=MATMUL(Vm(1:dim,1:m),y) !CALCUL de X=X+Vm.y Bufferx=Bufferx+Vmy !Actualisation r: r=bufferf-MatVecSPARSE(AA,IA,JA,Bufferx) beta=sqrt(DOT_PRODUCT(r,r)) k=k+1 ! PRINT*,'APRES k=k+1',k,beta if(rang==0)then print*,'gmres rang,k,res',rang,k,beta end if END DO boucle_eps_kmax b = beta x(it1:itN) = Bufferx(1:dim) Deallocate(Bufferx0,Bufferx,Bufferf) End Subroutine GMres_COO !---------- !$$$$$$$$$$$$$$$$ARNOLDI MGS REORTHO$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ subroutine arnoldi_reortho(dim,m,AA,IA,JA,ro,beta,Vm,Hm_)!v,Vm,Hm_) Implicit None !la notation Hm_ pour la barre up du Hm correspondant !à la notation theorique !m nbr de colonne de Vm ; Vm appartient à M_n,m(R), n =dim ici integer,intent(in)::dim,m !on utilise m pour fixer la dimension de Vm, !base constituée des (vi)i Real(PR),dimension(1:dim),intent(in)::ro Real(PR),intent(in)::beta !ro=b-Axo !beta =||ro|| au carré !Real(PR),dimension(1:dim),intent(inout)::v !v vecteur constituant les colonnes de Vm Real(PR), Dimension(:), Intent(In) :: AA Integer, Dimension(:), Intent(In) :: IA,JA !Real(PR),dimension(1:dim,1:dim),intent(in)::A Real(PR),dimension(1:dim,1:m+1),intent(out)::Vm Real(PR),dimension(1:m+1,1:m),intent(out)::Hm_ Real(PR),dimension(1:dim)::z,Av !z vecteur de stockage pour calcul de v !Av pour stocker A.v_j ,v_j la colonne de Vm Real(PR)::pscal,nz,tmp !nz pour calculer la norme de z integer::k,i,j,c,d !**INITIALISATION DE v: Vm=0.0_PR Hm_=0.0_PR !v=ro/beta !v1 do i=1,dim Vm(i,1)=ro(i)/beta end do !**CALCUL DE z: j=0 do while(j<m) j=j+1 !$$CALCUL DE A.v: Av=0.0_PR Av = Av + COL_MatVecSPARSE(AA,IA,JA,Vm(1:dim,j),dim) z=Av do i=1,j !$$CALCUL DE SUM(<Avj|vi>.vi) pscal=0.0_PR pscal=DOT_PRODUCT(Av,Vm(1:dim,i)) Hm_(i,j)=pscal z=z-Hm_(i,j)*Vm(:,i) end do!fin do i !$$$$$REORTHO do i=1,j!j tmp=0.0_PR tmp=DOT_PRODUCT(z,Vm(:,i)) z=z-tmp*Vm(:,i) Hm_(i,j)=Hm_(i,j)+tmp end do !$$CALCUL DE ||z||: nz=0.0_PR nz=DOT_PRODUCT(z,z) nz=sqrt(nz) Hm_(j+1,j)=nz !$$CONDITION ARRET HEUREUX: if(abs(Hm_(j+1,j))<0.00000001_PR)then j=m+1!stop else !end if !$$FIN CONDITION ARRET HEUREUX !$$ACTUALISATION/CALCUL DE Vm(:,j+1); v_(j+1) la j+1 ieme cows de Vm Vm(:,j+1)=z !/Hm_(j+1,j) Vm(:,j+1)=Vm(:,j+1)/nz end if ! PRINT*,'MGS_REORTHO',j end do end subroutine arnoldi_reortho subroutine givens_QR_opt2(dim,m,Rm_,Qm_)!Hm_,Qm_,Rm_) Implicit None integer,intent(in)::dim,m !real,dimension(1:m+1,1:m),intent(in)::Hm_ Real(PR),dimension(1:m+1,1:m),intent(inout)::Rm_ Real(PR),dimension(1:m+1,1:m+1),intent(out)::Qm_ Real(PR)::c,s Real(PR)::coef1,coef2,coef_a,coef_b Real(PR)::TQ1,TQ2,TQ3,TQ4 Real(PR)::Qg,Qd integer::i,j,k,l !Rm_=Hm_ Qm_=0.0_PR do i=1,m+1 Qm_(i,i)=1.0_PR!?stock_T_Qm_(i,i)=1. end do do j=1,m!-1!m do l=j+1,j+1,-1!m+1,j+1,-1 !DE j+1 à j+1 car Hm_ forme de Hessenberg coef1=Rm_(l,j);coef2=Rm_(l-1,j) c=coef1*coef1+coef2*coef2;c=sqrt(c) s=c c=coef2/c;s=-coef1/s TQ1=c !T_Qm_(l,l)=c TQ2=c !T_Qm_(l-1,l-1)=c TQ3=-s !T_Qm_(l-1,l)=-s TQ4=s !T_Qm_(l,l-1)=s do k=j,m coef_a=Rm_(l-1,k);coef_b=Rm_(l,k) Rm_(l-1,k)=c*coef_a-s*coef_b Rm_(l,k)=s*coef_a+c*coef_b end do Rm_(l,j)=0.0_PR TQ3=-TQ3 TQ4=-TQ4 if(j==1 .AND. l==j+1)then Qm_(l,l)=TQ1;Qm_(l-1,l-1)=TQ2;Qm_(l-1,l)=TQ3;Qm_(l,l-1)=TQ4 else do i=1,m+1 Qg=Qm_(i,l-1);Qd=Qm_(i,l) Qm_(i,l-1)=Qg*TQ2+Qd*TQ4 Qm_(i,l)=Qg*TQ3+Qd*TQ1 end do end if end do !fin do l ! PRINT*,'GIVENS',j end do !fin do j end subroutine givens_QR_opt2 end module mod_gmres
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/DD_Neuman_TRUE_LAST/mod_gradconj.f90
!----------------------------------------- ! CE MODULE CONTIENT LE GRADIENT CONJUGUÉ ! EN PLEIN ET EN CREUX (FORMAT COORDONNES) !----------------------------------------- Module mod_gradconj !---modules---------------- use mod_parametres use mod_fonctions !-------------------------- Implicit None Contains !---GRADIENT CONJUGUÉ POUR UNE MATRICE A PLEINE--------- Subroutine gradconj(A,b,x0,x,beta,k,n) !---variables------------------------------------ Integer, Intent(In) :: n !taille vecteur solution (=taille de la matrice carrée) Real(PR), Dimension(:,:), Intent(In) :: A !matrice à inverser Real(PR), Dimension(:), Intent(In) :: b,x0 ! b second membre, x0 CI Real(PR), Dimension(:), Intent(Out) :: x !solution finale Real(PR), Intent(Out) :: beta !norme du résidu Real(PR), Dimension(:), Allocatable :: p,z,r1,r2 Real(PR) :: alpha,gamma,eps Integer, Intent(Out) :: k !nb d'itération pr convergence Integer :: kmax !------------------------------------------------- eps=0.01_PR kmax=150 Allocate(p(n),z(n),r1(n),r2(n)) r1=b-matmul(A,x0) p=r1 beta=sqrt(sum(r1*r1)) k=0 Do While (beta>eps .and. k<=kmax) z=matmul(A,p) alpha=dot_product(r1,r1)/dot_product(z,p) x=x+alpha*p r2=r1-alpha*z gamma=dot_product(r2,r2)/dot_product(r1,r1) p=r2+gamma*p beta=sqrt(sum(r1*r1)) k=k+1 r1=r2 End Do If (k>kmax) then Print*,"Tolérance non atteinte:",beta End If Deallocate(p,z,r1,r2) End Subroutine gradconj !---------------------------------------------------- !---GRADIENT CONJUGUÉ POUR MATRICE CREUSE AU FORMAT COORDONNÉES----- !---A PARALLELISER : PRODUIT MATRICE/VECTEUR + PRODUIT SCALAIRE Subroutine gradconj_SPARSE(AA,IA,JA,F,x0,x,b,k,n) Implicit None !---variables --------------------------------------- Integer, Intent(In) :: n !taille vecteur solution Real(PR), Dimension(:), Intent(In) :: AA Integer, Dimension(:), Intent(In) :: IA,JA Real(PR), Dimension(:), Intent(In) :: f,x0 !f=vect source , x0=CI Real(PR), Dimension(:), Intent(InOut) :: x !solution finale Real(PR), Intent(Out) :: b !norme du résidu Real(PR), Dimension(:), Allocatable :: p,z,r1,r2 Real(PR) :: a,g,eps Integer, Intent(Out) :: k !nb d'itérations pour convergence Integer :: kmax !nb d'itérations max !----------------------------------------------------- eps=0.01_PR kmax=1500 Allocate(p(n),z(n),r1(n),r2(n)) !---paralléliser------------------------ r1=f-MatVecSPARSE(AA,IA,JA,x0) !------------------------------------- p=r1 b=sqrt(sum(r1*r1)) k=0 Do While (b>eps .and. k<=kmax) !---paralléliser------------------ z=MatVecSPARSE(AA,IA,JA,p) !--------------------------------- a=dot_product(r1,r1)/dot_product(z,p) x=x+a*p r2=r1-a*z g=dot_product(r2,r2)/dot_product(r1,r1) p=r2+g*p b=sqrt(sum(r1*r1)) k=k+1 r1=r2 End Do If (k>kmax) then Print*,"Tolérance non atteinte:",b End If Deallocate(p,z,r1,r2) End Subroutine gradconj_SPARSE !-------------------------------------------------------------- !---FONCTION PRODUIT MATxVEC EN SPARSE------------------------- Function MatVecSPARSE(AA,IA,JA,x) Result(y) !Produit MatriceSPARSE.vecteur plein (x) retourne vecteur plein(y) !---variables------------------------------------------ Real(PR), Dimension(:), Intent(In) :: AA,x Integer, Dimension(:), Intent(In) :: IA,JA Real(PR), Dimension(Size(x)) :: y Integer :: i,n,nnz !-------------------------------------------------------- n=Size(x,1) nnz=Size(AA,1) y(1:n)=0._PR Do i=1,nnz if (IA(i)==0) then print*,"element IA nul pour i =",i end if y(IA(i))=y(IA(i))+AA(i)*x(JA(i)) End Do End Function MatVecSPARSE !--------------------------------------------------------------- !GC COO FORMAT BUILD FOR global numerotation over x Subroutine MOD_gradconj_SPARSE(AA,IA,JA,f,x0,x,b,k,it1,itN) Implicit None !---variables --------------------------------------- Integer, Intent(In) :: it1,itN !taille vecteur solution Real(PR), Dimension(:), Intent(In) :: AA Integer, Dimension(:), Intent(In) :: IA,JA Real(PR), Dimension(it1:itN), Intent(In) :: f,x0 !f=vect source , x0=CI Real(PR), Dimension(it1:itN), Intent(InOut) :: x !solution finale Real(PR), Intent(Out) :: b !norme du résidu Real(PR), Dimension(:), Allocatable :: p,z,r1,r2 Real(PR) :: a,g,eps Integer, Intent(Out) :: k !nb d'itérations pour convergence Integer :: kmax !nb d'itérations max !----------------------------------------------------- eps=0.000001_PR kmax=1500 Allocate(p(it1:itN),z(it1:itN),r1(it1:itN),r2(it1:itN)) !---paralléliser------------------------ r1=f-MOD_MatVecSPARSE(AA,IA,JA,x0,it1,itN) !------------------------------------- p=r1 b=sqrt(sum(r1*r1)) k=0 Do While (b>eps .and. k<=kmax) !---paralléliser------------------ z=MOD_MatVecSPARSE(AA,IA,JA,p,it1,itN) !--------------------------------- a=dot_product(r1,r1)/dot_product(z,p) x=x+a*p r2=r1-a*z g=dot_product(r2,r2)/dot_product(r1,r1) p=r2+g*p b=sqrt(sum(r1*r1)) k=k+1 r1=r2 !PRINT*,'k,b',k,b End Do If (k>kmax) then Print*,"Tolérance non atteinte:",b End If Deallocate(p,z,r1,r2) End Subroutine MOD_gradconj_SPARSE !-------------------------------------------------------------- !---FONCTION PRODUIT MATxVEC EN SPARSE------------------------- Function MOD_MatVecSPARSE(AA,IA,JA,x,it1,itN) Result(y) !Produit MatriceSPARSE.vecteur plein (x) retourne vecteur plein(y) !---variables------------------------------------------ INTEGER,INTENT(IN)::it1,itN Real(PR), Dimension(:), Intent(In) :: AA Real(PR), Dimension(it1:itN), Intent(In) ::x Integer, Dimension(:), Intent(In) :: IA,JA Real(PR), Dimension(it1:itN) :: y Integer :: i,n,nnz,val !-------------------------------------------------------- n=Size(x,1) !PRINT*,'***',n,itN-it1+1 nnz=Size(AA,1) y(it1:itN)=0._PR val=(it1-1) Do i=1,nnz if (IA(i)==0) then print*,"element IA nul pour i =",i end if !PRINT*,i,IA(i),val+IA(i),JA(i),val+JA(i),x(val+JA(i)) y(val+IA(i))=y(val+IA(i))+AA(i)*x(val+JA(i)) End Do End Function MOD_MatVecSPARSE !--------------------------------------------------------------- Subroutine MOD_jacobi_SPARSE(AA,IA,JA,F,x0,x,resnorm,k) !-----variables--------------------- Real(PR), Dimension(nnz_l), Intent(In) :: AA Integer, Dimension(nnz_l), Intent(In) :: IA,JA Real(PR), Dimension(it1:itN), Intent(InOut) :: F,x0 !f=vect source , x0=CI Real(PR), Dimension(it1:itN), Intent(InOut) :: x !solution finale Real(PR), Intent(Out) :: resnorm !norme du résidu Real(PR), Dimension(:), Allocatable :: r Real(PR) :: eps,somme Integer, Intent(InOut) :: k !nb d'itérations pour convergence Integer :: kmax,pp,val,ii,borne !nb d'itérations max ALLOCATE(r(it1:itN)) borne=nnz_l+1 x=x0 eps = 0.000001_PR kmax = 100000 r = F-MOD_MatVecSPARSE(AA,IA,JA,x0,it1,itN) !résidu initial resnorm = sqrt(sum(r*r)) !norme 2 du résidu k = 0 !initialisation itération boucle_resolution: Do While ((resnorm>eps) .and. (k<kmax)) k=k+1 !on calcule xi^k+1=(1/aii)*(bi-sum(j=1,n;j/=i)aij*xj^k) x0=0._PR pp=1;val=it1-1 boucle_xi: Do ii=1,Na_l !calcul de la somme des aij*xj^k pour j=1,n;j/=i somme = 0.0_PR; !!$ if(rang==0)then !!$ PRINT*,'ii,pp,k,nnz_l,ubound IA',ii,pp,k,nnz_l,ubound(IA,1),nnz_l+1 !!$ end if DO WHILE((pp<borne) .AND. (ii==IA(pp))) IF (IA(pp) /= JA(pp)) THEN somme= somme + x(val+JA(pp)) * AA(pp) END IF !!$ if(rang==0)then !!$ PRINT*,'ii,pp,IA(pp),JA(pp),AA(pp),x(JA(pp))',ii,pp,IA(pp),JA(pp),AA(pp),x(val+JA(pp)) !!$ end if pp=pp+1 !PRINT*,'pp',pp if(pp==borne)then !because the do while check both pp<borne and ii==IA(pp),maybe due to makefile ! he should break when pp>=borne and don't check ii==IA(pp) GOTO 7777 end if END DO !calcul du nouveau xi 7777 x0(val+ii)=(1._PR/alpha)*(F(val+ii)-somme) x0(val+ii)=(1._PR/alpha)*(F(val+ii)-somme)!;print*,'t',rang End Do boucle_xi x=x0 !on calcule le nouveau résidu r = F - MOD_MatVecSPARSE(AA,IA,JA,x,it1,itN) ! calcul de la norme 2 du résidu resnorm = sqrt(sum(r*r)) if(mod(k,1000)==0)then print*,resnorm,k end if End Do boucle_resolution If (k>kmax) then Print*,"Tolérance non atteinte:",resnorm End If DEALLOCATE(r) print*,"converge avec eps=",resnorm End Subroutine MOD_jacobi_SPARSE subroutine BICGSTAB(it1, itN, AA, IA, JA, x, b, eps) implicit none Integer, Intent(IN) :: it1, itN real(PR), dimension(:), intent(In) :: AA integer, dimension(:), intent(In) :: IA, JA real(PR), dimension(it1:itN), intent(InOut) :: x real(PR), dimension(it1:itN), intent(In) :: b real(PR), intent(In) :: eps real(PR), dimension(it1:itN) :: r0, v, p, r, h, s, t real(PR) :: rho_i, rho_im1, alpha_CG, omega, w, beta_CG Real(PR) :: beta_res integer :: kmax integer :: k omega = 1.0_PR !x = 0._PR r0 = b - MOD_MatVecSPARSE(AA,IA,JA,x,it1,itN) r = r0 beta_res = SQRT(DOT_PRODUCT(r0,r0)) rho_im1 = 1._PR; alpha_CG = 1._PR; w = 1._PR v = 0._PR; p = 0._PR k = 0 kmax = 2*Na_l*Na_l !do while((maxval(abs(r))>eps) .and. (k<kmax)) do while( beta_res >eps .and. (k<kmax) ) rho_i = dot_product(r0, r) beta_CG = (rho_i/rho_im1)*(alpha_CG/w) p = r+beta_CG*(p-v*w) v = MOD_MatVecSPARSE(AA,IA,JA,p,it1,itN) alpha_CG = rho_i/dot_product(r0, v) h = x+p*alpha_CG s = r-v*alpha_CG t = MOD_MatVecSPARSE(AA,IA,JA,s,it1,itN) w = dot_product(t, s)/dot_product(t, t) x = h+s*w r = s-t*w beta_res = SQRT(DOT_PRODUCT(r,r)) rho_im1 = rho_i k = k+1 end do !PRINT*,'RESIDU=',maxval(abs(r)) end subroutine BICGSTAB End Module mod_gradconj
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/DD_Neuman_TRUE_LAST/mod_matsys.f90
!---------------------------------------------------- ! CE MODULE CONTIENT LA CONSTRUCTION DE LA MATRICE A ! ET LE VECTEUR SOURCE F !---------------------------------------------------- Module mod_matsys !---modules------------------- Use mod_parametres Use mod_fonctions Use mod_gradconj Use mod_constr_mat !----------------------------- Implicit None Contains !--- SUBROUTINE QUI CONSTRUIT LA MATRICE A : UN SEUL APPEL ---------------------- Subroutine matsys_v2(nnz,Nx_l,Ny_l,AA,IA,JA) Integer, Intent(IN) ::nnz,Nx_l,Ny_l Real(PR), Dimension(:), Allocatable, Intent(Out) :: AA Integer, Dimension(:), Allocatable, Intent(Out) :: IA,JA Integer :: k, mul2, d1, d2, mul1 k = 1; mul2 = Nx_l*Ny_l; mul1 = Ny_l*(Nx_l-1)+1 ALLOCATE(AA(nnz),IA(nnz),JA(nnz)) !L1----------------------------------------------------------- IF(Nx_l > 1)THEN if (rang/=0) then CALL L1_neuman(Ny_l,nnz,k,AA,IA,JA) else CALL L1(Ny_l,nnz,k,AA,IA,JA) end if !CRTL nnz_L1 IF(k /= crtl_L1_nnz)THEN PRINT*,'ERROR L1_nnz','RANG',rang,'k_L1',k,'/=','crtl_L1_nnz',crtl_L1_nnz AA=0._PR;IA=0;JA=0 END IF ELSE IF(Nx_l == 1)THEN CALL L1_NXL_eqv_1(Ny_l,nnz,k,AA,IA,JA) IF(k /= crtl_L1_nnz_Nxl_EQV_1)THEN PRINT*,'ERROR L1_nnz','RANG',rang,'k_L1',k,'/=','crtl_L1_nnz_Nxl_EQV_1',crtl_L1_nnz_Nxl_EQV_1 AA=0._PR;IA=0;JA=0 END IF END IF !L2----------------------------------------------------------- IF(Nx_l>2)THEN d1 = Ny_l+1; d2 = 2*Ny_l CALL L2(Nx_l,Ny_l,nnz,d1,d2,k,AA,IA,JA) IF(k /= crtl_L1_nnz + crtl_L2_nnz)THEN PRINT*,'ERROR L2_nnz','RANG',rang,'k_L2',k-crtl_L1_nnz,'/=','crtl_L2_nnz',crtl_L2_nnz AA=0._PR;IA=0;JA=0 END IF END IF !L3----------------------------------------------------------- IF(Nx_l>1)THEN if (rang/=Np-1) then CALL L3_neuman(mul1,mul2,Ny_l,nnz,k,AA,IA,JA) else CALL L3(mul1,mul2,Ny_l,nnz,k,AA,IA,JA) end if PRINT*,'rang',rang,'k',k,'FIN L3' IF(k /= sum_crtl_L_nnz)THEN PRINT*,'ERROR L3_nnz','RANG',rang,'k_L3',k-crtl_L1_nnz-crtl_L2_nnz,'/=','crtl_L3_nnz',crtl_L3_nnz AA=0._PR;IA=0;JA=0 END IF END IF END Subroutine matsys_v2 !--------SUBROUTINE DU VECTEUR SOURCE EN FONCTION DE L'ITERATION N ET DU VECTEUR U-------- Subroutine vectsource(CT,U,S1,S2,X,Y,T,F) Implicit None !---variables---------------------------------- Integer, Intent(In) :: CT, S1, S2 Real(PR), Dimension(it1:itN), Intent(In) :: U Real(PR), Dimension(LBX:UBX), Intent(IN) :: X Real(PR), Dimension(0:Ny_g+1), Intent(IN) :: Y !BECAUSE DD 1D => Ny_l == Ny_g Real(PR), Intent(IN) :: T Real(PR), Dimension(it1:itN), Intent(INOUT) :: F Integer :: i,j,k DO i = S1, S2 DO j = 1, Ny_g k = j + (i-1)*Ny_g F(k) = dt * f1(CT,X(i),Y(j),T) IF(i == 1)THEN F(k) = F(k) - h1(CT,X(i-1),Y(j),T)*beta ELSE IF(i == Nx_g)THEN F(k) = F(k) - h1(CT,X(i+1),Y(j),T)*beta END IF IF(j == 1)THEN F(k) = F(k) - g1(CT,X(i),Y(j-1),T)*gamma ELSE IF(j == Ny_g)THEN F(k) = F(k) - g1(CT,X(i),Y(j+1),T)*gamma END IF END DO END DO F = F +U End Subroutine vectsource Subroutine vectsource_FULL(CT,U,UG,UD,S1,S2,X,Y,T,F) Implicit None !---variables---------------------------------- Integer, Intent(In) :: CT, S1, S2 Real(PR), Dimension(it1:itN), Intent(In) :: U Real(PR), Dimension(LBUG:UBUG), Intent(In) :: UG Real(PR), Dimension(LBUD:UBUD), Intent(In) :: UD Real(PR), Dimension(LBX:UBX), Intent(IN) :: X Real(PR), Dimension(0:Ny_g+1), Intent(IN) :: Y !BECAUSE DD 1D => Ny_l == Ny_g Real(PR), Intent(IN) :: T Real(PR), Dimension(it1:itN), Intent(INOUT) :: F Integer :: i,j,k DO i = S1, S2 DO j = 1, Ny_g k = j + (i-1)*Ny_g F(k) = dt * f1(CT,X(i),Y(j),T) IF(i == 1)THEN F(k) = F(k) - h1(CT,X(i-1),Y(j),T)*beta ELSE IF(i == S1 )THEN !.AND. rang /= 0)THEN not needed with the current order if... else if F(k) = F(k) + (D*dt/dx)*UG(k)*c_neuman + beta*( UG(k+Ny_g)-UG(k) ) ELSE IF(i == Nx_g)THEN F(k) = F(k) - h1(CT,X(i+1),Y(j),T)*beta ELSE IF(i == S2)THEN !.AND. rang /= Np-1)THEN not needed with the current order else if... else if F(k) = F(k) + (D*dt/dx)*UD(k)*c_neuman + beta*( UD(k-Ny_g)-UD(k) ) END IF IF(j == 1)THEN F(k) = F(k) - g1(CT,X(i),Y(j-1),T)*gamma ELSE IF(j == Ny_g)THEN F(k) = F(k) - g1(CT,X(i),Y(j+1),T)*gamma END IF END DO END DO F = F +U End Subroutine vectsource_FULL End Module mod_matsys !!$DO d = 1, Ny_l !!$ IF(d == 1)THEN !!$ AA(k)=alpha; IA(k)=d; JA(k)=d !!$ DO hit = d+1, d+Ny_l, Ny_l-1 !!$ IF(hit == d+1)THEN !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=hit !!$ ELSE !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=hit !!$ END IF !!$ END DO !!$ ELSE IF(d>1 .AND. d<Ny_l)THEN !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 !!$ k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l !!$ ELSE IF(d == Ny_l)THEN !!$ DO hit = d-1, d !!$ IF(hit == d-1)THEN !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=hit !!$ ELSE !!$ k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=hit !!$ END IF !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l !!$ END DO !!$ END IF !!$ END DO !!$IF(Nx_l>2)THEN !!$ d1 = Ny_l+1; d2 = 2*Ny_l !!$ DO i = 1, Nx_l-2 !!$ DO d = d1,d2 !!$ IF(d == d1)THEN !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l !!$ k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l !!$ ELSE IF(d>d1 .AND. d<d2)THEN !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 !!$ k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d+1 !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l !!$ ELSE IF(d == d2)THEN !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d-Ny_l !!$ k=k+1; AA(k)=gamma; IA(k)=d; JA(k)=d-1 !!$ k=k+1; AA(k)=alpha; IA(k)=d; JA(k)=d !!$ k=k+1; AA(k)=beta; IA(k)=d; JA(k)=d+Ny_l !!$ END IF !!$ END DO !!$ d1 = d2+1; d2=d2+Ny_l !!$ END DO !!$ END IF !!$Subroutine matsys(nnz,AA,IA,JA) !!$ Integer, Intent(In) :: nnz !!$ Real(PR), Dimension(:), Allocatable, Intent(Out) :: AA !!$ Integer, Dimension(:), Allocatable, Intent(Out) :: IA,JA !!$ Integer :: i,j,k !!$ k=1 !!$ Allocate(AA(nnz),IA(nnz),JA(nnz)) !!$ Do i=1,na !!$ Do j=1,na !!$ If (i==j) Then !diagonale principale !!$ AA(k)=alpha !!$ IA(k)=i !!$ JA(k)=j !!$ k=k+1 !!$ ElseIf ((i==j-1) .and. (modulo(i,nx)/=0)) Then !diagonale sup !!$ AA(k)=beta !!$ IA(k)=i !!$ JA(k)=j !!$ k=k+1 !!$ ElseIf ((i==j+1) .and. (i/=1) .and. (modulo(j,ny)/=0)) Then !diagonale inf !!$ AA(k)=beta !!$ IA(k)=i !!$ JA(k)=j !!$ k=k+1 !!$ ElseIf (j==ny+i) Then !diagonale la plus a droite !!$ AA(k)=gamma !!$ IA(k)=i !!$ JA(k)=j !!$ k=k+1 !!$ ElseIf (i==j+nx) Then !diagonale la plus a gauche !!$ AA(k)=gamma !!$ IA(k)=i !!$ JA(k)=j !!$ k=k+1 !!$ End If !!$ End Do !!$ End Do !!$End Subroutine matsys
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/DD_Neuman_TRUE_LAST/mod_parametres.f90
!----------------------------------------------- ! CE MODULE CONTIENT LES PARAMETRES DU PROBLEME !----------------------------------------------- Module mod_parametres USE mpi Implicit None !---Précision des calculs ------------------- Integer, Parameter :: PR=8 !-------------------------------------------- !---Parametres géométriques----------------- Real(PR), Parameter :: Lx=1._PR !Longueur de la barre Real(PR), Parameter :: Ly=1._PR !Largeur de la barre Real(PR), Parameter :: D=1._PR !Coefficient de diffusion !-------------------------------------------- !PARAMETRE DE VISUALISATION: INTEGER :: sysmove !---Parametres numériques------------------- !g means global Domain GLobal matrix WITHOUT DD ADDITIVE !l means local Domain local matrix Integer :: nnz_g Integer, Parameter :: Nx_g=200 !lignes de A (discrétisation en x) Integer, Parameter :: Ny_g=100 !colonnes de A (discrétisation en y) Integer, Parameter :: Na_g=Nx_g*Ny_g !taille de la matrice A Integer, Parameter :: Nt=30 !discrétisation du temps Real(PR), Parameter :: dx=1._PR/(Real(Nx_g)+1) ! pas en x Real(PR), Parameter :: dy=1._PR/(Real(Ny_g)+1) ! pas en y Real(PR), Parameter :: Tf=2._PR !temps final de la simulation Real(PR), Parameter :: dt=Tf/(Real(Nt)+1) !pas de temps Real(PR), Parameter :: pi=4._PR*atan(1._PR) Real(PR), Parameter :: alpha =1._PR+(2._PR*D*dt/(dx**2._PR))+(2._PR*D*dt/(dy**2._PR)) ! Real(PR), Parameter :: beta = (-D*dt)/(dx**2._PR) !AL ! CF coefficients matrice Real(PR), Parameter :: gamma =(-D*dt)/(dy**2._PR) !AP ! 2 autres coef sont dans ! mod_constr_mat.f90 !------------------------------------------- !---PARAMETRES MPI-------------------------- INTEGER ::rang,Pivot INTEGER ::Np INTEGER ::stateinfo INTEGER,DIMENSION(MPI_STATUS_SIZE)::status CHARACTER(LEN=3) ::rank INTEGER ::TAG !FOR TAG FILE !------------------------------------------ !---DEFINE INTERVALLE SUIVANT Y PAR PROCS------ INTEGER ::S1_old, S2_old, it1_old, itN_old !avant call charge_overlap INTEGER ::S1 INTEGER ::S2 !=> X_i^(rang) \in [|S1;S2|] INTEGER ::it1 INTEGER ::itN !=> P(OMEGA^(rang)) \in [|it1;itN|] INTEGER ::overlapd INTEGER ::overlapg INTEGER,PARAMETER::overlap=1 INTEGER ::Na_l !NBR rows or cols in local matrix !na_loc == (S2-S1+1)*Ny INTEGER ::Nx_l !Nx local will be set to S2-S1+1 INTEGER ::Ny_l INTEGER ::nnz_l !nbr de non zero in local matrix INTEGER ::crtl_nnz_l !control de nnz !since a A_l matrix local is made by block D AND C such: ![D][C][0][0] ! |s x 0 0| ! |v 0 0 0| ! A_l.rows=Nx_l*Ny_l=A_l.cols ![C][D][C][0] ![D]=|x s x 0| ![C]=|0 v 0 0| ! D.rows=D.cols=Ny_l ![0][C][D][C] ! |0 x s x| ! |0 0 v 0| ! C.cols=C.rows=Ny_l ![0][0][C][D] ! |0 0 x s| ! |0 0 0 v| !We got (Nx_l) [D] block & (Nx_l-1) [C] upper block !& (Nx_l-1) [C] lower block !SUCH THAT crtl_nnz_l=(Nx_l*Ny_l) + 2 * (Nx_l) * (Ny_l - 1) + 2 * (Nx_l - 1) * (Ny_l) INTEGER ::D_rows !will be set to Ny_l INTEGER ::D_nnz !will be set to D_rows+2*(D_rows-1) INTEGER ::C_rows !will be set to Ny_l INTEGER ::C_nnz !will be set to C_rows ! WE DEFINE a control nnz_l parameter over L1, L2, L3 such that: !|[D][C][0][0]| = [L1] !avec s=alpha_newmann INTEGER ::crtl_L1_nnz !will be set to D_nnz+C_nnz !|[C][D][C][0]| = [L2] !avec s=alpha !|[0][C][D][C]| INTEGER ::crtl_L2_nnz !will be set to (Nx_l-2)*(D_nnz+2*C_nnz) !|[0][0][C][D]| = [L3] !avec s=alpha_newmann INTEGER ::crtl_L3_nnz !will be set to D_nnz+C_nnz !SUCH THAT THE RELATION (*) NEED TO BE .TRUE.: !(*)crtl_L1_nnz+crtl_L2_nnz+crtl_L3_nnz = crtl_nnz_l = nnz_l INTEGER ::sum_crtl_L_nnz !sum of crtl_Li_nnz !DANS LE CAS OU Nx_l == 1: INTEGER :: crtl_L1_nnz_Nxl_EQV_1 ! will be set to D_nnz !---variables---------------------------------! Real(PR), Dimension(:), Allocatable :: X Real(PR), Dimension(:), Allocatable :: Y !Ny_g+2 Real(PR), Dimension(:), Allocatable :: T !Nt+2 Real(PR), Dimension(:), Allocatable :: AA Integer, Dimension(:), Allocatable :: IA,JA Real(PR), Dimension(:), Allocatable :: U,Uo,F !Na_l Real(Pr), Dimension(:), Allocatable :: UG, UD ! CL FROM BORDER IMMERGEE need to be set at zero Real(PR) :: res,t1,t2 !résidu du grandconj Integer :: k,i,j,it,CT !--- VARIABLES DE REDUCTION POUR SIZE OF x, UD, UG !initialisées in mod_fonctions.f90 INTEGER :: LBX INTEGER :: UBX !it's set to lbound(x) and ubound(x) INTEGER :: LBUD, LBUG !it's compute to set lbound(UD) and lbound(UG) INTEGER :: UBUD, UBUG !it's compute to set ubound(UD) and ubound(UG) !WILL BE SET TO: ! LBUD = itN+1-2*Ny_g || UBUD = itN ! LBUG = it1 || UBUG = it1-1+2*Ny_g !NEXT VARIABLES WILL BE USED ITO mod_comm.f90 !FOR SIZE OF VECTORS SEND INTEGER :: A, B INTEGER :: C, DD !A = (itN - 2*overlap*Ny_g) +1; B = A + 2*Ny_g -1 !C = DD - 2*Ny_g +1; DD = (it1 + 2*overlap*Ny_g) -1 !VARIABLES POUR LA BOUCLE SCHWARZ, CONVERGENCE DD: REAL(PR) :: Norm1, Norm2, C1, err REAL(PR), PARAMETER :: err_LIM = 0.0000000001_PR!0.0000001_PR INTEGER :: step End Module mod_parametres
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/DD_Neuman_TRUE_LAST/mod_sol.f90
module mod_sol use mpi use mod_parametres IMPLICIT NONE !*** MODULE ModSOL POUR DONNER LA SOLUTION EXACTE ET !*** POUR GERER L'ENREGISTREMENT DE LA SOLUTION DANS DES FICHIERS !*** SUBROUTINE POUR APPELLER UN SCRIPT GNUPLOT POUR LA VISUALISATION CONTAINS SUBROUTINE UEXACT(U,userchoice)!userchoice==CT INTEGER,INTENT(INOUT)::userchoice REAL(PR),DIMENSION(it1:itN),INTENT(IN)::U REAL(PR),DIMENSION(:),ALLOCATABLE::UEXA,DIFF REAL(PR)::ErrN2_RED,ErrN2,Ninf_RED,Ninf CHARACTER(len=3)::CAS!rank,CAS !INITIALISATION DE UEXA SUIVANT LE CAS SOURCE ALLOCATE(UEXA(it1:itN)) WRITE(CAS,fmt='(1I3)')userchoice OPEN(TAG,file='EXACTE_ERREUR/SOL_EXACTE_CAS'//trim(adjustl(CAS))//'_ME'//trim(adjustl(rank))//'.dat') SELECT CASE(userchoice) CASE(1)!F1 DO i=S1,S2 DO j=1,Ny_g k=j+(i-1)*Ny_g UEXA(k)=X(i)*(1-X(i))*Y(j)*(1-Y(j)) WRITE(TAG,*)X(i),Y(j),UEXA(k) END DO END DO CASE(2)!F2 DO i=S1,S2 DO j=1,Ny_g k=j+(i-1)*Ny_g UEXA(k)=sin(X(i))+cos(Y(j)) WRITE(TAG,*)X(i),Y(j),UEXA(k) END DO END DO CASE DEFAULT!F3 PAS DE SOL EXACTE PRINT*,'PAS DE SOLUTION EXACTE POUR CE CAS (F3)' END SELECT CLOSE(TAG) !SUR LE DOMAINE [|S1;S2|]x[|1;Ny_g|]: !ERREUR NORME_2: ALLOCATE(DIFF(it1:itN)) DIFF=UEXA-U(it1:itN) ErrN2_RED=DOT_PRODUCT(DIFF,DIFF) CALL MPI_ALLREDUCE(ErrN2_RED,ErrN2,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,stateinfo) ErrN2=SQRT(ErrN2) !ERREUR NORME INFINIE Ninf_RED=MAXVAL(ABS(UEXA(it1:itN)-U(it1:itN))) CALL MPI_ALLREDUCE(Ninf_RED,Ninf,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) PRINT*,'PAR DOMAINE: ','ERREUR NORME 2 :=',ErrN2,' ERREUR NORME INFINIE :=',Ninf OPEN(TAG,file='EXACTE_ERREUR/ErrABSOLUE_PAR_DOMAINE'//trim(adjustl(CAS))//'_ME'//trim(adjustl(rank))//'.dat') DO i=S1,S2 DO j=1,Ny_g!GAP(i,1),GAP(i,2) k=j+(i-1)*Ny_g!Ny_g WRITE(TAG,*)X(i),Y(j),-DIFF(k) END DO END DO CLOSE(TAG) !SUR LE DOMAINE [|S1_old;S2_old|]x[|1;Ny_g|]: ErrN2_RED=0.0_PR; ErrN2=0.0_PR; Ninf_RED=0.0_PR; Ninf=0.0_PR !DIFF(it1_old:itN_old)=UEXA(it1_old:itN_old)-U(it1_old:itN_old) ErrN2_RED=DOT_PRODUCT(DIFF(it1_old:itN_old),DIFF(it1_old:itN_old)) CALL MPI_ALLREDUCE(ErrN2_RED,ErrN2,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,stateinfo) ErrN2=SQRT(ErrN2) Ninf_RED=MAXVAL(ABS(UEXA(it1_old:itN_old)-U(it1_old:itN_old))) CALL MPI_ALLREDUCE(Ninf_RED,Ninf,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) PRINT*,'SUR [|S1old;S2old|]: ','ERREUR NORME 2 :=',ErrN2,' ERREUR NORME INFINIE :=',Ninf OPEN(TAG,file='EXACTE_ERREUR/ErrABSOLUE_oldDD'//trim(adjustl(CAS))//'_ME'//trim(adjustl(rank))//'.dat') DO i=S1_old,S2_old DO j=1,Ny_g!GAP(i,1),GAP(i,2) k=j+(i-1)*Ny_g!Ny_g WRITE(TAG,*)X(i),Y(j),-DIFF(k) END DO END DO CLOSE(TAG) DEALLOCATE(DIFF,UEXA) END SUBROUTINE UEXACT SUBROUTINE WR_U(U,IT_TEMPS) INTEGER,INTENT(IN)::IT_TEMPS REAL(PR),DIMENSION(it1_old:itN_old),INTENT(INOUT)::U CHARACTER(len=3)::CAS CHARACTER(len=3)::Ntps INTEGER::i,j WRITE(CAS,fmt='(1I3)')CT;WRITE(Ntps,fmt='(1I3)')IT_TEMPS OPEN(10+rang,file='SOL_NUMERIQUE/U_ME'//trim(adjustl(rank))& //'_T'//trim(adjustl(Ntps))) SELECT CASE(CT) CASE(1) DO i=S1_old,S2_old DO j=1,Ny_g k=j+(i-1)*Ny_g IF(i-1==0)THEN WRITE(10+rang,*)0.0_PR,Y(j),0.0_PR END IF IF(i+1==Nx_g+1)THEN WRITE(10+rang,*)Lx,Y(j),0.0_PR END IF IF(j-1==0)THEN WRITE(10+rang,*)X(i),0.0_PR,0.0_PR END IF IF(j+1==Ny_g+1)THEN WRITE(10+rang,*)X(i),Ly,0.0_PR END IF WRITE(10+rang,*)X(i),Y(j),U(k) END DO END DO CASE(2) DO i=S1_old,S2_old DO j=1,Ny_g k=j+(i-1)*Ny_g IF(i==1)THEN!BC OUEST (H) WRITE(10+rang,*)0.0_PR,Y(j),cos(Y(j)) END IF IF(i==Nx_g)THEN!BC EST (H) WRITE(10+rang,*)Lx,Y(j),cos(Y(j))+sin(Lx) END IF IF(j==1)THEN!BC SUD (G) WRITE(10+rang,*)X(i),0.0_PR,1.0_PR+sin(X(i)) END IF IF(j==Ny_g)THEN!BC NORD (G) WRITE(10+rang,*)X(i),Ly,cos(Ly)+sin(X(i)) END IF WRITE(10+rang,*)X(i),Y(j),U(k) END DO END DO CASE(3) DO i=S1_old,S2_old DO j=1,Ny_g k=j+(i-1)*Ny_g IF(i-1==0)THEN!BC OUEST OU EST (H) WRITE(10+rang,*)0.0_PR,Y(j),1.0_PR END IF IF(i+1==Nx_g+1)THEN!BC OUEST OU EST (H) WRITE(10+rang,*)Lx,Y(j),1.0_PR END IF IF(j-1==0)THEN!BC SUD OU NORD (G) WRITE(10+rang,*)X(i),0.0_PR,0.0_PR END IF IF(j+1==Ny_g+1)THEN!BC SUD OU NORD (G) WRITE(10+rang,*)X(i),Ly,0.0_PR END IF WRITE(10+rang,*)X(i),Y(j),U(k) END DO END DO END SELECT CLOSE(10+rang) END SUBROUTINE WR_U SUBROUTINE VIZU_SOL_NUM(userchoice)!sequentiel call by proc 0 at the end INTEGER,INTENT(INOUT)::userchoice CHARACTER(LEN=12)::VIZU INTEGER::vi1,vi2 VIZU='VIZU_PLT.plt' PRINT*,'*****************************************************************************************' PRINT*,'************** VISUALISATION SOLUTION POUR LE CAS #',userchoice,' ***********************' PRINT*,'*****************************************************************************************' PRINT*,'************* SACHANT QUE DT=',dt,'ET ITMAX=',Nt,':' PRINT*,'*****************************************************************************************' PRINT*,'** ENTREZ LE NUMERO DE L''ITERATION A LAQUELLE VOUS VOULEZ COMMENCER LA VISUALISATION **' READ*,vi1 PRINT*,'*****************************************************************************************' PRINT*,'*****************************************************************************************' PRINT*,'*** ENTREZ LE NUMERO DE L''ITERATION A LAQUELLE VOUS VOULEZ STOPPER LA VISUALISATION ***' READ*,vi2 PRINT*,'*****************************************************************************************' PRINT*,'*****************************************************************************************' OPEN(50,file=VIZU) SELECT CASE(userchoice) CASE(1) WRITE(50,*)'set cbrange[0:0.5]' CASE(2) WRITE(50,*)'set cbrange[0.8:2]' CASE(3) WRITE(50,*)'set cbrange[0:1]' END SELECT WRITE(50,*)'set dgrid3d,',Nx_g+2,',',Ny_g+2; WRITE(50,*)'set hidden3d'; WRITE(50,*)'set pm3d' !WRITE(50,*)'do for [i=',vi1,':',vi2,']{splot ''SOL_NUMERIQUE/U.dat'' index i u 1:2:3 with pm3d at sb}' WRITE(50,*)'splot ''SOL_NUMERIQUE/U.dat''u 1:2:3 with pm3d at sb' CLOSE(50) call system('gnuplot -p VIZU_PLT.plt') END SUBROUTINE VIZU_SOL_NUM SUBROUTINE VIZU_SOL_NUM_ONLY_Nt(userchoice,MINU,MAXU)!sequentiel call by proc 0 at the end INTEGER,INTENT(INOUT) :: userchoice REAL(PR),INTENT(IN) :: MINU, MAXU CHARACTER(LEN=12)::VIZU VIZU='VIZU_PLT.plt' PRINT*,'*****************************************************************************************' PRINT*,'************** VISUALISATION SOLUTION POUR LE CAS #',userchoice,' ***********************' PRINT*,'*****************************************************************************************' PRINT*,'************* SACHANT QUE DT=',dt,'ET ITMAX=',Nt,':' PRINT*,'*****************************************************************************************' PRINT*,'** VISUALISATION AU TEMPS FINAL **' PRINT*, (Nt)*dt,' secondes' PRINT*,'*****************************************************************************************' OPEN(50,file=VIZU) SELECT CASE(userchoice) CASE(1) WRITE(50,*)'set cbrange[',MINU,':',MAXU,']' CASE(2) WRITE(50,*)'set cbrange[',MINU,':',MAXU,']' CASE(3) WRITE(50,*)'set cbrange[',MINU,':',MAXU,']' END SELECT WRITE(50,*)'set dgrid3d,',Nx_g+2,',',Ny_g+2; WRITE(50,*)'set hidden3d'; WRITE(50,*)'set pm3d' WRITE(50,*)'splot ''SOL_NUMERIQUE/U.dat'' u 1:2:3 with pm3d at sb' CLOSE(50) call system('gnuplot -p VIZU_PLT.plt') END SUBROUTINE VIZU_SOL_NUM_ONLY_Nt end module mod_sol
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/MPI_EQ_CHALEUR/ModData.f90
module ModData implicit none !Nx-2 noeuds interieurs suivant x !Ny-2 noeuds interieurs suivant y INTEGER,parameter::RK_DATA=8 !ModDATA CONTIENT LA SUBROUTINE POUR LIRE LE FICHIER DATA REMPLIT PAR L'UTILISATEUR contains subroutine INI_PARA(rang,Lx,Ly,D,Nx,Ny,PARAMETRES_USER,sysmove,userchoice,DT,ITER_TMAX) integer,intent(in)::rang !Lx, Ly longueur suivant x et y !D coeff de diffusion !Nx Ny nombre de noeuds dans la direction x et y !ch nom du fichier à lire pour obtenir les para real(RK_DATA),intent(out)::Lx,Ly,D,DT integer,intent(out)::Nx,Ny,sysmove,userchoice,ITER_TMAX character(len=4),intent(in)::PARAMETRES_USER open(10+rang,file=PARAMETRES_USER) read(10+rang,*) read(10+rang,*)Lx,Ly,D,Nx,Ny!LX,Ly,Nx,Ny:PARAMETRES GEOMETRIQUES ET D: COEFF DIFFUSION read(10+rang,*) read(10+rang,*)sysmove!=1 => VISUALISATION SOLUTION; =0 => PAS DE VISUALISATION, JUSTE ECRITURE SOLUTION read(10+rang,*) read(10+rang,*) read(10+rang,*) read(10+rang,*) read(10+rang,*) read(10+rang,*)userchoice!LE CAS SOURCE:1=F1;2=F2;3=F3 read(10+rang,*) read(10+rang,*)DT,ITER_TMAX!LE PAS DE TEMPS ET L'ITERATION MAX EN TEMPS close(10+rang) end subroutine INI_PARA end module ModData
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/MPI_EQ_CHALEUR/ModF.f90
module ModF use mpi implicit none INTEGER,parameter::RK_F=8 ! ModF CONTIENT: !SUBROUTINES PERMETTANT DE CALCULER LES FONCTIONS SOURCES, !LES FONCTIONS DE BORDS contains SUBROUTINE F1(it1,itN,S1,S2,INTER_Y,GAP,X,Y,F) INTEGER,INTENT(IN)::it1,itN,S1,S2,INTER_Y INTEGER,DIMENSION(S1:S2,1:2),INTENT(IN)::GAP REAL(RK_F),DIMENSION(S1:S2),INTENT(IN)::X REAL(RK_F),DIMENSION(1:INTER_Y),INTENT(IN)::Y REAL(RK_F),DIMENSION(it1:itN),INTENT(OUT)::F INTEGER::i,j,k REAL(RK_F)::FX DO i=S1,S2!CHARGE LOCALE EN X FX=X(i)-X(i)**2!POUR i FIXER, ON PEUT NE CALCULER FX QU'UNE SEULE FOIS DO j=GAP(i,1),GAP(i,2)!CHARGE LOCALE EN Y k=j+(i-1)*INTER_Y!CHARGE GLOBALE F(k)=2*(Y(j)-Y(j)**2)+2*FX!CALCUL FONCTION SOURCE END DO END DO END SUBROUTINE F1 SUBROUTINE F2(it1,itN,S1,S2,INTER_Y,GAP,X,Y,F) INTEGER,INTENT(IN)::it1,itN,S1,S2,INTER_Y INTEGER,DIMENSION(S1:S2,1:2),INTENT(IN)::GAP REAL(RK_F),DIMENSION(S1:S2),INTENT(IN)::X REAL(RK_F),DIMENSION(1:INTER_Y),INTENT(IN)::Y REAL(RK_F),DIMENSION(it1:itN),INTENT(OUT)::F INTEGER::i,j,k REAL(RK_F)::FX DO i=S1,S2 FX=sin(X(i))!POUR i FIXER, ON PEUT NE CALCULER FX QU'UNE SEULE FOIS DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y F(k)=cos(Y(j))+FX END DO END DO END SUBROUTINE F2 SUBROUTINE F3_FIXE(Lx,Ly,it1,itN,S1,S2,INTER_Y,GAP,X,Y,F)!ON NE STOCKE DANS LE VECTEUR F, !QUE LA PARTIE FIXE DE F3 REAL(RK_F),INTENT(IN)::Lx,Ly INTEGER,INTENT(IN)::it1,itN,S1,S2,INTER_Y INTEGER,DIMENSION(S1:S2,1:2),INTENT(IN)::GAP REAL(RK_F),DIMENSION(S1:S2),INTENT(IN)::X REAL(RK_F),DIMENSION(1:INTER_Y),INTENT(IN)::Y REAL(RK_F),DIMENSION(it1:itN),INTENT(OUT)::F INTEGER::i,j,k REAL(RK_F)::FX DO i=S1,S2 FX=exp(-(X(i)-0.50d0*Lx)**2)!POUR i FIXER, ON PEUT NE CALCULER FX QU'UNE SEULE FOIS DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y F(k)=FX*exp(-(Y(j)-0.50d0*Ly)**2) END DO END DO END SUBROUTINE F3_FIXE SUBROUTINE WR_F(rang,it1,itN,INTER_Y,F,S1,S2,GAP,X,Y)! ECRITUE DE F DANS LE REPERTOIRE: F INTEGER,INTENT(IN)::rang,it1,itN,S1,S2,INTER_Y INTEGER,DIMENSION(S1:S2,1:2),INTENT(IN)::GAP REAL(RK_F),DIMENSION(S1:S2),INTENT(IN)::X REAL(RK_F),DIMENSION(1:INTER_Y),INTENT(IN)::Y REAL(RK_F),DIMENSION(it1:itN),INTENT(IN)::F INTEGER::i,j,k CHARACTER(LEN=3)::rank WRITE(rank,fmt='(1I3)')rang OPEN(rang+10,file='F/F_'//trim(adjustl(rank))//'.dat') DO i=S1,S2 DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y WRITE(10+rang,*)X(i),Y(j),F(k) END DO END DO CLOSE(10+rang) END SUBROUTINE WR_F SUBROUTINE BC(AP,AL,userchoice,S1,S2,GAP,it1,itN,INTER_Y,INTER_X& ,X,Y,DX,DY,Lx,Ly,VECT)!ON CALCUL LES CONDITIONS LIMITES(BC) REAL(RK_F),INTENT(IN)::AP,AL!LES COEFF DE LA MATRICE INTEGER,INTENT(IN)::userchoice,S1,S2,it1,itN,INTER_X,INTER_Y INTEGER,DIMENSION(S1:S2,1:2),INTENT(IN)::GAP REAL(RK_F),INTENT(IN)::DX,DY,Lx,Ly REAL(RK_F),DIMENSION(S1:S2),INTENT(IN)::X REAL(RK_F),DIMENSION(1:INTER_Y),INTENT(IN)::Y REAL(RK_F),DIMENSION(it1:itN),INTENT(INOUT)::VECT integer::i,j,k real(RK_F)::G,H SELECT CASE(userchoice) CASE(2)!F2 DO i=S1,S2 DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y IF(i==1)THEN!BC H VECT(k)=VECT(k)+AL*cos(Y(j)) ELSE IF(i==INTER_X)THEN VECT(k)=VECT(k)+AL*(cos(Y(j))+sin(Lx)) END IF IF(j==1)THEN!BC G VECT(k)=VECT(k)+AP*(1.0d0+sin(X(i))) ELSE IF(j==INTER_Y)THEN VECT(k)=VECT(k)+AP*(cos(Ly)+sin(X(i))) END IF END DO END DO CASE(3)!F3 IF(S1==1)THEN!BC i=S1 DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y;VECT(k)=VECT(k)+AL !CAR:G=0 ET H=1 END DO END IF IF(S2==INTER_X)THEN!BC i=S2 DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y;VECT(k)=VECT(k)+AL !CAR:G=0 ET H=1 END DO END IF END SELECT END SUBROUTINE BC end module ModF
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/MPI_EQ_CHALEUR/ModGC.f90
module ModGC use mpi implicit none INTEGER,PARAMETER::RK_GC=8 !ModGC CONTIENT: !SUBROUTINE: GRADIENT CONJUGUE, 2 TYPES DE COMMUNICATION VECTEUR, PRODUIT MATRICE/VECTEUR contains !GRADIENT CONJUGUE: SUBROUTINE GC(A,AP,AL,U,F,F_VAR,userchoice,DT,TOL,KMAX,it1,itN& ,INTER_Y,INTER_X,S1,S2,GAP,Np,rang,stateinfo,status,mode,r,z,p,& Tpmv,Tcomm,Tall,PIVOT,NUM_tps) REAL(RK_GC),INTENT(IN)::A,AP,AL INTEGER,INTENT(IN)::it1,itN,INTER_Y,INTER_X,S1,S2,Np,rang,userchoice,KMAX,mode,PIVOT,NUM_tps INTEGER,INTENT(IN),DIMENSION(S1:S2,1:2)::GAP REAL(RK_GC),INTENT(IN)::DT,TOL,F_VAR REAL(RK_GC),DIMENSION(it1-INTER_Y:itN+INTER_Y),INTENT(INOUT)::U REAL(RK_GC),DIMENSION(it1:itN),INTENT(IN)::F INTEGER,DIMENSION(MPI_STATUS_SIZE),INTENT(inout)::status INTEGER,INTENT(INOUT)::stateinfo REAL(RK_GC)::beta,beta_RED,alpha,beta_old,DOTzp_RED,DOTzp,gamma REAL(RK_GC),DIMENSION(it1:itN),INTENT(INOUT)::r,z REAL(RK_GC),DIMENSION(it1-INTER_Y:itN+INTER_Y),INTENT(INOUT)::p REAL(RK_GC),INTENT(INOUT)::Tpmv,Tcomm,Tall!TEMPS (SUM) produit matrice/vecteur,communication vecteur, MPI_ALLREDUCE REAL(RK_GC)::Tpmv_RED,Tcomm_RED,Tall_RED!VARIABLES DE REDUCTION REAL(RK_GC)::Tp1,Tp2,Tc1,Tc2,Ta1,Ta2!TEMPS !REAL(RK_GC),DIMENSION(:),ALLOCATABLE::r,p,z INTEGER::it_GC !ALLOCATE(r(it1:itN),z(it1:itN),p(it1-INTER_Y:itN+INTER_Y)) !INITIALISATION: it_GC=0 r=0.0d0;z=0.0d0 !INITIALISATION TEMPS: Tp1=0.0d0;Tp2=0.0d0;Ta1=0.0d0;Ta2=0.0d0;Tc1=0.0d0;Tc2=0.0d0 Tpmv_RED=0.0d0;Tcomm_RED=0.0d0;Tall_RED=0.0d0 Tpmv=0.0d0;Tcomm=0.0d0;Tall=0.0d0 !UN PRODUIT MATRICE/VECTEUR NECESSITE UNE COMM DE PARTIE DU VECTEUR ENTRE PROCS: Tc1=MPI_WTIME() IF(Np>1)THEN!DECOMMENTER LE MODE DE COMMUNICATION QUE VOUS VOULEZ, COMMENTER L'AUTRE CALL COMM_VECT(status,stateinfo,rang,Np,U,it1,itN,INTER_Y,INTER_X,mode) !CALL COMM_VECT_PIVOT(status,stateinfo,rang,Np,U,it1,itN,INTER_Y,INTER_X,mode,PIVOT) END IF Tc2=MPI_WTIME() Tp1=MPI_WTIME() CALL PMV(A,AP,AL,INTER_Y,INTER_X,it1,itN,r,U,S1,S2,GAP) Tp2=MPI_WTIME() !ON NE SOUHAITE PAS RECALCULER F3, NI STOCKER b=U+DT*F SELECT CASE(userchoice) CASE(3)!POUR F=F3, DANS CE CAS ON RAJOUTE LA VARIABLE EN TEMPS POUR LA FORCE F_VAR=cos(Pi*t/2) r=-r+U(it1:itN)+DT*F_VAR*F!.EQV. r=b-A.U avec b=U(it1:itN)+DT*F_VAR*F CASE DEFAULT!POUR F=F1 OU F=F2 r=-r+U(it1:itN)+DT*F!.EQV. r=b-A.U avec b=U(it1:itN)+DT*F END SELECT beta_RED=DOT_PRODUCT(r,r)!NORME2 AU CARRE DU RESIDU (PAR MORCEAU) Ta1=MPI_WTIME() CALL MPI_ALLREDUCE(beta_RED,beta,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,stateinfo)!reduction Ta2=MPI_WTIME() p(it1-INTER_Y:it1-1)=0.0d0;p(it1:itN)=r(it1:itN);p(itN+1:itN+INTER_Y)=0.0d0!p la direction de descente du GC !TEMPS Tpmv_RED=Tp2-Tp1;Tcomm_RED=Tc2-Tc1;Tall_RED=Ta2-Ta1; DO WHILE(SQRT(beta)>TOL.AND.(it_GC<KMAX))!BOUCLE DE CONVERGENCE !z=Ap, OBLIGATION DE FAIRE UNE COMM SUR p: Tc1=MPI_WTIME() IF(Np>1)THEN!DECOMMENTER LE MODE DE COMMUNICATION QUE VOUS VOULEZ, COMMENTER L'AUTRE CALL COMM_VECT(status,stateinfo,rang,Np,p,it1,itN,INTER_Y,INTER_X,mode) !CALL COMM_VECT_PIVOT(status,stateinfo,rang,Np,p,it1,itN,INTER_Y,INTER_X,mode,PIVOT) END IF Tc2=MPI_WTIME() Tcomm_RED=Tcomm_RED+Tc2-Tc1 Tp1=MPI_WTIME() CALL PMV(A,AP,AL,INTER_Y,INTER_X,it1,itN,z,p,S1,S2,GAP)!PRODUIT MATRICE VECTEUR Tp2=MPI_WTIME() Tpmv_RED=Tpmv_RED+Tp2-Tp1 !REDUCTION SUR DOT_PRODUCT(z,p): DOTzp_RED=DOT_PRODUCT(z(it1:itN),p(it1:itN)) Ta1=MPI_WTIME() CALL MPI_ALLREDUCE(DOTzp_RED,DOTzp,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,stateinfo) Ta2=MPI_WTIME() Tall_RED=Tall_RED+Ta2-Ta1 !CALCUL DE alpha le pas de descente: alpha=beta/DOTzp !ACTUALISATION DE U ET de r: U(it1:itN)=U(it1:itN)+alpha*p(it1:itN) r=r-alpha*z !SAVE beta dans beta_old: beta_old=beta !ACTUALISATION DE BETA ET REDUCTION: beta_RED=DOT_PRODUCT(r,r) Ta1=MPI_WTIME() CALL MPI_ALLREDUCE(beta_RED,beta,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,stateinfo) Ta2=MPI_WTIME() Tall_RED=Tall_RED+Ta2-Ta1 !CALCUL de gamma: gamma=beta/beta_old !ACTUALISATION DE LA DIRECTION DE DESCENTE p: p(it1:itN)=r(it1:itN)+gamma*p(it1:itN) !ACTUALISATION DE k: it_GC=it_GC+1 END DO !SORTIE DES MAX(SUM TEMPS): CALL MPI_ALLREDUCE(Tcomm_RED,Tcomm,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) CALL MPI_ALLREDUCE(Tall_RED,Tall,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) CALL MPI_ALLREDUCE(Tpmv_RED,Tpmv,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) PRINT*,'it temps',NUM_tps,'it_GC',it_GC,'SQRT(beta)',SQRT(beta),'TOL',TOL,'RANG',rang END SUBROUTINE GC !POUR COMMUNIQUER DES PARTIES D'UN VECTEUR: SUBROUTINE COMM_VECT(status,stateinfo,rang,NBR_P,ES,it1,itN,INTER_Y,INTER_X,mode) INTEGER,DIMENSION(MPI_STATUS_SIZE),INTENT(inout)::status INTEGER,INTENT(INOUT)::stateinfo INTEGER,INTENT(IN)::rang,NBR_P,it1,itN,INTER_Y,INTER_X,mode REAL(RK_GC),DIMENSION(it1-INTER_Y:itN+INTER_Y),INTENT(INOUT)::ES!LE VECTEUR A COMMUNIQUER INTEGER::NP,NPP,T1M,T1MM,REQUEST,A,B NP=itN+1;NPP=itN+INTER_Y;T1M=it1-1;T1MM=it1-INTER_Y A=itN-INTER_Y+1;B=it1+INTER_Y-1 IF(NBR_P<=INTER_X)THEN IF(rang==0)THEN CALL MPI_SEND(ES(A:itN),INTER_Y,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(ES(NP:NPP),INTER_Y,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) !SEND PARTIE NORD DE ES AU RANG+1 ET RECV PARTIE SUD DE ES DU RANG+1 ELSE IF(rang>0.AND.rang<NBR_P-1)THEN CALL MPI_RECV(ES(T1MM:T1M),INTER_Y,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) CALL MPI_SEND(ES(it1:B),INTER_Y,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) !RECV PARTIE NORD DE ES DU RANG-1 ET SEND PARTIE SUD DE ES AU RANG-1 CALL MPI_SEND(ES(A:itN),INTER_Y,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(ES(NP:NPP),INTER_Y,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) !SEND PARTIE NORD DE ES AU RANG+1 ET RECV PARTIE SUD DE ES DU RANG+1 ELSE IF(rang==NBR_P-1)THEN CALL MPI_RECV(ES(T1MM:T1M),INTER_Y,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) CALL MPI_SEND(ES(it1:B),INTER_Y,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) !RECV PARTIE NORD DE ES DU RANG-1 ET SEND PARTIE SUD DE ES AU RANG-1 END IF ELSE CALL COMM_NP_SUP(NBR_P,rang,it1,itN,INTER_Y,ES,stateinfo,status)!SI Np>INTER_X END IF END SUBROUTINE COMM_VECT ! POUR LE MODE 2 DANS LE CAS Np>Nx-2, un processus peut avoir a send et recv ! pour plus de 1 processus de rang sup ou de rang inf: ! SANS TRI obligation de faire comm point à point avec remonté et descente pour transmettre l'information subroutine COMM_NP_SUP(Np,rang,it1,itN,INTER,ENTER,stateinfo,status) integer::k,wr!i,j,k,liste integer,intent(in)::Np,rang,it1,itN,INTER!INTER=INTER_Y integer,intent(inout)::stateinfo integer,dimension(MPI_STATUS_SIZE),intent(inout)::status real(RK_GC),dimension(it1-INTER:itN+INTER),intent(inout)::ENTER INTEGER::A,B,C,D,E,F A=itN-INTER+1;B=it1-INTER;C=it1-1;D=it1+INTER-1;E=itN+1;F=itN+INTER k=0 wr=0 !** BOUCLE COMMUNICATION POINT A POINT: RANG SEND PARTIE NORD DE ES A RANG+1 ET RANG+1 RECV PARTIE NORD DE ES DE RANG do wr=0,Np-1 if(wr==rang)then if(rang<Np-1)then call MPI_SEND(ENTER(A:itN),INTER,MPI_DOUBLE_PRECISION,rang+1,21,MPI_COMM_WORLD,stateinfo) !call MPI_SEND(ENTER(itN-INTER+1:itN),INTER,MPI_DOUBLE_PRECISION,rang+1,21,MPI_COMM_WORLD,stateinfo) end if else if(rang==wr+1)then call MPI_RECV(ENTER(B:C),INTER,MPI_DOUBLE_PRECISION,rang-1,21,MPI_COMM_WORLD,status,stateinfo) !call MPI_RECV(ENTER(it1-INTER:it1-1),INTER,MPI_DOUBLE_PRECISION,rang-1,21,MPI_COMM_WORLD,status,stateinfo) end if end do !** BOUCLE COMMUNICATION POINT A POINT: SENS INVERSE do wr=Np-1,0,-1 if(wr==rang)then if(rang>0)then call MPI_SEND(ENTER(it1:D),INTER,MPI_DOUBLE_PRECISION,rang-1,31,MPI_COMM_WORLD,stateinfo) !call MPI_SEND(ENTER(it1:it1+INTER-1),INTER,MPI_DOUBLE_PRECISION,rang-1,31,MPI_COMM_WORLD,stateinfo) end if else if(rang==wr-1)then call MPI_RECV(ENTER(E:F),INTER,MPI_DOUBLE_PRECISION,rang+1,31,MPI_COMM_WORLD,status,stateinfo) !call MPI_RECV(ENTER(itN+1:itN+INTER),INTER,MPI_DOUBLE_PRECISION,rang+1,31,MPI_COMM_WORLD,status,stateinfo) end if end do end subroutine COMM_NP_SUP !PRODUIT MATRICE VECTEUR PAR MORCEAU, ON NE STOCKE QUE LES TROIS COEFFICIANTS NON NULS DE LA MATRICE !A,AP,AL, ETANT DONNE QUE LA MATRICE EST PENTADIAGONALE SDP, A COEFFICIANTS CONSTANTS PAR DIAGONALE SUBROUTINE PMV(A,AP,AL,INTER_Y,INTER_X,it1,itN,E,V,S1,S2,GAP) REAL(RK_GC),INTENT(IN)::A,AP,AL!COEF MATRICE INTEGER,INTENT(IN)::INTER_Y,INTER_X,it1,itN,S1,S2 INTEGER,INTENT(IN),DIMENSION(S1:S2,1:2)::GAP real(RK_GC),dimension(it1:itN),intent(out)::E !E=A.V real(RK_GC),dimension(it1-INTER_Y:itN+INTER_Y),intent(out)::V INTEGER::i,j,k !BC=CONDITIONS LIMITES DO i=S1,S2 IF(i==1)THEN!BC DO j=GAP(1,1),GAP(1,2) IF(j==1)THEN!BC E(1)=A*V(1)-AP*V(2)-AL*V(1+INTER_Y) ELSE IF(j<INTER_Y)THEN!BC E(j)=-AP*V(j-1)+A*V(j)-AP*V(j+1)-AL*V(j+INTER_Y) ELSE!BC E(j)=-AP*V(INTER_Y-1)+A*V(INTER_Y)-AL*V(2*INTER_Y) END IF END DO ELSE IF(i>1.AND.i<INTER_X)THEN DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y IF(j==1)THEN!BC E(k)=-AL*V(k-INTER_Y)+A*V(k)-AP*V(k+1)-AL*V(k+INTER_Y) ELSE IF(j<INTER_Y)THEN!PAS DE BC E(k)=-AL*V(k-INTER_Y)-AP*V(k-1)+A*V(k)-AP*V(k+1)-AL*V(k+INTER_Y) ELSE!BC E(k)=-AL*V(k-INTER_Y)-AP*V(k-1)+A*V(k)-AL*V(k+INTER_Y) END IF END DO ELSE!BC DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y IF(j==1)THEN!BC E(k)=-AL*V(k-INTER_Y)+A*V(k)-AP*V(k+1) ELSE IF(j<INTER_Y)THEN!BC E(k)=-AL*V(k-INTER_Y)-AP*V(k-1)+A*V(k)-AP*V(k+1) ELSE!BC E(k)=-AL*V(k-INTER_Y)-AP*V(k-1)+A*V(k) END IF END DO END IF END DO END SUBROUTINE PMV ! ********************************************************************************************************************************* ! ********************************************************************************************************************************* ! ********************************************************************************************************************************* ! ********************************************************************************************************************************* ! ********************************************************************************************************************************* !COMMUNICATION VERSION 2: 2_PtoP: POINT A POINT RANG INF AU PIVOT ET POINT A POINT RANG SUP AU PIVOT: !BUG POUR NX=1002=NY, Err N2 ET Ninfinity SONT BONNES POUR DES TAILLES PLUS PETITES SUBROUTINE COMM_VECT_PIVOT(status,stateinfo,rang,NBR_P,ES,it1,itN,INTER_Y,INTER_X,mode,PIVOT) INTEGER,DIMENSION(MPI_STATUS_SIZE),INTENT(inout)::status INTEGER,INTENT(INOUT)::stateinfo INTEGER,INTENT(IN)::rang,NBR_P,it1,itN,INTER_Y,INTER_X,mode,PIVOT REAL(RK_GC),DIMENSION(it1-INTER_Y:itN+INTER_Y),INTENT(INOUT)::ES!LE VECTEUR A COMMUNIQUER INTEGER::NP,NPP,T1M,T1MM,REQUEST,A,B NP=itN+1;NPP=itN+INTER_Y;T1M=it1-1;T1MM=it1-INTER_Y A=itN-INTER_Y+1;B=it1+INTER_Y-1 IF(NBR_P<=INTER_X)THEN IF(rang==0)THEN CALL MPI_SEND(ES(A:itN),INTER_Y,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(ES(NP:NPP),INTER_Y,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) !SEND PARTIE NORD DE ES AU RANG+1 ET RECV PARTIE SUD DE ES DU RANG+1 ELSE IF(rang>0.AND.rang<PIVOT)THEN CALL MPI_RECV(ES(T1MM:T1M),INTER_Y,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) CALL MPI_SEND(ES(it1:B),INTER_Y,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) !RECV PARTIE NORD DE ES DU RANG-1 ET SEND PARTIE SUD DE ES AU RANG-1 CALL MPI_SEND(ES(A:itN),INTER_Y,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(ES(NP:NPP),INTER_Y,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) !SEND PARTIE NORD DE ES AU RANG+1 ET RECV PARTIE SUD DE ES DU RANG+1 ELSE IF(rang>=PIVOT.AND.rang<NBR_P-1)THEN CALL MPI_RECV(ES(NP:NPP),INTER_Y,MPI_DOUBLE_PRECISION,rang+1,rang,MPI_COMM_WORLD,status,stateinfo) CALL MPI_SEND(ES(A:itN),INTER_Y,MPI_DOUBLE_PRECISION,rang+1,rang+1,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(ES(it1:B),INTER_Y,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(ES(T1MM:T1M),INTER_Y,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) !RECV PARTIE NORD DE ES DU RANG-1 ET SEND PARTIE SUD DE ES AU RANG-1 ELSE!RANG=NBR_P-1 CALL MPI_SEND(ES(it1:B),INTER_Y,MPI_DOUBLE_PRECISION,rang-1,rang-1,MPI_COMM_WORLD,stateinfo) CALL MPI_RECV(ES(T1MM:T1M),INTER_Y,MPI_DOUBLE_PRECISION,rang-1,rang,MPI_COMM_WORLD,status,stateinfo) END IF ELSE CALL COMM_NP_SUP_PIVOT(NBR_P,rang,it1,itN,INTER_Y,ES,stateinfo,status,PIVOT)!SI Np>INTER_X END IF END SUBROUTINE COMM_VECT_PIVOT !*********** UNIQUEMENT SI Np>INTER_X: *********************************************** subroutine COMM_NP_SUP_PIVOT(Np,rang,it1,itN,INTER,ENTER,stateinfo,status,PIVOT) integer::k,wr!i,j,k,liste integer,intent(in)::Np,rang,it1,itN,INTER,PIVOT!INTER=INTER_Y integer,intent(inout)::stateinfo integer,dimension(MPI_STATUS_SIZE),intent(inout)::status real(RK_GC),dimension(it1-INTER:itN+INTER),intent(inout)::ENTER INTEGER::A,B,C,D,E,F A=itN-INTER+1;B=it1-INTER;C=it1-1;D=it1+INTER-1;E=itN+1;F=itN+INTER k=0 wr=0 IF(rang<PIVOT)THEN !** BOUCLE COMMUNICATION POINT A POINT: RANG SEND PARTIE NORD DE ES A RANG+1 ET RANG+1 RECV PARTIE NORD DE ES DE RANG do wr=0,PIVOT-2 if(wr==rang)then if(rang<Np-1)then call MPI_SEND(ENTER(A:itN),INTER,MPI_DOUBLE_PRECISION,rang+1,21,MPI_COMM_WORLD,stateinfo) !call MPI_SEND(ENTER(itN-INTER+1:itN),INTER,MPI_DOUBLE_PRECISION,rang+1,21,MPI_COMM_WORLD,stateinfo) end if else if(rang==wr+1)then call MPI_RECV(ENTER(B:C),INTER,MPI_DOUBLE_PRECISION,rang-1,21,MPI_COMM_WORLD,status,stateinfo) !call MPI_RECV(ENTER(it1-INTER:it1-1),INTER,MPI_DOUBLE_PRECISION,rang-1,21,MPI_COMM_WORLD,status,stateinfo) end if end do ELSE !** BOUCLE COMMUNICATION POINT A POINT: SENS INVERSE do wr=Np-1,PIVOT+1,-1 if(wr==rang)then if(rang>0)then call MPI_SEND(ENTER(it1:D),INTER,MPI_DOUBLE_PRECISION,rang-1,31,MPI_COMM_WORLD,stateinfo) !call MPI_SEND(ENTER(it1:it1+INTER-1),INTER,MPI_DOUBLE_PRECISION,rang-1,31,MPI_COMM_WORLD,stateinfo) end if else if(rang==wr-1)then call MPI_RECV(ENTER(E:F),INTER,MPI_DOUBLE_PRECISION,rang+1,31,MPI_COMM_WORLD,status,stateinfo) !call MPI_RECV(ENTER(itN+1:itN+INTER),INTER,MPI_DOUBLE_PRECISION,rang+1,31,MPI_COMM_WORLD,status,stateinfo) end if end do END IF PRINT*,'ECHO1',RANG !COMMUNICATION(ECHANGE) ENTRE PIVOT ET PIVOT-1: IF(rang==PIVOT)THEN CALL MPI_SEND(ENTER(it1:D),INTER,MPI_DOUBLE_PRECISION,rang-1,31,MPI_COMM_WORLD,stateinfo) call MPI_RECV(ENTER(B:C),INTER,MPI_DOUBLE_PRECISION,rang-1,21,MPI_COMM_WORLD,status,stateinfo) ELSE IF(rang==PIVOT-1)THEN CALL MPI_RECV(ENTER(E:F),INTER,MPI_DOUBLE_PRECISION,rang+1,31,MPI_COMM_WORLD,status,stateinfo) call MPI_SEND(ENTER(A:itN),INTER,MPI_DOUBLE_PRECISION,rang+1,21,MPI_COMM_WORLD,stateinfo) END IF PRINT*,'ECHO2',RANG CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) PRINT*,'ECHO3',RANG !INVERSION: IF(rang>=PIVOT)THEN !** BOUCLE COMMUNICATION POINT A POINT: RANG SEND PARTIE NORD DE ES A RANG+1 ET RANG+1 RECV PARTIE NORD DE ES DE RANG do wr=PIVOT,Np-2 if(wr==rang)then if(rang<Np-1)then call MPI_SEND(ENTER(A:itN),INTER,MPI_DOUBLE_PRECISION,rang+1,21,MPI_COMM_WORLD,stateinfo) !call MPI_SEND(ENTER(itN-INTER+1:itN),INTER,MPI_DOUBLE_PRECISION,rang+1,21,MPI_COMM_WORLD,stateinfo) end if else if(rang==wr+1)then call MPI_RECV(ENTER(B:C),INTER,MPI_DOUBLE_PRECISION,rang-1,21,MPI_COMM_WORLD,status,stateinfo) !call MPI_RECV(ENTER(it1-INTER:it1-1),INTER,MPI_DOUBLE_PRECISION,rang-1,21,MPI_COMM_WORLD,status,stateinfo) end if end do ELSE !** BOUCLE COMMUNICATION POINT A POINT: SENS INVERSE do wr=PIVOT-1,1,-1 if(wr==rang)then if(rang>0)then call MPI_SEND(ENTER(it1:D),INTER,MPI_DOUBLE_PRECISION,rang-1,31,MPI_COMM_WORLD,stateinfo) !call MPI_SEND(ENTER(it1:it1+INTER-1),INTER,MPI_DOUBLE_PRECISION,rang-1,31,MPI_COMM_WORLD,stateinfo) end if else if(rang==wr-1)then call MPI_RECV(ENTER(E:F),INTER,MPI_DOUBLE_PRECISION,rang+1,31,MPI_COMM_WORLD,status,stateinfo) !call MPI_RECV(ENTER(itN+1:itN+INTER),INTER,MPI_DOUBLE_PRECISION,rang+1,31,MPI_COMM_WORLD,status,stateinfo) end if end do END IF end subroutine COMM_NP_SUP_PIVOT ! ********************************************************************************************************************************* ! ********************************************************************************************************************************* ! ********************************************************************************************************************************* ! ********************************************************************************************************************************* !PGC NON UTILISE ICI: SUBROUTINE PGC(A,AP,AL,U,F,F_VAR,userchoice,DT,TOL,KMAX,it1,itN& ,INTER_Y,INTER_X,S1,S2,GAP,Np,rang,stateinfo,status,mode,r,z,p) REAL(RK_GC),INTENT(IN)::A,AP,AL INTEGER,INTENT(IN)::it1,itN,INTER_Y,INTER_X,S1,S2,Np,rang,userchoice,KMAX,mode INTEGER,INTENT(IN),DIMENSION(S1:S2,1:2)::GAP REAL(RK_GC),INTENT(IN)::DT,TOL,F_VAR REAL(RK_GC),DIMENSION(it1-INTER_Y:itN+INTER_Y),INTENT(INOUT)::U REAL(RK_GC),DIMENSION(it1:itN),INTENT(IN)::F INTEGER,DIMENSION(MPI_STATUS_SIZE),INTENT(inout)::status INTEGER,INTENT(INOUT)::stateinfo REAL(RK_GC)::beta,beta_RED,alpha,beta_old,DOTzp_RED,DOTzp,gamma REAL(RK_GC),DIMENSION(it1:itN),INTENT(INOUT)::r,z REAL(RK_GC),DIMENSION(it1-INTER_Y:itN+INTER_Y),INTENT(INOUT)::p REAL(RK_GC),DIMENSION(it1:itN)::mp INTEGER::k !ALLOCATE(r(it1:itN),z(it1:itN),p(it1-INTER_Y:itN+INTER_Y)) !INITIALISATION: k=0 r=0.0d0;z=0.0d0 !UN PRODUIT MATRICE/VECTEUR NECESSITE UNE COMM DE PARTIE DU VECTEUR ENTRE PROCS: IF(Np>1)THEN CALL COMM_VECT(status,stateinfo,rang,Np,U,it1,itN,INTER_Y,INTER_X,mode) END IF CALL PMV(A,AP,AL,INTER_Y,INTER_X,it1,itN,r,U,S1,S2,GAP) !ON NE SOUHAITE PAS RECALCULER F3, NI STOCKER b=U+DT*F SELECT CASE(userchoice) CASE(3)!POUR F=F3, DANS CE CAS ON RAJOUTE LA VARIABLE EN TEMPS POUR LA FORCE F_VAR=cos(Pi*t/2) r=-r+U(it1:itN)+DT*F_VAR*F!.EQV. r=b-A.U avec b=U(it1:itN)+DT*F_VAR*F CASE DEFAULT!POUR F=F1 OU F=F2 r=-r+U(it1:itN)+DT*F!.EQV. r=b-A.U avec b=U(it1:itN)+DT*F END SELECT mp=r/A!LE PRECONDITIONNEUR DIAGONALE beta_RED=DOT_PRODUCT(r,mp)!NORME2 AU CARRE DU RESIDU (PAR MORCEAU) CALL MPI_ALLREDUCE(beta_RED,beta,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,stateinfo)!reduction p(it1-INTER_Y:it1-1)=0.0d0;p(it1:itN)=mp(it1:itN);p(itN+1:itN+INTER_Y)=0.0d0!p la direction de descente du GC DO WHILE(SQRT(beta)>TOL.AND.(k<KMAX))!BOUCLE DE CONVERGENCE !z=Ap, OBLIGATION DE FAIRE UNE COMM SUR p: IF(Np>1)THEN CALL COMM_VECT(status,stateinfo,rang,Np,p,it1,itN,INTER_Y,INTER_X,mode) END IF CALL PMV(A,AP,AL,INTER_Y,INTER_X,it1,itN,z,p,S1,S2,GAP)!PRODUIT MATRICE VECTEUR !REDUCTION SUR DOT_PRODUCT(z,p): DOTzp_RED=DOT_PRODUCT(z(it1:itN),p(it1:itN)) CALL MPI_ALLREDUCE(DOTzp_RED,DOTzp,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,stateinfo) !CALCUL DE alpha le pas de descente: alpha=beta/DOTzp !ACTUALISATION DE U ET de r: U(it1:itN)=U(it1:itN)+alpha*p(it1:itN) r=r-alpha*z !SAVE beta dans beta_old: beta_old=beta !ACTUALISATION DE mp: mp=r/A !ACTUALISATION DE BETA ET REDUCTION: beta_RED=DOT_PRODUCT(r,mp) CALL MPI_ALLREDUCE(beta_RED,beta,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,stateinfo) !CALCUL de gamma: gamma=beta/beta_old !ACTUALISATION DE LA DIRECTION DE DESCENTE p: p(it1:itN)=mp(it1:itN)+gamma*p(it1:itN) !ACTUALISATION DE k: k=k+1 END DO PRINT*,'k',k,'SQRT(beta)',SQRT(beta),'TOL',TOL,'RANG',rang END SUBROUTINE PGC end module ModGC
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/MPI_EQ_CHALEUR/ModSOL.f90
module ModSOL use mpi IMPLICIT NONE INTEGER,PARAMETER::RK_SOL=8 !*** MODULE ModSOL POUR DONNER LA SOLUTION EXACTE ET !*** POUR GERER L'ENREGISTREMENT DE LA SOLUTION DANS DES FICHIERS !*** SUBROUTINE POUR APPELLER UN SCRIPT GNUPLOT POUR LA VISUALISATION CONTAINS SUBROUTINE UEXACT(U,userchoice,it1,itN,INTER_Y,INTER_X,X,Y,S1,S2,GAP,stateinfo,rang) INTEGER,INTENT(IN)::userchoice,it1,itN,INTER_Y,INTER_X,S1,S2,rang INTEGER,DIMENSION(S1:S2,1:2),INTENT(IN)::GAP INTEGER,INTENT(INOUT)::stateinfo REAL(RK_SOL),DIMENSION(it1-INTER_Y:itN+INTER_Y),INTENT(IN)::U REAL(RK_SOL),DIMENSION(S1:S2),INTENT(IN)::X REAL(RK_SOL),DIMENSION(1:INTER_Y),INTENT(IN)::Y REAL(RK_SOL),DIMENSION(:),ALLOCATABLE::UEXA,DIFF integer::i,j,k REAL(RK_SOL)::ErrN2_RED,ErrN2,Ninf_RED,Ninf CHARACTER(len=3)::rank,CAS !INITIALISATION DE UEXA SUIVANT LE CAS SOURCE ALLOCATE(UEXA(it1:itN)) WRITE(rank,fmt='(1I3)')rang;WRITE(CAS,fmt='(1I3)')userchoice OPEN(10+rang,file='EXACTE_ERREUR/SOL_EXACTE_'//trim(adjustl(CAS))//'_ME'//trim(adjustl(rank))//'.dat') SELECT CASE(userchoice) CASE(1)!F1 DO i=S1,S2 DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y UEXA(k)=X(i)*(1-X(i))*Y(j)*(1-Y(j)) WRITE(10+rang,*)X(i),Y(j),UEXA(k) END DO END DO CASE(2)!F2 DO i=S1,S2 DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y UEXA(k)=sin(X(i))+cos(Y(j)) WRITE(10+rang,*)X(i),Y(j),UEXA(k) END DO END DO CASE DEFAULT!F3 PAS DE SOL EXACTE PRINT*,'PAS DE SOLUTION EXACTE POUR CE CAS (F3)' END SELECT CLOSE(10+rang) !ERREUR NORME_2: ALLOCATE(DIFF(it1:itN)) DIFF=UEXA-U(it1:itN) ErrN2_RED=DOT_PRODUCT(DIFF,DIFF) CALL MPI_ALLREDUCE(ErrN2_RED,ErrN2,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,stateinfo) ErrN2=SQRT(ErrN2) !ERREUR NORME INFINIE Ninf_RED=MAXVAL(ABS(UEXA(it1:itN)-U(it1:itN))) CALL MPI_ALLREDUCE(Ninf_RED,Ninf,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) PRINT*,'ERREUR NORME 2:=',ErrN2,' ERREUR NORME INFINIE:=',Ninf OPEN(20+rang,file='EXACTE_ERREUR/ErrABSOLUE'//trim(adjustl(CAS))//'_ME'//trim(adjustl(rank))//'.dat') DO i=S1,S2 DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y WRITE(20+rang,*)X(i),Y(j),-DIFF(k) END DO END DO CLOSE(20+rang) DEALLOCATE(DIFF,UEXA) END SUBROUTINE UEXACT SUBROUTINE WR_U(U,it1,itN,INTER_X,INTER_Y,S1,S2,GAP,userchoice,rang,& IT_TEMPS,IT_MAX,Lx,Ly,X,Y) INTEGER,INTENT(IN)::userchoice,it1,itN,INTER_Y,INTER_X,S1,S2,rang,IT_TEMPS,IT_MAX INTEGER,DIMENSION(S1:S2,1:2),INTENT(IN)::GAP REAL(RK_SOL),INTENT(IN)::Lx,Ly REAL(RK_SOL),DIMENSION(it1-INTER_Y:itN+INTER_Y),INTENT(IN)::U REAL(RK_SOL),DIMENSION(S1:S2),INTENT(IN)::X REAL(RK_SOL),DIMENSION(1:INTER_Y),INTENT(IN)::Y integer::i,j,k CHARACTER(len=3)::rank,CAS CHARACTER(len=3)::Ntps WRITE(rank,fmt='(1I3)')rang;WRITE(CAS,fmt='(1I3)')userchoice;WRITE(Ntps,fmt='(1I3)')IT_TEMPS OPEN(10+rang,file='SOL_NUMERIQUE/U_ME'//trim(adjustl(rank))& //'_T'//trim(adjustl(Ntps))) SELECT CASE(userchoice) CASE(1) DO i=S1,S2 DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y IF(i-1==0)THEN WRITE(10+rang,*)0.0d0,Y(j),0.0d0 END IF IF(i+1==INTER_X+1)THEN WRITE(10+rang,*)Lx,Y(j),0.0d0 END IF IF(j-1==0)THEN WRITE(10+rang,*)X(i),0.0d0,0.0d0 END IF IF(j+1==INTER_Y+1)THEN WRITE(10+rang,*)X(i),Ly,0.0d0 END IF WRITE(10+rang,*)X(i),Y(j),U(k) END DO END DO CASE(2) DO i=S1,S2 DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y IF(i==1)THEN!BC OUEST (H) WRITE(10+rang,*)0.0d0,Y(j),cos(Y(j)) END IF IF(i==INTER_X)THEN!BC EST (H) WRITE(10+rang,*)Lx,Y(j),cos(Y(j))+sin(Lx) END IF IF(j==1)THEN!BC SUD (G) WRITE(10+rang,*)X(i),0.0d0,1.0d0+sin(X(i)) END IF IF(j==INTER_Y)THEN!BC NORD (G) WRITE(10+rang,*)X(i),Ly,cos(Ly)+sin(X(i)) END IF WRITE(10+rang,*)X(i),Y(j),U(k) END DO END DO CASE(3) DO i=S1,S2 DO j=GAP(i,1),GAP(i,2) k=j+(i-1)*INTER_Y IF(i-1==0)THEN!BC OUEST OU EST (H) WRITE(10+rang,*)0.0d0,Y(j),1.0d0 END IF IF(i+1==INTER_X+1)THEN!BC OUEST OU EST (H) WRITE(10+rang,*)Lx,Y(j),1.0d0 END IF IF(j-1==0.OR.j+1==INTER_Y+1)THEN!BC SUD OU NORD (G) WRITE(10+rang,*)X(i),Y(j),0.0d0 END IF IF(j+1==INTER_Y+1)THEN!BC SUD OU NORD (G) WRITE(10+rang,*)X(i),Ly,0.0d0 END IF WRITE(10+rang,*)X(i),Y(j),U(k) END DO END DO END SELECT CLOSE(10+rang) END SUBROUTINE WR_U SUBROUTINE VIZU_SOL_NUM(userchoice,DT,ITMAX,Nx,Ny) INTEGER,INTENT(INOUT)::userchoice,ITMAX,Nx,Ny REAL(RK_SOL),INTENT(IN)::DT CHARACTER(LEN=12)::VIZU INTEGER::i1,i2,i VIZU='VIZU_PLT.plt' PRINT*,'*****************************************************************************************' PRINT*,'************** VISUALISATION SOLUTION POUR LE CAS #',userchoice,' ***********************' PRINT*,'*****************************************************************************************' PRINT*,'************* SACHANT QUE DT=',DT,'ET ITMAX=',ITMAX,':' PRINT*,'*****************************************************************************************' PRINT*,'** ENTREZ LE NUMERO DE L''ITERATION A LAQUELLE VOUS VOULEZ COMMENCER LA VISUALISATION **' READ*,i1 PRINT*,'*****************************************************************************************' PRINT*,'*****************************************************************************************' PRINT*,'*** ENTREZ LE NUMERO DE L''ITERATION A LAQUELLE VOUS VOULEZ STOPPER LA VISUALISATION ***' READ*,i2 PRINT*,'*****************************************************************************************' PRINT*,'*****************************************************************************************' OPEN(10,file=VIZU) SELECT CASE(userchoice) CASE(1) WRITE(10,*)'set cbrange[0:1]' CASE(2) WRITE(10,*)'set cbrange[0.8:2]' CASE(3) WRITE(10,*)'set cbrange[0:1]' END SELECT WRITE(10,*)'set dgrid3d,',Nx,',',Ny; WRITE(10,*)'set hidden3d'; WRITE(10,*)'set pm3d' WRITE(10,*)'do for [i=',i1,':',i2,']{splot ''SOL_NUMERIQUE/U.dat'' index i u 1:2:3 with pm3d at sb}' CLOSE(10) call system('gnuplot -p VIZU_PLT.plt') END SUBROUTINE VIZU_SOL_NUM end module ModSOL
0
ALLM/ADDITIVE_SCHWARZ_METHOD
ALLM/ADDITIVE_SCHWARZ_METHOD/MPI_EQ_CHALEUR/main.f90
program main use mpi use ModData use ModF use ModGC use ModSOL implicit none !******************************************************************************** !MAIN CONTIENT: !L'INITIALISATION DES PARAMETRES DU PROBLEME ET VECTEURS !LA BOUCLE ITERATIVE EN TEMPS POUR RESOUDRE A.U=b ET L'ECRITURE DE LA SOLUTION !LE CODAGE DE LA SOLUTION EXACTE !LA CONCATENATION DES FICHIERS SOLUTIONS (RANG ET TEMPS DEPENDANT) !SUBROUTINES: POUR LE CODAGE EN ESPAGE, LA CHARGE LOCALE ET GLOBALE !******************************************************************************* INTEGER,parameter::RK_MAIN=8 !PARAMETRES DATA.F90: INTEGER::userchoice,sysmove!choix du cas, choix visualisation sol REAL(RK_MAIN)::Lx,Ly,D !LONG,LARG,COEF_DIFFUSION INTEGER::Nx,Ny !NBR PTS EN X, EN Y INTEGER::ITMAX!NBR ITERATION EN TEMPS REAL(RK_MAIN)::DT!LE PAS DE TEMPS !PAS D'ESPACE: REAL(RK_MAIN)::DX,DY !POUR LA CHARGE: INTEGER::DIM!DIMENSION DE LA MATRICE:=NBR PTS DE CALCUL:=NBR PTS INT:= CHARGE A REPARTIR ENTRE PROCS INTEGER::it1,itN !CHARGE NUMEROTATION GLO INTEGER::S1,S2,INTER_X !LOCALE EN X, NBR_PTS INT EN X INTEGER::INTER_Y !LOCALE FIXE(MODE1) EN Y:=NBR_PTS INT EN Y INTEGER,DIMENSION(:,:),ALLOCATABLE::GAP !LOCALE MOBILE (MODE2) EN Y !STOCKAGE D'ESPACE(UNIQUEMENT PTS INT) REAL(RK_MAIN),DIMENSION(:),ALLOCATABLE::X,Y !CONDI DE BORDS SI CST:(CAS 1 et CAS 3) REAL(RK_MAIN)::G,H !G->SUD ET NORD(y=0 et y=Ly) H->OUEST ET EST(x=0 et x=lx) !SI NON CST (CAS 2): pas de stockage mais calcul. ! VARIABLES TEMPS: REAL(RK_MAIN)::t !le temps t=k*DT INTEGER::k !l'ITERANT SUR LA BOUCLE EN TEMPS !COEF DE LA MATRICE: REAL(RK_MAIN)::A,AP,AL !A|AP|0|0|AL 1er ligne Nx=NY=6 !BORNE EN X ET EN Y: INTEGER::IXMAX,IYMAX! on a Nx pts en X on va de 0 à Nx-1 !NOM FICHIER RANG: CHARACTER(LEN=3)::rank CHARACTER(LEN=4),parameter::PARAMETRES_USER='DATA' CHARACTER(LEN=20)::NFILE,NT,OUT_FILE CHARACTER(LEN=1)::ESPACE !POUR ENVI PARA: INTEGER::rang,Np,stateinfo INTEGER,DIMENSION(MPI_STATUS_SIZE)::status !MODE DE REPARTION: INTEGER,PARAMETER::MODE=2 !VECTEURS U,F,b. A.U=b=UO+DT.F+CONDITIONS DE BORDS REAL(RK_MAIN),DIMENSION(:),ALLOCATABLE::U,F!,b REAL(RK_MAIN)::F_VAR !TEMPS CPU: REAL(RK_MAIN)::TPS1,TPS2,MAX_TPS !TOLERANCE DU GC: REAL(RK_MAIN),PARAMETER::TOL=0.0000000000000001d0!0.000000000001d0 !ITERATION DU GC: INTEGER::KMAX !VECTEUR DU GC:r=RESIDU,z=AP,p=DIRECTION DE DESCENTE REAL(RK_MAIN),DIMENSION(:),ALLOCATABLE::r,z,p !PI: REAL(RK_MAIN),PARAMETER::PI=3.141592653589793 !TEMPS DES COMMUNICATION, PRODUIT MATRICE/VECTEUR, MPI_ALLREDUCE: REAL(RK_GC)::Tpmv,Tcomm,Tall,MAX_pmv,MAX_comm,MAX_all,WR1,WR2,WR,MAX_WR !PIVOT DE COMMUNICATION: INTEGER::PIVOT !**** INTEGER::i,j !********* DEBUT REGION PARA: CALL MPI_INIT(stateinfo) !INITIALISATION DU //LISME CALL MPI_COMM_RANK(MPI_COMM_WORLD,rang,stateinfo) !ON RECUPERE LES RANGS AU SEIN DE L'ENSEMBLE MPI_COMM_WORLD CALL MPI_COMM_SIZE(MPI_COMM_WORLD,Np,stateinfo) !ET LE NOMBRE DU PROCESSUS !INIT TEMPS CPU: TPS1=MPI_WTIME() !LECTURE DE DATA: CALL INI_PARA(rang,Lx,Ly,D,Nx,Ny,PARAMETRES_USER,sysmove,userchoice,DT,ITMAX) !INITIALISATION DES VARIABLES: INTER_Y=Ny-2;INTER_X=Nx-2;IYMAX=Ny-1;IXMAX=Nx-1 DY=Ly/IYMAX;DX=Lx/IXMAX !INITIALISATION DIMENSION MATRICE ET COEF MATRICE: DIM=INTER_X*INTER_Y AP=D*DT/(DY**2);AL=D*DT/(DX**2);A=1+2*AP+2*AL !ON FIXE KMAX LE NOMBRE D'ITERATION DU GC: KMAX=2*DIM !ON SAIT QUE LE GC CONVERGE EN DIM ITERATION, ON MET 2*DIM. IF(MODE==1)THEN !INITIALISATION REPARTITION SUIVANT LE MODE 1: CALL MODE1(rang,Np,INTER_X,INTER_Y,S1,S2,it1,itN,DX,DY,X,Y) !INFO: DANS LE REPERTOIRE M1, ON ENREGISTRE LA CHARGE PAR PROCS WRITE(rank,fmt='(1I3)')rang OPEN(rang+10,file='M1/MAP_'//trim(adjustl(rank))//'.dat') DO i=S1,S2 DO j=1,INTER_Y WRITE(10+rang,*)X(i),Y(j),rang END DO END DO CLOSE(rang+10) ALLOCATE(GAP(S1:S2,1:2));GAP(:,1)=1;GAP(:,2)=INTER_Y ELSE IF(MODE==2)THEN !INITIALISATION REPARTITION SUIVANT LE MODE 2: CALL MODE2(rang,Np,DIM,IXMAX,INTER_X,INTER_Y,S1,S2,GAP,it1,itN,DX,DY,X,Y) !INFO: DANS LE REPERTOIRE: M1, ON ENREGISTRE LA CHARGE PAR PROCS WRITE(rank,fmt='(1I3)')rang OPEN(rang+10,file='M1/MAP_'//trim(adjustl(rank))//'.dat') DO i=S1,S2 DO j=GAP(i,1),GAP(i,2) WRITE(10+rang,*)X(i),Y(j),rang END DO END DO CLOSE(rang+10) END IF !INITIALISATION U,b,F,BC: ALLOCATE(U(it1-INTER_Y:itN+INTER_Y),F(it1:itN)) !INITIALISATION DES TEMPS MAX: MAX_TPS=0.0d0 MAX_pmv=0.0d0;MAX_comm=0.0d0;MAX_all=0.0d0 WR1=0.0d0;WR2=0.0d0;WR=0.0d0;MAX_WR=0.0d0 !PIVOT DE COMMUNICATION: PIVOT=(Np-mod(Np,2))/2 !SELON LE CHOIX DE L'UTILISATEUR SUR LA FONCTION SOURCE: SELECT CASE(userchoice) CASE(1)!POUR F=F1=2*(y-y^2+x-x^2) ET G=H=0 U(it1:itN)=2.0d0! U=Uo=2: INITIALISATION WR1=MPI_WTIME()!POUR LE TEMPS D'ECRITURE DE LA SOLUTION CALL WR_U(U,it1,itN,INTER_X,INTER_Y,S1,S2,GAP,userchoice,rang,& 0,ITMAX,Lx,Ly,X,Y)!ON ENREGISTRE U Au TEMPS 0 sec (CF: REPERTOIRE SOL_NUMERIQUE) WR2=MPI_WTIME() WR=WR+WR2-WR1!POUR LE TEMPS D'ECRITURE DE LA SOLUTION CALL F1(it1,itN,S1,S2,INTER_Y,GAP,X,Y,F)!ON CALCUL LA FONCTION SOURCE CALL WR_F(rang,it1,itN,INTER_Y,F,S1,S2,GAP,X,Y) ! ON ENREGISTRE LA FONCTION SOURCE (CF REPERTOIRE: F) F_VAR=0.0d0 ALLOCATE(r(it1:itN),z(it1:itN),p(it1-INTER_Y:itN+INTER_Y))! ALLOCATION DES VECTEUR POUR LE GC(GRADIENT CONJUGUE) DO k=1,ITMAX! BOUCLE EN TEMPS POUR RESOUDRE: A.U=Uo+DT*F+CONDITIONS DE BORDS U(it1-INTER_Y:it1-1)=0.0d0;U(itN+1:itN+INTER_Y)=0.0d0!A CHAQUE ITERATION EN TEMPS, LES BORDS U SONT REMIS A ZERO CALL GC(A,AP,AL,U,F,F_VAR,userchoice,DT,TOL,KMAX,it1,itN& ,INTER_Y,INTER_X,S1,S2,GAP,Np,rang,stateinfo,status,mode,r,z,p,& Tpmv,Tcomm,Tall,PIVOT,k)!ON APPELLE LE GC POUR CALCULER LA SOLUTION AU TEMPS k*DT MAX_pmv=MAX_pmv+Tpmv;MAX_comm=MAX_comm+Tcomm;MAX_all=MAX_all+Tall!ON SUM SUR LES TEMPS MAX WR1=MPI_WTIME()!POUR LE TEMPS D'ECRITURE DE LA SOLUTION CALL WR_U(U,it1,itN,INTER_X,INTER_Y,S1,S2,GAP,userchoice,rang,& k,ITMAX,Lx,Ly,X,Y)! ON ENREGISTRE LA SOLUTION U AU TEMPS k*DT (CF: REPERTOIRE SOL_NUMERIQUE) WR2=MPI_WTIME() WR=WR+WR2-WR1!POUR LE TEMPS D'ECRITURE DE LA SOLUTION END DO CASE(2)!POUR F=F2=G=H=SIN(x)+COS(y) U(it1:itN)=2.0d0! U=Uo=2: INITIALISATION WR1=MPI_WTIME()!POUR LE TEMPS D'ECRITURE DE LA SOLUTION CALL WR_U(U,it1,itN,INTER_X,INTER_Y,S1,S2,GAP,userchoice,rang,& 0,ITMAX,Lx,Ly,X,Y)!ON ENREGISTRE U Au TEMPS 0 sec WR2=MPI_WTIME() WR=WR+WR2-WR1!POUR LE TEMPS D'ECRITURE DE LA SOLUTION CALL F2(it1,itN,S1,S2,INTER_Y,GAP,X,Y,F)!ON CALCUL LA FONCTION SOURCE CALL WR_F(rang,it1,itN,INTER_Y,F,S1,S2,GAP,X,Y) ! ON ENREGISTRE LA FONCTION SOURCE (CF REPERTOIRE: F) F_VAR=0.0d0 ALLOCATE(r(it1:itN),z(it1:itN),p(it1-INTER_Y:itN+INTER_Y))! ALLOCATION DES VECTEUR POUR LE GC(GRADIENT CONJUGUE) DO k=1,ITMAX! BOUCLE EN TEMPS POUR RESOUDRE: A.U=Uo+DT*F+CONDITIONS DE BORDS U(it1-INTER_Y:it1-1)=0.0d0;U(itN+1:itN+INTER_Y)=0.0d0!A CHAQUE ITERATION EN TEMPS, LES BORDS U SONT REMIS A ZERO CALL BC(AP,AL,userchoice,S1,S2,GAP,it1,itN,INTER_Y,INTER_X& ,X,Y,DX,DY,Lx,Ly,U(it1:itN))!LA BC EST NON NULLE ON DOIT L'APPELE A CHAQUE ITERATION EN TEMPS CALL GC(A,AP,AL,U,F,F_VAR,userchoice,DT,TOL,KMAX,it1,itN& ,INTER_Y,INTER_X,S1,S2,GAP,Np,rang,stateinfo,status,mode,r,z,p,& Tpmv,Tcomm,Tall,PIVOT,k)!ON APPELLE LE GC POUR CALCULER LA SOLUTION AU TEMPS k*DT MAX_pmv=MAX_pmv+Tpmv;MAX_comm=MAX_comm+Tcomm;MAX_all=MAX_all+Tall!ON SUM SUR LES TEMPS MAX WR1=MPI_WTIME()!POUR LE TEMPS D'ECRITURE DE LA SOLUTION CALL WR_U(U,it1,itN,INTER_X,INTER_Y,S1,S2,GAP,userchoice,rang,& k,ITMAX,Lx,Ly,X,Y)! ON ENREGISTRE LA SOLUTION U AU TEMPS k*DT (CF: REPERTOIRE SOL_NUMERIQUE) WR2=MPI_WTIME() WR=WR+WR2-WR1!POUR LE TEMPS D'ECRITURE DE LA SOLUTION END DO CASE(3)!POUR F=F3=EXP(-(X-0.5*Lx)^2)*EXP(-(Y-0.5*Ly)^2)*COS(0.5*t*Pi) ET G=0, H=1 U(it1:itN)=5.0d0! U=Uo=5: INITIALISATION WR1=MPI_WTIME()!POUR LE TEMPS D'ECRITURE DE LA SOLUTION CALL WR_U(U,it1,itN,INTER_X,INTER_Y,S1,S2,GAP,userchoice,rang,& 0,ITMAX,Lx,Ly,X,Y)!ON ENREGISTRE U Au TEMPS 0 sec WR2=MPI_WTIME() WR=WR+WR2-WR1!POUR LE TEMPS D'ECRITURE DE LA SOLUTION CALL F3_FIXE(Lx,Ly,it1,itN,S1,S2,INTER_Y,GAP,X,Y,F)!ON CALCUL LA PARITE FIXE DE LA FONCTION SOURCE CALL WR_F(rang,it1,itN,INTER_Y,F,S1,S2,GAP,X,Y) ! ON ENREGISTRE LA FONCTION SOURCE (CF REPERTOIRE: F) ALLOCATE(r(it1:itN),z(it1:itN),p(it1-INTER_Y:itN+INTER_Y))! ALLOCATION DES VECTEUR POUR LE GC(GRADIENT CONJUGUE) DO k=1,ITMAX! BOUCLE EN TEMPS POUR RESOUDRE: A.U=Uo+DT*F+CONDITIONS DE BORDS U(it1-INTER_Y:it1-1)=0.0d0;U(itN+1:itN+INTER_Y)=0.0d0 t=k*DT! ICI PB INSTATIONNAIRE F_VAR=cos(PI*t/2)! ON CALCUL LA PARTIE VARIABLE DE LA FONCTION SOURCE CALL BC(AP,AL,userchoice,S1,S2,GAP,it1,itN,INTER_Y,INTER_X& ,X,Y,DX,DY,Lx,Ly,U(it1:itN))!LA BC EST NON NULLE ON DOIT L'APPELE A CHAQUE ITERATION EN TEMPS CALL GC(A,AP,AL,U,F,F_VAR,userchoice,DT,TOL,KMAX,it1,itN& ,INTER_Y,INTER_X,S1,S2,GAP,Np,rang,stateinfo,status,mode,r,z,p,& Tpmv,Tcomm,Tall,PIVOT,k)!APPELLE DU GC MAX_pmv=MAX_pmv+Tpmv;MAX_comm=MAX_comm+Tcomm;MAX_all=MAX_all+Tall!ON SUM SUR LES TEMPS MAX WR1=MPI_WTIME()!POUR LE TEMPS D'ECRITURE DE LA SOLUTION CALL WR_U(U,it1,itN,INTER_X,INTER_Y,S1,S2,GAP,userchoice,rang,& k,ITMAX,Lx,Ly,X,Y)! ON ENREGISTRE LA SOLUTION U AU TEMPS k*DT (CF: REPERTOIRE SOL_NUMERIQUE) WR2=MPI_WTIME() WR=WR+WR2-WR1!POUR LE TEMPS D'ECRITURE DE LA SOLUTION END DO END SELECT CALL MPI_ALLREDUCE(WR,MAX_WR,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) DEALLOCATE(r,z,p)! VECTEUR POUR LE GC ON PEUT DEALLOCATE !VERIFICATION AVEC UNE SOLUTION ANALYTIQUE POUR CAS 1 Et CAS 2: IF(userchoice==1.OR.userchoice==2)THEN CALL UEXACT(U,userchoice,it1,itN,INTER_Y,INTER_X,X,Y,S1,S2,GAP,stateinfo,rang) END IF! VOIR LE REPERTOIRE: EXACTE_ERREUR DEALLOCATE(U,F) !VECTEURS ET TABLEAU ON DEALLOCATE CAR ILS NE SONT PLUS APPELE DEALLOCATE(X,Y,GAP) !FIN TPS CPU: TPS2=MPI_WTIME() CALL MPI_ALLREDUCE(TPS2-TPS1,MAX_TPS,1,MPI_DOUBLE_PRECISION,MPI_MAX,MPI_COMM_WORLD,stateinfo) !ON REND LE TEMPS TOTAL ET LA SUM DES TEMPS MAX: IF(rang==0)THEN PRINT*,'RANG',rang,'MAX TEMPS TOTAL=',MAX_TPS,'SUM_MAX:' PRINT*,'COMM=',MAX_comm,'PMV=',MAX_pmv,'allRED=',MAX_all,'Ecriture=',MAX_WR END IF !********* FIN REGION PARA: CALL MPI_FINALIZE(stateinfo) !VIZUALISATION SEQUENTIELLE: ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE RANG DIFFERENTS DANS UN FICHIER IF(rang==0.AND.sysmove==1)THEN ESPACE=' ' DO i=0,ITMAX WRITE(NT,fmt='(1I3)')i; NFILE='U_ME*'//'_T'//trim(adjustl(NT));OUT_FILE='UT'//trim(adjustl(NT))//'.dat' !ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE RANG DIFFERENTS DANS UN FICHIER CALL system('cat SOL_NUMERIQUE/'//NFILE//' >> SOL_NUMERIQUE/'//OUT_FILE) CALL system('rm SOL_NUMERIQUE/'//NFILE) OPEN(10,file='SOL_NUMERIQUE/'//OUT_FILE,position='append') SELECT CASE(userchoice)!ICI IL FAUT RAJOUTER LES POINTS AUX COINS DU DOMAINES CASE(1) WRITE(10,*)0.0d0,0.0d0,0.0d0;WRITE(10,*)Lx,0.0d0,0.0d0 WRITE(10,*)0.0d0,Ly,0.0d0;WRITE(10,*)Lx,Ly,0.0d0 CASE(2) WRITE(10,*)0.0d0,0.0d0,1.0d0;WRITE(10,*)Lx,0.0d0,1.0d0+sin(Lx) WRITE(10,*)0.0d0,Ly,cos(Ly);WRITE(10,*)Lx,Ly,cos(Ly)+sin(Lx) CASE(3) WRITE(10,*)0.0d0,0.0d0,0.5d0;WRITE(10,*)Lx,0.0d0,0.5d0!TEMPERATURES IMPOSEES DIFFERENTES, ON MOYENNE:((G+H)/2) WRITE(10,*)0.0d0,Ly,0.5d0;WRITE(10,*)Lx,Ly,0.5d0 END SELECT WRITE(10,fmt='(1A1)')ESPACE WRITE(10,fmt='(1A1)')ESPACE CLOSE(10) !ON CONCATENE POUR UNE ITERATION EN TEMPS DONNEE, LES FICHIERS DE TEMPS DIFFERENTS DANS UN FICHIER CALL system('cat SOL_NUMERIQUE/'//OUT_FILE//' >> SOL_NUMERIQUE/U.dat') CALL system('rm SOL_NUMERIQUE/'//OUT_FILE) END DO !A LA FIN, IL RESTE UN FICHIER OU LA SOLUTION EN TEMPS EST SOUS FORME D'INDEX GNUPLOT !ON APPELLE LA SUBROUTIEN DE VISUALISATION: CALL VIZU_SOL_NUM(userchoice,DT,ITMAX,Nx,Ny) END IF contains !************* !MODE DE REPARTITION 2: ******************************************************** !CALCUL LA CHARGE GLOBALE PAR PROCS POUR EN DEDUIRE LA CHARGE LOCALE EN X ET Y !LA DIFFERENCE MAXIMALE DE CHARGE ENTRE 2 PROCS EST TOUJOURS DE 1 !UTILISABLE POUR 1<=Np<=DIM, DIM=INTER_X*INTER_Y LE NBR DE POINTS DE CALCULS SUBROUTINE MODE2(rang,Np,DIM,IXMAX,INTER_X,INTER_Y,S1,S2,GAP,it1,itN,DX,DY,X,Y) INTEGER,INTENT(in)::rang,Np,DIM,IXMAX,INTER_X,INTER_Y REAL(RK_MAIN),INTENT(IN)::DX,DY INTEGER,INTENT(out)::S1,S2,it1,itN REAL(RK_MAIN),DIMENSION(:),ALLOCATABLE::X,Y INTEGER,DIMENSION(:,:),ALLOCATABLE::GAP CALL CHARGE_GLO(rang,Np,DIM,it1,itN) CALL ALLOC_X(Np,IXMAX,INTER_Y,it1,itN,S1,S2) CALL ALLOC_Y(rang,Np,S1,S2,it1,itN,INTER_Y,INTER_X,GAP) ALLOCATE(X(S1:S2));ALLOCATE(Y(1:INTER_Y)) CALL SPACE_X(S1,S2,DX,X);CALL SPACE_Y(INTER_Y,DY,Y) END SUBROUTINE MODE2 SUBROUTINE CHARGE_GLO(rang,Np,DIM,it1,itN)!CALCUL DE CHARGE CLASSIQUE INTEGER,INTENT(in)::rang,Np,DIM INTEGER,INTENT(out)::it1,itN REAL::CO_RE INTEGER::m IF(Np==1)THEN it1=1;itN=DIM ELSE CO_RE=DIM/Np;m=mod(DIM,Np) IF(rang<m)THEN it1=rang*(CO_RE+1)+1;itN=(rang+1)*(CO_RE+1) ELSE it1=1+m+rang*CO_RE;itN=it1+CO_re-1 END IF END IF END SUBROUTINE CHARGE_GLO !CALCULE LA CHARGE LOCALE EN X EN UTILISANT LA CHARGE GLOBALE(it1:itN): SUBROUTINE ALLOC_X(Np,IXMAX,INTER_Y,it1,itN,S1,S2) INTEGER,INTENT(IN)::Np,IXMAX,INTER_Y,it1,itN INTEGER,INTENT(out)::S1,S2 INTEGER::i,j,k,mult INTEGER::AFF1,AFF2 IF(Np==1)THEN S1=1;S2=IXMAX-1 ELSE AFF1=0;AFF2=0 i=1 DO WHILE(i<IXMAX.AND.(AFF1+AFF2)<2) mult=i*INTER_Y IF((AFF1==0).AND. it1<=mult)THEN!PERMET DE DETERMINER LA PRJECTION DE it1 SUR L'AXE X AFF1=1;S1=i END IF IF((AFF2==0).AND. itN<=mult)THEN!!PERMET DE DETERMINER LA PRJECTION DE itN SUR L'AXE X AFF2=1;S2=i END IF IF(AFF1==0.OR.AFF2==0)THEN i=i+1 END IF END DO END IF END SUBROUTINE ALLOC_X !ON UTILISE LA CHARGE EN X ET LA CHARGE GLOBALE POUR CALCULER LA CHARGE EN Y: SUBROUTINE ALLOC_Y(rang,Np,S1,S2,it1,itN,INTER_Y,INTER_X,GAP) INTEGER,INTENT(IN)::rang,Np,S1,S2,it1,itN,INTER_X,INTER_Y INTEGER,DIMENSION(:,:),ALLOCATABLE::TAB INTEGER,DIMENSION(:,:),ALLOCATABLE,INTENT(out)::GAP INTEGER::i,j,k IF(Np==1)THEN ALLOCATE(GAP(1:INTER_X,1:2));GAP(:,1)=1;GAP(:,2)=INTER_Y ELSE ALLOCATE(TAB(S1:S2,0:INTER_Y+1)) TAB=0 k=it1;i=S1;j=0 DO WHILE(k<itN+1)!POUR k allant de it1 à itN (charge globale) j=k-(i-1)*INTER_Y!ON CONNAIT k et i POUR TOUS LES PROCS, ON PEUT EN DEDUIRE j (i,j charges locales en X et Y) TAB(i,j)=TAB(i,j-1)+1! ON COMPTE la charge en j k=k+1 IF(j==INTER_Y)THEN!ON PASSE A LA COLONNE SUIVANTE i=i+1 END IF END DO ALLOCATE(GAP(S1:S2,1:2)) DO i=S1,S2!CHARGE LOCALE EN X DO j=1,INTER_Y!NBR LIGNE IF(TAB(i,j)==1)THEN!<=>LE PREMIER ELEMENT CONNU DU PROCS DANS UNE COLONNE GAP(i,1)=j! ON RECUREPE L'INFORMATION END IF IF(TAB(i,j)>TAB(i,j-1).AND.TAB(i,j)>TAB(i,j+1))THEN!LE PLUS GRAND ELEMENT DE TAB(,) GAP(i,2)=j !<=>AU DERNIER ELEMENT CONNU DANS LA COLONNE PAR UN PROC END IF END DO END DO DEALLOCATE(TAB) END IF END SUBROUTINE ALLOC_Y !********** !MODE 1 DE REPARTITION: *********************************************************** !SE BASE SUR LA CHARGE EN X POUR CALCULER LA CHARGE TOTALE(GLOBALE) !INDUIT POUR MOD(DIM,Np)/=0 UNE DIFFERENCE DE CHARGE = A INTER_Y ENTRE 2 PROCS !UTILISABLE POUR Np<=INTER_X SUBROUTINE MODE1(rang,Np,INTER_X,INTER_Y,S1,S2,it1,itN,DX,DY,X,Y) INTEGER,INTENT(in)::rang,Np,INTER_X,INTER_Y REAL(RK_MAIN),INTENT(IN)::DX,DY INTEGER,INTENT(out)::S1,S2,it1,itN REAL(RK_MAIN),DIMENSION(:),ALLOCATABLE::X,Y !CHARGE EN X: CALL CHARGE_X(rang,Np,INTER_X,S1,S2) ALLOCATE(X(S1:S2),Y(1:INTER_Y))! LES PROCS CONNAISSENT TOUT DE Y !CHARGE TOT: CALL CHARGE_TOT(S1,S2,INTER_Y,it1,itN) !INI ESPACE: CALL SPACE_X(S1,S2,DX,X);CALL SPACE_Y(INTER_Y,DY,Y) END SUBROUTINE MODE1 SUBROUTINE CHARGE_X(rang,Np,INTER_X,S1,S2)!REPERTITION CLASSIQUE DE LA CHARGE EN X INTEGER,INTENT(in)::rang,Np,INTER_X INTEGER,INTENT(OUT)::S1,S2 REAL::CO_RE!COEFF_REPARTION IF(Np==1)THEN S1=1;S2=INTER_X ELSE CO_RE=INTER_X/Np IF(rang<mod(INTER_X,Np))THEN S1=rang*(CO_RE+1)+1;S2=(rang+1)*(CO_RE+1) ELSE S1=1+mod(INTER_X,Np)+rang*CO_RE;S2=S1+CO_RE-1 END IF END IF END SUBROUTINE CHARGE_X SUBROUTINE SPACE_X(S1,S2,DX,X)! DISCRETISATION DE L'ESPACE EN X INTEGER,INTENT(IN)::S1,S2 REAL(RK_MAIN),INTENT(in)::DX REAL(RK_MAIN),DIMENSION(S1:S2),INTENT(out)::X INTEGER::i DO i=S1,S2 X(i)=i*DX END DO END SUBROUTINE SPACE_X SUBROUTINE SPACE_Y(INTER_Y,DY,Y)! DISCRETISATION DE L'ESPACE EN Y INTEGER,INTENT(IN)::INTER_Y REAL(RK_MAIN),INTENT(in)::DY REAL(RK_MAIN),DIMENSION(1:INTER_Y),INTENT(out)::Y INTEGER::j DO j=1,INTER_Y Y(j)=j*DY END DO END SUBROUTINE SPACE_Y SUBROUTINE CHARGE_TOT(S1,S2,INTER_Y,it1,itN)! CHARGE GLOBALE PAR PROCS INTEGER,INTENT(in)::S1,S2,INTER_Y INTEGER,INTENT(out)::it1,itN it1=(S1-1)*INTER_Y+1;itN=S2*INTER_Y END SUBROUTINE CHARGE_TOT end program main
0
ALLM
ALLM/GPU_REDO/GPU_TILLING.cu
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <omp.h> #include <cuda.h> #include <cuda_runtime.h> #include <cuda_profiler_api.h> #define SOFT 1e-20f #define THREADS_PER_BLOCK 128 #define DUMP #define BLOCK_SIZE 256 typedef struct { float4 *POS, *VIT; } PType; void randomizeBodies(float *data, int n) { for (int i = 0; i < n; i++) { data[i] = 2.0f * (rand() / (float)RAND_MAX) - 1.0f; } } void dump(int iter, int nParticles, PType pv) { char filename[64]; snprintf(filename, 64, "output_%d.txt", iter); FILE *f; f = fopen(filename, "w+"); int i; for (i = 0; i < nParticles; i++) { fprintf(f, "%e %e %e %e %e %e\n", pv.POS[i].x, pv.POS[i].y, pv.POS[i].z, pv.VIT[i].x, pv.VIT[i].y, pv.VIT[i].z); } fclose(f); } __global__ void bodyForce(float4 *p, float4 *v, float dt, int n) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < n) { float Fx = 0.0f; float Fy = 0.0f; float Fz = 0.0f; for (int tile = 0; tile < gridDim.x; tile++) { __shared__ float3 p3[BLOCK_SIZE]; float4 tmp_pos = p[tile * blockDim.x + threadIdx.x]; p3[threadIdx.x] = make_float3(tmp_pos.x, tmp_pos.y, tmp_pos.z); __syncthreads(); for (int j = 0; j < BLOCK_SIZE; j++) { float dx = p3[j].x - p[i].x; float dy = p3[j].y - p[i].y; float dz = p3[j].z - p[i].z; float distSqr = dx*dx + dy*dy + dz*dz + SOFT; float invDist = rsqrtf(distSqr); float invDist3 = invDist * invDist * invDist; Fx += dx * invDist3; Fy += dy * invDist3; Fz += dz * invDist3; } __syncthreads(); } v[i].x += dt*Fx; v[i].y += dt*Fy; v[i].z += dt*Fz; } } int main(const int argc, const char** argv) { int nBodies = 16384; int nParticles; if (argc > 1) nBodies = atoi(argv[1]); nParticles = nBodies; const float dt = 0.00005f; // time step const int nIters = 10; // simulation iterations int nSteps = nIters; int bytes = 2*nBodies*sizeof(float4); float *buf = (float*)malloc(bytes); PType p = { (float4*)buf, ((float4*)buf) + nBodies }; randomizeBodies(buf, 8*nBodies); // Init pos / vit data float *d_buf; cudaMalloc(&d_buf, bytes); PType d_p = { (float4*)d_buf, ((float4*)d_buf) + nBodies }; int nBlocks = (nBodies + BLOCK_SIZE - 1) / BLOCK_SIZE; double totalTime = 0.0; // Perform benchmark printf("\nPropagating %d particles using 1 thread...\n\n", nParticles ); double rate = 0, dRate = 0; // Benchmarking data const int skipSteps = 3; // Skip first iteration (warm-up) printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); cudaProfilerStart(); for (int step = 1; step <= nIters; step++) { const double tStart = omp_get_wtime(); // Start timing cudaMemcpy(d_buf, buf, bytes, cudaMemcpyHostToDevice); bodyForce<<<nBlocks, BLOCK_SIZE>>>(d_p.POS, d_p.VIT, dt, nBodies); cudaMemcpy(buf, d_buf, bytes, cudaMemcpyDeviceToHost); const double tEnd = omp_get_wtime(); // End timing for (int i = 0 ; i < nBodies; i++) { // integrate position p.POS[i].x += p.VIT[i].x*dt; p.POS[i].y += p.VIT[i].y*dt; p.POS[i].z += p.VIT[i].z*dt; } const float HztoInts = ((float)nParticles)*((float)(nParticles-1)) ; const float HztoGFLOPs = 20.0*1e-9*((float)(nParticles))*((float)(nParticles-1)); if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); dump(step, nBodies, p); } cudaProfilerStop(); free(buf); cudaFree(d_buf); //------------------------------------------------------------------------------------------------------------------------- rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); }
0
ALLM
ALLM/GPU_REDO/nbody.c
#include <stdio.h> #include <math.h> #include <stdlib.h> // drand48 #include <omp.h> #define DUMP struct ParticleType { float x, y, z; float vx, vy, vz; }; void MoveParticles(const int nParticles, struct ParticleType* const particle, const float dt) { // Loop over particles that experience force for (int i = 0; i < nParticles; i++) { // Components of the gravity force on particle i float Fx = 0, Fy = 0, Fz = 0; // Loop over particles that exert force for (int j = 0; j < nParticles; j++) { // No self interaction if (i != j) { // Avoid singularity and interaction with self const float softening = 1e-20; // Newton's law of universal gravity const float dx = particle[j].x - particle[i].x; const float dy = particle[j].y - particle[i].y; const float dz = particle[j].z - particle[i].z; const float drSquared = dx*dx + dy*dy + dz*dz + softening; const float drPower32 = pow(drSquared, 3.0/2.0); // Calculate the net force Fx += dx / drPower32; Fy += dy / drPower32; Fz += dz / drPower32; } } // Accelerate particles in response to the gravitational force particle[i].vx += dt*Fx; particle[i].vy += dt*Fy; particle[i].vz += dt*Fz; } // Move particles according to their velocities // O(N) work, so using a serial loop for (int i = 0 ; i < nParticles; i++) { particle[i].x += particle[i].vx*dt; particle[i].y += particle[i].vy*dt; particle[i].z += particle[i].vz*dt; } } void dump(int iter, int nParticles, struct ParticleType* particle) { char filename[64]; snprintf(filename, 64, "output_%d.txt", iter); FILE *f; f = fopen(filename, "w+"); int i; for (i = 0; i < nParticles; i++) { fprintf(f, "%e %e %e %e %e %e\n", particle[i].x, particle[i].y, particle[i].z, particle[i].vx, particle[i].vy, particle[i].vz); } fclose(f); } // Initialize random number generator and particles: void init_rand(int nParticles, struct ParticleType* particle){ srand48(0x2020); for (int i = 0; i < nParticles; i++) { particle[i].x = 2.0*drand48() - 1.0; particle[i].y = 2.0*drand48() - 1.0; particle[i].z = 2.0*drand48() - 1.0; particle[i].vx = 2.0*drand48() - 1.0; particle[i].vy = 2.0*drand48() - 1.0; particle[i].vz = 2.0*drand48() - 1.0; } } // Initialize (no random generator) particles void init_norand(int nParticles, struct ParticleType* particle){ const float a=127.0/nParticles; for (int i = 0; i < nParticles; i++) { particle[i].x = i*a;//2.0*drand48() - 1.0; particle[i].y = i*a;//2.0*drand48() - 1.0; particle[i].z = 1.0;//2.0*drand48() - 1.0; particle[i].vx = 0.5;//2.0*drand48() - 1.0; particle[i].vy = 0.5;//2.0*drand48() - 1.0; particle[i].vz = 0.5;//2.0*drand48() - 1.0; } } void init_sphere(int nParticles, struct ParticleType* particle){ const float a = 0.0f, b = 0.0f, c = 0.0f; const float r = 100.0f; particle[0].x = 0.0f; particle[0].y = 0.0f; particle[0].z = r; particle[0].vx = 0.0f; particle[0].vy = 0.0f; particle[0].vz = -r; particle[1].x = 0.0f; particle[1].y = 0.0f; particle[1].z = -r; particle[1].vx = 0.0f; particle[1].vy = 0.0f; particle[1].vz = r; for (int i = 2; i < 3289; i++) { float eta = 2*3.14159265359/3287; particle[i].x = r*cos(eta); particle[i].y = r*sin(eta); particle[i].z = 0.0f; particle[i].vx = -r*cos(eta); particle[i].vy = r*sin(eta); particle[i].vz = 0.0f; } for (int i = 3289; i < nParticles; i++) float eta = 2*3.14159265359/13095.0; particle[i].x = r*cos(eta); particle[i].y = r*sin(eta); particle[i].z = 0.0f; particle[i].vx = -r*cos(eta); particle[i].vy = r*sin(eta); particle[i].vz = -99.0f+0.01504391f; } } int main(const int argc, const char** argv) { // Problem size and other parameters const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384); // Duration of test const int nSteps = (argc > 2)?atoi(argv[2]):10; // Particle propagation time step const float dt = 0.0005f; struct ParticleType* particle = malloc(nParticles*sizeof(struct ParticleType)); // Initialize random number generator and particles //init_rand(nParticles, particle); // Initialize (no random generator) particles init_norand(nParticles, particle); // Perform benchmark printf("\nPropagating %d particles using 1 thread...\n\n", nParticles ); double rate = 0, dRate = 0; // Benchmarking data const int skipSteps = 3; // Skip first iteration (warm-up) printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); for (int step = 1; step <= nSteps; step++) { const double tStart = omp_get_wtime(); // Start timing MoveParticles(nParticles, particle, dt); const double tEnd = omp_get_wtime(); // End timing const float HztoInts = ((float)nParticles)*((float)(nParticles-1)) ; const float HztoGFLOPs = 20.0*1e-9*((float)(nParticles))*((float)(nParticles-1)); if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); #ifdef DUMP dump(step, nParticles, particle); #endif } rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); free(particle); return 0; }
0
ALLM
ALLM/GPU_REDO/nbody_aos.cu
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <math.h> #include <omp.h> #include <cuda.h> #include <cuda_runtime.h> #include <cuda_profiler_api.h> #define nPart 16384 #define THREADS_PER_BLOCK 256 #define DUMP //------------------------------------------------------------------------------------------------------------------------- //struct ParticleType{ // float x, y, z, vx, vy, vz; //}; struct ParticleType{ float x[nPart],y[nPart],z[nPart]; float vx[nPart],vy[nPart],vz[nPart]; }; //------------------------------------------------------------------------------------------------------------------------- //CUDA VERSION: __global__ void MoveParticles_CUDA(const int nParticles, struct ParticleType* const particle){ // Particle propagation time step const float dt = 0.0005f; int i = threadIdx.x + blockIdx.x * blockDim.x; if(i<nParticles){ float Fx=0.,Fy=0.,Fz=0.; for(int j = 0; j< nParticles; j++){ //no self interaction: if(i != j){ //avoid singularity and interaction with self: const float softening = 1e-20; //Newton's law of universal gravity: const float dx = particle->x[j] - particle->x[i]; const float dy = particle->y[j] - particle->y[i]; const float dz = particle->z[j] - particle->z[i]; const float drSquared = dx*dx + dy*dy + dz*dz + softening; const float drPower32 = pow(drSquared, 3.0/2.0); //Calculate the net force: Fx += dx / drPower32; Fy += dy / drPower32; Fz += dz / drPower32; }//fi i!=j }//j loop //Accelerate particles in response to the gravitational force: particle->vx[i] += dt*Fx; particle->vy[i] += dt*Fy; particle->vz[i] += dt*Fz; } }//fct MoveParticles_CUDA //------------------------------------------------------------------------------------------------------------------------- // Initialize random number generator and particles: void init_rand(int nParticles, struct ParticleType* particle){ srand48(0x2020); for (int i = 0; i < nParticles; i++) { particle->x[i] = 2.0*drand48() - 1.0; particle->y[i] = 2.0*drand48() - 1.0; particle->z[i] = 2.0*drand48() - 1.0; particle->vx[i] = 2.0*drand48() - 1.0; particle->vy[i] = 2.0*drand48() - 1.0; particle->vz[i] = 2.0*drand48() - 1.0; } } //------------------------------------------------------------------------------------------------------------------------- // Initialize (no random generator) particles void init_norand(int nParticles, struct ParticleType* const particle){ const float a=127.0/nParticles; for (int i = 0; i < nParticles; i++) { particle->x[i] = i*a;//2.0*drand48() - 1.0; particle->y[i] = i*a;//2.0*drand48() - 1.0; particle->z[i] = 1.0;//2.0*drand48() - 1.0; particle->vx[i] = 0.5;//2.0*drand48() - 1.0; particle->vy[i] = 0.5;//2.0*drand48() - 1.0; particle->vz[i] = 0.5;//2.0*drand48() - 1.0; } } //------------------------------------------------------------------------------------------------------------------------- void dump(int iter, int nParticles, struct ParticleType* particle) { char filename[64]; snprintf(filename, 64, "output_%d.txt", iter); FILE *f; f = fopen(filename, "w+"); int i; for (i = 0; i < nParticles; i++) { fprintf(f, "%e %e %e %e %e %e\n", particle->x[i], particle->y[i], particle->z[i], particle->vx[i], particle->vy[i], particle->vz[i]); } fclose(f); } //------------------------------------------------------------------------------------------------------------------------- int main(const int argc, const char** argv) { // Problem size and other parameters // const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384); const int nParticles=nPart; // Duration of test const int nSteps = (argc > 2)?atoi(argv[2]):10; // Particle propagation time step const float ddt = 0.0005f; //------------------------------------------------------------------------------------------------------------------------- //DEFINE SIZE: int SIZE = sizeof(struct ParticleType); //------------------------------------------------------------------------------------------------------------------------- //DECLARATION & ALLOC particle ON HOST: struct ParticleType* particle = (struct ParticleType*) malloc(SIZE); //------------------------------------------------------------------------------------------------------------------------- // Initialize random number generator and particles srand48(0x2020); //Initialize random number generator and particles //init_rand(nParticles, particle); // Initialize (no random generator) particles init_norand(nParticles, particle); //------------------------------------------------------------------------------------------------------------------------- // Perform benchmark printf("\nPropagating %d particles using %d thread...\n\n", 128 ,nParticles ); double rate = 0, dRate = 0; // Benchmarking data const int skipSteps = 3; // Skip first iteration (warm-up) printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); //------------------------------------------------------------------------------------------------------------------------- cudaProfilerStart(); //------------------------------------------------------------------------------------------------------------------------- struct ParticleType *particle_cuda; cudaMalloc((void **)&particle_cuda, SIZE); //------------------------------------------------------------------------------------------------------------------------- // cudaMemcpy(particle_cuda, particle, SIZE, cudaMemcpyHostToDevice); //------------------------------------------------------------------------------------------------------------------------- for (int step = 1; step <= nSteps; step++) { const double tStart = omp_get_wtime(); // Start timing cudaMemcpy(particle_cuda, particle, SIZE, cudaMemcpyHostToDevice); MoveParticles_CUDA<<<nParticles/THREADS_PER_BLOCK,THREADS_PER_BLOCK>>>(nParticles, particle_cuda); cudaMemcpy(particle, particle_cuda, SIZE, cudaMemcpyDeviceToHost);//need to do? const double tEnd = omp_get_wtime(); // End timing // Move particles according to their velocities // O(N) work, so using a serial loop for (int i = 0 ; i < nParticles; i++) { particle->x[i] += particle->vx[i]*ddt; particle->y[i] += particle->vy[i]*ddt; particle->z[i] += particle->vz[i]*ddt; } const float HztoInts = ((float)nParticles)*((float)(nParticles-1)) ; const float HztoGFLOPs = 20.0*1e-9*((float)(nParticles))*((float)(nParticles-1)); if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); #ifdef DUMP dump(step, nParticles, particle); #endif } cudaFree(particle_cuda); //------------------------------------------------------------------------------------------------------------------------- cudaProfilerStop(); //------------------------------------------------------------------------------------------------------------------------- rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); free(particle); return 0; }
0
ALLM
ALLM/GPU_REDO/nbody_cuda.cu
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <math.h> #include <omp.h> #include <cuda.h> #include <cuda_runtime.h> #include <cuda_profiler_api.h> #define THREADS_PER_BLOCK 128 #define DUMP //------------------------------------------------------------------------------------------------------------------------- struct ParticleType{ float x, y, z, vx, vy, vz; }; //------------------------------------------------------------------------------------------------------------------------- //CUDA VERSION: __global__ void MoveParticles_CUDA(const int nParticles, struct ParticleType* const particle){ // Particle propagation time step const float dt = 0.0005f; float Fx = 0.0, Fy = 0.0, Fz = 0.0; int i = threadIdx.x + blockIdx.x * blockDim.x; if(i<nParticles){ for(int j = 0; j< nParticles; j++){ //no self interaction: if(i != j){ //avoid singularity and interaction with self: const float softening = 1e-20; //Newton's law of universal gravity: const float dx = particle[j].x - particle[i].x; const float dy = particle[j].y - particle[i].y; const float dz = particle[j].z - particle[i].z; const float drSquared = dx*dx + dy*dy + dz*dz + softening; const float drPower32 = pow(drSquared, 3.0/2.0); //Calculate the net force: Fx += dx / drPower32; Fy += dy / drPower32; Fz += dz / drPower32; }//fi i!=j }//j loop //Accelerate particles in response to the gravitational force: particle[i].vx += dt*Fx; particle[i].vy += dt*Fy; particle[i].vz += dt*Fz; } }//fct MoveParticles_CUDA //------------------------------------------------------------------------------------------------------------------------- // Initialize random number generator and particles: void init_rand(int nParticles, struct ParticleType* particle){ srand48(0x2020); for (int i = 0; i < nParticles; i++) { particle[i].x = 2.0*drand48() - 1.0; particle[i].y = 2.0*drand48() - 1.0; particle[i].z = 2.0*drand48() - 1.0; particle[i].vx = 2.0*drand48() - 1.0; particle[i].vy = 2.0*drand48() - 1.0; particle[i].vz = 2.0*drand48() - 1.0; } } //------------------------------------------------------------------------------------------------------------------------- // Initialize (no random generator) particles void init_norand(int nParticles, struct ParticleType* particle){ const float a=127.0/nParticles; for (int i = 0; i < nParticles; i++) { particle[i].x = i*a;//2.0*drand48() - 1.0; particle[i].y = i*a;//2.0*drand48() - 1.0; particle[i].z = 1.0;//2.0*drand48() - 1.0; particle[i].vx = 0.5;//2.0*drand48() - 1.0; particle[i].vy = 0.5;//2.0*drand48() - 1.0; particle[i].vz = 0.5;//2.0*drand48() - 1.0; } } void init_sphere(int nParticles, struct ParticleType* particle){ const float a = 0.0f, b = 0.0f, c = 0.0f; const float r = 100.0f; particle[0].x = 0.0f; particle[0].y = 0.0f; particle[0].z = r; particle[0].vx = 0.0f; particle[0].vy = 0.0f; particle[0].vz = -r; particle[1].x = 0.0f; particle[1].y = 0.0f; particle[1].z = -r; particle[1].vx = 0.0f; particle[1].vy = 0.0f; particle[1].vz = r; for (int i = 2; i < 3289; i++) { float eta = 2*3.14159265359/3287; particle[i].x = r*cos(eta); particle[i].y = r*sin(eta); particle[i].z = 0.0f; particle[i].vx = -r*cos(eta); particle[i].vy = r*sin(eta); particle[i].vz = 0.0f; } for (int i = 3289; i < nParticles; i++) float eta = 2*3.14159265359/13095.0; particle[i].x = r*cos(eta); particle[i].y = r*sin(eta); particle[i].z = 0.0f; particle[i].vx = -r*cos(eta); particle[i].vy = r*sin(eta); particle[i].vz = -99.0f+0.01504391f; } } //------------------------------------------------------------------------------------------------------------------------- void dump(int iter, int nParticles, struct ParticleType* particle) { char filename[64]; snprintf(filename, 64, "output_%d.txt", iter); FILE *f; f = fopen(filename, "w+"); int i; for (i = 0; i < nParticles; i++) { fprintf(f, "%e %e %e %e %e %e\n", particle[i].x, particle[i].y, particle[i].z, particle[i].vx, particle[i].vy, particle[i].vz); } fclose(f); } //------------------------------------------------------------------------------------------------------------------------- int main(const int argc, const char** argv) { // Problem size and other parameters const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384); // Duration of test const int nSteps = (argc > 2)?atoi(argv[2]):10; // Particle propagation time step const float ddt = 0.0005f; //------------------------------------------------------------------------------------------------------------------------- //DEFINE SIZE: int SIZE = nParticles * sizeof(struct ParticleType); //------------------------------------------------------------------------------------------------------------------------- //DECLARATION & ALLOC particle ON HOST: struct ParticleType* particle = (struct ParticleType*) malloc(SIZE); //------------------------------------------------------------------------------------------------------------------------- // Initialize random number generator and particles srand48(0x2020); // Initialize random number generator and particles //init_rand(nParticles, particle); // Initialize (no random generator) particles init_norand(nParticles, particle); //------------------------------------------------------------------------------------------------------------------------- // Perform benchmark printf("\nPropagating %d particles using 1 thread...\n\n", nParticles ); double rate = 0, dRate = 0; // Benchmarking data const int skipSteps = 3; // Skip first iteration (warm-up) printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); //------------------------------------------------------------------------------------------------------------------------- cudaProfilerStart(); //------------------------------------------------------------------------------------------------------------------------- struct ParticleType *particle_cuda; cudaMalloc((void **)&particle_cuda, SIZE); //------------------------------------------------------------------------------------------------------------------------- cudaMemcpy(particle_cuda, particle, SIZE, cudaMemcpyHostToDevice); //------------------------------------------------------------------------------------------------------------------------- for (int step = 1; step <= nSteps; step++) { const double tStart = omp_get_wtime(); // Start timing cudaMemcpy(particle_cuda, particle, SIZE, cudaMemcpyHostToDevice); MoveParticles_CUDA<<<nParticles/THREADS_PER_BLOCK,THREADS_PER_BLOCK>>>(nParticles, particle_cuda); cudaMemcpy(particle, particle_cuda, SIZE, cudaMemcpyDeviceToHost);//need to do? const double tEnd = omp_get_wtime(); // End timing // Move particles according to their velocities // O(N) work, so using a serial loop for (int i = 0 ; i < nParticles; i++) { particle[i].x += particle[i].vx*ddt; particle[i].y += particle[i].vy*ddt; particle[i].z += particle[i].vz*ddt; } const float HztoInts = ((float)nParticles)*((float)(nParticles-1)) ; const float HztoGFLOPs = 20.0*1e-9*((float)(nParticles))*((float)(nParticles-1)); if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); #ifdef DUMP dump(step, nParticles, particle); #endif } cudaFree(particle_cuda); //------------------------------------------------------------------------------------------------------------------------- cudaProfilerStop(); //------------------------------------------------------------------------------------------------------------------------- rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); free(particle); return 0; }
0
ALLM
ALLM/GPU_REDO/nbody_cudaV2.cu
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <math.h> #include <omp.h> #include <cuda.h> #include <cuda_runtime.h> #include <cuda_profiler_api.h> #define THREADS_PER_BLOCK 128 #define DUMP //------------------------------------------------------------------------------------------------------------------------- struct PType{ float x,y,z; }; //------------------------------------------------------------------------------------------------------------------------- //CUDA VERSION: __global__ void MoveParticles_CUDA(const int nParticles, struct PType* const POS, struct PType* const VIT){ // Particle propagation time step const float dt = 0.0005f; float Fx = 0.0, Fy = 0.0, Fz = 0.0; int i = threadIdx.x + blockIdx.x * blockDim.x; if(i<nParticles){ for(int j = 0; j< nParticles; j++){ //no self interaction: if(i != j){ //avoid singularity and interaction with self: const float softening = 1e-20; //Newton's law of universal gravity: const float dx = POS[j].x - POS[i].x; const float dy = POS[j].y - POS[i].y; const float dz = POS[j].z - POS[i].z; const float drSquared = dx*dx + dy*dy + dz*dz + softening; const float drPower32 = pow(drSquared, 3.0/2.0); //Calculate the net force: Fx += dx / drPower32; Fy += dy / drPower32; Fz += dz / drPower32; }//fi i!=j }//j loop //Accelerate particles in response to the gravitational force: VIT[i].x += dt*Fx; VIT[i].y += dt*Fy; VIT[i].z += dt*Fz; } }//fct MoveParticles_CUDA //------------------------------------------------------------------------------------------------------------------------- // Initialize random number generator and particles: void init_rand(int nParticles, struct PType* POS, struct PType* VIT){ srand48(0x2020); for (int i = 0; i < nParticles; i++) { POS[i].x = 2.0*drand48() - 1.0; POS[i].y = 2.0*drand48() - 1.0; POS[i].z = 2.0*drand48() - 1.0; VIT[i].x = 2.0*drand48() - 1.0; VIT[i].y = 2.0*drand48() - 1.0; VIT[i].z = 2.0*drand48() - 1.0; } } //------------------------------------------------------------------------------------------------------------------------- // Initialize (no random generator) particles void init_norand(int nParticles, struct PType* POS, struct PType* VIT){ const float a=127.0/nParticles; for (int i = 0; i < nParticles; i++) { POS[i].x = i*a;//2.0*drand48() - 1.0; POS[i].y = i*a;//2.0*drand48() - 1.0; POS[i].z = 1.0;//2.0*drand48() - 1.0; VIT[i].x = 0.5;//2.0*drand48() - 1.0; VIT[i].y = 0.5;//2.0*drand48() - 1.0; VIT[i].z = 0.5;//2.0*drand48() - 1.0; } } void init_sphere(int nParticles, struct ParticleType* particle){ const float a = 0.0f, b = 0.0f, c = 0.0f; const float r = 100.0f; particle[0].x = 0.0f; particle[0].y = 0.0f; particle[0].z = r; particle[0].vx = 0.0f; particle[0].vy = 0.0f; particle[0].vz = -r; particle[1].x = 0.0f; particle[1].y = 0.0f; particle[1].z = -r; particle[1].vx = 0.0f; particle[1].vy = 0.0f; particle[1].vz = r; for (int i = 2; i < 3289; i++) { float eta = 2*3.14159265359/3287; particle[i].x = r*cos(eta); particle[i].y = r*sin(eta); particle[i].z = 0.0f; particle[i].vx = -r*cos(eta); particle[i].vy = r*sin(eta); particle[i].vz = 0.0f; } for (int i = 3289; i < nParticles; i++) float eta = 2*3.14159265359/13095.0; particle[i].x = r*cos(eta); particle[i].y = r*sin(eta); particle[i].z = 0.0f; particle[i].vx = -r*cos(eta); particle[i].vy = r*sin(eta); particle[i].vz = -99.0f+0.01504391f; } } //------------------------------------------------------------------------------------------------------------------------- void dump(int iter, int nParticles, struct PType* POS, struct PType* VIT) { char filename[64]; snprintf(filename, 64, "output_%d.txt", iter); FILE *f; f = fopen(filename, "w+"); int i; for (i = 0; i < nParticles; i++) { fprintf(f, "%e %e %e %e %e %e\n", POS[i].x, POS[i].y, POS[i].z, VIT[i].x, VIT[i].y, VIT[i].z); } fclose(f); } //------------------------------------------------------------------------------------------------------------------------- int main(const int argc, const char** argv) { // Problem size and other parameters const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384); // Duration of test const int nSteps = (argc > 2)?atoi(argv[2]):10; // Particle propagation time step const float ddt = 0.0005f; //------------------------------------------------------------------------------------------------------------------------- //DEFINE SIZE: int SIZE = nParticles * sizeof(struct PType); //------------------------------------------------------------------------------------------------------------------------- //DECLARATION & ALLOC particle ON HOST: struct PType* POS = (struct PType*) malloc(SIZE); struct PType* VIT = (struct PType*) malloc(SIZE); //------------------------------------------------------------------------------------------------------------------------- // Initialize random number generator and particles srand48(0x2020); // Initialize random number generator and particles //init_rand(nParticles, POS, VIT); // Initialize (no random generator) particles init_norand(nParticles, POS, VIT); //------------------------------------------------------------------------------------------------------------------------- // Perform benchmark printf("\nPropagating %d particles using 1 thread...\n\n", nParticles ); double rate = 0, dRate = 0; // Benchmarking data const int skipSteps = 3; // Skip first iteration (warm-up) printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); //------------------------------------------------------------------------------------------------------------------------- cudaProfilerStart(); //------------------------------------------------------------------------------------------------------------------------- struct PType *POS_cuda; cudaMalloc((void **)&POS_cuda, SIZE); //cudaMemcpy(POS_cuda, POS, SIZE, cudaMemcpyHostToDevice); //------------------------------------------------------------------------------------------------------------------------- struct PType *VIT_cuda; cudaMalloc((void **)&VIT_cuda, SIZE); //cudaMemcpy(VIT_cuda, VIT, SIZE, cudaMemcpyHostToDevice); //------------------------------------------------------------------------------------------------------------------------- for (int step = 1; step <= nSteps; step++) { const double tStart = omp_get_wtime(); // Start timing cudaMemcpy(POS_cuda, POS, SIZE, cudaMemcpyHostToDevice); cudaMemcpy(VIT_cuda, VIT, SIZE, cudaMemcpyHostToDevice); MoveParticles_CUDA<<<nParticles/THREADS_PER_BLOCK,THREADS_PER_BLOCK>>>(nParticles, POS_cuda, VIT_cuda); cudaMemcpy(POS, POS_cuda, SIZE, cudaMemcpyDeviceToHost); cudaMemcpy(VIT, VIT_cuda, SIZE, cudaMemcpyDeviceToHost); const double tEnd = omp_get_wtime(); // End timing // Move particles according to their velocities // O(N) work, so using a serial loop for (int i = 0 ; i < nParticles; i++) { POS[i].x += VIT[i].x*ddt; POS[i].y += VIT[i].y*ddt; POS[i].z += VIT[i].z*ddt; } const float HztoInts = ((float)nParticles)*((float)(nParticles-1)) ; const float HztoGFLOPs = 20.0*1e-9*((float)(nParticles))*((float)(nParticles-1)); if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); #ifdef DUMP dump(step, nParticles, POS, VIT); #endif } cudaFree(POS_cuda); cudaFree(VIT_cuda); //------------------------------------------------------------------------------------------------------------------------- cudaProfilerStop(); //------------------------------------------------------------------------------------------------------------------------- rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); free(POS); free(VIT); return 0; }
0
ALLM
ALLM/GPU_REDO/nbody_omp.c
#include <stdio.h> #include <math.h> #include <stdlib.h> // drand48 #include <omp.h> #define DUMP struct ParticleType { float x, y, z; float vx, vy, vz; }; void MoveParticles(const int nParticles, struct ParticleType* const particle, const float dt) { int i,j; float Fx,Fy,Fz; // Loop over particles that experience force #pragma omp parallel for private(j) for (i = 0; i < nParticles; i++) { // Components of the gravity force on particle i Fx = 0, Fy = 0, Fz = 0; // Loop over particles that exert force for (j = 0; j < nParticles; j++) { // No self interaction //if (i != j) { // Avoid singularity and interaction with self const float softening = 1e-20; // Newton's law of universal gravity const float dx = particle[j].x - particle[i].x; const float dy = particle[j].y - particle[i].y; const float dz = particle[j].z - particle[i].z; const float drSquared = dx*dx + dy*dy + dz*dz + softening; const float drPower32 = pow(drSquared, 3.0/2.0); // Calculate the net force Fx += dx / drPower32; Fy += dy / drPower32; Fz += dz / drPower32; //} } // Accelerate particles in response to the gravitational force particle[i].vx += dt*Fx; particle[i].vy += dt*Fy; particle[i].vz += dt*Fz; } // Move particles according to their velocities // O(N) work, so using a serial loop #pragma omp parallel for for (int i = 0 ; i < nParticles; i++) { particle[i].x += particle[i].vx*dt; particle[i].y += particle[i].vy*dt; particle[i].z += particle[i].vz*dt; } } void dump(int iter, int nParticles, struct ParticleType* particle) { char filename[64]; snprintf(filename, 64, "output_%d.txt", iter); FILE *f; f = fopen(filename, "w+"); int i; for (i = 0; i < nParticles; i++) { fprintf(f, "%e %e %e %e %e %e\n", particle[i].x, particle[i].y, particle[i].z, particle[i].vx, particle[i].vy, particle[i].vz); } fclose(f); } // Initialize random number generator and particles: void init_rand(int nParticles, struct ParticleType* particle){ srand48(0x2020); #pragma omp parallel for for (int i = 0; i < nParticles; i++) { particle[i].x = 2.0*drand48() - 1.0; particle[i].y = 2.0*drand48() - 1.0; particle[i].z = 2.0*drand48() - 1.0; particle[i].vx = 2.0*drand48() - 1.0; particle[i].vy = 2.0*drand48() - 1.0; particle[i].vz = 2.0*drand48() - 1.0; } } // Initialize (no random generator) particles void init_norand(int nParticles, struct ParticleType* particle){ const float a=127.0/nParticles; #pragma omp parallel for for (int i = 0; i < nParticles; i++) { particle[i].x = i*a;//2.0*drand48() - 1.0; particle[i].y = i*a;//2.0*drand48() - 1.0; particle[i].z = 1.0;//2.0*drand48() - 1.0; particle[i].vx = 0.5;//2.0*drand48() - 1.0; particle[i].vy = 0.5;//2.0*drand48() - 1.0; particle[i].vz = 0.5;//2.0*drand48() - 1.0; } } int main(const int argc, const char** argv) { // Problem size and other parameters const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384); // Duration of test const int nSteps = (argc > 2)?atoi(argv[2]):10; // Particle propagation time step const float dt = 0.0005f; struct ParticleType* particle = malloc(nParticles*sizeof(struct ParticleType)); // Initialize random number generator and particles //init_rand(nParticles, particle); // Initialize (no random generator) particles init_norand(nParticles, particle); // Perform benchmark printf("\nPropagating %d particles using 1 thread...\n\n", nParticles ); double rate = 0, dRate = 0; // Benchmarking data const int skipSteps = 3; // Skip first iteration (warm-up) printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); for (int step = 1; step <= nSteps; step++) { const double tStart = omp_get_wtime(); // Start timing MoveParticles(nParticles, particle, dt); const double tEnd = omp_get_wtime(); // End timing const float HztoInts = ((float)nParticles)*((float)(nParticles-1)) ; const float HztoGFLOPs = 20.0*1e-9*((float)(nParticles))*((float)(nParticles-1)); if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); #ifdef DUMP dump(step, nParticles, particle); #endif } rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); free(particle); return 0; }
0
ALLM
ALLM/GPU_REDO/openacc.c
#include <stdio.h> #include <math.h> #include <stdlib.h> // drand48 #include <omp.h> #define DUMP struct ParticleType { float x, y, z; float vx, vy, vz; }; void MoveParticles(const int nParticles, struct ParticleType* const particle, const float dt) { int i,j; float Fx,Fy,Fz; // Loop over particles that experience force #pragma parallel loop//acc kernels async(2) wait(1) for (i = 0; i < nParticles; i++) { // Components of the gravity force on particle i Fx = 0, Fy = 0, Fz = 0; // Loop over particles that exert force //#pragma acc parallel loop independent reduction(+:Fx,Fy,Fz) for (j = 0; j < nParticles; j++) { // No self interaction // Avoid singularity and interaction with self const float softening = 1e-20; // Newton's law of universal gravity const float dx = particle[j].x - particle[i].x; const float dy = particle[j].y - particle[i].y; const float dz = particle[j].z - particle[i].z; const float drSquared = dx*dx + dy*dy + dz*dz + softening; const float drPower32 = pow(drSquared, 3.0/2.0); // Calculate the net force Fx += dx / drPower32; Fy += dy / drPower32; Fz += dz / drPower32; } // Accelerate particles in response to the gravitational force particle[i].vx += dt*Fx; particle[i].vy += dt*Fy; particle[i].vz += dt*Fz; } // Move particles according to their velocities // O(N) work, so using a serial loop for (int i = 0 ; i < nParticles; i++) { particle[i].x += particle[i].vx*dt; particle[i].y += particle[i].vy*dt; particle[i].z += particle[i].vz*dt; } } void dump(int iter, int nParticles, struct ParticleType* particle) { char filename[64]; snprintf(filename, 64, "output_%d.txt", iter); FILE *f; f = fopen(filename, "w+"); int i; for (i = 0; i < nParticles; i++) { fprintf(f, "%e %e %e %e %e %e\n", particle[i].x, particle[i].y, particle[i].z, particle[i].vx, particle[i].vy, particle[i].vz); } fclose(f); } // Initialize random number generator and particles: void init_rand(int nParticles, struct ParticleType* particle){ srand48(0x2020); for (int i = 0; i < nParticles; i++) { particle[i].x = 2.0*drand48() - 1.0; particle[i].y = 2.0*drand48() - 1.0; particle[i].z = 2.0*drand48() - 1.0; particle[i].vx = 2.0*drand48() - 1.0; particle[i].vy = 2.0*drand48() - 1.0; particle[i].vz = 2.0*drand48() - 1.0; } } // Initialize (no random generator) particles void init_norand(int nParticles, struct ParticleType* particle){ const float a=127.0/nParticles; for (int i = 0; i < nParticles; i++) { particle[i].x = i*a;//2.0*drand48() - 1.0; particle[i].y = i*a;//2.0*drand48() - 1.0; particle[i].z = 1.0;//2.0*drand48() - 1.0; particle[i].vx = 0.5;//2.0*drand48() - 1.0; particle[i].vy = 0.5;//2.0*drand48() - 1.0; particle[i].vz = 0.5;//2.0*drand48() - 1.0; } } int main(const int argc, const char** argv) { // Problem size and other parameters const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384); // Duration of test const int nSteps = (argc > 2)?atoi(argv[2]):10; // Particle propagation time step const float dt = 0.0005f; struct ParticleType* particle = malloc(nParticles*sizeof(struct ParticleType)); // Initialize random number generator and particles //init_rand(nParticles, particle); // Initialize (no random generator) particles init_norand(nParticles, particle); // Perform benchmark printf("\nPropagating %d particles using 1 thread...\n\n", nParticles ); double rate = 0, dRate = 0; // Benchmarking data const int skipSteps = 3; // Skip first iteration (warm-up) printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); #pragma acc data copyin(particle[0:nParticles],dt) for (int step = 1; step <= nSteps; step++) { const double tStart = omp_get_wtime(); // Start timing #pragma acc update host(particle[0:nParticles]) MoveParticles(nParticles, particle, dt); #pragma acc update device(particle[0:nParticles]) const double tEnd = omp_get_wtime(); // End timing const float HztoInts = ((float)nParticles)*((float)(nParticles-1)) ; const float HztoGFLOPs = 20.0*1e-9*((float)(nParticles))*((float)(nParticles-1)); if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); #ifdef DUMP dump(step, nParticles, particle); #endif } rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); free(particle); }
0
ALLM
ALLM/MAILLAGE/barycentre.f90
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!Programme adapté au prog de base pour connaitre si oui ou non un point est dans le triangle grâce aux oordonnées barycentriques w1 w2 w3 du point !!!!A modifier pour qu'ils renvoient les signes des coordonnées barycentriques logical function in_triangle(Ptarget,CO3P) implicit none Real(PR), Dimension(2), Intent(IN) :: Ptarget !X Y Real(PR), Dimension(6), Intent(IN) :: CO3P !X1 Y1 X2 Y2 X3 Y3 !Real(PR), Intent(IN) :: WIZ ! What IS ZERO i.e la tol pour Dist Real(PR) :: A123, P12,P23,P31 Real(PR)::xP2_3,yP2_3,xP3_1,yP2_3,xP1_2,yP1_2,w1,w2,w3 !Calcul de l'aire du triangle P12=COP3(1)*COP3(4)-COP3(2)*COP3(3) P23=COP3(3)*COP3(6)-COP3(4)*COP3(5) P31=COP3(5)*COP3(2)-COP3(6)*COP3(1) A123=abs((P12+P23+P31)/2) !Calcul des coordonnées des 'différences' des sommets xP2_3=COP3(3)-COP3(5); yP2_3=COP3(4)-COP3(6); xP3_1=COP3(5)-COP3(1); yP3_1=COP3(6)-COP3(2); xP1_2=COP3(1)-COP3(3); yP1_2=COP3(2)-COP3(4); !Calcul des coordonnées barycentriques w1=(P23-Ptarget(1)*yP2_3+Ptarget(2)*xP2_3)/A123 w2=(P31-Ptarget(1)*yP3_1+Ptarget(2)*xP3_1)/A123 w3=(P12-Ptarget(1)*yP1_2+Ptarget(2)*xP1_2)/A123 IF(w1>0 .and. w2>0 .and. w3>0)THEN in_triangle = .TRUE. ELSE in_triangle = .FALSE. END IF end function in_triangle
0
ALLM
ALLM/MULTI_COEURS/aos.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define SIZE 50000000 typedef struct { float a,b,c,d,e,f,g,h; } s_t; void wr_time(int echo, double sum_main, double sum){ int j; FILE *fpp; fpp = fopen ("time.txt", "a"); if(echo == 0){fputs("temps cpu: main func compute \n", fpp );} fprintf(fpp, " aos.c %f %f \n", sum_main, sum ); fclose(fpp); } void wr(s_t *a){ int j; FILE *fp; fp = fopen ("val.txt", "a"); fputs(" j .a .b .d \n", fp ); for(j=0; j<32; j++){ fprintf(fp, "%d %f %f %f \n",j, a[j].a,a[j].b,a[j].d ); } fclose(fp); } void compute(s_t *a) { int i; for (i=4; i<SIZE; i++) {//boucle elements a[i].a=(a[i-1].b * 0.42 + a[i-3].d * 0.32); //fprintf(stderr,"wwi=%d %f %f %f %f\n",i,a[i].a,a[i-1].b,a[i-3].d,0.42*a[i-1].b+0.32*a[i-3].d); a[i].b = a[i].c / 7.56+ a[i].f; a[i].c = a[i].d + a[i].g*a[i].d; a[i].d = .567111/sqrt(a[i].f*a[i].f + a[i].h*a[i].h); a[i].e*=exp(-a[i].d); //fprintf(stderr,".g %f \n",a[i].g); if (a[i].f + a[i].g>1e-3){a[i].f = (a[i].f - a[i].g)*(a[i].f + a[i].g);} //fprintf(stderr,". i= %d i-4= %d gi-4 %f gi %f bi %f di %f \n",i,i-4,a[i-4].g,a[i].g,a[i].b,a[i].d); a[i].g = a[i-4].g + .1; //fprintf(stderr,". apres i= %d i-4= %d gi-4 %f gi %f bi %f di %f \n",i,i-4,a[i-4].g,a[i].g,a[i].b,a[i].d); //fprintf(stderr,".g %f \n",a[i].g); a[i].h = .3*a[i].h + .2; } } int main() { int i,j; float percent; clock_t tm1, tm2, tc1, tc2; double sum_main, sum; s_t *a; a=(s_t *)malloc(sizeof(s_t)*SIZE); tm1 = tm2 = tc1 = tc2 = sum = 0.0; /* Initialization */ tm1 = clock(); for (i=0; i<SIZE; i++){a[i].a=a[i].b=a[i].c=a[i].d=a[i].e=a[i].f=a[i].g=a[i].h=1./(i+1);} //fprintf(stderr,"%f %f %f %f\n",a[8].a,a[7].b,a[5].d,0.42*a[7].b+0.32*a[5].d); //wr(a); /* Computation */ for(i=0;i<100;i++) {//boucle temps tc1 =clock(); //fprintf(stderr,".g av compute %f \n",a[8].g); //for(j=0;j<2*8;j++){fprintf(stderr,"temps= %d j=%d a.b %f a.d %f \n", i, j, a[j].b, a[j].d);} compute(a); //wr(a); //for(j=0;j<2*8;j++){fprintf(stderr,"temps= %d j=%d a.a %f a.h %f \n", i, j, a[j].a, a[j].h);} tc2 =clock(); sum = sum + ( (double) (tc2-tc1) ) /CLOCKS_PER_SEC ; if((i % 10)==0 ){ percent = (i* (float) 100) / ((float) 99); fprintf(stderr,"\r TPS CODE= %f In progress %f %% ",sum, percent);fflush(stdout); } //fprintf(stderr,"."); //fprintf(stderr,"*** %f %f %f %f\n",a[8].a,a[7].b,a[5].d,0.42*a[7].b+0.32*a[5].d); } tm2 = clock(); sum_main = ((double) (tm2-tm1))/CLOCKS_PER_SEC; fprintf(stderr,"%f ",a[10].a); fprintf(stderr,"\n"); fprintf(stderr, "alloc a==s_t: %ld\n",sizeof(s_t)*SIZE ); /*for(i=0; i<SIZE; i++){ fprintf(stderr, "%d %f %f %f \n",i, a[i].a,a[i].b,a[i].c );} wr(a);*/ int echo=1; wr_time(echo, sum_main, sum); free(a); return 0; }
0
ALLM
ALLM/MULTI_COEURS/aos_C1.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define SIZE 50000000 #define BLOCK 8 #define QO SIZE/BLOCK typedef struct { float a,b,c,d,e,f,g,h; } s_t; typedef struct { float gtmp; } s_t_temp; void init_bd_gtmp(s_t_temp *btmp, s_t_temp *dtmp, int i){ int j, jj, jjj; j = (i-1)*BLOCK; for(jj=0; jj<BLOCK; jj++){ jjj = j+jj; btmp[jj].gtmp=dtmp[jj].gtmp=1./(jjj+1); //fprintf(stderr,"jjj= %d co= %f a[%d].a= %f \n",jjj, 1./(jjj+1), jj, a[jj].a); } } void init_s_t(s_t *a, int i){ int j, jj, jjj; j = (i-1)*BLOCK; for(jj=0; jj<BLOCK; jj++){ jjj = j+jj; a[jj].a=a[jj].b=a[jj].c=a[jj].d=a[jj].e=a[jj].f=a[jj].g=a[jj].h=1./(jjj+1); //fprintf(stderr,"jjj= %d co= %f a[%d].a= %f \n",jjj, 1./(jjj+1), jj, a[jj].a); } } void wr_time(int echo, double sum_main, double sum){ int j; FILE *fpp; fpp = fopen ("time.txt", "a"); if(echo == 0){fputs("temps cpu: main func compute \n", fpp );} else{fprintf(fpp, "aos_C1.c %f %f \n", sum_main, sum );} fclose(fpp); } void wr(s_t *a){ int j; FILE *fp; fp = fopen ("val_C1.txt", "a"); fputs("j .a .b .d \n", fp ); for(j=0; j<BLOCK; j++){ fprintf(fp, "%d %f %f %f \n",j, a[j].a,a[j].b,a[j].d ); } fclose(fp); } void compute(s_t *a) { int i; for (i=4; i<8; i++) {//boucle elements a[i].a=(a[i-1].b * 0.42 + a[i-3].d * .32); //fprintf(stderr,"B47 i=%d %f %f %f %f\n",i,a[i].a,a[i-1].b,a[i-3].d,0.42*a[i-1].b+0.32*a[i-3].d); a[i].b = a[i].c / 7.56+ a[i].f; a[i].c = a[i].d + a[i].g*a[i].d; a[i].d = .567111/sqrt(a[i].f*a[i].f + a[i].h*a[i].h); a[i].e*=exp(-a[i].d); if (a[i].f + a[i].g>1e-3) a[i].f = (a[i].f - a[i].g)*(a[i].f + a[i].g); a[i].g = a[i-4].g + .1; a[i].h = .3*a[i].h + .2; } } void compute_s_t(s_t *a, s_t_temp *gtmp, s_t_temp *btmp, s_t_temp *dtmp, int it) { int i, j; int temps; for(temps=0; temps<100; temps++){//boucle temps for(j=0;j<BLOCK-1;j++){btmp[j].gtmp=a[j].c / 7.56+ a[j].f;} for(j=0;j<BLOCK-3;j++){dtmp[j].gtmp=.567111/sqrt(a[j].f*a[j].f + a[j].h*a[j].h);} //a[i].a=(a[i-1].b * 0.42 + a[i-3].d * .32); a[0].a=(btmp[7].gtmp * 0.42 + dtmp[5].gtmp * .32); //fprintf(stderr,"$$temps= %d a7.b %f a5.d %f \n", temps, btmp[7].gtmp, dtmp[5].gtmp); //fprintf(stderr, "temps= %d \n",temps); //a[0].a=(a[3].b * 0.42 + a[1].d * .32); //fprintf(stderr, "%d %f %f %f \n",temps, a[0].a,a[3].b,a[1].d ); a[1].a=(btmp[0].gtmp * 0.42 + dtmp[6].gtmp * .32); a[2].a=(btmp[1].gtmp * 0.42 + dtmp[7].gtmp * .32); a[3].a=(btmp[2].gtmp * 0.42 + dtmp[0].gtmp * .32); //fprintf(stderr,"!!temps= %d a2.b %f a0.d %f \n", temps, a[2].b, a[0].d); a[4].a=(btmp[3].gtmp * 0.42 + dtmp[1].gtmp * .32); //fprintf(stderr, "%d %f %f %f \n",temps, a[4].a,a[3].b,a[1].d ); a[5].a=(btmp[4].gtmp * 0.42 + dtmp[2].gtmp * .32); //fprintf(stderr,"??temps= %d a4.b %f a0.d %f \n", temps, a[4].b, a[4].d); a[6].a=(btmp[5].gtmp * 0.42 + dtmp[3].gtmp * .32); a[7].a=(btmp[6].gtmp * 0.42 + dtmp[4].gtmp * .32); //a[i].b = a[i].c / 7.56+ a[i].f; a[0].b = a[0].c / 7.56+ a[0].f; a[1].b = a[1].c / 7.56+ a[1].f; a[2].b = a[2].c / 7.56+ a[2].f; a[3].b = a[3].c / 7.56+ a[3].f; a[4].b = a[4].c / 7.56+ a[4].f; a[5].b = a[5].c / 7.56+ a[5].f; a[6].b = a[6].c / 7.56+ a[6].f; a[7].b = a[7].c / 7.56+ a[7].f; //SWAP: //for(j=0;j<BLOCK;j++){btmp[j].gtmp=a[j].b;} //fprintf(stderr,"temps= %d a7.b %f a5.d %f \n", temps, a[7].b, a[5].d); //a[i].c = a[i].d + a[i].g*a[i].d; a[0].c = a[0].d + a[0].g*a[0].d; a[1].c = a[1].d + a[1].g*a[1].d; a[2].c = a[2].d + a[2].g*a[2].d; a[3].c = a[3].d + a[3].g*a[3].d; a[4].c = a[4].d + a[4].g*a[4].d; a[5].c = a[5].d + a[5].g*a[5].d; a[6].c = a[6].d + a[6].g*a[6].d; a[7].c = a[7].d + a[7].g*a[7].d; //a[i].d = .567111/sqrt(a[1].f*a[i].f + a[i].h*a[i].h); /*a[].d = .567111/sqrt(a[].f*a[].f + a[].h*a[].h);*/ a[0].d = .567111/sqrt(a[0].f*a[0].f + a[0].h*a[0].h); a[1].d = .567111/sqrt(a[1].f*a[1].f + a[1].h*a[1].h); a[2].d = .567111/sqrt(a[2].f*a[2].f + a[2].h*a[2].h); a[3].d = .567111/sqrt(a[3].f*a[3].f + a[3].h*a[3].h); a[4].d = .567111/sqrt(a[4].f*a[4].f + a[4].h*a[4].h); a[5].d = .567111/sqrt(a[5].f*a[5].f + a[5].h*a[5].h); a[6].d = .567111/sqrt(a[6].f*a[6].f + a[6].h*a[6].h); a[7].d = .567111/sqrt(a[7].f*a[7].f + a[7].h*a[7].h); //SWAP: // for(j=0;j<BLOCK;j++){dtmp[j].gtmp=a[j].d;} //a[i].e*=exp(-a[i].d); a[0].e *= exp(-a[0].d); a[1].e *= exp(-a[1].d); a[2].e *= exp(-a[2].d); a[3].e *= exp(-a[3].d); a[4].e *= exp(-a[4].d); a[5].e *= exp(-a[5].d); a[6].e *= exp(-a[6].d); a[7].e *= exp(-a[7].d); for(i=0; i<BLOCK; i++){ //if (a[i].f + gm[i].gtmp>1e-3){a[i].f = (a[i].f - gm[i].gtmp)*(a[i].f + gm[i].gtmp);} if (a[i].f + a[i].g>1e-3){a[i].f = (a[i].f - a[i].g)*(a[i].f + a[i].g);} } //a[i].g = a[i-4].g + .1; a[0].g = gtmp[0].gtmp + 0.1; a[1].g = gtmp[1].gtmp + 0.1; a[2].g = gtmp[2].gtmp + 0.1; a[3].g = gtmp[3].gtmp + 0.1; a[4].g = gtmp[4].gtmp + 0.1; a[5].g = gtmp[5].gtmp + 0.1; a[6].g = gtmp[6].gtmp + 0.1; a[7].g = gtmp[7].gtmp + 0.1; //gtmp[0:7].gtmp = a[0:7].g; /*gtmp[0].gtmp = a[4].g; gtmp[1].gtmp = a[5].g; gtmp[2].gtmp = a[6].g; gtmp[3].gtmp = a[7].g; gtmp[4].gtmp = a[4].g//+ .1; gtmp[5].gtmp = a[5].g//+ .1; gtmp[6].gtmp = a[6].g//+ .1; gtmp[7].gtmp = a[7].g//+ .1;*/ //a[i].h = .3*a[i].h + .2; a[0].h = .3*a[0].h + .2; a[1].h = .3*a[1].h + .2; a[2].h = .3*a[2].h + .2; a[3].h = .3*a[3].h + .2; a[4].h = .3*a[4].h + .2; a[5].h = .3*a[5].h + .2; a[6].h = .3*a[6].h + .2; a[7].h = .3*a[7].h + .2; //wr(a); //for(j=0;j<BLOCK;j++){fprintf(stderr,"temps= %d [8:15] j=%d a.a %f a.h %f \n", temps, j, a[j].a, a[j].h);} } } int main() { int i, j; float percent; int echo; clock_t tm1, tm2, tc1, tc2; double sum_main, sum; s_t *a; s_t_temp *gtmp, *btmp, *dtmp; a = (s_t *)malloc(sizeof(s_t)*BLOCK); gtmp = (s_t_temp *)malloc(sizeof(s_t_temp)*BLOCK); btmp = (s_t_temp *)malloc(sizeof(s_t_temp)*BLOCK); dtmp = (s_t_temp *)malloc(sizeof(s_t_temp)*BLOCK); tm1 = tm2 = tc1 = tc2 = sum = sum_main = 0.0; echo = 0; wr_time(echo, sum_main, sum); /* Initialization */ init_s_t(a, 1); //wr(a); //boucle temps for(i=0;i<100;i++){ /*fprintf(stderr,"temps= %d a7.b %f a5.d %f \n", i, a[7].b, a[5].d); fprintf(stderr,"!!temps= %d a2.b %f a0.d %f \n", i, a[2].b, a[0].d); fprintf(stderr,"??temps= %d a4.b %f a4.d %f \n", i, a[4].b, a[4].d);*/ compute(a); //wr(a); //for(j=0;j<BLOCK;j++){fprintf(stderr,"temps= %d [0:7] j=%d a.h %f a.f %f \n", i, j, a[j].a, a[j].h);} } tm1 = clock(); /* Computation */ for(i=2;i<QO+1;i++) {//boucle elements /*INITIALIZATION*/ btmp[7].gtmp = a[7].b; dtmp[7].gtmp = a[7].d; dtmp[6].gtmp = a[6].d; dtmp[5].gtmp = a[5].d; gtmp[0].gtmp = a[4].g; gtmp[1].gtmp = a[5].g; gtmp[2].gtmp = a[6].g; gtmp[3].gtmp = a[7].g; gtmp[4].gtmp = a[4].g+0.1; gtmp[5].gtmp = a[5].g+0.1; gtmp[6].gtmp = a[6].g+0.1; gtmp[7].gtmp = a[7].g+0.1; init_s_t(a, i); //init_bd_gtmp(btmp, dtmp, i-1); /*gtmp[0].gtmp = a[0].g+ .1; gtmp[1].gtmp = a[1].g+ .1; gtmp[2].gtmp = a[2].g+ .1; gtmp[3].gtmp = a[3].g+ .1; gtmp[4].gtmp = a[0].g+ .2; gtmp[5].gtmp = a[1].g+ .2; gtmp[6].gtmp = a[2].g+ .2; gtmp[7].gtmp = a[3].g+ .2;*/ //for(j=0;j<BLOCK;j++){fprintf(stderr,"B816 j gtmp.gtmp j=%d %f \n", j, gtmp[j].gtmp);} //fprintf(stderr,"a[%d].a= %f \n", 2, a[2].a); //gtmp[].gtmp = a[].g; //already swap by init_s_t?! tc1 =clock(); //for(j=0;j<BLOCK;j++){fprintf(stderr,"B816 av compute a.g j=%d %f \n", j, a[j].g);} compute_s_t(a, gtmp, btmp, dtmp, i); //for(j=0;j<BLOCK;j++){fprintf(stderr,"B816 j=%d %f %f \n", j, a[j].a, a[j].g);} //if(i==1){ //fprintf(stderr,"!!! a[%d].a= %f \n", 2, a[2].a); //fprintf(stderr,"%f ",a[2].a); //fprintf(stderr,"\n"); //} tc2 =clock(); if((i == 2) ){fprintf(stderr,"%f \n",a[2].a);} sum = sum + ( (double) (tc2-tc1) ) /CLOCKS_PER_SEC ; if((i % 10000)==0 ){ percent = (i* (float) 100) / ((float) QO); fprintf(stderr,"\r TPS CODE= %f In progress %f %% ",sum, percent);fflush(stdout); } } tm2 = clock(); sum_main = ((double) (tm2-tm1))/CLOCKS_PER_SEC; fprintf(stderr,"\n"); //fprintf(stderr,"%f ",a[2].a); //fprintf(stderr,"\n"); fprintf(stderr, "alloc a==s_t: %ld \n",sizeof(s_t)*BLOCK+3*sizeof(s_t_temp)*BLOCK ); /*for(i=0; i<SIZE; i++){ fprintf(stderr, "%d %f %f %f \n",i, a[i].a,a[i].b,a[i].c );} wr(a);*/ echo=1; wr_time(echo, sum_main, sum); free(a); free(gtmp); free(btmp); free(dtmp); return 0; }
0
ALLM
ALLM/NANIKA/nanika.py
from pathlib import Path import getopt, sys, os, shutil from langchain_community.document_loaders import ( DirectoryLoader, UnstructuredPDFLoader, TextLoader, PythonLoader, UnstructuredImageLoader, UnstructuredExcelLoader, UnstructuredWordDocumentLoader, UnstructuredXMLLoader, UnstructuredCSVLoader, UnstructuredPowerPointLoader, UnstructuredODTLoader, UnstructuredMarkdownLoader ) from langchain_community.embeddings import OllamaEmbeddings from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_community.vectorstores import Chroma #from langchain.indexes import VectorstoreIndexCreator from langchain.prompts import ChatPromptTemplate, PromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_community.chat_models import ChatOllama from langchain_core.runnables import RunnablePassthrough from langchain.retrievers.multi_query import MultiQueryRetriever def routerloader(obj): loader = [] accumulator = [] if os.path.isfile(obj): Fname = os.path.basename(obj) if Fname.endswith(".pdf"): loader = UnstructuredPDFLoader(str(obj), mode="single", strategy="hi_res", show_progress=True, use_multithreading=True) if Fname.endswith(".txt") or Fname.endswith(".py"): loader = TextLoader(obj, autodetect_encoding = True) # BEGIN F90 C .h CPP As TextLoader if Fname.endswith(".f90") or Fname.endswith(".c") or Fname.endswith(".h") or Fname.endswith(".cpp"): loader = TextLoader(obj, autodetect_encoding = True) # END F90 C .h CPP As TextLoader if Fname.endswith(".py"): loader = PythonLoader(obj) if Fname.endswith(".png") or Fname.endswith(".jpg"): loader = UnstructuredImageLoader(str(obj), mode="single", strategy="hi_res", show_progress=True, use_multithreading=True) if Fname.endswith(".xlsx") or Fname.endswith(".xls"): loader = UnstructuredExcelLoader(str(obj), mode="single", strategy="hi_res", show_progress=True, use_multithreading=True) if Fname.endswith(".odt"): loader = UnstructuredODTLoader(str(obj), mode="single", strategy="hi_res", show_progress=True, use_multithreading=True) if Fname.endswith(".csv"): loader = UnstructuredCSVLoader(str(obj), mode="single", strategy="hi_res", show_progress=True, use_multithreading=True) if Fname.endswith(".pptx"): loader = UnstructuredPowerPointLoader(str(obj), mode="single", strategy="hi_res", show_progress=True, use_multithreading=True) if Fname.endswith(".md"): loader = UnstructuredMarkdownLoader(str(obj), mode="single", strategy="hi_res", show_progress=True, use_multithreading=True) if Fname.endswith(".org"): loader = UnstructuredOrgModeLoader(str(obj), mode="single", strategy="hi_res", show_progress=True, use_multithreading=True) accumulator.extend(loader.load()) elif os.path.isdir(obj): if any(File.endswith(".pdf") for File in os.listdir(obj)): abc={'mode': "single", 'strategy': "hi_res"} loader = DirectoryLoader( obj, glob="**/*.pdf", loader_cls=UnstructuredPDFLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) if any(File.endswith(".txt") for File in os.listdir(obj)): abc={'autodetect_encoding': True} loader = DirectoryLoader( obj, glob="**/*.txt", loader_cls=TextLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) # BEGIN F90 C .h CPP As TextLoader if any(File.endswith(".f90") for File in os.listdir(obj)): abc={'autodetect_encoding': True} loader = DirectoryLoader( obj, glob="**/*.f90", loader_cls=TextLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) if any(File.endswith(".c") for File in os.listdir(obj)): abc={'autodetect_encoding': True} loader = DirectoryLoader( obj, glob="**/*.c", loader_cls=TextLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) if any(File.endswith(".h") for File in os.listdir(obj)): abc={'autodetect_encoding': True} loader = DirectoryLoader( obj, glob="**/*.h", loader_cls=TextLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) if any(File.endswith(".cpp") for File in os.listdir(obj)): abc={'autodetect_encoding': True} loader = DirectoryLoader( obj, glob="**/*.cpp", loader_cls=TextLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) # END F90 C .h CPP As TextLoader if any(File.endswith(".py") for File in os.listdir(obj)): loader = DirectoryLoader( obj, glob="**/*.py", loader_cls=PythonLoader, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) if any(File.endswith(".png") for File in os.listdir(obj)): abc={'mode': "single", 'strategy': "hi_res"} loader = DirectoryLoader( obj, glob="**/*.png", loader_cls=UnstructuredImageLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) if any(File.endswith(".jpg") for File in os.listdir(obj)): abc={'mode': "single", 'strategy': "hi_res"} loader = DirectoryLoader( obj, glob="**/*.jpg", loader_cls=UnstructuredImageLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) if any(File.endswith(".xls") for File in os.listdir(obj)): abc={'mode': "single", 'strategy': "hi_res"} loader = DirectoryLoader( obj, glob="**/*.xls", loader_cls=UnstructuredExcelLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) if any(File.endswith(".xlsx") for File in os.listdir(obj)): abc={'mode': "single", 'strategy': "hi_res"} loader = DirectoryLoader( obj, glob="**/*.xlsx", loader_cls=UnstructuredExcelLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) if any(File.endswith(".odt") for File in os.listdir(obj)): abc={'mode': "single", 'strategy': "hi_res"} loader = DirectoryLoader( obj, glob="**/*.odt", loader_cls=UnstructuredODTLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) if any(File.endswith(".csv") for File in os.listdir(obj)): abc={'mode': "single", 'strategy': "hi_res"} loader = DirectoryLoader( obj, glob="**/*.csv", loader_cls=UnstructuredCSVLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) if any(File.endswith(".pptx") for File in os.listdir(obj)): abc={'mode': "single", 'strategy': "hi_res"} loader = DirectoryLoader( obj, glob="**/*.pptx", loader_cls=UnstructuredPowerPointLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) if any(File.endswith(".md") for File in os.listdir(obj)): abc={'mode': "single", 'strategy': "hi_res"} loader = DirectoryLoader( obj, glob="**/*.md", loader_cls=UnstructuredMarkdownLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) if any(File.endswith(".org") for File in os.listdir(obj)): abc={'mode': "single", 'strategy': "hi_res"} loader = DirectoryLoader( obj, glob="**/*.org", loader_cls=UnstructuredOrgModeLoader, loader_kwargs=abc, show_progress=True, use_multithreading=True ) accumulator.extend(loader.load()) return accumulator def loaddata(data_path): documents = [] for data in data_path: documents.extend(routerloader(data)) return documents def remove_blankline(d): text = d.page_content.replace('\n\n','\n') d.page_content = text return d def initfromcmdlineargs(): PDF_ROOT_DIR = "" IDOC_PATH = [] VDB_PATH = "./default_chroma_vdb" COLLECTION_NAME = "default_collection_name" MODEL_NAME = "" EMBEDDING_NAME = "" REUSE_VDB = False DISPLAY_DOC = False argumentlist = sys.argv[1:] options = "hm:e:i:v:c:r:d:" long_options = ["help", "model_name=", "embedding_name=", "inputdocs_path=", "vdb_path=", "collection_name=", "reuse=", "display_doc="] try: arguments, values = getopt.getopt(argumentlist, options, long_options) for currentArgument, currentValue in arguments: print("currArg ", currentArgument, " currVal", currentValue) if currentArgument in ("-h", "--help"): print ("Displaying Help:") print ("-h or --help to get this help msg") print ("-m or --model_name name of the model used, ex:phi3") print ("-e or --embedding_name name of the embedding model used, ex:nomic-embed-text") print ("-i or --inputdocs_path path list between \" \" to folders or files to be used for RAG") print ("-v or --vdb_path path to the directory used as a vector database") print ("-c or --collection_name name of the vector database collection") print ("Collection name Rules:") print ("(1) contains 3-63 characters") print ("(2) starts and ends with an alphanumeric character") print ("(3) otherwise contains only alphanumeric characters, underscores or hyphens (-)") print ("(4) contains no two consecutive periods (..) and") print ("(5) is not a valid IPv4 address") print ("-r or --reuse str True or False reuse vector database") print("-d or --display_doc str Tur or False whether or not to display partially input documents") print("Command line arguments example:") print("python --model_name MyModelName --embedding_name MyEmbeddingModel \ ") print("--inputdocs_path \"My/Path/To/folder1 My/Path/To/folder2 My/Path/To/file1\" \ ") print("--collection_name MyCollectionName \ ") print("--reuse False --display-doc False") exit() elif currentArgument in ("-m", "--model_name"): MODEL_NAME = currentValue elif currentArgument in ("-e", "--embedding_name"): EMBEDDING_NAME = currentValue elif currentArgument in ("-i", "--inputdocs_path"): for i in currentValue.split(" "): if (len(i) != 0): if (os.path.isfile(i)) or ((os.path.isdir(i)) and (len(os.listdir(i)) != 0)): IDOC_PATH.append(Path(i)) elif currentArgument in ("-v", "--vdb_path"): VDB_PATH = Path(currentValue) elif currentArgument in ("-c", "--collection_name"): COLLECTION_NAME = currentValue elif currentArgument in ("-r", "--reuse"): if currentValue.casefold() == "true": REUSE_VDB = True else: REUSE_VDB = False elif currentArgument in ("-d", "--display_doc"): if currentValue.casefold() == "true": DISPLAY_DOC = True else: DISPLAY_DOC = False return MODEL_NAME, EMBEDDING_NAME, IDOC_PATH, VDB_PATH, COLLECTION_NAME, REUSE_VDB, DISPLAY_DOC except getopt.error as err: print (str(err)) exit() def create_vdb(splitted_data, embedding, vdb_path, collection_name, reuse_vdb): """Create a vector database from the documents""" Isvectordb = False if vdb_path.exists(): if any(vdb_path.iterdir()): if reuse_vdb == True: vectordb = Chroma(persist_directory=str(vdb_path), embedding_function=embedding, collection_name=collection_name) print("vectordb._collection.count() ", vectordb._collection.count()) Isvectordb = True print(f"vector database REUSED in {vdb_path}") else: shutil.rmtree(str(vdb_path)) print(f"vector database REMOVED in {vdb_path}") else: vdb_path.mkdir(parents=True) if Isvectordb == False: vectordb = Chroma.from_documents( documents=splitted_data, embedding=embedding, persist_directory=str(vdb_path), # Does not accept Path collection_name=collection_name ) print(f"vector database CREATED in {vdb_path}") return vectordb #----------------------------------------------------------------------------------------------------------# #----------------------------------------------------------------------------------------------------------# print("#-----------------------------------#") print("# INPUTS ARGS #") print("#-----------------------------------#") MODEL_NAME, EMBEDDING_NAME, IDOC_PATH, VDB_PATH, COLLECTION_NAME, REUSE_VDB, DISPLAY_DOC = initfromcmdlineargs() print("MODEL NAME::", MODEL_NAME) print("EMBEDDING NAME::", EMBEDDING_NAME) print("INPUT DOCS PATH::", IDOC_PATH) print("VDB PATH::", VDB_PATH) print("COLLECTION NAME::", COLLECTION_NAME) print("REUSE VDB ::", REUSE_VDB) print("DISPLAY DOC ::", DISPLAY_DOC) print("#-----------------------------------#") print("# STARTING DATA LOAD AND SPLIT #") print("#-----------------------------------#") splitted_data = None if REUSE_VDB is False: # Load datas documents = loaddata(IDOC_PATH) print("documents length::", len(documents)) if DISPLAY_DOC is True: for i in range(len(documents)): print("Printing document ", i, " :") print(documents[i].page_content[0:300]) documents = [remove_blankline(d) for d in documents] if DISPLAY_DOC is True: for i in range(len(documents)): print("Printing document after remove_blankline() ", i, " :") print(documents[i].page_content[0:300]) # Split and chunk splitter = RecursiveCharacterTextSplitter( chunk_size=300, chunk_overlap=30, separators=["\n\n", "\n", r"(?<=\. )", " ", "", "\u200b","\uff0c","\u3001","\uff0e","\u3002",] ) splitted_data = splitter.split_documents(documents) if DISPLAY_DOC is True: for i in range(len(splitted_data)): print("Printing splitted_data ", i, " :") print(splitted_data[i].page_content[0:300]) # Split and chunk print("#-----------------------------------#") print("# STARTING VECTOR DATABASE #") print("#-----------------------------------#") # Embedding Using Ollama ollama_embeddings = OllamaEmbeddings( model=EMBEDDING_NAME, show_progress=True ) # Add to vector database vectordb = create_vdb(splitted_data, ollama_embeddings, Path(VDB_PATH), COLLECTION_NAME, REUSE_VDB) print("vectordb._collection.count() ", vectordb._collection.count()) print("#-----------------------------------#") print("# STARTING LLM AND PROMPT RAG #") print("#-----------------------------------#") # LLM model local_model = MODEL_NAME llm = ChatOllama(model=local_model, temperature=0) QUERY_PROMPT = PromptTemplate( input_variables=["question"], template="""You are an AI language model assistant. Your task is to generate four different versions of the given user question to retrieve relevant documents from a vector database. By generating multiple perspectives on the user question, your goal is to help the user overcome some of the limitations of the distance-based similarity search. Provide these alternative questions separated by newlines. Original question: {question}""", ) retriever = MultiQueryRetriever.from_llm( vectordb.as_retriever(), llm, prompt=QUERY_PROMPT ) # RAG prompt template = """Answer the question based ONLY on the following context: {context} Question: {question} """ print("*"*20) prompt = ChatPromptTemplate.from_template(template) print("*"*20) chain = ( {"context": retriever, "question": RunnablePassthrough()} | prompt | llm | StrOutputParser() ) question = "" print("#-----------------------------------#") print("# STARTING RAG Q&A #") print("#-----------------------------------#") question = "" while True: print("*"*20) print("Enter a QUESTION: (to exit enter q or quit)") question = input("") if question.casefold() == "q" or question.casefold() == "quit": print("End QA") break else: response = chain.invoke(question) print(response)
0
ALLM/RAPPORT_STOKES_CODE_FREEFEM
ALLM/RAPPORT_STOKES_CODE_FREEFEM/CT1_PENA_ADAPT/CT1_PENA_ADAPT.edp.edp
// SOLVE STOKES EQUATION * // FOR AN INCOMPRESSIBLE FLOW VISCOUS FUID * // Re<<1 * // Stationary Mode * //*********************************************************************** //load "parms_FreeFem" // Trace de l'éxécution dans un fichier ofstream ufile("LOG_CT1_PENA_ADAPT_UMFPACK.txt"); ofstream gfile("LOG_CT1_PENA_ADAPT_GMRES.txt"); int Gcpt; int Ucpt; string knu; //***************************************************************************** // *** SET PARAMETER FLOW: real mu=1.0; //DYNAMIQUE VISCOSITY real Uo=1.0; //CARACTERISTIC SPEED // *** DEFINE FUNCTION VOL: real f1=1.0,f2=1.0; // *** DEFINE FUNCTION VOL: int DKSP; //DIM KRYLOV (<=>m) real PREP; //tol solver int IDPREP; //DUAL DE PREP POUR SPLOT real[int] TPREP(4); //precision du solver int[int] DTPREP(4); //et dual du tableau pour splot TPREP[0] = 1.0e-6; DTPREP[0]=4; TPREP[1] = 1.0e-8; DTPREP[1]=3; TPREP[2] = 1.0e-10; DTPREP[2]=2; TPREP[3] = 1.0e-12; DTPREP[3]=1; int S1 = TPREP.n; //ON STOCK LA SIZE real[int] perturbation(9); //pour la perturbation, int[int] Dperturbation(9); // et Dperturbation pour les splots (chgt de var) perturbation[0]=10.0; Dperturbation[0]=9; perturbation[1]=1.0; Dperturbation[1]=8; perturbation[2]=0.1; Dperturbation[2]=7; perturbation[3]=0.001; Dperturbation[3]=6; perturbation[4]=0.000015; Dperturbation[4]=5; perturbation[5]=0.00001; Dperturbation[5]=4; perturbation[6]=0.0000015; Dperturbation[6]=3; perturbation[7]=0.000001; Dperturbation[7]=2; perturbation[8]=0.0000001; Dperturbation[8]=1; int S2 = perturbation.n; real tmps1,tmps2; // TEMPS SOLVER for(int NUMSOLVER=0;NUMSOLVER<2;++NUMSOLVER) //BOUCLE SUR LE SOLVER, 0->UMFPACK & 1->GMRES {//BOUCLE NUMSOLVER for(int iprep=0; iprep<S1; iprep=iprep+1) { //BOUCLE PRECISION DU SOLVER GMRES PREP = TPREP[iprep]; IDPREP = DTPREP[iprep]; for(int iperturbation=0; iperturbation<S2; ++iperturbation) { //BOUCLE SUR LA PERTURBATION int PTEDGE=10; //POINTS SEED PAR COTE DU MESH // *** DEFINE MESH BY BORDER THEN BY BUILD: mesh CT1; // SIMILI OF REF TRIANGULAR MESH border LOW(t=0,1) {x=t;y=0;label=1;}; // LOWER BORDER border DIAG(t=1,0) {x=t;y=1-t;label=2;}; // DIAG BORDER border LEFT(t=1,0) {x=0;y=t;label=3;}; // LEFT BORDER CT1=buildmesh( LOW(PTEDGE) + DIAG(PTEDGE+PTEDGE/3) + LEFT(PTEDGE) ); fespace Vh(CT1, P1b); //FOR VITESSE Vh u1, u2; Vh v1, v2; //v is test function, u true unknow fespace Qh(CT1,P1); //FOR PRESSURE Qh p; Qh q; for(int k=0;k<4;++k) //BOUCLE SUR MESH { if((NUMSOLVER==0 & iprep==0) | (NUMSOLVER==1)) { if(k==0){knu="k_zero.eps";} if(k==1){knu="k_un.eps";} if(k==2){knu="k_deux.eps";} if(k==3){knu="k_trois.eps";} plot(LOW(PTEDGE)+DIAG(PTEDGE)+LEFT(PTEDGE)); plot(CT1, ps=knu); p=0.0; q=0; u1=0; v1=0; u2=0; v2=0; macro GRAD(u) [dx(u), dy(u)]// macro DIV(u1,u2) (dx(u1)+dy(u2))// if(NUMSOLVER==0 & iprep==0) { DKSP = Vh.ndof+Qh.ndof; // dimKrylov here also the real Vh.ndof+Qh.ndof for the current mesh tmps1 = clock(); problem STOKES([u1,u2,p],[v1,v2,q],solver=UMFPACK)=int2d(CT1)(mu*(GRAD(u1)' *GRAD(v1)+GRAD(u2)' *GRAD(v2)) -p*DIV(v1,v2)-DIV(u1,u2)*q-p*q*perturbation[iperturbation])+int2d(CT1)(f1*v1+f2*v2)+on(1,2,3,u1=x,u2=-y); STOKES; tmps2 = clock(); if(k!=4){CT1 = adaptmesh(CT1,[u1,u2],p,err=0.015,nbvx=2000);} } else if(NUMSOLVER == 1) { DKSP = Vh.ndof+Qh.ndof; // dimKrylov here also the real Vh.ndof+Qh.ndof for the current mesh tmps1 = clock(); problem STOKES([u1,u2,p],[v1,v2,q],solver=GMRES,dimKrylov=DKSP,eps=PREP,nbiter=Vh.ndof+2*Qh.ndof)=int2d(CT1)(mu*(GRAD(u1)' *GRAD(v1)+GRAD(u2)' *GRAD(v2)) -p*DIV(v1,v2)-DIV(u1,u2)*q-p*q*perturbation[iperturbation])+int2d(CT1)(f1*v1+f2*v2)+on(1,2,3,u1=x,u2=-y); STOKES; tmps2 = clock(); if(k!=4){CT1 = adaptmesh(CT1,[u1,u2],p,err=0.01,nbvx=2000);} } //SOLUTION ANALYTIQUE Vh ue1,ue2; Qh pe; ue1=x; ue2=-y; pe=x+y-2.0/3.0; if(NUMSOLVER==0 & iprep==0) { // Calcul des erreurs real normeL2, errL2, errPL2, NpL2; normeL2 = sqrt( int2d(CT1) ( (ue1)^2+(ue2)^2 ) ); errL2 = sqrt( int2d(CT1) ( (u1-ue1)^2+(u2-ue2)^2 ) ); NpL2 = sqrt( int2d(CT1)((pe)^2)); errPL2 = sqrt( int2d(CT1) (p-pe)^2); cout<< "UMFPACK " << perturbation[iperturbation] << " " << DKSP << " " << errL2/normeL2 << " " << errPL2/NpL2 << " " << tmps2-tmps1 <<endl; cout << " UMFPACK ERR L2 RELATIVE=" << "sur la vitesse:" << errL2/normeL2 << endl; cout << " UMFPACK ERR L2 RELATIVE=" << "sur la pression:" << errPL2/NpL2 <<endl; //ufile << perturbation[iperturbation] << " " << Vh.ndof+Qh.ndof << " " << errL2/normeL2 << " " << errPL2/NpL2 << " " << tmps2-tmps1 <<endl; ufile << Dperturbation[iperturbation] << " " << DKSP << " " << errL2/normeL2 << " " << errPL2/NpL2 << " " << tmps2-tmps1 <<endl; } else if(NUMSOLVER == 1) { // Calcul des erreurs real normeL2, errL2, errPL2, NpL2; normeL2 = sqrt( int2d(CT1) ( (ue1)^2+(ue2)^2 ) ); errL2 = sqrt( int2d(CT1) ( (u1-ue1)^2+(u2-ue2)^2 ) ); NpL2 = sqrt( int2d(CT1)((pe)^2)); errPL2 = sqrt( int2d(CT1) (p-pe)^2); //cout << Vh.ndof+Qh.ndof <<" "<< errL2/normeL2 <<" "<< errPL2/NpL2<<" "<< tmps2-tmps1 << " " << perturbation[iperturbation] << " DIMKRYLOV= "<< DKSP << " eps= "<<PREP<<endl; //gfile << Vh.ndof+Qh.ndof <<" "<< errL2/normeL2 <<" "<< errPL2/NpL2<<" "<< tmps2-tmps1<< " " << perturbation[iperturbation] << " DIMKRYLOV= "<< DKSP << " eps= "<<PREP<<endl; cout <<"GMRES " << PREP << " " << perturbation[iperturbation] << " " << DKSP << " " << DKSP << " " << errL2/normeL2 << " " << errPL2/NpL2 << " " << tmps2-tmps1 <<endl; cout << " GMRES ERR L2 RELATIVE=" << "sur la vitesse:" << errL2/normeL2 << endl; cout << " GMRES ERR L2 RELATIVE=" << "sur la pression:" << errPL2/NpL2 <<endl; gfile << IDPREP << " " << Dperturbation[iperturbation] << " " << DKSP << " " << DKSP << " " << errL2/normeL2 << " " << errPL2/NpL2 << " " << tmps2-tmps1 <<endl; } } }//FIN BOUCLE mesh if(NUMSOLVER==0 & iprep==0){ ufile <<" "<<endl; ufile <<" "<<endl;} }//FIN BOUCLE PERTURBATION if(NUMSOLVER==1){ gfile <<" "<<endl; gfile <<" "<<endl;} }//FIN BOUCLE Precision }//FIN BOUCLE NUMSOLVER Gcpt = S1 * S2;//= size(TPREP)*size(PERTURBATION) Ucpt = S2;
0
ALLM/RAPPORT_STOKES_CODE_FREEFEM
ALLM/RAPPORT_STOKES_CODE_FREEFEM/CT1_PENA_REG/stokes_CT1_pen.edp
// SOLVE STOKES EQUATION * // FOR AN INCOMPRESSIBLE FLOW VISCOUS FUID * // Re<<1 * // Stationary Mode * //*********************************************************************** //load "parms_FreeFem" // Trace de l'éxécution dans un fichier ofstream ufile("LOG_CT1_PENA_UMFPACK.txt"); ofstream gfile("LOG_CT1_PENA_GMRES.txt"); int Gcpt; int Ucpt; string knu; //***************************************************************************** // *** SET PARAMETER FLOW: real mu=1.0; //DYNAMIQUE VISCOSITY real Uo=1.0; //CARACTERISTIC SPEED // *** DEFINE FUNCTION VOL: real f1=1.0,f2=1.0; // *** DEFINE FUNCTION VOL: int DKSP; //DIM KRYLOV (<=>m) real PREP; //tol solver int IDPREP; //DUAL DE PREP POUR SPLOT real[int] TPREP(4); //precision du solver int[int] DTPREP(4); //et dual du tableau pour splot TPREP[0] = 1.0e-6; DTPREP[0]=4; TPREP[1] = 1.0e-8; DTPREP[1]=3; TPREP[2] = 1.0e-10; DTPREP[2]=2; TPREP[3] = 1.0e-12; DTPREP[3]=1; int S1 = TPREP.n; //ON STOCK LA SIZE real[int] perturbation(12); //pour la perturbation, int[int] Dperturbation(12); // et Dperturbation pour les splots (chgt de var) perturbation[0]=10.0; Dperturbation[0]=9; perturbation[1]=1.0; Dperturbation[1]=8; perturbation[2]=0.1; Dperturbation[2]=7; perturbation[3]=0.001; Dperturbation[3]=6; perturbation[4]=0.000015; Dperturbation[4]=5; perturbation[5]=0.00001; Dperturbation[5]=4; perturbation[6]=0.0000015; Dperturbation[6]=3; perturbation[7]=0.000001; Dperturbation[7]=2; perturbation[8]=0.0000001; Dperturbation[8]=1; perturbation[9]=0.00000001; Dperturbation[9]=0; perturbation[10]=0.000000001; Dperturbation[10]=-1; perturbation[11]=0.0000000001; Dperturbation[11]=-2; int S2 = perturbation.n; real tmps1,tmps2; // TEMPS SOLVER //***************************************************************************** // *** SET MESH: //***************************************************************************** // *** SET SEED MESH: //PREP = 1.0e-6; for(int NUMSOLVER=0;NUMSOLVER<2;++NUMSOLVER) //BOUCLE SUR LE SOLVER, 0->UMFPACK & 1->GMRES {//BOUCLE NUMSOLVER for(int iprep=0; iprep<S1; iprep=iprep+1) { //BOUCLE PRECISION DU SOLVER GMRES PREP = TPREP[iprep]; IDPREP = DTPREP[iprep]; for(int iperturbation=0; iperturbation<8; ++iperturbation)//S2 { //BOUCLE SUR LA PERTURBATION for(int k=0;k<4;k=k+1) //BOUCLE SUR MESH: k in [|0;3|] { if(k==0){knu="k_zero.eps";} if(k==1){knu="k_un.eps";} if(k==2){knu="k_deux.eps";} if(k==3){knu="k_trois.eps";} int PTEDGE=k*10+10; //SEED utilisée pour le nbr de point par border //POINTS SEED PAR COTE DU MESH // *** DEFINE MESH BY BORDER THEN BY BUILD: mesh CT1; // SIMILI OF REF TRIANGULAR MESH border LOW(t=0,1) {x=t;y=0;label=1;}; // LOWER BORDER border DIAG(t=1,0) {x=t;y=1-t;label=2;}; // DIAG BORDER border LEFT(t=1,0) {x=0;y=t;label=3;}; // LEFT BORDER CT1=buildmesh( LOW(PTEDGE) + DIAG(PTEDGE+PTEDGE/3) + LEFT(PTEDGE) ); //border DIAG a une seed differente pour equilibrage(=>maillage homogène) plot(LOW(PTEDGE)+DIAG(PTEDGE)+LEFT(PTEDGE)); plot(CT1, ps=knu); // *** END SET MESH. //****************************************************************************** //****************************************************************************** // *** CALLING MIXT SPACE WITH STABLE ELEM: fespace Vh(CT1, P1b); //FOR VITESSE Vh u1, u2; Vh v1, v2; //v is test function, u true unknow fespace Qh(CT1,P1); //FOR PRESSURE Qh p; Qh q; //p=0.0; //q is test function, p true unknow // *** CONSTRUCTION OF STOKES PB: // *** 1ere METHOD TO DEFINE AND SOLVE STOKES: on utilise plutot la seconde méthode /*problem STOKES([u1,u2,p],[v1,v2,q])=int2d(CT1)(mu*(dx(u1)*dx(v1)+dy(u1)*dy(v1)+dx(u2)*dx(v2)+dy(u2)*dy(v2)) -p*(dx(v1)+dy(v2))-q*(dx(u1)+dy(u2)))+int2d(CT1)((p*q)*0.001 ) +int2d(CT1) (f1*v1+f2*v2)+on(1,2,3,u1=0.0,u2=0.0);*/ // *** 2nd METHOD TO DEFINE AND SOLVE STOKES:VIA MACRO p=0.0; macro GRAD(u) [dx(u), dy(u)]// macro DIV(u1,u2) (dx(u1)+dy(u2))// if(NUMSOLVER==0 & iprep==0) { tmps1 = clock(); problem STOKES([u1,u2,p],[v1,v2,q],solver=UMFPACK)=int2d(CT1)(mu*(GRAD(u1)' *GRAD(v1)+GRAD(u2)' *GRAD(v2)) -p*DIV(v1,v2)-DIV(u1,u2)*q-p*q*perturbation[iperturbation])+int2d(CT1)(f1*v1+f2*v2)+on(1,2,3,u1=x,u2=-y); STOKES; tmps2 = clock(); } else if(NUMSOLVER == 1) { DKSP = Vh.ndof+Qh.ndof; // dimKrylov tmps1 = clock(); problem STOKES([u1,u2,p],[v1,v2,q],solver=GMRES,dimKrylov=DKSP,eps=PREP,nbiter=2*Vh.ndof+2*Qh.ndof)=int2d(CT1)(mu*(GRAD(u1)' *GRAD(v1)+GRAD(u2)' *GRAD(v2)) -p*DIV(v1,v2)-DIV(u1,u2)*q-p*q*perturbation[iperturbation])+int2d(CT1)(f1*v1+f2*v2)+on(1,2,3,u1=x,u2=-y); STOKES; tmps2 = clock(); } // for(int i=0;i<u1[].n;++i){ // cout<<u1[][i]<<" "<<u2[][i]<<endl;} //plot(u1, fill=true,value=true,boundary=true,wait=true); //plot([u1,u2],p,ps="stokes_exple.eps",value=true) ; //SOLUTION ANALYTIQUE Vh ue1,ue2; Qh pe; ue1=x; ue2=-y; //for (int i=0; i<ue1.n;i++) // cout << "ue1" << " " << ue1[][i] << endl; pe=x+y-2.0/3.0; //plot([ue1,ue2], fill=true,value=true,boundary=true,wait=true); //plot(pe, cmm="Pressure"); if(NUMSOLVER==0 & iprep==0) { // Calcul des erreurs real normeL2, errL2, errPL2, NpL2; normeL2 = sqrt( int2d(CT1) ( (ue1)^2+(ue2)^2 ) ); errL2 = sqrt( int2d(CT1) ( (u1-ue1)^2+(u2-ue2)^2 ) ); NpL2 = sqrt( int2d(CT1)((pe)^2)); errPL2 = sqrt( int2d(CT1) (p-pe)^2); cout<< "UMFPACK " << perturbation[iperturbation] << " " << Vh.ndof+Qh.ndof << " " << errL2/normeL2 << " " << errPL2/NpL2 << " " << tmps2-tmps1 <<endl; cout << " UMFPACK ERR L2 RELATIVE=" << "sur la vitesse:" << errL2/normeL2 << endl; cout << " UMFPACK ERR L2 RELATIVE=" << "sur la pression:" << errPL2/NpL2 <<endl; //ufile << perturbation[iperturbation] << " " << Vh.ndof+Qh.ndof << " " << errL2/normeL2 << " " << errPL2/NpL2 << " " << tmps2-tmps1 <<endl; ufile << Dperturbation[iperturbation] << " " << Vh.ndof+Qh.ndof << " " << errL2/normeL2 << " " << errPL2/NpL2 << " " << tmps2-tmps1 <<endl; } else if(NUMSOLVER == 1) { // Calcul des erreurs real normeL2, errL2, errPL2, NpL2; normeL2 = sqrt( int2d(CT1) ( (ue1)^2+(ue2)^2 ) ); errL2 = sqrt( int2d(CT1) ( (u1-ue1)^2+(u2-ue2)^2 ) ); NpL2 = sqrt( int2d(CT1)((pe)^2)); errPL2 = sqrt( int2d(CT1) (p-pe)^2); //cout << Vh.ndof+Qh.ndof <<" "<< errL2/normeL2 <<" "<< errPL2/NpL2<<" "<< tmps2-tmps1 << " " << perturbation[iperturbation] << " DIMKRYLOV= "<< DKSP << " eps= "<<PREP<<endl; //gfile << Vh.ndof+Qh.ndof <<" "<< errL2/normeL2 <<" "<< errPL2/NpL2<<" "<< tmps2-tmps1<< " " << perturbation[iperturbation] << " DIMKRYLOV= "<< DKSP << " eps= "<<PREP<<endl; cout <<"GMRES " << PREP << " " << perturbation[iperturbation] << " " << Vh.ndof+Qh.ndof << " " << DKSP << " " << errL2/normeL2 << " " << errPL2/NpL2 << " " << tmps2-tmps1 <<endl; cout << " GMRES ERR L2 RELATIVE=" << "sur la vitesse:" << errL2/normeL2 << endl; cout << " GMRES ERR L2 RELATIVE=" << "sur la pression:" << errPL2/NpL2 <<endl; gfile << IDPREP << " " << Dperturbation[iperturbation] << " " << Vh.ndof+Qh.ndof << " " << DKSP << " " << errL2/normeL2 << " " << errPL2/NpL2 << " " << tmps2-tmps1 <<endl; } }//FIN BOUCLE mesh if(NUMSOLVER==0 & iprep==0){ ufile <<" "<<endl; ufile <<" "<<endl;}//pour faire des index pour gnuplot }//FIN BOUCLE PERTURBATION if(NUMSOLVER==1){ gfile <<" "<<endl; gfile <<" "<<endl;}//pour faire des index pour gnuplot }//FIN BOUCLE Precision }//FIN BOUCLE NUMSOLVER Gcpt = S1 * S2;//= size(TPREP)*size(PERTURBATION) Ucpt = S2;
0
ALLM/RAPPORT_STOKES_CODE_FREEFEM
ALLM/RAPPORT_STOKES_CODE_FREEFEM/CT1_UZAWA_REG_ADAPT/stokes_CT1_uzawa_RETRY.edp
/******************************************************************* DÉFINITION DES ESPACES ET DES VARIABLES ********************************************************************/ ofstream file("LOG_CT1_UZAWA.txt"); //Définition des opérateurs utiles à la résolution macro Grad(u) [dx(u),dy(u)] //EOM macro Div(u1,u2) (dx(u1)+dy(u2)) //EOM /* -Delta u + gradP = 0 div u =0 */ string knu; real tmps1; real tmps2; real[int] prep(2); prep[0]=1e-6; prep[1]=1e-12; for(int iprep=0;iprep<2;++iprep)//boucle precision { for(int k=0;k<5;++k)//boucle mesh { if(k==0){knu="k_zero.eps";} if(k==1){knu="k_un.eps";} if(k==2){knu="k_deux.eps";} if(k==3){knu="k_trois.eps";} if(k==4){knu="k_quatre.eps";} int PTEDGE=10+10*k; //POINTS SEED PAR COTE DU MESH // *** DEFINE MESH BY BORDER THEN BY BUILD: mesh Th; // SIMILI OF REF TRIANGULAR MESH border LOW(t=0,1) {x=t;y=0;label=1;}; // LOWER BORDER border DIAG(t=1,0) {x=t;y=1-t;label=2;}; // DIAG BORDER border LEFT(t=1,0) {x=0;y=t;label=3;}; // LEFT BORDER Th=buildmesh( LOW(PTEDGE) + DIAG(PTEDGE+PTEDGE/3) + LEFT(PTEDGE) ); plot(Th, wait=false ,ps=knu); real AreaDomain=Th.area; // parameter in the Uzawa method, we define the value as 1 here real alpha = 1; //alpha = wopt = 1/(1+beta) //beta==1 real nu=1.0; //VISCOSITE DYNAMIQUE fespace Uh(Th,[P1b,P1b]); // fonction space for u=(u1,u2) fespace Ph(Th,P1); // function space for p fespace Ph0(Th,P0); Uh [u1,u2],[v1,v2],[usave1,usave2]; Ph p, q; Uh [uh1,uh2],[uvisu1,uvisu2]; Ph ph,pvisu; // Setting for the analytic solution real beta = 0.44; // to be change with each different case func ue1= x; func ue2= -y; func pe= x+y-(2./3.); func dxue1= 1.0; func dyue1= 0.0; func dxue2= 0.0; func dyue2= -1.0; func f1= 1; func f2= 1; [uvisu1,uvisu2]=[ue1,ue2]; pvisu=pe; // variational formulation to define: varf a([u1,u2],[v1,v2])=int2d(Th)(Grad(u1)'*Grad(v1)+Grad(u2)'*Grad(v2))+int2d(Th)(f1*v1+f2*v2) +on(1,2,3,u1=ue1,u2=ue2); varf bc1([u1,u2],[v1,v2])=on(1,2,3,u1=1,u2=1); varf b([u1,u2],[q])= int2d(Th)(Div(u1,u2)*q); varf c([p],[q])=int2d(Th)(p*q); matrix A=a(Uh,Uh,tgv=-1,solver=GMRES,eps=prep[iprep],dimKrylov=Uh.ndof+Ph.ndof); //matrix A=a(Uh,Uh,tgv=-1,solver=CG,eps=prep[iprep]); //matrix A=a(Uh,Uh,tgv=-1,solver=UMFPACK); matrix B=b(Uh,Ph,solver=GMRES,eps=prep[iprep],dimKrylov=Uh.ndof+Ph.ndof); matrix Bt=B'; matrix C=c(Ph,Ph,solver=CG,eps=prep[iprep]); // set solver=CG, to avoird the alert message from C^-1; real[int] F=a(0,Uh,tgv=-1); //Boundary conditions real[int] BC=bc1(0,Uh,tgv=-1); //Boundary conditions Uh [b1,b2]; func real[int] DJ(real[int] &u) { real[int] Au=A*u; return Au; // return of global variable ok }; p=0; real epsgc= 1e-10; // Uzawa iteration int inumOuter=0; tmps1 = clock(); while(inumOuter<10000){ b1[]=Bt*p[]; b1[]+=F; // second membre Au=Btu+F b1[]= BC ? F : b1[]; u1[]= BC? F: u1[]; LinearCG(DJ,u1[],b1[],veps=epsgc,nbiter=2000,verbosity=0); epsgc=-abs(epsgc); real[int] Bu1=B*u1[]; Bu1*=alpha; real normBu1=sqrt(Bu1'*Bu1); if (normBu1<1e-10) break; // update for p real[int] ptemp(p[].n); ptemp=C^-1*Bu1; // C p^{k+1}=C p^{k} - alpha Bu p[]-=ptemp; p[]-=int2d(Th)(p)/AreaDomain; cout<< "inumOuter "<<inumOuter<<endl; inumOuter++; } tmps2 = clock(); ph=p; [uh1,uh2]=[u1,u2]; // save the solution of exact uzawa method real normeL2vit, errL2vit; normeL2vit = sqrt( int2d(Th) ( (ue1)^2+(ue2)^2) );//= sqrt( int3d(Th) (normeL2vit ) ); errL2vit = sqrt( int2d(Th) ( (u1-ue1)^2+(u2-ue2)^2) ); //sqrt( int3d(Th) ((errL2vit)^2 ) ) real NPL2,EPL2; NPL2 = sqrt(int2d(Th) (pe^2) ); EPL2 = sqrt(int2d(Th) ((p-pe)^2) ); cout << "ERR L2 RELATIVE VITESSE =" << errL2vit/normeL2vit << endl; cout << "ERR L2 RELATIVE PRESSION=" << EPL2/NPL2 <<endl; plot([uh1,uh2],ph,wait=false,value=1,fill=0,ps="numericalsolutionu.eps",cmm="Numerical solution uh, ph"); file << prep[iprep]<<" "<<Uh.ndof+Ph.ndof<<" "<<errL2vit/normeL2vit<<" "<<EPL2/NPL2<<" "<<tmps2-tmps1<<endl; }//fin boucle MESH file <<" "<<endl; file <<" "<<endl; }//fin boucle precision
0
ALLM/RAPPORT_STOKES_CODE_FREEFEM
ALLM/RAPPORT_STOKES_CODE_FREEFEM/CT1_UZAWA_REG_ADAPT/stokes_CT1_uzawa_RETRY_ADAPT.edp
/******************************************************************* DÉFINITION DES ESPACES ET DES VARIABLES ********************************************************************/ //load "Element_Mixte" /* -Delta u + gradP = 0 div u =0 */ //Définition des opérateurs utiles à la résolution macro Grad(u) [dx(u),dy(u)] //EOM macro Div(u1,u2) (dx(u1)+dy(u2)) //EOM int k=2; int PTEDGE=10*2^k; //POINTS SEED PAR COTE DU MESH // *** DEFINE MESH BY BORDER THEN BY BUILD: mesh Th; // SIMILI OF REF TRIANGULAR MESH border LOW(t=0,1) {x=t;y=0;label=1;}; // LOWER BORDER border DIAG(t=1,0) {x=t;y=1-t;label=2;}; // DIAG BORDER border LEFT(t=1,0) {x=0;y=t;label=3;}; // LEFT BORDER Th=buildmesh( LOW(PTEDGE) + DIAG(PTEDGE+PTEDGE/3) + LEFT(PTEDGE) ); real AreaDomain=Th.area; real alpha = 1; real nu=1.0; //VISCOSITE DYNAMIQUE fespace Uh(Th,[P2,P2]); // fonction space for u=(u1,u2) fespace Ph(Th,P1); // function space for p fespace Ph0(Th,P0); Uh [u1,u2],[v1,v2],[usave1,usave2]; Ph p, q; Uh [uh1,uh2],[uvisu1,uvisu2]; Ph ph,pvisu; // analytic solution real beta = 0.44; func ue1= x; func ue2= -y; func pe= x+y-(2./3.); func dxue1= 1.0; func dyue1= 0.0; func dxue2= 0.0; func dyue2= -1.0; func f1= 1; func f2= 1; [uvisu1,uvisu2]=[ue1,ue2]; pvisu=pe; fespace Vh(Th,[P2,P2]); Vh [s1,s2]; [s1,s2]=[x,-y]; //MESH ADAPT DONC ON DOIT RECONSTRUIRE LES MATRICES A CHAQUE ADAPTATION: macro buildmat(){ varf a([u1,u2],[v1,v2])=int2d(Th)(Grad(u1)'*Grad(v1)+Grad(u2)'*Grad(v2))+int2d(Th)(f1*v1+f2*v2) +on(1,2,3,u1=ue1,u2=ue2); varf bc1([u1,u2],[v1,v2])=on(1,2,3,u1=1,u2=1); varf b([u1,u2],[q])= int2d(Th)(Div(u1,u2)*q); varf c([p],[q])=int2d(Th)(p*q); matrix A=a(Uh,Uh,tgv=-1,solver=GMRES); matrix B=b(Uh,Ph); matrix Bt=B'; matrix C=c(Ph,Ph,solver=CG); real[int] F=a(0,Uh,tgv=-1); real[int] BC=bc1(0,Uh,tgv=-1); Uh [b1,b2]; }// //CONSTRUCTION INITIALE: varf a([u1,u2],[v1,v2])=int2d(Th)(Grad(u1)'*Grad(v1)+Grad(u2)'*Grad(v2))+int2d(Th)(f1*v1+f2*v2) +on(1,2,3,u1=ue1,u2=ue2); varf bc1([u1,u2],[v1,v2])=on(1,2,3,u1=1,u2=1); varf b([u1,u2],[q])= int2d(Th)(Div(u1,u2)*q); varf c([p],[q])=int2d(Th)(p*q); matrix A=a(Uh,Uh,tgv=-1,solver=GMRES); matrix B=b(Uh,Ph); matrix Bt=B'; matrix C=c(Ph,Ph,solver=CG); real[int] F=a(0,Uh,tgv=-1); real[int] BC=bc1(0,Uh,tgv=-1); Uh [b1,b2]; func real[int] DJ(real[int] &u) { real[int] Au=A*u; return Au; // return of global variable ok }; p=0; real epsgc= 1e-10; // Uzawa iteration int inumOuter=0; while(inumOuter<500){ //A AUGMENTER SI BESOIN DE PRECISION b1[]=Bt*p[]; b1[]+=F; // second member Au=Btu+F b1[]= BC ? F : b1[]; u1[]= BC? F: u1[]; LinearCG(DJ,u1[],b1[],veps=epsgc,nbiter=2000,verbosity=0); epsgc=-abs(epsgc); real[int] Bu1=B*u1[]; Bu1*=alpha; real normBu1=sqrt(Bu1'*Bu1); if (normBu1<1e-10) break; // update for p real[int] ptemp(p[].n); ptemp=C^-1*Bu1; // C p^{k+1}=C p^{k} - alpha Bu p[]-=ptemp; p[]-=int2d(Th)(p)/AreaDomain; cout<< "inumOuter "<<inumOuter<<" Uh.ndof "<<Uh.ndof<<" u1.n "<<u1.n<<endl; //ON ADAPT TOUTE LES 10 ITERATIONS, ET ON REBUILD LES MATRICES if(inumOuter%10==0){Th = adaptmesh(Th,[u1,u2],p,err=0.001);plot(Th);buildmat} inumOuter++; } ph=p; [uh1,uh2]=[u1,u2]; // save the solution of exact uzawa method real normeL2vit, errL2vit; normeL2vit = sqrt( int2d(Th) ( (ue1)^2+(ue2)^2) );//= sqrt( int3d(Th) (normeL2vit ) ); errL2vit = sqrt( int2d(Th) ( (u1-ue1)^2+(u2-ue2)^2) ); //sqrt( int3d(Th) ((errL2vit)^2 ) ) real NPL2,EPL2; NPL2 = sqrt(int2d(Th) (pe^2) ); EPL2 = sqrt(int2d(Th) ((p-pe)^2) ); cout << "ERR L2 RELATIVE VITESSE =" << errL2vit/normeL2vit<<" "<<u1.n<<" "<<Th.nv<<" "<<Th.nt << endl; cout << "ERR L2 RELATIVE PRESSION=" << EPL2/NPL2 <<endl; plot([u1,u2],p,wait=true,value=1,fill=0,ps="numericalsolutionu.eps",cmm="Numerical solution uh, ph"); ofstream ufile("V.txt"); for(int i=0;i<u1.n;i+=2){ ufile <<u1[][i]<<" "<<s1[][i]<<" "<<u1[][i+1]<<" "<<s1[][i+1]<<endl; }
0
ALLM/RAPPORT_STOKES_CODE_FREEFEM
ALLM/RAPPORT_STOKES_CODE_FREEFEM/CT2_UZAWA_PENALISATION/stokes_CT2_pen.edp
/****************************************************************************** CAS TEST 2 : ÉQUATION DE STOKES SUR UN MAILLAGE CUBIQUE 3D MÉTHODE DE RÉSOLUTION : PÉNALISATION *******************************************************************************/ load "msh3" // module de génération de maillage 3D load "medit" // Module de sortie graphique en temps réel include "Cube.idp" // Module contenant la construction du maillage cubique 3D load "iovtk" //pour l'écriture au format .vtk // ofstream afile("CT2_pen_MER_p1bp1.txt"); /******************************************************************* DÉFINITION DES ESPACES ET DES VARIABLES ********************************************************************/ //**********CONSTRUCTION DU MAILLAGE int nb=10; // Nombre de points par arete pour le maillage mesh3 Th=meshgen(nb); // Génération du maillage d'apres Cube.idp //*********ESPACES DE RÉSOLUTION fespace VVh(Th,[P1b,P1b,P1b]); // Espace pour la vitesse [u1,u2,u3] fespace QQh(Th,P1); // Espace pour la pression p VVh [u1,u2,u3], [v1,v2,v3]; QQh p, q; //*********OPÉRATEURS ET VARIABLES UTILES macro Grad(u) [dx(u),dy(u),dz(u)] // macro div(u1,u2,u3) (dx(u1)+dy(u2)+dz(u3)) // real nu=1.0; // Viscosité dynamique //Définition des vitesses et pression analytiques pour le cas test func ue1=x; func ue2=y; func ue3=-2*z; func pe=x+y+z-(3./2.); //Définition du second membre de l'équation de Stokes func f=1.; /******************************************************************* RÉSOLUTION DU PROBLÈME VARIATIONNEL ********************************************************************/ //*******VARIABLES DE RÉSOLUTION real t1,t2,pen; cout << "----------------------------" << endl; t1=clock(); // START CHRONO pen=1e-10; // Coefficient de pénalisation int dimk=0.5*(VVh.ndof+QQh.ndof); // Dimension de l'espace de KRYLOV pour GMRES int ite=2*dimk; // Nombre d'itérations pour le solveur //*******PROBLEME VARIATIONNEL solve Stokes([u1,u2,u3,p],[v1,v2,v3,q],solver=GMRES,eps=1e-10,dimKrylov=dimk, nbiter=ite) = // solve Stokes([u1,u2,u3,p],[v1,v2,v3,q],solver=UMFPACK)= int3d(Th)( Grad(u1)'*Grad(v1) + Grad(u2)'*Grad(v2) + Grad(u3)'*Grad(v3) - div(u1,u2,u3)*q - div(v1,v2,v3)*p - pen*q*p ) +int3d(Th)(-f*(v1+v2+v3)) + on(1,2,3,4,5,6,u1=ue1,u2=ue2,u3=ue3,p=pe); t2=clock(); // STOP CHRONO /******************************************************************* CALCUL DES ERREURS ET AFFICHAGE DES SORTIES ********************************************************************/ real normeL2vit, errL2vit; real normeL2press, errL2press; //Pour la vitesse normeL2vit = sqrt( int3d(Th) ( (ue1)^2+(ue2)^2+(ue3)^2) ); errL2vit = sqrt( int3d(Th) ( (u1-ue1)^2+(u2-ue2)^2+(u3-ue3)^2) ); //Pour la pression normeL2press = sqrt( int3d(Th) ( (pe)^2 )); errL2press = sqrt( int3d(Th) ( (p-pe)^2 ) ); //AFFICHAGE DES ERREURS À L'ECRAN //afile << VVh.ndof+QQh.ndof << " " << pen << " "<< //(errL2vit/normeL2vit+errL2press/normeL2press)*0.5 << " "<< t2-t1 << endl; cout << "pour V" << VVh.ndof << endl; cout << "pour P" << QQh.ndof << endl; cout << "-----------------------" << endl; cout << "ERR L2 RELATIVE VITESSE =" << errL2vit/normeL2vit << endl; cout << "ERR L2 RELATIVE PRESSION =" << errL2press/normeL2press << endl; cout << "Temps CPU :" << t2-t1 << endl; //plot([ux,uz],value=true,cmm="cut y=1"); /******************************************************************** ÉCRITURE DES FICHIERS SOLUTIONS AU FORMAT VTK ********************************************************************/ // int[int] Order = [1]; // string DataName = "Vitesse"; // savevtk("vit.vtk", Th,[u1,u2,u3], dataname=DataName, order=Order); // DataName="Pression"; // savevtk("p.vtk", Th, p, dataname=DataName, order=Order); //AFFICHAGE DES SOLUTIONS FINALES SUR LE MAILLAGE AVEC MEDIT // medit("vit",Th,[u1,u2,u3]); // medit("p",Th,p);
0
ALLM/RAPPORT_STOKES_CODE_FREEFEM
ALLM/RAPPORT_STOKES_CODE_FREEFEM/CT2_UZAWA_PENALISATION/stokes_CT2_uzawa.edp
/* RÉSOLUTION DE L'ÉQUATION DE STOKES STATIONNAIRE SUR UN CUBE UNITAIRE (CT2) AVEC LA MÉTHODE D'UZAWA -Delta u + gradP = 0 div u =0 */ /******************************************************************* DÉFINITION DES ESPACES ET DES VARIABLES ********************************************************************/ /* MODULES */ load "msh3" load "medit" // dynamics load tools for 3d. include "Cube.idp" load "iovtk" //ofstream afile("CT2_uzawa_mesh_p1p0test.txt"); // Création du maillage int nb=5; mesh3 Th=meshgen(nb); //medit("Cube", Th); //affichage du maillage initial avec MEDIT // Définition des éléments finis utilisés: fespace VVh(Th,[P1,P1,P1]); //Pour la vitesse fespace QQh(Th,P1); // Pour la pression //Définition des opérateurs utiles à la résolution macro Grad(u) [dx(u),dy(u),dz(u)] // macro div(u1,u2,u3) (dx(u1)+dy(u2)+dz(u3)) // real nu=1.0; //VISCOSITE DYNAMIQUE VVh [u1,u2,u3], [v1,v2,v3]; //vecteurs vitesse et vecteurs vitesse tests QQh p, q; //vecteur pression et pression tests //Définition des vitesses et pression analytiques pour le cas test func ue1=x; func ue2=y; func ue3=-2*z; func pe=x+y+z-(3./2.); //Définition du second membre de l'équation de Stokes func f=1.; /******************************************************************** Assemblage matrices problème général + fonctions ********************************************************************/ //----------Création de la matrice A du problème (vitesse) varf aaa([u1, u2, u3], [v1, v2, v3])= int3d(Th)(nu*( Grad(u1)'*Grad(v1) + Grad(u2)'*Grad(v2) + Grad(u3)'*Grad(v3) )) +int3d(Th)(f*(v1+v2+v3)) + on(1,2,3,4,5,6,u1=ue1,u2=ue2,u3=ue3); matrix AA = aaa(VVh, VVh, solver=GMRES, tgv=-1); //matrice A du PB VAR //----------Conditions aux limites pour les vitesses varf bc1([u1, u2, u3], [v1, v2, v3])=on(1,2,3,4,5,6,u1=1,u2=1,u3=1); //----------Matrice de masse varf massp(p,q) = int3d(Th)(p * q); matrix Mp = massp(QQh, QQh, solver=CG); //----------Conditions aux limites + forces exterieures real[int] F=aaa(0,VVh,tgv=-1), G=bc1(0,VVh,tgv=-1); //----------Création de la matrice B pour le PB VAR varf bbb([u1,u2,u3], [q]) = int3d(Th)(div(u1,u2,u3)*q ); matrix DB = bbb(VVh,QQh); // La matrice B du PB VAR matrix DBT = DB'; //B transposée VVh [b1,b2,b3]; // vecteur pour les conditions aux limites //----------Conditions aux limites real[int] bbc = aaa(0, VVh ,tgv=-1); // Dirichlet //---------Fonction d'appel pour le GC func real[int] DJ(real[int] &u){ real[int] au=AA*u; return au; } //--------Intialisation pour la pression et résolution système linéaire p[]=0.; real areadomain = 1.; int inumouter=0; real epsgc=1e-10; real norm=1.; /******************************************************************** BOUCLE RÉSOLUTION CG + CALCUL DE P AVEC UZAWA ********************************************************************/ real t1,t2; t1=clock(); while (inumouter<10000){ //cout << inumouter << endl; b1[]=DBT*p[]; b1[]+=F; b1[]=G ? F : b1[]; u1[]=G ? F : u1[]; LinearCG(DJ, u1[],b1[],veps=epsgc,nbiter=2*(VVh.ndof+QQh.ndof),eps=1e-12, verbosity=0); epsgc=-abs(epsgc); real[int] bu1=DB*u1[]; real alpha=1.; bu1*=alpha; real normbu1=sqrt(bu1'*bu1); norm=normbu1; if (normbu1<1e-20){ break; } real[int] ptemp(p[].n); ptemp=Mp^-1*bu1; p[]-=ptemp; p[]-=int3d(Th)(p)/areadomain;//int3d(Th)(p); inumouter++; } t2=clock(); /******************************************************************* CALCUL DES ERREURS ET AFFICHAGE DES SORTIES ********************************************************************/ real normeL2vit, errL2vit; real normeL2press, errL2press; //Pour la vitesse normeL2vit = sqrt( int3d(Th) ( (ue1)^2+(ue2)^2+(ue3)^2) ); errL2vit = sqrt( int3d(Th) ( (u1-ue1)^2+(u2-ue2)^2+(u3-ue3)^2) ); //Pour la pression normeL2press = sqrt( int3d(Th) ( (pe)^2 )); errL2press = sqrt( int3d(Th) ( (p-pe)^2 ) ); //AFFICHAGE DES ERREURS À L'ECRAN cout << "ERR L2 RELATIVE VITESSE =" << errL2vit/normeL2vit << endl; cout << "ERR L2 RELATIVE PRESSION =" << errL2press/normeL2press << endl; //afile << VVh.ndof+QQh.ndof << " "<< errL2vit/normeL2vit << " "<< errL2press/normeL2press << " "<< t2-t1 << endl; cout << "pour V" << VVh.ndof << endl; cout << "pour P" << QQh.ndof << endl; cout << "Temps CPU" << t2-t1 << endl; /******************************************************************** ÉCRITURE DES FICHIERS SOLUTIONS AU FORMAT VTK ********************************************************************/ // int[int] Order = [1]; // string DataName = "Vitesse"; // savevtk("vit.vtk", Th,[u1,u2,u3], dataname=DataName, order=Order); // DataName="Pression"; // savevtk("p.vtk", Th, p, dataname=DataName, order=Order); //AFFICHAGE DES SOLUTIONS FINALES SUR LE MAILLAGE AVEC MEDIT // medit("vit",Th,[u1,u2,u3]); // medit("p",Th,p);
0
ALLM/RAPPORT_STOKES_CODE_FREEFEM
ALLM/RAPPORT_STOKES_CODE_FREEFEM/CT3_PENA/stokes_CT3.edp
include "cylindre2.idp" load "iovtk" // Espaces de résolution //fespace VVh(Th,[P1b,P1b,P1b]); fespace VVh(Th,[P2,P2,P2]); fespace QQh(Th,P1); //Définition des opérateurs utiles à la résolution macro Grad(u) [dx(u),dy(u),dz(u)] // EOM macro div(u1,u2,u3) (dx(u1)+dy(u2)+dz(u3)) //EOM real nu = 1.0; real L = 4.0; //a modifier dans cylindre2.idp :=zbound[0,L] real Rayon = 1.0; //Rayon du cylindre real CLZ; // CL sur u3 (dirichlet homogene) en z=0 si on veut faire le test du debit(cf projet) real cstpression; //a calculer analytiquement pour avoir pression moyenne nulle // Variables à résoudre dans le calcul VVh [u1,u2,u3], [v1,v2,v3]; QQh p, q; // Variables solution exacte func ue1 = 0.0; func ue2 = 0.0; func ue3 = 1-x*x-y*y; cstpression = 2*L; //VIA etude theorique func pe = -4*z+cstpression;//VIA etude theorique VVh [u1exa,u2exa,u3exa]; [u1exa,u2exa,u3exa] = [0.0,0.0,1-x*x-y*y]; // Définition du terme source real f = 0.0; // Coeff penalisation real pena = 1e-7; //CLZ: CLZ = 1.0-(0.5*Rayon*Rayon);// ==0.5 car Rayon=1 /******************************************************************* RÉSOLUTION DU PROBLÈME VARIATIONNEL ********************************************************************/ real tmps1,tmps2; //temps de calcul /* MÉTHODE DE PÉNALISATION */ p = 0; // //Problème Variationnel //GMRES,eps=1e-6,nbiter=2*VVh.ndof+2*QQh.ndof,dimKrylov=VVh.ndof tmps1 = clock(); solve Stokes([u1,u2,u3,p],[v1,v2,v3,q],solver=UMFPACK) = int3d(Th)( nu*(Grad(u1)'*Grad(v1) + Grad(u2)'*Grad(v2) + Grad(u3)'*Grad(v3)) - div(u1,u2,u3)*q - div(v1,v2,v3)*p - pena*q*p ) +int3d(Th)(-f*(v1+v2+v3)) +on(3,u1=0.0,u2=0.0,u3 = ue3,p=pe) //Contour cylindre vitesse nulle +on(2,u1=0.0,u2=0.0,u3 = ue3,p=pe) //Entrée +on(1,u1=0.0,u2=0.0,u3 = ue3,p=pe); //Sortie tmps2 = clock(); /* ÉCRITURE FICHIERS */ // Écriture de la solution au format .vtk //int[int] Order = [1]; //string DataName = "U"; //savevtk("u1.vtk",Th,u1, dataname=DataName, order=Order); // savevtk("u2.vtk",Th,u2, dataname=DataName, order=Order); // savevtk("u3.vtk",Th,u3, dataname=DataName, order=Order); //savevtk("press.vtk",Th,p, dataname=DataName, order=Order); /******************************************************************* CALCUL DES ERREURS ET AFFICHAGE DES SORTIES ********************************************************************/ real normeL2vit, errL2vit, normeL2press, errL2press; //Pour la vitesse normeL2vit = 0.0; errL2vit = 0.0; //le calcul de norme: for(int i=0; i<u3.n-2;i=i+3){//i=i+3 car la solution sur toutes les composantes est save dans la compo u3. normeL2vit = normeL2vit + (0.0)^2 + (0.0)^2 + (u3exa[][i+2])^2 ; errL2vit = errL2vit + (u1[][i]-0.0)^2 + (u2[][i+1]-0.0)^2 + (u3[][i+2]-u3exa[][i+2])^2; //cout<< "u1 "<<u1[][i]<< " u2 "<<u2[][i+1]<< " u3 "<<u3[][i+2]<<" u3exa "<<u3exa[][i+2]<<endl; } normeL2vit = sqrt( int3d(Th) ( normeL2vit) ); errL2vit = sqrt( int3d(Th) ( errL2vit ) ); //Pour la pression normeL2press = sqrt( int3d(Th) ( (pe)^2 )); errL2press = sqrt( int3d(Th) ( (p-pe)^2 ) ); cout << "NDOF " << VVh.ndof+QQh.ndof << " VVh.NDOF " << VVh.ndof << " u1.n " << u1.n << endl; cout << "ERR L2 RELATIVE VITESSE =" << errL2vit/normeL2vit << endl; cout << "ERR L2 RELATIVE PRESSION =" << errL2press/normeL2press << endl; cout << "TEMPS DE CALCUL en Sec "<< tmps2-tmps1<<" deb out "<< int2d(Th,1)(u3)*(pi*Rayon*Rayon) << endl; //string DataName2 = "P"; //savevtk("vitesse.vtk", Th,u3, dataname=DataName2, order=Order); medit("vit",Th,u3); medit("Press",Th,p); /* POUR VISUALISER AVEC MEDIT: cliquer sur la fenetre faire au clavier m pour les couleurs B (maj+b), puis G(maj+g) et A(maj+a) pour boxe grille axe fn F1 pour une coupe */
0
ALLM/RAPPORT_STOKES_CODE_FREEFEM
ALLM/RAPPORT_STOKES_CODE_FREEFEM/UZAWA-CT3/stokes_CT3_uza.edp
/* RÉSOLUTION DE L'ÉQUATION DE STOKES STATIONNAIRE SUR UN CYLINDRE AVEC LA MÉTHODE D'UZAWA -Delta u + gradP = 0 div u =0 */ /******************************************************************* DÉFINITION DES ESPACES ET DES VARIABLES ********************************************************************/ /* MODULES */ include "cylindre2.idp" load "iovtk" //ofstream afile("CT3_uzawa.txt"); // Définition des éléments finis utilisés: fespace VVh(Th,[P2,P2,P2]); //Pour la vitesse fespace QQh(Th,P1); // Pour la pression //Définition des opérateurs utiles à la résolution macro Grad(u) [dx(u),dy(u),dz(u)] // macro div(u1,u2,u3) (dx(u1)+dy(u2)+dz(u3)) // real nu=1.0; //VISCOSITE DYNAMIQUE VVh [u1,u2,u3], [v1,v2,v3]; //vecteurs vitesse et vecteurs vitesse tests QQh p, q; //vecteur pression et pression tests //Définition des vitesses et pression analytiques pour le cas test func ue1=0.; func ue2=0.; func ue3=1.-x*x-y*y; real L=5.0;//SI modification de L, pensez a aussi modifier zbound[0,L] dans le .idp real Rayon=1.0; real cstpression=2.*L; func pe=-4.*z+cstpression; //Définition du second membre de l'équation de Stokes func f=0.; func CLZ=1-0.5*Rayon*Rayon;//=0.5; car rayon=1//SI ON VEUT METTRE UNE VITESSE CST EN Z=0 CF PROJET /******************************************************************** Assemblage matrices problème général + fonctions ********************************************************************/ //----------Création de la matrice A du problème (vitesse) varf aaa([u1, u2, u3], [v1, v2, v3])= int3d(Th)(nu*( Grad(u1)'*Grad(v1) + Grad(u2)'*Grad(v2) + Grad(u3)'*Grad(v3) )) +int3d(Th)(f*(v1+v2+v3)) + on(1,u1=0.0,u2=0.0,u3=ue3) //z=L sortie + on(3,u1=0.0,u2=0.0,u3=ue3) //r=R latéral + on(2,u1=0.0,u2=0.0,u3=ue3); //z=0 entrée // pour les CL issues du calcul du debit faire: /*+ on(1,u1=0.0,u2=0.0) //z=L sortie + on(3,u1=0.0,u2=0.0,u3=ue3) //r=R latéral + on(2,u1=0.0,u2=0.0,u3=CLZ); //z=0 entrée*/ matrix AA = aaa(VVh, VVh, solver=GMRES, tgv=-1); //matrice A du PB VAR //----------Conditions aux limites pour les vitesses varf bc1([u1, u2, u3], [v1, v2, v3])=on(1,2,3,u1=1,u2=1,u3=1); //----------Matrice de masse varf massp(p,q) = int3d(Th)(p * q); matrix Mp = massp(QQh, QQh, solver=CG); //----------Conditions aux limites + forces exterieures real[int] F=aaa(0,VVh,tgv=-1), G=bc1(0,VVh,tgv=-1); //----------Création de la matrice B pour le PB VAR varf bbb([u1,u2,u3], [q]) = int3d(Th)(div(u1,u2,u3)*q ); matrix DB = bbb(VVh,QQh); // La matrice B du PB VAR matrix DBT = DB'; //B transposée VVh [b1,b2,b3]; // vecteur pour les conditions aux limites //----------Conditions aux limites real[int] bbc = aaa(0, VVh ,tgv=-1); // Dirichlet //---------Fonction d'appel pour le GC func real[int] DJ(real[int] &u){ real[int] au=AA*u; return au; } //--------Intialisation pour la pression et résolution système linéaire p[]=0.; real rayon=1.; real areadomain = pi*rayon*rayon*L; int inumouter=0; real epsgc=1e-10; real norm=1.; /******************************************************************** BOUCLE RÉSOLUTION CG + CALCUL DE P AVEC UZAWA ********************************************************************/ real t1,t2; t1=clock(); while (inumouter<2000){//AUGMENTER LA BORNE DE inumouter POUR UNE MEILLEUR CONVERGENCE cout << inumouter << endl; //calcul second membre b1[]=DBT*p[]; b1[]+=F; //switch second membre b1[]=G ? F : b1[]; u1[]=G ? F : u1[]; //resolution de la vitesse: LinearCG(DJ, u1[],b1[],veps=epsgc,nbiter=2*(VVh.ndof+QQh.ndof),eps=1e-12, verbosity=5); epsgc=-abs(epsgc); real[int] bu1=DB*u1[];//DIVERGENCE VITESSE real alpha=1.; bu1*=alpha;//alpha=1/(1+Rbeta), ici Rbeta=1 real normbu1=sqrt(bu1'*bu1); norm=normbu1; if (normbu1<1e-10){//condition sur la norme de la divergence, possibilité de la diminuer ex:1e-12 break; } //resolution pour la pression: real[int] ptemp(p[].n); ptemp=Mp^-1*bu1; p[]-=ptemp; p[]-=int3d(Th)(p)/areadomain; inumouter++; } t2=clock(); /******************************************************************* CALCUL DES ERREURS ET AFFICHAGE DES SORTIES ********************************************************************/ real normeL2vit, errL2vit; real normeL2press, errL2press; //Pour la vitesse normeL2vit = sqrt( int3d(Th) ( (ue1)^2+(ue2)^2+(ue3)^2) ); errL2vit = sqrt( int3d(Th) ( (u1-ue1)^2+(u2-ue2)^2+(u3-ue3)^2) ); //Pour la pression normeL2press = sqrt( int3d(Th) ( (pe)^2 )); errL2press = sqrt( int3d(Th) ( (p-pe)^2 ) ); //AFFICHAGE DES ERREURS À L'ECRAN cout <<"********************************************************************"<<endl; cout << "ERR L2 RELATIVE VITESSE ALL DOMAINE =" << errL2vit/normeL2vit << endl; cout << "ERR L2 RELATIVE PRESSION ALL DOMAINE =" << errL2press/normeL2press << endl; cout << "TEMPS " << t2-t1 << " ndof " << VVh.ndof+QQh.ndof <<" DEBIT OUT " << int2d(Th,1)(u3)*pi*Rayon*Rayon<< endl; cout << " DEBIT IN " << int2d(Th,2)(u3)*pi*Rayon*Rayon <<" DEBIT OUT " << int2d(Th,1)(u3)*pi*Rayon*Rayon<< endl; cout <<"********************************************************************"<<endl; cout <<"********************************************************************"<<endl; //pour z=L: //Pour la vitesse SUR LA FACE z=L normeL2vit = sqrt( int2d(Th,1) ( (ue1)^2+(ue2)^2+(ue3)^2) ); errL2vit = sqrt( int2d(Th,1) ( (u1-ue1)^2+(u2-ue2)^2+(u3-ue3)^2) ); //Pour la pression SUR LA FACE z=L normeL2press = sqrt( int2d(Th,1) ( (pe)^2 )); errL2press = sqrt( int2d(Th,1) ( (p-pe)^2 ) ); cout <<"********************************************************************"<<endl; cout << "ERR L2 RELATIVE VITESSE EN Z=L = " << errL2vit/normeL2vit << endl; cout << "ERR L2 RELATIVE PRESSION EN Z=L = " << errL2press/normeL2press << endl; cout <<"********************************************************************"<<endl; //afile << VVh.ndof+QQh.ndof << " "<< errL2vit/normeL2vit << " "<< errL2press/normeL2press << " "<< t2-t1 << endl; // mesh cut=square(nb,nb,[x,y]); // fespace Vcut(cut,P2); // Vcut ux=u1(x,0.5,y); // Vcut uz=u3(x,0.5,y); // Vcut p2=p(x,0.5,y); //plot([ux,uz],value=true,cmm="cut y=1"); //} /******************************************************************** ÉCRITURE DES FICHIERS SOLUTIONS AU FORMAT VTK ********************************************************************/ // int[int] Order = [1]; // string DataName = "Vitesse"; // savevtk("vit.vtk", Th,[u1,u2,u3], dataname=DataName, order=Order); // DataName="Pression"; // savevtk("p.vtk", Th, p, dataname=DataName, order=Order); //AFFICHAGE DES SOLUTIONS FINALES SUR LE MAILLAGE AVEC MEDIT medit("vit",Th,u3); medit("p",Th,p);
0
ALLM/Savitzky-Golay-Filtering
ALLM/Savitzky-Golay-Filtering/src/SavitzkyGolayFIR.m
function [FIRFiltersCoeff, MatrixOfDiffFilter, frame_half_len] = SavitzkyGolayFIR(order, framelen) % designs a Savitzky-Golay Finite Impulse Response (FIR) smothing filter with polynomial order order and frame lenght framelen. % INPUTS: % order -- polynomial order positive odd integer % framelen -- Frame lenght, specified as a positive odd integer. it Must be greater than order. % % OUTPUTS: % b -- Time-varying FIR filter coefficiants (matrix) % g -- Matrix of differentiation filters (matrix) % f -- frame half lenght arguments order (1,1) double {mustBeNumeric, mustBeReal, mustBePositive, mustBeGreaterThanOrEqual(order,0)} framelen (1,1) double {mustBeNumeric, mustBeReal, mustBePositive, mustBeGreaterThan(framelen,order)} end % framelen rounding case if mod( framelen,1) ~= 0 framelen = round( framelen); warning("framelen was rounded to the nearest integer."); end % framelen must be odd if mod( framelen,2) ~= 1 warning("framelen must be odd, provided framelen was not odd. Continuing with framelen = framelen + 1"); framelen = framelen + 1; end % order rounding case if mod( order,1) ~= 0 order = round(order); warning("order was rounded to the nearest integer."); end % Get frame half lenght and Vandermonde(-frame_half_len:frame_half_len) %fliptype = 'fliplr'; fliptype = 'none'; [frame_half_len, vander_obj] = GetVander( framelen, fliptype); VanderMatrix = vander_obj( :,framelen:-1:framelen - order); % Compute (B)FIRFiltersCoeff and (G)MatrixOfDiffFilter [~,R] = qr( VanderMatrix,0); MatrixOfDiffFilter = (R'*R)\VanderMatrix'; MatrixOfDiffFilter = VanderMatrix/R/R'; FIRFiltersCoeff = MatrixOfDiffFilter * VanderMatrix'; end function [frame_half_len, vander_obj] = GetVander( framelen, fliptype) arguments framelen (1,1) double {mustBeNumeric, mustBeReal, mustBePositive, mustBeGreaterThan(framelen,1)} fliptype (1,:) char {mustBeMember(fliptype,{'none','fliplr'})} = 'none' end frame_half_len = ( framelen - 1) / 2; if strcmp( fliptype,'fliplr') vander_obj = fliplr( vander( -frame_half_len:frame_half_len)); else vander_obj = vander( -frame_half_len:frame_half_len); end end
0
ALLM/Savitzky-Golay-Filtering
ALLM/Savitzky-Golay-Filtering/src/sgolayfilt.m
function smoothed_data = sgolayfilt(input_data, order, framelen, mode, trst, cval) % designs a Savitzky-Golay Finite Impulse Response (FIR) smothing filter with polynomial order order and frame lenght framelen. % INPUTS: % input_data -- data to be smoothed % order -- polynomial order positive odd integer % framelen -- Frame lenght, specified as a positive odd integer. it Must be greater than order. % mode -- 'mirror' Repeats the values at the edges in reverse order. The value closest to the edge is not included. % -- 'nearest' The extension contains the nearest input value. % -- 'constant' The extension contains the value given by the cval argument. % -- 'wrap' The extension contains the values from the other end of the array. % -- 'classic' Use transient for edges, steady at frame_half_len % -- 'default' Use of transient for edges, steady at frame_half_len+1 % trst -- transient "yes" or "no" wether to use transient reconstruction for edges at begin and end for mode != classic and default. default "yes". % cval Value to fill past the edges of the input if mode is ‘constant’. Default is 0.0. % OUTPUTS: % smoothed_data -- filtered data arguments input_data {mustBeNumeric, mustBeReal} order (1,1) double {mustBeNumeric, mustBeReal, mustBePositive, mustBeGreaterThanOrEqual(order,0)} framelen (1,1) double {mustBeNumeric, mustBeReal, mustBePositive, mustBeGreaterThan(framelen,order)} mode (1,:) char {mustBeMember(mode,{'mirror','constant','nearest','wrap','classic','default'})} = 'default' trst (1,:) char {mustBeMember(trst,{'yes','no'})} = 'yes' cval (1,1) double {mustBeNumeric, mustBeReal} = 0. end [FIRFiltersCoeff, MatrixOfDiffFilter, frame_half_len] = SavitzkyGolayFIR( order, framelen); if length(size(input_data)>1) if size(input_data,1)<size(input_data,2) padded_data = input_data'; else padded_data = input_data; end else padded_data = input_data; end begin = 1; if ~strcmp(mode, 'default') & ~strcmp(mode, 'classic') %if mode!='default' switch mode case 'mirror' nb = input_data( begin + 1); ne = input_data( end - 1); case 'constant' nb = cval; ne = cval; case 'nearest' nb = input_data( begin); ne = input_data( end); case 'wrap' nb = input_data( end - 1 + 1); ne = input_data( begin + 1 - 1); end for i = 2:frame_half_len switch mode case 'mirror' nb = [input_data( begin + i); nb]; ne = [ne; input_data( end - i)]; case 'constant' nb = [cval; nb]; ne = [ne; cval]; case 'nearest' nb = [input_data( begin); nb]; ne = [ne; input_data( end)]; case 'wrap' nb = [input_data( end - i + 1); nb]; ne = [ne; input_data( begin + i - 1)]; end end padded_data = [nb; padded_data; ne]; switch trst case 'no' smoothed_data = conv( padded_data, FIRFiltersCoeff( frame_half_len+1, :), 'valid'); case 'yes' steady = conv( padded_data, FIRFiltersCoeff( frame_half_len+1, :), 'valid'); ybeg = FIRFiltersCoeff( begin:frame_half_len,:) * padded_data( begin:framelen); yend = FIRFiltersCoeff( framelen - frame_half_len + 1:framelen, :) * padded_data(end - framelen + 1: end); smoothed_data = steady; smoothed_data( begin:frame_half_len) = ybeg; smoothed_data( end - frame_half_len +1:end) = yend; end else a = 0; if strcmp(mode, 'default') a = 1; end steady = conv( padded_data, FIRFiltersCoeff( frame_half_len+a, :), 'same'); ybeg = FIRFiltersCoeff( begin:frame_half_len,:) * padded_data( begin:framelen); yend = FIRFiltersCoeff( framelen - frame_half_len + 1:framelen, :) * padded_data(end - framelen + 1: end); smoothed_data = steady; smoothed_data( begin:frame_half_len) = ybeg; smoothed_data( end - frame_half_len +1:end) = yend; end %end if mode!='default' end
0
ALLM/Savitzky-Golay-Filtering
ALLM/Savitzky-Golay-Filtering/test/SGolay_Differentiation.m
% Generate a signal that consists of a 0.2 Hz sinusoid embedded in white Gaussian noise and sampled four times a second for 20 seconds. dt = 0.25; t = (0:dt:20-1)'; freq = 0.2; % frequency omega = 2.0*pi*freq; % pulsation i.e angular frequency, omega*t angle in radians. Amp = 5.0; % Amplitude x = Amp*sin(omega*t)+0.5*randn(size(t)); % Estimate the first three derivatives of the sinusoid using the Savitzky-Golay method. Use 25-sample frames and fifth order polynomials. Divide the columns by powers of dt to scale the derivatives correctly. order = 5 framelen = 25; [FIRFiltersCoeff, MatrixOfDiffFilter, frame_half_len] = SavitzkyGolayFIR(order, framelen); dx = zeros(length(x),4); for p = 0:3 coeff = factorial(p)/(-dt)^p; dx(:,p+1) = conv(x, coeff * MatrixOfDiffFilter(:,p+1), 'same'); end % Plot the original signal, the smoothed sequence, and the derivative estimates. plot(x,'.-') hold on plot(dx) hold off legend('x','x (smoothed)','x''','x''''', 'x''''''') title('Savitzky-Golay Derivative Estimates')
0
ALLM/Savitzky-Golay-Filtering
ALLM/Savitzky-Golay-Filtering/test/SGolay_FilteringSpeechSignal.m
load mtlb; t = (0:length(mtlb)-1)/Fs; rd = 9; fl = 21; mirror = sgolayfilt(mtlb,rd,fl,'mirror'); wrap = sgolayfilt(mtlb,rd,fl,'wrap'); classic = sgolayfilt(mtlb,rd,fl,'classic'); default = sgolayfilt(mtlb,rd,fl,'default'); subplot(2,2,1) plot(t,mtlb) hold on plot(t,mirror) axis([0.2 0.22 -3 2]) title('mirror') grid subplot(2,2,2) plot(t,mtlb) hold on plot(t,wrap) axis([0.2 0.22 -3 2]) title('wrap') grid subplot(2,2,3) plot(t,mtlb) hold on plot(t,classic) axis([0.2 0.22 -3 2]) title('classic') grid subplot(2,2,4) plot(t,mtlb) hold on plot(t,default) axis([0.2 0.22 -3 2]) title('.default') grid
0
ALLM/Savitzky-Golay-Filtering
ALLM/Savitzky-Golay-Filtering/test/SGolay_SmoothingOfNoisySinusoid.m
% Generate a signal that consists of a 0.2 Hz sinusoid embedded in white Gaussian noise and sampled five times a second for 200 seconds. dt = 1.0/5.0; LB = 0.; UB = 200.; t = (LB:dt:UB-dt)'; freq = 0.2; % frequency Hz omega = 2.0*pi*freq; % angular frequency (pulsation) rad/s Amp = 5.0; % amplitude x = Amp*sin(omega*t) + randn(size(t)); % Use sgolay to smooth the signal. Use 21-sample frames and fourth order polynomials. order = 4; framelen = 21; [FIRFiltersCoeff, MatrixOfDiffFilter, frame_half_len] = SavitzkyGolayFIR(order, framelen); % Compute the steady-state portion of the signal by convolving it with the center row of b. ycenter = conv(x,FIRFiltersCoeff(frame_half_len+1,:),'valid'); %Compute the transients. Use the last rows of b for the startup and the first rows of b for the terminal. ybegin = FIRFiltersCoeff(end:-1:frame_half_len+2,:) * x(framelen:-1:1); yend = FIRFiltersCoeff(frame_half_len:-1:1,:) * x(end:-1:end-(framelen-1)); %Concatenate the transients and the steady-state portion to generate the complete smoothed signal. Plot the original signal and the Savitzky-Golay estimate. y = [ybegin; ycenter; yend]; plot([x y]) legend('Noisy Sinusoid','S-G smoothed sinusoid')
0
ALLM/Savitzky-Golay-Filtering
ALLM/Savitzky-Golay-Filtering/test/SteadyStateAndTransientSGFilters.m
% Generate a random signal and smooth it using sgolay. Specify a polynomial order of 3 and a frame length of 11. Plot the original and smoothed signals. lx = 34; % lenght x = randn(lx, 1); % signal disp("size(x)"); display(size(x)); % Use sgolay to smooth the signal. Use 11-sample frames and third order polynomials. order = 3; framelen = 11; frame_half_len = (framelen - 1) / 2; [FIRFiltersCoeff, MatrixOfDiffFilter, frame_half_len] = SavitzkyGolayFIR(order, framelen); % Compute the steady-state portion of the signal by convolving it with the center row of b. ycenter = conv(x,FIRFiltersCoeff(frame_half_len,:),'same'); %ycenter = conv(x,FIRFiltersCoeff((framelen+1)/2,:),'same'); plot(x,':'); hold on plot(ycenter,'.-') %Samples close to the signal edges cannot be placed at the center of a symmetric window and have to be treated differently. %To determine the startup transient, matrix multiply the first (framelen-1)/2 rows of B by the first framelen samples of the signal. ybeg = FIRFiltersCoeff(1:frame_half_len,:) * x(1:framelen); %To determine the terminal transient, matrix multiply the final (framelen-1)/2 rows of B by the final framelen samples of the signal. yend = FIRFiltersCoeff(framelen-frame_half_len+1:framelen,:) * x(lx-framelen+1:lx); %Concatenate the transients and the steady-state portion to generate the complete signal. cmplt = ycenter; cmplt(1:frame_half_len) = ybeg; cmplt(lx-frame_half_len+1:lx) = yend; disp("size(cmplt)"); display(size(cmplt)); plot(cmplt) legend('Signal','Steady','complete')
0
ALLM/Savitzky-Golay-Filtering
ALLM/Savitzky-Golay-Filtering/test/UsingSgolayfilt_SteadyStateAndTransientSGFilters.m
% Generate a random signal and smooth it using sgolay. Specify a polynomial order of 3 and a frame length of 11. Plot the original and smoothed signals. %rng(1) lx = 34; % lenght x = randn(lx, 1); % signal % Use sgolay to smooth the signal. Use 11-sample frames and third order polynomials. order = 3; framelen = 11; frame_half_len = (framelen - 1) / 2; modes = ["mirror" "constant" "nearest" "wrap" "classic" "default"] plot(x,':'); hold on for i = 1:6 smoothed_data = sgolayfilt(x, order, framelen, modes(i),'yes'); plot(smoothed_data,'-+'); end %plot(smoothed_data,'.-'); [FIRFiltersCoeff, MatrixOfDiffFilter, frame_half_len] = SavitzkyGolayFIR(order, framelen); % Compute the steady-state portion of the signal by convolving it with the center row of b. ycenter = conv(x,FIRFiltersCoeff(frame_half_len,:),'same'); plot(ycenter) %Samples close to the signal edges cannot be placed at the center of a symmetric window and have to be treated differently. %To determine the startup transient, matrix multiply the first (framelen-1)/2 rows of B by the first framelen samples of the signal. ybeg = FIRFiltersCoeff(1:frame_half_len,:) * x(1:framelen); %To determine the terminal transient, matrix multiply the final (framelen-1)/2 rows of B by the final framelen samples of the signal. yend = FIRFiltersCoeff(framelen-frame_half_len+1:framelen,:) * x(lx-framelen+1:lx); %Concatenate the transients and the steady-state portion to generate the complete signal. cmplt = ycenter; cmplt(1:frame_half_len) = ybeg; cmplt(lx-frame_half_len+1:lx) = yend; plot(cmplt,'.-'); legend('Signal',"mirror","constant","nearest","wrap","classic","def",'Steady','complete');
0
ALLM/Savitzky-Golay-Filtering
ALLM/Savitzky-Golay-Filtering/test/test_cutx.m
% Gathering signal's file informations fileID = fopen("cut_x.txt","r"); formatSpec = '%f'; sizex = [1 Inf]; % Savitzky-Golay parameters polynomial_order = 3; framelen = 11; derivative_order = 1; % Reading from a file the input signal to be filtered x = fscanf(fileID,formatSpec, sizex); x_max = max(x); % Filtering Normalized (Norm 1) input signal using SavitzkyGolay Method y = sgolayfilt(x/x_max, polynomial_order, framelen,'classic'); % Ploting Normalized input signal plot(x/x_max,':'); hold("on"); % Ploting output/filtered signal plot(y,':'); legend('signal', 'filtered signal with 0-th derivative');
0
ALLM/Savitzky-Golay-Filtering
ALLM/Savitzky-Golay-Filtering/test/test_signal_zlens.m
% Gathering signal's file informations fileID = fopen("signal_zlens.txt","r"); formatSpec = '%f'; sizex = [1 inf]; abs_X = 0.0:0.025:0.8; % Savitzky-Golay parameters polynomial_order = 7; framelen = 13; derivative_order = 1; % Reading from a file the input signal to be filtered %x = fscanf(fileID,formatSpec, sizex); data=load("signal_zlens.txt"); data_size = size(data); nrows = data_size(1,1); ncols = data_size(1,2); path="~/Bureau/GitHub_repo/Savitzky-Golay-Filtering/data/output/signal_zlens" def = figure; for i = 1:ncols subplot(3,6,i); x = data(:, i); x_max = max(x); y = sgolayfilt(x/x_max, polynomial_order, framelen); plot(x/x_max,'b'); hold("on"); plot(y,'r'); txt = sprintf('curve %i',i); txt = strcat('filtered signal', txt); txt = strcat('default ', txt); title(txt); grid; end saveas(def, strcat(path,"/default"), "pdf"); savefig(def, strcat(path,"/default")); hold off; classic = figure; for i = 1:ncols subplot(3,6,i); x = data(:, i); x_max = max(x); y = sgolayfilt(x/x_max, polynomial_order, framelen, "classic"); plot(x/x_max,'b'); hold("on"); plot(y,'r'); txt = sprintf('curve %i',i); txt = strcat('filtered signal', txt); txt = strcat('classic', txt); grid; end saveas(classic, strcat(path,"/classic"), "pdf"); savefig(classic, strcat(path,"/classic")); hold off; near = figure; for i = 1:ncols subplot(3,6,i); x = data(:, i); x_max = max(x); y = sgolayfilt(x/x_max, polynomial_order, framelen, "nearest"); plot(x/x_max,'b'); hold("on"); plot(y,'r'); txt = sprintf('curve %i',i); txt = strcat('filtered signal', txt); txt = strcat('nearest-trst', txt); title(txt); grid; end saveas(near, strcat(path,"/nearest"), "pdf"); savefig(near, strcat(path,"/nearest")); hold off; near2 = figure; for i = 1:ncols subplot(3,6,i); x = data(:, i); x_max = max(x); y = sgolayfilt(x/x_max, polynomial_order, framelen, "nearest","no"); plot(x/x_max,'b'); hold("on"); plot(y,'r'); txt = sprintf('curve %i',i); txt = strcat('filtered signal', txt); txt = strcat('nearest-notrst', txt); title(txt); grid; end saveas(near2, strcat(path,"/nearest-no-trst"), "pdf"); savefig(near2, strcat(path,"/nearest-no-trst"));
0
ALLM/TER2019
ALLM/TER2019/CODE_F90_MPI/ModMatrice.f90
module ModMatrice use ModMesh use MPI implicit none integer,parameter::nbr_point_par_ele=3,nombre_node=10181,nombre_ddl=2 contains !JACOBIENNE DE LA TRANSFORMATION subroutine JACOBIENNE(T_node,T_conn,jac,i,nbr_tri) integer,intent(in)::i,nbr_tri TYPE(tab_node),intent(in)::T_node integer,dimension(1:nbr_tri,1:5),intent(in)::T_conn real(rki),dimension(1:2,1:2),intent(out)::jac integer::P1,P2,P3 !i : itérant sur la liste des connectivité des élé triangle !P numero du noeud de l'élément jac=0.d0 P1=T_conn(i,2);P2=T_conn(i,3);P3=T_conn(i,4) jac(1,1)=T_node%c_node(P2,1)-T_node%c_node(P1,1);jac(1,2)=T_node%c_node(P2,2)-T_node%c_node(P1,2) jac(2,1)=T_node%c_node(P3,1)-T_node%c_node(P1,1);jac(2,2)=T_node%c_node(P3,2)-T_node%c_node(P1,2) end subroutine JACOBIENNE !DETERMINANT DE J subroutine DETERMINANT_JAC(jac,det) real(rki),dimension(1:2,1:2),intent(in)::jac real(rki),intent(out)::det det=0. det=jac(1,1)*jac(2,2)-jac(1,2)*jac(2,1) end subroutine DETERMINANT_JAC !INVERSE DE LA JACOBIENNE: subroutine INVERSE_JAC(jac,det,inv_jac) real(rki),dimension(1:2,1:2),intent(in)::jac real(rki),dimension(1:2,1:2),intent(out)::inv_jac real(rki),intent(in)::det real(rki)::inv_det inv_jac=0. !call DETERMINANT_JAC(jac,det) inv_det=1/det inv_jac(1,1)=jac(2,2);inv_jac(2,1)=-jac(2,1) inv_jac(1,2)=-jac(1,2);inv_jac(2,2)=jac(1,1) inv_jac=inv_det*inv_jac end subroutine INVERSE_JAC !MATRICE MODIFIEE DE INV_J POUR CORRESPONDRE A LA FORMULATION DU PB subroutine Q_INV_J(inv_jac,Q) real(rki),dimension(1:2,1:2),intent(in)::inv_jac real(rki),dimension(1:3,1:4),intent(out)::Q Q=0. Q(1,1)=inv_jac(1,1);Q(1,2)=inv_jac(1,2);Q(1,3:4)=0. Q(2,1:2)=0.;Q(2,3)=inv_jac(2,1);Q(2,4)=inv_jac(2,2) Q(3,1)=inv_jac(2,1);Q(3,2)=inv_jac(2,2);Q(3,3)=inv_jac(1,1);Q(3,4)=inv_jac(1,2) end subroutine Q_INV_J !RETOURNE B i.e Q.DN avec DN derivé fct de forme dans base ele ref subroutine GRAD_N(Q,DN,B) real(rki),dimension(1:3,1:4),intent(in)::Q real(rki),dimension(1:4,1:6),intent(in)::DN real(rki),dimension(1:3,1:6),intent(inout)::B !B:=OPERATEUR DERIVATION dans la base de ref :epsilon=B.dpl(élé) integer::i,j,k B=0. DO i=1,3 DO j=1,6 DO k=1,4 B(i,j)=B(i,j)+Q(i,k)*DN(k,j) END DO END DO END DO ! ou B=MATMUL(Q,DN) end subroutine GRAD_N !MATRICE DE RIGIDITE ELEMENTAIRE DE l'ELEMENT CONSIDERE: subroutine MATRICE_RIGIDITE_ELEMENT(B,HOOK,det,K_ele) real(rki),dimension(1:3,1:6),intent(in)::B real(rki),dimension(1:3,1:3),intent(in)::HOOK real(rki),intent(in)::det real(rki),dimension(1:6,1:6),intent(out)::K_ele real(rki),dimension(1:6,1:3)::inter real(rki),dimension(1:6,1:6)::trans real(rki)::ep integer::i,j,k ep=1 K_ele=0. inter=0. !inter=tranpose(B)*HOOK: DO j=1,6 DO i=1,3 DO k=1,3 inter(j,i)=inter(j,i)+B(k,j)*HOOK(k,i) END DO END DO END DO !SINON FAIRE inter=MATMUL(TRANSPOSE(B),HOOK) !k_ele=inter*B: DO i=1,6 DO j=1,6 DO k=1,3 K_ele(i,j)=K_ele(i,j)+inter(i,k)*B(k,j) END DO END DO END DO !SINON FAIRE K_ele=MATMUL(inter,B) K_ele=0.5*ABS(det)*K_ele!*ep !!$trans=TRANSPOSE(K_ele) !!$PRINT*,' ' !!$PRINT*,'K_ele' !!$DO i=1,6 !!$ PRINT*,K_ele(i,:)!-trans(i,:) !!$END DO end subroutine MATRICE_RIGIDITE_ELEMENT SUBROUTINE DPL_IMPO(K_ele,T_conn,T_node,nbr_tri,i,condi_x,condi_y) real(rki),dimension(1:6,1:6),intent(inout)::K_ele integer,intent(in)::i,nbr_tri TYPE(tab_node),intent(in)::T_node integer,dimension(1:nbr_tri,1:5),intent(in)::T_conn real(rki),intent(in)::condi_x,condi_y integer::P1,P2,P3,k1,k,k2 real(rki)::a,b !i : itérant sur la liste des connectivité des élé triangle !P numero du noeud de l'élément P1=T_conn(i,2);P2=T_conn(i,3);P3=T_conn(i,4) DO k=2,4 IF((T_node%c_node(T_conn(i,k),1)==condi_x))THEN !dpl bloqué en x=condi_x, i.e dpl(x)=0: k1=2*k-3 !bijection a=K_ele(k1,k1);K_ele(k1,:)=0.0d0;K_ele(:,k1)=0.0d0;K_ele(k1,k1)=1.0d0!a*nbr_tri PRINT*,'CONDI_X',T_node%c_node(T_conn(i,k),1) ELSE IF((T_node%c_node(T_conn(i,k),2)==condi_y))THEN !dpl bloqué en y=condi_y, i.e dpl(y)=0: k2=2*k-2 !bijection b=K_ele(k2,k2);K_ele(k2,:)=0.0d0;k_ele(:,k2)=0.0d0;K_ele(k2,k2)=1.0d0!b*nbr_tri PRINT*,'CONDI_Y',T_node%c_node(T_conn(i,k),2) END IF END DO END SUBROUTINE DPL_IMPO !SUBROUTINE DE LOCALISATION: subroutine LOC_i(n,NDDL,nbr_tri,T_conn,i,localisation) integer,intent(in)::n,NDDL,nbr_tri integer,dimension(1:nbr_tri,1:5),intent(in)::T_conn integer,intent(in)::i integer,dimension(1:n*NDDL),intent(out)::localisation integer::j,k,l localisation=0 k=1 DO WHILE(k<n*NDDL+1) DO j=2,4 !1,n de 2à4 car stocke colonne 2à4 DO l=1,NDDL localisation(k)=(T_conn(i,j)-1)*NDDL+l k=k+1 END DO END DO END DO end subroutine LOC_i !PRE-TRI SUBROUTINE PRE_TRI(T1,T2,T3,NBR_C,SIZE,rang,L1,L2,L3,RC1,RC2,RC3,status,stateinfo) integer,dimension(MPI_STATUS_SIZE),intent(inout)::status INTEGER,intent(in)::T1,T2,T3,NBR_C,SIZE,rang !L1=TAB_CL(1,:), SIZE = la taille de L1 INTEGER,intent(inout)::stateinfo INTEGER,dimension(1:SIZE),intent(in)::L1,L2 !L2=TAB_CL(2,:) REAL(rki),dimension(1:SIZE),intent(in)::L3 !L3=TAB_V(:) INTEGER,dimension(1:4)::PIV1,PIV2,other INTEGER::cpt,t,i,j,he,TAILLE,GAP INTEGER,dimension(:),allocatable::EX1,EX2 real(rki),dimension(:),allocatable::EX3 INTEGER,dimension(:),allocatable,intent(out)::RC1,RC2 real(rki),dimension(:),allocatable,intent(out)::RC3 INTEGER::TAG CHARACTER(len=3)::rank PIV1(1)=0;PIV1(2)=T1;PIV1(3)=T2;PIV1(4)=T3 PIV2(1)=T1;PIV2(2)=T2;PIV2(3)=T3;PIV2(4)=NBR_C write(rank,fmt='(i3.3)')rang DO t=3,0,-1!0,3 SI ON FAIT LA BOUCLE DE t=0,3 IL Y A UN BUG: PIV1(4)==0 ALORS QU'IL VAUT T3 cpt=0 DO j=1,SIZE IF(L1(j)<=PIV2(t+1))THEN IF(L1(j)>PIV1(t+1))THEN cpt=cpt+1 END IF END IF END DO IF(cpt>0)THEN ALLOCATE (EX1(1:cpt),EX2(1:cpt),EX3(1:cpt));TAG=1 ELSE TAG=0 END IF cpt=0 TAILLE=0;other=0 IF(rang/=t)THEN IF(TAG==1)THEN DO i=1,SIZE IF((L1(i)>PIV1(t+1)).AND.(L1(i)<=PIV2(t+1)))THEN cpt=cpt+1 EX1(cpt)=L1(i);EX2(cpt)=L2(i);EX3(cpt)=L3(i) END IF END DO END IF call MPI_SEND(cpt,1,MPI_INTEGER,t,10+rang+t,MPI_COMM_WORLD,stateinfo) IF(TAG==1)THEN CALL MPI_SEND(EX1(1:cpt),cpt,MPI_INTEGER,t,30+rang+t,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(EX2(1:cpt),cpt,MPI_INTEGER,t,60+rang+t,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(EX3(1:cpt),cpt,MPI_DOUBLE_PRECISION,t,90+rang+t,MPI_COMM_WORLD,stateinfo) DEALLOCATE(EX1,EX2,EX3) END IF ELSE IF(TAG==1)THEN DO i=1,SIZE IF((L1(i)>PIV1(t+1)).AND.(L1(i)<=PIV2(t+1)))THEN cpt=cpt+1 EX1(cpt)=L1(i);EX2(cpt)=L2(i);EX3(cpt)=L3(i) END IF END DO END IF other(rang)=cpt TAILLE=cpt DO he=0,3 IF(he/=t)THEN CALL MPI_RECV(other(he),1,MPI_INTEGER,he,10+he+t,MPI_COMM_WORLD,status,stateinfo) TAILLE=TAILLE+other(he) END IF END DO ALLOCATE(RC1(1:TAILLE),RC2(1:TAILLE),RC3(1:TAILLE)) IF(TAG==1)THEN DO i=1,other(rang) RC1(i)=EX1(i);RC2(i)=EX2(i);RC3(i)=EX3(i) END DO DEALLOCATE(EX1,EX2,EX3) END IF GAP=other(rang) DO he=0,3 IF(other(he)>0.AND.he/=t)THEN!t ou rang)then CALL MPI_RECV(RC1(GAP+1:GAP+other(he)),other(he),MPI_INTEGER,he,30+he+t,MPI_COMM_WORLD,status,stateinfo) CALL MPI_RECV(RC2(GAP+1:GAP+other(he)),other(he),MPI_INTEGER,he,60+he+t,MPI_COMM_WORLD,status,stateinfo) CALL MPI_RECV(RC3(GAP+1:GAP+other(he)),other(he),MPI_DOUBLE_PRECISION,he,90+he+t,MPI_COMM_WORLD,status,stateinfo) GAP=GAP+other(he) END IF END DO END IF END DO PRINT*,'RANG',rang,'FIN BOUCLE t, t=',t END SUBROUTINE PRE_TRI !POUR LE FORMAT SPARSE: SUBROUTINE MAKE_A_LISTE1(rang,NNZ_LOW_PART,CHARGE_ME,ite,it1,k_ite,n_NDDL,LOC,K_ele,TAB_CL,TAB_V) integer,intent(in)::rang,NNZ_LOW_PART,CHARGE_ME,ite,it1,n_NDDL !itération actuelle !nbr non zero dans la partie triangulaire inferieur de K_ele !nbr d'élément traité par chaque proc integer,dimension(1:n_NDDL),intent(in)::LOC real(rki),dimension(1:n_NDDL,1:n_NDDL),intent(in)::K_ele integer,intent(inout)::k_ite integer,dimension(1:NNZ_LOW_PART*CHARGE_ME,1:2),intent(out)::TAB_CL !STOCK cows rows where NNZ in K_ele_exp real(rki),dimension(1:NNZ_LOW_PART*CHARGE_ME),intent(out)::TAB_V !STOCK VAL nnz de K_ele_exp partie trian inf integer::i,j character(len=3)::rank WRITE(rank,fmt='(i3.3)')rang !integer::lenght !lenght=NNZ_LOW_PART*CHARGE_ME !TAB_CL=0;TAB_V=0.d0 IF(ite==it1)THEN k_ite=1 END IF !***POUR "simuler" un format CCS SYMETRIQUE !k_ite=1 DO j=1,n_NDDL DO i=1,n_NDDL !j,n_NDDL !IF(LOC(i)>=LOC(j))THEN IF(K_ele(i,j)/=0.d0)THEN TAB_CL(k_ite,1)=LOC(j);TAB_CL(k_ite,2)=LOC(i) TAB_V(k_ite)=K_ele(i,j) k_ite=k_ite+1 ELSE TAB_CL(k_ite,1)=0;TAB_CL(k_ite,2)=0 TAB_V(k_ite)=0.d0 k_ite=k_ite+1 END IF !END IF END DO END DO END SUBROUTINE MAKE_A_LISTE1 subroutine EXPANSER_RIGIDITE_LOCALE(K_ele,localisation,n,NDDL,Nd,K_ele_expansee) integer,intent(in)::n,NDDL,Nd integer,dimension(1:n*NDDL),intent(in)::localisation real(rki),dimension(1:n*NDDL,1:n*NDDL),intent(in)::K_ele real(rki),dimension(1:Nd*NDDL,1:Nd*NDDL),intent(out)::K_ele_expansee integer::k,l PRINT*,'DANS EXPANSER RIGIDITE LOC' K_ele_expansee=0.d0 DO k=1,n*NDDL print*,'ex_ri_loc',' k=',k DO l=1,n*NDDL !print*,'l=',l K_ele_expansee(localisation(k),localisation(l))=K_ele(k,l) END DO END DO PRINT*,'FIN EXP RIG LOC' end subroutine EXPANSER_RIGIDITE_LOCALE !****************************************************************************************************** subroutine FORCE_LOCALE_SUIVANT_Y(nume,P,longueur,n,Nd,NDDL,nbr_tri,T_node,T_conn,F_LOCALE,MODEL) real(rki),intent(in)::P,longueur integer,intent(in)::nume,n,Nd,NDDL,nbr_tri,MODEL TYPE(tab_node),intent(in)::T_node integer,dimension(1:nbr_tri,1:5),intent(in)::T_conn real(rki),dimension(1:n*NDDL),intent(out)::F_LOCALE !integer::i,k,j,l integer::P1,P2,P3 real(rki)::X1,X2,X3,Y1,Y2,Y3,ep ep=0.00003 F_LOCALE=0.d0 P1=T_conn(nume,2);P2=T_conn(nume,3);P3=T_conn(nume,4) X1=T_node%c_node(P1,1);X2=T_node%c_node(P2,1);X3=T_node%c_node(P3,1) Y1=T_node%c_node(P1,2);Y2=T_node%c_node(P2,2);Y3=T_node%c_node(P3,2) SELECT CASE(MODEL) CASE(0) IF(Y1==0. .AND. Y2==0.)THEN F_LOCALE(2)=-P*abs(X1-X2)*0.5;F_LOCALE(4)=F_LOCALE(2) ELSE IF(Y1==0. .AND. Y3==0.)THEN F_LOCALE(2)=-P*abs(X1-X3)*0.5;F_LOCALE(6)=F_LOCALE(2) ELSE IF(Y2==0. .AND. Y3==0.)THEN F_LOCALE(4)=-P*abs(X2-X3)*0.5;F_LOCALE(6)=F_LOCALE(4) ELSE IF(Y1==longueur .AND. Y2==longueur)THEN F_LOCALE(2)=P*abs(X1-X2)*0.5;F_LOCALE(4)=F_LOCALE(2) ELSE IF(Y1==longueur .AND. Y3==longueur)THEN F_LOCALE(2)=P*abs(X1-X3)*0.5;F_LOCALE(6)=F_LOCALE(2) ELSE IF(Y2==longueur .AND. Y3==longueur)THEN F_LOCALE(4)=P*abs(X2-X3)*0.5;F_LOCALE(6)=F_LOCALE(4) END IF CASE(1) IF(Y1==longueur .AND. Y2==longueur)THEN F_LOCALE(2)=P*abs(X1-X2)*0.5;F_LOCALE(4)=F_LOCALE(2) ELSE IF(Y1==longueur .AND. Y3==longueur)THEN F_LOCALE(2)=P*abs(X1-X3)*0.5;F_LOCALE(6)=F_LOCALE(2) ELSE IF(Y2==longueur .AND. Y3==longueur)THEN F_LOCALE(4)=P*abs(X2-X3)*0.5;F_LOCALE(6)=F_LOCALE(4) END IF END SELECT end subroutine FORCE_LOCALE_SUIVANT_Y subroutine FORCE_LOCALE_SUIVANT_X(nume,P,largeur,n,Nd,NDDL,nbr_tri,T_node,T_conn,F_LOCALE) real(rki),intent(in)::P,largeur integer,intent(in)::nume,n,Nd,NDDL,nbr_tri TYPE(tab_node),intent(in)::T_node integer,dimension(1:nbr_tri,1:5),intent(in)::T_conn real(rki),dimension(1:n*NDDL),intent(out)::F_LOCALE !integer::i,k,j,l integer::P1,P2,P3 real(rki)::X1,X2,X3,Y1,Y2,Y3 F_LOCALE=0.0d0 P1=T_conn(nume,2);P2=T_conn(nume,3);P3=T_conn(nume,4) X1=T_node%c_node(P1,1);X2=T_node%c_node(P2,1);X3=T_node%c_node(P3,1) Y1=T_node%c_node(P1,2);Y2=T_node%c_node(P2,2);Y3=T_node%c_node(P3,2) !PRINT*,'Y ',Y1,' ',Y2,' ',Y3,'longueur',longueur,' P',P1,' ',P2,' ',P3 !P=E_L*facteur_de_dpl !159*10**9*0.001 !!$ IF(X1==0.0d0 .AND. X2==0.0d0)THEN !!$ !PRINT*,'$$$$$$$$$$$$$$$$$$$$$1',-P*abs(Y1-Y2)*0.5,' ',abs(Y1-Y2) !!$ F_LOCALE(1)=-P*abs(Y1-Y2)*0.5;F_LOCALE(3)=F_LOCALE(1) !!$ ELSE IF(X1==0.0d0 .AND. X3==0.0d0)THEN !!$ !PRINT*,'$$$$$$$$$$$$$$2' !!$ F_LOCALE(1)=-P*abs(Y1-Y3)*0.5;F_LOCALE(5)=F_LOCALE(1) !!$ ELSE IF(X2==0.0d0 .AND. X3==0.0d0)THEN !!$ !PRINT*,'$$$$$$$$$$$$$$$3' !!$ F_LOCALE(3)=-P*abs(Y2-Y3)*0.5;F_LOCALE(5)=F_LOCALE(3) IF(ABS(X1-largeur)<=0.0000001 .AND. ABS(X2-largeur)<=0.0000001)THEN!(X1==largeur .AND. X2==largeur)THEN !PRINT*,'$$$$$$$$$$*******************$$$$$$$$$$$$$$$$$$$$$$$4',abs(Y1-Y2) F_LOCALE(1)=P*abs(Y1-Y2)*0.5;F_LOCALE(3)=F_LOCALE(1) ELSE IF(ABS(X1-largeur)<=0.0000001 .AND. ABS(X3-largeur)<=0.0000001)THEN!(X1==largeur .AND. X3==largeur)THEN !PRINT*,'*********5' F_LOCALE(1)=P*abs(Y1-Y3)*0.5;F_LOCALE(5)=F_LOCALE(1) ELSE IF(ABS(X2-largeur)<=0.0000001 .AND. ABS(X3-largeur)<=0.0000001)THEN!(X2==largeur .AND. X3==largeur)THEN !PRINT*,'********6' F_LOCALE(3)=P*abs(Y2-Y3)*0.5;F_LOCALE(5)=F_LOCALE(3) END IF end subroutine FORCE_LOCALE_SUIVANT_X subroutine FORCE_LOCALE_SUIVANT_Y_EXPANSEE(n,NDDL,Nd,localisation,F_LOCALE,F_EXPANSEE) integer,intent(in)::n,NDDL,Nd integer,dimension(1:n*NDDL),intent(in)::localisation real(rki),dimension(1:n*NDDL),intent(in)::F_LOCALE real(rki),dimension(1:Nd*NDDL),intent(out)::F_EXPANSEE integer::k,rank F_EXPANSEE=0.d0 DO k=1,n*NDDL F_EXPANSEE(localisation(k))=F_LOCALE(k) END DO end subroutine FORCE_LOCALE_SUIVANT_Y_EXPANSEE subroutine node_loc(n,NDDL,nbr_tri,ite,rang,localisation,T_conn) integer,intent(in)::n,NDDL,nbr_tri,ite,rang integer,dimension(1:n*NDDL),intent(in)::localisation integer,dimension(1:nbr_tri,1:5),intent(in)::T_conn integer::k,j character(len=3)::rank write(rank,fmt='(i3.3)')rang OPEN(10+rang,file='NODE_LOC'//trim(adjustl(rank))//'.dat',position='append') DO j=2,4 WRITE(10+rang,*)T_conn(ite,1),T_conn(ite,j),localisation(1:6) END DO CLOSE(10+rang) end subroutine node_loc SUBROUTINE WR_K(userchoice,Nd,NDDL,NNZ) integer,intent(inout)::userchoice integer,intent(in)::Nd,NDDL,NNZ !character(len=21),parameter::R_F='CLV_PC001_RANK000.dat' character(len=10),parameter::R_F='CCS000.dat' character(len=10),parameter::W_R='K_VIEW.vtk' integer::i,j,a,b,d,err real(rki)::c real(rki),dimension(:,:),allocatable::K K=0.d0 SELECT CASE(userchoice) CASE(1) err=0 ALLOCATE(K(1:Nd*NDDL,1:ND*NDDL)) !allocate(K(1:Nd*NDDL)) K=0.d0 OPEN(30,file=W_R) write(30,fmt='(1A26)') '# vtk DataFile Version 3.0' write(30,fmt='(1A4)') 'cell' write(30,fmt='(1A5)') 'ASCII' write(30,fmt='(1A25)') 'DATASET STRUCTURED_POINTS' write(30,fmt='(1A11,1I5,1A1,1I5,1A2)') 'DIMENSIONS ', Nd*NDDL ,' ' , Nd*NDDL, ' 1' write(30,fmt='(1A12)') 'ORIGIN 0 0 0' write(30,fmt='(1A13)') 'SPACING 1 1 1' write(30,fmt='(1A11,1I9)') 'POINT_DATA ' , (Nd*NDDL)**2 write(30,fmt='(1A18)') 'SCALARS cell float' write(30,fmt='(1A20)') 'LOOKUP_TABLE default' i=1 OPEN(40,file=R_F) i=1 DO WHILE(i<NNZ+1) READ(40,*)a,b,c,d PRINT*,'i=',i,' ',a,b,c,d K(b,a)=c i=i+1 PRINT*,'i=',i END DO DO i=1,Nd*NDDL WRITE(30,*)K(i,:) END DO CLOSE(40) CLOSE(30) deallocate(K) userchoice=0 if(err<0)then print*,'fin de fichier ' else print*,'erreur de lecture' end if CASE DEFAULT userchoice=0 END SELECT END SUBROUTINE WR_K subroutine SAVE_K_me(Nd,NDDL,K_GLOBALE,rang,num_pc,stateinfo,status) integer,dimension(MPI_STATUS_SIZE),intent(inout)::status integer,intent(inout)::stateinfo integer,intent(in)::Nd,NDDL,rang,num_pc real(rki),dimension(1:Nd*NDDL,1:Nd*NDDL),intent(in)::K_GLOBALE character(len=3)::rank,pc integer::i,j write(rank,fmt='(i3.3)')rang write(pc,fmt='(i3.3)')num_pc open(20+rang,file='PC_'//trim(adjustl(pc))//'_pour_'//'K_'//trim(adjustl(rank))//'.dat') DO j=1,Nd*NDDL DO i=1,ND*NDDL write(20+rang,*)K_GLOBALE(i,j) END DO END DO close(20+rang) end subroutine SAVE_K_ME subroutine VIEW_K_GLOBALE(Nd,NDDL,K_GLOBALE) integer,intent(in)::Nd,NDDL real(rki),dimension(1:Nd*NDDL,1:Nd*NDDL),intent(in)::K_GLOBALE real(rki),dimension(1:Nd*NDDL)::A integer::i,j open(20,file='view_K_globale.vtk') write(20,*)'# vtk DataFile Version 3.0' write(20,*)'cell' write(20,*)'ASCII' write(20,*)'DATASET STRUCTURED_POINTS' write(20,*)'DIMENSIONS ',Nd*NDDL,' ',Nd*NDDL,' 1' write(20,*)'ORIGIN 0 0 0 ' write(20,*)'SPACING 1 1 1' write(20,*)'POINT_DATA ',(Nd*NDDL)**2 write(20,*)'SCALARS cell float' write(20,*)'LOOKUP_TABLE default' DO j=1,Nd*NDDL A(:)=K_GLOBALE(:,j) !DO i=1,ND*NDDL !IF(K_GLOBALE(i,j)==0.d0)THEN write(20,*)A(:) !END DO END DO close(20) end subroutine VIEW_K_GLOBALE end module ModMatrice
0
ALLM/TER2019
ALLM/TER2019/CODE_F90_MPI/ModMesh.f90
Module ModMesh implicit none integer,parameter::rki=8 TYPE tab_node integer,dimension(:),allocatable::n_node real(rki),dimension(:,:),allocatable::c_node !1::x, 2::y, 3::z END TYPE tab_node !LES 2 TYPES SUIVANT SONT POUR STOCKER LES NODES QUI SONT SUR LES LIGNES EN SUD ET NORD !C'EST POUR LES FORCES TYPE info_pts integer::num_node real(rki)::x_node,y_node END TYPE info_pts TYPE TAB_INFO TYPE(info_pts),dimension(1:6)::liste END TYPE TAB_INFO contains subroutine read_mesh(mesh_file,nbr_node,nbr_tri,T_node,T_conn,rang,MARK1,MARK2) character(len=*),intent(in)::mesh_file character(len=25)::CHEMIN integer,intent(in)::nbr_node,nbr_tri,rang,MARK1,MARK2 !MARK1 1ere ligne où les éléments sont triangles, MARK2 dernière ligne où les élé sont triangles integer::k,j,b,c,n1,n2,n3,n4,n5,n6,n7,n8,T real::a !a,b,c dummy variables real(rki)::x,y,z !x,y,z coordonnées nodes integer::num_node !numero du node TYPE(tab_node),intent(out)::T_node integer,dimension(1:nbr_tri,1:5),intent(out)::T_conn ALLOCATE(T_node%n_node(1:nbr_node),T_node%c_node(1:nbr_node,1:3)) CHEMIN='./MESH/'//mesh_file open(10,file=CHEMIN)!mesh_file) k=1 DO WHILE(k<6) READ(10,*) k=k+1 END DO PRINT*,'k=',k T=0 DO WHILE(k<nbr_node+6) read(10,*)num_node,x,y,z T=T+1 T_node%n_node(num_node)=num_node T_node%c_node(num_node,1)=x T_node%c_node(num_node,2)=y T_node%c_node(num_node,3)=z IF(RANG==0)THEN PRINT*,'k=',k,' ',T_node%n_node(num_node),T_node%c_node(num_node,:) END IF !print*,'k=',k,' ',num_node,x,y,z k=k+1 END DO PRINT*,k !k=10187 read(10,*) !lit $EndNodes k=k+1 PRINT*,k read(10,*) !lit $Elements k=k+1 PRINT*,k read(10,*) !lit NBR d'ele total k=k+1 PRINT*,k,'avvv' DO WHILE(k<MARK1) read(10,*) k=k+1 END DO j=1 DO WHILE(k<MARK2+1) k=k+1 !on lit cette ligne read(10,*)n1,n2,n3,n4,n5,n6,n7,n8 !PRINT*,k,' ',n1,n2,n3,n4,n5,n6,n7,n8 T_conn(j,1)=n1 !num ele T_conn(j,2)=n6;T_conn(j,3)=n7;T_conn(j,4)=n8 !num sommets T_conn(j,5)=n5 !num elementary tag IF(rang==0)THEN PRINT*,j,' ',T_conn(j,1),T_conn(j,2),T_conn(j,3),T_conn(j,4),T_conn(j,5) END IF j=j+1 END DO close(10) PRINT*,'NBR NODES= ',nbr_node,' T=',T,' j=',j-1 end subroutine read_mesh SUBROUTINE READ_DATA(rang,file_name,mesh_name,Nd,N_TRI,FIRST_ROW,LAST_ROW,KMAX,TOL& ,PMAX,STEP,N_STEP,MODEL,LONG,LARG,RAY,condi_x,condi_y)!,DIR) INTEGER,intent(in)::rang CHARACTER(LEN=*),intent(in)::file_name CHARACTER(LEN=*),intent(out)::mesh_name INTEGER,intent(out)::Nd,N_TRI,FIRST_ROW,LAST_ROW,KMAX!,DIR REAL(rki),intent(out)::TOL REAL(rki),intent(out)::PMAX INTEGER,intent(out)::STEP,N_STEP,MODEL REAL(rki),intent(out)::LONG,LARG,RAY,condi_x,condi_y OPEN(10+rang,file=file_name) read(10+rang,*) read(10+rang,*)mesh_name read(10+rang,*) read(10+rang,*)Nd read(10+rang,*) read(10+rang,*)N_TRI read(10+rang,*) read(10+rang,*)FIRST_ROW read(10+rang,*) read(10+rang,*)LAST_ROW read(10+rang,*) read(10+rang,*)KMAX read(10+rang,*) read(10+rang,*)TOL !read(10+rang,*) !read(10+rang,*)DIR read(10+rang,*) read(10+rang,*)PMAX read(10+rang,*) read(10+rang,*)STEP read(10+rang,*) read(10+rang,*)N_STEP read(10+rang,*) read(10+rang,*)MODEL read(10+rang,*) read(10+rang,*)LONG read(10+rang,*) read(10+rang,*)LARG read(10+rang,*) read(10+rang,*)RAY read(10+rang,*) read(10+rang,*)condi_x read(10+rang,*) read(10+rang,*)condi_y CLOSE(10+rang) END SUBROUTINE READ_DATA SUBROUTINE DEFORMEE_DPL(rang,INPUT_MESH,OUTPUT_DEF,OUTPUT_X,OUTPUT_Y,Nd,SOLX,SOLY) INTEGER,intent(in)::rang,Nd CHARACTER(LEN=*),intent(in)::INPUT_MESH CHARACTER(LEN=*),intent(out)::OUTPUT_DEF,OUTPUT_X,OUTPUT_Y REAL(rki),DIMENSION(1:Nd),intent(in)::SOLX,SOLY integer::k,a real(rki)::x,y,z character(len=25)::CHEMIN CHEMIN='./MESH/'//INPUT_MESH IF(rang==0)THEN OPEN(10,file=CHEMIN)!INPUT_MESH) OPEN(20,file=OUTPUT_DEF) READ(10,*);READ(10,*);READ(10,*);READ(10,*);READ(10,*) DO k=1,Nd READ(10,*)a,x,y,z WRITE(20,*)a,x+SOLX(k),y+SOLY(k),z END DO CLOSE(20) CLOSE(10) ELSE IF(rang==1)THEN OPEN(30,file=OUTPUT_X) DO k=1,Nd WRITE(30,*)k,SOLX(k) END DO CLOSE(30) ELSE IF(rang==2)THEN OPEN(40,file=OUTPUT_Y) DO k=1,Nd WRITE(40,*)k,SOLY(k) END DO CLOSE(40) END IF END SUBROUTINE DEFORMEE_DPL SUBROUTINE MAP_RESIDUS(rang,OUTPUT_X,OUTPUT_Y,Nd,SOLX,SOLY) INTEGER,intent(in)::rang,Nd CHARACTER(LEN=*),intent(out)::OUTPUT_X,OUTPUT_Y REAL(rki),DIMENSION(1:Nd),intent(in)::SOLX,SOLY integer::k real(rki)::x,y,z IF(rang==0)THEN OPEN(30,file=OUTPUT_X) DO k=1,Nd WRITE(30,*)k,SOLX(k) END DO CLOSE(30) ELSE IF(rang==3)THEN OPEN(40,file=OUTPUT_Y) DO k=1,Nd WRITE(40,*)k,SOLY(k) END DO CLOSE(40) END IF END SUBROUTINE MAP_RESIDUS end Module ModMesh
0
ALLM/TER2019
ALLM/TER2019/CODE_F90_MPI/ModPGC.f90
module ModPGC use mpi use ModMesh implicit none contains subroutine PGC(rang,it1,itN,NNZ_P,kmax,TOL,stateinfo,status,X,VAL,J_IND,I_cpt,b,Nd,NDDL,RES,H_NM) integer,intent(in)::rang,it1,itN,NNZ_P,Nd,NDDL,kmax real(rki),intent(in)::TOL CHARACTER(LEN=*),intent(in)::H_NM !NNZ_P := nbr de non zero par processeur integer,intent(inout)::stateinfo integer,dimension(MPI_STATUS_SIZE),intent(inout)::status real(rki),dimension(it1:itN),intent(inout)::X real(rki),dimension(it1:itN),intent(out)::RES real(rki),dimension(1:NNZ_P),intent(in)::VAL !ele non nul integer,dimension(1:NNZ_P),intent(in)::J_ind !num des cols ou ele non nul integer,dimension(1:itN-it1+2),intent(in)::I_cpt real(rki),dimension(it1:itN),intent(in)::b real(rki),dimension(it1:itN)::r,z real(rki),dimension(1:Nd*NDDL)::p,Ap real(rki)::beta,alpha,gamma real(rki)::beta_P,alpha_p real(rki)::drz,dApp,drz_old !<r|z>, <Ap|p> real(rki)::drz_P,dApp_P integer,dimension(1:2,1:4)::CHARGE integer::k IF(rang==0)THEN OPEN(20,file='./RES/'//trim(H_NM)//'res.txt') END IF !INI: beta=0;beta_P=0;k=0 CALL COMM_CHARGE(rang,stateinfo,status,it1,itN,CHARGE) PRINT*,'FIN COMM_CHARGE' !INITIALISATION DE X à Xo=0.0d0: X=0.0d0 !ro=b-A*X et beta =norm2(ro): r(it1:itN)=b(it1:itN) beta_P=DOT_PRODUCT(r(it1:itN),r(it1:itN)) PRINt*,'INIT beta_P' CALL REDUCTION_REEL(rang,stateinfo,status,beta,beta_P) beta=sqrt(beta) PRINT*,'REDUCTION INITIALE DE beta' !zo=INV_DIAG(A).ro: (precondi jacobi) CALL PRE_DIAG(rang,it1,itN,NNZ_P,Nd,NDDL,VAL,J_IND,I_cpt,z(it1:itN),r(it1:itN)) !INI p à z: p(it1:itN)=z(it1:itN) PRINT*,'INIT zo et po' IF(rang==0)THEN WRITE(20,*)k,beta END IF CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) PRINT*,'DEBUT BOUCLE PGC' DO WHILE((k<kmax+1) .AND. (beta>TOL)) k=k+1 !CALCUL DE Ap_k: Ap=A.p !SEND&RECV POUR QUE TOUS LES PROCS connaissent P(1:Nd*NDDL): CALL SEND_RECV_VECT(rang,CHARGE,Nd,NDDL,stateinfo,status,p) CALL SP_PMV(rang,it1,itN,NNZ_P,Nd,NDDL,VAL,J_IND,I_cpt,p,Ap) !CALCUL de <Ap|p>: dApp_P=DOT_PRODUCT(Ap(it1:itN),p(it1:itN)) CALL REDUCTION_REEL(rang,stateinfo,status,dApp,dApp_P) !CALCUL de <r|z>: drz_P=DOT_PRODUCT(r(it1:itN),z(it1:itN)) CALL REDUCTION_REEL(rang,stateinfo,status,drz,drz_P) !on doit stocker drz dans dzr_old: drz_old=drz !CALCUL de alpha_k: alpha=<r|z>/<Ap|p>: alpha=drz/dApp !CALCUL DE X_k+1:=X_k+alpha_k.p_k: X(it1:itN)=X(it1:itN)+alpha*p(it1:itN) !CALCUL DE r_k+1=r_k-alpha_k*Ap_k: r(it1:itN)=r(it1:itN)-alpha*Ap(it1:itN) !CALCUL DE z_k+1=INV_DIAG(A)*r: CALL PRE_DIAG(rang,it1,itN,NNZ_P,Nd,NDDL,VAL,J_IND,I_cpt,z(it1:itN),r(it1:itN)) !RECALCUL DE <r|z>: drz_P=DOT_PRODUCT(r(it1:itN),z(it1:itN)) CALL REDUCTION_REEL(rang,stateinfo,status,drz,drz_P) !CALCUL DE GAMMA:=drz/drz_old gamma=drz/drz_old !CALCUL DE P_K+1=Z_K+GAMMA*P_K: p(it1:itN)=z(it1:itN)+gamma*p(it1:itN) !CALCUL DE LA NORME DU RESIDU BETA: beta_P=DOT_PRODUCT(r(it1:itN),r(it1:itN)) CALL REDUCTION_REEL(rang,stateinfo,status,beta,beta_P) beta=sqrt(beta) IF(rang==0)THEN WRITE(20,*)k,beta PRINT*,'k=',k,' beta=',beta,'TOL',TOL END IF END DO IF(rang==0)THEN CLOSE(20) END IF RES=r end subroutine PGC subroutine COMM_CHARGE(rang,stateinfo,status,it1,itN,CHARGE) integer,intent(in)::rang,it1,itN integer,intent(inout)::stateinfo integer,dimension(MPI_STATUS_SIZE),intent(inout)::status integer,dimension(1:2,1:4),intent(out)::CHARGE integer::i,he CHARGE(1,rang+1)=it1;CHARGE(2,rang+1)=itN DO he=0,3 IF(rang/=he)THEN CALL MPI_SEND(CHARGE(1:2,rang+1),2,MPI_INTEGER,he,10+rang,MPI_COMM_WORLD,stateinfo) ELSE DO i=0,3 IF(i/=rang)THEN CALL MPI_RECV(charge(1:2,i+1),2,MPI_INTEGER,i,10+i,MPI_COMM_WORLD,status,stateinfo) END IF END DO END IF END DO end subroutine COMM_CHARGE subroutine SEND_RECV_VECT(rang,CHARGE,Nd,NDDL,stateinfo,status,V_P) integer,intent(in)::rang,Nd,NDDL integer,dimension(1:2,1:4),intent(in)::CHARGE integer,intent(inout)::stateinfo integer,dimension(MPI_STATUS_SIZE),intent(inout)::status real(rki),dimension(1:Nd*NDDL),intent(inout)::V_P !real(rki),dimension(1:Nd*NDDL),intent(out)::V integer::i,he,G,D DO he=0,3 IF(rang/=he)THEN G=CHARGE(1,rang+1);D=CHARGE(2,rang+1) CALL MPI_SEND(V_P(G:D),D-G+1,MPI_DOUBLE_PRECISION,he,10+rang,MPI_COMM_WORLD,stateinfo) ELSE DO i=0,3 IF(i/=rang)THEN G=CHARGE(1,i+1);D=CHARGE(2,i+1) CALL MPI_RECV(V_P(G:D),D-G+1,MPI_DOUBLE_PRECISION,i,10+i,MPI_COMM_WORLD,status,stateinfo) END IF END DO END IF END DO end subroutine SEND_RECV_VECT subroutine REDUCTION_REEL(rang,stateinfo,status,R,R_P) integer,intent(in)::rang integer,intent(inout)::stateinfo integer,dimension(MPI_STATUS_SIZE),intent(inout)::status real(rki),intent(in)::R_P real(rki),intent(inout)::R real(rki)::reduc integer::he !*** SEND R_P: IF(rang/=0)THEN CALL MPI_SEND(R_P,1,MPI_DOUBLE_PRECISION,0,10+rang,MPI_COMM_WORLD,stateinfo) ELSE R=R_P do he=1,3 CALL MPI_RECV(reduc,1,MPI_DOUBLE_PRECISION,he,10+he,MPI_COMM_WORLD,status,stateinfo) R=R+reduc end do END IF !*** SEND R: IF(rang==0)THEN do he=1,3 CALL MPI_SEND(R,1,MPI_DOUBLE_PRECISION,he,10+he,MPI_COMM_WORLD,stateinfo) end do ELSE CALL MPI_RECV(R,1,MPI_DOUBLE_PRECISION,0,10+rang,MPI_COMM_WORLD,status,stateinfo) END IF end subroutine REDUCTION_REEL subroutine PRE_DIAG(rang,it1,itN,NNZ_P,Nd,NDDL,VAL,J_IND,I_cpt,z,r) integer,intent(in)::rang,it1,itN,NNZ_P,Nd,NDDL real(rki),dimension(1:NNZ_P),intent(in)::VAL integer,dimension(1:NNZ_P),intent(in)::J_IND integer,dimension(1:itN-it1+2),intent(in)::I_cpt real(rki),dimension(it1:itN),intent(out)::z !z=INV_DIAG(A).r real(rki),dimension(it1:itN),intent(in)::r !le residu !INV_DIAG := l'inverse de DIAG(A) pour le preconditionneur, avec A.X=b integer::i,k,a,C,d,b,NNZ_R !NNZ_P := nbr de non zero par processeur !NNZ_R := nbr de non zero par ligne par proc d=0;a=1;b=0;C=0 DO i=it1,itN NNZ_R=I_cpt(a+1)-I_cpt(a) IF(NNZ_R/=0)THEN DO k=1,NNZ_R b=k+d C=J_IND(b) if(C==i)then z(i)=r(C)/VAL(b) end if END DO d=d+NNZ_R END IF a=a+1 END DO end subroutine PRE_DIAG !PRODUIT MATRICE VECTEUR: subroutine SP_PMV(rang,it1,itN,NNZ_P,Nd,NDDL,VAL,J_IND,I_cpt,VECT,PMV) integer,intent(in)::rang,it1,itN,NNZ_P,Nd,NDDL real(rki),dimension(1:NNZ_P),intent(in)::VAL integer,dimension(1:NNZ_P),intent(in)::J_IND integer,dimension(1:itN-it1+2),intent(in)::I_cpt real(rki),dimension(1:Nd*NDDL),intent(in)::VECT real(rki),dimension(1:Nd*NDDL),intent(out)::PMV integer::i,j,k,a,b,d,C,NNZ_R d=0;a=1;b=0;C=0;PMV=0.0d0 DO i=it1,itN NNZ_R=I_cpt(a+1)-I_cpt(a) IF(NNZ_R/=0)THEN do k=1,NNZ_R b=d+k C=J_IND(b) PMV(i)=PMV(i)+VAL(b)*VECT(C) end do d=d+NNZ_R END IF a=a+1 END DO end subroutine SP_PMV !FORMAT SPARSE subroutine CCS(S_SIZE,Nd,NDDL,CCS_it1,CCS_itN,S_CL,S_V,VAL,J_IND,I_cpt) integer,intent(in)::S_SIZE,Nd,NDDL,CCS_it1,CCS_itN integer,dimension(1:S_SIZE,1:2),intent(in)::S_CL real(rki),dimension(1:S_SIZE),intent(in)::S_V real(rki),dimension(1:S_SIZE),intent(out)::VAL integer,dimension(1:S_SIZE),intent(out)::J_IND integer,dimension(1:(CCS_itN-CCS_it1)+2),intent(out)::I_cpt !integer,dimension(1:(Nd*NDDL)+1),intent(out)::I_cpt integer::i,j,k,NNZ_R,cpt I_cpt(1)=1;cpt=0;k=0 DO i=CCS_it1,CCS_itN NNZ_R=0;k=k+1 DO j=1,S_SIZE IF(S_CL(j,1)==i)THEN NNZ_R=NNZ_R+1;cpt=cpt+1 VAL(cpt)=S_V(j);J_IND(cpt)=S_CL(j,2) END IF END DO I_cpt(k+1)=NNZ_R+I_cpt(k) END DO end subroutine CCS subroutine SEND_RECV_F_GLO(rang,CHARGE,it1,itN,Nd,NDDL,stateinfo,status,V_P,F_GP) integer,intent(in)::rang,Nd,NDDL,it1,itN integer,dimension(1:2,1:4),intent(in)::CHARGE integer,intent(inout)::stateinfo integer,dimension(MPI_STATUS_SIZE),intent(inout)::status real(rki),dimension(it1:itN),intent(inout)::V_P real(rki),dimension(1:Nd*NDDL),intent(inout)::F_GP !F_GLOBAL PAR PROC real(rki),dimension(:),allocatable::V_reduc integer::i,he,G,D ALLOCATE(V_reduc(it1:itN)) V_P(it1:itN)=F_GP(it1:itN) DO he=0,3 IF(rang/=he)THEN G=CHARGE(1,he+1);D=CHARGE(2,he+1) CALL MPI_SEND(F_GP(G:D),D-G+1,MPI_DOUBLE_PRECISION,he,10+rang,MPI_COMM_WORLD,stateinfo) ELSE DO i=0,3 IF(i/=rang)THEN !G=CHARGE(1,rang+1);D=CHARGE(2,rang+1) !CALL MPI_RECV(V_reduc(G:D),D-G+1,MPI_DOUBLE_PRECISION,i,10+i,MPI_COMM_WORLD,status,stateinfo) CALL MPI_RECV(V_reduc(it1:itN),itN-it1+1,MPI_DOUBLE_PRECISION,i,10+i,MPI_COMM_WORLD,status,stateinfo) V_P(it1:itN)=V_P(it1:itN)+V_reduc(it1:itN) END IF END DO END IF END DO DEALLOCATE(V_reduc) end subroutine SEND_RECV_F_GLO subroutine SEND_RECV_SOL(rang,CHARGE,CCS_it1,CCS_itN,Nd,NDDL,stateinfo,status,X,SOL_X,SOL_Y) integer,intent(in)::rang,Nd,NDDL,CCS_it1,CCS_itN integer,dimension(1:2,1:4),intent(in)::CHARGE integer,intent(inout)::stateinfo integer,dimension(MPI_STATUS_SIZE),intent(inout)::status real(rki),dimension(CCS_it1:CCS_itN),intent(in)::X real(rki),dimension(1:Nd),intent(inout)::SOL_X,SOL_Y !DPL_X DPL_Y PAR PROC real(rki),dimension(:),allocatable::SOL_Xreduc1,SOL_Yreduc1,SOL_Xreduc2,SOL_Yreduc2 integer::i,he,G,D,k,SIZE_X,a,b a=0;b=0 ALLOCATE(SOL_Xreduc1(1:Nd),SOL_Yreduc1(1:Nd),SOL_Xreduc2(1:Nd),SOL_Yreduc2(1:Nd)) SIZE_X=CCS_itN-CCS_it1+1 SOL_X=0.0d0;SOL_Y=0.0d0 SOL_Xreduc1=0.0d0;SOL_Yreduc1=0.0d0;SOL_Xreduc2=0.0d0;SOL_Yreduc2=0.0d0 DO k=CCS_it1,CCS_itN IF(mod(k,2)==0)THEN SOL_Y(k/2)=X(k) ELSE a=(k-mod(k,2))/2+mod(k,2) SOL_X(a)=X(k) END IF END DO SOL_Xreduc2=SOL_X SOL_Yreduc2=SOL_Y DO he=0,3 IF(rang/=he)THEN !G=CHARGE(1,rang+1);D=CHARGE(2,rang+1) CALL MPI_SEND(SOL_Xreduc2(1:Nd),Nd,MPI_DOUBLE_PRECISION,he,10+rang,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(SOL_Yreduc2(1:Nd),Nd,MPI_DOUBLE_PRECISION,he,10+rang,MPI_COMM_WORLD,stateinfo) ELSE DO i=0,3 IF(i/=rang)THEN !G=CHARGE(1,i+1);D=CHARGE(2,i+1) CALL MPI_RECV(SOL_Xreduc1(1:Nd),Nd,MPI_DOUBLE_PRECISION,i,10+i,MPI_COMM_WORLD,status,stateinfo) CALL MPI_RECV(SOL_Yreduc1(1:Nd),Nd,MPI_DOUBLE_PRECISION,i,10+i,MPI_COMM_WORLD,status,stateinfo) SOL_X=SOL_X+SOL_Xreduc1 SOL_Y=SOL_Y+SOL_Yreduc1 END IF END DO END IF END DO DEALLOCATE(SOL_Xreduc1,SOL_Yreduc1,SOL_Xreduc2,SOL_Yreduc2) end subroutine SEND_RECV_SOL SUBROUTINE FIRST_REDUCTION_SIGMA_OU_DEF(rang,Nd,COEF_POND,SIGMA_GLO,DUMMY1,DUMMY2,stateinfo,status) !OPERATION DE REDUCTION FACON TRI PAIR-IMPAIR: integer,intent(inout)::stateinfo integer,dimension(MPI_STATUS_SIZE),intent(inout)::status INTEGER,intent(in)::rang,Nd INTEGER,dimension(1:Nd),intent(inout)::COEF_POND INTEGER,dimension(:),allocatable,intent(inout)::DUMMY2 REAL(rki),dimension(1:Nd),intent(inout)::SIGMA_GLO REAL(rki),dimension(:),allocatable,intent(inout)::DUMMY1 IF(rang==1)THEN CALL MPI_SEND(COEF_POND(1:Nd),Nd,MPI_INTEGER,0,30,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(SIGMA_GLO(1:Nd),Nd,MPI_DOUBLE_PRECISION,0,31,MPI_COMM_WORLD,stateinfo) ELSE IF(rang==0)THEN ALLOCATE(DUMMY1(1:Nd),DUMMY2(1:Nd)) CALL MPI_RECV(DUMMY2(1:Nd),Nd,MPI_INTEGER,1,30,MPI_COMM_WORLD,status,stateinfo) CALL MPI_RECV(DUMMY1(1:Nd),Nd,MPI_DOUBLE_PRECISION,1,31,MPI_COMM_WORLD,status,stateinfo) COEF_POND=COEF_POND+DUMMY2 SIGMA_GLO=SIGMA_GLO+DUMMY1 DEALLOCATE(DUMMY1,DUMMY2) ELSE IF(rang==2)THEN CALL MPI_SEND(COEF_POND(1:Nd),Nd,MPI_INTEGER,3,40,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(SIGMA_GLO(1:Nd),Nd,MPI_DOUBLE_PRECISION,3,41,MPI_COMM_WORLD,stateinfo) ELSE IF(rang==3)THEN ALLOCATE(DUMMY1(1:Nd),DUMMY2(1:Nd)) CALL MPI_RECV(DUMMY2(1:Nd),Nd,MPI_INTEGER,2,40,MPI_COMM_WORLD,status,stateinfo) CALL MPI_RECV(DUMMY1(1:Nd),Nd,MPI_DOUBLE_PRECISION,2,41,MPI_COMM_WORLD,status,stateinfo) COEF_POND=COEF_POND+DUMMY2 SIGMA_GLO=SIGMA_GLO+DUMMY1 DEALLOCATE(DUMMY1,DUMMY2) END IF END SUBROUTINE FIRST_REDUCTION_SIGMA_OU_DEF end module ModPGC
0
ALLM/TER2019
ALLM/TER2019/CODE_F90_MPI/ModParra.f90
MODULE ModParra use mpi implicit none CONTAINS subroutine CHARGE(rang,Np,it1,itN,CHARGE_TOT,enplus) integer,intent(in)::rang,Np,CHARGE_TOT,enplus integer,intent(out)::it1,itN real::coeff_repartition coeff_repartition=CHARGE_TOT/Np SELECT CASE(Np) CASE(1) it1=1 itN=CHARGE_TOT CASE DEFAULT if(rang<mod(CHARGE_TOT,Np))then it1=rang*(coeff_repartition+1)+1 it1=it1+enplus itN=(rang+1)*(coeff_repartition+1) itN=itN+enplus print*,'RANGRANG',rang,' coeff rep=',coeff_repartition,' mod(chargetot,Np)', mod(CHARGE_TOT,Np) else it1=1+mod(CHARGE_TOT,Np)+rang*coeff_repartition it1=it1+enplus itN=it1+coeff_repartition-1 !itN=itN end if END SELECT print*,'je suis proc',rang,'je vais de',it1,'à',itN end subroutine CHARGE END MODULE ModParra
0
ALLM/TER2019
ALLM/TER2019/CODE_F90_MPI/ModTri.f90
module ModTri use ModMesh use mpi implicit none contains SUBROUTINE DOUBLON(SIZE,rang,T_CL,T_V,Z) INTEGER,intent(in)::SIZE,rang INTEGER,dimension(1:SIZE,1:2),intent(inout)::T_CL REAL(rki),dimension(1:SIZE),intent(inout)::T_V INTEGER,intent(out)::Z !NBR DE ZERO INTEGER::i,j !ON SUPPOSE QUE T_V(:)/=0 DO j=1,SIZE-1 IF(T_V(j)/=0)THEN DO i=j+1,SIZE IF(T_V(i)/=0)THEN !PRINT*,'RANG',rang,j,i,'DOUBLON' IF((T_CL(j,1)==T_CL(i,1)).AND.(T_CL(j,2)==T_CL(i,2)))THEN T_V(j)=T_V(j)+T_V(i);T_V(i)=0 END IF END IF END DO END IF END DO Z=0 DO i=1,SIZE IF(T_V(i)==0.d0)THEN Z=Z+1 END IF END DO END SUBROUTINE DOUBLON SUBROUTINE TRI_CR(SIZE,Z,rang,T_CL,T_V,S_CL,S_V,NNZ)!TRI OVER ALL T_CL(:,1) ET T_CL(:,2) INTEGER,intent(in)::SIZE,Z,rang INTEGER,dimension(1:SIZE,1:2),intent(in)::T_CL INTEGER,dimension(1:SIZE)::T_TRI REAL(rki),dimension(1:SIZE),intent(in)::T_V INTEGER,intent(out)::NNZ INTEGER,dimension(:,:),intent(out),allocatable::S_CL REAL(rki),dimension(:),intent(out),allocatable::S_V INTEGER::i,j,DIM,pt DIM=SIZE-Z ALLOCATE(S_CL(1:DIM,1:2),S_V(1:DIM)) T_TRI=0;S_CL=0;S_V=0.d0 DO j=1,SIZE !PRINT*,'RANG',RANG,'j=',j IF(T_V(j)/=0)THEN !PRINT*,'RANG',rang,'IF' DO i=1,SIZE !PRINT*,'RANG',rang,'i=',i IF(T_V(i)/=0)THEN !PRINT*,'RANG',rang,j,i,'TRI' IF(T_Cl(j,1)==T_CL(i,1).AND.T_CL(j,2)>=T_CL(i,2))THEN T_TRI(j)=T_TRI(j)+1 ELSE IF(T_CL(j,1)>T_CL(i,1))THEN T_TRI(j)=T_TRI(j)+1 END IF END IF END DO END IF END DO DO i=1,SIZE IF(T_TRI(i)/=0)THEN pt=T_TRI(i) S_CL(pt,1)=T_CL(i,1);S_CL(pt,2)=T_CL(i,2);S_V(pt)=T_V(i); END IF END DO NNZ=0 DO i=1,DIM IF(S_V(i)/=0)THEN NNZ=NNZ+1 END IF END DO PRINT*,'RANG',rang,'DIM',DIM,'NNZ',NNZ END SUBROUTINE TRI_CR end module ModTri
0
ALLM/TER2019
ALLM/TER2019/CODE_F90_MPI/main.f90
program main use ModMesh use ModMatrice use ModParra use ModTri use mpi use ModPGC implicit none !mpirun -n 4 --mca pml ob1 ./a.out integer::rang,Np,stateinfo,me integer,dimension(MPI_STATUS_SIZE)::status integer::num_pc,indice,userchoice !POUR LE MAILLAGE: INTEGER::PX,PY,P1,P2,P3 INTEGER::MARK1,MARK2 ! cf ModMesh.f90 pour info !n:nbr de noeuds par élé, ici 3 !NDDL:nbr de degre de liberté aux noeuds, ici 2 !Nd:nbr de noeuds total !taille matrice rigidité locale: n.NDDL par n.NDDL !taille matrice globale et expansee: Nd.NDDL par Nd.NDDL !POUR DEFINIR LES NOMS DES FICHIERS character(len=20)::mesh_file character(len=3)::rank,N_PC,u_dir character(len=4)::INPUT_DATA character(len=25)::DEF_NODE character(len=25)::DEF_X,DEF_Y,RES_X,RES_Y !*** POUR MEF integer::nbr_node,nbr_tri,Nd INTEGER::it1,itn,CHARGE_TOT,CHARGE_ME,k_ite integer::i,j,k,l,he,compteur_ite,NNZ,NNZ1,NNZ2,NNZ0,NNZ3,TRUE_NNZ,NZ integer,parameter::n=3,NDDL=2 integer::n_NDDL !T_node TABLEAU DE CORD DES NOEUDS TYPE(tab_node)::T_node !ALLOCATE(T_node%n_node(1:nbr_node),T_node%c_node(1:nbr_node,1:3)) integer,dimension(:,:),allocatable::T_conn !*** POUR MEF real(rki),dimension(1:2,1:2)::jac,inv_jac real(rki),dimension(1:3,1:4)::Q real(rki),dimension(1:4,1:6)::DN !DERIVE FCT DE FORME DANS BASE ELE REF real(rki),dimension(1:3,1:6)::B real(rki),dimension(1:3,1:3)::HOOK real(rki),dimension(1:6,1:6)::K_ele real(rki),dimension(1:6,1:3)::inter integer,dimension(1:n*NDDL)::localisation integer,dimension(1:n*NDDL,1:3)::liste !CONDITION DPL BLOQUE: real(rki)::condi_x,condi_y INTEGER::MODEL !POUR SAVOIR SI 1/4 DE PLAQUE OU ENTIERE !*** POUR TRI INTEGER::T1,T2,T3,Z !Z nbr ZERO INTEGER::TAILLE INTEGER,dimension(:),allocatable::RC1,RC2 real(rki),dimension(:),allocatable::RC3 integer,dimension(:,:),allocatable::TAB_CL,T_CL,T01_CL,T23_CL,L01_CL,L23_CL,T03_CL,L03_CL,S_CL real(rki),dimension(:),allocatable::TAB_V,T_V,T01_V,T23_V,L01_V,L23_V,T03_V,L03_V,S_V !*** POUR MEF real(rki)::det REAL(rki)::longueur,largeur,RAY REAL(rki)::P,P_MAX INTEGER::N_P INTEGER::N_STEP,STEP real(rki),dimension(1:n*NDDL)::F_LOCALE real(rki),dimension(:),allocatable::F_LOCALE_EXPANSEE,F_GLOBAL,F !*** POUR PGC ET FORMAT CCS: real(rki)::TOL integer::CCS_it1,CCS_itN,AA,BB,CC,DD,KMAX real(rki),dimension(:),allocatable::VAL integer,dimension(:),allocatable::J_IND integer,dimension(:),allocatable::I_cpt real(rki),dimension(:),allocatable::X,SOLX,SOLY,RES,RESX,RESY integer,dimension(1:2,1:4)::TAB_IT,TAB_CHARGE !*** POUR CALCUL DE SIGMA ET DEFORMATION: INTEGER::DIR,DIR_ALL,TRACE REAL(rki),dimension(1:6)::DPL REAL(rki),dimension(1:3)::SIGMA_LOC,DEF_LOC REAL(rki),dimension(1:3,1:6)::AB REAL(rki),dimension(:),allocatable::SIGMA_GLO,DUMMY1,DEF_GLO,DUMMY3 INTEGER,dimension(:),allocatable::COEF_POND,DUMMY2,COEF_POND_2,DUMMY4 !coeff de pondération !*** POUR LES MODULE E_XX,E_YYou G_XY: !REAL(rki),dimension(:),allocatable::MOD_ING REAL(rki)::MOY_MOD_ING,SOM_SIG,SOM_DEF,X_TRACE,Y_TRACE !moyenne et point de niveau pour relever S_YY sur la ligne INTEGER::CPT_TRACE,H_A,H_B CHARACTER(len=20)::HOST_NM !*** CPU TIME real(rki)::start,end !****************************************************** !****************************************************** CALL MPI_INIT(stateinfo) !DEBUT REGION // CALL MPI_COMM_RANK(MPI_COMM_WORLD,rang,stateinfo) CALL MPI_COMM_SIZE(MPI_COMM_WORLD,Np,stateinfo) PRINT*,'AFFICHAGE NBR PROC:' IF(rang==0)THEN PRINT*,'**********************************' PRINT*,'NOMBRE DE PROCESSUS ACTIF:',Np PRINT*,'**********************************' END IF CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) PRINT*,'|' PRINT*,'PROCESSUS #',rang PRINT*,'|' IF(rang==0)THEN PRINT*,'**********************************' END IF CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) !****************************************************** indice=0 !INI n_NDDL=n*NDDL !condi_dpl: !condi_x=0.0125d0;condi_y=0.08d0 !condi_x=0.036d0;condi_y=0.0d0!0.2305d0 !INITIALAISATION DN: DN=0.0d0 DN(1,1)=-1.0d0;DN(1,3)=1.0d0;DN(2,1)=-1.0d0;DN(2,5)=1.0d0;DN(3,2)=-1.0d0;DN(3,4)=1.0d0 DN(4,2)=-1.0d0;DN(4,6)=1.0d0 !INITIALISATION DE HOOK: on switch c11 avec c22 car traction sens y HOOK=0.d0 !OTCH2: HOOK(1,1)=43.0630d0;HOOK(2,2)=HOOK(1,1) HOOK(1,2)=13.4340d0;HOOK(2,1)=HOOK(1,2) HOOK(3,3)=14.8140d0 HOOK=HOOK*10**9 HOOK(1,3)=0.0d0;HOOK(3,1)=0.0d0;HOOK(2,3)=0.0d0;HOOK(3,2)=0.0d0 !mesh_file='HOLE.o.msh' write(rank,fmt='(i3.3)')rang !mesh_file='HOLE_'//trim(adjustl(rank))//'.o.msh' !*** LECTURE DE DATA.txt POUR LES PARAMETRES DU CODE: INPUT_DATA='DATA'!.txt' CALL READ_DATA(rang,INPUT_DATA,mesh_file,nbr_node,nbr_tri,MARK1,MARK2,KMAX,TOL,P_MAX,STEP,N_STEP & ,MODEL,longueur,largeur,RAY,condi_x,condi_y)!,DIR) SELECT CASE(MODEL) CASE(1) X_TRACE=0.0d0;Y_TRACE=0.0d0 CASE(0) X_TRACE=largeur/2.0d0;Y_TRACE=longueur/2.0d0 END SELECT num_pc=1 write(N_PC,fmt='(i3.3)')num_pc Nd=nbr_node CHARGE_TOT=nbr_tri !BOUCLE POUR VARTIATION DE CHARGE ET EVENTUELLLEMENT SI L'ON VEUT DISTRIBUER LA BOUCLE SUR PLUSIEURS PC: CALL hostnm(HOST_NM)!LE NOM DU PC IF(STEP==1)THEN IF(HOST_NM=='foissac')THEN CALL CHARGE(rang,5,H_A,H_B,N_STEP,0)!!H_A=1;H_B=10 ELSE IF(HOST_NM=='enlene')THEN CALL CHARGE(rang,5,H_A,H_B,N_STEP,0) ELSE IF(HOST_NM=='combarelles')THEN CALL CHARGE(rang,5,H_A,H_B,N_STEP,0)! H_A=21;H_B=30 ELSE IF(HOST_NM=='cosquer')THEN CALL CHARGE(rang,5,H_A,H_B,N_STEP,0)!H_A=31;H_B=40 ELSE IF(HOST_NM=='cussac')THEN CALL CHARGE(rang,5,H_A,H_B,N_STEP,0)!H_A=41;H_B=50 END IF ELSE IF(STEP==0)THEN HOST_NM='DELL' H_A=1;H_B=1;N_STEP=1 END IF P=0.0d0 DO N_P=H_A,H_B P=P+N_P*(P_MAX/N_STEP)!N_P*POURCENTAGE_P*P_MAX ALLOCATE(T_conn(1:nbr_tri,1:5)) ALLOCATE(F_LOCALE_EXPANSEE(1:Nd*NDDL),F_GLOBAL(1:Nd*NDDL)) F_GLOBAL=0.d0 CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) PRINT*,'READ MESH' call read_mesh(mesh_file,nbr_node,nbr_tri,T_node,T_conn,rang,MARK1,MARK2) CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) !*** DEFINITION DES CHARGES PAR PROCESSEURS CALL CHARGE(rang,Np,it1,itN,CHARGE_TOT,0)!CHARGE_TOT=4970,enplus) CHARGE_ME=itN-it1+1 CALL COMM_CHARGE(rang,stateinfo,status,it1,itN,TAB_CHARGE) ALLOCATE(TAB_CL(1:36*CHARGE_ME,1:2),TAB_V(1:36*CHARGE_ME)) CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) compteur_ite=1 PRINT*,'DEBUT BOUCLE MEF' start=MPI_Wtime() DO i=it1,itN !1,nbr_tri PRINT*,'RANG',rang,'i=',i call JACOBIENNE(T_node,T_conn,jac,i,nbr_tri) call DETERMINANT_JAC(jac,det) call INVERSE_JAC(jac,det,inv_jac) call Q_INV_J(inv_jac,Q) call GRAD_N(Q,DN,B) call MATRICE_RIGIDITE_ELEMENT(B,HOOK,det,K_ele) !pour les dpl bloqué: IF(MODEL==1)THEN !MODEL 1/4 DE PLAQUE call DPL_IMPO(K_ele,T_conn,T_node,nbr_tri,i,condi_x,condi_y) END IF call LOC_i(n,NDDL,nbr_tri,T_conn,i,localisation) !************************************************************************************** CALL MAKE_A_LISTE1(rang,36,CHARGE_ME,i,it1,k_ite,n_NDDL,localisation,K_ele,TAB_CL,TAB_V) !POUR FORMAT CREUX !21 pour low tri part but use ful matrix i.e 6*6=36 !************************************************************************************* call FORCE_LOCALE_SUIVANT_Y(i,P,longueur,n,Nd,NDDL,nbr_tri,T_node,T_conn,F_LOCALE,MODEL) !********************************************************************************************* call FORCE_LOCALE_SUIVANT_Y_EXPANSEE(n,NDDL,Nd,localisation,F_LOCALE,F_LOCALE_EXPANSEE) F_GLOBAL=F_GLOBAL+F_LOCALE_EXPANSEE !********************************************************************************************* compteur_ite=compteur_ite+1 END DO !FIN BOUCLE i end=MPI_Wtime() OPEN(60+rang,file='./TPS_CPU/'//trim(HOST_NM)//'temps_cpu.txt',position='append') write(60+rang,*)'RANG=',rang,'MEF_1',end-start CLOSE(60+rang) DEALLOCATE(F_LOCALE_EXPANSEE) CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) PRINT*,'FIN BOUCLE' !*******************PRE_TRI********************************* !*** POUR TRI PAR ORDRE CROISSANT SUR LES COLS DE K_GLOBALE !*** EN VUE DU FORMAT CCS T1=((Nd*NDDL)-mod((Nd*NDDL),4))/4;T2=2*T1;T3=3*T1 PRINT*,size(TAB_V),mod(size(TAB_V),4),T1,T2,T3,Nd*NDDL start=MPI_Wtime() CALL PRE_TRI(T1,T2,T3,Nd*NDDL,size(TAB_V),rang,TAB_CL(:,1),TAB_CL(:,2),TAB_V,RC1,RC2,RC3,status,stateinfo) end=MPI_Wtime() OPEN(60+rang,file='./TPS_CPU/'//trim(HOST_NM)//'temps_cpu.txt',position='append') write(60+rang,*)'RANG=',rang,'PRE_TRI',end-start CLOSE(60+rang) CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) DEALLOCATE(TAB_CL,TAB_V) IF(size(RC1)>0)THEN ALLOCATE(TAB_CL(1:size(RC1),1:2),TAB_V(1:size(RC1))) TAB_CL(:,1)=RC1;TAB_CL(:,2)=RC2;TAB_V=RC3 PRINT*,TAB_CL(1:3,1) END IF DEALLOCATE(RC1,RC2,RC3) PRINT*,'FIN PRE TRI' !*********************TRI************************************* PRINT*,'DEBUT TRI:' start=MPI_Wtime() IF(SIZE(TAB_V)>0)THEN!(SIZE(RC1)>0)THEN CALL DOUBLON(size(TAB_V),rang,TAB_CL,TAB_V,Z) CALL TRI_CR(size(TAB_V),Z,rang,TAB_CL,TAB_V,S_CL,S_V,NNZ) END IF end=MPI_Wtime() OPEN(60+rang,file='./TPS_CPU/'//trim(HOST_NM)//'temps_cpu.txt',position='append') write(60+rang,*)'RANG=',rang,'TRI',end-start CLOSE(60+rang) DEALLOCATE(TAB_CL,TAB_V) !*******************FIN TRI********************************* CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) PRINT*,'RANG',rang,' PREMIER TRI DONE' !*** ON REMPLIT LE FORMAT CCS (A est SYM DONC CCS=CCR) CCS_it1=minval(S_CL(:,1));CCS_itN=maxval(S_CL(:,1)) ALLOCATE(VAL(1:size(S_V)),J_IND(1:size(S_V)),I_cpt(1:(CCS_itN-CCS_it1)+2))!I_cpt(1:(Nd*NDDL)+1)) start=MPI_Wtime() CALL CCS(size(S_V),Nd,NDDL,CCS_it1,CCS_itN,S_CL,S_V,VAL,J_IND,I_cpt) end=MPI_Wtime() OPEN(60+rang,file='./TPS_CPU/'//trim(HOST_NM)//'temps_cpu.txt',position='append') write(60+rang,*)'RANG=',rang,'CCS',end-start,' NNZ=',size(VAL) CLOSE(60+rang) !***POUR VERIFICATION DECOMMENTER: !!$ open(30+rang,file='SPARSE'//trim(adjustl(rank))//'.dat') !!$ BB=CCS_it1;CC=0 !!$ DO i=1,size(I_cpt)-1!NNZ!21*CHARGE_ME !!$ AA=I_cpt(i+1)-I_cpt(i) !!$ IF(AA/=0)THEN !!$ DO j=1,AA !!$ write(30+rang,*)BB,J_IND(j+CC),VAL(j+CC)!,TRUE_NNZ!,NNZ!21*CHARGE_ME !!$ END DO !!$ END IF !!$ BB=BB+1;CC=CC+AA !!$ END DO !!$ close(30+rang) DEALLOCATE (S_CL,S_V) CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) PRINT*,'rang=',rang,'it1 itN=',it1,itN !*** SWITCH DE LA CHARGE PAR PROCS POUR EN VUE DU SOLVEUR: it1=CCS_it1;itN=CCS_itN PRINT*,'rang=',rang,'CCS_it1 CCS_itN=',CCS_it1,CCS_itN !*** CELA S'APPARENTE A UNE OPERATION DE REDUCTION PAR PARTIE !*** SUR F_GLOBAL POUR QUE TOUT LES PROCS AIENT L'ADDITION DE F_GLOBAL SUR LEUR it1:itN !*** STOCKE DANS F: ALLOCATE(F(it1:itN)) CALL COMM_CHARGE(rang,stateinfo,status,it1,itN,TAB_IT) CALL SEND_RECV_F_GLO(rang,TAB_IT,it1,itN,Nd,NDDL,stateinfo,status,F,F_GLOBAL) CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) DEALLOCATE(F_GLOBAL) !*** ALLOC SOL INIT ET PGC: ALLOCATE(X(it1:itN),RES(it1:itN)) !TOL=0.000001 PRINT*,'DEBUT PGC PRECONDITIONEUR DIAGONAL' start=MPI_Wtime() CALL PGC(rang,it1,itN,size(VAL),KMAX,TOL,stateinfo,status,X,VAL,J_IND,I_cpt,F,Nd,NDDL,RES,HOST_NM) end=MPI_Wtime() OPEN(60+rang,file='./TPS_CPU/'//trim(HOST_NM)//'temps_cpu.txt',position='append') write(60+rang,*)'RANG=',rang,'PGC+WR_res',end-start,' NNZ=',size(VAL),'it1',it1,'itN',itN CLOSE(60+rang) ALLOCATE(SOLX(1:Nd),SOLY(1:Nd)) ALLOCATE(RESX(1:Nd),RESY(1:Nd)) CALL SEND_RECV_SOL(rang,TAB_IT,CCS_it1,CCS_itN,Nd,NDDL,stateinfo,status,X,SOLX,SOLY) CALL SEND_RECV_SOL(rang,TAB_IT,CCS_it1,CCS_itN,Nd,NDDL,stateinfo,status,RES,RESX,RESY) DEALLOCATE(X,F,RES) PRINT*,'rang=',rang,' SOL_X(1:5)',SOLX(1:5) !*** MODIFICATION DU FICHIER DE MAILLAGE POUR VOIR LA DEFORMEE: DEF_NODE='./DPL/'//trim(HOST_NM)//'NODE.txt' DEF_X='./DPL/'//trim(HOST_NM)//'DPL_X.txt' DEF_Y='./DPL/'//trim(HOST_NM)//'DPL_Y.txt' RES_X='./RES/'//trim(HOST_NM)//'RES_X.txt' RES_Y='./RES/'//trim(HOST_NM)//'RES_Y.txt' CALL DEFORMEE_DPL(rang,mesh_file,DEF_NODE,DEF_X,DEF_Y,Nd,SOLX,SOLY) CALL MAP_RESIDUS(rang,RES_X,RES_Y,Nd,RESX,RESY) !*** DEALLOCATE(VAl,J_IND,I_cpt) DEALLOCATE(RESX,RESY) !*** CALCUL DES DEFORMATION ET DE SIGMA: DO DIR_ALL=1,3 DIR=DIR_ALL write(u_dir,fmt='(i3.3)')DIR ALLOCATE(DEF_GLO(1:Nd),COEF_POND_2(1:Nd)) DEF_GLO=0.d0;COEF_POND_2=0 ALLOCATE(SIGMA_GLO(1:Nd),COEF_POND(1:Nd)) SIGMA_GLO=0.d0;COEF_POND=0 !DIR=2 compteur_ite=1 PRINT*,'DEBUT BOUCLE POUR CALCUL DE SIGMA' start=MPI_WTIME() DO i=TAB_CHARGE(1,rang+1),TAB_CHARGE(2,rang+1) !PRINT*,'RANG',rang,'i=',i call JACOBIENNE(T_node,T_conn,jac,i,nbr_tri) call DETERMINANT_JAC(jac,det) call INVERSE_JAC(jac,det,inv_jac) call Q_INV_J(inv_jac,Q) call GRAD_N(Q,DN,B) !FORMATION DE DPL T1=T_conn(i,2);T2=T_conn(i,3);T3=T_conn(i,4) DPL(1)=SOLX(T1);DPL(2)=SOLY(T1) DPL(3)=SOLX(T2);DPL(4)=SOLY(T2) DPL(5)=SOLX(T3);DPL(6)=SOLY(T3) !PRINT*,'rang',rang,'T1',T1,'SOLX(T1)',SOLX(T1),'DPL(1)',DPL(1) !CALCUL DE DEFORMATION: DEF_LOC: DEF_LOC=MATMUL(B,DPL) !CALCUL DE SIGMA_LOC: SIGMA_LOC=MATMUL(HOOK,DEF_LOC) !REDUCTION/EXTRAPOLATION AUX NOEUDS DE DEFORMATION: SIGMA_GLO: DEF_GLO(T1)=DEF_GLO(T1)+DEF_LOC(DIR);COEF_POND_2(T1)=COEF_POND_2(T1)+1 DEF_GLO(T2)=DEF_GLO(T2)+DEF_LOC(DIR);COEF_POND_2(T2)=COEF_POND_2(T2)+1 DEF_GLO(T3)=DEF_GLO(T3)+DEF_LOC(DIR);COEF_POND_2(T3)=COEF_POND_2(T3)+1 !REDUCTION/EXTRAPOLATION AUX NOEUDS DE SIGMA: SIGMA_GLO: SIGMA_GLO(T1)=SIGMA_GLO(T1)+SIGMA_LOC(DIR);COEF_POND(T1)=COEF_POND(T1)+1 SIGMA_GLO(T2)=SIGMA_GLO(T2)+SIGMA_LOC(DIR);COEF_POND(T2)=COEF_POND(T2)+1 SIGMA_GLO(T3)=SIGMA_GLO(T3)+SIGMA_LOC(DIR);COEF_POND(T3)=COEF_POND(T3)+1 compteur_ite=compteur_ite+1 END DO !FIN BOUCLE i CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) IF(DIR_ALL==3)THEN DEALLOCATE(SOLX,SOLY) END IF !OPERATION DE REDUCTION FACON TRI PAIR-IMPAIR: CALL FIRST_REDUCTION_SIGMA_OU_DEF(rang,Nd,COEF_POND,SIGMA_GLO,DUMMY1,DUMMY2,stateinfo,status) CALL FIRST_REDUCTION_SIGMA_OU_DEF(rang,Nd,COEF_POND_2,DEF_GLO,DUMMY3,DUMMY4,stateinfo,status) CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) !LAST_REDUCTION POUR DEFORMATION: IF(rang==3)THEN CALL MPI_SEND(COEF_POND_2(1:Nd),Nd,MPI_INTEGER,0,50,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(DEF_GLO(1:Nd),Nd,MPI_DOUBLE_PRECISION,0,51,MPI_COMM_WORLD,stateinfo) DEALLOCATE(DEF_GLO,COEF_POND_2) ELSE IF(rang==0)THEN ALLOCATE(DUMMY3(1:Nd),DUMMY4(1:Nd)) CALL MPI_RECV(DUMMY4(1:Nd),Nd,MPI_INTEGER,3,50,MPI_COMM_WORLD,status,stateinfo) CALL MPI_RECV(DUMMY3(1:Nd),Nd,MPI_DOUBLE_PRECISION,3,51,MPI_COMM_WORLD,status,stateinfo) COEF_POND_2=COEF_POND_2+DUMMY4 DEF_GLO=DEF_GLO+DUMMY3 DEALLOCATE(DUMMY3,DUMMY4) IF(DIR_ALL==1)THEN OPEN(60,file='./DEF/'//trim(HOST_NM)//'def_xx.txt') ELSE IF(DIR_ALL==2)THEN OPEN(60,file='./DEF/'//trim(HOST_NM)//'def_yy.txt') ELSE IF(DIR_ALL==3)THEN OPEN(60,file='./DEF/'//trim(HOST_NM)//'def_xy.txt') END IF DO i=1,Nd DEF_GLO(i)=DEF_GLO(i)/COEF_POND_2(i) WRITE(60,*)i,DEF_GLO(i) END DO CLOSE(60) IF(DIR_ALL==2)THEN open(90,file='./DEF/'//trim(HOST_NM)//'TRACE_DEF_YY.txt') CPT_TRACE=0 SOM_DEF=0.0d0 DO i=1,Nd TRACE=T_node%n_node(i) !PRINT*,'TRACE=',TRACE,' T_node%c_node(TRACE)=',T_node%c_node(TRACE,2) IF(T_node%c_node(TRACE,2)==Y_TRACE .AND. T_node%c_node(TRACE,1)>=X_TRACE )THEN write(90,*)T_node%c_node(TRACE,1)-RAY,DEF_GLO(TRACE) !PRINT*,T_node%c_node(TRACE,1),SIGMA_GLO(TRACE) END IF SOM_DEF=SOM_DEF+DEF_GLO(TRACE) CPT_TRACE=CPT_TRACE+1 END DO SOM_DEF=SOM_DEF/CPT_TRACE close(90) END IF DEALLOCATE(COEF_POND_2)!DEALLOCATE(DEF_GLO,COEF_POND_2) ELSE DEALLOCATE(DEF_GLO,COEF_POND_2) END IF !LAST_REDUCTION POUR SIGMA: IF(rang==3)THEN CALL MPI_SEND(COEF_POND(1:Nd),Nd,MPI_INTEGER,0,50,MPI_COMM_WORLD,stateinfo) CALL MPI_SEND(SIGMA_GLO(1:Nd),Nd,MPI_DOUBLE_PRECISION,0,51,MPI_COMM_WORLD,stateinfo) DEALLOCATE(SIGMA_GLO,COEF_POND) ELSE IF(rang==0)THEN ALLOCATE(DUMMY1(1:Nd),DUMMY2(1:Nd)) CALL MPI_RECV(DUMMY2(1:Nd),Nd,MPI_INTEGER,3,50,MPI_COMM_WORLD,status,stateinfo) CALL MPI_RECV(DUMMY1(1:Nd),Nd,MPI_DOUBLE_PRECISION,3,51,MPI_COMM_WORLD,status,stateinfo) COEF_POND=COEF_POND+DUMMY2 SIGMA_GLO=SIGMA_GLO+DUMMY1 DEALLOCATE(DUMMY1,DUMMY2) IF(DIR_ALL==1)THEN OPEN(60,file='./SIGMA/'//trim(HOST_NM)//'sigma_xx.txt') ELSE IF(DIR_ALL==2)THEN OPEN(60,file='./SIGMA/'//trim(HOST_NM)//'sigma_yy.txt') ELSE IF(DIR_ALL==3)THEN OPEN(60,file='./SIGMA/'//trim(HOST_NM)//'sigma_xy.txt') END IF DO i=1,Nd SIGMA_GLO(i)=SIGMA_GLO(i)/COEF_POND(i) WRITE(60,*)i,SIGMA_GLO(i) END DO CLOSE(60) IF(DIR_ALL==2)THEN open(90,file='./SIGMA/'//trim(HOST_NM)//'TRACE_SIGMA_YY.txt') open(95,file='./MODULE_EVO/'//trim(HOST_NM)//'ELASTICITE_LIN.txt',position='append') SOM_SIG=0.d0 CPT_TRACE=0 DO i=1,Nd TRACE=T_node%n_node(i) !PRINT*,'TRACE=',TRACE,' T_node%c_node(TRACE)=',T_node%c_node(TRACE,2) IF(T_node%c_node(TRACE,2)==Y_TRACE .AND. T_node%c_node(TRACE,1)>=X_TRACE )THEN write(90,*)T_node%c_node(TRACE,1)-RAY,SIGMA_GLO(TRACE) !PRINT*,T_node%c_node(TRACE,1),SIGMA_GLO(TRACE) END IF SOM_SIG=SOM_SIG+SIGMA_GLO(TRACE) CPT_TRACE=CPT_TRACE+1 END DO close(90) SOM_SIG=SOM_SIG/CPT_TRACE WRITE(95,*)SOM_DEF,SOM_SIG,P close(95) END IF DEALLOCATE(COEF_POND)!DEALLOCATE(SIGMA_GLO,COEF_POND) ELSE DEALLOCATE(SIGMA_GLO,COEF_POND) END IF IF(rang==0)THEN !allocate(MOD_ING(1:Nd)) MOY_MOD_ING=0.0d0 DO i=1,Nd MOY_MOD_ING=MOY_MOD_ING+SIGMA_GLO(i)/DEF_GLO(i) !MOD_ING(i)=SIGMA_GLO(i)/DEF_GLO(i) !MOY_MOD_ING=MOY_MOD_ING+MOD_ING(i) END DO MOY_MOD_ING=MOY_MOD_ING/Nd OPEN(10+DIR_ALL,file='./MODULE_EVO/'//trim(HOST_NM)//'EVO_MOD_ING_4AVERAGE'//trim(adjustl(u_dir))//'.txt',POSITION='APPEND') WRITE(10+DIR_ALL,*)P,MOY_MOD_ING CLOSE(10+DIR_ALL) DEALLOCATE(SIGMA_GLO,DEF_GLO) END IF end=MPI_WTIME() OPEN(70+rang,file='./TPS_CPU/'//trim(HOST_NM)//'temps_cpu.txt',position='append') !write(70+rang,*)'RANG=',rang,'MEF2+SIGMA',end-start IF(DIR_ALL==1)THEN write(70+rang,*)'RANG=',rang,'MEF2+SIGMA_XX',end-start ELSE IF(DIR_ALL==2)THEN write(70+rang,*)'RANG=',rang,'MEF2+SIGMA_YY',end-start ELSE IF(DIR_ALL==3)THEN write(70+rang,*)'RANG=',rang,'MEF2+SIGMA_XY',end-start END IF CLOSE(70+rang) END DO CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) DEALLOCATE(T_node%n_node,T_node%c_node) DEALLOCATE(T_conn) PRINT*,'DEALLOCATE T_node et T_conn' CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) END DO CALL MPI_BARRIER(MPI_COMM_WORLD,stateinfo) CALL MPI_FINALIZE(stateinfo) end program main
0
ALLM/TER2019/CODE_F90_MPI
ALLM/TER2019/CODE_F90_MPI/DEF/poi.f90
program poi implicit none integer::i,k REAL(kind=8)::DX,DY,SUM_DX,SUM_DY,POISSON POISSON=0.0d0;SUM_DX=0.0d0;SUM_DY=0.0d0 OPEN(10,file='DELLdef_xx.txt') DO i=1,27430 READ(10,*)k,DX SUM_DX=SUM_DX+DX END DO CLOSE(10) OPEN(11,file='DELLdef_yy.txt') DO i=1,27430 READ(11,*)k,DY SUM_DY=SUM_DY+DY END DO CLOSE(11) POISSON=-SUM_DX/SUM_DY PRINT*,'POI=',POISSON end program poi
0
ALLM
ALLM/test-mipp/benchfmadd.R
library(ggplot2) df <- read.csv("./benchfmadd.csv") p <- ggplot(data = df, aes(x=Mem, y=Time, color=optim, group=optim))+geom_line() p <- p + ggtitle("fmadd") + labs(y = "Time (ms)", x = "Memory (Mb)") ggsave("bench.pdf", plot=p) transform <- subset(df, optim == "transform") mipp <- subset(df, optim == "mipp") for(i in 1:length(mipp$type)) { mipp$TotSpeedUp[i] = transform$Total[i] / mipp$Total[i] mipp$SpeedUp[i] = transform$Time[i] / mipp$Time[i] print(mipp$SpeedUp[i]) } p <- ggplot(data = mipp, aes(x=Mem, y=SpeedUp))+geom_line() p <- p + ggtitle("fmadd") + labs(y = "SpeedUp", x = "Memory (Mb)") ggsave("SpeedUp.pdf", plot=p) #p <- p+facet_grid(Sthetac ~ Sic+Swhichc+l)+labs(y="Backward error")+labs(x="Solver iter.")
0
ALLM
ALLM/test-mipp/benchfmadd.bash
#!/bin/bash #-DNELE=$power CFLAGS="-O3 -funroll-loops -floop-unroll-and-jam -march=cascadelake -mavx512f -mavx512dq -mavx512ifma" for p in {30..6..-1} do power=$((2 ** $p)) g++ $CFLAGS -DTYPE=double -DNSAMPLE=20 -DOPTIM=transform -o fmadd fmadd.cpp ./fmadd $power done for p in {30..6..-1} do power=$((2 ** $p)) g++ $CFLAGS -DTYPE=double -DNSAMPLE=20 -DOPTIM=mipp -o mippfmadd mipp_fmadd.cpp ./mippfmadd $power done echo "DONE"
0
ALLM
ALLM/test-mipp/fmadd.cpp
#include <bits/stdc++.h> // #include <algorithm> // using namespace std; #define xstr(s) str(s) #define str(s) #s /* #ifndef NELE #define NELE 3 #endif */ #ifndef TYPE #define TYPE double #endif #ifndef NSAMPLE #define NSAMPLE 1 #endif #ifndef OPTIM #define OPTIM classic #endif #define STROPTIM xstr(OPTIM) #define STRTYPE xstr(TYPE) inline bool IsFileExist(const std::string &name) { std::ifstream f(name.c_str()); return f.good(); } int main(int argc, char *argv[]) { int ierr = 0; long NELE = std::stol(argv[1]); std::vector<TYPE> A(NELE, 1); std::vector<TYPE> B(NELE, 2); std::vector<TYPE> C(NELE, 3); std::vector<TYPE> RES(NELE, 0); double Mem = 4 * NELE * sizeof(TYPE) / 1000000.; // MB auto t_before = std::chrono::steady_clock::now(); for (long i = 0; i < NSAMPLE; i++) { std::transform(A.begin(), A.end(), B.begin(), RES.begin(), std::multiplies<TYPE>()); std::transform(C.begin(), C.end(), RES.begin(), RES.begin(), std::plus<TYPE>()); } auto t_after = std::chrono::steady_clock::now(); auto d_delta = t_after - t_before; auto decod_time_ms = (float)d_delta.count() * 0.000001f; std::cout << STRTYPE << " " << STROPTIM << '\n'; std::cout << "time: " << decod_time_ms / NSAMPLE << " ms" << std::endl; std::cout << "cumulative time: " << decod_time_ms << " ms over " << NSAMPLE << " Mem MB " << Mem << std::endl; TYPE sum = std::accumulate(RES.begin(), RES.end(), (double)0.0); std::cout << ((5 * (double)NELE) == sum) << " " << (5) * NELE << " " << sum << '\n'; std::ofstream tabledb; auto fname = "benchfmadd.csv"; auto header = "type,Total,Time,NSample,Mem,optim"; auto isfile = IsFileExist(fname); if (!isfile) { tabledb.open(fname, std::ios::app); tabledb << header << "\n"; tabledb.close(); } tabledb.open(fname, std::ios::app); tabledb << STRTYPE << "," << decod_time_ms << "," << decod_time_ms / NSAMPLE << "," << NSAMPLE << "," << Mem << "," << STROPTIM << "\n"; tabledb.close(); return ierr; }
0
ALLM
ALLM/test-mipp/mipp_fmadd.cpp
#include "mipp/mipp.h" #include <bits/stdc++.h> // #include <algorithm> // using namespace std; #define xstr(s) str(s) #define str(s) #s /* #ifndef NELE #define NELE 3 #endif */ #ifndef TYPE #define TYPE double #endif #ifndef NSAMPLE #define NSAMPLE 1 #endif #ifndef OPTIM #define OPTIM classic #endif #define STROPTIM xstr(OPTIM) #define STRTYPE xstr(TYPE) inline bool IsFileExist(const std::string &name) { std::ifstream f(name.c_str()); return f.good(); } int main(int argc, char *argv[]) { int ierr = 0; long NELE = std::stol(argv[1]); mipp::vector<TYPE> A(NELE, 1); mipp::vector<TYPE> B(NELE, 2); mipp::vector<TYPE> C(NELE, 3); mipp::vector<TYPE> RES(NELE, 0); mipp::Reg<TYPE> rA, rB, rC, rR; double Mem = 4 * (double)NELE * sizeof(TYPE) / 1000000.; // MB auto t_before = std::chrono::steady_clock::now(); for (long i = 0; i < NSAMPLE; i++) { for (long l = 0; l < NELE; l += mipp::N<TYPE>()) { rA.load(&A[l]); rB.load(&B[l]); rC.load(&C[l]); rR.load(&RES[l]); rR = rA * rB + rC; rR.store(&RES[l]); } } auto t_after = std::chrono::steady_clock::now(); auto d_delta = t_after - t_before; auto decod_time_ms = (float)d_delta.count() * 0.000001f; std::cout << STRTYPE << " " << STROPTIM << '\n'; std::cout << "time: " << decod_time_ms / NSAMPLE << " ms" << std::endl; std::cout << "cumulative time: " << decod_time_ms << " ms over " << NSAMPLE << " Mem MB " << Mem << std::endl; TYPE sum = std::accumulate(RES.begin(), RES.end(), (double)0.0); // std::cout << (5) * NELE << " " << sum << '\n'; std::cout << ((5 * (double)NELE) == sum) << " " << (5) * NELE << " " << sum << '\n'; std::ofstream tabledb; auto fname = "benchfmadd.csv"; auto header = "type,Total,Time,NSample,Mem,optim"; auto isfile = IsFileExist(fname); if (!isfile) { tabledb.open(fname, std::ios::app); tabledb << header << "\n"; tabledb.close(); } tabledb.open(fname, std::ios::app); tabledb << STRTYPE << "," << decod_time_ms << "," << decod_time_ms / NSAMPLE << "," << NSAMPLE << "," << Mem << "," << STROPTIM << "\n"; tabledb.close(); return ierr; }
0
ALLM
ALLM/testgemm/gemmloop.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef TYPE #define TYPE float #endif #define max(a, b) (((a) < (b)) ? (b) : (a)) #define min(a, b) (((a) < (b)) ? (a) : (b)) int GetDim(long *m, long *n, long *k, int argc, char **argv) { int ierr = EXIT_SUCCESS; char *endPtr = NULL; if (argc != 4) { printf("Trying to Compute C = A*B + C\n"); printf("Please rerun with:/t./exec m n k\n"); printf("Where A is mxk; B is kxn; C is mxk\n"); exit(ierr); } else { *m = strtol(argv[1], &endPtr, 10); *n = strtol(argv[2], &endPtr, 10); *k = strtol(argv[3], &endPtr, 10); printf("m = %ld\tn = %ld\tk = %ld\n", *m, *n, *k); } return ierr; } int FillMat(long nrow, long ncol, TYPE val, TYPE *Mat) { int ierr = EXIT_SUCCESS; if (!Mat) { return EXIT_FAILURE; } size_t size = nrow * ncol; for (size_t i = 0; i < size; i++) { Mat[i] = val; } return ierr; } int ShowMat(long nrow, long nr1, long nr2, long nc1, long nc2, TYPE *Mat) { int ierr = EXIT_SUCCESS; if (!Mat) { return EXIT_FAILURE; } for (long i = nr1; i < nr2; i++) { for (long j = nc1; j < nc2; j++) { // printf("%ld\t", i + j * nrow); printf("%lf\t", Mat[i + j * nrow]); } printf("\n"); } return ierr; } int main(int argc, char **argv) { int ierr = EXIT_SUCCESS; TYPE *A = NULL; TYPE *B = NULL; TYPE *C = NULL; double Mem = 0.; const TYPE alpha = 1; const TYPE beta = 1; long m = 0, n = 0, k = 0; long lda = 0, ldb = 0, ldc = 0; size_t Asize = m * k; size_t Bsize = k * n; size_t Csize = m * n; ierr = GetDim(&m, &n, &k, argc, argv); printf("m = %ld\tn = %ld\tk = %ld\n", m, n, k); A = (TYPE *)calloc(Asize, sizeof(TYPE)); B = (TYPE *)calloc(Bsize, sizeof(TYPE)); C = (TYPE *)calloc(Csize, sizeof(TYPE)); ierr = FillMat(m, k, 1., A); ierr = FillMat(m, k, 2., B); ierr = FillMat(m, k, 3., C); ierr = ShowMat(m, max(0, 2), min(5, m), max(0, 2), min(5, k), A); free(A); free(B); free(C); A = NULL; B = NULL; C = NULL; return ierr; }
0
ALLM/testgemm
ALLM/testgemm/LIBTG/TGInstaller.bash
#!/bin/bash exp=$PWD/example srcp=$PWD/src CFLT="-O3 -march=native -DITYPE=I64 -DTYPE=float -DETYPE=TGFloat" CDBL="-O3 -march=native -DITYPE=I64 -DTYPE=double -DETYPE=TGDouble" CCX32="-O3 -march=native -DITYPE=I64 -DTYPE=comple32 -DETYPE=TGComple32" CCX64="-O3 -march=native -DITYPE=I64 -DTYPE=comple64 -DETYPE=TGComple64" for i in "flt" "dbl" "cx32" "cx64" do echo "Case $i" cat $exp/$i > $exp/Makefile.am cat $srcp/$i > $srcp/Makefile.am autoconf automake --add-missing if [[ "$i" = "flt" ]] then CFLAGS=$CFLT #./configure --prefix=$PWD/build #make #make install elif [[ "$i" = "dbl" ]] then CFLAGS=$CDBL ./configure --prefix=$PWD/build make make install elif [[ "$i" = "cx32" ]] then CFLAGS=$CCX32 elif [[ "$i" = "cx64" ]] then CFLAGS=$CCX64 fi echo $CFLAGS #./configure --prefix=$PWD/build CFLAGS=$CFLAGS done echo "" > $exp/Makefile.am echo "" > $srcp/Makefile.am
0
ALLM/testgemm/LIBTG
ALLM/testgemm/LIBTG/example/gemmloop.c
#include "datatype.h" int main(int argc, char **argv) { int ierr = EXIT_SUCCESS; tg_scalar_t *A = NULL; tg_scalar_t *B = NULL; tg_scalar_t *C = NULL; tg_fixdbl_t Mem = 0.; const tg_scalar_t alpha = 1; const tg_scalar_t beta = 1; tg_int_t m = 0, n = 0, k = 0; tg_int_t lda = 0, ldb = 0, ldc = 0; printf("size of tg_scalar_t %zu double %zu float %zu\n", tg_size_of(ETYPE), tg_size_of(TGDouble), tg_size_of(TGFloat)); #if TYPE == tg_float_t printf("CASE TGFloat\n"); #elif TYPE == tg_double_t printf("CASE TGDouble\n"); #endif ierr = GetDim(&m, &n, &k, &lda, &ldb, &ldc, argc, argv); printf("%zu\n", SIZE_MAX); printf("m = %ld\tn = %ld\tk = %ld\n", m, n, k); printf("lda = %ld\tldb = %ld\tldc = %ld\n", lda, ldb, ldc); size_t Asize = m * k; size_t Bsize = k * n; size_t Csize = m * n; A = (TYPE *)calloc(Asize, sizeof(TYPE)); B = (TYPE *)calloc(Bsize, sizeof(TYPE)); C = (TYPE *)calloc(Csize, sizeof(TYPE)); ierr = FillMat(m, k, 1., A); ierr = FillMat(m, k, 2., B); ierr = FillMat(m, k, 3., C); ierr = ShowMat(m, max(0, 2), min(5, m), max(0, 2), min(5, k), A); free(A); free(B); free(C); A = NULL; B = NULL; C = NULL; tg_mat_t matA = TGMATNULL(); matA.nr = m; matA.nc = k; matA.ldnr = lda; matA.ldnc = lda; matA.rowcol_order = TGRowMajor; matA.coeftype = ETYPE; TGAlloc(&matA); ierr = TGFillMat2(&matA); tg_rectrange_t range = {.nr1 = 0, .nr2 = lda, .nc1 = 0, .nc2 = lda}; ierr = TGShowMat(range, &matA); range = (tg_rectrange_t){ .nr1 = min(2, m), .nr2 = min(5, m), .nc1 = min(2, k), .nc2 = min(5, k)}; ierr = TGShowMat(range, &matA); TGExit(&matA); return ierr; }
0
ALLM/testgemm/LIBTG
ALLM/testgemm/LIBTG/include/datatype.h
#ifndef _datatype_h_ #define _datatype_h_ #include <assert.h> #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef int32_t tg_int32_t; typedef int64_t tg_int64_t; typedef uint32_t tg_uint32_t; typedef uint64_t tg_uint64_t; typedef double tg_fixdbl_t; typedef float tg_fixflt_t; typedef double tg_double_t; typedef float tg_float_t; /** * Compiler numbers (Extracted form PaRSEC project) **/ #if defined(_MSC_VER) && !defined(__INTEL_COMPILER) /* Windows and non-Intel compiler */ #include <complex> typedef std::complex<float> tg_complex32_t; typedef std::complex<double> tg_complex64_t; #else typedef float _Complex tg_complex32_t; typedef double _Complex tg_complex64_t; #endif #if !defined(__cplusplus) && defined(HAVE_COMPLES_H) #include <complex.h> #else #ifdef __cplusplus extern "C" { #endif /** * These declaration will not clash with C++ provides because * the names in C++ are name-mangled. */ extern double cabs(tg_complex64_t z); extern double creal(tg_complex64_t z); extern double cimag(tg_complex64_t z); extern float cabsf(tg_complex32_t z); extern float crealf(tg_complex32_t z); extern float cimagf(tg_complex32_t z); extern tg_complex64_t conj(tg_complex64_t z); extern tg_complex64_t csqrt(tg_complex64_t z); extern tg_complex32_t conjf(tg_complex32_t z); extern tg_complex32_t csqrtf(tg_complex32_t z); #ifdef __cplusplus } #endif #endif /* HAVE_COMPLEX_H */ #ifndef TYPE #define TYPE other #endif #if TYPE == float #undef TYPE #define TYPE tg_float_t #define ETYPE TGFloat typedef tg_float_t tg_scalar_t; #elif TYPE == double #undef TYPE #define TYPE tg_double_t #define ETYPE TGDouble typedef tg_double_t tg_scalar_t; #elif TYPE == cx32 #undef TYPE #define TYPE tg_complex32_t #define ETYPE TGComplex32 typedef tg_complex32_t tg_scalar_t; #elif TYPE == cx64 #undef TYPE #define TYPE tg_complex64_t #define ETYPE TGComplex64 typedef tg_complex64_t tg_scalar_t; #else #error Undefined TYPE not supported exit(EXIT_SUCCESS); #endif // TYPE #ifndef ITYPE #define ITYPE I32 #endif #if ITYPE == I32 #undef ITYPE #define ITYPE tg_int32_t typedef tg_int32_t tg_int_t; typedef tg_uint32_t tg_uint_t; #elif ITYPE == I64 #undef ITYPE #define ITYPE tg_int64_t typedef tg_int64_t tg_int_t; typedef tg_uint64_t tg_uint_t; #else #error Undefined ITYPE not supported exit(EXIT_SUCCESS); #endif // TYPE #define max(a, b) (((a) < (b)) ? (b) : (a)) #define min(a, b) (((a) < (b)) ? (a) : (b)) typedef enum tg_rc_major_order_e { TGRowMajor, /**< Row major order >*/ TGColMajor /**< Col major order >*/ } tg_rc_major_order_t; typedef enum tg_coeftype_e { TGFloat = 2, TGDouble = 3, TGComplex32 = 4, TGComplex64 = 5 } tg_coeftype_t; struct tg_rectrange_s; typedef struct tg_rectrange_s { tg_int_t nr1; tg_int_t nr2; tg_int_t nc1; tg_int_t nc2; } tg_rectrange_t; struct tg_mat_s; typedef struct tg_mat_s { tg_rc_major_order_t rowcol_order; tg_coeftype_t coeftype; tg_int_t nr; tg_int_t nc; tg_int_t ldnr; tg_int_t ldnc; void *val; } tg_mat_t; #define TGMATNULL() \ { \ .rowcol_order = TGColMajor, .coeftype = TGDouble, .nr = 0, .nc = 0, \ .ldnr = 0, .ldnc = 0, .val = NULL \ } struct tg_submat_s; typedef struct tg_submat_s { tg_rectrange_t rectrange; tg_mat_t *mat; } tg_submat_t; static inline size_t tg_size_of(tg_coeftype_t type) { switch (type) { case TGFloat: return sizeof(float); case TGDouble: return sizeof(double); case TGComplex32: return 2 * sizeof(float); case TGComplex64: return 2 * sizeof(double); default: fprintf(stderr, "tg_size_of: invalid type parameter\n"); assert(0); return sizeof(double); } } #endif /* _datatype_h_ */
0
ALLM/testgemm/LIBTG
ALLM/testgemm/LIBTG/src/tgutils.c
#include "include/datatype.h" void TGFill(tg_int_t pos, tg_scalar_t filler, tg_scalar_t *scalar) { scalar[pos] = filler; } void TGShow(tg_int_t pos, tg_scalar_t *scalar) { printf("%f ", (tg_scalar_t)scalar[pos]); } void TGAlloc(tg_mat_t *mat) { if (mat->val == NULL) { size_t valsize = (size_t)mat->ldnr * (size_t)mat->ldnc; mat->val = calloc(valsize, tg_size_of(mat->coeftype)); } } void TGExit(tg_mat_t *mat) { if (mat->val != NULL) { free(mat->val); mat->val = NULL; } } int TGFillMat(tg_scalar_t val, tg_mat_t *mat) { int ierr = EXIT_SUCCESS; if (!mat) { return EXIT_FAILURE; if (!mat->val) { return EXIT_FAILURE; } } size_t size = mat->ldnr * mat->ldnc; for (size_t i = 0; i < size; i++) { TGFill(i, val, mat->val); } return ierr; } int TGFillMat2(tg_mat_t *mat) { int ierr = EXIT_SUCCESS; size_t i = 0, j = 0, offset = 0; size_t imax = (size_t)mat->ldnr; size_t jmax = (size_t)mat->ldnc; if (!mat) { return EXIT_FAILURE; if (!mat->val) { return EXIT_FAILURE; } } if (mat->rowcol_order == TGRowMajor) { offset = (size_t)mat->ldnc; printf("\toffset=%zu\n", offset); for (i = 0; i < imax; i++) { size_t k = offset * i; for (j = 0; j < jmax; j++) { printf("\ti=%zu\tj=%zu\tl=%zu\n", i, j, j + k); TGFill(j + k, (tg_scalar_t)(j + k), (tg_scalar_t *)mat->val); } } } else if (mat->rowcol_order == TGColMajor) { offset = mat->ldnr; printf("\toffset=%zu\n", offset); for (j = 0; j < jmax; j++) { size_t k = offset * j; for (i = 0; i < imax; i++) { printf("\tj=%zu\ti=%zu\tl=%zu\n", j, i, i + k); TGFill(i + k, (tg_scalar_t)(i + k), (tg_scalar_t *)mat->val); } } } return ierr; } int TGShowMat(tg_rectrange_t range, tg_mat_t *mat) { int ierr = EXIT_SUCCESS; size_t i = 0, j = 0, offset = 0; tg_int_t imin = range.nr1; tg_int_t jmin = range.nc1; tg_int_t imax = range.nr2; tg_int_t jmax = range.nc2; printf("RANGE\n"); printf("%zu\t%zu\t%zu\t%zu\n", range.nr1, range.nr2, range.nc1, range.nc2); printf("%zu\t%zu\t%zu\t%zu\n", imin, imax, jmin, jmax); if (!mat) { return EXIT_FAILURE; if (!mat->val) { return EXIT_FAILURE; } } if (mat->rowcol_order == TGRowMajor) { offset = mat->ldnc; for (i = imin; i < imax; i++) { size_t k = offset * i; for (j = jmin; j < jmax; j++) { TGShow(j + k, (tg_scalar_t *)mat->val); } printf("\n"); } } else if (mat->rowcol_order == TGColMajor) { offset = mat->ldnr; for (j = jmin; j < jmax; j++) { size_t k = offset * j; for (i = imin; i < imax; i++) { TGShow(i + k, (tg_scalar_t *)mat->val); } printf("\n"); } } return ierr; } int FillMat(tg_int_t nrow, tg_int_t ncol, tg_scalar_t val, tg_scalar_t *Mat) { int ierr = EXIT_SUCCESS; if (!Mat) { return EXIT_FAILURE; } size_t size = nrow * ncol; for (size_t i = 0; i < size; i++) { Mat[i] = val; } return ierr; } int ShowMat(tg_int_t nrow, tg_int_t nr1, tg_int_t nr2, tg_int_t nc1, tg_int_t nc2, TYPE *Mat) { int ierr = EXIT_SUCCESS; tg_int_t i = 0; tg_int_t j = 0; if (!Mat) { return EXIT_FAILURE; } for (i = nr1; i < nr2; i++) { for (j = nc1; j < nc2; j++) { printf("%lf\t", Mat[i + j * nrow]); } printf("\n"); } return ierr; } int GetDim(tg_int_t *m, tg_int_t *n, tg_int_t *k, tg_int_t *lda, tg_int_t *ldb, tg_int_t *ldc, int argc, char **argv) { int ierr = EXIT_SUCCESS; char *endPtr = NULL; if (argc != 7) { printf("Trying to Compute C = A*B + C\n"); printf("Please rerun with:/t./exec m n k lda ldb ldc\n"); printf("Where A is mxk inside ldaxlda; B is kxn inside ldbxldb; C is mxk " "inside ldcxldc\n"); exit(ierr); } else { *m = strtol(argv[1], &endPtr, 10); *n = strtol(argv[2], &endPtr, 10); *k = strtol(argv[3], &endPtr, 10); *lda = strtol(argv[4], &endPtr, 10); *ldb = strtol(argv[5], &endPtr, 10); *ldc = strtol(argv[6], &endPtr, 10); printf("m = %ld\tn = %ld\tk = %ld\n", *m, *n, *k); printf("lda = %ld\tldb = %ld\tldc = %ld\n", *lda, *ldb, *ldc); } return ierr; }
0
ALLM/M2
ALLM/M2/lapack/lapack_testing.py
#!/usr/bin/env python3 ############################################################################### # lapack_testing.py ############################################################################### from subprocess import Popen, STDOUT, PIPE import os, sys, math import getopt # Arguments try: opts, args = getopt.getopt(sys.argv[1:], "hd:b:srep:t:n", ["help", "dir=", "bin=", "short", "run", "error","prec=","test=","number"]) except getopt.error as msg: print(msg) print("for help use --help") sys.exit(2) short_summary = False with_file = True just_errors = False prec='x' test='all' only_numbers = False test_dir='TESTING' bin_dir='bin/Release' for o, a in opts: if o in ("-h", "--help"): print(sys.argv[0]+" [-h|--help] [-d dir |--dir dir] [-s |--short] [-r |--run] [-e |--error] [-p p |--prec p] [-t test |--test test] [-n | --number]") print(" - h is to print this message") print(" - r is to use to run the LAPACK tests then analyse the output (.out files). By default, the script will not run all the LAPACK tests") print(" - d [dir] indicates the location of the LAPACK testing directory (.out files). By default, the script will use {:s}.".format(test_dir)) print(" - b [bin] indicates the location of the LAPACK binary files. By default, the script will use {:s}.".format(bin_dir)) print(" LEVEL OF OUTPUT") print(" - e is to print only the error summary") print(" - s is to print a short summary") print(" - n is to print the numbers of failing tests (turn on summary mode)") print(" SELECTION OF TESTS:") print(" - p [s/c/d/z/x] is to indicate the PRECISION to run:") print(" s=single") print(" d=double") print(" sd=single/double") print(" c=complex") print(" z=double complex") print(" cz=complex/double complex") print(" x=all [DEFAULT]") print(" - t [lin/eig/mixed/rfp/all] is to indicate which TEST FAMILY to run:") print(" lin=Linear Equation") print(" eig=Eigen Problems") print(" mixed=mixed-precision") print(" rfp=rfp format") print(" all=all tests [DEFAULT]") print(" EXAMPLES:") print(" ./lapack_testing.py -n") print(" Will return the numbers of failed tests by analyzing the LAPACK output") print(" ./lapack_testing.py -n -r -p s") print(" Will return the numbers of failed tests in REAL precision by running the LAPACK Tests then analyzing the output") print(" ./lapack_testing.py -n -p s -t eig ") print(" Will return the numbers of failed tests in REAL precision by analyzing only the LAPACK output of EIGEN testings") sys.exit(0) else: if o in ("-s", "--short"): short_summary = True if o in ("-r", "--run"): with_file = False if o in ("-e", "--error"): just_errors = True if o in ( '-p', '--prec' ): prec = a if o in ( '-b', '--bin' ): bin_dir = a if o in ( '-d', '--dir' ): test_dir = a if o in ( '-t', '--test' ): test = a if o in ( '-n', '--number' ): only_numbers = True short_summary = True # process options abs_bin_dir=os.path.abspath(bin_dir) os.chdir(test_dir) execution=1 summary="\n\t\t\t--> LAPACK TESTING SUMMARY <--\n"; if with_file: summary+= "\t\tProcessing LAPACK Testing output found in the "+test_dir+" directory\n"; summary+="SUMMARY \tnb test run \tnumerical error \tother error \n"; summary+="================ \t===========\t=================\t================ \n"; nb_of_test=0 # Add current directory to the path for subshells of this shell # Allows the popen to find local files in both windows and unixes os.environ["PATH"] = os.environ["PATH"]+":." # Define a function to open the executable (different filenames on unix and Windows) def run_summary_test( f, cmdline, short_summary): nb_test_run=0 nb_test_fail=0 nb_test_illegal=0 nb_test_info=0 if with_file: if not os.path.exists(cmdline): error_message=cmdline+" file not found" r=1 if short_summary: return [nb_test_run,nb_test_fail,nb_test_illegal,nb_test_info] else: pipe = open(cmdline,'r') r=0 else: cmdline = os.path.join(abs_bin_dir, cmdline) outfile=cmdline.split()[4] #pipe = open(outfile,'w') p = Popen(cmdline, shell=True)#, stdout=pipe) p.wait() #pipe.close() r=p.returncode pipe = open(outfile,'r') error_message=cmdline+" did not work" if r != 0 and not with_file: print("---- TESTING " + cmdline.split()[0] + "... FAILED(" + error_message +") !") for line in pipe.readlines(): f.write(str(line)) elif r != 0 and with_file and not short_summary: print("---- WARNING: please check that you have the LAPACK output : "+cmdline+"!") print("---- WARNING: with the option -r, we can run the LAPACK testing for you") # print "---- "+error_message else: for line in pipe.readlines(): f.write(str(line)) words_in_line=line.split() if (line.find("run)")!=-1): # print line whereisrun=words_in_line.index("run)") nb_test_run+=int(words_in_line[whereisrun-2]) if (line.find("out of")!=-1): if not short_summary: print(line, end=' ') whereisout= words_in_line.index("out") nb_test_fail+=int(words_in_line[whereisout-1]) if ((line.find("illegal")!=-1) or (line.find("Illegal")!=-1)): if not short_summary: print(line, end=' ') nb_test_illegal+=1 if (line.find(" INFO")!=-1): if not short_summary: print(line, end=' ') nb_test_info+=1 if with_file: pipe.close() f.flush(); return [nb_test_run,nb_test_fail,nb_test_illegal,nb_test_info] # If filename cannot be opened, send output to sys.stderr filename = "testing_results.txt" try: f = open(filename, 'w') except IOError: f = sys.stdout if not short_summary: print(" ") print("---------------- Testing LAPACK Routines ----------------") print(" ") print("-- Detailed results are stored in", filename) dtypes = ( ("s", "d", "c", "z"), ("REAL ", "DOUBLE PRECISION", "COMPLEX ", "COMPLEX16 "), ) if prec=='s': range_prec=[0] elif prec=='d': range_prec=[1] elif prec=='sd': range_prec=[0,1] elif prec=='c': range_prec=[2] elif prec=='z': range_prec=[3] elif prec=='cz': range_prec=[2,3] else: prec='x'; range_prec=list(range(4)) if test=='lin': range_test=[16] elif test=='mixed': range_test=[17] range_prec=[1,3] elif test=='rfp': range_test=[18] elif test=='dmd': range_test=[20] elif test=='eig': range_test=list(range(16)) else: range_test=list(range(19)) list_results = [ [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], ] for dtype in range_prec: letter = dtypes[0][dtype] name = dtypes[1][dtype] if not short_summary: print(" ") print("------------------------- %s ------------------------" % name) print(" ") sys.stdout.flush() dtests = ( ("nep", "sep", "se2", "svd", letter+"ec",letter+"ed",letter+"gg", letter+"gd",letter+"sb",letter+"sg", letter+"bb","glm","gqr", "gsv","csd","lse", letter+"test", letter+dtypes[0][dtype-1]+"test",letter+"test_rfp",letter+"dmd"), ("Nonsymmetric-Eigenvalue-Problem", "Symmetric-Eigenvalue-Problem", "Symmetric-Eigenvalue-Problem-2-stage", "Singular-Value-Decomposition", "Eigen-Condition","Nonsymmetric-Eigenvalue","Nonsymmetric-Generalized-Eigenvalue-Problem", "Nonsymmetric-Generalized-Eigenvalue-Problem-driver", "Symmetric-Eigenvalue-Problem", "Symmetric-Eigenvalue-Generalized-Problem", "Banded-Singular-Value-Decomposition-routines", "Generalized-Linear-Regression-Model-routines", "Generalized-QR-and-RQ-factorization-routines", "Generalized-Singular-Value-Decomposition-routines", "CS-Decomposition-routines", "Constrained-Linear-Least-Squares-routines", "Linear-Equation-routines", "Mixed-Precision-linear-equation-routines","RFP-linear-equation-routines","Dynamic-Mode-Decomposition"), (letter+"nep", letter+"sep", letter+"se2", letter+"svd", letter+"ec",letter+"ed",letter+"gg", letter+"gd",letter+"sb",letter+"sg", letter+"bb",letter+"glm",letter+"gqr", letter+"gsv",letter+"csd",letter+"lse", letter+"test", letter+dtypes[0][dtype-1]+"test",letter+"test_rfp",letter+"dmd"), ) for dtest in range_test: nb_of_test=0 # NEED TO SKIP SOME PRECISION (namely s and c) FOR PROTO MIXED PRECISION TESTING if dtest==17 and (letter=="s" or letter=="c"): continue if with_file: cmdbase=dtests[2][dtest]+".out" else: if dtest==16: # LIN TESTS cmdbase="xlintst"+letter+" < "+dtests[0][dtest]+".in > "+dtests[2][dtest]+".out" elif dtest==17: # PROTO LIN TESTS cmdbase="xlintst"+letter+dtypes[0][dtype-1]+" < "+dtests[0][dtest]+".in > "+dtests[2][dtest]+".out" elif dtest==18: # PROTO LIN TESTS cmdbase="xlintstrf"+letter+" < "+dtests[0][dtest]+".in > "+dtests[2][dtest]+".out" elif dtest==20: # DMD EIG TESTS cmdbase="xdmdeigtst"+letter+" < "+dtests[0][dtest]+".in > "+dtests[2][dtest]+".out" else: # EIG TESTS cmdbase="xeigtst"+letter+" < "+dtests[0][dtest]+".in > "+dtests[2][dtest]+".out" if not just_errors and not short_summary: print("Testing "+name+" "+dtests[1][dtest]+"-"+cmdbase, end=' ') # Run the process: either to read the file or run the LAPACK testing nb_test = run_summary_test(f, cmdbase, short_summary) list_results[0][dtype]+=nb_test[0] list_results[1][dtype]+=nb_test[1] list_results[2][dtype]+=nb_test[2] list_results[3][dtype]+=nb_test[3] got_error=nb_test[1]+nb_test[2]+nb_test[3] if not short_summary: if nb_test[0] > 0 and not just_errors: print("passed: "+str(nb_test[0])) if nb_test[1] > 0: print("failing to pass the threshold: "+str(nb_test[1])) if nb_test[2] > 0: print("Illegal Error: "+str(nb_test[2])) if nb_test[3] > 0: print("Info Error: "+str(nb_test[3])) if got_error > 0 and just_errors: print("ERROR IS LOCATED IN "+name+" "+dtests[1][dtest]+" [ "+cmdbase+" ]") print("") if not just_errors: print("") # elif (got_error>0): # print dtests[2][dtest]+".out \t"+str(nb_test[1])+"\t"+str(nb_test[2])+"\t"+str(nb_test[3]) sys.stdout.flush() if (list_results[0][dtype] > 0 ): percent_num_error=float(list_results[1][dtype])/float(list_results[0][dtype])*100 percent_error=float(list_results[2][dtype]+list_results[3][dtype])/float(list_results[0][dtype])*100 else: percent_num_error=0 percent_error=0 summary+=name+"\t"+str(list_results[0][dtype])+"\t\t"+str(list_results[1][dtype])+"\t("+"%.3f" % percent_num_error+"%)\t"+str(list_results[2][dtype]+list_results[3][dtype])+"\t("+"%.3f" % percent_error+"%)\t""\n" list_results[0][4]+=list_results[0][dtype] list_results[1][4]+=list_results[1][dtype] list_results[2][4]+=list_results[2][dtype] list_results[3][4]+=list_results[3][dtype] if only_numbers: print(str(list_results[1][4])+"\n"+str(list_results[2][4]+list_results[3][4])) else: print(summary) if (list_results[0][4] > 0 ): percent_num_error=float(list_results[1][4])/float(list_results[0][4])*100 percent_error=float(list_results[2][4]+list_results[3][4])/float(list_results[0][4])*100 else: percent_num_error=0 percent_error=0 if (prec=='x'): print("--> ALL PRECISIONS\t"+str(list_results[0][4])+"\t\t"+str(list_results[1][4])+"\t("+"%.3f" % percent_num_error+"%)\t"+str(list_results[2][4]+list_results[3][4])+"\t("+"%.3f" % percent_error+"%)\t""\n") if list_results[0][4] == 0: print("NO TESTS WERE ANALYZED, please use the -r option to run the LAPACK TESTING") # This may close the sys.stdout stream, so make it the last statement f.close()
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/caxpy.f
*> \brief \b CAXPY * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CAXPY(N,CA,CX,INCX,CY,INCY) * * .. Scalar Arguments .. * COMPLEX CA * INTEGER INCX,INCY,N * .. * .. Array Arguments .. * COMPLEX CX(*),CY(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CAXPY constant times a vector plus a vector. *> \endverbatim * * Arguments: * ========== * *> \param[in] N *> \verbatim *> N is INTEGER *> number of elements in input vector(s) *> \endverbatim *> *> \param[in] CA *> \verbatim *> CA is COMPLEX *> On entry, CA specifies the scalar alpha. *> \endverbatim *> *> \param[in] CX *> \verbatim *> CX is COMPLEX array, dimension ( 1 + ( N - 1 )*abs( INCX ) ) *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> storage spacing between elements of CX *> \endverbatim *> *> \param[in,out] CY *> \verbatim *> CY is COMPLEX array, dimension ( 1 + ( N - 1 )*abs( INCY ) ) *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> storage spacing between elements of CY *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup axpy * *> \par Further Details: * ===================== *> *> \verbatim *> *> jack dongarra, linpack, 3/11/78. *> modified 12/3/93, array(1) declarations changed to array(*) *> \endverbatim *> * ===================================================================== SUBROUTINE CAXPY(N,CA,CX,INCX,CY,INCY) * * -- Reference BLAS level1 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX CA INTEGER INCX,INCY,N * .. * .. Array Arguments .. COMPLEX CX(*),CY(*) * .. * * ===================================================================== * * .. Local Scalars .. INTEGER I,IX,IY * .. * .. External Functions .. REAL SCABS1 EXTERNAL SCABS1 * .. IF (N.LE.0) RETURN IF (SCABS1(CA).EQ.0.0E+0) RETURN IF (INCX.EQ.1 .AND. INCY.EQ.1) THEN * * code for both increments equal to 1 * DO I = 1,N CY(I) = CY(I) + CA*CX(I) END DO ELSE * * code for unequal increments or equal increments * not equal to 1 * IX = 1 IY = 1 IF (INCX.LT.0) IX = (-N+1)*INCX + 1 IF (INCY.LT.0) IY = (-N+1)*INCY + 1 DO I = 1,N CY(IY) = CY(IY) + CA*CX(IX) IX = IX + INCX IY = IY + INCY END DO END IF * RETURN * * End of CAXPY * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/ccopy.f
*> \brief \b CCOPY * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CCOPY(N,CX,INCX,CY,INCY) * * .. Scalar Arguments .. * INTEGER INCX,INCY,N * .. * .. Array Arguments .. * COMPLEX CX(*),CY(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CCOPY copies a vector x to a vector y. *> \endverbatim * * Arguments: * ========== * *> \param[in] N *> \verbatim *> N is INTEGER *> number of elements in input vector(s) *> \endverbatim *> *> \param[in] CX *> \verbatim *> CX is COMPLEX array, dimension ( 1 + ( N - 1 )*abs( INCX ) ) *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> storage spacing between elements of CX *> \endverbatim *> *> \param[out] CY *> \verbatim *> CY is COMPLEX array, dimension ( 1 + ( N - 1 )*abs( INCY ) ) *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> storage spacing between elements of CY *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup copy * *> \par Further Details: * ===================== *> *> \verbatim *> *> jack dongarra, linpack, 3/11/78. *> modified 12/3/93, array(1) declarations changed to array(*) *> \endverbatim *> * ===================================================================== SUBROUTINE CCOPY(N,CX,INCX,CY,INCY) * * -- Reference BLAS level1 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. INTEGER INCX,INCY,N * .. * .. Array Arguments .. COMPLEX CX(*),CY(*) * .. * * ===================================================================== * * .. Local Scalars .. INTEGER I,IX,IY * .. IF (N.LE.0) RETURN IF (INCX.EQ.1 .AND. INCY.EQ.1) THEN * * code for both increments equal to 1 * DO I = 1,N CY(I) = CX(I) END DO ELSE * * code for unequal increments or equal increments * not equal to 1 * IX = 1 IY = 1 IF (INCX.LT.0) IX = (-N+1)*INCX + 1 IF (INCY.LT.0) IY = (-N+1)*INCY + 1 DO I = 1,N CY(IY) = CX(IX) IX = IX + INCX IY = IY + INCY END DO END IF RETURN * * End of CCOPY * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/cdotc.f
*> \brief \b CDOTC * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * COMPLEX FUNCTION CDOTC(N,CX,INCX,CY,INCY) * * .. Scalar Arguments .. * INTEGER INCX,INCY,N * .. * .. Array Arguments .. * COMPLEX CX(*),CY(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CDOTC forms the dot product of two complex vectors *> CDOTC = X^H * Y *> *> \endverbatim * * Arguments: * ========== * *> \param[in] N *> \verbatim *> N is INTEGER *> number of elements in input vector(s) *> \endverbatim *> *> \param[in] CX *> \verbatim *> CX is COMPLEX array, dimension ( 1 + ( N - 1 )*abs( INCX ) ) *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> storage spacing between elements of CX *> \endverbatim *> *> \param[in] CY *> \verbatim *> CY is COMPLEX array, dimension ( 1 + ( N - 1 )*abs( INCY ) ) *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> storage spacing between elements of CY *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup dot * *> \par Further Details: * ===================== *> *> \verbatim *> *> jack dongarra, linpack, 3/11/78. *> modified 12/3/93, array(1) declarations changed to array(*) *> \endverbatim *> * ===================================================================== COMPLEX FUNCTION CDOTC(N,CX,INCX,CY,INCY) * * -- Reference BLAS level1 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. INTEGER INCX,INCY,N * .. * .. Array Arguments .. COMPLEX CX(*),CY(*) * .. * * ===================================================================== * * .. Local Scalars .. COMPLEX CTEMP INTEGER I,IX,IY * .. * .. Intrinsic Functions .. INTRINSIC CONJG * .. CTEMP = (0.0,0.0) CDOTC = (0.0,0.0) IF (N.LE.0) RETURN IF (INCX.EQ.1 .AND. INCY.EQ.1) THEN * * code for both increments equal to 1 * DO I = 1,N CTEMP = CTEMP + CONJG(CX(I))*CY(I) END DO ELSE * * code for unequal increments or equal increments * not equal to 1 * IX = 1 IY = 1 IF (INCX.LT.0) IX = (-N+1)*INCX + 1 IF (INCY.LT.0) IY = (-N+1)*INCY + 1 DO I = 1,N CTEMP = CTEMP + CONJG(CX(IX))*CY(IY) IX = IX + INCX IY = IY + INCY END DO END IF CDOTC = CTEMP RETURN * * End of CDOTC * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/cdotu.f
*> \brief \b CDOTU * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * COMPLEX FUNCTION CDOTU(N,CX,INCX,CY,INCY) * * .. Scalar Arguments .. * INTEGER INCX,INCY,N * .. * .. Array Arguments .. * COMPLEX CX(*),CY(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CDOTU forms the dot product of two complex vectors *> CDOTU = X^T * Y *> *> \endverbatim * * Arguments: * ========== * *> \param[in] N *> \verbatim *> N is INTEGER *> number of elements in input vector(s) *> \endverbatim *> *> \param[in] CX *> \verbatim *> CX is COMPLEX array, dimension ( 1 + ( N - 1 )*abs( INCX ) ) *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> storage spacing between elements of CX *> \endverbatim *> *> \param[in] CY *> \verbatim *> CY is COMPLEX array, dimension ( 1 + ( N - 1 )*abs( INCY ) ) *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> storage spacing between elements of CY *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup dot * *> \par Further Details: * ===================== *> *> \verbatim *> *> jack dongarra, linpack, 3/11/78. *> modified 12/3/93, array(1) declarations changed to array(*) *> \endverbatim *> * ===================================================================== COMPLEX FUNCTION CDOTU(N,CX,INCX,CY,INCY) * * -- Reference BLAS level1 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. INTEGER INCX,INCY,N * .. * .. Array Arguments .. COMPLEX CX(*),CY(*) * .. * * ===================================================================== * * .. Local Scalars .. COMPLEX CTEMP INTEGER I,IX,IY * .. CTEMP = (0.0,0.0) CDOTU = (0.0,0.0) IF (N.LE.0) RETURN IF (INCX.EQ.1 .AND. INCY.EQ.1) THEN * * code for both increments equal to 1 * DO I = 1,N CTEMP = CTEMP + CX(I)*CY(I) END DO ELSE * * code for unequal increments or equal increments * not equal to 1 * IX = 1 IY = 1 IF (INCX.LT.0) IX = (-N+1)*INCX + 1 IF (INCY.LT.0) IY = (-N+1)*INCY + 1 DO I = 1,N CTEMP = CTEMP + CX(IX)*CY(IY) IX = IX + INCX IY = IY + INCY END DO END IF CDOTU = CTEMP RETURN * * End of CDOTU * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/cgbmv.f
*> \brief \b CGBMV * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CGBMV(TRANS,M,N,KL,KU,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) * * .. Scalar Arguments .. * COMPLEX ALPHA,BETA * INTEGER INCX,INCY,KL,KU,LDA,M,N * CHARACTER TRANS * .. * .. Array Arguments .. * COMPLEX A(LDA,*),X(*),Y(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CGBMV performs one of the matrix-vector operations *> *> y := alpha*A*x + beta*y, or y := alpha*A**T*x + beta*y, or *> *> y := alpha*A**H*x + beta*y, *> *> where alpha and beta are scalars, x and y are vectors and A is an *> m by n band matrix, with kl sub-diagonals and ku super-diagonals. *> \endverbatim * * Arguments: * ========== * *> \param[in] TRANS *> \verbatim *> TRANS is CHARACTER*1 *> On entry, TRANS specifies the operation to be performed as *> follows: *> *> TRANS = 'N' or 'n' y := alpha*A*x + beta*y. *> *> TRANS = 'T' or 't' y := alpha*A**T*x + beta*y. *> *> TRANS = 'C' or 'c' y := alpha*A**H*x + beta*y. *> \endverbatim *> *> \param[in] M *> \verbatim *> M is INTEGER *> On entry, M specifies the number of rows of the matrix A. *> M must be at least zero. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the number of columns of the matrix A. *> N must be at least zero. *> \endverbatim *> *> \param[in] KL *> \verbatim *> KL is INTEGER *> On entry, KL specifies the number of sub-diagonals of the *> matrix A. KL must satisfy 0 .le. KL. *> \endverbatim *> *> \param[in] KU *> \verbatim *> KU is INTEGER *> On entry, KU specifies the number of super-diagonals of the *> matrix A. KU must satisfy 0 .le. KU. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is COMPLEX *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] A *> \verbatim *> A is COMPLEX array, dimension ( LDA, N ) *> Before entry, the leading ( kl + ku + 1 ) by n part of the *> array A must contain the matrix of coefficients, supplied *> column by column, with the leading diagonal of the matrix in *> row ( ku + 1 ) of the array, the first super-diagonal *> starting at position 2 in row ku, the first sub-diagonal *> starting at position 1 in row ( ku + 2 ), and so on. *> Elements in the array A that do not correspond to elements *> in the band matrix (such as the top left ku by ku triangle) *> are not referenced. *> The following program segment will transfer a band matrix *> from conventional full matrix storage to band storage: *> *> DO 20, J = 1, N *> K = KU + 1 - J *> DO 10, I = MAX( 1, J - KU ), MIN( M, J + KL ) *> A( K + I, J ) = matrix( I, J ) *> 10 CONTINUE *> 20 CONTINUE *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> On entry, LDA specifies the first dimension of A as declared *> in the calling (sub) program. LDA must be at least *> ( kl + ku + 1 ). *> \endverbatim *> *> \param[in] X *> \verbatim *> X is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n' *> and at least *> ( 1 + ( m - 1 )*abs( INCX ) ) otherwise. *> Before entry, the incremented array X must contain the *> vector x. *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> On entry, INCX specifies the increment for the elements of *> X. INCX must not be zero. *> \endverbatim *> *> \param[in] BETA *> \verbatim *> BETA is COMPLEX *> On entry, BETA specifies the scalar beta. When BETA is *> supplied as zero then Y need not be set on input. *> \endverbatim *> *> \param[in,out] Y *> \verbatim *> Y is COMPLEX array, dimension at least *> ( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n' *> and at least *> ( 1 + ( n - 1 )*abs( INCY ) ) otherwise. *> Before entry, the incremented array Y must contain the *> vector y. On exit, Y is overwritten by the updated vector y. *> If either m or n is zero, then Y not referenced and the function *> performs a quick return. *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> On entry, INCY specifies the increment for the elements of *> Y. INCY must not be zero. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup gbmv * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 2 Blas routine. *> The vector and matrix arguments are not referenced when N = 0, or M = 0 *> *> -- Written on 22-October-1986. *> Jack Dongarra, Argonne National Lab. *> Jeremy Du Croz, Nag Central Office. *> Sven Hammarling, Nag Central Office. *> Richard Hanson, Sandia National Labs. *> \endverbatim *> * ===================================================================== SUBROUTINE CGBMV(TRANS,M,N,KL,KU,ALPHA,A,LDA,X,INCX, + BETA,Y,INCY) * * -- Reference BLAS level2 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX ALPHA,BETA INTEGER INCX,INCY,KL,KU,LDA,M,N CHARACTER TRANS * .. * .. Array Arguments .. COMPLEX A(LDA,*),X(*),Y(*) * .. * * ===================================================================== * * .. Parameters .. COMPLEX ONE PARAMETER (ONE= (1.0E+0,0.0E+0)) COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * .. Local Scalars .. COMPLEX TEMP INTEGER I,INFO,IX,IY,J,JX,JY,K,KUP1,KX,KY,LENX,LENY LOGICAL NOCONJ * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CONJG,MAX,MIN * .. * * Test the input parameters. * INFO = 0 IF (.NOT.LSAME(TRANS,'N') .AND. .NOT.LSAME(TRANS,'T') .AND. + .NOT.LSAME(TRANS,'C')) THEN INFO = 1 ELSE IF (M.LT.0) THEN INFO = 2 ELSE IF (N.LT.0) THEN INFO = 3 ELSE IF (KL.LT.0) THEN INFO = 4 ELSE IF (KU.LT.0) THEN INFO = 5 ELSE IF (LDA.LT. (KL+KU+1)) THEN INFO = 8 ELSE IF (INCX.EQ.0) THEN INFO = 10 ELSE IF (INCY.EQ.0) THEN INFO = 13 END IF IF (INFO.NE.0) THEN CALL XERBLA('CGBMV ',INFO) RETURN END IF * * Quick return if possible. * IF ((M.EQ.0) .OR. (N.EQ.0) .OR. + ((ALPHA.EQ.ZERO).AND. (BETA.EQ.ONE))) RETURN * NOCONJ = LSAME(TRANS,'T') * * Set LENX and LENY, the lengths of the vectors x and y, and set * up the start points in X and Y. * IF (LSAME(TRANS,'N')) THEN LENX = N LENY = M ELSE LENX = M LENY = N END IF IF (INCX.GT.0) THEN KX = 1 ELSE KX = 1 - (LENX-1)*INCX END IF IF (INCY.GT.0) THEN KY = 1 ELSE KY = 1 - (LENY-1)*INCY END IF * * Start the operations. In this version the elements of A are * accessed sequentially with one pass through the band part of A. * * First form y := beta*y. * IF (BETA.NE.ONE) THEN IF (INCY.EQ.1) THEN IF (BETA.EQ.ZERO) THEN DO 10 I = 1,LENY Y(I) = ZERO 10 CONTINUE ELSE DO 20 I = 1,LENY Y(I) = BETA*Y(I) 20 CONTINUE END IF ELSE IY = KY IF (BETA.EQ.ZERO) THEN DO 30 I = 1,LENY Y(IY) = ZERO IY = IY + INCY 30 CONTINUE ELSE DO 40 I = 1,LENY Y(IY) = BETA*Y(IY) IY = IY + INCY 40 CONTINUE END IF END IF END IF IF (ALPHA.EQ.ZERO) RETURN KUP1 = KU + 1 IF (LSAME(TRANS,'N')) THEN * * Form y := alpha*A*x + y. * JX = KX IF (INCY.EQ.1) THEN DO 60 J = 1,N TEMP = ALPHA*X(JX) K = KUP1 - J DO 50 I = MAX(1,J-KU),MIN(M,J+KL) Y(I) = Y(I) + TEMP*A(K+I,J) 50 CONTINUE JX = JX + INCX 60 CONTINUE ELSE DO 80 J = 1,N TEMP = ALPHA*X(JX) IY = KY K = KUP1 - J DO 70 I = MAX(1,J-KU),MIN(M,J+KL) Y(IY) = Y(IY) + TEMP*A(K+I,J) IY = IY + INCY 70 CONTINUE JX = JX + INCX IF (J.GT.KU) KY = KY + INCY 80 CONTINUE END IF ELSE * * Form y := alpha*A**T*x + y or y := alpha*A**H*x + y. * JY = KY IF (INCX.EQ.1) THEN DO 110 J = 1,N TEMP = ZERO K = KUP1 - J IF (NOCONJ) THEN DO 90 I = MAX(1,J-KU),MIN(M,J+KL) TEMP = TEMP + A(K+I,J)*X(I) 90 CONTINUE ELSE DO 100 I = MAX(1,J-KU),MIN(M,J+KL) TEMP = TEMP + CONJG(A(K+I,J))*X(I) 100 CONTINUE END IF Y(JY) = Y(JY) + ALPHA*TEMP JY = JY + INCY 110 CONTINUE ELSE DO 140 J = 1,N TEMP = ZERO IX = KX K = KUP1 - J IF (NOCONJ) THEN DO 120 I = MAX(1,J-KU),MIN(M,J+KL) TEMP = TEMP + A(K+I,J)*X(IX) IX = IX + INCX 120 CONTINUE ELSE DO 130 I = MAX(1,J-KU),MIN(M,J+KL) TEMP = TEMP + CONJG(A(K+I,J))*X(IX) IX = IX + INCX 130 CONTINUE END IF Y(JY) = Y(JY) + ALPHA*TEMP JY = JY + INCY IF (J.GT.KU) KX = KX + INCX 140 CONTINUE END IF END IF * RETURN * * End of CGBMV * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/cgemm.f
*> \brief \b CGEMM * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CGEMM(TRANSA,TRANSB,M,N,K,ALPHA,A,LDA,B,LDB,BETA,C,LDC) * * .. Scalar Arguments .. * COMPLEX ALPHA,BETA * INTEGER K,LDA,LDB,LDC,M,N * CHARACTER TRANSA,TRANSB * .. * .. Array Arguments .. * COMPLEX A(LDA,*),B(LDB,*),C(LDC,*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CGEMM performs one of the matrix-matrix operations *> *> C := alpha*op( A )*op( B ) + beta*C, *> *> where op( X ) is one of *> *> op( X ) = X or op( X ) = X**T or op( X ) = X**H, *> *> alpha and beta are scalars, and A, B and C are matrices, with op( A ) *> an m by k matrix, op( B ) a k by n matrix and C an m by n matrix. *> \endverbatim * * Arguments: * ========== * *> \param[in] TRANSA *> \verbatim *> TRANSA is CHARACTER*1 *> On entry, TRANSA specifies the form of op( A ) to be used in *> the matrix multiplication as follows: *> *> TRANSA = 'N' or 'n', op( A ) = A. *> *> TRANSA = 'T' or 't', op( A ) = A**T. *> *> TRANSA = 'C' or 'c', op( A ) = A**H. *> \endverbatim *> *> \param[in] TRANSB *> \verbatim *> TRANSB is CHARACTER*1 *> On entry, TRANSB specifies the form of op( B ) to be used in *> the matrix multiplication as follows: *> *> TRANSB = 'N' or 'n', op( B ) = B. *> *> TRANSB = 'T' or 't', op( B ) = B**T. *> *> TRANSB = 'C' or 'c', op( B ) = B**H. *> \endverbatim *> *> \param[in] M *> \verbatim *> M is INTEGER *> On entry, M specifies the number of rows of the matrix *> op( A ) and of the matrix C. M must be at least zero. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the number of columns of the matrix *> op( B ) and the number of columns of the matrix C. N must be *> at least zero. *> \endverbatim *> *> \param[in] K *> \verbatim *> K is INTEGER *> On entry, K specifies the number of columns of the matrix *> op( A ) and the number of rows of the matrix op( B ). K must *> be at least zero. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is COMPLEX *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] A *> \verbatim *> A is COMPLEX array, dimension ( LDA, ka ), where ka is *> k when TRANSA = 'N' or 'n', and is m otherwise. *> Before entry with TRANSA = 'N' or 'n', the leading m by k *> part of the array A must contain the matrix A, otherwise *> the leading k by m part of the array A must contain the *> matrix A. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> On entry, LDA specifies the first dimension of A as declared *> in the calling (sub) program. When TRANSA = 'N' or 'n' then *> LDA must be at least max( 1, m ), otherwise LDA must be at *> least max( 1, k ). *> \endverbatim *> *> \param[in] B *> \verbatim *> B is COMPLEX array, dimension ( LDB, kb ), where kb is *> n when TRANSB = 'N' or 'n', and is k otherwise. *> Before entry with TRANSB = 'N' or 'n', the leading k by n *> part of the array B must contain the matrix B, otherwise *> the leading n by k part of the array B must contain the *> matrix B. *> \endverbatim *> *> \param[in] LDB *> \verbatim *> LDB is INTEGER *> On entry, LDB specifies the first dimension of B as declared *> in the calling (sub) program. When TRANSB = 'N' or 'n' then *> LDB must be at least max( 1, k ), otherwise LDB must be at *> least max( 1, n ). *> \endverbatim *> *> \param[in] BETA *> \verbatim *> BETA is COMPLEX *> On entry, BETA specifies the scalar beta. When BETA is *> supplied as zero then C need not be set on input. *> \endverbatim *> *> \param[in,out] C *> \verbatim *> C is COMPLEX array, dimension ( LDC, N ) *> Before entry, the leading m by n part of the array C must *> contain the matrix C, except when beta is zero, in which *> case C need not be set on entry. *> On exit, the array C is overwritten by the m by n matrix *> ( alpha*op( A )*op( B ) + beta*C ). *> \endverbatim *> *> \param[in] LDC *> \verbatim *> LDC is INTEGER *> On entry, LDC specifies the first dimension of C as declared *> in the calling (sub) program. LDC must be at least *> max( 1, m ). *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup gemm * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 3 Blas routine. *> *> -- Written on 8-February-1989. *> Jack Dongarra, Argonne National Laboratory. *> Iain Duff, AERE Harwell. *> Jeremy Du Croz, Numerical Algorithms Group Ltd. *> Sven Hammarling, Numerical Algorithms Group Ltd. *> \endverbatim *> * ===================================================================== SUBROUTINE CGEMM(TRANSA,TRANSB,M,N,K,ALPHA,A,LDA,B,LDB, + BETA,C,LDC) * * -- Reference BLAS level3 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX ALPHA,BETA INTEGER K,LDA,LDB,LDC,M,N CHARACTER TRANSA,TRANSB * .. * .. Array Arguments .. COMPLEX A(LDA,*),B(LDB,*),C(LDC,*) * .. * * ===================================================================== * * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CONJG,MAX * .. * .. Local Scalars .. COMPLEX TEMP INTEGER I,INFO,J,L,NROWA,NROWB LOGICAL CONJA,CONJB,NOTA,NOTB * .. * .. Parameters .. COMPLEX ONE PARAMETER (ONE= (1.0E+0,0.0E+0)) COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * * Set NOTA and NOTB as true if A and B respectively are not * conjugated or transposed, set CONJA and CONJB as true if A and * B respectively are to be transposed but not conjugated and set * NROWA and NROWB as the number of rows of A and B respectively. * NOTA = LSAME(TRANSA,'N') NOTB = LSAME(TRANSB,'N') CONJA = LSAME(TRANSA,'C') CONJB = LSAME(TRANSB,'C') IF (NOTA) THEN NROWA = M ELSE NROWA = K END IF IF (NOTB) THEN NROWB = K ELSE NROWB = N END IF * * Test the input parameters. * INFO = 0 IF ((.NOT.NOTA) .AND. (.NOT.CONJA) .AND. + (.NOT.LSAME(TRANSA,'T'))) THEN INFO = 1 ELSE IF ((.NOT.NOTB) .AND. (.NOT.CONJB) .AND. + (.NOT.LSAME(TRANSB,'T'))) THEN INFO = 2 ELSE IF (M.LT.0) THEN INFO = 3 ELSE IF (N.LT.0) THEN INFO = 4 ELSE IF (K.LT.0) THEN INFO = 5 ELSE IF (LDA.LT.MAX(1,NROWA)) THEN INFO = 8 ELSE IF (LDB.LT.MAX(1,NROWB)) THEN INFO = 10 ELSE IF (LDC.LT.MAX(1,M)) THEN INFO = 13 END IF IF (INFO.NE.0) THEN CALL XERBLA('CGEMM ',INFO) RETURN END IF * * Quick return if possible. * IF ((M.EQ.0) .OR. (N.EQ.0) .OR. + (((ALPHA.EQ.ZERO).OR. (K.EQ.0)).AND. (BETA.EQ.ONE))) RETURN * * And when alpha.eq.zero. * IF (ALPHA.EQ.ZERO) THEN IF (BETA.EQ.ZERO) THEN DO 20 J = 1,N DO 10 I = 1,M C(I,J) = ZERO 10 CONTINUE 20 CONTINUE ELSE DO 40 J = 1,N DO 30 I = 1,M C(I,J) = BETA*C(I,J) 30 CONTINUE 40 CONTINUE END IF RETURN END IF * * Start the operations. * IF (NOTB) THEN IF (NOTA) THEN * * Form C := alpha*A*B + beta*C. * DO 90 J = 1,N IF (BETA.EQ.ZERO) THEN DO 50 I = 1,M C(I,J) = ZERO 50 CONTINUE ELSE IF (BETA.NE.ONE) THEN DO 60 I = 1,M C(I,J) = BETA*C(I,J) 60 CONTINUE END IF DO 80 L = 1,K TEMP = ALPHA*B(L,J) DO 70 I = 1,M C(I,J) = C(I,J) + TEMP*A(I,L) 70 CONTINUE 80 CONTINUE 90 CONTINUE ELSE IF (CONJA) THEN * * Form C := alpha*A**H*B + beta*C. * DO 120 J = 1,N DO 110 I = 1,M TEMP = ZERO DO 100 L = 1,K TEMP = TEMP + CONJG(A(L,I))*B(L,J) 100 CONTINUE IF (BETA.EQ.ZERO) THEN C(I,J) = ALPHA*TEMP ELSE C(I,J) = ALPHA*TEMP + BETA*C(I,J) END IF 110 CONTINUE 120 CONTINUE ELSE * * Form C := alpha*A**T*B + beta*C * DO 150 J = 1,N DO 140 I = 1,M TEMP = ZERO DO 130 L = 1,K TEMP = TEMP + A(L,I)*B(L,J) 130 CONTINUE IF (BETA.EQ.ZERO) THEN C(I,J) = ALPHA*TEMP ELSE C(I,J) = ALPHA*TEMP + BETA*C(I,J) END IF 140 CONTINUE 150 CONTINUE END IF ELSE IF (NOTA) THEN IF (CONJB) THEN * * Form C := alpha*A*B**H + beta*C. * DO 200 J = 1,N IF (BETA.EQ.ZERO) THEN DO 160 I = 1,M C(I,J) = ZERO 160 CONTINUE ELSE IF (BETA.NE.ONE) THEN DO 170 I = 1,M C(I,J) = BETA*C(I,J) 170 CONTINUE END IF DO 190 L = 1,K TEMP = ALPHA*CONJG(B(J,L)) DO 180 I = 1,M C(I,J) = C(I,J) + TEMP*A(I,L) 180 CONTINUE 190 CONTINUE 200 CONTINUE ELSE * * Form C := alpha*A*B**T + beta*C * DO 250 J = 1,N IF (BETA.EQ.ZERO) THEN DO 210 I = 1,M C(I,J) = ZERO 210 CONTINUE ELSE IF (BETA.NE.ONE) THEN DO 220 I = 1,M C(I,J) = BETA*C(I,J) 220 CONTINUE END IF DO 240 L = 1,K TEMP = ALPHA*B(J,L) DO 230 I = 1,M C(I,J) = C(I,J) + TEMP*A(I,L) 230 CONTINUE 240 CONTINUE 250 CONTINUE END IF ELSE IF (CONJA) THEN IF (CONJB) THEN * * Form C := alpha*A**H*B**H + beta*C. * DO 280 J = 1,N DO 270 I = 1,M TEMP = ZERO DO 260 L = 1,K TEMP = TEMP + CONJG(A(L,I))*CONJG(B(J,L)) 260 CONTINUE IF (BETA.EQ.ZERO) THEN C(I,J) = ALPHA*TEMP ELSE C(I,J) = ALPHA*TEMP + BETA*C(I,J) END IF 270 CONTINUE 280 CONTINUE ELSE * * Form C := alpha*A**H*B**T + beta*C * DO 310 J = 1,N DO 300 I = 1,M TEMP = ZERO DO 290 L = 1,K TEMP = TEMP + CONJG(A(L,I))*B(J,L) 290 CONTINUE IF (BETA.EQ.ZERO) THEN C(I,J) = ALPHA*TEMP ELSE C(I,J) = ALPHA*TEMP + BETA*C(I,J) END IF 300 CONTINUE 310 CONTINUE END IF ELSE IF (CONJB) THEN * * Form C := alpha*A**T*B**H + beta*C * DO 340 J = 1,N DO 330 I = 1,M TEMP = ZERO DO 320 L = 1,K TEMP = TEMP + A(L,I)*CONJG(B(J,L)) 320 CONTINUE IF (BETA.EQ.ZERO) THEN C(I,J) = ALPHA*TEMP ELSE C(I,J) = ALPHA*TEMP + BETA*C(I,J) END IF 330 CONTINUE 340 CONTINUE ELSE * * Form C := alpha*A**T*B**T + beta*C * DO 370 J = 1,N DO 360 I = 1,M TEMP = ZERO DO 350 L = 1,K TEMP = TEMP + A(L,I)*B(J,L) 350 CONTINUE IF (BETA.EQ.ZERO) THEN C(I,J) = ALPHA*TEMP ELSE C(I,J) = ALPHA*TEMP + BETA*C(I,J) END IF 360 CONTINUE 370 CONTINUE END IF END IF * RETURN * * End of CGEMM * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/cgemv.f
*> \brief \b CGEMV * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CGEMV(TRANS,M,N,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) * * .. Scalar Arguments .. * COMPLEX ALPHA,BETA * INTEGER INCX,INCY,LDA,M,N * CHARACTER TRANS * .. * .. Array Arguments .. * COMPLEX A(LDA,*),X(*),Y(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CGEMV performs one of the matrix-vector operations *> *> y := alpha*A*x + beta*y, or y := alpha*A**T*x + beta*y, or *> *> y := alpha*A**H*x + beta*y, *> *> where alpha and beta are scalars, x and y are vectors and A is an *> m by n matrix. *> \endverbatim * * Arguments: * ========== * *> \param[in] TRANS *> \verbatim *> TRANS is CHARACTER*1 *> On entry, TRANS specifies the operation to be performed as *> follows: *> *> TRANS = 'N' or 'n' y := alpha*A*x + beta*y. *> *> TRANS = 'T' or 't' y := alpha*A**T*x + beta*y. *> *> TRANS = 'C' or 'c' y := alpha*A**H*x + beta*y. *> \endverbatim *> *> \param[in] M *> \verbatim *> M is INTEGER *> On entry, M specifies the number of rows of the matrix A. *> M must be at least zero. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the number of columns of the matrix A. *> N must be at least zero. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is COMPLEX *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] A *> \verbatim *> A is COMPLEX array, dimension ( LDA, N ) *> Before entry, the leading m by n part of the array A must *> contain the matrix of coefficients. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> On entry, LDA specifies the first dimension of A as declared *> in the calling (sub) program. LDA must be at least *> max( 1, m ). *> \endverbatim *> *> \param[in] X *> \verbatim *> X is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n' *> and at least *> ( 1 + ( m - 1 )*abs( INCX ) ) otherwise. *> Before entry, the incremented array X must contain the *> vector x. *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> On entry, INCX specifies the increment for the elements of *> X. INCX must not be zero. *> \endverbatim *> *> \param[in] BETA *> \verbatim *> BETA is COMPLEX *> On entry, BETA specifies the scalar beta. When BETA is *> supplied as zero then Y need not be set on input. *> \endverbatim *> *> \param[in,out] Y *> \verbatim *> Y is COMPLEX array, dimension at least *> ( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n' *> and at least *> ( 1 + ( n - 1 )*abs( INCY ) ) otherwise. *> Before entry with BETA non-zero, the incremented array Y *> must contain the vector y. On exit, Y is overwritten by the *> updated vector y. *> If either m or n is zero, then Y not referenced and the function *> performs a quick return. *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> On entry, INCY specifies the increment for the elements of *> Y. INCY must not be zero. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup gemv * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 2 Blas routine. *> The vector and matrix arguments are not referenced when N = 0, or M = 0 *> *> -- Written on 22-October-1986. *> Jack Dongarra, Argonne National Lab. *> Jeremy Du Croz, Nag Central Office. *> Sven Hammarling, Nag Central Office. *> Richard Hanson, Sandia National Labs. *> \endverbatim *> * ===================================================================== SUBROUTINE CGEMV(TRANS,M,N,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) * * -- Reference BLAS level2 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX ALPHA,BETA INTEGER INCX,INCY,LDA,M,N CHARACTER TRANS * .. * .. Array Arguments .. COMPLEX A(LDA,*),X(*),Y(*) * .. * * ===================================================================== * * .. Parameters .. COMPLEX ONE PARAMETER (ONE= (1.0E+0,0.0E+0)) COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * .. Local Scalars .. COMPLEX TEMP INTEGER I,INFO,IX,IY,J,JX,JY,KX,KY,LENX,LENY LOGICAL NOCONJ * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CONJG,MAX * .. * * Test the input parameters. * INFO = 0 IF (.NOT.LSAME(TRANS,'N') .AND. .NOT.LSAME(TRANS,'T') .AND. + .NOT.LSAME(TRANS,'C')) THEN INFO = 1 ELSE IF (M.LT.0) THEN INFO = 2 ELSE IF (N.LT.0) THEN INFO = 3 ELSE IF (LDA.LT.MAX(1,M)) THEN INFO = 6 ELSE IF (INCX.EQ.0) THEN INFO = 8 ELSE IF (INCY.EQ.0) THEN INFO = 11 END IF IF (INFO.NE.0) THEN CALL XERBLA('CGEMV ',INFO) RETURN END IF * * Quick return if possible. * IF ((M.EQ.0) .OR. (N.EQ.0) .OR. + ((ALPHA.EQ.ZERO).AND. (BETA.EQ.ONE))) RETURN * NOCONJ = LSAME(TRANS,'T') * * Set LENX and LENY, the lengths of the vectors x and y, and set * up the start points in X and Y. * IF (LSAME(TRANS,'N')) THEN LENX = N LENY = M ELSE LENX = M LENY = N END IF IF (INCX.GT.0) THEN KX = 1 ELSE KX = 1 - (LENX-1)*INCX END IF IF (INCY.GT.0) THEN KY = 1 ELSE KY = 1 - (LENY-1)*INCY END IF * * Start the operations. In this version the elements of A are * accessed sequentially with one pass through A. * * First form y := beta*y. * IF (BETA.NE.ONE) THEN IF (INCY.EQ.1) THEN IF (BETA.EQ.ZERO) THEN DO 10 I = 1,LENY Y(I) = ZERO 10 CONTINUE ELSE DO 20 I = 1,LENY Y(I) = BETA*Y(I) 20 CONTINUE END IF ELSE IY = KY IF (BETA.EQ.ZERO) THEN DO 30 I = 1,LENY Y(IY) = ZERO IY = IY + INCY 30 CONTINUE ELSE DO 40 I = 1,LENY Y(IY) = BETA*Y(IY) IY = IY + INCY 40 CONTINUE END IF END IF END IF IF (ALPHA.EQ.ZERO) RETURN IF (LSAME(TRANS,'N')) THEN * * Form y := alpha*A*x + y. * JX = KX IF (INCY.EQ.1) THEN DO 60 J = 1,N TEMP = ALPHA*X(JX) DO 50 I = 1,M Y(I) = Y(I) + TEMP*A(I,J) 50 CONTINUE JX = JX + INCX 60 CONTINUE ELSE DO 80 J = 1,N TEMP = ALPHA*X(JX) IY = KY DO 70 I = 1,M Y(IY) = Y(IY) + TEMP*A(I,J) IY = IY + INCY 70 CONTINUE JX = JX + INCX 80 CONTINUE END IF ELSE * * Form y := alpha*A**T*x + y or y := alpha*A**H*x + y. * JY = KY IF (INCX.EQ.1) THEN DO 110 J = 1,N TEMP = ZERO IF (NOCONJ) THEN DO 90 I = 1,M TEMP = TEMP + A(I,J)*X(I) 90 CONTINUE ELSE DO 100 I = 1,M TEMP = TEMP + CONJG(A(I,J))*X(I) 100 CONTINUE END IF Y(JY) = Y(JY) + ALPHA*TEMP JY = JY + INCY 110 CONTINUE ELSE DO 140 J = 1,N TEMP = ZERO IX = KX IF (NOCONJ) THEN DO 120 I = 1,M TEMP = TEMP + A(I,J)*X(IX) IX = IX + INCX 120 CONTINUE ELSE DO 130 I = 1,M TEMP = TEMP + CONJG(A(I,J))*X(IX) IX = IX + INCX 130 CONTINUE END IF Y(JY) = Y(JY) + ALPHA*TEMP JY = JY + INCY 140 CONTINUE END IF END IF * RETURN * * End of CGEMV * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/cgerc.f
*> \brief \b CGERC * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CGERC(M,N,ALPHA,X,INCX,Y,INCY,A,LDA) * * .. Scalar Arguments .. * COMPLEX ALPHA * INTEGER INCX,INCY,LDA,M,N * .. * .. Array Arguments .. * COMPLEX A(LDA,*),X(*),Y(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CGERC performs the rank 1 operation *> *> A := alpha*x*y**H + A, *> *> where alpha is a scalar, x is an m element vector, y is an n element *> vector and A is an m by n matrix. *> \endverbatim * * Arguments: * ========== * *> \param[in] M *> \verbatim *> M is INTEGER *> On entry, M specifies the number of rows of the matrix A. *> M must be at least zero. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the number of columns of the matrix A. *> N must be at least zero. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is COMPLEX *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] X *> \verbatim *> X is COMPLEX array, dimension at least *> ( 1 + ( m - 1 )*abs( INCX ) ). *> Before entry, the incremented array X must contain the m *> element vector x. *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> On entry, INCX specifies the increment for the elements of *> X. INCX must not be zero. *> \endverbatim *> *> \param[in] Y *> \verbatim *> Y is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCY ) ). *> Before entry, the incremented array Y must contain the n *> element vector y. *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> On entry, INCY specifies the increment for the elements of *> Y. INCY must not be zero. *> \endverbatim *> *> \param[in,out] A *> \verbatim *> A is COMPLEX array, dimension ( LDA, N ) *> Before entry, the leading m by n part of the array A must *> contain the matrix of coefficients. On exit, A is *> overwritten by the updated matrix. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> On entry, LDA specifies the first dimension of A as declared *> in the calling (sub) program. LDA must be at least *> max( 1, m ). *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup ger * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 2 Blas routine. *> *> -- Written on 22-October-1986. *> Jack Dongarra, Argonne National Lab. *> Jeremy Du Croz, Nag Central Office. *> Sven Hammarling, Nag Central Office. *> Richard Hanson, Sandia National Labs. *> \endverbatim *> * ===================================================================== SUBROUTINE CGERC(M,N,ALPHA,X,INCX,Y,INCY,A,LDA) * * -- Reference BLAS level2 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX ALPHA INTEGER INCX,INCY,LDA,M,N * .. * .. Array Arguments .. COMPLEX A(LDA,*),X(*),Y(*) * .. * * ===================================================================== * * .. Parameters .. COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * .. Local Scalars .. COMPLEX TEMP INTEGER I,INFO,IX,J,JY,KX * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CONJG,MAX * .. * * Test the input parameters. * INFO = 0 IF (M.LT.0) THEN INFO = 1 ELSE IF (N.LT.0) THEN INFO = 2 ELSE IF (INCX.EQ.0) THEN INFO = 5 ELSE IF (INCY.EQ.0) THEN INFO = 7 ELSE IF (LDA.LT.MAX(1,M)) THEN INFO = 9 END IF IF (INFO.NE.0) THEN CALL XERBLA('CGERC ',INFO) RETURN END IF * * Quick return if possible. * IF ((M.EQ.0) .OR. (N.EQ.0) .OR. (ALPHA.EQ.ZERO)) RETURN * * Start the operations. In this version the elements of A are * accessed sequentially with one pass through A. * IF (INCY.GT.0) THEN JY = 1 ELSE JY = 1 - (N-1)*INCY END IF IF (INCX.EQ.1) THEN DO 20 J = 1,N IF (Y(JY).NE.ZERO) THEN TEMP = ALPHA*CONJG(Y(JY)) DO 10 I = 1,M A(I,J) = A(I,J) + X(I)*TEMP 10 CONTINUE END IF JY = JY + INCY 20 CONTINUE ELSE IF (INCX.GT.0) THEN KX = 1 ELSE KX = 1 - (M-1)*INCX END IF DO 40 J = 1,N IF (Y(JY).NE.ZERO) THEN TEMP = ALPHA*CONJG(Y(JY)) IX = KX DO 30 I = 1,M A(I,J) = A(I,J) + X(IX)*TEMP IX = IX + INCX 30 CONTINUE END IF JY = JY + INCY 40 CONTINUE END IF * RETURN * * End of CGERC * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/cgeru.f
*> \brief \b CGERU * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CGERU(M,N,ALPHA,X,INCX,Y,INCY,A,LDA) * * .. Scalar Arguments .. * COMPLEX ALPHA * INTEGER INCX,INCY,LDA,M,N * .. * .. Array Arguments .. * COMPLEX A(LDA,*),X(*),Y(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CGERU performs the rank 1 operation *> *> A := alpha*x*y**T + A, *> *> where alpha is a scalar, x is an m element vector, y is an n element *> vector and A is an m by n matrix. *> \endverbatim * * Arguments: * ========== * *> \param[in] M *> \verbatim *> M is INTEGER *> On entry, M specifies the number of rows of the matrix A. *> M must be at least zero. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the number of columns of the matrix A. *> N must be at least zero. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is COMPLEX *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] X *> \verbatim *> X is COMPLEX array, dimension at least *> ( 1 + ( m - 1 )*abs( INCX ) ). *> Before entry, the incremented array X must contain the m *> element vector x. *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> On entry, INCX specifies the increment for the elements of *> X. INCX must not be zero. *> \endverbatim *> *> \param[in] Y *> \verbatim *> Y is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCY ) ). *> Before entry, the incremented array Y must contain the n *> element vector y. *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> On entry, INCY specifies the increment for the elements of *> Y. INCY must not be zero. *> \endverbatim *> *> \param[in,out] A *> \verbatim *> A is COMPLEX array, dimension ( LDA, N ) *> Before entry, the leading m by n part of the array A must *> contain the matrix of coefficients. On exit, A is *> overwritten by the updated matrix. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> On entry, LDA specifies the first dimension of A as declared *> in the calling (sub) program. LDA must be at least *> max( 1, m ). *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup ger * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 2 Blas routine. *> *> -- Written on 22-October-1986. *> Jack Dongarra, Argonne National Lab. *> Jeremy Du Croz, Nag Central Office. *> Sven Hammarling, Nag Central Office. *> Richard Hanson, Sandia National Labs. *> \endverbatim *> * ===================================================================== SUBROUTINE CGERU(M,N,ALPHA,X,INCX,Y,INCY,A,LDA) * * -- Reference BLAS level2 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX ALPHA INTEGER INCX,INCY,LDA,M,N * .. * .. Array Arguments .. COMPLEX A(LDA,*),X(*),Y(*) * .. * * ===================================================================== * * .. Parameters .. COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * .. Local Scalars .. COMPLEX TEMP INTEGER I,INFO,IX,J,JY,KX * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC MAX * .. * * Test the input parameters. * INFO = 0 IF (M.LT.0) THEN INFO = 1 ELSE IF (N.LT.0) THEN INFO = 2 ELSE IF (INCX.EQ.0) THEN INFO = 5 ELSE IF (INCY.EQ.0) THEN INFO = 7 ELSE IF (LDA.LT.MAX(1,M)) THEN INFO = 9 END IF IF (INFO.NE.0) THEN CALL XERBLA('CGERU ',INFO) RETURN END IF * * Quick return if possible. * IF ((M.EQ.0) .OR. (N.EQ.0) .OR. (ALPHA.EQ.ZERO)) RETURN * * Start the operations. In this version the elements of A are * accessed sequentially with one pass through A. * IF (INCY.GT.0) THEN JY = 1 ELSE JY = 1 - (N-1)*INCY END IF IF (INCX.EQ.1) THEN DO 20 J = 1,N IF (Y(JY).NE.ZERO) THEN TEMP = ALPHA*Y(JY) DO 10 I = 1,M A(I,J) = A(I,J) + X(I)*TEMP 10 CONTINUE END IF JY = JY + INCY 20 CONTINUE ELSE IF (INCX.GT.0) THEN KX = 1 ELSE KX = 1 - (M-1)*INCX END IF DO 40 J = 1,N IF (Y(JY).NE.ZERO) THEN TEMP = ALPHA*Y(JY) IX = KX DO 30 I = 1,M A(I,J) = A(I,J) + X(IX)*TEMP IX = IX + INCX 30 CONTINUE END IF JY = JY + INCY 40 CONTINUE END IF * RETURN * * End of CGERU * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/chbmv.f
*> \brief \b CHBMV * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CHBMV(UPLO,N,K,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) * * .. Scalar Arguments .. * COMPLEX ALPHA,BETA * INTEGER INCX,INCY,K,LDA,N * CHARACTER UPLO * .. * .. Array Arguments .. * COMPLEX A(LDA,*),X(*),Y(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CHBMV performs the matrix-vector operation *> *> y := alpha*A*x + beta*y, *> *> where alpha and beta are scalars, x and y are n element vectors and *> A is an n by n hermitian band matrix, with k super-diagonals. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> On entry, UPLO specifies whether the upper or lower *> triangular part of the band matrix A is being supplied as *> follows: *> *> UPLO = 'U' or 'u' The upper triangular part of A is *> being supplied. *> *> UPLO = 'L' or 'l' The lower triangular part of A is *> being supplied. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the order of the matrix A. *> N must be at least zero. *> \endverbatim *> *> \param[in] K *> \verbatim *> K is INTEGER *> On entry, K specifies the number of super-diagonals of the *> matrix A. K must satisfy 0 .le. K. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is COMPLEX *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] A *> \verbatim *> A is COMPLEX array, dimension ( LDA, N ) *> Before entry with UPLO = 'U' or 'u', the leading ( k + 1 ) *> by n part of the array A must contain the upper triangular *> band part of the hermitian matrix, supplied column by *> column, with the leading diagonal of the matrix in row *> ( k + 1 ) of the array, the first super-diagonal starting at *> position 2 in row k, and so on. The top left k by k triangle *> of the array A is not referenced. *> The following program segment will transfer the upper *> triangular part of a hermitian band matrix from conventional *> full matrix storage to band storage: *> *> DO 20, J = 1, N *> M = K + 1 - J *> DO 10, I = MAX( 1, J - K ), J *> A( M + I, J ) = matrix( I, J ) *> 10 CONTINUE *> 20 CONTINUE *> *> Before entry with UPLO = 'L' or 'l', the leading ( k + 1 ) *> by n part of the array A must contain the lower triangular *> band part of the hermitian matrix, supplied column by *> column, with the leading diagonal of the matrix in row 1 of *> the array, the first sub-diagonal starting at position 1 in *> row 2, and so on. The bottom right k by k triangle of the *> array A is not referenced. *> The following program segment will transfer the lower *> triangular part of a hermitian band matrix from conventional *> full matrix storage to band storage: *> *> DO 20, J = 1, N *> M = 1 - J *> DO 10, I = J, MIN( N, J + K ) *> A( M + I, J ) = matrix( I, J ) *> 10 CONTINUE *> 20 CONTINUE *> *> Note that the imaginary parts of the diagonal elements need *> not be set and are assumed to be zero. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> On entry, LDA specifies the first dimension of A as declared *> in the calling (sub) program. LDA must be at least *> ( k + 1 ). *> \endverbatim *> *> \param[in] X *> \verbatim *> X is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCX ) ). *> Before entry, the incremented array X must contain the *> vector x. *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> On entry, INCX specifies the increment for the elements of *> X. INCX must not be zero. *> \endverbatim *> *> \param[in] BETA *> \verbatim *> BETA is COMPLEX *> On entry, BETA specifies the scalar beta. *> \endverbatim *> *> \param[in,out] Y *> \verbatim *> Y is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCY ) ). *> Before entry, the incremented array Y must contain the *> vector y. On exit, Y is overwritten by the updated vector y. *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> On entry, INCY specifies the increment for the elements of *> Y. INCY must not be zero. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup hbmv * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 2 Blas routine. *> The vector and matrix arguments are not referenced when N = 0, or M = 0 *> *> -- Written on 22-October-1986. *> Jack Dongarra, Argonne National Lab. *> Jeremy Du Croz, Nag Central Office. *> Sven Hammarling, Nag Central Office. *> Richard Hanson, Sandia National Labs. *> \endverbatim *> * ===================================================================== SUBROUTINE CHBMV(UPLO,N,K,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) * * -- Reference BLAS level2 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX ALPHA,BETA INTEGER INCX,INCY,K,LDA,N CHARACTER UPLO * .. * .. Array Arguments .. COMPLEX A(LDA,*),X(*),Y(*) * .. * * ===================================================================== * * .. Parameters .. COMPLEX ONE PARAMETER (ONE= (1.0E+0,0.0E+0)) COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * .. Local Scalars .. COMPLEX TEMP1,TEMP2 INTEGER I,INFO,IX,IY,J,JX,JY,KPLUS1,KX,KY,L * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CONJG,MAX,MIN,REAL * .. * * Test the input parameters. * INFO = 0 IF (.NOT.LSAME(UPLO,'U') .AND. .NOT.LSAME(UPLO,'L')) THEN INFO = 1 ELSE IF (N.LT.0) THEN INFO = 2 ELSE IF (K.LT.0) THEN INFO = 3 ELSE IF (LDA.LT. (K+1)) THEN INFO = 6 ELSE IF (INCX.EQ.0) THEN INFO = 8 ELSE IF (INCY.EQ.0) THEN INFO = 11 END IF IF (INFO.NE.0) THEN CALL XERBLA('CHBMV ',INFO) RETURN END IF * * Quick return if possible. * IF ((N.EQ.0) .OR. ((ALPHA.EQ.ZERO).AND. (BETA.EQ.ONE))) RETURN * * Set up the start points in X and Y. * IF (INCX.GT.0) THEN KX = 1 ELSE KX = 1 - (N-1)*INCX END IF IF (INCY.GT.0) THEN KY = 1 ELSE KY = 1 - (N-1)*INCY END IF * * Start the operations. In this version the elements of the array A * are accessed sequentially with one pass through A. * * First form y := beta*y. * IF (BETA.NE.ONE) THEN IF (INCY.EQ.1) THEN IF (BETA.EQ.ZERO) THEN DO 10 I = 1,N Y(I) = ZERO 10 CONTINUE ELSE DO 20 I = 1,N Y(I) = BETA*Y(I) 20 CONTINUE END IF ELSE IY = KY IF (BETA.EQ.ZERO) THEN DO 30 I = 1,N Y(IY) = ZERO IY = IY + INCY 30 CONTINUE ELSE DO 40 I = 1,N Y(IY) = BETA*Y(IY) IY = IY + INCY 40 CONTINUE END IF END IF END IF IF (ALPHA.EQ.ZERO) RETURN IF (LSAME(UPLO,'U')) THEN * * Form y when upper triangle of A is stored. * KPLUS1 = K + 1 IF ((INCX.EQ.1) .AND. (INCY.EQ.1)) THEN DO 60 J = 1,N TEMP1 = ALPHA*X(J) TEMP2 = ZERO L = KPLUS1 - J DO 50 I = MAX(1,J-K),J - 1 Y(I) = Y(I) + TEMP1*A(L+I,J) TEMP2 = TEMP2 + CONJG(A(L+I,J))*X(I) 50 CONTINUE Y(J) = Y(J) + TEMP1*REAL(A(KPLUS1,J)) + ALPHA*TEMP2 60 CONTINUE ELSE JX = KX JY = KY DO 80 J = 1,N TEMP1 = ALPHA*X(JX) TEMP2 = ZERO IX = KX IY = KY L = KPLUS1 - J DO 70 I = MAX(1,J-K),J - 1 Y(IY) = Y(IY) + TEMP1*A(L+I,J) TEMP2 = TEMP2 + CONJG(A(L+I,J))*X(IX) IX = IX + INCX IY = IY + INCY 70 CONTINUE Y(JY) = Y(JY) + TEMP1*REAL(A(KPLUS1,J)) + ALPHA*TEMP2 JX = JX + INCX JY = JY + INCY IF (J.GT.K) THEN KX = KX + INCX KY = KY + INCY END IF 80 CONTINUE END IF ELSE * * Form y when lower triangle of A is stored. * IF ((INCX.EQ.1) .AND. (INCY.EQ.1)) THEN DO 100 J = 1,N TEMP1 = ALPHA*X(J) TEMP2 = ZERO Y(J) = Y(J) + TEMP1*REAL(A(1,J)) L = 1 - J DO 90 I = J + 1,MIN(N,J+K) Y(I) = Y(I) + TEMP1*A(L+I,J) TEMP2 = TEMP2 + CONJG(A(L+I,J))*X(I) 90 CONTINUE Y(J) = Y(J) + ALPHA*TEMP2 100 CONTINUE ELSE JX = KX JY = KY DO 120 J = 1,N TEMP1 = ALPHA*X(JX) TEMP2 = ZERO Y(JY) = Y(JY) + TEMP1*REAL(A(1,J)) L = 1 - J IX = JX IY = JY DO 110 I = J + 1,MIN(N,J+K) IX = IX + INCX IY = IY + INCY Y(IY) = Y(IY) + TEMP1*A(L+I,J) TEMP2 = TEMP2 + CONJG(A(L+I,J))*X(IX) 110 CONTINUE Y(JY) = Y(JY) + ALPHA*TEMP2 JX = JX + INCX JY = JY + INCY 120 CONTINUE END IF END IF * RETURN * * End of CHBMV * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/chemm.f
*> \brief \b CHEMM * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CHEMM(SIDE,UPLO,M,N,ALPHA,A,LDA,B,LDB,BETA,C,LDC) * * .. Scalar Arguments .. * COMPLEX ALPHA,BETA * INTEGER LDA,LDB,LDC,M,N * CHARACTER SIDE,UPLO * .. * .. Array Arguments .. * COMPLEX A(LDA,*),B(LDB,*),C(LDC,*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CHEMM performs one of the matrix-matrix operations *> *> C := alpha*A*B + beta*C, *> *> or *> *> C := alpha*B*A + beta*C, *> *> where alpha and beta are scalars, A is an hermitian matrix and B and *> C are m by n matrices. *> \endverbatim * * Arguments: * ========== * *> \param[in] SIDE *> \verbatim *> SIDE is CHARACTER*1 *> On entry, SIDE specifies whether the hermitian matrix A *> appears on the left or right in the operation as follows: *> *> SIDE = 'L' or 'l' C := alpha*A*B + beta*C, *> *> SIDE = 'R' or 'r' C := alpha*B*A + beta*C, *> \endverbatim *> *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> On entry, UPLO specifies whether the upper or lower *> triangular part of the hermitian matrix A is to be *> referenced as follows: *> *> UPLO = 'U' or 'u' Only the upper triangular part of the *> hermitian matrix is to be referenced. *> *> UPLO = 'L' or 'l' Only the lower triangular part of the *> hermitian matrix is to be referenced. *> \endverbatim *> *> \param[in] M *> \verbatim *> M is INTEGER *> On entry, M specifies the number of rows of the matrix C. *> M must be at least zero. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the number of columns of the matrix C. *> N must be at least zero. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is COMPLEX *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] A *> \verbatim *> A is COMPLEX array, dimension ( LDA, ka ), where ka is *> m when SIDE = 'L' or 'l' and is n otherwise. *> Before entry with SIDE = 'L' or 'l', the m by m part of *> the array A must contain the hermitian matrix, such that *> when UPLO = 'U' or 'u', the leading m by m upper triangular *> part of the array A must contain the upper triangular part *> of the hermitian matrix and the strictly lower triangular *> part of A is not referenced, and when UPLO = 'L' or 'l', *> the leading m by m lower triangular part of the array A *> must contain the lower triangular part of the hermitian *> matrix and the strictly upper triangular part of A is not *> referenced. *> Before entry with SIDE = 'R' or 'r', the n by n part of *> the array A must contain the hermitian matrix, such that *> when UPLO = 'U' or 'u', the leading n by n upper triangular *> part of the array A must contain the upper triangular part *> of the hermitian matrix and the strictly lower triangular *> part of A is not referenced, and when UPLO = 'L' or 'l', *> the leading n by n lower triangular part of the array A *> must contain the lower triangular part of the hermitian *> matrix and the strictly upper triangular part of A is not *> referenced. *> Note that the imaginary parts of the diagonal elements need *> not be set, they are assumed to be zero. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> On entry, LDA specifies the first dimension of A as declared *> in the calling (sub) program. When SIDE = 'L' or 'l' then *> LDA must be at least max( 1, m ), otherwise LDA must be at *> least max( 1, n ). *> \endverbatim *> *> \param[in] B *> \verbatim *> B is COMPLEX array, dimension ( LDB, N ) *> Before entry, the leading m by n part of the array B must *> contain the matrix B. *> \endverbatim *> *> \param[in] LDB *> \verbatim *> LDB is INTEGER *> On entry, LDB specifies the first dimension of B as declared *> in the calling (sub) program. LDB must be at least *> max( 1, m ). *> \endverbatim *> *> \param[in] BETA *> \verbatim *> BETA is COMPLEX *> On entry, BETA specifies the scalar beta. When BETA is *> supplied as zero then C need not be set on input. *> \endverbatim *> *> \param[in,out] C *> \verbatim *> C is COMPLEX array, dimension ( LDC, N ) *> Before entry, the leading m by n part of the array C must *> contain the matrix C, except when beta is zero, in which *> case C need not be set on entry. *> On exit, the array C is overwritten by the m by n updated *> matrix. *> \endverbatim *> *> \param[in] LDC *> \verbatim *> LDC is INTEGER *> On entry, LDC specifies the first dimension of C as declared *> in the calling (sub) program. LDC must be at least *> max( 1, m ). *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup hemm * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 3 Blas routine. *> *> -- Written on 8-February-1989. *> Jack Dongarra, Argonne National Laboratory. *> Iain Duff, AERE Harwell. *> Jeremy Du Croz, Numerical Algorithms Group Ltd. *> Sven Hammarling, Numerical Algorithms Group Ltd. *> \endverbatim *> * ===================================================================== SUBROUTINE CHEMM(SIDE,UPLO,M,N,ALPHA,A,LDA,B,LDB,BETA,C,LDC) * * -- Reference BLAS level3 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX ALPHA,BETA INTEGER LDA,LDB,LDC,M,N CHARACTER SIDE,UPLO * .. * .. Array Arguments .. COMPLEX A(LDA,*),B(LDB,*),C(LDC,*) * .. * * ===================================================================== * * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CONJG,MAX,REAL * .. * .. Local Scalars .. COMPLEX TEMP1,TEMP2 INTEGER I,INFO,J,K,NROWA LOGICAL UPPER * .. * .. Parameters .. COMPLEX ONE PARAMETER (ONE= (1.0E+0,0.0E+0)) COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * * Set NROWA as the number of rows of A. * IF (LSAME(SIDE,'L')) THEN NROWA = M ELSE NROWA = N END IF UPPER = LSAME(UPLO,'U') * * Test the input parameters. * INFO = 0 IF ((.NOT.LSAME(SIDE,'L')) .AND. + (.NOT.LSAME(SIDE,'R'))) THEN INFO = 1 ELSE IF ((.NOT.UPPER) .AND. + (.NOT.LSAME(UPLO,'L'))) THEN INFO = 2 ELSE IF (M.LT.0) THEN INFO = 3 ELSE IF (N.LT.0) THEN INFO = 4 ELSE IF (LDA.LT.MAX(1,NROWA)) THEN INFO = 7 ELSE IF (LDB.LT.MAX(1,M)) THEN INFO = 9 ELSE IF (LDC.LT.MAX(1,M)) THEN INFO = 12 END IF IF (INFO.NE.0) THEN CALL XERBLA('CHEMM ',INFO) RETURN END IF * * Quick return if possible. * IF ((M.EQ.0) .OR. (N.EQ.0) .OR. + ((ALPHA.EQ.ZERO).AND. (BETA.EQ.ONE))) RETURN * * And when alpha.eq.zero. * IF (ALPHA.EQ.ZERO) THEN IF (BETA.EQ.ZERO) THEN DO 20 J = 1,N DO 10 I = 1,M C(I,J) = ZERO 10 CONTINUE 20 CONTINUE ELSE DO 40 J = 1,N DO 30 I = 1,M C(I,J) = BETA*C(I,J) 30 CONTINUE 40 CONTINUE END IF RETURN END IF * * Start the operations. * IF (LSAME(SIDE,'L')) THEN * * Form C := alpha*A*B + beta*C. * IF (UPPER) THEN DO 70 J = 1,N DO 60 I = 1,M TEMP1 = ALPHA*B(I,J) TEMP2 = ZERO DO 50 K = 1,I - 1 C(K,J) = C(K,J) + TEMP1*A(K,I) TEMP2 = TEMP2 + B(K,J)*CONJG(A(K,I)) 50 CONTINUE IF (BETA.EQ.ZERO) THEN C(I,J) = TEMP1*REAL(A(I,I)) + ALPHA*TEMP2 ELSE C(I,J) = BETA*C(I,J) + TEMP1*REAL(A(I,I)) + + ALPHA*TEMP2 END IF 60 CONTINUE 70 CONTINUE ELSE DO 100 J = 1,N DO 90 I = M,1,-1 TEMP1 = ALPHA*B(I,J) TEMP2 = ZERO DO 80 K = I + 1,M C(K,J) = C(K,J) + TEMP1*A(K,I) TEMP2 = TEMP2 + B(K,J)*CONJG(A(K,I)) 80 CONTINUE IF (BETA.EQ.ZERO) THEN C(I,J) = TEMP1*REAL(A(I,I)) + ALPHA*TEMP2 ELSE C(I,J) = BETA*C(I,J) + TEMP1*REAL(A(I,I)) + + ALPHA*TEMP2 END IF 90 CONTINUE 100 CONTINUE END IF ELSE * * Form C := alpha*B*A + beta*C. * DO 170 J = 1,N TEMP1 = ALPHA*REAL(A(J,J)) IF (BETA.EQ.ZERO) THEN DO 110 I = 1,M C(I,J) = TEMP1*B(I,J) 110 CONTINUE ELSE DO 120 I = 1,M C(I,J) = BETA*C(I,J) + TEMP1*B(I,J) 120 CONTINUE END IF DO 140 K = 1,J - 1 IF (UPPER) THEN TEMP1 = ALPHA*A(K,J) ELSE TEMP1 = ALPHA*CONJG(A(J,K)) END IF DO 130 I = 1,M C(I,J) = C(I,J) + TEMP1*B(I,K) 130 CONTINUE 140 CONTINUE DO 160 K = J + 1,N IF (UPPER) THEN TEMP1 = ALPHA*CONJG(A(J,K)) ELSE TEMP1 = ALPHA*A(K,J) END IF DO 150 I = 1,M C(I,J) = C(I,J) + TEMP1*B(I,K) 150 CONTINUE 160 CONTINUE 170 CONTINUE END IF * RETURN * * End of CHEMM * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/chemv.f
*> \brief \b CHEMV * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CHEMV(UPLO,N,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) * * .. Scalar Arguments .. * COMPLEX ALPHA,BETA * INTEGER INCX,INCY,LDA,N * CHARACTER UPLO * .. * .. Array Arguments .. * COMPLEX A(LDA,*),X(*),Y(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CHEMV performs the matrix-vector operation *> *> y := alpha*A*x + beta*y, *> *> where alpha and beta are scalars, x and y are n element vectors and *> A is an n by n hermitian matrix. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> On entry, UPLO specifies whether the upper or lower *> triangular part of the array A is to be referenced as *> follows: *> *> UPLO = 'U' or 'u' Only the upper triangular part of A *> is to be referenced. *> *> UPLO = 'L' or 'l' Only the lower triangular part of A *> is to be referenced. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the order of the matrix A. *> N must be at least zero. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is COMPLEX *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] A *> \verbatim *> A is COMPLEX array, dimension ( LDA, N ) *> Before entry with UPLO = 'U' or 'u', the leading n by n *> upper triangular part of the array A must contain the upper *> triangular part of the hermitian matrix and the strictly *> lower triangular part of A is not referenced. *> Before entry with UPLO = 'L' or 'l', the leading n by n *> lower triangular part of the array A must contain the lower *> triangular part of the hermitian matrix and the strictly *> upper triangular part of A is not referenced. *> Note that the imaginary parts of the diagonal elements need *> not be set and are assumed to be zero. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> On entry, LDA specifies the first dimension of A as declared *> in the calling (sub) program. LDA must be at least *> max( 1, n ). *> \endverbatim *> *> \param[in] X *> \verbatim *> X is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCX ) ). *> Before entry, the incremented array X must contain the n *> element vector x. *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> On entry, INCX specifies the increment for the elements of *> X. INCX must not be zero. *> \endverbatim *> *> \param[in] BETA *> \verbatim *> BETA is COMPLEX *> On entry, BETA specifies the scalar beta. When BETA is *> supplied as zero then Y need not be set on input. *> \endverbatim *> *> \param[in,out] Y *> \verbatim *> Y is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCY ) ). *> Before entry, the incremented array Y must contain the n *> element vector y. On exit, Y is overwritten by the updated *> vector y. *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> On entry, INCY specifies the increment for the elements of *> Y. INCY must not be zero. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup hemv * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 2 Blas routine. *> The vector and matrix arguments are not referenced when N = 0, or M = 0 *> *> -- Written on 22-October-1986. *> Jack Dongarra, Argonne National Lab. *> Jeremy Du Croz, Nag Central Office. *> Sven Hammarling, Nag Central Office. *> Richard Hanson, Sandia National Labs. *> \endverbatim *> * ===================================================================== SUBROUTINE CHEMV(UPLO,N,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) * * -- Reference BLAS level2 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX ALPHA,BETA INTEGER INCX,INCY,LDA,N CHARACTER UPLO * .. * .. Array Arguments .. COMPLEX A(LDA,*),X(*),Y(*) * .. * * ===================================================================== * * .. Parameters .. COMPLEX ONE PARAMETER (ONE= (1.0E+0,0.0E+0)) COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * .. Local Scalars .. COMPLEX TEMP1,TEMP2 INTEGER I,INFO,IX,IY,J,JX,JY,KX,KY * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CONJG,MAX,REAL * .. * * Test the input parameters. * INFO = 0 IF (.NOT.LSAME(UPLO,'U') .AND. .NOT.LSAME(UPLO,'L')) THEN INFO = 1 ELSE IF (N.LT.0) THEN INFO = 2 ELSE IF (LDA.LT.MAX(1,N)) THEN INFO = 5 ELSE IF (INCX.EQ.0) THEN INFO = 7 ELSE IF (INCY.EQ.0) THEN INFO = 10 END IF IF (INFO.NE.0) THEN CALL XERBLA('CHEMV ',INFO) RETURN END IF * * Quick return if possible. * IF ((N.EQ.0) .OR. ((ALPHA.EQ.ZERO).AND. (BETA.EQ.ONE))) RETURN * * Set up the start points in X and Y. * IF (INCX.GT.0) THEN KX = 1 ELSE KX = 1 - (N-1)*INCX END IF IF (INCY.GT.0) THEN KY = 1 ELSE KY = 1 - (N-1)*INCY END IF * * Start the operations. In this version the elements of A are * accessed sequentially with one pass through the triangular part * of A. * * First form y := beta*y. * IF (BETA.NE.ONE) THEN IF (INCY.EQ.1) THEN IF (BETA.EQ.ZERO) THEN DO 10 I = 1,N Y(I) = ZERO 10 CONTINUE ELSE DO 20 I = 1,N Y(I) = BETA*Y(I) 20 CONTINUE END IF ELSE IY = KY IF (BETA.EQ.ZERO) THEN DO 30 I = 1,N Y(IY) = ZERO IY = IY + INCY 30 CONTINUE ELSE DO 40 I = 1,N Y(IY) = BETA*Y(IY) IY = IY + INCY 40 CONTINUE END IF END IF END IF IF (ALPHA.EQ.ZERO) RETURN IF (LSAME(UPLO,'U')) THEN * * Form y when A is stored in upper triangle. * IF ((INCX.EQ.1) .AND. (INCY.EQ.1)) THEN DO 60 J = 1,N TEMP1 = ALPHA*X(J) TEMP2 = ZERO DO 50 I = 1,J - 1 Y(I) = Y(I) + TEMP1*A(I,J) TEMP2 = TEMP2 + CONJG(A(I,J))*X(I) 50 CONTINUE Y(J) = Y(J) + TEMP1*REAL(A(J,J)) + ALPHA*TEMP2 60 CONTINUE ELSE JX = KX JY = KY DO 80 J = 1,N TEMP1 = ALPHA*X(JX) TEMP2 = ZERO IX = KX IY = KY DO 70 I = 1,J - 1 Y(IY) = Y(IY) + TEMP1*A(I,J) TEMP2 = TEMP2 + CONJG(A(I,J))*X(IX) IX = IX + INCX IY = IY + INCY 70 CONTINUE Y(JY) = Y(JY) + TEMP1*REAL(A(J,J)) + ALPHA*TEMP2 JX = JX + INCX JY = JY + INCY 80 CONTINUE END IF ELSE * * Form y when A is stored in lower triangle. * IF ((INCX.EQ.1) .AND. (INCY.EQ.1)) THEN DO 100 J = 1,N TEMP1 = ALPHA*X(J) TEMP2 = ZERO Y(J) = Y(J) + TEMP1*REAL(A(J,J)) DO 90 I = J + 1,N Y(I) = Y(I) + TEMP1*A(I,J) TEMP2 = TEMP2 + CONJG(A(I,J))*X(I) 90 CONTINUE Y(J) = Y(J) + ALPHA*TEMP2 100 CONTINUE ELSE JX = KX JY = KY DO 120 J = 1,N TEMP1 = ALPHA*X(JX) TEMP2 = ZERO Y(JY) = Y(JY) + TEMP1*REAL(A(J,J)) IX = JX IY = JY DO 110 I = J + 1,N IX = IX + INCX IY = IY + INCY Y(IY) = Y(IY) + TEMP1*A(I,J) TEMP2 = TEMP2 + CONJG(A(I,J))*X(IX) 110 CONTINUE Y(JY) = Y(JY) + ALPHA*TEMP2 JX = JX + INCX JY = JY + INCY 120 CONTINUE END IF END IF * RETURN * * End of CHEMV * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/cher.f
*> \brief \b CHER * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CHER(UPLO,N,ALPHA,X,INCX,A,LDA) * * .. Scalar Arguments .. * REAL ALPHA * INTEGER INCX,LDA,N * CHARACTER UPLO * .. * .. Array Arguments .. * COMPLEX A(LDA,*),X(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CHER performs the hermitian rank 1 operation *> *> A := alpha*x*x**H + A, *> *> where alpha is a real scalar, x is an n element vector and A is an *> n by n hermitian matrix. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> On entry, UPLO specifies whether the upper or lower *> triangular part of the array A is to be referenced as *> follows: *> *> UPLO = 'U' or 'u' Only the upper triangular part of A *> is to be referenced. *> *> UPLO = 'L' or 'l' Only the lower triangular part of A *> is to be referenced. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the order of the matrix A. *> N must be at least zero. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is REAL *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] X *> \verbatim *> X is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCX ) ). *> Before entry, the incremented array X must contain the n *> element vector x. *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> On entry, INCX specifies the increment for the elements of *> X. INCX must not be zero. *> \endverbatim *> *> \param[in,out] A *> \verbatim *> A is COMPLEX array, dimension ( LDA, N ) *> Before entry with UPLO = 'U' or 'u', the leading n by n *> upper triangular part of the array A must contain the upper *> triangular part of the hermitian matrix and the strictly *> lower triangular part of A is not referenced. On exit, the *> upper triangular part of the array A is overwritten by the *> upper triangular part of the updated matrix. *> Before entry with UPLO = 'L' or 'l', the leading n by n *> lower triangular part of the array A must contain the lower *> triangular part of the hermitian matrix and the strictly *> upper triangular part of A is not referenced. On exit, the *> lower triangular part of the array A is overwritten by the *> lower triangular part of the updated matrix. *> Note that the imaginary parts of the diagonal elements need *> not be set, they are assumed to be zero, and on exit they *> are set to zero. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> On entry, LDA specifies the first dimension of A as declared *> in the calling (sub) program. LDA must be at least *> max( 1, n ). *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup her * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 2 Blas routine. *> *> -- Written on 22-October-1986. *> Jack Dongarra, Argonne National Lab. *> Jeremy Du Croz, Nag Central Office. *> Sven Hammarling, Nag Central Office. *> Richard Hanson, Sandia National Labs. *> \endverbatim *> * ===================================================================== SUBROUTINE CHER(UPLO,N,ALPHA,X,INCX,A,LDA) * * -- Reference BLAS level2 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. REAL ALPHA INTEGER INCX,LDA,N CHARACTER UPLO * .. * .. Array Arguments .. COMPLEX A(LDA,*),X(*) * .. * * ===================================================================== * * .. Parameters .. COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * .. Local Scalars .. COMPLEX TEMP INTEGER I,INFO,IX,J,JX,KX * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CONJG,MAX,REAL * .. * * Test the input parameters. * INFO = 0 IF (.NOT.LSAME(UPLO,'U') .AND. .NOT.LSAME(UPLO,'L')) THEN INFO = 1 ELSE IF (N.LT.0) THEN INFO = 2 ELSE IF (INCX.EQ.0) THEN INFO = 5 ELSE IF (LDA.LT.MAX(1,N)) THEN INFO = 7 END IF IF (INFO.NE.0) THEN CALL XERBLA('CHER ',INFO) RETURN END IF * * Quick return if possible. * IF ((N.EQ.0) .OR. (ALPHA.EQ.REAL(ZERO))) RETURN * * Set the start point in X if the increment is not unity. * IF (INCX.LE.0) THEN KX = 1 - (N-1)*INCX ELSE IF (INCX.NE.1) THEN KX = 1 END IF * * Start the operations. In this version the elements of A are * accessed sequentially with one pass through the triangular part * of A. * IF (LSAME(UPLO,'U')) THEN * * Form A when A is stored in upper triangle. * IF (INCX.EQ.1) THEN DO 20 J = 1,N IF (X(J).NE.ZERO) THEN TEMP = ALPHA*CONJG(X(J)) DO 10 I = 1,J - 1 A(I,J) = A(I,J) + X(I)*TEMP 10 CONTINUE A(J,J) = REAL(A(J,J)) + REAL(X(J)*TEMP) ELSE A(J,J) = REAL(A(J,J)) END IF 20 CONTINUE ELSE JX = KX DO 40 J = 1,N IF (X(JX).NE.ZERO) THEN TEMP = ALPHA*CONJG(X(JX)) IX = KX DO 30 I = 1,J - 1 A(I,J) = A(I,J) + X(IX)*TEMP IX = IX + INCX 30 CONTINUE A(J,J) = REAL(A(J,J)) + REAL(X(JX)*TEMP) ELSE A(J,J) = REAL(A(J,J)) END IF JX = JX + INCX 40 CONTINUE END IF ELSE * * Form A when A is stored in lower triangle. * IF (INCX.EQ.1) THEN DO 60 J = 1,N IF (X(J).NE.ZERO) THEN TEMP = ALPHA*CONJG(X(J)) A(J,J) = REAL(A(J,J)) + REAL(TEMP*X(J)) DO 50 I = J + 1,N A(I,J) = A(I,J) + X(I)*TEMP 50 CONTINUE ELSE A(J,J) = REAL(A(J,J)) END IF 60 CONTINUE ELSE JX = KX DO 80 J = 1,N IF (X(JX).NE.ZERO) THEN TEMP = ALPHA*CONJG(X(JX)) A(J,J) = REAL(A(J,J)) + REAL(TEMP*X(JX)) IX = JX DO 70 I = J + 1,N IX = IX + INCX A(I,J) = A(I,J) + X(IX)*TEMP 70 CONTINUE ELSE A(J,J) = REAL(A(J,J)) END IF JX = JX + INCX 80 CONTINUE END IF END IF * RETURN * * End of CHER * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/cher2.f
*> \brief \b CHER2 * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CHER2(UPLO,N,ALPHA,X,INCX,Y,INCY,A,LDA) * * .. Scalar Arguments .. * COMPLEX ALPHA * INTEGER INCX,INCY,LDA,N * CHARACTER UPLO * .. * .. Array Arguments .. * COMPLEX A(LDA,*),X(*),Y(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CHER2 performs the hermitian rank 2 operation *> *> A := alpha*x*y**H + conjg( alpha )*y*x**H + A, *> *> where alpha is a scalar, x and y are n element vectors and A is an n *> by n hermitian matrix. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> On entry, UPLO specifies whether the upper or lower *> triangular part of the array A is to be referenced as *> follows: *> *> UPLO = 'U' or 'u' Only the upper triangular part of A *> is to be referenced. *> *> UPLO = 'L' or 'l' Only the lower triangular part of A *> is to be referenced. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the order of the matrix A. *> N must be at least zero. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is COMPLEX *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] X *> \verbatim *> X is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCX ) ). *> Before entry, the incremented array X must contain the n *> element vector x. *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> On entry, INCX specifies the increment for the elements of *> X. INCX must not be zero. *> \endverbatim *> *> \param[in] Y *> \verbatim *> Y is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCY ) ). *> Before entry, the incremented array Y must contain the n *> element vector y. *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> On entry, INCY specifies the increment for the elements of *> Y. INCY must not be zero. *> \endverbatim *> *> \param[in,out] A *> \verbatim *> A is COMPLEX array, dimension ( LDA, N ) *> Before entry with UPLO = 'U' or 'u', the leading n by n *> upper triangular part of the array A must contain the upper *> triangular part of the hermitian matrix and the strictly *> lower triangular part of A is not referenced. On exit, the *> upper triangular part of the array A is overwritten by the *> upper triangular part of the updated matrix. *> Before entry with UPLO = 'L' or 'l', the leading n by n *> lower triangular part of the array A must contain the lower *> triangular part of the hermitian matrix and the strictly *> upper triangular part of A is not referenced. On exit, the *> lower triangular part of the array A is overwritten by the *> lower triangular part of the updated matrix. *> Note that the imaginary parts of the diagonal elements need *> not be set, they are assumed to be zero, and on exit they *> are set to zero. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> On entry, LDA specifies the first dimension of A as declared *> in the calling (sub) program. LDA must be at least *> max( 1, n ). *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup her2 * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 2 Blas routine. *> *> -- Written on 22-October-1986. *> Jack Dongarra, Argonne National Lab. *> Jeremy Du Croz, Nag Central Office. *> Sven Hammarling, Nag Central Office. *> Richard Hanson, Sandia National Labs. *> \endverbatim *> * ===================================================================== SUBROUTINE CHER2(UPLO,N,ALPHA,X,INCX,Y,INCY,A,LDA) * * -- Reference BLAS level2 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX ALPHA INTEGER INCX,INCY,LDA,N CHARACTER UPLO * .. * .. Array Arguments .. COMPLEX A(LDA,*),X(*),Y(*) * .. * * ===================================================================== * * .. Parameters .. COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * .. Local Scalars .. COMPLEX TEMP1,TEMP2 INTEGER I,INFO,IX,IY,J,JX,JY,KX,KY * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CONJG,MAX,REAL * .. * * Test the input parameters. * INFO = 0 IF (.NOT.LSAME(UPLO,'U') .AND. .NOT.LSAME(UPLO,'L')) THEN INFO = 1 ELSE IF (N.LT.0) THEN INFO = 2 ELSE IF (INCX.EQ.0) THEN INFO = 5 ELSE IF (INCY.EQ.0) THEN INFO = 7 ELSE IF (LDA.LT.MAX(1,N)) THEN INFO = 9 END IF IF (INFO.NE.0) THEN CALL XERBLA('CHER2 ',INFO) RETURN END IF * * Quick return if possible. * IF ((N.EQ.0) .OR. (ALPHA.EQ.ZERO)) RETURN * * Set up the start points in X and Y if the increments are not both * unity. * IF ((INCX.NE.1) .OR. (INCY.NE.1)) THEN IF (INCX.GT.0) THEN KX = 1 ELSE KX = 1 - (N-1)*INCX END IF IF (INCY.GT.0) THEN KY = 1 ELSE KY = 1 - (N-1)*INCY END IF JX = KX JY = KY END IF * * Start the operations. In this version the elements of A are * accessed sequentially with one pass through the triangular part * of A. * IF (LSAME(UPLO,'U')) THEN * * Form A when A is stored in the upper triangle. * IF ((INCX.EQ.1) .AND. (INCY.EQ.1)) THEN DO 20 J = 1,N IF ((X(J).NE.ZERO) .OR. (Y(J).NE.ZERO)) THEN TEMP1 = ALPHA*CONJG(Y(J)) TEMP2 = CONJG(ALPHA*X(J)) DO 10 I = 1,J - 1 A(I,J) = A(I,J) + X(I)*TEMP1 + Y(I)*TEMP2 10 CONTINUE A(J,J) = REAL(A(J,J)) + + REAL(X(J)*TEMP1+Y(J)*TEMP2) ELSE A(J,J) = REAL(A(J,J)) END IF 20 CONTINUE ELSE DO 40 J = 1,N IF ((X(JX).NE.ZERO) .OR. (Y(JY).NE.ZERO)) THEN TEMP1 = ALPHA*CONJG(Y(JY)) TEMP2 = CONJG(ALPHA*X(JX)) IX = KX IY = KY DO 30 I = 1,J - 1 A(I,J) = A(I,J) + X(IX)*TEMP1 + Y(IY)*TEMP2 IX = IX + INCX IY = IY + INCY 30 CONTINUE A(J,J) = REAL(A(J,J)) + + REAL(X(JX)*TEMP1+Y(JY)*TEMP2) ELSE A(J,J) = REAL(A(J,J)) END IF JX = JX + INCX JY = JY + INCY 40 CONTINUE END IF ELSE * * Form A when A is stored in the lower triangle. * IF ((INCX.EQ.1) .AND. (INCY.EQ.1)) THEN DO 60 J = 1,N IF ((X(J).NE.ZERO) .OR. (Y(J).NE.ZERO)) THEN TEMP1 = ALPHA*CONJG(Y(J)) TEMP2 = CONJG(ALPHA*X(J)) A(J,J) = REAL(A(J,J)) + + REAL(X(J)*TEMP1+Y(J)*TEMP2) DO 50 I = J + 1,N A(I,J) = A(I,J) + X(I)*TEMP1 + Y(I)*TEMP2 50 CONTINUE ELSE A(J,J) = REAL(A(J,J)) END IF 60 CONTINUE ELSE DO 80 J = 1,N IF ((X(JX).NE.ZERO) .OR. (Y(JY).NE.ZERO)) THEN TEMP1 = ALPHA*CONJG(Y(JY)) TEMP2 = CONJG(ALPHA*X(JX)) A(J,J) = REAL(A(J,J)) + + REAL(X(JX)*TEMP1+Y(JY)*TEMP2) IX = JX IY = JY DO 70 I = J + 1,N IX = IX + INCX IY = IY + INCY A(I,J) = A(I,J) + X(IX)*TEMP1 + Y(IY)*TEMP2 70 CONTINUE ELSE A(J,J) = REAL(A(J,J)) END IF JX = JX + INCX JY = JY + INCY 80 CONTINUE END IF END IF * RETURN * * End of CHER2 * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/cher2k.f
*> \brief \b CHER2K * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CHER2K(UPLO,TRANS,N,K,ALPHA,A,LDA,B,LDB,BETA,C,LDC) * * .. Scalar Arguments .. * COMPLEX ALPHA * REAL BETA * INTEGER K,LDA,LDB,LDC,N * CHARACTER TRANS,UPLO * .. * .. Array Arguments .. * COMPLEX A(LDA,*),B(LDB,*),C(LDC,*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CHER2K performs one of the hermitian rank 2k operations *> *> C := alpha*A*B**H + conjg( alpha )*B*A**H + beta*C, *> *> or *> *> C := alpha*A**H*B + conjg( alpha )*B**H*A + beta*C, *> *> where alpha and beta are scalars with beta real, C is an n by n *> hermitian matrix and A and B are n by k matrices in the first case *> and k by n matrices in the second case. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> On entry, UPLO specifies whether the upper or lower *> triangular part of the array C is to be referenced as *> follows: *> *> UPLO = 'U' or 'u' Only the upper triangular part of C *> is to be referenced. *> *> UPLO = 'L' or 'l' Only the lower triangular part of C *> is to be referenced. *> \endverbatim *> *> \param[in] TRANS *> \verbatim *> TRANS is CHARACTER*1 *> On entry, TRANS specifies the operation to be performed as *> follows: *> *> TRANS = 'N' or 'n' C := alpha*A*B**H + *> conjg( alpha )*B*A**H + *> beta*C. *> *> TRANS = 'C' or 'c' C := alpha*A**H*B + *> conjg( alpha )*B**H*A + *> beta*C. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the order of the matrix C. N must be *> at least zero. *> \endverbatim *> *> \param[in] K *> \verbatim *> K is INTEGER *> On entry with TRANS = 'N' or 'n', K specifies the number *> of columns of the matrices A and B, and on entry with *> TRANS = 'C' or 'c', K specifies the number of rows of the *> matrices A and B. K must be at least zero. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is COMPLEX *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] A *> \verbatim *> A is COMPLEX array, dimension ( LDA, ka ), where ka is *> k when TRANS = 'N' or 'n', and is n otherwise. *> Before entry with TRANS = 'N' or 'n', the leading n by k *> part of the array A must contain the matrix A, otherwise *> the leading k by n part of the array A must contain the *> matrix A. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> On entry, LDA specifies the first dimension of A as declared *> in the calling (sub) program. When TRANS = 'N' or 'n' *> then LDA must be at least max( 1, n ), otherwise LDA must *> be at least max( 1, k ). *> \endverbatim *> *> \param[in] B *> \verbatim *> B is COMPLEX array, dimension ( LDB, kb ), where kb is *> k when TRANS = 'N' or 'n', and is n otherwise. *> Before entry with TRANS = 'N' or 'n', the leading n by k *> part of the array B must contain the matrix B, otherwise *> the leading k by n part of the array B must contain the *> matrix B. *> \endverbatim *> *> \param[in] LDB *> \verbatim *> LDB is INTEGER *> On entry, LDB specifies the first dimension of B as declared *> in the calling (sub) program. When TRANS = 'N' or 'n' *> then LDB must be at least max( 1, n ), otherwise LDB must *> be at least max( 1, k ). *> \endverbatim *> *> \param[in] BETA *> \verbatim *> BETA is REAL *> On entry, BETA specifies the scalar beta. *> \endverbatim *> *> \param[in,out] C *> \verbatim *> C is COMPLEX array, dimension ( LDC, N ) *> Before entry with UPLO = 'U' or 'u', the leading n by n *> upper triangular part of the array C must contain the upper *> triangular part of the hermitian matrix and the strictly *> lower triangular part of C is not referenced. On exit, the *> upper triangular part of the array C is overwritten by the *> upper triangular part of the updated matrix. *> Before entry with UPLO = 'L' or 'l', the leading n by n *> lower triangular part of the array C must contain the lower *> triangular part of the hermitian matrix and the strictly *> upper triangular part of C is not referenced. On exit, the *> lower triangular part of the array C is overwritten by the *> lower triangular part of the updated matrix. *> Note that the imaginary parts of the diagonal elements need *> not be set, they are assumed to be zero, and on exit they *> are set to zero. *> \endverbatim *> *> \param[in] LDC *> \verbatim *> LDC is INTEGER *> On entry, LDC specifies the first dimension of C as declared *> in the calling (sub) program. LDC must be at least *> max( 1, n ). *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup her2k * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 3 Blas routine. *> *> -- Written on 8-February-1989. *> Jack Dongarra, Argonne National Laboratory. *> Iain Duff, AERE Harwell. *> Jeremy Du Croz, Numerical Algorithms Group Ltd. *> Sven Hammarling, Numerical Algorithms Group Ltd. *> *> -- Modified 8-Nov-93 to set C(J,J) to REAL( C(J,J) ) when BETA = 1. *> Ed Anderson, Cray Research Inc. *> \endverbatim *> * ===================================================================== SUBROUTINE CHER2K(UPLO,TRANS,N,K,ALPHA,A,LDA,B,LDB,BETA,C,LDC) * * -- Reference BLAS level3 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX ALPHA REAL BETA INTEGER K,LDA,LDB,LDC,N CHARACTER TRANS,UPLO * .. * .. Array Arguments .. COMPLEX A(LDA,*),B(LDB,*),C(LDC,*) * .. * * ===================================================================== * * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CONJG,MAX,REAL * .. * .. Local Scalars .. COMPLEX TEMP1,TEMP2 INTEGER I,INFO,J,L,NROWA LOGICAL UPPER * .. * .. Parameters .. REAL ONE PARAMETER (ONE=1.0E+0) COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * * Test the input parameters. * IF (LSAME(TRANS,'N')) THEN NROWA = N ELSE NROWA = K END IF UPPER = LSAME(UPLO,'U') * INFO = 0 IF ((.NOT.UPPER) .AND. (.NOT.LSAME(UPLO,'L'))) THEN INFO = 1 ELSE IF ((.NOT.LSAME(TRANS,'N')) .AND. + (.NOT.LSAME(TRANS,'C'))) THEN INFO = 2 ELSE IF (N.LT.0) THEN INFO = 3 ELSE IF (K.LT.0) THEN INFO = 4 ELSE IF (LDA.LT.MAX(1,NROWA)) THEN INFO = 7 ELSE IF (LDB.LT.MAX(1,NROWA)) THEN INFO = 9 ELSE IF (LDC.LT.MAX(1,N)) THEN INFO = 12 END IF IF (INFO.NE.0) THEN CALL XERBLA('CHER2K',INFO) RETURN END IF * * Quick return if possible. * IF ((N.EQ.0) .OR. (((ALPHA.EQ.ZERO).OR. + (K.EQ.0)).AND. (BETA.EQ.ONE))) RETURN * * And when alpha.eq.zero. * IF (ALPHA.EQ.ZERO) THEN IF (UPPER) THEN IF (BETA.EQ.REAL(ZERO)) THEN DO 20 J = 1,N DO 10 I = 1,J C(I,J) = ZERO 10 CONTINUE 20 CONTINUE ELSE DO 40 J = 1,N DO 30 I = 1,J - 1 C(I,J) = BETA*C(I,J) 30 CONTINUE C(J,J) = BETA*REAL(C(J,J)) 40 CONTINUE END IF ELSE IF (BETA.EQ.REAL(ZERO)) THEN DO 60 J = 1,N DO 50 I = J,N C(I,J) = ZERO 50 CONTINUE 60 CONTINUE ELSE DO 80 J = 1,N C(J,J) = BETA*REAL(C(J,J)) DO 70 I = J + 1,N C(I,J) = BETA*C(I,J) 70 CONTINUE 80 CONTINUE END IF END IF RETURN END IF * * Start the operations. * IF (LSAME(TRANS,'N')) THEN * * Form C := alpha*A*B**H + conjg( alpha )*B*A**H + * C. * IF (UPPER) THEN DO 130 J = 1,N IF (BETA.EQ.REAL(ZERO)) THEN DO 90 I = 1,J C(I,J) = ZERO 90 CONTINUE ELSE IF (BETA.NE.ONE) THEN DO 100 I = 1,J - 1 C(I,J) = BETA*C(I,J) 100 CONTINUE C(J,J) = BETA*REAL(C(J,J)) ELSE C(J,J) = REAL(C(J,J)) END IF DO 120 L = 1,K IF ((A(J,L).NE.ZERO) .OR. (B(J,L).NE.ZERO)) THEN TEMP1 = ALPHA*CONJG(B(J,L)) TEMP2 = CONJG(ALPHA*A(J,L)) DO 110 I = 1,J - 1 C(I,J) = C(I,J) + A(I,L)*TEMP1 + + B(I,L)*TEMP2 110 CONTINUE C(J,J) = REAL(C(J,J)) + + REAL(A(J,L)*TEMP1+B(J,L)*TEMP2) END IF 120 CONTINUE 130 CONTINUE ELSE DO 180 J = 1,N IF (BETA.EQ.REAL(ZERO)) THEN DO 140 I = J,N C(I,J) = ZERO 140 CONTINUE ELSE IF (BETA.NE.ONE) THEN DO 150 I = J + 1,N C(I,J) = BETA*C(I,J) 150 CONTINUE C(J,J) = BETA*REAL(C(J,J)) ELSE C(J,J) = REAL(C(J,J)) END IF DO 170 L = 1,K IF ((A(J,L).NE.ZERO) .OR. (B(J,L).NE.ZERO)) THEN TEMP1 = ALPHA*CONJG(B(J,L)) TEMP2 = CONJG(ALPHA*A(J,L)) DO 160 I = J + 1,N C(I,J) = C(I,J) + A(I,L)*TEMP1 + + B(I,L)*TEMP2 160 CONTINUE C(J,J) = REAL(C(J,J)) + + REAL(A(J,L)*TEMP1+B(J,L)*TEMP2) END IF 170 CONTINUE 180 CONTINUE END IF ELSE * * Form C := alpha*A**H*B + conjg( alpha )*B**H*A + * C. * IF (UPPER) THEN DO 210 J = 1,N DO 200 I = 1,J TEMP1 = ZERO TEMP2 = ZERO DO 190 L = 1,K TEMP1 = TEMP1 + CONJG(A(L,I))*B(L,J) TEMP2 = TEMP2 + CONJG(B(L,I))*A(L,J) 190 CONTINUE IF (I.EQ.J) THEN IF (BETA.EQ.REAL(ZERO)) THEN C(J,J) = REAL(ALPHA*TEMP1+ + CONJG(ALPHA)*TEMP2) ELSE C(J,J) = BETA*REAL(C(J,J)) + + REAL(ALPHA*TEMP1+ + CONJG(ALPHA)*TEMP2) END IF ELSE IF (BETA.EQ.REAL(ZERO)) THEN C(I,J) = ALPHA*TEMP1 + CONJG(ALPHA)*TEMP2 ELSE C(I,J) = BETA*C(I,J) + ALPHA*TEMP1 + + CONJG(ALPHA)*TEMP2 END IF END IF 200 CONTINUE 210 CONTINUE ELSE DO 240 J = 1,N DO 230 I = J,N TEMP1 = ZERO TEMP2 = ZERO DO 220 L = 1,K TEMP1 = TEMP1 + CONJG(A(L,I))*B(L,J) TEMP2 = TEMP2 + CONJG(B(L,I))*A(L,J) 220 CONTINUE IF (I.EQ.J) THEN IF (BETA.EQ.REAL(ZERO)) THEN C(J,J) = REAL(ALPHA*TEMP1+ + CONJG(ALPHA)*TEMP2) ELSE C(J,J) = BETA*REAL(C(J,J)) + + REAL(ALPHA*TEMP1+ + CONJG(ALPHA)*TEMP2) END IF ELSE IF (BETA.EQ.REAL(ZERO)) THEN C(I,J) = ALPHA*TEMP1 + CONJG(ALPHA)*TEMP2 ELSE C(I,J) = BETA*C(I,J) + ALPHA*TEMP1 + + CONJG(ALPHA)*TEMP2 END IF END IF 230 CONTINUE 240 CONTINUE END IF END IF * RETURN * * End of CHER2K * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/cherk.f
*> \brief \b CHERK * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CHERK(UPLO,TRANS,N,K,ALPHA,A,LDA,BETA,C,LDC) * * .. Scalar Arguments .. * REAL ALPHA,BETA * INTEGER K,LDA,LDC,N * CHARACTER TRANS,UPLO * .. * .. Array Arguments .. * COMPLEX A(LDA,*),C(LDC,*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CHERK performs one of the hermitian rank k operations *> *> C := alpha*A*A**H + beta*C, *> *> or *> *> C := alpha*A**H*A + beta*C, *> *> where alpha and beta are real scalars, C is an n by n hermitian *> matrix and A is an n by k matrix in the first case and a k by n *> matrix in the second case. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> On entry, UPLO specifies whether the upper or lower *> triangular part of the array C is to be referenced as *> follows: *> *> UPLO = 'U' or 'u' Only the upper triangular part of C *> is to be referenced. *> *> UPLO = 'L' or 'l' Only the lower triangular part of C *> is to be referenced. *> \endverbatim *> *> \param[in] TRANS *> \verbatim *> TRANS is CHARACTER*1 *> On entry, TRANS specifies the operation to be performed as *> follows: *> *> TRANS = 'N' or 'n' C := alpha*A*A**H + beta*C. *> *> TRANS = 'C' or 'c' C := alpha*A**H*A + beta*C. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the order of the matrix C. N must be *> at least zero. *> \endverbatim *> *> \param[in] K *> \verbatim *> K is INTEGER *> On entry with TRANS = 'N' or 'n', K specifies the number *> of columns of the matrix A, and on entry with *> TRANS = 'C' or 'c', K specifies the number of rows of the *> matrix A. K must be at least zero. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is REAL *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] A *> \verbatim *> A is COMPLEX array, dimension ( LDA, ka ), where ka is *> k when TRANS = 'N' or 'n', and is n otherwise. *> Before entry with TRANS = 'N' or 'n', the leading n by k *> part of the array A must contain the matrix A, otherwise *> the leading k by n part of the array A must contain the *> matrix A. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> On entry, LDA specifies the first dimension of A as declared *> in the calling (sub) program. When TRANS = 'N' or 'n' *> then LDA must be at least max( 1, n ), otherwise LDA must *> be at least max( 1, k ). *> \endverbatim *> *> \param[in] BETA *> \verbatim *> BETA is REAL *> On entry, BETA specifies the scalar beta. *> \endverbatim *> *> \param[in,out] C *> \verbatim *> C is COMPLEX array, dimension ( LDC, N ) *> Before entry with UPLO = 'U' or 'u', the leading n by n *> upper triangular part of the array C must contain the upper *> triangular part of the hermitian matrix and the strictly *> lower triangular part of C is not referenced. On exit, the *> upper triangular part of the array C is overwritten by the *> upper triangular part of the updated matrix. *> Before entry with UPLO = 'L' or 'l', the leading n by n *> lower triangular part of the array C must contain the lower *> triangular part of the hermitian matrix and the strictly *> upper triangular part of C is not referenced. On exit, the *> lower triangular part of the array C is overwritten by the *> lower triangular part of the updated matrix. *> Note that the imaginary parts of the diagonal elements need *> not be set, they are assumed to be zero, and on exit they *> are set to zero. *> \endverbatim *> *> \param[in] LDC *> \verbatim *> LDC is INTEGER *> On entry, LDC specifies the first dimension of C as declared *> in the calling (sub) program. LDC must be at least *> max( 1, n ). *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup herk * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 3 Blas routine. *> *> -- Written on 8-February-1989. *> Jack Dongarra, Argonne National Laboratory. *> Iain Duff, AERE Harwell. *> Jeremy Du Croz, Numerical Algorithms Group Ltd. *> Sven Hammarling, Numerical Algorithms Group Ltd. *> *> -- Modified 8-Nov-93 to set C(J,J) to REAL( C(J,J) ) when BETA = 1. *> Ed Anderson, Cray Research Inc. *> \endverbatim *> * ===================================================================== SUBROUTINE CHERK(UPLO,TRANS,N,K,ALPHA,A,LDA,BETA,C,LDC) * * -- Reference BLAS level3 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. REAL ALPHA,BETA INTEGER K,LDA,LDC,N CHARACTER TRANS,UPLO * .. * .. Array Arguments .. COMPLEX A(LDA,*),C(LDC,*) * .. * * ===================================================================== * * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CMPLX,CONJG,MAX,REAL * .. * .. Local Scalars .. COMPLEX TEMP REAL RTEMP INTEGER I,INFO,J,L,NROWA LOGICAL UPPER * .. * .. Parameters .. REAL ONE,ZERO PARAMETER (ONE=1.0E+0,ZERO=0.0E+0) * .. * * Test the input parameters. * IF (LSAME(TRANS,'N')) THEN NROWA = N ELSE NROWA = K END IF UPPER = LSAME(UPLO,'U') * INFO = 0 IF ((.NOT.UPPER) .AND. (.NOT.LSAME(UPLO,'L'))) THEN INFO = 1 ELSE IF ((.NOT.LSAME(TRANS,'N')) .AND. + (.NOT.LSAME(TRANS,'C'))) THEN INFO = 2 ELSE IF (N.LT.0) THEN INFO = 3 ELSE IF (K.LT.0) THEN INFO = 4 ELSE IF (LDA.LT.MAX(1,NROWA)) THEN INFO = 7 ELSE IF (LDC.LT.MAX(1,N)) THEN INFO = 10 END IF IF (INFO.NE.0) THEN CALL XERBLA('CHERK ',INFO) RETURN END IF * * Quick return if possible. * IF ((N.EQ.0) .OR. (((ALPHA.EQ.ZERO).OR. + (K.EQ.0)).AND. (BETA.EQ.ONE))) RETURN * * And when alpha.eq.zero. * IF (ALPHA.EQ.ZERO) THEN IF (UPPER) THEN IF (BETA.EQ.ZERO) THEN DO 20 J = 1,N DO 10 I = 1,J C(I,J) = ZERO 10 CONTINUE 20 CONTINUE ELSE DO 40 J = 1,N DO 30 I = 1,J - 1 C(I,J) = BETA*C(I,J) 30 CONTINUE C(J,J) = BETA*REAL(C(J,J)) 40 CONTINUE END IF ELSE IF (BETA.EQ.ZERO) THEN DO 60 J = 1,N DO 50 I = J,N C(I,J) = ZERO 50 CONTINUE 60 CONTINUE ELSE DO 80 J = 1,N C(J,J) = BETA*REAL(C(J,J)) DO 70 I = J + 1,N C(I,J) = BETA*C(I,J) 70 CONTINUE 80 CONTINUE END IF END IF RETURN END IF * * Start the operations. * IF (LSAME(TRANS,'N')) THEN * * Form C := alpha*A*A**H + beta*C. * IF (UPPER) THEN DO 130 J = 1,N IF (BETA.EQ.ZERO) THEN DO 90 I = 1,J C(I,J) = ZERO 90 CONTINUE ELSE IF (BETA.NE.ONE) THEN DO 100 I = 1,J - 1 C(I,J) = BETA*C(I,J) 100 CONTINUE C(J,J) = BETA*REAL(C(J,J)) ELSE C(J,J) = REAL(C(J,J)) END IF DO 120 L = 1,K IF (A(J,L).NE.CMPLX(ZERO)) THEN TEMP = ALPHA*CONJG(A(J,L)) DO 110 I = 1,J - 1 C(I,J) = C(I,J) + TEMP*A(I,L) 110 CONTINUE C(J,J) = REAL(C(J,J)) + REAL(TEMP*A(I,L)) END IF 120 CONTINUE 130 CONTINUE ELSE DO 180 J = 1,N IF (BETA.EQ.ZERO) THEN DO 140 I = J,N C(I,J) = ZERO 140 CONTINUE ELSE IF (BETA.NE.ONE) THEN C(J,J) = BETA*REAL(C(J,J)) DO 150 I = J + 1,N C(I,J) = BETA*C(I,J) 150 CONTINUE ELSE C(J,J) = REAL(C(J,J)) END IF DO 170 L = 1,K IF (A(J,L).NE.CMPLX(ZERO)) THEN TEMP = ALPHA*CONJG(A(J,L)) C(J,J) = REAL(C(J,J)) + REAL(TEMP*A(J,L)) DO 160 I = J + 1,N C(I,J) = C(I,J) + TEMP*A(I,L) 160 CONTINUE END IF 170 CONTINUE 180 CONTINUE END IF ELSE * * Form C := alpha*A**H*A + beta*C. * IF (UPPER) THEN DO 220 J = 1,N DO 200 I = 1,J - 1 TEMP = ZERO DO 190 L = 1,K TEMP = TEMP + CONJG(A(L,I))*A(L,J) 190 CONTINUE IF (BETA.EQ.ZERO) THEN C(I,J) = ALPHA*TEMP ELSE C(I,J) = ALPHA*TEMP + BETA*C(I,J) END IF 200 CONTINUE RTEMP = ZERO DO 210 L = 1,K RTEMP = RTEMP + REAL(CONJG(A(L,J))*A(L,J)) 210 CONTINUE IF (BETA.EQ.ZERO) THEN C(J,J) = ALPHA*RTEMP ELSE C(J,J) = ALPHA*RTEMP + BETA*REAL(C(J,J)) END IF 220 CONTINUE ELSE DO 260 J = 1,N RTEMP = ZERO DO 230 L = 1,K RTEMP = RTEMP + REAL(CONJG(A(L,J))*A(L,J)) 230 CONTINUE IF (BETA.EQ.ZERO) THEN C(J,J) = ALPHA*RTEMP ELSE C(J,J) = ALPHA*RTEMP + BETA*REAL(C(J,J)) END IF DO 250 I = J + 1,N TEMP = ZERO DO 240 L = 1,K TEMP = TEMP + CONJG(A(L,I))*A(L,J) 240 CONTINUE IF (BETA.EQ.ZERO) THEN C(I,J) = ALPHA*TEMP ELSE C(I,J) = ALPHA*TEMP + BETA*C(I,J) END IF 250 CONTINUE 260 CONTINUE END IF END IF * RETURN * * End of CHERK * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/chpmv.f
*> \brief \b CHPMV * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CHPMV(UPLO,N,ALPHA,AP,X,INCX,BETA,Y,INCY) * * .. Scalar Arguments .. * COMPLEX ALPHA,BETA * INTEGER INCX,INCY,N * CHARACTER UPLO * .. * .. Array Arguments .. * COMPLEX AP(*),X(*),Y(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CHPMV performs the matrix-vector operation *> *> y := alpha*A*x + beta*y, *> *> where alpha and beta are scalars, x and y are n element vectors and *> A is an n by n hermitian matrix, supplied in packed form. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> On entry, UPLO specifies whether the upper or lower *> triangular part of the matrix A is supplied in the packed *> array AP as follows: *> *> UPLO = 'U' or 'u' The upper triangular part of A is *> supplied in AP. *> *> UPLO = 'L' or 'l' The lower triangular part of A is *> supplied in AP. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the order of the matrix A. *> N must be at least zero. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is COMPLEX *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] AP *> \verbatim *> AP is COMPLEX array, dimension at least *> ( ( n*( n + 1 ) )/2 ). *> Before entry with UPLO = 'U' or 'u', the array AP must *> contain the upper triangular part of the hermitian matrix *> packed sequentially, column by column, so that AP( 1 ) *> contains a( 1, 1 ), AP( 2 ) and AP( 3 ) contain a( 1, 2 ) *> and a( 2, 2 ) respectively, and so on. *> Before entry with UPLO = 'L' or 'l', the array AP must *> contain the lower triangular part of the hermitian matrix *> packed sequentially, column by column, so that AP( 1 ) *> contains a( 1, 1 ), AP( 2 ) and AP( 3 ) contain a( 2, 1 ) *> and a( 3, 1 ) respectively, and so on. *> Note that the imaginary parts of the diagonal elements need *> not be set and are assumed to be zero. *> \endverbatim *> *> \param[in] X *> \verbatim *> X is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCX ) ). *> Before entry, the incremented array X must contain the n *> element vector x. *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> On entry, INCX specifies the increment for the elements of *> X. INCX must not be zero. *> \endverbatim *> *> \param[in] BETA *> \verbatim *> BETA is COMPLEX *> On entry, BETA specifies the scalar beta. When BETA is *> supplied as zero then Y need not be set on input. *> \endverbatim *> *> \param[in,out] Y *> \verbatim *> Y is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCY ) ). *> Before entry, the incremented array Y must contain the n *> element vector y. On exit, Y is overwritten by the updated *> vector y. *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> On entry, INCY specifies the increment for the elements of *> Y. INCY must not be zero. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup hpmv * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 2 Blas routine. *> The vector and matrix arguments are not referenced when N = 0, or M = 0 *> *> -- Written on 22-October-1986. *> Jack Dongarra, Argonne National Lab. *> Jeremy Du Croz, Nag Central Office. *> Sven Hammarling, Nag Central Office. *> Richard Hanson, Sandia National Labs. *> \endverbatim *> * ===================================================================== SUBROUTINE CHPMV(UPLO,N,ALPHA,AP,X,INCX,BETA,Y,INCY) * * -- Reference BLAS level2 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX ALPHA,BETA INTEGER INCX,INCY,N CHARACTER UPLO * .. * .. Array Arguments .. COMPLEX AP(*),X(*),Y(*) * .. * * ===================================================================== * * .. Parameters .. COMPLEX ONE PARAMETER (ONE= (1.0E+0,0.0E+0)) COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * .. Local Scalars .. COMPLEX TEMP1,TEMP2 INTEGER I,INFO,IX,IY,J,JX,JY,K,KK,KX,KY * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CONJG,REAL * .. * * Test the input parameters. * INFO = 0 IF (.NOT.LSAME(UPLO,'U') .AND. .NOT.LSAME(UPLO,'L')) THEN INFO = 1 ELSE IF (N.LT.0) THEN INFO = 2 ELSE IF (INCX.EQ.0) THEN INFO = 6 ELSE IF (INCY.EQ.0) THEN INFO = 9 END IF IF (INFO.NE.0) THEN CALL XERBLA('CHPMV ',INFO) RETURN END IF * * Quick return if possible. * IF ((N.EQ.0) .OR. ((ALPHA.EQ.ZERO).AND. (BETA.EQ.ONE))) RETURN * * Set up the start points in X and Y. * IF (INCX.GT.0) THEN KX = 1 ELSE KX = 1 - (N-1)*INCX END IF IF (INCY.GT.0) THEN KY = 1 ELSE KY = 1 - (N-1)*INCY END IF * * Start the operations. In this version the elements of the array AP * are accessed sequentially with one pass through AP. * * First form y := beta*y. * IF (BETA.NE.ONE) THEN IF (INCY.EQ.1) THEN IF (BETA.EQ.ZERO) THEN DO 10 I = 1,N Y(I) = ZERO 10 CONTINUE ELSE DO 20 I = 1,N Y(I) = BETA*Y(I) 20 CONTINUE END IF ELSE IY = KY IF (BETA.EQ.ZERO) THEN DO 30 I = 1,N Y(IY) = ZERO IY = IY + INCY 30 CONTINUE ELSE DO 40 I = 1,N Y(IY) = BETA*Y(IY) IY = IY + INCY 40 CONTINUE END IF END IF END IF IF (ALPHA.EQ.ZERO) RETURN KK = 1 IF (LSAME(UPLO,'U')) THEN * * Form y when AP contains the upper triangle. * IF ((INCX.EQ.1) .AND. (INCY.EQ.1)) THEN DO 60 J = 1,N TEMP1 = ALPHA*X(J) TEMP2 = ZERO K = KK DO 50 I = 1,J - 1 Y(I) = Y(I) + TEMP1*AP(K) TEMP2 = TEMP2 + CONJG(AP(K))*X(I) K = K + 1 50 CONTINUE Y(J) = Y(J) + TEMP1*REAL(AP(KK+J-1)) + ALPHA*TEMP2 KK = KK + J 60 CONTINUE ELSE JX = KX JY = KY DO 80 J = 1,N TEMP1 = ALPHA*X(JX) TEMP2 = ZERO IX = KX IY = KY DO 70 K = KK,KK + J - 2 Y(IY) = Y(IY) + TEMP1*AP(K) TEMP2 = TEMP2 + CONJG(AP(K))*X(IX) IX = IX + INCX IY = IY + INCY 70 CONTINUE Y(JY) = Y(JY) + TEMP1*REAL(AP(KK+J-1)) + ALPHA*TEMP2 JX = JX + INCX JY = JY + INCY KK = KK + J 80 CONTINUE END IF ELSE * * Form y when AP contains the lower triangle. * IF ((INCX.EQ.1) .AND. (INCY.EQ.1)) THEN DO 100 J = 1,N TEMP1 = ALPHA*X(J) TEMP2 = ZERO Y(J) = Y(J) + TEMP1*REAL(AP(KK)) K = KK + 1 DO 90 I = J + 1,N Y(I) = Y(I) + TEMP1*AP(K) TEMP2 = TEMP2 + CONJG(AP(K))*X(I) K = K + 1 90 CONTINUE Y(J) = Y(J) + ALPHA*TEMP2 KK = KK + (N-J+1) 100 CONTINUE ELSE JX = KX JY = KY DO 120 J = 1,N TEMP1 = ALPHA*X(JX) TEMP2 = ZERO Y(JY) = Y(JY) + TEMP1*REAL(AP(KK)) IX = JX IY = JY DO 110 K = KK + 1,KK + N - J IX = IX + INCX IY = IY + INCY Y(IY) = Y(IY) + TEMP1*AP(K) TEMP2 = TEMP2 + CONJG(AP(K))*X(IX) 110 CONTINUE Y(JY) = Y(JY) + ALPHA*TEMP2 JX = JX + INCX JY = JY + INCY KK = KK + (N-J+1) 120 CONTINUE END IF END IF * RETURN * * End of CHPMV * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/chpr.f
*> \brief \b CHPR * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CHPR(UPLO,N,ALPHA,X,INCX,AP) * * .. Scalar Arguments .. * REAL ALPHA * INTEGER INCX,N * CHARACTER UPLO * .. * .. Array Arguments .. * COMPLEX AP(*),X(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CHPR performs the hermitian rank 1 operation *> *> A := alpha*x*x**H + A, *> *> where alpha is a real scalar, x is an n element vector and A is an *> n by n hermitian matrix, supplied in packed form. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> On entry, UPLO specifies whether the upper or lower *> triangular part of the matrix A is supplied in the packed *> array AP as follows: *> *> UPLO = 'U' or 'u' The upper triangular part of A is *> supplied in AP. *> *> UPLO = 'L' or 'l' The lower triangular part of A is *> supplied in AP. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the order of the matrix A. *> N must be at least zero. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is REAL *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] X *> \verbatim *> X is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCX ) ). *> Before entry, the incremented array X must contain the n *> element vector x. *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> On entry, INCX specifies the increment for the elements of *> X. INCX must not be zero. *> \endverbatim *> *> \param[in,out] AP *> \verbatim *> AP is COMPLEX array, dimension at least *> ( ( n*( n + 1 ) )/2 ). *> Before entry with UPLO = 'U' or 'u', the array AP must *> contain the upper triangular part of the hermitian matrix *> packed sequentially, column by column, so that AP( 1 ) *> contains a( 1, 1 ), AP( 2 ) and AP( 3 ) contain a( 1, 2 ) *> and a( 2, 2 ) respectively, and so on. On exit, the array *> AP is overwritten by the upper triangular part of the *> updated matrix. *> Before entry with UPLO = 'L' or 'l', the array AP must *> contain the lower triangular part of the hermitian matrix *> packed sequentially, column by column, so that AP( 1 ) *> contains a( 1, 1 ), AP( 2 ) and AP( 3 ) contain a( 2, 1 ) *> and a( 3, 1 ) respectively, and so on. On exit, the array *> AP is overwritten by the lower triangular part of the *> updated matrix. *> Note that the imaginary parts of the diagonal elements need *> not be set, they are assumed to be zero, and on exit they *> are set to zero. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup hpr * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 2 Blas routine. *> *> -- Written on 22-October-1986. *> Jack Dongarra, Argonne National Lab. *> Jeremy Du Croz, Nag Central Office. *> Sven Hammarling, Nag Central Office. *> Richard Hanson, Sandia National Labs. *> \endverbatim *> * ===================================================================== SUBROUTINE CHPR(UPLO,N,ALPHA,X,INCX,AP) * * -- Reference BLAS level2 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. REAL ALPHA INTEGER INCX,N CHARACTER UPLO * .. * .. Array Arguments .. COMPLEX AP(*),X(*) * .. * * ===================================================================== * * .. Parameters .. COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * .. Local Scalars .. COMPLEX TEMP INTEGER I,INFO,IX,J,JX,K,KK,KX * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CONJG,REAL * .. * * Test the input parameters. * INFO = 0 IF (.NOT.LSAME(UPLO,'U') .AND. .NOT.LSAME(UPLO,'L')) THEN INFO = 1 ELSE IF (N.LT.0) THEN INFO = 2 ELSE IF (INCX.EQ.0) THEN INFO = 5 END IF IF (INFO.NE.0) THEN CALL XERBLA('CHPR ',INFO) RETURN END IF * * Quick return if possible. * IF ((N.EQ.0) .OR. (ALPHA.EQ.REAL(ZERO))) RETURN * * Set the start point in X if the increment is not unity. * IF (INCX.LE.0) THEN KX = 1 - (N-1)*INCX ELSE IF (INCX.NE.1) THEN KX = 1 END IF * * Start the operations. In this version the elements of the array AP * are accessed sequentially with one pass through AP. * KK = 1 IF (LSAME(UPLO,'U')) THEN * * Form A when upper triangle is stored in AP. * IF (INCX.EQ.1) THEN DO 20 J = 1,N IF (X(J).NE.ZERO) THEN TEMP = ALPHA*CONJG(X(J)) K = KK DO 10 I = 1,J - 1 AP(K) = AP(K) + X(I)*TEMP K = K + 1 10 CONTINUE AP(KK+J-1) = REAL(AP(KK+J-1)) + REAL(X(J)*TEMP) ELSE AP(KK+J-1) = REAL(AP(KK+J-1)) END IF KK = KK + J 20 CONTINUE ELSE JX = KX DO 40 J = 1,N IF (X(JX).NE.ZERO) THEN TEMP = ALPHA*CONJG(X(JX)) IX = KX DO 30 K = KK,KK + J - 2 AP(K) = AP(K) + X(IX)*TEMP IX = IX + INCX 30 CONTINUE AP(KK+J-1) = REAL(AP(KK+J-1)) + REAL(X(JX)*TEMP) ELSE AP(KK+J-1) = REAL(AP(KK+J-1)) END IF JX = JX + INCX KK = KK + J 40 CONTINUE END IF ELSE * * Form A when lower triangle is stored in AP. * IF (INCX.EQ.1) THEN DO 60 J = 1,N IF (X(J).NE.ZERO) THEN TEMP = ALPHA*CONJG(X(J)) AP(KK) = REAL(AP(KK)) + REAL(TEMP*X(J)) K = KK + 1 DO 50 I = J + 1,N AP(K) = AP(K) + X(I)*TEMP K = K + 1 50 CONTINUE ELSE AP(KK) = REAL(AP(KK)) END IF KK = KK + N - J + 1 60 CONTINUE ELSE JX = KX DO 80 J = 1,N IF (X(JX).NE.ZERO) THEN TEMP = ALPHA*CONJG(X(JX)) AP(KK) = REAL(AP(KK)) + REAL(TEMP*X(JX)) IX = JX DO 70 K = KK + 1,KK + N - J IX = IX + INCX AP(K) = AP(K) + X(IX)*TEMP 70 CONTINUE ELSE AP(KK) = REAL(AP(KK)) END IF JX = JX + INCX KK = KK + N - J + 1 80 CONTINUE END IF END IF * RETURN * * End of CHPR * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/chpr2.f
*> \brief \b CHPR2 * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CHPR2(UPLO,N,ALPHA,X,INCX,Y,INCY,AP) * * .. Scalar Arguments .. * COMPLEX ALPHA * INTEGER INCX,INCY,N * CHARACTER UPLO * .. * .. Array Arguments .. * COMPLEX AP(*),X(*),Y(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CHPR2 performs the hermitian rank 2 operation *> *> A := alpha*x*y**H + conjg( alpha )*y*x**H + A, *> *> where alpha is a scalar, x and y are n element vectors and A is an *> n by n hermitian matrix, supplied in packed form. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> On entry, UPLO specifies whether the upper or lower *> triangular part of the matrix A is supplied in the packed *> array AP as follows: *> *> UPLO = 'U' or 'u' The upper triangular part of A is *> supplied in AP. *> *> UPLO = 'L' or 'l' The lower triangular part of A is *> supplied in AP. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the order of the matrix A. *> N must be at least zero. *> \endverbatim *> *> \param[in] ALPHA *> \verbatim *> ALPHA is COMPLEX *> On entry, ALPHA specifies the scalar alpha. *> \endverbatim *> *> \param[in] X *> \verbatim *> X is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCX ) ). *> Before entry, the incremented array X must contain the n *> element vector x. *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> On entry, INCX specifies the increment for the elements of *> X. INCX must not be zero. *> \endverbatim *> *> \param[in] Y *> \verbatim *> Y is COMPLEX array, dimension at least *> ( 1 + ( n - 1 )*abs( INCY ) ). *> Before entry, the incremented array Y must contain the n *> element vector y. *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> On entry, INCY specifies the increment for the elements of *> Y. INCY must not be zero. *> \endverbatim *> *> \param[in,out] AP *> \verbatim *> AP is COMPLEX array, dimension at least *> ( ( n*( n + 1 ) )/2 ). *> Before entry with UPLO = 'U' or 'u', the array AP must *> contain the upper triangular part of the hermitian matrix *> packed sequentially, column by column, so that AP( 1 ) *> contains a( 1, 1 ), AP( 2 ) and AP( 3 ) contain a( 1, 2 ) *> and a( 2, 2 ) respectively, and so on. On exit, the array *> AP is overwritten by the upper triangular part of the *> updated matrix. *> Before entry with UPLO = 'L' or 'l', the array AP must *> contain the lower triangular part of the hermitian matrix *> packed sequentially, column by column, so that AP( 1 ) *> contains a( 1, 1 ), AP( 2 ) and AP( 3 ) contain a( 2, 1 ) *> and a( 3, 1 ) respectively, and so on. On exit, the array *> AP is overwritten by the lower triangular part of the *> updated matrix. *> Note that the imaginary parts of the diagonal elements need *> not be set, they are assumed to be zero, and on exit they *> are set to zero. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup hpr2 * *> \par Further Details: * ===================== *> *> \verbatim *> *> Level 2 Blas routine. *> *> -- Written on 22-October-1986. *> Jack Dongarra, Argonne National Lab. *> Jeremy Du Croz, Nag Central Office. *> Sven Hammarling, Nag Central Office. *> Richard Hanson, Sandia National Labs. *> \endverbatim *> * ===================================================================== SUBROUTINE CHPR2(UPLO,N,ALPHA,X,INCX,Y,INCY,AP) * * -- Reference BLAS level2 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX ALPHA INTEGER INCX,INCY,N CHARACTER UPLO * .. * .. Array Arguments .. COMPLEX AP(*),X(*),Y(*) * .. * * ===================================================================== * * .. Parameters .. COMPLEX ZERO PARAMETER (ZERO= (0.0E+0,0.0E+0)) * .. * .. Local Scalars .. COMPLEX TEMP1,TEMP2 INTEGER I,INFO,IX,IY,J,JX,JY,K,KK,KX,KY * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC CONJG,REAL * .. * * Test the input parameters. * INFO = 0 IF (.NOT.LSAME(UPLO,'U') .AND. .NOT.LSAME(UPLO,'L')) THEN INFO = 1 ELSE IF (N.LT.0) THEN INFO = 2 ELSE IF (INCX.EQ.0) THEN INFO = 5 ELSE IF (INCY.EQ.0) THEN INFO = 7 END IF IF (INFO.NE.0) THEN CALL XERBLA('CHPR2 ',INFO) RETURN END IF * * Quick return if possible. * IF ((N.EQ.0) .OR. (ALPHA.EQ.ZERO)) RETURN * * Set up the start points in X and Y if the increments are not both * unity. * IF ((INCX.NE.1) .OR. (INCY.NE.1)) THEN IF (INCX.GT.0) THEN KX = 1 ELSE KX = 1 - (N-1)*INCX END IF IF (INCY.GT.0) THEN KY = 1 ELSE KY = 1 - (N-1)*INCY END IF JX = KX JY = KY END IF * * Start the operations. In this version the elements of the array AP * are accessed sequentially with one pass through AP. * KK = 1 IF (LSAME(UPLO,'U')) THEN * * Form A when upper triangle is stored in AP. * IF ((INCX.EQ.1) .AND. (INCY.EQ.1)) THEN DO 20 J = 1,N IF ((X(J).NE.ZERO) .OR. (Y(J).NE.ZERO)) THEN TEMP1 = ALPHA*CONJG(Y(J)) TEMP2 = CONJG(ALPHA*X(J)) K = KK DO 10 I = 1,J - 1 AP(K) = AP(K) + X(I)*TEMP1 + Y(I)*TEMP2 K = K + 1 10 CONTINUE AP(KK+J-1) = REAL(AP(KK+J-1)) + + REAL(X(J)*TEMP1+Y(J)*TEMP2) ELSE AP(KK+J-1) = REAL(AP(KK+J-1)) END IF KK = KK + J 20 CONTINUE ELSE DO 40 J = 1,N IF ((X(JX).NE.ZERO) .OR. (Y(JY).NE.ZERO)) THEN TEMP1 = ALPHA*CONJG(Y(JY)) TEMP2 = CONJG(ALPHA*X(JX)) IX = KX IY = KY DO 30 K = KK,KK + J - 2 AP(K) = AP(K) + X(IX)*TEMP1 + Y(IY)*TEMP2 IX = IX + INCX IY = IY + INCY 30 CONTINUE AP(KK+J-1) = REAL(AP(KK+J-1)) + + REAL(X(JX)*TEMP1+Y(JY)*TEMP2) ELSE AP(KK+J-1) = REAL(AP(KK+J-1)) END IF JX = JX + INCX JY = JY + INCY KK = KK + J 40 CONTINUE END IF ELSE * * Form A when lower triangle is stored in AP. * IF ((INCX.EQ.1) .AND. (INCY.EQ.1)) THEN DO 60 J = 1,N IF ((X(J).NE.ZERO) .OR. (Y(J).NE.ZERO)) THEN TEMP1 = ALPHA*CONJG(Y(J)) TEMP2 = CONJG(ALPHA*X(J)) AP(KK) = REAL(AP(KK)) + + REAL(X(J)*TEMP1+Y(J)*TEMP2) K = KK + 1 DO 50 I = J + 1,N AP(K) = AP(K) + X(I)*TEMP1 + Y(I)*TEMP2 K = K + 1 50 CONTINUE ELSE AP(KK) = REAL(AP(KK)) END IF KK = KK + N - J + 1 60 CONTINUE ELSE DO 80 J = 1,N IF ((X(JX).NE.ZERO) .OR. (Y(JY).NE.ZERO)) THEN TEMP1 = ALPHA*CONJG(Y(JY)) TEMP2 = CONJG(ALPHA*X(JX)) AP(KK) = REAL(AP(KK)) + + REAL(X(JX)*TEMP1+Y(JY)*TEMP2) IX = JX IY = JY DO 70 K = KK + 1,KK + N - J IX = IX + INCX IY = IY + INCY AP(K) = AP(K) + X(IX)*TEMP1 + Y(IY)*TEMP2 70 CONTINUE ELSE AP(KK) = REAL(AP(KK)) END IF JX = JX + INCX JY = JY + INCY KK = KK + N - J + 1 80 CONTINUE END IF END IF * RETURN * * End of CHPR2 * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/crotg.f90
!> \brief \b CROTG generates a Givens rotation with real cosine and complex sine. ! ! =========== DOCUMENTATION =========== ! ! Online html documentation available at ! http://www.netlib.org/lapack/explore-html/ ! !> \par Purpose: ! ============= !> !> \verbatim !> !> CROTG constructs a plane rotation !> [ c s ] [ a ] = [ r ] !> [ -conjg(s) c ] [ b ] [ 0 ] !> where c is real, s is complex, and c**2 + conjg(s)*s = 1. !> !> The computation uses the formulas !> |x| = sqrt( Re(x)**2 + Im(x)**2 ) !> sgn(x) = x / |x| if x /= 0 !> = 1 if x = 0 !> c = |a| / sqrt(|a|**2 + |b|**2) !> s = sgn(a) * conjg(b) / sqrt(|a|**2 + |b|**2) !> r = sgn(a)*sqrt(|a|**2 + |b|**2) !> When a and b are real and r /= 0, the formulas simplify to !> c = a / r !> s = b / r !> the same as in SROTG when |a| > |b|. When |b| >= |a|, the !> sign of c and s will be different from those computed by SROTG !> if the signs of a and b are not the same. !> !> \endverbatim !> !> @see lartg, @see lartgp ! ! Arguments: ! ========== ! !> \param[in,out] A !> \verbatim !> A is COMPLEX !> On entry, the scalar a. !> On exit, the scalar r. !> \endverbatim !> !> \param[in] B !> \verbatim !> B is COMPLEX !> The scalar b. !> \endverbatim !> !> \param[out] C !> \verbatim !> C is REAL !> The scalar c. !> \endverbatim !> !> \param[out] S !> \verbatim !> S is COMPLEX !> The scalar s. !> \endverbatim ! ! Authors: ! ======== ! !> \author Weslley Pereira, University of Colorado Denver, USA ! !> \date December 2021 ! !> \ingroup rotg ! !> \par Further Details: ! ===================== !> !> \verbatim !> !> Based on the algorithm from !> !> Anderson E. (2017) !> Algorithm 978: Safe Scaling in the Level 1 BLAS !> ACM Trans Math Softw 44:1--28 !> https://doi.org/10.1145/3061665 !> !> \endverbatim ! ! ===================================================================== subroutine CROTG( a, b, c, s ) integer, parameter :: wp = kind(1.e0) ! ! -- Reference BLAS level1 routine -- ! -- Reference BLAS is a software package provided by Univ. of Tennessee, -- ! -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- ! ! .. Constants .. real(wp), parameter :: zero = 0.0_wp real(wp), parameter :: one = 1.0_wp complex(wp), parameter :: czero = 0.0_wp ! .. ! .. Scaling constants .. real(wp), parameter :: safmin = real(radix(0._wp),wp)**max( & minexponent(0._wp)-1, & 1-maxexponent(0._wp) & ) real(wp), parameter :: safmax = real(radix(0._wp),wp)**max( & 1-minexponent(0._wp), & maxexponent(0._wp)-1 & ) real(wp), parameter :: rtmin = sqrt( safmin ) ! .. ! .. Scalar Arguments .. real(wp) :: c complex(wp) :: a, b, s ! .. ! .. Local Scalars .. real(wp) :: d, f1, f2, g1, g2, h2, u, v, w, rtmax complex(wp) :: f, fs, g, gs, r, t ! .. ! .. Intrinsic Functions .. intrinsic :: abs, aimag, conjg, max, min, real, sqrt ! .. ! .. Statement Functions .. real(wp) :: ABSSQ ! .. ! .. Statement Function definitions .. ABSSQ( t ) = real( t )**2 + aimag( t )**2 ! .. ! .. Executable Statements .. ! f = a g = b if( g == czero ) then c = one s = czero r = f else if( f == czero ) then c = zero if( real(g) == zero ) then r = abs(aimag(g)) s = conjg( g ) / r elseif( aimag(g) == zero ) then r = abs(real(g)) s = conjg( g ) / r else g1 = max( abs(real(g)), abs(aimag(g)) ) rtmax = sqrt( safmax/2 ) if( g1 > rtmin .and. g1 < rtmax ) then ! ! Use unscaled algorithm ! ! The following two lines can be replaced by `d = abs( g )`. ! This algorithm do not use the intrinsic complex abs. g2 = ABSSQ( g ) d = sqrt( g2 ) s = conjg( g ) / d r = d else ! ! Use scaled algorithm ! u = min( safmax, max( safmin, g1 ) ) gs = g / u ! The following two lines can be replaced by `d = abs( gs )`. ! This algorithm do not use the intrinsic complex abs. g2 = ABSSQ( gs ) d = sqrt( g2 ) s = conjg( gs ) / d r = d*u end if end if else f1 = max( abs(real(f)), abs(aimag(f)) ) g1 = max( abs(real(g)), abs(aimag(g)) ) rtmax = sqrt( safmax/4 ) if( f1 > rtmin .and. f1 < rtmax .and. & g1 > rtmin .and. g1 < rtmax ) then ! ! Use unscaled algorithm ! f2 = ABSSQ( f ) g2 = ABSSQ( g ) h2 = f2 + g2 ! safmin <= f2 <= h2 <= safmax if( f2 >= h2 * safmin ) then ! safmin <= f2/h2 <= 1, and h2/f2 is finite c = sqrt( f2 / h2 ) r = f / c rtmax = rtmax * 2 if( f2 > rtmin .and. h2 < rtmax ) then ! safmin <= sqrt( f2*h2 ) <= safmax s = conjg( g ) * ( f / sqrt( f2*h2 ) ) else s = conjg( g ) * ( r / h2 ) end if else ! f2/h2 <= safmin may be subnormal, and h2/f2 may overflow. ! Moreover, ! safmin <= f2*f2 * safmax < f2 * h2 < h2*h2 * safmin <= safmax, ! sqrt(safmin) <= sqrt(f2 * h2) <= sqrt(safmax). ! Also, ! g2 >> f2, which means that h2 = g2. d = sqrt( f2 * h2 ) c = f2 / d if( c >= safmin ) then r = f / c else ! f2 / sqrt(f2 * h2) < safmin, then ! sqrt(safmin) <= f2 * sqrt(safmax) <= h2 / sqrt(f2 * h2) <= h2 * (safmin / f2) <= h2 <= safmax r = f * ( h2 / d ) end if s = conjg( g ) * ( f / d ) end if else ! ! Use scaled algorithm ! u = min( safmax, max( safmin, f1, g1 ) ) gs = g / u g2 = ABSSQ( gs ) if( f1 / u < rtmin ) then ! ! f is not well-scaled when scaled by g1. ! Use a different scaling for f. ! v = min( safmax, max( safmin, f1 ) ) w = v / u fs = f / v f2 = ABSSQ( fs ) h2 = f2*w**2 + g2 else ! ! Otherwise use the same scaling for f and g. ! w = one fs = f / u f2 = ABSSQ( fs ) h2 = f2 + g2 end if ! safmin <= f2 <= h2 <= safmax if( f2 >= h2 * safmin ) then ! safmin <= f2/h2 <= 1, and h2/f2 is finite c = sqrt( f2 / h2 ) r = fs / c rtmax = rtmax * 2 if( f2 > rtmin .and. h2 < rtmax ) then ! safmin <= sqrt( f2*h2 ) <= safmax s = conjg( gs ) * ( fs / sqrt( f2*h2 ) ) else s = conjg( gs ) * ( r / h2 ) end if else ! f2/h2 <= safmin may be subnormal, and h2/f2 may overflow. ! Moreover, ! safmin <= f2*f2 * safmax < f2 * h2 < h2*h2 * safmin <= safmax, ! sqrt(safmin) <= sqrt(f2 * h2) <= sqrt(safmax). ! Also, ! g2 >> f2, which means that h2 = g2. d = sqrt( f2 * h2 ) c = f2 / d if( c >= safmin ) then r = fs / c else ! f2 / sqrt(f2 * h2) < safmin, then ! sqrt(safmin) <= f2 * sqrt(safmax) <= h2 / sqrt(f2 * h2) <= h2 * (safmin / f2) <= h2 <= safmax r = fs * ( h2 / d ) end if s = conjg( gs ) * ( fs / d ) end if ! Rescale c and r c = c * w r = r * u end if end if a = r return end subroutine
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/cscal.f
*> \brief \b CSCAL * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CSCAL(N,CA,CX,INCX) * * .. Scalar Arguments .. * COMPLEX CA * INTEGER INCX,N * .. * .. Array Arguments .. * COMPLEX CX(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CSCAL scales a vector by a constant. *> \endverbatim * * Arguments: * ========== * *> \param[in] N *> \verbatim *> N is INTEGER *> number of elements in input vector(s) *> \endverbatim *> *> \param[in] CA *> \verbatim *> CA is COMPLEX *> On entry, CA specifies the scalar alpha. *> \endverbatim *> *> \param[in,out] CX *> \verbatim *> CX is COMPLEX array, dimension ( 1 + ( N - 1 )*abs( INCX ) ) *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> storage spacing between elements of CX *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup scal * *> \par Further Details: * ===================== *> *> \verbatim *> *> jack dongarra, linpack, 3/11/78. *> modified 3/93 to return if incx .le. 0. *> modified 12/3/93, array(1) declarations changed to array(*) *> \endverbatim *> * ===================================================================== SUBROUTINE CSCAL(N,CA,CX,INCX) * * -- Reference BLAS level1 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. COMPLEX CA INTEGER INCX,N * .. * .. Array Arguments .. COMPLEX CX(*) * .. * * ===================================================================== * * .. Local Scalars .. INTEGER I,NINCX * .. * .. Parameters .. COMPLEX ONE PARAMETER (ONE= (1.0E+0,0.0E+0)) * .. IF (N.LE.0 .OR. INCX.LE.0 .OR. CA.EQ.ONE) RETURN IF (INCX.EQ.1) THEN * * code for increment equal to 1 * DO I = 1,N CX(I) = CA*CX(I) END DO ELSE * * code for increment not equal to 1 * NINCX = N*INCX DO I = 1,NINCX,INCX CX(I) = CA*CX(I) END DO END IF RETURN * * End of CSCAL * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/csrot.f
*> \brief \b CSROT * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CSROT( N, CX, INCX, CY, INCY, C, S ) * * .. Scalar Arguments .. * INTEGER INCX, INCY, N * REAL C, S * .. * .. Array Arguments .. * COMPLEX CX( * ), CY( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CSROT applies a plane rotation, where the cos and sin (c and s) are real *> and the vectors cx and cy are complex. *> jack dongarra, linpack, 3/11/78. *> \endverbatim * * Arguments: * ========== * *> \param[in] N *> \verbatim *> N is INTEGER *> On entry, N specifies the order of the vectors cx and cy. *> N must be at least zero. *> \endverbatim *> *> \param[in,out] CX *> \verbatim *> CX is COMPLEX array, dimension at least *> ( 1 + ( N - 1 )*abs( INCX ) ). *> Before entry, the incremented array CX must contain the n *> element vector cx. On exit, CX is overwritten by the updated *> vector cx. *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> On entry, INCX specifies the increment for the elements of *> CX. INCX must not be zero. *> \endverbatim *> *> \param[in,out] CY *> \verbatim *> CY is COMPLEX array, dimension at least *> ( 1 + ( N - 1 )*abs( INCY ) ). *> Before entry, the incremented array CY must contain the n *> element vector cy. On exit, CY is overwritten by the updated *> vector cy. *> \endverbatim *> *> \param[in] INCY *> \verbatim *> INCY is INTEGER *> On entry, INCY specifies the increment for the elements of *> CY. INCY must not be zero. *> \endverbatim *> *> \param[in] C *> \verbatim *> C is REAL *> On entry, C specifies the cosine, cos. *> \endverbatim *> *> \param[in] S *> \verbatim *> S is REAL *> On entry, S specifies the sine, sin. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup rot * * ===================================================================== SUBROUTINE CSROT( N, CX, INCX, CY, INCY, C, S ) * * -- Reference BLAS level1 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. INTEGER INCX, INCY, N REAL C, S * .. * .. Array Arguments .. COMPLEX CX( * ), CY( * ) * .. * * ===================================================================== * * .. Local Scalars .. INTEGER I, IX, IY COMPLEX CTEMP * .. * .. Executable Statements .. * IF( N.LE.0 ) $ RETURN IF( INCX.EQ.1 .AND. INCY.EQ.1 ) THEN * * code for both increments equal to 1 * DO I = 1, N CTEMP = C*CX( I ) + S*CY( I ) CY( I ) = C*CY( I ) - S*CX( I ) CX( I ) = CTEMP END DO ELSE * * code for unequal increments or equal increments not equal * to 1 * IX = 1 IY = 1 IF( INCX.LT.0 ) $ IX = ( -N+1 )*INCX + 1 IF( INCY.LT.0 ) $ IY = ( -N+1 )*INCY + 1 DO I = 1, N CTEMP = C*CX( IX ) + S*CY( IY ) CY( IY ) = C*CY( IY ) - S*CX( IX ) CX( IX ) = CTEMP IX = IX + INCX IY = IY + INCY END DO END IF RETURN * * End of CSROT * END
0
ALLM/M2/lapack/BLAS
ALLM/M2/lapack/BLAS/SRC/csscal.f
*> \brief \b CSSCAL * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CSSCAL(N,SA,CX,INCX) * * .. Scalar Arguments .. * REAL SA * INTEGER INCX,N * .. * .. Array Arguments .. * COMPLEX CX(*) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CSSCAL scales a complex vector by a real constant. *> \endverbatim * * Arguments: * ========== * *> \param[in] N *> \verbatim *> N is INTEGER *> number of elements in input vector(s) *> \endverbatim *> *> \param[in] SA *> \verbatim *> SA is REAL *> On entry, SA specifies the scalar alpha. *> \endverbatim *> *> \param[in,out] CX *> \verbatim *> CX is COMPLEX array, dimension ( 1 + ( N - 1 )*abs( INCX ) ) *> \endverbatim *> *> \param[in] INCX *> \verbatim *> INCX is INTEGER *> storage spacing between elements of CX *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \ingroup scal * *> \par Further Details: * ===================== *> *> \verbatim *> *> jack dongarra, linpack, 3/11/78. *> modified 3/93 to return if incx .le. 0. *> modified 12/3/93, array(1) declarations changed to array(*) *> \endverbatim *> * ===================================================================== SUBROUTINE CSSCAL(N,SA,CX,INCX) * * -- Reference BLAS level1 routine -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * * .. Scalar Arguments .. REAL SA INTEGER INCX,N * .. * .. Array Arguments .. COMPLEX CX(*) * .. * * ===================================================================== * * .. Local Scalars .. INTEGER I,NINCX * .. * .. Parameters .. REAL ONE PARAMETER (ONE=1.0E+0) * .. * .. Intrinsic Functions .. INTRINSIC AIMAG,CMPLX,REAL * .. IF (N.LE.0 .OR. INCX.LE.0 .OR. SA.EQ.ONE) RETURN IF (INCX.EQ.1) THEN * * code for increment equal to 1 * DO I = 1,N CX(I) = CMPLX(SA*REAL(CX(I)),SA*AIMAG(CX(I))) END DO ELSE * * code for increment not equal to 1 * NINCX = N*INCX DO I = 1,NINCX,INCX CX(I) = CMPLX(SA*REAL(CX(I)),SA*AIMAG(CX(I))) END DO END IF RETURN * * End of CSSCAL * END