source
stringlengths
3
92
c
stringlengths
26
2.25M
poissonSORRB.c
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <math.h> #include <sys/time.h> #include <omp.h> #define TIME_RES 1000 double** w; double** u; double initial_time; double clearcache [30000000]; int iter; double p; double tol; double diff; //número de pontos da grelha int N; void clearCache (){ int i; for(i=0; i<30000000;i++) clearcache[i]=i; } void start(){ double time= omp_get_wtime(); initial_time= time* TIME_RES; } double stop(){ double time = omp_get_wtime(); double final = time * TIME_RES; return final - initial_time; } void initialize_matrices(){ int i, j; u = (double**) malloc(sizeof(double*) * N); w = (double**) malloc(sizeof(double*) * N); // Preencher a matriz com 100 nos limites inferiores e laterais e 50 nos interiores for(i = 0; i < N; i++){ w[i] = (double*) malloc(sizeof(double) * N); u[i] = (double*) malloc(sizeof(double) * N); for(j = 0; j < N; j++){ u[i][j]=0; //Inicializar a matriz u a zeros if(i == N-1 || (j == 0 && i!=0) || (j == N-1 && i != 0)){ //fronteiras inferiores e laterais w[i][j] = 100; }else{ if(i ==0){ w[i][j] = 0; //valores do limite superior }else { w[i][j] = 50; //valores iniciais dos pontos interiores } } } } } // Dar print da matriz w void print_matrix(){ int i, j; for(i = 0; i < N; i++){ for(j = 0; j < N; j++){ printf("%f ", w[i][j]); } printf("\n"); } } void free_matrices(){ free(u); free(w); } //funcao que calcula a diferenca entre 2 vetores e guarda o resultado noutro vetor double** diferenca(double** a, double** b){ double** result = (double**) malloc(N * sizeof(double)); int i, j; for(i = 0; i < N; i++){ result[i] = (double*) malloc(N * sizeof(double*)); for(j = 0; j < N; j++){ result[i][j] = a[i][j] - b[i][j]; } } return result; } //funcao que retorna um vetor bi-dimensional com o valor absoluto de cada elemento double** absol(double** vetor){ int i, j; for(i = 0; i < N; i++){ for(j = 0; j < N; j++){ vetor[i][j] = fabs(vetor[i][j]); } } return vetor; } //funcao que retorna o maior elemento de um vetor double maximum(double** vetor){ double max = 0; int i, j; for(i = 0; i < N; i++){ for(j = 0; j < N; j++){ if(vetor[i][j] > max) max = vetor[i][j]; } } return max; } void iguala(double **a, double**b){ int i, j; for(i = 0; i < N; i++){ for(j = 0; j < N; j++){ a[i][j] = b[i][j]; } } } void parallel(int threads){ int i,j; while(diff > tol){ iguala(u,w); #pragma omp parallel for private(i,j) schedule(static) num_threads(threads) for(i = 1; i < N-1; i++){ for(j = 1 + (i%2); j < N-1; j += 2){ #pragma omp atomic write w[i][j] = (1-p) * w[i][j] + p * (w[i-1][j] + w[i][j-1] + w[i][j+1] + w[i+1][j])/4; } } #pragma omp parallel for private(i,j) schedule(static) num_threads(threads) for(i = 1; i < N-1; i++){ for(j = 1 + ((i+1)%2); j < N-1; j += 2){ #pragma omp atomic write w[i][j] = (1-p) * w[i][j] + p * (w[i-1][j] + w[i][j-1] + w[i][j+1] + w[i+1][j])/4; } } iter++; diff = maximum(absol(diferenca(w,u))); } } int main(int argc, char* argv[]){ if(argc != 3){ printf ("Usage : ./ poissonSORRB <nr pontos da grelha> <numero threads>\n"); return 0; } N = atoi(argv[1]); int threads = atoi(argv[2]); int i, j; clearCache(); // Preparar as matrizes para aplicar o algoritmo initialize_matrices(); // print_matrix(); // parâmetro de relaxamento p = 2/(1 + sin(M_PI/(N-1))); tol = 1/(double)(N*N); diff = (tol + 1); iter = 0; FILE* fp = fopen("results/resultados.csv","a"); start(); parallel(threads); double tempo = stop(); //print_matrix(); fprintf(fp,"%d,%d,%2f,%d,%2f\n", N, threads, tol, iter, tempo); fclose(fp); free_matrices(); return 0; }
compare.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO M M PPPP AAA RRRR EEEEE % % C O O MM MM P P A A R R E % % C O O M M M PPPP AAAAA RRRR EEE % % C O O M M P A A R R E % % CCCC OOO M M P A A R R EEEEE % % % % % % MagickCore Image Comparison Methods % % % % Software Design % % Cristy % % December 2003 % % % % % % Copyright 1999-2014 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/compare.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/statistic.h" #include "MagickCore/thread-private.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p a r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImages() compares one or more pixel channels of an image to a % reconstructed image and returns the difference image. % % The format of the CompareImages method is: % % Image *CompareImages(const Image *image,const Image *reconstruct_image, % const MetricType metric,double *distortion,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o metric: the metric. % % o distortion: the computed distortion between the images. % % o exception: return any errors or warnings in this structure. % */ static size_t GetImageChannels(const Image *image) { register ssize_t i; size_t channels; channels=0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) != 0) channels++; } return(channels == 0 ? 1 : channels); } static inline MagickBooleanType ValidateImageMorphology( const Image *restrict image,const Image *restrict reconstruct_image) { /* Does the image match the reconstructed image morphology? */ return(MagickTrue); } MagickExport Image *CompareImages(Image *image,const Image *reconstruct_image, const MetricType metric,double *distortion,ExceptionInfo *exception) { CacheView *highlight_view, *image_view, *reconstruct_view; const char *artifact; Image *difference_image, *highlight_image; MagickBooleanType status; PixelInfo highlight, lowlight; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickSignature); assert(distortion != (double *) NULL); *distortion=0.0; if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (metric != PerceptualHashErrorMetric) if (ValidateImageMorphology(image,reconstruct_image) == MagickFalse) ThrowImageException(ImageError,"ImageMorphologyDiffers"); status=GetImageDistortion(image,reconstruct_image,metric,distortion, exception); if (status == MagickFalse) return((Image *) NULL); difference_image=CloneImage(image,0,0,MagickTrue,exception); if (difference_image == (Image *) NULL) return((Image *) NULL); (void) SetImageAlphaChannel(difference_image,OpaqueAlphaChannel,exception); highlight_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (highlight_image == (Image *) NULL) { difference_image=DestroyImage(difference_image); return((Image *) NULL); } status=SetImageStorageClass(highlight_image,DirectClass,exception); if (status == MagickFalse) { difference_image=DestroyImage(difference_image); highlight_image=DestroyImage(highlight_image); return((Image *) NULL); } (void) SetImageAlphaChannel(highlight_image,OpaqueAlphaChannel,exception); (void) QueryColorCompliance("#f1001ecc",AllCompliance,&highlight,exception); artifact=GetImageArtifact(image,"highlight-color"); if (artifact != (const char *) NULL) (void) QueryColorCompliance(artifact,AllCompliance,&highlight,exception); (void) QueryColorCompliance("#ffffffcc",AllCompliance,&lowlight,exception); artifact=GetImageArtifact(image,"lowlight-color"); if (artifact != (const char *) NULL) (void) QueryColorCompliance(artifact,AllCompliance,&lowlight,exception); /* Generate difference image. */ status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); highlight_view=AcquireAuthenticCacheView(highlight_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,highlight_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const Quantum *restrict p, *restrict q; register Quantum *restrict r; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,image->columns,1, exception); r=QueueCacheViewAuthenticPixels(highlight_view,0,y,highlight_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL) || (r == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double Da, Sa; MagickStatusType difference; register ssize_t i; if (GetPixelReadMask(image,p) == 0) { SetPixelInfoPixel(highlight_image,&lowlight,r); p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); r+=GetPixelChannels(highlight_image); continue; } difference=MagickFalse; Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; distance=Sa*p[i]-Da*GetPixelChannel(reconstruct_image,channel,q); if (fabs(distance) >= MagickEpsilon) difference=MagickTrue; } if (difference == MagickFalse) SetPixelInfoPixel(highlight_image,&lowlight,r); else SetPixelInfoPixel(highlight_image,&highlight,r); p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); r+=GetPixelChannels(highlight_image); } sync=SyncCacheViewAuthenticPixels(highlight_view,exception); if (sync == MagickFalse) status=MagickFalse; } highlight_view=DestroyCacheView(highlight_view); reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); (void) CompositeImage(difference_image,highlight_image,image->compose, MagickTrue,0,0,exception); highlight_image=DestroyImage(highlight_image); if (status == MagickFalse) difference_image=DestroyImage(difference_image); return(difference_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e D i s t o r t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageDistortion() compares one or more pixel channels of an image to a % reconstructed image and returns the specified distortion metric. % % The format of the GetImageDistortion method is: % % MagickBooleanType GetImageDistortion(const Image *image, % const Image *reconstruct_image,const MetricType metric, % double *distortion,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o metric: the metric. % % o distortion: the computed distortion between the images. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickMax(const double x,const double y) { if (x > y) return(x); return(y); } static MagickBooleanType GetAbsoluteDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; double fuzz; MagickBooleanType status; ssize_t y; /* Compute the absolute difference in pixels between two images. */ status=MagickTrue; if (image->fuzz == 0.0) fuzz=MagickMax(reconstruct_image->fuzz,MagickSQ1_2)* MagickMax(reconstruct_image->fuzz,MagickSQ1_2); else if (reconstruct_image->fuzz == 0.0) fuzz=MagickMax(image->fuzz,MagickSQ1_2)* MagickMax(image->fuzz,MagickSQ1_2); else fuzz=MagickMax(image->fuzz,MagickSQ1_2)* MagickMax(reconstruct_image->fuzz,MagickSQ1_2); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_distortion[MaxPixelChannels+1]; register const Quantum *restrict p, *restrict q; register ssize_t i, x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,reconstruct_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) image->columns; x++) { double Da, Sa; MagickBooleanType difference; register ssize_t i; if (GetPixelReadMask(image,p) == 0) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } difference=MagickFalse; Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; distance=Sa*p[i]-Da*GetPixelChannel(reconstruct_image,channel,q); if ((distance*distance) > fuzz) { difference=MagickTrue; break; } } if (difference != MagickFalse) { channel_distortion[i]++; channel_distortion[CompositePixelChannel]++; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetAbsoluteError) #endif for (i=0; i <= MaxPixelChannels; i++) distortion[i]+=channel_distortion[i]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType GetFuzzDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; MagickBooleanType status; register ssize_t i; ssize_t y; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_distortion[MaxPixelChannels+1]; register const Quantum *restrict p, *restrict q; register ssize_t i, x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,reconstruct_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } (void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) image->columns; x++) { double Da, Sa; register ssize_t i; if (GetPixelReadMask(image,p) == 0) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; distance=QuantumScale*(Sa*p[i]-Da*GetPixelChannel(reconstruct_image, channel,q)); channel_distortion[i]+=distance*distance; channel_distortion[CompositePixelChannel]+=distance*distance; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetFuzzDistortion) #endif for (i=0; i <= MaxPixelChannels; i++) distortion[i]+=channel_distortion[i]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); for (i=0; i <= MaxPixelChannels; i++) distortion[i]/=((double) image->columns*image->rows); distortion[CompositePixelChannel]/=(double) GetImageChannels(image); distortion[CompositePixelChannel]=sqrt(distortion[CompositePixelChannel]); return(status); } static MagickBooleanType GetMeanAbsoluteDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; MagickBooleanType status; register ssize_t i; ssize_t y; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_distortion[MaxPixelChannels+1]; register const Quantum *restrict p, *restrict q; register ssize_t i, x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,reconstruct_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) image->columns; x++) { double Da, Sa; register ssize_t i; if (GetPixelReadMask(image,p) == 0) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; distance=QuantumScale*fabs(Sa*p[i]-Da*GetPixelChannel(reconstruct_image, channel,q)); channel_distortion[i]+=distance; channel_distortion[CompositePixelChannel]+=distance; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetMeanAbsoluteError) #endif for (i=0; i <= MaxPixelChannels; i++) distortion[i]+=channel_distortion[i]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); for (i=0; i <= MaxPixelChannels; i++) distortion[i]/=((double) image->columns*image->rows); distortion[CompositePixelChannel]/=(double) GetImageChannels(image); return(status); } static MagickBooleanType GetMeanErrorPerPixel(Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; MagickBooleanType status; double area, maximum_error, mean_error; ssize_t y; status=MagickTrue; area=0.0; maximum_error=0.0; mean_error=0.0; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *restrict p, *restrict q; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,reconstruct_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { double Da, Sa; register ssize_t i; if (GetPixelReadMask(image,p) == 0) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; distance=fabs(Sa*p[i]-Da*GetPixelChannel(reconstruct_image,channel,q)); distortion[i]+=distance; distortion[CompositePixelChannel]+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; area++; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); image->error.mean_error_per_pixel=distortion[CompositePixelChannel]/area; image->error.normalized_mean_error=QuantumScale*QuantumScale*mean_error/area; image->error.normalized_maximum_error=QuantumScale*maximum_error; return(status); } static MagickBooleanType GetMeanSquaredDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; MagickBooleanType status; register ssize_t i; ssize_t y; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_distortion[MaxPixelChannels+1]; register const Quantum *restrict p, *restrict q; register ssize_t i, x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,reconstruct_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) image->columns; x++) { double Da, Sa; register ssize_t i; if (GetPixelReadMask(image,p) == 0) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; distance=QuantumScale*(Sa*p[i]-Da*GetPixelChannel(reconstruct_image, channel,q)); channel_distortion[i]+=distance*distance; channel_distortion[CompositePixelChannel]+=distance*distance; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetMeanSquaredError) #endif for (i=0; i <= MaxPixelChannels; i++) distortion[i]+=channel_distortion[i]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); for (i=0; i <= MaxPixelChannels; i++) distortion[i]/=((double) image->columns*image->rows); distortion[CompositePixelChannel]/=GetImageChannels(image); return(status); } static MagickBooleanType GetNormalizedCrossCorrelationDistortion( const Image *image,const Image *reconstruct_image,double *distortion, ExceptionInfo *exception) { #define SimilarityImageTag "Similarity/Image" CacheView *image_view, *reconstruct_view; ChannelStatistics *image_statistics, *reconstruct_statistics; double area; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Normalize to account for variation due to lighting and exposure condition. */ image_statistics=GetImageStatistics(image,exception); reconstruct_statistics=GetImageStatistics(reconstruct_image,exception); if ((image_statistics == (ChannelStatistics *) NULL) || (reconstruct_statistics == (ChannelStatistics *) NULL)) { if (image_statistics != (ChannelStatistics *) NULL) image_statistics=(ChannelStatistics *) RelinquishMagickMemory( image_statistics); if (reconstruct_statistics != (ChannelStatistics *) NULL) reconstruct_statistics=(ChannelStatistics *) RelinquishMagickMemory( reconstruct_statistics); return(MagickFalse); } status=MagickTrue; progress=0; for (i=0; i <= MaxPixelChannels; i++) distortion[i]=0.0; area=1.0/((double) image->columns*image->rows); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *restrict p, *restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,reconstruct_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double Da, Sa; register ssize_t i; if (GetPixelReadMask(image,p) == 0) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; distortion[i]+=area*QuantumScale*(Sa*p[i]-image_statistics[i].mean)* (Da*GetPixelChannel(reconstruct_image,channel,q)- reconstruct_statistics[channel].mean); } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,SimilarityImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); /* Divide by the standard deviation. */ distortion[CompositePixelChannel]=0.0; for (i=0; i < MaxPixelChannels; i++) { double gamma; PixelChannel channel=GetPixelChannelChannel(image,i); gamma=image_statistics[i].standard_deviation* reconstruct_statistics[channel].standard_deviation; gamma=PerceptibleReciprocal(gamma); distortion[i]=QuantumRange*gamma*distortion[i]; distortion[CompositePixelChannel]+=distortion[i]*distortion[i]; } distortion[CompositePixelChannel]=sqrt(distortion[CompositePixelChannel]/ GetImageChannels(image)); /* Free resources. */ reconstruct_statistics=(ChannelStatistics *) RelinquishMagickMemory( reconstruct_statistics); image_statistics=(ChannelStatistics *) RelinquishMagickMemory( image_statistics); return(status); } static MagickBooleanType GetPeakAbsoluteDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_distortion[MaxPixelChannels+1]; register const Quantum *restrict p, *restrict q; register ssize_t i, x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,reconstruct_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) image->columns; x++) { double Da, Sa; register ssize_t i; if (GetPixelReadMask(image,p) == 0) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; distance=QuantumScale*fabs(Sa*p[i]-Da*GetPixelChannel(reconstruct_image, channel,q)); if (distance > channel_distortion[i]) channel_distortion[i]=distance; if (distance > channel_distortion[CompositePixelChannel]) channel_distortion[CompositePixelChannel]=distance; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetPeakAbsoluteError) #endif for (i=0; i <= MaxPixelChannels; i++) if (channel_distortion[i] > distortion[i]) distortion[i]=channel_distortion[i]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); return(status); } static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } static MagickBooleanType GetPeakSignalToNoiseRatio(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { MagickBooleanType status; register ssize_t i; status=GetMeanSquaredDistortion(image,reconstruct_image,distortion,exception); for (i=0; i <= MaxPixelChannels; i++) distortion[i]=20.0*MagickLog10((double) 1.0/sqrt(distortion[i])); return(status); } static MagickBooleanType GetPerceptualHashDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { ChannelPerceptualHash *image_phash, *reconstruct_phash; ssize_t channel; /* Compute perceptual hash in the sRGB colorspace. */ image_phash=GetImagePerceptualHash(image,exception); if (image_phash == (ChannelPerceptualHash *) NULL) return(MagickFalse); reconstruct_phash=GetImagePerceptualHash(reconstruct_image,exception); if (reconstruct_phash == (ChannelPerceptualHash *) NULL) { image_phash=(ChannelPerceptualHash *) RelinquishMagickMemory(image_phash); return(MagickFalse); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) #endif for (channel=0; channel < MaxPixelChannels; channel++) { double difference; register ssize_t i; difference=0.0; for (i=0; i < MaximumNumberOfImageMoments; i++) { double alpha, beta; alpha=image_phash[channel].srgb_hu_phash[i]; beta=reconstruct_phash[channel].srgb_hu_phash[i]; difference+=(beta-alpha)*(beta-alpha); } distortion[channel]+=difference; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetPerceptualHashDistortion) #endif distortion[CompositePixelChannel]+=difference; } /* Compute perceptual hash in the HCLP colorspace. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) #endif for (channel=0; channel < MaxPixelChannels; channel++) { double difference; register ssize_t i; difference=0.0; for (i=0; i < MaximumNumberOfImageMoments; i++) { double alpha, beta; alpha=image_phash[channel].hclp_hu_phash[i]; beta=reconstruct_phash[channel].hclp_hu_phash[i]; difference+=(beta-alpha)*(beta-alpha); } distortion[channel]+=difference; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetPerceptualHashDistortion) #endif distortion[CompositePixelChannel]+=difference; } /* Free resources. */ reconstruct_phash=(ChannelPerceptualHash *) RelinquishMagickMemory( reconstruct_phash); image_phash=(ChannelPerceptualHash *) RelinquishMagickMemory(image_phash); return(MagickTrue); } static MagickBooleanType GetRootMeanSquaredDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { MagickBooleanType status; register ssize_t i; status=GetMeanSquaredDistortion(image,reconstruct_image,distortion,exception); for (i=0; i <= MaxPixelChannels; i++) distortion[i]=sqrt(distortion[i]); return(status); } MagickExport MagickBooleanType GetImageDistortion(Image *image, const Image *reconstruct_image,const MetricType metric,double *distortion, ExceptionInfo *exception) { double *channel_distortion; MagickBooleanType status; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickSignature); assert(distortion != (double *) NULL); *distortion=0.0; if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (metric != PerceptualHashErrorMetric) if (ValidateImageMorphology(image,reconstruct_image) == MagickFalse) ThrowBinaryException(ImageError,"ImageMorphologyDiffers",image->filename); /* Get image distortion. */ length=MaxPixelChannels+1; channel_distortion=(double *) AcquireQuantumMemory(length, sizeof(*channel_distortion)); if (channel_distortion == (double *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(channel_distortion,0,length* sizeof(*channel_distortion)); switch (metric) { case AbsoluteErrorMetric: { status=GetAbsoluteDistortion(image,reconstruct_image,channel_distortion, exception); break; } case FuzzErrorMetric: { status=GetFuzzDistortion(image,reconstruct_image,channel_distortion, exception); break; } case MeanAbsoluteErrorMetric: { status=GetMeanAbsoluteDistortion(image,reconstruct_image, channel_distortion,exception); break; } case MeanErrorPerPixelErrorMetric: { status=GetMeanErrorPerPixel(image,reconstruct_image,channel_distortion, exception); break; } case MeanSquaredErrorMetric: { status=GetMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } case NormalizedCrossCorrelationErrorMetric: default: { status=GetNormalizedCrossCorrelationDistortion(image,reconstruct_image, channel_distortion,exception); break; } case PeakAbsoluteErrorMetric: { status=GetPeakAbsoluteDistortion(image,reconstruct_image, channel_distortion,exception); break; } case PeakSignalToNoiseRatioErrorMetric: { status=GetPeakSignalToNoiseRatio(image,reconstruct_image, channel_distortion,exception); break; } case PerceptualHashErrorMetric: { status=GetPerceptualHashDistortion(image,reconstruct_image, channel_distortion,exception); break; } case RootMeanSquaredErrorMetric: { status=GetRootMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } } *distortion=channel_distortion[CompositePixelChannel]; channel_distortion=(double *) RelinquishMagickMemory(channel_distortion); (void) FormatImageProperty(image,"distortion","%.*g",GetMagickPrecision(), *distortion); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e D i s t o r t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageDistortions() compares the pixel channels of an image to a % reconstructed image and returns the specified distortion metric for each % channel. % % The format of the GetImageDistortions method is: % % double *GetImageDistortions(const Image *image, % const Image *reconstruct_image,const MetricType metric, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o metric: the metric. % % o exception: return any errors or warnings in this structure. % */ MagickExport double *GetImageDistortions(Image *image, const Image *reconstruct_image,const MetricType metric, ExceptionInfo *exception) { double *channel_distortion; MagickBooleanType status; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (metric != PerceptualHashErrorMetric) if (ValidateImageMorphology(image,reconstruct_image) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageMorphologyDiffers","`%s'",image->filename); return((double *) NULL); } /* Get image distortion. */ length=MaxPixelChannels+1UL; channel_distortion=(double *) AcquireQuantumMemory(length, sizeof(*channel_distortion)); if (channel_distortion == (double *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(channel_distortion,0,length* sizeof(*channel_distortion)); status=MagickTrue; switch (metric) { case AbsoluteErrorMetric: { status=GetAbsoluteDistortion(image,reconstruct_image,channel_distortion, exception); break; } case FuzzErrorMetric: { status=GetFuzzDistortion(image,reconstruct_image,channel_distortion, exception); break; } case MeanAbsoluteErrorMetric: { status=GetMeanAbsoluteDistortion(image,reconstruct_image, channel_distortion,exception); break; } case MeanErrorPerPixelErrorMetric: { status=GetMeanErrorPerPixel(image,reconstruct_image,channel_distortion, exception); break; } case MeanSquaredErrorMetric: { status=GetMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } case NormalizedCrossCorrelationErrorMetric: default: { status=GetNormalizedCrossCorrelationDistortion(image,reconstruct_image, channel_distortion,exception); break; } case PeakAbsoluteErrorMetric: { status=GetPeakAbsoluteDistortion(image,reconstruct_image, channel_distortion,exception); break; } case PeakSignalToNoiseRatioErrorMetric: { status=GetPeakSignalToNoiseRatio(image,reconstruct_image, channel_distortion,exception); break; } case PerceptualHashErrorMetric: { status=GetRootMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } case RootMeanSquaredErrorMetric: { status=GetRootMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } } if (status == MagickFalse) { channel_distortion=(double *) RelinquishMagickMemory(channel_distortion); return((double *) NULL); } return(channel_distortion); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s I m a g e s E q u a l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsImagesEqual() measures the difference between colors at each pixel % location of two images. A value other than 0 means the colors match % exactly. Otherwise an error measure is computed by summing over all % pixels in an image the distance squared in RGB space between each image % pixel and its corresponding pixel in the reconstruct image. The error % measure is assigned to these image members: % % o mean_error_per_pixel: The mean error for any single pixel in % the image. % % o normalized_mean_error: The normalized mean quantization error for % any single pixel in the image. This distance measure is normalized to % a range between 0 and 1. It is independent of the range of red, green, % and blue values in the image. % % o normalized_maximum_error: The normalized maximum quantization % error for any single pixel in the image. This distance measure is % normalized to a range between 0 and 1. It is independent of the range % of red, green, and blue values in your image. % % A small normalized mean square error, accessed as % image->normalized_mean_error, suggests the images are very similar in % spatial layout and color. % % The format of the IsImagesEqual method is: % % MagickBooleanType IsImagesEqual(Image *image, % const Image *reconstruct_image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsImagesEqual(Image *image, const Image *reconstruct_image,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; MagickBooleanType status; double area, maximum_error, mean_error, mean_error_per_pixel; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickSignature); if (ValidateImageMorphology(image,reconstruct_image) == MagickFalse) ThrowBinaryException(ImageError,"ImageMorphologyDiffers",image->filename); area=0.0; maximum_error=0.0; mean_error_per_pixel=0.0; mean_error=0.0; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *restrict p, *restrict q; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,reconstruct_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelReadMask(image,p) == 0) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; distance=fabs(p[i]-(double) GetPixelChannel(reconstruct_image, channel,q)); if (distance >= MagickEpsilon) { mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; } area++; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); image->error.mean_error_per_pixel=(double) (mean_error_per_pixel/area); image->error.normalized_mean_error=(double) (QuantumScale*QuantumScale* mean_error/area); image->error.normalized_maximum_error=(double) (QuantumScale*maximum_error); status=image->error.mean_error_per_pixel == 0.0 ? MagickTrue : MagickFalse; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S i m i l a r i t y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SimilarityImage() compares the reference image of the image and returns the % best match offset. In addition, it returns a similarity image such that an % exact match location is completely white and if none of the pixels match, % black, otherwise some gray level in-between. % % The format of the SimilarityImageImage method is: % % Image *SimilarityImage(const Image *image,const Image *reference, % const MetricType metric,const double similarity_threshold, % RectangleInfo *offset,double *similarity,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reference: find an area of the image that closely resembles this image. % % o metric: the metric. % % o similarity_threshold: minimum distortion for (sub)image match. % % o offset: the best match offset of the reference image within the image. % % o similarity: the computed similarity between the images. % % o exception: return any errors or warnings in this structure. % */ static double GetSimilarityMetric(const Image *image,const Image *reference, const MetricType metric,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { double distortion; Image *similarity_image; MagickBooleanType status; RectangleInfo geometry; SetGeometry(reference,&geometry); geometry.x=x_offset; geometry.y=y_offset; similarity_image=CropImage(image,&geometry,exception); if (similarity_image == (Image *) NULL) return(0.0); distortion=0.0; status=GetImageDistortion(similarity_image,reference,metric,&distortion, exception); similarity_image=DestroyImage(similarity_image); if (status == MagickFalse) return(0.0); return(distortion); } static inline double MagickMin(const double x,const double y) { if (x < y) return(x); return(y); } MagickExport Image *SimilarityImage(Image *image,const Image *reference, const MetricType metric,const double similarity_threshold, RectangleInfo *offset,double *similarity_metric,ExceptionInfo *exception) { #define SimilarityImageTag "Similarity/Image" CacheView *similarity_view; Image *similarity_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); assert(offset != (RectangleInfo *) NULL); SetGeometry(reference,offset); *similarity_metric=MagickMaximumValue; if (ValidateImageMorphology(image,reference) == MagickFalse) ThrowImageException(ImageError,"ImageMorphologyDiffers"); similarity_image=CloneImage(image,image->columns-reference->columns+1, image->rows-reference->rows+1,MagickTrue,exception); if (similarity_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(similarity_image,DirectClass,exception); if (status == MagickFalse) { similarity_image=DestroyImage(similarity_image); return((Image *) NULL); } (void) SetImageAlphaChannel(similarity_image,DeactivateAlphaChannel, exception); /* Measure similarity of reference image against image. */ status=MagickTrue; progress=0; similarity_view=AcquireAuthenticCacheView(similarity_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ shared(progress,status,similarity_metric) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) (image->rows-reference->rows+1); y++) { double similarity; register Quantum *restrict q; register ssize_t x; if (status == MagickFalse) continue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp flush(similarity_metric) #endif if (*similarity_metric <= similarity_threshold) continue; q=GetCacheViewAuthenticPixels(similarity_view,0,y,similarity_image->columns, 1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) (image->columns-reference->columns+1); x++) { register ssize_t i; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp flush(similarity_metric) #endif if (*similarity_metric <= similarity_threshold) break; similarity=GetSimilarityMetric(image,reference,metric,x,y,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SimilarityImage) #endif if (similarity < *similarity_metric) { offset->x=x; offset->y=y; *similarity_metric=similarity; } if (metric == PerceptualHashErrorMetric) similarity=MagickMin(0.01*similarity,1.0); if (GetPixelReadMask(similarity_image,q) == 0) { SetPixelBackgoundColor(similarity_image,q); q+=GetPixelChannels(similarity_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(similarity_image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait similarity_traits=GetPixelChannelTraits(similarity_image, channel); if ((traits == UndefinedPixelTrait) || (similarity_traits == UndefinedPixelTrait) || ((similarity_traits & UpdatePixelTrait) == 0)) continue; SetPixelChannel(similarity_image,channel,ClampToQuantum(QuantumRange- QuantumRange*similarity),q); } q+=GetPixelChannels(similarity_image); } if (SyncCacheViewAuthenticPixels(similarity_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SimilarityImage) #endif proceed=SetImageProgress(image,SimilarityImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } similarity_view=DestroyCacheView(similarity_view); if (status == MagickFalse) similarity_image=DestroyImage(similarity_image); return(similarity_image); }
scaledAdd.c
extern "C" void FUNC(scaledAdd) (const dlong & N, const pfloat & alpha, const pfloat * __restrict__ x, const pfloat & beta, pfloat * __restrict__ y){ #ifdef __NEKRS__OMP__ #pragma omp parallel for #endif for(dlong n = 0; n < N; ++n){ y[n] = alpha*x[n] + beta*y[n]; } }
util.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> void read_matrix(int** index, int** matrix, double scaling, int N_kw, char* input_fileName) { FILE *fp = fopen(input_fileName, "r"); fscanf(fp, "%*[^\n]\n"); for (int ii = 0; ii < N_kw; ii++) fscanf(fp, "%d,", &((*index)[ii])); fscanf(fp, "%*[^\n]\n"); int tmp; for (int ii = 0; ii < N_kw; ii++) { for (int jj = 0; jj < N_kw; jj++) { fscanf(fp, "%d,", &tmp); (*matrix)[ii*N_kw + jj] = (int) (tmp * scaling); } fscanf(fp, "%*[^\n]\n"); } fclose(fp); } void pad_matrix(int** matrix_padded, int** matrix, int N_kw, int N_doc, double sec_budget, int fixed_padding) { // Initialising RNG const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); // perform padding on the keywords int ii, jj; #pragma omp parallel for private(ii) for (int ii = 0; ii < N_kw; ii++) (*matrix_padded)[ii*N_kw + ii] = 2 * (*matrix)[ii*N_kw + ii] + fixed_padding + (int) gsl_ran_laplace(r, 2.0/sec_budget); // perform padding #pragma omp parallel for private(ii, jj) for (ii = 0; ii < N_kw; ii++) { for (jj = 0; jj < N_kw; jj++) { if (ii > jj) { int n1 = (*matrix_padded)[ii*N_kw + ii] - (*matrix)[ii*N_kw + ii]; int n2 = (*matrix_padded)[jj*N_kw + jj] - (*matrix)[jj*N_kw + jj]; int x1 = gsl_ran_hypergeometric(r, n1, 2*N_doc-n1, (*matrix_padded)[jj*N_kw + jj]); int x2 = gsl_ran_hypergeometric(r, n2, 2*N_doc-n2, (*matrix_padded)[ii*N_kw + ii]); (*matrix_padded)[ii*N_kw + jj] = (*matrix)[ii*N_kw + jj] + x1 + x2; (*matrix_padded)[jj*N_kw + ii] = (*matrix_padded)[ii*N_kw + jj]; } } } gsl_rng_free(r); } void observe_matrix(gsl_matrix* matrix_obs, int** matrix_padded, int N_kw) { // perform observed count generation for (int ii = 0; ii < N_kw; ii++) for (int jj = 0; jj < N_kw; jj++) gsl_matrix_set(matrix_obs, ii, jj, (double) ((*matrix_padded)[ii*N_kw + jj])); } void permutation_generation(int* idx1, int* idx2, int** permutation_tmp, int** permutation, int** permutation_inv, gsl_matrix* matrix_obs, int** matrix, int fixed_padding, int N_kw, int N_obs, int N_doc, double sec_budget) { double N1_lower, N1_upper, N2_lower, N2_upper; int check = -1; int count = 0; *idx1 = rand() % N_obs; *idx2 = -1; int idx_old = (*permutation)[*idx1]; int idx_new = 0; do { idx_new = rand() % N_kw; count++; if ((*permutation_inv)[idx_new] >= 0) { *idx2 = (*permutation_inv)[idx_new]; N1_lower = 2 * (*matrix)[idx_new*N_kw + idx_new] - 4 * sqrt((*matrix)[idx_new*N_kw + idx_new] * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) / N_doc) - 4 / sec_budget + fixed_padding; N1_upper = 2 * (*matrix)[idx_new*N_kw + idx_new] + 4 * sqrt((*matrix)[idx_new*N_kw + idx_new] * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) / N_doc) + 4 / sec_budget + fixed_padding; N2_lower = 2 * (*matrix)[idx_old*N_kw + idx_old] - 4 * sqrt((*matrix)[idx_old*N_kw + idx_old] * (N_doc - (*matrix)[idx_old*N_kw + idx_old]) / N_doc) - 4 / sec_budget + fixed_padding; N2_upper = 2 * (*matrix)[idx_old*N_kw + idx_old] + 4 * sqrt((*matrix)[idx_old*N_kw + idx_old] * (N_doc - (*matrix)[idx_old*N_kw + idx_old]) / N_doc) + 4 / sec_budget + fixed_padding; if ((gsl_matrix_get(matrix_obs, *idx1, *idx1) > N1_lower) && (gsl_matrix_get(matrix_obs, *idx1, *idx1) < N1_upper)) if ((gsl_matrix_get(matrix_obs, *idx2, *idx2) > N2_lower) && (gsl_matrix_get(matrix_obs, *idx2, *idx2) > N2_lower)) check = 1; } else { *idx2 = -1; N1_lower = 2 * (*matrix)[idx_new*N_kw + idx_new] - 4 * sqrt((*matrix)[idx_new*N_kw + idx_new] * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) / N_doc) - 4 / sec_budget + fixed_padding; N1_upper = 2 * (*matrix)[idx_new*N_kw + idx_new] + 4 * sqrt((*matrix)[idx_new*N_kw + idx_new] * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) / N_doc) + 4 / sec_budget + fixed_padding; if ((gsl_matrix_get(matrix_obs, *idx1, *idx1) > N1_lower) && (gsl_matrix_get(matrix_obs, *idx1, *idx1) < N1_upper)) check = 1; } } while ((check < 0) && (count < 200)); if (count == 200) *idx2 = *idx1; if (*idx1 != *idx2) { (*permutation_tmp)[*idx1] = idx_new; if ((*permutation_inv)[idx_new] >= 0) { *idx2 = (*permutation_inv)[idx_new]; (*permutation_tmp)[*idx2] = idx_old; } } }
gep.c
#include <stdio.h> #include "./gep.h" #define CACHE_SIZE 32 /* An implementation of the Gaussian elimination paradigm for simple dynamic programming problems */ uint64_t get_entry(dp_matrix_t* X, uint64_t i, uint64_t j) { if (i > X->width || j > X->height) { return 0; // return 0 if the entry is out of range } return X->entries[j*X->width + i]; } uint64_t* get_entry_addr(dp_matrix_t* X, uint64_t i, uint64_t j) { if (i > X->width || j > X->height) { return NULL; // return NULL if the entry is out of range } return X->entries + j*X->width + i; } void set_entry(dp_matrix_t* X, uint64_t i, uint64_t j, uint64_t value) { if (i >= X->width || j >= X->height) { return; } X->entries[j*X->width + i] = value; } dp_matrix_t* init(uint64_t width, uint64_t height) { dp_matrix_t* X = malloc(sizeof(dp_matrix_t)); uint64_t* matrix = (uint64_t*) calloc(sizeof(uint64_t), width * height); X->width = width; X->height = height; X->entries = matrix; return X; } void iterative(dp_matrix_t* X, uint64_t i_1, uint64_t i_2, uint64_t j_1, uint64_t j_2, uint64_t k_1, uint64_t k_2, UPDATE_F update_f, UPDATE_EXISTS_F update_exists_f) { for (uint64_t k = k_1; k <= k_2; k++) { for (uint64_t i = i_1; i <= i_2; i++) { for (uint64_t j = j_1; j <= j_2; j++) { if (update_exists_f(X->width, i, i, j, j, k, k)) { uint64_t* x = get_entry_addr(X, i, j); uint64_t* u = get_entry_addr(X, i, k); uint64_t* v = get_entry_addr(X, k, j); uint64_t* w = get_entry_addr(X, k, k); set_entry(X, i, j, update_f(x, u, v, w)); } } } } } void recursive_gep(dp_matrix_t* X, uint64_t i_1, uint64_t i_2, uint64_t j_1, uint64_t j_2, uint64_t k_1, uint64_t k_2, UPDATE_F update_f, UPDATE_EXISTS_F update_exists_f) { // printf("%lld %lld %lld %lld %lld %lld\n", i_1, i_2, j_1, j_2, k_1, k_2); if (update_exists_f(X->width, i_1, i_2, j_1, j_2, k_1, k_2) == false || k_2 < k_1 || j_2 < j_1 || i_2 < i_1) { return; } if (k_2 - k_1 < CACHE_SIZE) { // base case iterative(X, i_1, i_2, j_1, j_2, k_1, k_2, update_f, update_exists_f); } else { uint64_t i_m = (i_1 + i_2)/2; uint64_t j_m = (j_1 + j_2)/2; uint64_t k_m = (k_1 + k_2)/2; // forward pass recursive_gep(X, i_1, i_m, j_1, j_m, k_1, k_m, update_f, update_exists_f); recursive_gep(X, i_m + 1, i_2, j_1, j_m, k_1, k_m, update_f, update_exists_f); recursive_gep(X, i_1, i_m, j_m + 1, j_2, k_1, k_m, update_f, update_exists_f); recursive_gep(X, i_m + 1, i_2, j_m + 1, j_2, k_1, k_m, update_f, update_exists_f); // backward pass recursive_gep(X, i_m + 1, i_2, j_m + 1, j_2, k_m + 1, k_2, update_f, update_exists_f); recursive_gep(X, i_1, i_m, j_m + 1, j_2, k_m + 1, k_2, update_f, update_exists_f); recursive_gep(X, i_m + 1, i_2, j_1, j_m, k_m + 1, k_2, update_f, update_exists_f); recursive_gep(X, i_1, i_m, j_1, j_m, k_m + 1, k_2, update_f, update_exists_f); } } // void recursive_parallel_gep(dp_matrix_t* X, uint64_t i_1, uint64_t i_2, // uint64_t j_1, uint64_t j_2, uint64_t k_1, uint64_t k_2, // UPDATE_F update_f, UPDATE_EXISTS_F update_exists_f) { // // printf("%lld %lld %lld %lld %lld %lld\n", i_1, i_2, j_1, j_2, k_1, k_2); // if (update_exists_f(X->width, i_1, i_2, j_1, j_2, k_1, k_2) == false || k_2 < k_1 || j_2 < j_1 || i_2 < i_1) { // return; // } // if (k_1 == k_2 && i_1 == i_2 && j_1 == j_2) { // base case // uint64_t x = get_entry(X, i_1, j_1); uint64_t u = get_entry(X, i_1, k_1); // uint64_t v = get_entry(X, k_1, j_1); // uint64_t w = get_entry(X, k_1, k_1); // // printf("%lld, %lld, %lld\n", i_1, j_1, k_1); // set_entry(X, i_1, j_1, update_f(x, u, v, w)); // } else { // uint64_t i_m = (i_1 + i_2)/2; // uint64_t j_m = (j_1 + j_2)/2; // uint64_t k_m = (k_1 + k_2)/2; // // // forward pass // recursive_gep(X, i_1, i_m, j_1, j_m, k_1, k_m, update_f, update_exists_f); // #pragma omp parallel // { // recursive_gep(X, i_m + 1, i_2, j_1, j_m, k_1, k_m, update_f, update_exists_f); // recursive_gep(X, i_1, i_m, j_m + 1, j_2, k_1, k_m, update_f, update_exists_f); // } // recursive_gep(X, i_m + 1, i_2, j_m + 1, j_2, k_1, k_m, update_f, update_exists_f); // // // backward pass // recursive_gep(X, i_m + 1, i_2, j_m + 1, j_2, k_m + 1, k_2, update_f, update_exists_f); // #pragma omp parallel // { // recursive_gep(X, i_1, i_m, j_m + 1, j_2, k_m + 1, k_2, update_f, update_exists_f); // recursive_gep(X, i_m + 1, i_2, j_1, j_m, k_m + 1, k_2, update_f, update_exists_f); // } // recursive_gep(X, i_1, i_m, j_1, j_m, k_m + 1, k_2, update_f, update_exists_f); // } // } // // void recursive_split_longest_gep(dp_matrix_t* X, uint64_t i_1, uint64_t i_2, // uint64_t j_1, uint64_t j_2, uint64_t k_1, uint64_t k_2, // UPDATE_F update_f, UPDATE_EXISTS_F update_exists_f, bool reverse) { // // printf("%lld %lld %lld %lld %lld %lld\n", i_1, i_2, j_1, j_2, k_1, k_2); // if (update_exists_f(X->width, i_1, i_2, j_1, j_2, k_1, k_2) == false) { // return; // } // if (k_1 == k_2 && i_1 == i_2 && j_1 == j_2) { // base case // // printf("%lld, %lld, %lld\n ", i_1, j_1, k_1); // uint64_t x = get_entry(X, i_1, j_1); // uint64_t u = get_entry(X, i_1, k_1); // uint64_t v = get_entry(X, k_1, j_1); // uint64_t w = get_entry(X, k_1, k_1); // set_entry(X, i_1, j_1, update_f(x, u, v, w)); // } else { // uint64_t i_diff = i_2 - i_1; // uint64_t j_diff = j_2 - j_1; // uint64_t k_diff = k_2 - k_1; // if (!reverse) { // if (k_diff >= j_diff && k_diff >= i_diff) { // uint64_t k_m = (k_1 + k_2)/2; // recursive_split_longest_gep(X, i_1, i_2, j_1, j_2, k_1, k_m, update_f, update_exists_f, false); // recursive_split_longest_gep(X, i_1, i_2, j_1, j_2, k_m + 1, k_2, update_f, update_exists_f, true); // } else if (j_diff >= i_diff && j_diff >= k_diff) { // uint64_t j_m = (j_1 + j_2)/2; // recursive_split_longest_gep(X, i_1, i_2, j_1, j_m, k_1, k_2, update_f, update_exists_f, false); // recursive_split_longest_gep(X, i_1, i_2, j_m + 1, j_2, k_1, k_2, update_f, update_exists_f, false); // } else { // uint64_t i_m = (i_1 + i_2)/2; // recursive_split_longest_gep(X, i_1, i_m, j_1, j_2, k_1, k_2, update_f, update_exists_f, false); // recursive_split_longest_gep(X, i_m + 1, i_2, j_1, j_2, k_1, k_2, update_f, update_exists_f, false); // } // } else { // if (k_diff >= j_diff && k_diff >= i_diff) { // uint64_t k_m = (k_1 + k_2)/2; // recursive_split_longest_gep(X, i_1, i_2, j_1, j_2, k_1, k_m, update_f, update_exists_f, false); // recursive_split_longest_gep(X, i_1, i_2, j_1, j_2, k_m + 1, k_2, update_f, update_exists_f, true); // } else if (j_diff >= i_diff && j_diff >= k_diff) { // uint64_t j_m = (j_1 + j_2)/2; // recursive_split_longest_gep(X, i_1, i_2, j_m + 1, j_2, k_1, k_2, update_f, update_exists_f, true); // recursive_split_longest_gep(X, i_1, i_2, j_1, j_m, k_1, k_2, update_f, update_exists_f, true); // } else { // uint64_t i_m = (i_1 + i_2)/2; // recursive_split_longest_gep(X, i_m + 1, i_2, j_1, j_2, k_1, k_2, update_f, update_exists_f, true); // recursive_split_longest_gep(X, i_1, i_m, j_1, j_2, k_1, k_2, update_f, update_exists_f, true); // } // } // } // } uint64_t gep_update(dp_matrix_t* X, UPDATE_F update_f, UPDATE_EXISTS_F update_exists_f) { uint64_t length = X->width; recursive_gep(X, 0, length - 1, 0, length - 1, 0, length - 1, update_f, update_exists_f); return get_entry(X, length - 1, length - 1); }
ab-totient-omp-12.c
// Distributed and parallel technologies, Andrew Beveridge, 03/03/2014 // To Compile: gcc -Wall -O -o ab-totient-omp -fopenmp ab-totient-omp.c // To Run / Time: /usr/bin/time -v ./ab-totient-omp range_start range_end #include <stdio.h> #include <omp.h> /* When input is a prime number, the totient is simply the prime number - 1. Totient is always even (except for 1). If n is a positive integer, then φ(n) is the number of integers k in the range 1 ≤ k ≤ n for which gcd(n, k) = 1 */ long getTotient (long number) { long result = number; // Check every prime number below the square root for divisibility if(number % 2 == 0){ result -= result / 2; do number /= 2; while(number %2 == 0); } // Primitive replacement for a list of primes, looping through every odd number long prime; for(prime = 3; prime * prime <= number; prime += 2){ if(number %prime == 0){ result -= result / prime; do number /= prime; while(number % prime == 0); } } // Last common factor if(number > 1) result -= result / number; // Return the result. return result; } // Main method. int main(int argc, char ** argv) { // Load inputs long lower, upper; sscanf(argv[1], "%ld", &lower); sscanf(argv[2], "%ld", &upper); int i; long result = 0.0; // We know the answer if it's 1; no need to execute the function if(lower == 1) { result = 1.0; lower = 2; } #pragma omp parallel for default(shared) private(i) schedule(auto) reduction(+:result) num_threads(12) // Sum all totients in the specified range for (i = lower; i <= upper; i++) { result = result + getTotient(i); } // Print the result printf("Sum of Totients between [%ld..%ld] is %ld \n", lower, upper, result); // A-OK! return 0; }
irbuilder_nested_parallel_for.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py // RUN: %clang_cc1 -verify -fopenmp -fopenmp-enable-irbuilder -x c++ -emit-llvm %s -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -o - | FileCheck --check-prefixes=CHECK %s // RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -x c++ -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -debug-info-kind=limited -std=c++11 -verify %s -emit-llvm -o - | FileCheck --check-prefixes=CHECK-DEBUG %s // expected-no-diagnostics // TODO: Teach the update script to check new functions too. #ifndef HEADER #define HEADER // CHECK-LABEL: @_Z14parallel_for_0v( // CHECK-NEXT: entry: // CHECK-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1:[0-9]+]]) // CHECK-NEXT: br label [[OMP_PARALLEL:%.*]] // CHECK: omp_parallel: // CHECK-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 0, void (i32*, i32*, ...)* bitcast (void (i32*, i32*)* @_Z14parallel_for_0v..omp_par to void (i32*, i32*, ...)*)) // CHECK-NEXT: br label [[OMP_PAR_OUTLINED_EXIT:%.*]] // CHECK: omp.par.outlined.exit: // CHECK-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // CHECK: omp.par.exit.split: // CHECK-NEXT: ret void // // CHECK-DEBUG-LABEL: @_Z14parallel_for_0v( // CHECK-DEBUG-NEXT: entry: // CHECK-DEBUG-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1:[0-9]+]]), !dbg [[DBG12:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_PARALLEL:%.*]] // CHECK-DEBUG: omp_parallel: // CHECK-DEBUG-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 0, void (i32*, i32*, ...)* bitcast (void (i32*, i32*)* @_Z14parallel_for_0v..omp_par to void (i32*, i32*, ...)*)), !dbg [[DBG13:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_PAR_OUTLINED_EXIT:%.*]] // CHECK-DEBUG: omp.par.outlined.exit: // CHECK-DEBUG-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // CHECK-DEBUG: omp.par.exit.split: // CHECK-DEBUG-NEXT: ret void, !dbg [[DBG17:![0-9]+]] // void parallel_for_0(void) { #pragma omp parallel { #pragma omp for for (int i = 0; i < 100; ++i) { } } } // CHECK-LABEL: @_Z14parallel_for_1Pfid( // CHECK-NEXT: entry: // CHECK-NEXT: [[R_ADDR:%.*]] = alloca float*, align 8 // CHECK-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[B_ADDR:%.*]] = alloca double, align 8 // CHECK-NEXT: store float* [[R:%.*]], float** [[R_ADDR]], align 8 // CHECK-NEXT: store i32 [[A:%.*]], i32* [[A_ADDR]], align 4 // CHECK-NEXT: store double [[B:%.*]], double* [[B_ADDR]], align 8 // CHECK-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1]]) // CHECK-NEXT: br label [[OMP_PARALLEL:%.*]] // CHECK: omp_parallel: // CHECK-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 3, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i32*, double*, float**)* @_Z14parallel_for_1Pfid..omp_par.4 to void (i32*, i32*, ...)*), i32* [[A_ADDR]], double* [[B_ADDR]], float** [[R_ADDR]]) // CHECK-NEXT: br label [[OMP_PAR_OUTLINED_EXIT16:%.*]] // CHECK: omp.par.outlined.exit16: // CHECK-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // CHECK: omp.par.exit.split: // CHECK-NEXT: ret void // // CHECK-DEBUG-LABEL: @_Z14parallel_for_1Pfid( // CHECK-DEBUG-NEXT: entry: // CHECK-DEBUG-NEXT: [[R_ADDR:%.*]] = alloca float*, align 8 // CHECK-DEBUG-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[B_ADDR:%.*]] = alloca double, align 8 // CHECK-DEBUG-NEXT: store float* [[R:%.*]], float** [[R_ADDR]], align 8 // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata float** [[R_ADDR]], metadata [[META71:![0-9]+]], metadata !DIExpression()), !dbg [[DBG72:![0-9]+]] // CHECK-DEBUG-NEXT: store i32 [[A:%.*]], i32* [[A_ADDR]], align 4 // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata i32* [[A_ADDR]], metadata [[META73:![0-9]+]], metadata !DIExpression()), !dbg [[DBG74:![0-9]+]] // CHECK-DEBUG-NEXT: store double [[B:%.*]], double* [[B_ADDR]], align 8 // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata double* [[B_ADDR]], metadata [[META75:![0-9]+]], metadata !DIExpression()), !dbg [[DBG76:![0-9]+]] // CHECK-DEBUG-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB6:[0-9]+]]), !dbg [[DBG77:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_PARALLEL:%.*]] // CHECK-DEBUG: omp_parallel: // CHECK-DEBUG-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB6]], i32 3, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i32*, double*, float**)* @_Z14parallel_for_1Pfid..omp_par.4 to void (i32*, i32*, ...)*), i32* [[A_ADDR]], double* [[B_ADDR]], float** [[R_ADDR]]), !dbg [[DBG78:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_PAR_OUTLINED_EXIT16:%.*]] // CHECK-DEBUG: omp.par.outlined.exit16: // CHECK-DEBUG-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // CHECK-DEBUG: omp.par.exit.split: // CHECK-DEBUG-NEXT: ret void, !dbg [[DBG80:![0-9]+]] // void parallel_for_1(float *r, int a, double b) { #pragma omp parallel { #pragma omp parallel { #pragma omp for for (int i = 0; i < 100; ++i) { *r = a + b; } } } } // CHECK-LABEL: @_Z14parallel_for_2Pfid( // CHECK-NEXT: entry: // CHECK-NEXT: [[R_ADDR:%.*]] = alloca float*, align 8 // CHECK-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[B_ADDR:%.*]] = alloca double, align 8 // CHECK-NEXT: [[I185:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[AGG_CAPTURED186:%.*]] = alloca [[STRUCT_ANON_17:%.*]], align 8 // CHECK-NEXT: [[AGG_CAPTURED187:%.*]] = alloca [[STRUCT_ANON_18:%.*]], align 4 // CHECK-NEXT: [[DOTCOUNT_ADDR188:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[P_LASTITER203:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[P_LOWERBOUND204:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[P_UPPERBOUND205:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[P_STRIDE206:%.*]] = alloca i32, align 4 // CHECK-NEXT: store float* [[R:%.*]], float** [[R_ADDR]], align 8 // CHECK-NEXT: store i32 [[A:%.*]], i32* [[A_ADDR]], align 4 // CHECK-NEXT: store double [[B:%.*]], double* [[B_ADDR]], align 8 // CHECK-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1]]) // CHECK-NEXT: br label [[OMP_PARALLEL:%.*]] // CHECK: omp_parallel: // CHECK-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 3, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i32*, double*, float**)* @_Z14parallel_for_2Pfid..omp_par.23 to void (i32*, i32*, ...)*), i32* [[A_ADDR]], double* [[B_ADDR]], float** [[R_ADDR]]) // CHECK-NEXT: br label [[OMP_PAR_OUTLINED_EXIT184:%.*]] // CHECK: omp.par.outlined.exit184: // CHECK-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // CHECK: omp.par.exit.split: // CHECK-NEXT: store i32 0, i32* [[I185]], align 4 // CHECK-NEXT: [[TMP0:%.*]] = getelementptr inbounds [[STRUCT_ANON_17]], %struct.anon.17* [[AGG_CAPTURED186]], i32 0, i32 0 // CHECK-NEXT: store i32* [[I185]], i32** [[TMP0]], align 8 // CHECK-NEXT: [[TMP1:%.*]] = getelementptr inbounds [[STRUCT_ANON_18]], %struct.anon.18* [[AGG_CAPTURED187]], i32 0, i32 0 // CHECK-NEXT: [[TMP2:%.*]] = load i32, i32* [[I185]], align 4 // CHECK-NEXT: store i32 [[TMP2]], i32* [[TMP1]], align 4 // CHECK-NEXT: call void @__captured_stmt.19(i32* [[DOTCOUNT_ADDR188]], %struct.anon.17* [[AGG_CAPTURED186]]) // CHECK-NEXT: [[DOTCOUNT189:%.*]] = load i32, i32* [[DOTCOUNT_ADDR188]], align 4 // CHECK-NEXT: br label [[OMP_LOOP_PREHEADER190:%.*]] // CHECK: omp_loop.preheader190: // CHECK-NEXT: store i32 0, i32* [[P_LOWERBOUND204]], align 4 // CHECK-NEXT: [[TMP3:%.*]] = sub i32 [[DOTCOUNT189]], 1 // CHECK-NEXT: store i32 [[TMP3]], i32* [[P_UPPERBOUND205]], align 4 // CHECK-NEXT: store i32 1, i32* [[P_STRIDE206]], align 4 // CHECK-NEXT: [[OMP_GLOBAL_THREAD_NUM207:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1]]) // CHECK-NEXT: call void @__kmpc_for_static_init_4u(%struct.ident_t* @[[GLOB1]], i32 [[OMP_GLOBAL_THREAD_NUM207]], i32 34, i32* [[P_LASTITER203]], i32* [[P_LOWERBOUND204]], i32* [[P_UPPERBOUND205]], i32* [[P_STRIDE206]], i32 1, i32 1) // CHECK-NEXT: [[TMP4:%.*]] = load i32, i32* [[P_LOWERBOUND204]], align 4 // CHECK-NEXT: [[TMP5:%.*]] = load i32, i32* [[P_UPPERBOUND205]], align 4 // CHECK-NEXT: [[TMP6:%.*]] = sub i32 [[TMP5]], [[TMP4]] // CHECK-NEXT: [[TMP7:%.*]] = add i32 [[TMP6]], 1 // CHECK-NEXT: br label [[OMP_LOOP_HEADER191:%.*]] // CHECK: omp_loop.header191: // CHECK-NEXT: [[OMP_LOOP_IV197:%.*]] = phi i32 [ 0, [[OMP_LOOP_PREHEADER190]] ], [ [[OMP_LOOP_NEXT199:%.*]], [[OMP_LOOP_INC194:%.*]] ] // CHECK-NEXT: br label [[OMP_LOOP_COND192:%.*]] // CHECK: omp_loop.cond192: // CHECK-NEXT: [[OMP_LOOP_CMP198:%.*]] = icmp ult i32 [[OMP_LOOP_IV197]], [[TMP7]] // CHECK-NEXT: br i1 [[OMP_LOOP_CMP198]], label [[OMP_LOOP_BODY193:%.*]], label [[OMP_LOOP_EXIT195:%.*]] // CHECK: omp_loop.body193: // CHECK-NEXT: [[TMP8:%.*]] = add i32 [[OMP_LOOP_IV197]], [[TMP4]] // CHECK-NEXT: call void @__captured_stmt.20(i32* [[I185]], i32 [[TMP8]], %struct.anon.18* [[AGG_CAPTURED187]]) // CHECK-NEXT: [[TMP9:%.*]] = load i32, i32* [[A_ADDR]], align 4 // CHECK-NEXT: [[CONV200:%.*]] = sitofp i32 [[TMP9]] to double // CHECK-NEXT: [[TMP10:%.*]] = load double, double* [[B_ADDR]], align 8 // CHECK-NEXT: [[ADD201:%.*]] = fadd double [[CONV200]], [[TMP10]] // CHECK-NEXT: [[CONV202:%.*]] = fptrunc double [[ADD201]] to float // CHECK-NEXT: [[TMP11:%.*]] = load float*, float** [[R_ADDR]], align 8 // CHECK-NEXT: store float [[CONV202]], float* [[TMP11]], align 4 // CHECK-NEXT: br label [[OMP_LOOP_INC194]] // CHECK: omp_loop.inc194: // CHECK-NEXT: [[OMP_LOOP_NEXT199]] = add nuw i32 [[OMP_LOOP_IV197]], 1 // CHECK-NEXT: br label [[OMP_LOOP_HEADER191]] // CHECK: omp_loop.exit195: // CHECK-NEXT: call void @__kmpc_for_static_fini(%struct.ident_t* @[[GLOB1]], i32 [[OMP_GLOBAL_THREAD_NUM207]]) // CHECK-NEXT: [[OMP_GLOBAL_THREAD_NUM208:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1]]) // CHECK-NEXT: call void @__kmpc_barrier(%struct.ident_t* @[[GLOB2:[0-9]+]], i32 [[OMP_GLOBAL_THREAD_NUM208]]) // CHECK-NEXT: br label [[OMP_LOOP_AFTER196:%.*]] // CHECK: omp_loop.after196: // CHECK-NEXT: ret void // // CHECK-DEBUG-LABEL: @_Z14parallel_for_2Pfid( // CHECK-DEBUG-NEXT: entry: // CHECK-DEBUG-NEXT: [[R_ADDR:%.*]] = alloca float*, align 8 // CHECK-DEBUG-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[B_ADDR:%.*]] = alloca double, align 8 // CHECK-DEBUG-NEXT: [[I185:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[AGG_CAPTURED186:%.*]] = alloca [[STRUCT_ANON_17:%.*]], align 8 // CHECK-DEBUG-NEXT: [[AGG_CAPTURED187:%.*]] = alloca [[STRUCT_ANON_18:%.*]], align 4 // CHECK-DEBUG-NEXT: [[DOTCOUNT_ADDR188:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[P_LASTITER203:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[P_LOWERBOUND204:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[P_UPPERBOUND205:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[P_STRIDE206:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: store float* [[R:%.*]], float** [[R_ADDR]], align 8 // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata float** [[R_ADDR]], metadata [[META132:![0-9]+]], metadata !DIExpression()), !dbg [[DBG133:![0-9]+]] // CHECK-DEBUG-NEXT: store i32 [[A:%.*]], i32* [[A_ADDR]], align 4 // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata i32* [[A_ADDR]], metadata [[META134:![0-9]+]], metadata !DIExpression()), !dbg [[DBG135:![0-9]+]] // CHECK-DEBUG-NEXT: store double [[B:%.*]], double* [[B_ADDR]], align 8 // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata double* [[B_ADDR]], metadata [[META136:![0-9]+]], metadata !DIExpression()), !dbg [[DBG137:![0-9]+]] // CHECK-DEBUG-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB13:[0-9]+]]), !dbg [[DBG138:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_PARALLEL:%.*]] // CHECK-DEBUG: omp_parallel: // CHECK-DEBUG-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB13]], i32 3, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i32*, double*, float**)* @_Z14parallel_for_2Pfid..omp_par.23 to void (i32*, i32*, ...)*), i32* [[A_ADDR]], double* [[B_ADDR]], float** [[R_ADDR]]), !dbg [[DBG139:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_PAR_OUTLINED_EXIT184:%.*]] // CHECK-DEBUG: omp.par.outlined.exit184: // CHECK-DEBUG-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // CHECK-DEBUG: omp.par.exit.split: // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata i32* [[I185]], metadata [[META143:![0-9]+]], metadata !DIExpression()), !dbg [[DBG146:![0-9]+]] // CHECK-DEBUG-NEXT: store i32 0, i32* [[I185]], align 4, !dbg [[DBG146]] // CHECK-DEBUG-NEXT: [[TMP0:%.*]] = getelementptr inbounds [[STRUCT_ANON_17]], %struct.anon.17* [[AGG_CAPTURED186]], i32 0, i32 0, !dbg [[DBG147:![0-9]+]] // CHECK-DEBUG-NEXT: store i32* [[I185]], i32** [[TMP0]], align 8, !dbg [[DBG147]] // CHECK-DEBUG-NEXT: [[TMP1:%.*]] = getelementptr inbounds [[STRUCT_ANON_18]], %struct.anon.18* [[AGG_CAPTURED187]], i32 0, i32 0, !dbg [[DBG147]] // CHECK-DEBUG-NEXT: [[TMP2:%.*]] = load i32, i32* [[I185]], align 4, !dbg [[DBG148:![0-9]+]] // CHECK-DEBUG-NEXT: store i32 [[TMP2]], i32* [[TMP1]], align 4, !dbg [[DBG147]] // CHECK-DEBUG-NEXT: call void @__captured_stmt.19(i32* [[DOTCOUNT_ADDR188]], %struct.anon.17* [[AGG_CAPTURED186]]), !dbg [[DBG147]] // CHECK-DEBUG-NEXT: [[DOTCOUNT189:%.*]] = load i32, i32* [[DOTCOUNT_ADDR188]], align 4, !dbg [[DBG147]] // CHECK-DEBUG-NEXT: br label [[OMP_LOOP_PREHEADER190:%.*]], !dbg [[DBG147]] // CHECK-DEBUG: omp_loop.preheader190: // CHECK-DEBUG-NEXT: store i32 0, i32* [[P_LOWERBOUND204]], align 4, !dbg [[DBG147]] // CHECK-DEBUG-NEXT: [[TMP3:%.*]] = sub i32 [[DOTCOUNT189]], 1, !dbg [[DBG147]] // CHECK-DEBUG-NEXT: store i32 [[TMP3]], i32* [[P_UPPERBOUND205]], align 4, !dbg [[DBG147]] // CHECK-DEBUG-NEXT: store i32 1, i32* [[P_STRIDE206]], align 4, !dbg [[DBG147]] // CHECK-DEBUG-NEXT: [[OMP_GLOBAL_THREAD_NUM207:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB42:[0-9]+]]), !dbg [[DBG147]] // CHECK-DEBUG-NEXT: call void @__kmpc_for_static_init_4u(%struct.ident_t* @[[GLOB42]], i32 [[OMP_GLOBAL_THREAD_NUM207]], i32 34, i32* [[P_LASTITER203]], i32* [[P_LOWERBOUND204]], i32* [[P_UPPERBOUND205]], i32* [[P_STRIDE206]], i32 1, i32 1), !dbg [[DBG147]] // CHECK-DEBUG-NEXT: [[TMP4:%.*]] = load i32, i32* [[P_LOWERBOUND204]], align 4, !dbg [[DBG147]] // CHECK-DEBUG-NEXT: [[TMP5:%.*]] = load i32, i32* [[P_UPPERBOUND205]], align 4, !dbg [[DBG147]] // CHECK-DEBUG-NEXT: [[TMP6:%.*]] = sub i32 [[TMP5]], [[TMP4]], !dbg [[DBG147]] // CHECK-DEBUG-NEXT: [[TMP7:%.*]] = add i32 [[TMP6]], 1, !dbg [[DBG147]] // CHECK-DEBUG-NEXT: br label [[OMP_LOOP_HEADER191:%.*]], !dbg [[DBG147]] // CHECK-DEBUG: omp_loop.header191: // CHECK-DEBUG-NEXT: [[OMP_LOOP_IV197:%.*]] = phi i32 [ 0, [[OMP_LOOP_PREHEADER190]] ], [ [[OMP_LOOP_NEXT199:%.*]], [[OMP_LOOP_INC194:%.*]] ], !dbg [[DBG147]] // CHECK-DEBUG-NEXT: br label [[OMP_LOOP_COND192:%.*]], !dbg [[DBG147]] // CHECK-DEBUG: omp_loop.cond192: // CHECK-DEBUG-NEXT: [[OMP_LOOP_CMP198:%.*]] = icmp ult i32 [[OMP_LOOP_IV197]], [[TMP7]], !dbg [[DBG147]] // CHECK-DEBUG-NEXT: br i1 [[OMP_LOOP_CMP198]], label [[OMP_LOOP_BODY193:%.*]], label [[OMP_LOOP_EXIT195:%.*]], !dbg [[DBG147]] // CHECK-DEBUG: omp_loop.body193: // CHECK-DEBUG-NEXT: [[TMP8:%.*]] = add i32 [[OMP_LOOP_IV197]], [[TMP4]], !dbg [[DBG147]] // CHECK-DEBUG-NEXT: call void @__captured_stmt.20(i32* [[I185]], i32 [[TMP8]], %struct.anon.18* [[AGG_CAPTURED187]]), !dbg [[DBG147]] // CHECK-DEBUG-NEXT: [[TMP9:%.*]] = load i32, i32* [[A_ADDR]], align 4, !dbg [[DBG149:![0-9]+]] // CHECK-DEBUG-NEXT: [[CONV200:%.*]] = sitofp i32 [[TMP9]] to double, !dbg [[DBG149]] // CHECK-DEBUG-NEXT: [[TMP10:%.*]] = load double, double* [[B_ADDR]], align 8, !dbg [[DBG150:![0-9]+]] // CHECK-DEBUG-NEXT: [[ADD201:%.*]] = fadd double [[CONV200]], [[TMP10]], !dbg [[DBG151:![0-9]+]] // CHECK-DEBUG-NEXT: [[CONV202:%.*]] = fptrunc double [[ADD201]] to float, !dbg [[DBG149]] // CHECK-DEBUG-NEXT: [[TMP11:%.*]] = load float*, float** [[R_ADDR]], align 8, !dbg [[DBG152:![0-9]+]] // CHECK-DEBUG-NEXT: store float [[CONV202]], float* [[TMP11]], align 4, !dbg [[DBG153:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_LOOP_INC194]], !dbg [[DBG147]] // CHECK-DEBUG: omp_loop.inc194: // CHECK-DEBUG-NEXT: [[OMP_LOOP_NEXT199]] = add nuw i32 [[OMP_LOOP_IV197]], 1, !dbg [[DBG147]] // CHECK-DEBUG-NEXT: br label [[OMP_LOOP_HEADER191]], !dbg [[DBG147]] // CHECK-DEBUG: omp_loop.exit195: // CHECK-DEBUG-NEXT: call void @__kmpc_for_static_fini(%struct.ident_t* @[[GLOB42]], i32 [[OMP_GLOBAL_THREAD_NUM207]]), !dbg [[DBG147]] // CHECK-DEBUG-NEXT: [[OMP_GLOBAL_THREAD_NUM208:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB42]]), !dbg [[DBG150]] // CHECK-DEBUG-NEXT: call void @__kmpc_barrier(%struct.ident_t* @[[GLOB43:[0-9]+]], i32 [[OMP_GLOBAL_THREAD_NUM208]]), !dbg [[DBG150]] // CHECK-DEBUG-NEXT: br label [[OMP_LOOP_AFTER196:%.*]], !dbg [[DBG147]] // CHECK-DEBUG: omp_loop.after196: // CHECK-DEBUG-NEXT: ret void, !dbg [[DBG154:![0-9]+]] // void parallel_for_2(float *r, int a, double b) { #pragma omp parallel { #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; #pragma omp parallel { #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; #pragma omp parallel { #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; } #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; #pragma omp parallel { #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; } #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; } #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; } #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; } #endif
opencl_sxc_fmt_plug.c
/* * Modified by Dhiru Kholia <dhiru at openwall.com> for Keychain format. * * This software is Copyright (c) 2012 Lukas Odzioba <ukasz@openwall.net> * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. */ #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_sxc; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_sxc); #else #include <string.h> #include "sha.h" #include <openssl/blowfish.h> #include "aes.h" #ifdef _OPENMP #include <omp.h> #endif #include "arch.h" #include "formats.h" #include "common.h" #include "stdint.h" #include "misc.h" #include "options.h" #include "common.h" #include "formats.h" #include "common-opencl.h" #define FORMAT_LABEL "sxc-opencl" #define FORMAT_NAME "StarOffice .sxc" #define ALGORITHM_NAME "PBKDF2-SHA1 OpenCL Blowfish" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define BINARY_SIZE 20 #define PLAINTEXT_LENGTH 64 #define SALT_SIZE sizeof(sxc_cpu_salt) #define BINARY_ALIGN MEM_ALIGN_WORD #define SALT_ALIGN 4 typedef struct { uint32_t length; uint8_t v[20]; // hash of password } sxc_password; typedef struct { uint32_t v[16/4]; } sxc_hash; typedef struct { uint32_t iterations; uint32_t outlen; uint32_t skip_bytes; uint8_t length; uint8_t salt[64]; } sxc_salt; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out)[32 / sizeof(ARCH_WORD_32)]; typedef struct { int cipher_type; int checksum_type; int iterations; int key_size; int iv_length; int salt_length; int original_length; int length; unsigned char iv[16]; unsigned char salt[32]; unsigned char content[1024]; } sxc_cpu_salt; static sxc_cpu_salt *cur_salt; static struct fmt_tests sxc_tests[] = { {"$sxc$*0*0*1024*16*4448359828281a1e6842c31453473abfeae584fb*8*dc0248bea0c7508c*16*1d53770002fe9d8016064e5ef9423174*860*864*f00399ab17b9899cd517758ecf918d4da78099ccd3557aef5e22e137fd5b81f732fc7c167c4de0cf263b4f82b50e3d6abc65da613a36b0025d89e1a09adeb4106da28040d1019bb4b36630fc8bc94fe5b515504bf8a92ea630bb95ace074868e7c10743ec970c89895f44b975a30b6ca032354f3e73ec86b2cc7a4f7a185884026d971b37b1e0e650376a2552e27ba955c700f8903a82a6df11f6cc2ecf63290f02ffdd278f890d1db75f9e8bd0f437c4ec613d3c6dcb421bbd1067be633593ba9bd58f77ef08e0cca64c732f892567d20de8d4c444fa9c1c1adc5e4657ef9740cb69ce55c8f9e6b1cfed0739ef002f1e1c1e54a5df50a759d92354f78eb90a9d9378f36df7d1edd8002ea0d637604fcd2408494c2d42b1771e2a2a20b55044836f76db4ed71e8a53f55a04f9437946603e7246c2d2d70caf6be0de82e8977fab4de84ca3783baedac041195d8b51166b502ff80c17db78f63d3632df1d5ef5b14d8d5553fc40b072030f9e3374c93e929a490c6cfb170f04433fc46f43b9c7d27f3f8c4ed759d4a20c2e53a0701b7c3d9201390a9b5597ce8ba35bd765b662e2242b9821bbb63b6be502d2150fff37e4b7f2a6b592fd0e319a7349df320e7fe7da600a2a05628dc00e04d480c085417f676bd0518bc39d9a9be34fc0cb192d5fa5e0c657cdf7c1ad265a2e81b90ac8b28d326f98b8f33c123df83edc964d2c17a904d0df8bd9ecbf629929d6e48cadc97f49a8941ada3d219e8c0f04f37cecc9a50cc5307fd2a488c34829b05cd1615ae0d1ef0ce450529aa755f9ae38332187ffe4144990de3265afaacb9f0f0fb9c67f6210369f7a0cc5bb346412db08e0f4732f91aa8d4b32fe6eece4fba118f118f6df2fb6c53fa9bc164c9ab7a9d414d33281eb0c3cd02abe0a4dd1c170e41c1c960a8f12a48a7b5e1f748c08e1b150a4e389c110ea3368bc6c6ef2bee98dc92c6825cbf6aee20e690e116c0e6cf48d49b38035f6a9b0cd6053b9f5b9f8360024c9c608cbba3fe5e7966b656fa08dec3e3ce3178a0c0007b7d177c7c44e6a68f4c7325cb98264b1e0f391c75a6a8fd3691581fb68ef459458830f2138d0fd743631efd92b742dfeb62c5ea8502515eb65af414bf805992f9272a7b1b745970fd54e128751f8f6c0a4d5bc7872bc09c04037e1e91dc7192d68f780cdb0f7ef6b282ea883be462ffeffb7b396e30303030", "openwall"}, {"$sxc$*0*0*1024*16*64983af0b26a6ee614e6c65b32c1d906f70c6397*8*259cafe530bd09f8*16*8f53ea878d0795cfe05dcc65fb272c20*1024*1024*ffb0f736b69d8433f958e8f475f609948ad7c9dd052f2b92c14cb1b395ffcac043a3def76d58442e131701b3b53d56ea570633bb20c83068542420160f5db3cee5eece05b67b54d0d4cdf3fbfd928d94852924e391aa3f70cad598b48b946399b0cd1e9e7e7d081a888933f8a1973e83166799396e8290771463c623620b51fb5310b9b0e0de3e5597b66a091301ada3ba6a5d7515d1fcf0eff65e543b50f8fe2222619600054eaf69c7aa680c96bc403f115cab32d6d8e8bc0db3904a71ce3eb1283ca73fd6f75845d9b7d0275e4727a0f56bfbf962a9079f51849de2c9dee7f1dadbbae944f442169281004773309b0f8d68f2cf83076fd8b19afbccf5ab7dc58fb9554fee82e2c491d6434a4cef6f3209775343c840bc4bdfab6705000e67412ac74d00f5b6aba1fd21bca5213234a5a1100a9d93daa141a4936723ea77d008a35c9078167a3529706432b36b9ec012c060d093535c85ca6feb75165d620d7d663c3e76b9bf3af614556ed8560b446a8a73649cb935383a30b4fd8fd75522203e4575cf4bc2b7f01a9294310fe021c71acbf68f6f1e95f48c30c14151c51d4fb878a16272ee73753bc750cbd48007c842412ca1dcb6214215b082c00d619a5318e2ebe9149410f501170093784afc2bd71dd9f5a87b349b96661747b1627e8cba8a5c98559fb146fa7e30db4c6f648ce3c2209f84551a7a1cd46d9172ae1354b6d093f89f6f5f58d29c1d7af8830df62e67753caa8166322caa0f8adf4b61d2013d35baa7c002e1d4c83b1cba8aaa57cf4946627fa63ba7a6a5a5c803e8d5a4794845ab670ef950b918a360cd9f12e8f3424ecab1f505cb494ad35f28d12ff183471d0f47bd67e6abd3b8c8e206d11149474a19b5c13d165d8f6dc39cf579fe1000295328aeeb82e0ae8020d2f61e4c3d6e68c25a655ab72aad5e9e74af4cf27c74158fdb1a29a3d76cd658976fa0a30743247408df00a23b593f68861348a6c46af05d21a4b81fedbf5715462ec8ffc5f001a85c43058ac1fab488236588ef0bf08dd8dd7c7fce630a0a996395b503647d9a2f0dd63dd2f939eca8e1849ee4ed41a6d5672d947177e8f890692de879a20dd9e366ec494d270faf0d24fc076172a25998aac218586404687e7c77b55e77e0eff9b1c65c3f8da99deaa86411ab6aca2531d84b364349591bc73e7504163afd23c5208e321883ee611ea7e4e5885086e4fa7196e16b948cb54808b64b94106c74900e3190fd5f6068b490fd0c9c64481771527a0e2d00899fd5b7a9e7f508cc6770018fadf09d965d7a12ad3624d2161d9546d4a7937b5f961d7f7c4714786380c147e1ec6b0583503bd5a139b892831d1ea925993bb86f12e75d9010ceba230a1c286fa3d1d654a1672313cbf0763c05c622cee452f76957c42ba0e853ecda163d15e8600a702ccdc9e8f88a", "Ghe+t0Blaster"}, {"$sxc$*0*0*1024*16*64983af0b26a6ee614e6c65b32c1d906f70c6397*8*9bb755c8a4fe8c34*16*112b9d41098c8677615755361da473a6*1024*1024*b95f0f2e0e1c7b4ee61168b646804d4b70b615f3c978cec65c9a7ab515417c79625d104373fd5012c3da6b356f8408a3a75edcc8b2aad0aa38bb33edd8933bdadbffde35a350ade73ccb9df29c2996082f5e94e324496835f8dfebe15ca38950e0f435d711ef964aa09915d58287967b5e321ca195a7f90253157afe82329da9a496c97292419b9a94cdb92f919e6d54700466aff61c200c5a355905b5a37c12d77b0e4ffd23f0204cfa664f4c0545f233db8d35af5fe337b459135da398fd23101becb194db305496474ba4179a7355285a9ec935044e1831f290f5f87ed3e00925e7fb4fc6bc38d9f0cfe9abf72560400490d2fd398d2d49516b618f99168602f323dd1786bcca394830341dfbeb377f9b7ef161dc1470f5e92b6152fa7a4f428e8ae40100791491a9e1c9385298522320488f00535866ac6e08354a75b8b2fd293066da7eb6b4ad7f3e13c8dc98cd815b2393f147fdac6279f76fdac9abd0a94131fa84fe4e99634a362a56d60ce588f6e0b66d6f8b6d411511272ffe32181d20e7d2c3d4b680764607afb2c29dcb94a845b920e96f6c27575534f8b7f9ddd93bdcef0d717d0a899fa937e7d2eeeb6d5b0338757f6e69dac72524d4b6f74edce1f937008eb3653bcc31a88712af940cf47ec3f3efd83e4da89d1a6cb7da6cf8d7d41430bc81a4b5d7bb46cad687f2f505e3379143ae274eed6201c3b17c1e05e516a14cbf2351ccf9fdd46e1309afb170bd01eb8f6a1d8e12441525199455fb550e3fc689b1801332b2d985e336b158f846fcbca18fbe6ea21438cf1fb5fdbce8d6350e65d6468342880845675ec721af2fb9df917a3968b4a1a477fc4c74ee38a71a230d77c2a7cf66ae6b83804488cbd25213ebc470cd845a2691b16161a640ebb385aa2381dc91f692f6c4ca2709b5a7e94dfb4548000a29b56f1da08701945d6209fabbd1621b28849fc27810775f1a0e0204d3ae9040a8cfb1386499a39d87149cfc1579de7d059662ad25a67abd42b30bb3608f09142ca030351c3a1e921e4c7bbc11aab846ef42eb5d1418c15ada77539aca096e0678439cd1b60950d2aa0cc4d2004b1ac48dc6a454c5a8e9ea7e910047c7c83895fd614fd9dfd961631eb23757646143c2aeb03c1a6476e78fc4ccf0f02cc1f88ec1b0080a170ac6871dc183939f7a4376965b0dfa7922012582eec4846ee621edc5547a2b9c4893e7f67f76541a4bd4a91827a57b3db5cdea29a2a3cc20238d89c8145c14b037360ad27f54f87317ef70472d6b1fd9f1168bcf8aba6071257b3adebab8d4e115188ed4af3fc3574fdccb4bc7eeb00a6a442f1b96a989b735f5e6059ec72c1677b77f437dcb93066f8591a11071799c3a0ec3b48f6160976aff1928c375358837e1ef02e20397b2e9d8d9c4bff23172c9b4c0b941cb1b49b5bc070f72a14cd384", "M1racl33"}, {"$sxc$*0*0*1024*16*64983af0b26a6ee614e6c65b32c1d906f70c6397*8*ceb1edb1e3cb72fd*16*f7104c9b2789540f5fd4beef009c0139*1024*1024*709130b940a9663d0a5687133c6f78535d05a72936faed8c2f3c1b4e29423baaabcee4f0d7d57e3ad8d8c090486f974c4d0ce4be5b29ef8e1b02c01b4af1959ed0b277146a45aec35a48997b584b82697803193644eefd88a7eefcae8819839e13702f887278a597dd954babd82bf71bf8ca8559af0e5537be0264e358d36b4f5067960edf608de731e04d117de953386aadee71849edbc494fac3e6b14567a9e9c545a06d402acd3158441829f25478ed0f9086dabd2d3913b123b43c27176f8f08f30312d84e82d47654097a2bce95554357db3ce3d45a7441472067f55e4ea6244a3dedc23db4bea8f549109ffac382cf5b652c5b1ee431bcab1051567c263a9d668c5d6a15a6f8da754914746c1d3c7eb6347bdd8d6a3ac82e4c742fcf8721913c111dfd5398f2698db00f7220d2a3562e02f7f7a6505af3ba1ee10b46f2ab5b5d2f52d288fd12814c6edbcb8d50b6e8716fba0d5962747b971689fe75e94fa36ec39598ea30e15ab2b9c9f22ca04b890a13b18fb3c7a962050426bb2da08c8b993608b9c1ffd0a21e0c74e993242ead8eb30f86d7d2dcdbd4774d85c2e06adbe4b40050ff0ac1a8afe8fbc2175ec4da4676a691b1fce38421175734c20f07a604fea5287e1c33b420aa9db4de9bd97382c161b4ec0818add675e52ebf036aad779f24b824be4b2b013c470ff66cbf44f5800e128a3b328e80a5fd6295b9b3a94e915f9add6710cb9444432751a7a31c3a3422f48a5eabc26d9a52571b8447bdd0a5977ff7153d95337cef7ff2ec29774332fbeed6ee5eed5e12288cc13e14ba9d5ff3dd052e28ba96715f5b95d7ea214ebcd9e60b26308eb11370b824b5cff2644dd2117985b3c25ba8076d4025cf3a3a62da62d5e11d44422a142048e8cd00c7de6a0a55fd5dc09a3ed01dfe35b88268f351b6ff289fee8e52ac29fe32d9990e0d6d87f39727b6a762bac9d509c6ea235fc8bedc3bec2143eae9fd2cb831b798ef8261d72785002638b940947de0aad64f791f9a27e5b091e55adf4aee0649f6785bdd37e0248fedd1759d771aeacacb3ff6e7cf2d045f791428ab61710b54e869213393caf1b6bc99066678351deafc290cecc1f6b40b5532adbbab9a70408c61a437d4483b6a75cb61a55b20881efc0d849e0f60c1887f0fa091672179a145c4ab1b6487a0e939e0123d5aaffa3aec66ab593f9c25d27f22f4a73a999a4ab45e8bc7d71a85e2d40afadad1a1dc0b8389f96f91614293fa205583ef1c3440e3df50e8aa5f1a13e5929b72cd003461ff03d44d8c84bdada176b24459021d398b2b91b61a9c0b553a8714c703d32452c691a33f1581e98c2439514ca3e7deeef90850f8d6d89bf1d3a5762a56ef769ea588f5c1705bfb7b944cfbbb0632718ee3722f4e1929b35706d6413a315a11bc16349af109a7e675df2ab1eebe93", "excel123"}, {NULL} }; static cl_int cl_error; static sxc_password *inbuffer; static sxc_hash *outbuffer; static sxc_salt currentsalt; static cl_mem mem_in, mem_out, mem_setting; static struct fmt_main *self; static size_t insize, outsize, settingsize; #define STEP 0 #define SEED 256 // This file contains auto-tuning routine(s). Has to be included after formats definitions. #include "opencl-autotune.h" #include "memdbg.h" static const char * warn[] = { "xfer: ", ", crypt: ", ", xfer: " }; /* ------- Helper functions ------- */ static size_t get_task_max_work_group_size() { return autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel); } static void create_clobj(size_t gws, struct fmt_main *self) { insize = sizeof(sxc_password) * gws; outsize = sizeof(sxc_hash) * gws; settingsize = sizeof(sxc_salt); inbuffer = mem_calloc(1, insize); outbuffer = mem_alloc(outsize); saved_key = mem_calloc(gws, sizeof(*saved_key)); crypt_out = mem_calloc(gws, sizeof(*crypt_out)); /// Allocate memory mem_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem in"); mem_setting = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, settingsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem setting"); mem_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem out"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 1, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 2, sizeof(mem_setting), &mem_setting), "Error while setting mem_salt kernel argument"); } static void release_clobj(void) { if (crypt_out) { HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in"); HANDLE_CLERROR(clReleaseMemObject(mem_setting), "Release mem setting"); HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out"); MEM_FREE(inbuffer); MEM_FREE(outbuffer); MEM_FREE(saved_key); MEM_FREE(crypt_out); } } static void done(void) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } static void init(struct fmt_main *_self) { self = _self; opencl_prepare_dev(gpu_id); } static void reset(struct db_main *db) { if (!autotuned) { char build_opts[64]; snprintf(build_opts, sizeof(build_opts), "-DKEYLEN=%d -DSALTLEN=%d -DOUTLEN=%d", (int)sizeof(inbuffer->v), (int)sizeof(currentsalt.salt), (int)sizeof(outbuffer->v)); opencl_init("$JOHN/kernels/pbkdf2_hmac_sha1_unsplit_kernel.cl", gpu_id, build_opts); crypt_kernel = clCreateKernel(program[gpu_id], "derive_key", &cl_error); HANDLE_CLERROR(cl_error, "Error creating kernel"); // Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, 0, NULL, warn, 1, self, create_clobj, release_clobj, sizeof(sxc_password), 0, db); // Auto tune execution from shared/included code. autotune_run(self, 1, 0, 1000); } } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy; char *keeptr; char *p; int res; if (strncmp(ciphertext, "$sxc$*", 6)) return 0; /* handle 'chopped' .pot lines */ if (ldr_isa_pot_source(ciphertext)) return 1; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += 6; if ((p = strtokm(ctcopy, "*")) == NULL) /* cipher type */ goto err; res = atoi(p); if (res != 0 && res != 1) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* checksum type */ goto err; res = atoi(p); if (res != 0 && res != 1) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* iterations */ goto err; res = atoi(p); if (res <= 0) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* key size */ goto err; res = atoi(p); if (res != 16 && res != 32) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* checksum field (skipped) */ goto err; if (hexlenl(p) != BINARY_SIZE * 2) goto err; if (!ishex(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* iv length */ goto err; res = atoi(p); if (res <= 0 || res > 16) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* iv */ goto err; if (hexlenl(p) != res * 2) goto err; if (!ishex(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* salt length */ goto err; res = atoi(p); if (res <= 0 || res > 32) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* salt */ goto err; if (hexlenl(p) != res * 2) goto err; if (!ishex(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* original length */ goto err; res = atoi(p); if (res <= 0 || res > 1024) /* 1024 because of "unsigned char output[1024];" in crypt_all */ goto err; if ((p = strtokm(NULL, "*")) == NULL) /* length */ goto err; res = atoi(p); if (res <= 0 || res > 1024) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* content */ goto err; if (hexlenl(p) != res * 2) goto err; if (strtokm(NULL, "*") != NULL) /* the end */ goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; int i; char *p; static sxc_cpu_salt cs; memset(&cs, 0, sizeof(cs)); ctcopy += 6; /* skip over "$sxc$*" */ p = strtokm(ctcopy, "*"); cs.cipher_type = atoi(p); p = strtokm(NULL, "*"); cs.checksum_type = atoi(p); p = strtokm(NULL, "*"); cs.iterations = atoi(p); p = strtokm(NULL, "*"); cs.key_size = atoi(p); strtokm(NULL, "*"); /* skip checksum field */ p = strtokm(NULL, "*"); cs.iv_length = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.iv_length; i++) cs.iv[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.salt_length = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.salt_length; i++) cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.original_length = atoi(p); p = strtokm(NULL, "*"); cs.length = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.length; i++) cs.content[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)&cs; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE+1]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; ctcopy += 6; /* skip over "$sxc$*" */ strtokm(ctcopy, "*"); strtokm(NULL, "*"); strtokm(NULL, "*"); strtokm(NULL, "*"); p = strtokm(NULL, "*"); for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } MEM_FREE(keeptr); return out; } static void set_salt(void *salt) { cur_salt = (sxc_cpu_salt*)salt; memcpy((char*)currentsalt.salt, cur_salt->salt, cur_salt->salt_length); currentsalt.length = cur_salt->salt_length; currentsalt.iterations = cur_salt->iterations; currentsalt.outlen = cur_salt->key_size; currentsalt.skip_bytes = 0; HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_setting, CL_FALSE, 0, settingsize, &currentsalt, 0, NULL, NULL), "Copy salt to gpu"); } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } #undef set_key static void set_key(char *key, int index) { int saved_len = strlen(key); if (saved_len > PLAINTEXT_LENGTH) saved_len = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_len); saved_key[index][saved_len] = 0; } static char *get_key(int index) { return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; size_t *lws = local_work_size ? &local_work_size : NULL; global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size); #ifdef _OPENMP #pragma omp parallel for #endif for(index = 0; index < count; index++) { unsigned char hash[20]; SHA_CTX ctx; SHA1_Init(&ctx); SHA1_Update(&ctx, (unsigned char *)saved_key[index], strlen(saved_key[index])); SHA1_Final((unsigned char *)hash, &ctx); memcpy(inbuffer[index].v, hash, 20); inbuffer[index].length = 20; } /// Copy data to gpu BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0, insize, inbuffer, 0, NULL, multi_profilingEvent[0]), "Copy data to gpu"); /// Run kernel BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[1]), "Run kernel"); /// Read the result back BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0, outsize, outbuffer, 0, NULL, multi_profilingEvent[2]), "Copy result back"); if (ocl_autotune_running) return count; #ifdef _OPENMP #pragma omp parallel for #endif for(index = 0; index < count; index++) { BF_KEY bf_key; SHA_CTX ctx; int bf_ivec_pos; unsigned char ivec[8]; unsigned char output[1024]; bf_ivec_pos = 0; memcpy(ivec, cur_salt->iv, 8); BF_set_key(&bf_key, cur_salt->key_size, (const unsigned char*)outbuffer[index].v); BF_cfb64_encrypt(cur_salt->content, output, cur_salt->length, &bf_key, ivec, &bf_ivec_pos, 0); SHA1_Init(&ctx); SHA1_Update(&ctx, output, cur_salt->original_length); SHA1_Final((unsigned char*)crypt_out[index], &ctx); } return count; } static int cmp_all(void *binary, int count) { int index = 0; for (; index < count; index++) if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static unsigned int iteration_count(void *salt) { sxc_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->iterations; } struct fmt_main fmt_opencl_sxc = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { "iteration count", }, sxc_tests }, { init, done, reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { iteration_count, }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
Pragma.h
//===--- Pragma.h - Pragma registration and handling ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PragmaHandler and PragmaTable interfaces. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PRAGMA_H #define LLVM_CLANG_PRAGMA_H #include "clang/Basic/LLVM.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include <cassert> namespace clang { class Preprocessor; class Token; class IdentifierInfo; class PragmaNamespace; /** * \brief Describes how the pragma was introduced, e.g., with #pragma, * _Pragma, or __pragma. */ enum PragmaIntroducerKind { /** * \brief The pragma was introduced via #pragma. */ PIK_HashPragma, /** * \brief The pragma was introduced via the C99 _Pragma(string-literal). */ PIK__Pragma, /** * \brief The pragma was introduced via the Microsoft * __pragma(token-string). */ PIK___pragma }; /// PragmaHandler - Instances of this interface defined to handle the various /// pragmas that the language front-end uses. Each handler optionally has a /// name (e.g. "pack") and the HandlePragma method is invoked when a pragma with /// that identifier is found. If a handler does not match any of the declared /// pragmas the handler with a null identifier is invoked, if it exists. /// /// Note that the PragmaNamespace class can be used to subdivide pragmas, e.g. /// we treat "#pragma STDC" and "#pragma GCC" as namespaces that contain other /// pragmas. class PragmaHandler { std::string Name; public: explicit PragmaHandler(StringRef name) : Name(name) {} PragmaHandler() {} virtual ~PragmaHandler(); StringRef getName() const { return Name; } virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) = 0; /// getIfNamespace - If this is a namespace, return it. This is equivalent to /// using a dynamic_cast, but doesn't require RTTI. virtual PragmaNamespace *getIfNamespace() { return 0; } }; /// EmptyPragmaHandler - A pragma handler which takes no action, which can be /// used to ignore particular pragmas. class EmptyPragmaHandler : public PragmaHandler { public: EmptyPragmaHandler(); virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken); }; /// PragmaNamespace - This PragmaHandler subdivides the namespace of pragmas, /// allowing hierarchical pragmas to be defined. Common examples of namespaces /// are "#pragma GCC", "#pragma STDC", and "#pragma omp", but any namespaces may /// be (potentially recursively) defined. class PragmaNamespace : public PragmaHandler { /// Handlers - This is a map of the handlers in this namespace with their name /// as key. /// llvm::StringMap<PragmaHandler*> Handlers; public: explicit PragmaNamespace(StringRef Name) : PragmaHandler(Name) {} virtual ~PragmaNamespace(); /// FindHandler - Check to see if there is already a handler for the /// specified name. If not, return the handler for the null name if it /// exists, otherwise return null. If IgnoreNull is true (the default) then /// the null handler isn't returned on failure to match. PragmaHandler *FindHandler(StringRef Name, bool IgnoreNull = true) const; /// AddPragma - Add a pragma to this namespace. /// void AddPragma(PragmaHandler *Handler); /// RemovePragmaHandler - Remove the given handler from the /// namespace. void RemovePragmaHandler(PragmaHandler *Handler); bool IsEmpty() { return Handlers.empty(); } virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken); virtual PragmaNamespace *getIfNamespace() { return this; } }; } // end namespace clang #endif
J1OrbitalSoA.h
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: // // File created by: Jeongnim Kim, jeongnim.kim@intel.com, Intel Corp. ////////////////////////////////////////////////////////////////////////////////////// // -*- C++ -*- #ifndef QMCPLUSPLUS_ONEBODYJASTROW_OPTIMIZED_SOA_H #define QMCPLUSPLUS_ONEBODYJASTROW_OPTIMIZED_SOA_H #include "Configuration.h" #include "QMCWaveFunctions/WaveFunctionComponent.h" #include "QMCWaveFunctions/Jastrow/DiffOneBodyJastrowOrbital.h" #include <qmc_common.h> #include <simd/allocator.hpp> #include <simd/algorithm.hpp> #include <map> #include <numeric> namespace qmcplusplus { /** @ingroup WaveFunctionComponent * @brief Specialization for one-body Jastrow function using multiple functors */ template<class FT> struct J1OrbitalSoA : public WaveFunctionComponent { ///alias FuncType using FuncType=FT; ///type of each component U, dU, d2U; using valT=typename FT::real_type; ///element position type using posT=TinyVector<valT,OHMMS_DIM>; ///use the same container using RowContainer=DistanceTableData::RowContainer; ///table index int myTableID; ///number of ions int Nions; ///number of electrons int Nelec; ///number of groups int NumGroups; ///reference to the sources (ions) const ParticleSet& Ions; valT curAt; valT curLap; posT curGrad; ///\f$Vat[i] = sum_(j) u_{i,j}\f$ Vector<valT> Vat; aligned_vector<valT> U, dU, d2U; aligned_vector<valT> DistCompressed; aligned_vector<int> DistIndice; Vector<posT> Grad; Vector<valT> Lap; ///Container for \f$F[ig*NumGroups+jg]\f$ std::vector<FT*> F; J1OrbitalSoA(const ParticleSet& ions, ParticleSet& els) : Ions(ions) { initalize(els); myTableID=els.addTable(ions,DT_SOA); OrbitalName = "J1OrbitalSoA"; } J1OrbitalSoA(const J1OrbitalSoA& rhs)=delete; ~J1OrbitalSoA() { for(int i=0; i<F.size(); ++i) if(F[i] != nullptr) delete F[i]; } /* initialize storage */ void initalize(ParticleSet& els) { Nions=Ions.getTotalNum(); NumGroups=Ions.getSpeciesSet().getTotalNum(); F.resize(std::max(NumGroups,4),nullptr); if(NumGroups>1 && !Ions.IsGrouped) { NumGroups=0; } Nelec=els.getTotalNum(); Vat.resize(Nelec); Grad.resize(Nelec); Lap.resize(Nelec); U.resize(Nions); dU.resize(Nions); d2U.resize(Nions); DistCompressed.resize(Nions); DistIndice.resize(Nions); } void addFunc(int source_type, FT* afunc, int target_type=-1) { if(F[source_type]!=nullptr) delete F[source_type]; F[source_type]=afunc; } void recompute(ParticleSet& P) { const DistanceTableData& d_ie(*(P.DistTables[myTableID])); for(int iat=0; iat<Nelec; ++iat) { computeU3(P,iat,d_ie.Distances[iat]); Vat[iat]=simd::accumulate_n(U.data(),Nions,valT()); Lap[iat]=accumulateGL(dU.data(),d2U.data(),d_ie.Displacements[iat],Grad[iat]); } } RealType evaluateLog(ParticleSet& P, ParticleSet::ParticleGradient_t& G, ParticleSet::ParticleLaplacian_t& L) { evaluateGL(P,G,L,true); return LogValue; } ValueType ratio(ParticleSet& P, int iat) { UpdateMode=ORB_PBYP_RATIO; curAt = computeU(P.DistTables[myTableID]->Temp_r.data()); return std::exp(Vat[iat]-curAt); } inline void evaluateRatios(VirtualParticleSet& VP, std::vector<ValueType>& ratios) { for(int k=0; k<ratios.size(); ++k) ratios[k]=std::exp(Vat[VP.refPtcl] - computeU(VP.DistTables[myTableID]->Distances[k])); } inline valT computeU(const valT* dist) { valT curVat(0); if(NumGroups>0) { for(int jg=0; jg<NumGroups; ++jg) { if(F[jg]!=nullptr) curVat += F[jg]->evaluateV(-1, Ions.first(jg), Ions.last(jg), dist, DistCompressed.data()); } } else { for(int c=0; c<Nions; ++c) { int gid=Ions.GroupID[c]; if(F[gid]!=nullptr) curVat += F[gid]->evaluate(dist[c]); } } return curVat; } void evaluateRatiosAlltoOne(ParticleSet& P, std::vector<ValueType>& ratios) { const valT* restrict dist=P.DistTables[myTableID]->Temp_r.data(); curAt = valT(0); if(NumGroups>0) { for(int jg=0; jg<NumGroups; ++jg) { if(F[jg]!=nullptr) curAt += F[jg]->evaluateV(-1, Ions.first(jg), Ions.last(jg), dist, DistCompressed.data()); } } else { for(int c=0; c<Nions; ++c) { int gid=Ions.GroupID[c]; if(F[gid]!=nullptr) curAt += F[gid]->evaluate(dist[c]); } } for(int i=0; i<Nelec; ++i) ratios[i]=std::exp(Vat[i]-curAt); } inline void evaluateGL(ParticleSet& P, ParticleSet::ParticleGradient_t& G, ParticleSet::ParticleLaplacian_t& L, bool fromscratch=false) { if(fromscratch) recompute(P); for(size_t iat=0; iat<Nelec; ++iat) G[iat]+=Grad[iat]; for(size_t iat=0; iat<Nelec; ++iat) L[iat]-=Lap[iat]; LogValue=-simd::accumulate_n(Vat.data(), Nelec, valT()); } /** compute gradient and lap * @return lap */ inline valT accumulateGL(const valT* restrict du, const valT* restrict d2u, const RowContainer& displ, posT& grad) const { valT lap(0); constexpr valT lapfac=OHMMS_DIM-RealType(1); //#pragma omp simd reduction(+:lap) for(int jat=0; jat<Nions; ++jat) lap+=d2u[jat]+lapfac*du[jat]; for(int idim=0; idim<OHMMS_DIM; ++idim) { const valT* restrict dX=displ.data(idim); valT s=valT(); //#pragma omp simd reduction(+:s) for(int jat=0; jat<Nions; ++jat) s+=du[jat]*dX[jat]; grad[idim]=s; } return lap; } /** compute U, dU and d2U * @param P quantum particleset * @param iat the moving particle * @param dist starting address of the distances of the ions wrt the iat-th particle */ inline void computeU3(ParticleSet& P, int iat, const valT* dist) { if(NumGroups>0) {//ions are grouped CONSTEXPR valT czero(0); std::fill_n(U.data(),Nions,czero); std::fill_n(dU.data(),Nions,czero); std::fill_n(d2U.data(),Nions,czero); for(int jg=0; jg<NumGroups; ++jg) { if(F[jg]==nullptr) continue; F[jg]->evaluateVGL(-1, Ions.first(jg), Ions.last(jg), dist, U.data(), dU.data(), d2U.data(), DistCompressed.data(), DistIndice.data()); } } else { for(int c=0; c<Nions; ++c) { int gid=Ions.GroupID[c]; if(F[gid]!=nullptr) { U[c]= F[gid]->evaluate(dist[c],dU[c],d2U[c]); dU[c]/=dist[c]; } } } } /** compute the gradient during particle-by-particle update * @param P quantum particleset * @param iat particle index */ GradType evalGrad(ParticleSet& P, int iat) { return GradType(Grad[iat]); } /** compute the gradient during particle-by-particle update * @param P quantum particleset * @param iat particle index * * Using Temp_r. curAt, curGrad and curLap are computed. */ ValueType ratioGrad(ParticleSet& P, int iat, GradType& grad_iat) { UpdateMode=ORB_PBYP_PARTIAL; computeU3(P,iat,P.DistTables[myTableID]->Temp_r.data()); curLap=accumulateGL(dU.data(),d2U.data(),P.DistTables[myTableID]->Temp_dr,curGrad); curAt=simd::accumulate_n(U.data(),Nions,valT()); grad_iat+=curGrad; return std::exp(Vat[iat]-curAt); } /** Rejected move. Nothing to do */ inline void restore(int iat) { } /** Accpted move. Update Vat[iat],Grad[iat] and Lap[iat] */ void acceptMove(ParticleSet& P, int iat) { if(UpdateMode == ORB_PBYP_RATIO) { computeU3(P,iat,P.DistTables[myTableID]->Temp_r.data()); curLap=accumulateGL(dU.data(),d2U.data(),P.DistTables[myTableID]->Temp_dr,curGrad); } LogValue += Vat[iat]-curAt; Vat[iat] = curAt; Grad[iat] = curGrad; Lap[iat] = curLap; } inline void registerData(ParticleSet& P, WFBufferType& buf) { if ( Bytes_in_WFBuffer == 0 ) { Bytes_in_WFBuffer = buf.current(); buf.add(Vat.begin(), Vat.end()); buf.add(Grad.begin(), Grad.end()); buf.add(Lap.begin(), Lap.end()); Bytes_in_WFBuffer = buf.current()-Bytes_in_WFBuffer; // free local space Vat.free(); Grad.free(); Lap.free(); } else { buf.forward(Bytes_in_WFBuffer); } } inline RealType updateBuffer(ParticleSet& P, WFBufferType& buf, bool fromscratch=false) { evaluateGL(P, P.G, P.L, false); buf.forward(Bytes_in_WFBuffer); return LogValue; } inline void copyFromBuffer(ParticleSet& P, WFBufferType& buf) { Vat.attachReference(buf.lendReference<valT>(Nelec), Nelec); Grad.attachReference(buf.lendReference<posT>(Nelec), Nelec); Lap.attachReference(buf.lendReference<valT>(Nelec), Nelec); } WaveFunctionComponentPtr makeClone(ParticleSet& tqp) const { J1OrbitalSoA<FT>* j1copy=new J1OrbitalSoA<FT>(Ions,tqp); j1copy->Optimizable=Optimizable; for (size_t i=0, n=F.size(); i<n; ++i) { if (F[i] != nullptr) j1copy->addFunc(i,new FT(*F[i])); } if (dPsi) { j1copy->dPsi = dPsi->makeClone(tqp); } return j1copy; } /**@{ WaveFunctionComponent virtual functions that are not essential for the development */ void resetTargetParticleSet(ParticleSet& P){} void reportStatus(std::ostream& os) { for (size_t i=0,n=F.size(); i<n; ++i) { if(F[i] != nullptr) F[i]->myVars.print(os); } } void checkInVariables(opt_variables_type& active) { myVars.clear(); for (size_t i=0,n=F.size(); i<n; ++i) { if(F[i] != nullptr) { F[i]->checkInVariables(active); F[i]->checkInVariables(myVars); } } } void checkOutVariables(const opt_variables_type& active) { myVars.getIndex(active); Optimizable=myVars.is_optimizable(); for (size_t i=0,n=F.size(); i<n; ++i) if (F[i] != nullptr) F[i]->checkOutVariables(active); if (dPsi) dPsi->checkOutVariables(active); } void resetParameters(const opt_variables_type& active) { if (!Optimizable) return; for (size_t i=0,n=F.size(); i<n; ++i) if (F[i] != nullptr) F[i]->resetParameters(active); for (int i=0; i<myVars.size(); ++i) { int ii=myVars.Index[i]; if (ii>=0) myVars[i]= active[ii]; } if (dPsi) dPsi->resetParameters(active); } /**@} */ }; } #endif
stresslet_rsrc.c
#include "mex.h" #include "math.h" #define X prhs[0] // Source locations #define F prhs[1] // Source strengths #define IDX prhs[2] // Source indeces #define DIS prhs[3] // Distances #define XI prhs[4] // Ewald Param #define U plhs[0] // Output #ifndef VERBOSE #define VERBOSE 0 #endif #define PI 3.141592653589793 static inline double dot(double x[], double y[]) { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; } void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { // input target const int M = mxGetM(X); const double xi = (double) mxGetScalar(XI); const double* restrict x = mxGetPr(X); const double* restrict f = mxGetPr(F); const double* restrict qvec = f; const double* restrict nvec = f + 3*M; // output U = mxCreateDoubleMatrix(M, 3, mxREAL); double* restrict u = mxGetPr(U); if(VERBOSE) mexPrintf("[FS Stresslet Real space ] MEX N=%d ",M); double xi2 = xi*xi; double xi3 = xi2*xi; // Loop through the cell #ifdef _OPENMP #pragma omp parallel for #endif for (int m=0; m<M; m++) { const mxArray * _IDX = mxGetCell(IDX, m); const mxArray * _DIS = mxGetCell(DIS, m); const int N= mxGetN(_IDX); // number of the source points in nblist double* idx= (double*) mxGetPr(_IDX);// index pointer of the source points in nblist double* dis= mxGetPr(_DIS); // distance pointer of the source points in nblist double p[3]; p[0] = 0; p[1] = 0; p[2] = 0; // First element is the target itself; see MATLAB doc for rangesearch. for(int n = 1; n<N; n++){ int idxn = (int) idx[n]-1; double qn[] = {qvec[idxn], qvec[idxn+M], qvec[idxn+2*M]}; double nn[] = {nvec[idxn], nvec[idxn+M], nvec[idxn+2*M]}; double rvec[] = {x[m]-x[idxn], x[m+M]-x[idxn+M],x[m+2*M]-x[idxn+2*M]}; double r = dis[n]; double r2= r*r; double c = xi2*r2; double expc = exp(-c); // Hasimoto double C = -2/(r2*r2)*( 3.0/r*erfc(xi*r) + 2.0*xi/sqrt(PI)*(3.0+2.0*c)*expc ); double D = 4/sqrt(PI)*xi3*expc; double rdotn = dot(rvec, nn); double rdotq = dot(rvec, qn); double ndotq = dot(nn, qn); double Kr = C*rdotn*rdotq + D*ndotq; double Kn = D*rdotq; double Kq = D*rdotn; for (int i=0; i<3; i++) { p[i] += Kr*rvec[i] + Kn*nn[i] + Kq*qn[i]; } } u[m ] = p[0]; u[m+ M] = p[1]; u[m+2*M] = p[2]; } }
GB_unaryop__identity_uint32_uint32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_uint32_uint32 // op(A') function: GB_tran__identity_uint32_uint32 // C type: uint32_t // A type: uint32_t // cast: uint32_t cij = (uint32_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ uint32_t z = (uint32_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_uint32_uint32 ( uint32_t *restrict Cx, const uint32_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_uint32_uint32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
omp_private.c
/* This file shows the problems with private variables which its value is NOT * copied. It also shows how the "firstprivate" directive can help with that. * * Code adapted from Introduction to Parallel Programming by Peter Pacheco. */ #include <stdio.h> #include <stdlib.h> #include <omp.h> int main(int argc, char* argv[]) { int x = 5; int thread_count = 8; #pragma omp parallel \ num_threads(thread_count) \ private(x) { int my_rank = omp_get_thread_num(); printf("Thread %d > before initialization, x = %d\n", my_rank, x); x = 2 * my_rank + 2; printf("Thread %d > after initialization, x = %d\n", my_rank, x); } printf("After parallel block, x = %d\n", x); return 0; }
ark_analytic_nonlin_ompdev.c
/*----------------------------------------------------------------- * Programmer(s): Shelby Lockhart @ LLNL *--------------------------------------------------------------- * This code is based on the serial code found in * ark_analytic_nonlin.c developed by Daniel R. Reynolds *--------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2022, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End *--------------------------------------------------------------- * Example problem: * * The following is a simple example problem with analytical * solution, * dy/dt = (t+1)*exp(-y) * for t in the interval [0.0, 10.0], with initial condition: y=0. * This has analytical solution * y(t) = log(0.5*t^2 + t + 1) * * This program solves the problem with the ERK method. * Output is printed every 1.0 units of time (10 total). * Run statistics (optional outputs) are printed at the end. *-----------------------------------------------------------------*/ /* Header files */ #include <stdio.h> #include <math.h> #include <arkode/arkode_erkstep.h> /* prototypes for ERKStep fcts., consts */ #include <nvector/nvector_openmpdev.h> /* OpenMPDEV N_Vector types, fcts., macros */ #include <sundials/sundials_types.h> /* def. of type 'realtype' */ #include <sundials/sundials_math.h> /* def. of SUNRsqrt, etc. */ #ifdef _OPENMP #include <omp.h> /* OpenMP functions */ #endif #if defined(SUNDIALS_EXTENDED_PRECISION) #define GSYM "Lg" #define ESYM "Le" #define FSYM "Lf" #else #define GSYM "g" #define ESYM "e" #define FSYM "f" #endif /* User-supplied Functions Called by the Solver */ static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data); /* Private function to check function return values */ static int check_flag(void *flagvalue, const char *funcname, int opt); /* Main Program */ int main() { /* general problem parameters */ realtype T0 = RCONST(0.0); /* initial time */ realtype Tf = RCONST(10.0); /* final time */ realtype dTout = RCONST(1.0); /* time between outputs */ sunindextype NEQ = 1; /* number of dependent vars. */ realtype reltol = 1.0e-6; /* tolerances */ realtype abstol = 1.0e-10; /* general problem variables */ int flag; /* reusable error-checking flag */ N_Vector y = NULL; /* empty vector for storing solution */ void *arkode_mem = NULL; /* empty ARKode memory structure */ FILE *UFID; realtype t, tout; long int nst, nst_a, nfe, netf; realtype *y_data = NULL; /* Create the SUNDIALS context object for this simulation */ SUNContext ctx; flag = SUNContext_Create(NULL, &ctx); if (check_flag(&flag, "SUNContext_Create", 1)) return 1; /* Initial problem output */ printf("\nAnalytical ODE test problem:\n"); printf(" reltol = %.1"ESYM"\n", reltol); printf(" abstol = %.1"ESYM"\n\n",abstol); /* Initialize data structures */ y = N_VNew_OpenMPDEV(NEQ, ctx); /* Create OpenMPDEV vector for solution */ if (check_flag((void *)y, "N_VNew_OpenMPDEV", 0)) return 1; y_data = N_VGetHostArrayPointer_OpenMPDEV(y); y_data[0] = 0.0; /* Specify initial condition */ N_VCopyToDevice_OpenMPDEV(y); /* Copy to device */ arkode_mem = ERKStepCreate(f, T0, y, ctx); /* Create the solver memory */ if (check_flag((void *)arkode_mem, "ERKStepCreate", 0)) return 1; /* Specify tolerances */ flag = ERKStepSStolerances(arkode_mem, reltol, abstol); if (check_flag(&flag, "ERKStepSStolerances", 1)) return 1; /* Open output stream for results, output comment line */ UFID = fopen("solution.txt","w"); fprintf(UFID,"# t u\n"); /* output initial condition to disk */ N_VCopyFromDevice_OpenMPDEV(y); fprintf(UFID," %.16"ESYM" %.16"ESYM"\n", T0, y_data[0]); /* Main time-stepping loop: calls ERKStep to perform the integration, then prints results. Stops when the final time has been reached */ t = T0; tout = T0+dTout; printf(" t u\n"); printf(" ---------------------\n"); while (Tf - t > 1.0e-15) { flag = ERKStepEvolve(arkode_mem, tout, y, &t, ARK_NORMAL); /* call integrator */ if (check_flag(&flag, "ERKStep", 1)) break; N_VCopyFromDevice_OpenMPDEV(y); printf(" %10.6"FSYM" %10.6"FSYM"\n", t, y_data[0]); /* access/print solution */ fprintf(UFID," %.16"ESYM" %.16"ESYM"\n", t, y_data[0]); if (flag >= 0) { /* successful solve: update time */ tout += dTout; tout = (tout > Tf) ? Tf : tout; } else { /* unsuccessful solve: break */ fprintf(stderr,"Solver failure, stopping integration\n"); break; } } printf(" ---------------------\n"); fclose(UFID); /* Print some final statistics */ flag = ERKStepGetNumSteps(arkode_mem, &nst); check_flag(&flag, "ERKStepGetNumSteps", 1); flag = ERKStepGetNumStepAttempts(arkode_mem, &nst_a); check_flag(&flag, "ERKStepGetNumStepAttempts", 1); flag = ERKStepGetNumRhsEvals(arkode_mem, &nfe); check_flag(&flag, "ERKStepGetNumRhsEvals", 1); flag = ERKStepGetNumErrTestFails(arkode_mem, &netf); check_flag(&flag, "ERKStepGetNumErrTestFails", 1); printf("\nFinal Solver Statistics:\n"); printf(" Internal solver steps = %li (attempted = %li)\n", nst, nst_a); printf(" Total RHS evals = %li\n", nfe); printf(" Total number of error test failures = %li\n\n", netf); /* Clean up and return with successful completion */ N_VDestroy(y); /* Free y vector */ ERKStepFree(&arkode_mem); /* Free integrator memory */ SUNContext_Free(&ctx); /* Free context */ return 0; } /*------------------------------- * Functions called by the solver *-------------------------------*/ /* f routine to compute the ODE RHS function f(t,y). */ static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data) { int dev; realtype *y_data = N_VGetDeviceArrayPointer_OpenMPDEV(y); realtype *ydot_data = N_VGetDeviceArrayPointer_OpenMPDEV(ydot); dev = omp_get_default_device(); #pragma omp target map(to:t) is_device_ptr(y_data, ydot_data) device(dev) { ydot_data[0] = (t+1.0)*SUNRexp(-1.0 * y_data[0]); } return 0; } /*------------------------------- * Private helper functions *-------------------------------*/ /* Check function return value... opt == 0 means SUNDIALS function allocates memory so check if returned NULL pointer opt == 1 means SUNDIALS function returns a flag so check if flag >= 0 opt == 2 means function allocates memory so check if returned NULL pointer */ static int check_flag(void *flagvalue, const char *funcname, int opt) { int *errflag; /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ if (opt == 0 && flagvalue == NULL) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return 1; } /* Check if flag < 0 */ else if (opt == 1) { errflag = (int *) flagvalue; if (*errflag < 0) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with flag = %d\n\n", funcname, *errflag); return 1; }} /* Check if function returned NULL pointer - no memory allocated */ else if (opt == 2 && flagvalue == NULL) { fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return 1; } return 0; } /*---- end of file ----*/
q_rhashmap_add.tmpl.c
/* * Copyright (c) 2019 Ramesh Subramonian <subramonian@gmail.com> * All rights reserved. * * Use is subject to license terms, as specified in the LICENSE file. This code was initially forked from the following. Subsequent to that, significant modifications have been made and new functionality added, bugs fixes, .... * Copyright (c) 2017 Mindaugas Rasiukevicius <rmind at noxt eu> * All rights reserved. * * Use is subject to license terms, as specified in the LICENSE file. */ /* * A general purpose hash table, using the Robin Hood hashing algorithm. * * Conceptually, it is a hash table using linear probing on lookup with * a particular displacement strategy on inserts. The central idea of * the Robin Hood hashing algorithm is to reduce the variance of the * probe sequence length (PSL). * * Reference: * * Pedro Celis, 1986, Robin Hood Hashing, University of Waterloo * https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf */ #include "_q_rhashmap__add___KV__.h" static int __attribute__((__unused__)) validate_psl_p( q_rhashmap___KV___t *hmap, const q_rh_bucket___KV___t *bucket, uint32_t i ) { uint32_t base_i = fast_rem32(bucket->hash, hmap->size, hmap->divinfo); uint32_t diff = (base_i > i) ? hmap->size - base_i + i : i - base_i; return bucket->key == 0 || diff == bucket->psl; } /* Checks whether resize is needed. If so, calculates newsize */ /* Resize needed when occupancy is too high or too low */ static int calc_new_size( uint32_t nitems, uint32_t minsize, uint32_t size, bool decreasing, /* true => just added an element and are concerned about sparsity * false=> just added an element and are concerned about denseness */ uint32_t *ptr_newsize, bool *ptr_resize ) { int status = 0; *ptr_resize = false; *ptr_newsize = 0; uint32_t threshold; if ( decreasing ) { /* * If the load factor is less than threshold, then shrink by * halving the size, but not more than the minimum size. */ threshold = (uint32_t)(LOW_WATER_MARK * size); if ( ( nitems > minsize ) && ( nitems < threshold ) ) { *ptr_resize = true; *ptr_newsize = MAX(size >> 1, minsize); } } else { /* * If the load factor is more than the threshold, then resize. */ threshold = (uint32_t)(0.85 * (float)size); // TODO P4 Clean up the following code if ( nitems > threshold ) { *ptr_resize = true; for ( ; nitems > threshold; ) { /* * Grow the hash table by doubling its size, but with * a limit of MAX_GROWTH_STEP. */ // TODO: P4 Worry about overflow in addition below const size_t grow_limit = size + MAX_GROWTH_STEP; *ptr_newsize = MIN(size << 1, grow_limit); threshold = (uint32_t)(0.85 * *ptr_newsize); } } } return status; } /* * q_rhashmap_get: lookup an value given the key. * * => If key is present, *ptr_val is set to its associated value * and is_found is set to true * => If key is absent, *ptr_val is set to 0 * and is_found is set to false */ int q_rhashmap_get___KV__( q_rhashmap___KV___t *hmap, __KEYTYPE__ key, __VALTYPE__ *ptr_val, bool *ptr_is_found ) { int status = 0; const uint32_t hash = murmurhash3(&key, sizeof(__KEYTYPE__), hmap->hashkey); uint32_t n = 0; uint32_t i = fast_rem32(hash, hmap->size, hmap->divinfo); q_rh_bucket___KV___t *bucket = NULL; *ptr_is_found = false; *ptr_val = 0; /* * Lookup is a linear probe. */ register uint64_t divinfo = hmap->divinfo; register uint64_t size = hmap->size; for ( ; ; ) { bucket = &hmap->buckets[i]; ASSERT(validate_psl_p(hmap, bucket, i)); if ( ( bucket->hash == hash ) && ( bucket->key == key ) ) { *ptr_val = bucket->val; *ptr_is_found = true; break; } /* * Stop probing if we hit an empty bucket; also, if we hit a * bucket with PSL lower than the distance from the base location, * then it means that we found the "rich" bucket which should * have been captured, if the key was inserted -- see the central * point of the algorithm in the insertion function. */ if ( ( !bucket->key ) || ( n > bucket->psl ) ) { *ptr_is_found = false; break; } n++; /* Continue to the next bucket. */ i = fast_rem32(i + 1, size, divinfo); } return status; } //------------------------------------------------------ int q_rhashmap_getn___KV__( q_rhashmap___KV___t *hmap, // INPUT __KEYTYPE__ *keys, // INPUT: [nkeys] uint32_t *hashes, // INPUT [nkeys] uint32_t *locs, // INPUT [nkeys] __VALTYPE__ *vals, // OUTPUT [nkeys] uint32_t nkeys // INPUT // TODO P4 we won't do is_found for the first implementation ) { int status = 0; int chunk_size = 1024; #pragma omp parallel for schedule(static, chunk_size) for ( uint32_t j = 0; j < nkeys; j++ ) { uint32_t n = 0; uint32_t i = locs[j]; uint32_t hash = hashes[j]; q_rh_bucket___KV___t *bucket = NULL; vals[j] = 0; for ( ; ; ) { bucket = &hmap->buckets[i]; ASSERT(validate_psl_p(hmap, bucket, i)); if ( ( bucket->hash == hash ) && ( bucket->key == keys[j] ) ) { vals[j] = bucket->val; break; // found } if (!bucket->key || n > bucket->psl) { break; // not found } n++; i = fast_rem32(i + 1, hmap->size, hmap->divinfo); } } return status; } /* * rhashmap_insert: internal rhashmap_put(), without the resize. */ static int q_rhashmap_insert( q_rhashmap___KV___t *hmap, __KEYTYPE__ key, __VALTYPE__ val, int update_type, __VALTYPE__ *ptr_oldval, int *ptr_num_probes ) { int status = 0; const uint32_t hash = murmurhash3(&key, sizeof(__KEYTYPE__), hmap->hashkey); q_rh_bucket___KV___t *bucket, entry; uint32_t i; int num_probes = 0; register uint32_t size = hmap->size; register uint64_t divinfo = hmap->divinfo; bool key_updated = false; // 0 is not a valid value for a key, TODO P3 Document this better // Note that we do NOT throw an error if ( key == 0 ) { return status; } // Setup the bucket entry. entry.key = key; entry.hash = hash; entry.val = val; entry.psl = 0; *ptr_oldval = 0; /* * From the paper: "when inserting, if a record probes a location * that is already occupied, the record that has traveled longer * in its probe sequence keeps the location, and the other one * continues on its probe sequence" (page 12). * * Basically: if the probe sequence length (PSL) of the element * being inserted is greater than PSL of the element in the bucket, * then swap them and continue. */ i = fast_rem32(hash, hmap->size, hmap->divinfo); for ( ; ; ) { bucket = &hmap->buckets[i]; // If there is a key in the bucket. if ( bucket->key ) { ASSERT(validate_psl_p(hmap, bucket, i)); // TODO P4 Why are we comparing the hash at all below? // If there is a key in the bucket and its you if ( (bucket->hash == hash) && (bucket->key == key) ) { key_updated = true; // do the prescribed update *ptr_oldval = bucket->val; if ( update_type == Q_RHM_SET ) { bucket->val = val; } else if ( update_type == Q_RHM_ADD ) { bucket->val += val; } else { go_BYE(-1); } break; } // We found a "rich" bucket. Capture its location. if (entry.psl > bucket->psl) { q_rh_bucket___KV___t tmp; /* * Place our key-value pair by swapping the "rich" * bucket with our entry. Copy the structures. */ tmp = entry; entry = *bucket; *bucket = tmp; } entry.psl++; /* Continue to the next bucket. */ ASSERT(validate_psl_p(hmap, bucket, i)); num_probes++; i = fast_rem32(i + 1, size, divinfo); } else { break; } } if ( !key_updated ) { // Found a free bucket: insert the entry. *bucket = entry; // copy hmap->nitems++; } ASSERT(validate_psl_p(hmap, bucket, i)); *ptr_num_probes = num_probes; BYE: return status; } static int q_rhashmap_resize( q_rhashmap___KV___t *hmap, size_t newsize ) { int status = 0; q_rh_bucket___KV___t *oldbuckets = hmap->buckets; const size_t oldsize = hmap->size; q_rh_bucket___KV___t *newbuckets = NULL; const size_t len = newsize * sizeof(q_rh_bucket___KV___t); int num_probes = 0; // some obvious logical checks if ( ( oldbuckets == NULL ) && ( oldsize != 0 ) ) { go_BYE(-1); } if ( ( oldbuckets != NULL ) && ( oldsize == 0 ) ) { go_BYE(-1); } if ( ( newsize <= 0 ) || ( newsize >= UINT_MAX ) ) { go_BYE(-1); } if ( newsize < hmap->nitems ) { go_BYE(-1); } // allocate buckets. newbuckets = malloc(len); return_if_malloc_failed(newbuckets); memset(newbuckets, '\0', len); hmap->buckets = newbuckets; hmap->size = newsize; hmap->nitems = 0; // generate a new hash key/seed every time we resize the hash table. hmap->divinfo = fast_div32_init(newsize); hmap->hashkey ^= random() | (random() << 32); for ( uint32_t i = 0; i < oldsize; i++) { const q_rh_bucket___KV___t *bucket = &oldbuckets[i]; /* Skip the empty buckets. */ if ( !bucket->key ) { continue; } __VALTYPE__ oldval; // not needed except for signature q_rhashmap_insert(hmap, bucket->key, bucket->val, Q_RHM_SET, &oldval, &num_probes); } free_if_non_null(oldbuckets); BYE: return status; } /* * rhashmap_put: insert a value given the key. * * => If the key is already present, return its associated value. * => Otherwise, on successful insert, return the given value. */ int q_rhashmap_put___KV__( q_rhashmap___KV___t *hmap, __KEYTYPE__ key, __VALTYPE__ val, int update_type, __VALTYPE__ *ptr_oldval, int *ptr_num_probes ) { int status = 0; uint32_t newsize; bool resize, decreasing = false; status = calc_new_size(hmap->nitems, hmap->minsize, hmap->size, decreasing, &newsize, &resize); if ( resize ) { status = q_rhashmap_resize(hmap, newsize); cBYE(status); } status = q_rhashmap_insert(hmap, key, val, update_type, ptr_oldval, ptr_num_probes); cBYE(status); BYE: return status; } /* * rhashmap_del: remove the given key and return its value. * * => If key was present, return its associated value; otherwise NULL. */ int q_rhashmap_del___KV__( q_rhashmap___KV___t *hmap, __KEYTYPE__ key, __VALTYPE__ *ptr_oldval, bool *ptr_is_found ) { int status = 0; const uint32_t hash = murmurhash3(&key, sizeof(__KEYTYPE__), hmap->hashkey); uint32_t n = 0, i = fast_rem32(hash, hmap->size, hmap->divinfo); q_rh_bucket___KV___t *bucket; *ptr_oldval = 0; bool decreasing = true, resize; uint32_t newsize; probe: /* * The same probing logic as in the lookup function. */ bucket = &hmap->buckets[i]; if (bucket->key == 0 ) { *ptr_is_found = false; goto BYE; } if ( n > bucket->psl ) { *ptr_is_found = false; goto BYE; } ASSERT(validate_psl_p(hmap, bucket, i)); if ( ( bucket->hash != hash ) || ( bucket->key != key ) ) { /* Continue to the next bucket. */ i = fast_rem32(i + 1, hmap->size, hmap->divinfo); n++; goto probe; } // Free the bucket. bucket->key = 0; *ptr_oldval = bucket->val; *ptr_is_found = true; bucket->val = 0; bucket->hash = 0; bucket->psl = 0; hmap->nitems--; /* * The probe sequence must be preserved in the deletion case. * Use the backwards-shifting method to maintain low variance. */ for ( ; ; ) { q_rh_bucket___KV___t *nbucket = NULL; bucket->key = 0; bucket->val = 0; bucket->hash = 0; bucket->psl = 0; i = fast_rem32(i + 1, hmap->size, hmap->divinfo); nbucket = &hmap->buckets[i]; ASSERT(validate_psl_p(hmap, nbucket, i)); /* * Stop if we reach an empty bucket or hit a key which * is in its base (original) location. */ if (!nbucket->key || nbucket->psl == 0) { break; } nbucket->psl--; *bucket = *nbucket; bucket = nbucket; } status = calc_new_size(hmap->nitems, hmap->minsize, hmap->size, decreasing, &newsize, &resize); cBYE(status); if ( resize ) { status = q_rhashmap_resize(hmap, newsize); cBYE(status); } BYE: return status; } /* * rhashmap_create: construct a new hash table. * * => If size is non-zero, then pre-allocate the given number of buckets; * => If size is zero, then a default minimum is used. */ q_rhashmap___KV___t * q_rhashmap_create___KV__( size_t size ) { q_rhashmap___KV___t *hmap = NULL; hmap = calloc(1, sizeof(q_rhashmap___KV___t)); if ( hmap == NULL ) { return NULL; } hmap->minsize = MAX(size, HASH_INIT_SIZE); if ( q_rhashmap_resize(hmap, hmap->minsize) != 0) { free(hmap); return NULL; } if (hmap->buckets == NULL ) { WHEREAMI; return NULL; } if (hmap->size == 0 ) { WHEREAMI; return NULL; } return hmap; } /* * rhashmap_destroy: free the memory used by the hash table. * * => It is the responsibility of the caller to remove elements if needed. */ void q_rhashmap_destroy___KV__( q_rhashmap___KV___t *ptr_hmap ) { free(ptr_hmap->buckets); ptr_hmap->buckets = NULL; ptr_hmap->size = 0; ptr_hmap->nitems = 0; ptr_hmap->divinfo = 0; ptr_hmap->buckets = 0; ptr_hmap->hashkey = 0; ptr_hmap->minsize = 0; free(ptr_hmap); ptr_hmap = NULL; } // Given // (1) a set of keys // (2) hash for each key // (3) value for each key // Update as follows. If j^{th} key found, then // (A) set is_found[j] to true // (B) update value with new value provided (either set or add) // Else, set is_found[j] to false int q_rhashmap_putn___KV__( q_rhashmap___KV___t *hmap, // INPUT int update_type, // INPUT __KEYTYPE__ *keys, // INPUT [nkeys] uint32_t *hashes, // INPUT [nkeys] uint32_t *locs, // INPUT [nkeys] -- starting point for probe uint8_t *tids, // INPUT [nkeys] -- thread who should work on it int nT, __VALTYPE__ *vals, // INPUT [nkeys] uint32_t nkeys, // INPUT uint8_t *is_founds // OUTPUT [nkeys bits] TODO: Change from byte to bit ) { int status = 0; int *is_new = NULL; register uint32_t hmap_size = hmap->size; register uint64_t hmap_divinfo = hmap->divinfo; // quick sanity check switch ( update_type ) { case Q_RHM_SET : case Q_RHM_ADD : break; default: go_BYE(-1); break; } is_new = malloc(nT * sizeof(int)); return_if_malloc_failed(is_new); for ( int i = 0; i < nT; i++ ) { is_new[i] = 0; } #pragma omp parallel { // TODO P3 Can I avoid get_thread_num() in each iteration? register uint32_t mytid = omp_get_thread_num(); for ( uint32_t j = 0; j < nkeys; j++ ) { // Following so that 2 threads don't deal with same key if ( tids[j] != mytid ) { continue; } register uint32_t hash = hashes[j]; register q_rh_bucket___KV___t *buckets = hmap->buckets; register __KEYTYPE__ key = keys[j]; register __VALTYPE__ val = vals[j]; uint32_t i = locs[j]; // fast_rem32(hash, hmap_size, hmap_divinfo); is_founds[j] = 0; uint32_t n = 0; for ( ; ; ) { // search until found q_rh_bucket___KV___t *bucket = buckets + i; ASSERT(validate_psl_p(hmap, bucket, i)); // TODO P4 needed? if ( ( bucket->hash == hash ) && ( bucket->key == key ) ) { switch ( update_type ) { case Q_RHM_SET : bucket->val = val; break; case Q_RHM_ADD : bucket->val += val; break; } is_founds[j] = 1; break; } if ( ( !bucket->key ) || ( n > bucket->psl ) ) { // not found is_founds[j] = 0; break; } n++; i = fast_rem32(i + 1, hmap_size, hmap_divinfo); } if ( is_founds[j] == 0 ) { if ( is_new[mytid] == 0 ) { is_new[mytid] = 1; } } } } // Find out if new keys were provided in the above loop bool need_sequential_put = false; for ( int i = 0; i < nT; i++ ) { if ( is_new[i] != 0 ) { need_sequential_put = true; } } // If so, we have no choice but to put these in sequentially // TODO P2: Currently, we are scannning the entire list of keys, // looking for the ones to add. Ideally, each thread should keep // a list of keys to be added and we should just scan that list. int num_new = 0; if ( need_sequential_put ) { for ( unsigned int i = 0; i < nkeys; i++ ) { if ( is_founds[i] == 0 ) { __VALTYPE__ oldval; int num_probes; // TODO P2 Should do this properly status = q_rhashmap_put___KV__(hmap, keys[i], vals[i], update_type, &oldval, &num_probes); cBYE(status); /* Following has been commented out because it is a wrong check By definition, these keys don't exist and hence oldval == 0 if ( oldval != 0 ) { go_BYE(-1); } */ num_new++; } } // TODO P1: Should return num_new as diagnostic information if ( num_new == 0 ) { go_BYE(-1); } } BYE: free_if_non_null(is_new); return status; }
gimplify.c
/* Tree lowering pass. This pass converts the GENERIC functions-as-trees tree representation into the GIMPLE form. Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. Major work done by Sebastian Pop <s.pop@laposte.net>, Diego Novillo <dnovillo@redhat.com> and Jason Merrill <jason@redhat.com>. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "tree.h" #include "rtl.h" #include "varray.h" #include "gimple.h" #include "tree-iterator.h" #include "tree-inline.h" #include "diagnostic.h" #include "langhooks.h" #include "langhooks-def.h" #include "tree-flow.h" #include "cgraph.h" #include "timevar.h" #include "except.h" #include "hashtab.h" #include "flags.h" #include "real.h" #include "function.h" #include "output.h" #include "expr.h" #include "ggc.h" #include "toplev.h" #include "target.h" #include "optabs.h" #include "pointer-set.h" #include "splay-tree.h" #include "vec.h" #include "gimple.h" #include "tree-pass.h" enum gimplify_omp_var_data { GOVD_SEEN = 1, GOVD_EXPLICIT = 2, GOVD_SHARED = 4, GOVD_PRIVATE = 8, GOVD_FIRSTPRIVATE = 16, GOVD_LASTPRIVATE = 32, GOVD_REDUCTION = 64, GOVD_LOCAL = 128, GOVD_DEBUG_PRIVATE = 256, GOVD_PRIVATE_OUTER_REF = 512, GOVD_DATA_SHARE_CLASS = (GOVD_SHARED | GOVD_PRIVATE | GOVD_FIRSTPRIVATE | GOVD_LASTPRIVATE | GOVD_REDUCTION | GOVD_LOCAL) }; enum omp_region_type { ORT_WORKSHARE = 0, ORT_PARALLEL = 2, ORT_COMBINED_PARALLEL = 3, ORT_TASK = 4, ORT_UNTIED_TASK = 5 }; struct gimplify_omp_ctx { struct gimplify_omp_ctx *outer_context; splay_tree variables; struct pointer_set_t *privatized_types; location_t location; enum omp_clause_default_kind default_kind; enum omp_region_type region_type; }; static struct gimplify_ctx *gimplify_ctxp; static struct gimplify_omp_ctx *gimplify_omp_ctxp; /* Formal (expression) temporary table handling: Multiple occurrences of the same scalar expression are evaluated into the same temporary. */ typedef struct gimple_temp_hash_elt { tree val; /* Key */ tree temp; /* Value */ } elt_t; /* Forward declarations. */ static enum gimplify_status gimplify_compound_expr (tree *, gimple_seq *, bool); /* Mark X addressable. Unlike the langhook we expect X to be in gimple form and we don't do any syntax checking. */ void mark_addressable (tree x) { while (handled_component_p (x)) x = TREE_OPERAND (x, 0); if (TREE_CODE (x) != VAR_DECL && TREE_CODE (x) != PARM_DECL && TREE_CODE (x) != RESULT_DECL) return ; TREE_ADDRESSABLE (x) = 1; } /* Return a hash value for a formal temporary table entry. */ static hashval_t gimple_tree_hash (const void *p) { tree t = ((const elt_t *) p)->val; return iterative_hash_expr (t, 0); } /* Compare two formal temporary table entries. */ static int gimple_tree_eq (const void *p1, const void *p2) { tree t1 = ((const elt_t *) p1)->val; tree t2 = ((const elt_t *) p2)->val; enum tree_code code = TREE_CODE (t1); if (TREE_CODE (t2) != code || TREE_TYPE (t1) != TREE_TYPE (t2)) return 0; if (!operand_equal_p (t1, t2, 0)) return 0; /* Only allow them to compare equal if they also hash equal; otherwise results are nondeterminate, and we fail bootstrap comparison. */ gcc_assert (gimple_tree_hash (p1) == gimple_tree_hash (p2)); return 1; } /* Link gimple statement GS to the end of the sequence *SEQ_P. If *SEQ_P is NULL, a new sequence is allocated. This function is similar to gimple_seq_add_stmt, but does not scan the operands. During gimplification, we need to manipulate statement sequences before the def/use vectors have been constructed. */ void gimplify_seq_add_stmt (gimple_seq *seq_p, gimple gs) { gimple_stmt_iterator si; if (gs == NULL) return; if (*seq_p == NULL) *seq_p = gimple_seq_alloc (); si = gsi_last (*seq_p); gsi_insert_after_without_update (&si, gs, GSI_NEW_STMT); } /* Append sequence SRC to the end of sequence *DST_P. If *DST_P is NULL, a new sequence is allocated. This function is similar to gimple_seq_add_seq, but does not scan the operands. During gimplification, we need to manipulate statement sequences before the def/use vectors have been constructed. */ static void gimplify_seq_add_seq (gimple_seq *dst_p, gimple_seq src) { gimple_stmt_iterator si; if (src == NULL) return; if (*dst_p == NULL) *dst_p = gimple_seq_alloc (); si = gsi_last (*dst_p); gsi_insert_seq_after_without_update (&si, src, GSI_NEW_STMT); } /* Set up a context for the gimplifier. */ void push_gimplify_context (struct gimplify_ctx *c) { memset (c, '\0', sizeof (*c)); c->prev_context = gimplify_ctxp; gimplify_ctxp = c; } /* Tear down a context for the gimplifier. If BODY is non-null, then put the temporaries into the outer BIND_EXPR. Otherwise, put them in the local_decls. BODY is not a sequence, but the first tuple in a sequence. */ void pop_gimplify_context (gimple body) { struct gimplify_ctx *c = gimplify_ctxp; gcc_assert (c && (c->bind_expr_stack == NULL || VEC_empty (gimple, c->bind_expr_stack))); VEC_free (gimple, heap, c->bind_expr_stack); gimplify_ctxp = c->prev_context; if (body) declare_vars (c->temps, body, false); else record_vars (c->temps); if (c->temp_htab) htab_delete (c->temp_htab); } static void gimple_push_bind_expr (gimple gimple_bind) { if (gimplify_ctxp->bind_expr_stack == NULL) gimplify_ctxp->bind_expr_stack = VEC_alloc (gimple, heap, 8); VEC_safe_push (gimple, heap, gimplify_ctxp->bind_expr_stack, gimple_bind); } static void gimple_pop_bind_expr (void) { VEC_pop (gimple, gimplify_ctxp->bind_expr_stack); } gimple gimple_current_bind_expr (void) { return VEC_last (gimple, gimplify_ctxp->bind_expr_stack); } /* Return the stack GIMPLE_BINDs created during gimplification. */ VEC(gimple, heap) * gimple_bind_expr_stack (void) { return gimplify_ctxp->bind_expr_stack; } /* Returns true iff there is a COND_EXPR between us and the innermost CLEANUP_POINT_EXPR. This info is used by gimple_push_cleanup. */ static bool gimple_conditional_context (void) { return gimplify_ctxp->conditions > 0; } /* Note that we've entered a COND_EXPR. */ static void gimple_push_condition (void) { #ifdef ENABLE_GIMPLE_CHECKING if (gimplify_ctxp->conditions == 0) gcc_assert (gimple_seq_empty_p (gimplify_ctxp->conditional_cleanups)); #endif ++(gimplify_ctxp->conditions); } /* Note that we've left a COND_EXPR. If we're back at unconditional scope now, add any conditional cleanups we've seen to the prequeue. */ static void gimple_pop_condition (gimple_seq *pre_p) { int conds = --(gimplify_ctxp->conditions); gcc_assert (conds >= 0); if (conds == 0) { gimplify_seq_add_seq (pre_p, gimplify_ctxp->conditional_cleanups); gimplify_ctxp->conditional_cleanups = NULL; } } /* A stable comparison routine for use with splay trees and DECLs. */ static int splay_tree_compare_decl_uid (splay_tree_key xa, splay_tree_key xb) { tree a = (tree) xa; tree b = (tree) xb; return DECL_UID (a) - DECL_UID (b); } /* Create a new omp construct that deals with variable remapping. */ static struct gimplify_omp_ctx * new_omp_context (enum omp_region_type region_type) { struct gimplify_omp_ctx *c; c = XCNEW (struct gimplify_omp_ctx); c->outer_context = gimplify_omp_ctxp; c->variables = splay_tree_new (splay_tree_compare_decl_uid, 0, 0); c->privatized_types = pointer_set_create (); c->location = input_location; c->region_type = region_type; if ((region_type & ORT_TASK) == 0) c->default_kind = OMP_CLAUSE_DEFAULT_SHARED; else c->default_kind = OMP_CLAUSE_DEFAULT_UNSPECIFIED; return c; } /* Destroy an omp construct that deals with variable remapping. */ static void delete_omp_context (struct gimplify_omp_ctx *c) { splay_tree_delete (c->variables); pointer_set_destroy (c->privatized_types); XDELETE (c); } static void omp_add_variable (struct gimplify_omp_ctx *, tree, unsigned int); static bool omp_notice_variable (struct gimplify_omp_ctx *, tree, bool); /* A subroutine of append_to_statement_list{,_force}. T is not NULL. */ static void append_to_statement_list_1 (tree t, tree *list_p) { tree list = *list_p; tree_stmt_iterator i; if (!list) { if (t && TREE_CODE (t) == STATEMENT_LIST) { *list_p = t; return; } *list_p = list = alloc_stmt_list (); } i = tsi_last (list); tsi_link_after (&i, t, TSI_CONTINUE_LINKING); } /* Add T to the end of the list container pointed to by LIST_P. If T is an expression with no effects, it is ignored. */ void append_to_statement_list (tree t, tree *list_p) { if (t && TREE_SIDE_EFFECTS (t)) append_to_statement_list_1 (t, list_p); } /* Similar, but the statement is always added, regardless of side effects. */ void append_to_statement_list_force (tree t, tree *list_p) { if (t != NULL_TREE) append_to_statement_list_1 (t, list_p); } /* Both gimplify the statement T and append it to *SEQ_P. This function behaves exactly as gimplify_stmt, but you don't have to pass T as a reference. */ void gimplify_and_add (tree t, gimple_seq *seq_p) { gimplify_stmt (&t, seq_p); } /* Gimplify statement T into sequence *SEQ_P, and return the first tuple in the sequence of generated tuples for this statement. Return NULL if gimplifying T produced no tuples. */ static gimple gimplify_and_return_first (tree t, gimple_seq *seq_p) { gimple_stmt_iterator last = gsi_last (*seq_p); gimplify_and_add (t, seq_p); if (!gsi_end_p (last)) { gsi_next (&last); return gsi_stmt (last); } else return gimple_seq_first_stmt (*seq_p); } /* Strip off a legitimate source ending from the input string NAME of length LEN. Rather than having to know the names used by all of our front ends, we strip off an ending of a period followed by up to five characters. (Java uses ".class".) */ static inline void remove_suffix (char *name, int len) { int i; for (i = 2; i < 8 && len > i; i++) { if (name[len - i] == '.') { name[len - i] = '\0'; break; } } } /* Create a new temporary name with PREFIX. Returns an identifier. */ static GTY(()) unsigned int tmp_var_id_num; tree create_tmp_var_name (const char *prefix) { char *tmp_name; if (prefix) { char *preftmp = ASTRDUP (prefix); remove_suffix (preftmp, strlen (preftmp)); prefix = preftmp; } ASM_FORMAT_PRIVATE_NAME (tmp_name, prefix ? prefix : "T", tmp_var_id_num++); return get_identifier (tmp_name); } /* Create a new temporary variable declaration of type TYPE. Does NOT push it into the current binding. */ tree create_tmp_var_raw (tree type, const char *prefix) { tree tmp_var; tree new_type; /* Make the type of the variable writable. */ new_type = build_type_variant (type, 0, 0); TYPE_ATTRIBUTES (new_type) = TYPE_ATTRIBUTES (type); tmp_var = build_decl (input_location, VAR_DECL, prefix ? create_tmp_var_name (prefix) : NULL, type); /* The variable was declared by the compiler. */ DECL_ARTIFICIAL (tmp_var) = 1; /* And we don't want debug info for it. */ DECL_IGNORED_P (tmp_var) = 1; /* Make the variable writable. */ TREE_READONLY (tmp_var) = 0; DECL_EXTERNAL (tmp_var) = 0; TREE_STATIC (tmp_var) = 0; TREE_USED (tmp_var) = 1; return tmp_var; } /* Create a new temporary variable declaration of type TYPE. DOES push the variable into the current binding. Further, assume that this is called only from gimplification or optimization, at which point the creation of certain types are bugs. */ tree create_tmp_var (tree type, const char *prefix) { tree tmp_var; /* We don't allow types that are addressable (meaning we can't make copies), or incomplete. We also used to reject every variable size objects here, but now support those for which a constant upper bound can be obtained. The processing for variable sizes is performed in gimple_add_tmp_var, point at which it really matters and possibly reached via paths not going through this function, e.g. after direct calls to create_tmp_var_raw. */ gcc_assert (!TREE_ADDRESSABLE (type) && COMPLETE_TYPE_P (type)); tmp_var = create_tmp_var_raw (type, prefix); gimple_add_tmp_var (tmp_var); return tmp_var; } /* Create a temporary with a name derived from VAL. Subroutine of lookup_tmp_var; nobody else should call this function. */ static inline tree create_tmp_from_val (tree val) { return create_tmp_var (TREE_TYPE (val), get_name (val)); } /* Create a temporary to hold the value of VAL. If IS_FORMAL, try to reuse an existing expression temporary. */ static tree lookup_tmp_var (tree val, bool is_formal) { tree ret; /* If not optimizing, never really reuse a temporary. local-alloc won't allocate any variable that is used in more than one basic block, which means it will go into memory, causing much extra work in reload and final and poorer code generation, outweighing the extra memory allocation here. */ if (!optimize || !is_formal || TREE_SIDE_EFFECTS (val)) ret = create_tmp_from_val (val); else { elt_t elt, *elt_p; void **slot; elt.val = val; if (gimplify_ctxp->temp_htab == NULL) gimplify_ctxp->temp_htab = htab_create (1000, gimple_tree_hash, gimple_tree_eq, free); slot = htab_find_slot (gimplify_ctxp->temp_htab, (void *)&elt, INSERT); if (*slot == NULL) { elt_p = XNEW (elt_t); elt_p->val = val; elt_p->temp = ret = create_tmp_from_val (val); *slot = (void *) elt_p; } else { elt_p = (elt_t *) *slot; ret = elt_p->temp; } } return ret; } /* Return true if T is a CALL_EXPR or an expression that can be assignmed to a temporary. Note that this predicate should only be used during gimplification. See the rationale for this in gimplify_modify_expr. */ static bool is_gimple_reg_rhs_or_call (tree t) { return (get_gimple_rhs_class (TREE_CODE (t)) != GIMPLE_INVALID_RHS || TREE_CODE (t) == CALL_EXPR); } /* Return true if T is a valid memory RHS or a CALL_EXPR. Note that this predicate should only be used during gimplification. See the rationale for this in gimplify_modify_expr. */ static bool is_gimple_mem_rhs_or_call (tree t) { /* If we're dealing with a renamable type, either source or dest must be a renamed variable. */ if (is_gimple_reg_type (TREE_TYPE (t))) return is_gimple_val (t); else return (is_gimple_val (t) || is_gimple_lvalue (t) || TREE_CODE (t) == CALL_EXPR); } /* Helper for get_formal_tmp_var and get_initialized_tmp_var. */ static tree internal_get_tmp_var (tree val, gimple_seq *pre_p, gimple_seq *post_p, bool is_formal) { tree t, mod; /* Notice that we explicitly allow VAL to be a CALL_EXPR so that we can create an INIT_EXPR and convert it into a GIMPLE_CALL below. */ gimplify_expr (&val, pre_p, post_p, is_gimple_reg_rhs_or_call, fb_rvalue); t = lookup_tmp_var (val, is_formal); if (is_formal && (TREE_CODE (TREE_TYPE (t)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE)) DECL_GIMPLE_REG_P (t) = 1; mod = build2 (INIT_EXPR, TREE_TYPE (t), t, unshare_expr (val)); if (EXPR_HAS_LOCATION (val)) SET_EXPR_LOCATION (mod, EXPR_LOCATION (val)); else SET_EXPR_LOCATION (mod, input_location); /* gimplify_modify_expr might want to reduce this further. */ gimplify_and_add (mod, pre_p); ggc_free (mod); /* If we're gimplifying into ssa, gimplify_modify_expr will have given our temporary an SSA name. Find and return it. */ if (gimplify_ctxp->into_ssa) { gimple last = gimple_seq_last_stmt (*pre_p); t = gimple_get_lhs (last); } return t; } /* Returns a formal temporary variable initialized with VAL. PRE_P is as in gimplify_expr. Only use this function if: 1) The value of the unfactored expression represented by VAL will not change between the initialization and use of the temporary, and 2) The temporary will not be otherwise modified. For instance, #1 means that this is inappropriate for SAVE_EXPR temps, and #2 means it is inappropriate for && temps. For other cases, use get_initialized_tmp_var instead. */ tree get_formal_tmp_var (tree val, gimple_seq *pre_p) { return internal_get_tmp_var (val, pre_p, NULL, true); } /* Returns a temporary variable initialized with VAL. PRE_P and POST_P are as in gimplify_expr. */ tree get_initialized_tmp_var (tree val, gimple_seq *pre_p, gimple_seq *post_p) { return internal_get_tmp_var (val, pre_p, post_p, false); } /* Declares all the variables in VARS in SCOPE. If DEBUG_INFO is true, generate debug info for them; otherwise don't. */ void declare_vars (tree vars, gimple scope, bool debug_info) { tree last = vars; if (last) { tree temps, block; gcc_assert (gimple_code (scope) == GIMPLE_BIND); temps = nreverse (last); block = gimple_bind_block (scope); gcc_assert (!block || TREE_CODE (block) == BLOCK); if (!block || !debug_info) { TREE_CHAIN (last) = gimple_bind_vars (scope); gimple_bind_set_vars (scope, temps); } else { /* We need to attach the nodes both to the BIND_EXPR and to its associated BLOCK for debugging purposes. The key point here is that the BLOCK_VARS of the BIND_EXPR_BLOCK of a BIND_EXPR is a subchain of the BIND_EXPR_VARS of the BIND_EXPR. */ if (BLOCK_VARS (block)) BLOCK_VARS (block) = chainon (BLOCK_VARS (block), temps); else { gimple_bind_set_vars (scope, chainon (gimple_bind_vars (scope), temps)); BLOCK_VARS (block) = temps; } } } } /* For VAR a VAR_DECL of variable size, try to find a constant upper bound for the size and adjust DECL_SIZE/DECL_SIZE_UNIT accordingly. Abort if no such upper bound can be obtained. */ static void force_constant_size (tree var) { /* The only attempt we make is by querying the maximum size of objects of the variable's type. */ HOST_WIDE_INT max_size; gcc_assert (TREE_CODE (var) == VAR_DECL); max_size = max_int_size_in_bytes (TREE_TYPE (var)); gcc_assert (max_size >= 0); DECL_SIZE_UNIT (var) = build_int_cst (TREE_TYPE (DECL_SIZE_UNIT (var)), max_size); DECL_SIZE (var) = build_int_cst (TREE_TYPE (DECL_SIZE (var)), max_size * BITS_PER_UNIT); } void gimple_add_tmp_var (tree tmp) { gcc_assert (!TREE_CHAIN (tmp) && !DECL_SEEN_IN_BIND_EXPR_P (tmp)); /* Later processing assumes that the object size is constant, which might not be true at this point. Force the use of a constant upper bound in this case. */ if (!host_integerp (DECL_SIZE_UNIT (tmp), 1)) force_constant_size (tmp); DECL_CONTEXT (tmp) = current_function_decl; DECL_SEEN_IN_BIND_EXPR_P (tmp) = 1; if (gimplify_ctxp) { TREE_CHAIN (tmp) = gimplify_ctxp->temps; gimplify_ctxp->temps = tmp; /* Mark temporaries local within the nearest enclosing parallel. */ if (gimplify_omp_ctxp) { struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp; while (ctx && ctx->region_type == ORT_WORKSHARE) ctx = ctx->outer_context; if (ctx) omp_add_variable (ctx, tmp, GOVD_LOCAL | GOVD_SEEN); } } else if (cfun) record_vars (tmp); else { gimple_seq body_seq; /* This case is for nested functions. We need to expose the locals they create. */ body_seq = gimple_body (current_function_decl); declare_vars (tmp, gimple_seq_first_stmt (body_seq), false); } } /* Determines whether to assign a location to the statement GS. */ static bool should_carry_location_p (gimple gs) { /* Don't emit a line note for a label. We particularly don't want to emit one for the break label, since it doesn't actually correspond to the beginning of the loop/switch. */ if (gimple_code (gs) == GIMPLE_LABEL) return false; return true; } /* Return true if a location should not be emitted for this statement by annotate_one_with_location. */ static inline bool gimple_do_not_emit_location_p (gimple g) { return gimple_plf (g, GF_PLF_1); } /* Mark statement G so a location will not be emitted by annotate_one_with_location. */ static inline void gimple_set_do_not_emit_location (gimple g) { /* The PLF flags are initialized to 0 when a new tuple is created, so no need to initialize it anywhere. */ gimple_set_plf (g, GF_PLF_1, true); } /* Set the location for gimple statement GS to LOCATION. */ static void annotate_one_with_location (gimple gs, location_t location) { if (!gimple_has_location (gs) && !gimple_do_not_emit_location_p (gs) && should_carry_location_p (gs)) gimple_set_location (gs, location); } /* Set LOCATION for all the statements after iterator GSI in sequence SEQ. If GSI is pointing to the end of the sequence, start with the first statement in SEQ. */ static void annotate_all_with_location_after (gimple_seq seq, gimple_stmt_iterator gsi, location_t location) { if (gsi_end_p (gsi)) gsi = gsi_start (seq); else gsi_next (&gsi); for (; !gsi_end_p (gsi); gsi_next (&gsi)) annotate_one_with_location (gsi_stmt (gsi), location); } /* Set the location for all the statements in a sequence STMT_P to LOCATION. */ void annotate_all_with_location (gimple_seq stmt_p, location_t location) { gimple_stmt_iterator i; if (gimple_seq_empty_p (stmt_p)) return; for (i = gsi_start (stmt_p); !gsi_end_p (i); gsi_next (&i)) { gimple gs = gsi_stmt (i); annotate_one_with_location (gs, location); } } /* Similar to copy_tree_r() but do not copy SAVE_EXPR or TARGET_EXPR nodes. These nodes model computations that should only be done once. If we were to unshare something like SAVE_EXPR(i++), the gimplification process would create wrong code. */ static tree mostly_copy_tree_r (tree *tp, int *walk_subtrees, void *data) { enum tree_code code = TREE_CODE (*tp); /* Don't unshare types, decls, constants and SAVE_EXPR nodes. */ if (TREE_CODE_CLASS (code) == tcc_type || TREE_CODE_CLASS (code) == tcc_declaration || TREE_CODE_CLASS (code) == tcc_constant || code == SAVE_EXPR || code == TARGET_EXPR /* We can't do anything sensible with a BLOCK used as an expression, but we also can't just die when we see it because of non-expression uses. So just avert our eyes and cross our fingers. Silly Java. */ || code == BLOCK) *walk_subtrees = 0; else { gcc_assert (code != BIND_EXPR); copy_tree_r (tp, walk_subtrees, data); } return NULL_TREE; } /* Callback for walk_tree to unshare most of the shared trees rooted at *TP. If *TP has been visited already (i.e., TREE_VISITED (*TP) == 1), then *TP is deep copied by calling copy_tree_r. This unshares the same trees as copy_tree_r with the exception of SAVE_EXPR nodes. These nodes model computations that should only be done once. If we were to unshare something like SAVE_EXPR(i++), the gimplification process would create wrong code. */ static tree copy_if_shared_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED, void *data ATTRIBUTE_UNUSED) { tree t = *tp; enum tree_code code = TREE_CODE (t); /* Skip types, decls, and constants. But we do want to look at their types and the bounds of types. Mark them as visited so we properly unmark their subtrees on the unmark pass. If we've already seen them, don't look down further. */ if (TREE_CODE_CLASS (code) == tcc_type || TREE_CODE_CLASS (code) == tcc_declaration || TREE_CODE_CLASS (code) == tcc_constant) { if (TREE_VISITED (t)) *walk_subtrees = 0; else TREE_VISITED (t) = 1; } /* If this node has been visited already, unshare it and don't look any deeper. */ else if (TREE_VISITED (t)) { walk_tree (tp, mostly_copy_tree_r, NULL, NULL); *walk_subtrees = 0; } /* Otherwise, mark the tree as visited and keep looking. */ else TREE_VISITED (t) = 1; return NULL_TREE; } static tree unmark_visited_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED, void *data ATTRIBUTE_UNUSED) { if (TREE_VISITED (*tp)) TREE_VISITED (*tp) = 0; else *walk_subtrees = 0; return NULL_TREE; } /* Unshare all the trees in BODY_P, a pointer into the body of FNDECL, and the bodies of any nested functions if we are unsharing the entire body of FNDECL. */ static void unshare_body (tree *body_p, tree fndecl) { struct cgraph_node *cgn = cgraph_node (fndecl); walk_tree (body_p, copy_if_shared_r, NULL, NULL); if (body_p == &DECL_SAVED_TREE (fndecl)) for (cgn = cgn->nested; cgn; cgn = cgn->next_nested) unshare_body (&DECL_SAVED_TREE (cgn->decl), cgn->decl); } /* Likewise, but mark all trees as not visited. */ static void unvisit_body (tree *body_p, tree fndecl) { struct cgraph_node *cgn = cgraph_node (fndecl); walk_tree (body_p, unmark_visited_r, NULL, NULL); if (body_p == &DECL_SAVED_TREE (fndecl)) for (cgn = cgn->nested; cgn; cgn = cgn->next_nested) unvisit_body (&DECL_SAVED_TREE (cgn->decl), cgn->decl); } /* Unconditionally make an unshared copy of EXPR. This is used when using stored expressions which span multiple functions, such as BINFO_VTABLE, as the normal unsharing process can't tell that they're shared. */ tree unshare_expr (tree expr) { walk_tree (&expr, mostly_copy_tree_r, NULL, NULL); return expr; } /* WRAPPER is a code such as BIND_EXPR or CLEANUP_POINT_EXPR which can both contain statements and have a value. Assign its value to a temporary and give it void_type_node. Returns the temporary, or NULL_TREE if WRAPPER was already void. */ tree voidify_wrapper_expr (tree wrapper, tree temp) { tree type = TREE_TYPE (wrapper); if (type && !VOID_TYPE_P (type)) { tree *p; /* Set p to point to the body of the wrapper. Loop until we find something that isn't a wrapper. */ for (p = &wrapper; p && *p; ) { switch (TREE_CODE (*p)) { case BIND_EXPR: TREE_SIDE_EFFECTS (*p) = 1; TREE_TYPE (*p) = void_type_node; /* For a BIND_EXPR, the body is operand 1. */ p = &BIND_EXPR_BODY (*p); break; case CLEANUP_POINT_EXPR: case TRY_FINALLY_EXPR: case TRY_CATCH_EXPR: TREE_SIDE_EFFECTS (*p) = 1; TREE_TYPE (*p) = void_type_node; p = &TREE_OPERAND (*p, 0); break; case STATEMENT_LIST: { tree_stmt_iterator i = tsi_last (*p); TREE_SIDE_EFFECTS (*p) = 1; TREE_TYPE (*p) = void_type_node; p = tsi_end_p (i) ? NULL : tsi_stmt_ptr (i); } break; case COMPOUND_EXPR: /* Advance to the last statement. Set all container types to void. */ for (; TREE_CODE (*p) == COMPOUND_EXPR; p = &TREE_OPERAND (*p, 1)) { TREE_SIDE_EFFECTS (*p) = 1; TREE_TYPE (*p) = void_type_node; } break; default: goto out; } } out: if (p == NULL || IS_EMPTY_STMT (*p)) temp = NULL_TREE; else if (temp) { /* The wrapper is on the RHS of an assignment that we're pushing down. */ gcc_assert (TREE_CODE (temp) == INIT_EXPR || TREE_CODE (temp) == MODIFY_EXPR); TREE_OPERAND (temp, 1) = *p; *p = temp; } else { temp = create_tmp_var (type, "retval"); *p = build2 (INIT_EXPR, type, temp, *p); } return temp; } return NULL_TREE; } /* Prepare calls to builtins to SAVE and RESTORE the stack as well as a temporary through which they communicate. */ static void build_stack_save_restore (gimple *save, gimple *restore) { tree tmp_var; *save = gimple_build_call (implicit_built_in_decls[BUILT_IN_STACK_SAVE], 0); tmp_var = create_tmp_var (ptr_type_node, "saved_stack"); gimple_call_set_lhs (*save, tmp_var); *restore = gimple_build_call (implicit_built_in_decls[BUILT_IN_STACK_RESTORE], 1, tmp_var); } /* Gimplify a BIND_EXPR. Just voidify and recurse. */ static enum gimplify_status gimplify_bind_expr (tree *expr_p, gimple_seq *pre_p) { tree bind_expr = *expr_p; bool old_save_stack = gimplify_ctxp->save_stack; tree t; gimple gimple_bind; gimple_seq body; tree temp = voidify_wrapper_expr (bind_expr, NULL); /* Mark variables seen in this bind expr. */ for (t = BIND_EXPR_VARS (bind_expr); t ; t = TREE_CHAIN (t)) { if (TREE_CODE (t) == VAR_DECL) { struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp; /* Mark variable as local. */ if (ctx && !is_global_var (t) && (! DECL_SEEN_IN_BIND_EXPR_P (t) || splay_tree_lookup (ctx->variables, (splay_tree_key) t) == NULL)) omp_add_variable (gimplify_omp_ctxp, t, GOVD_LOCAL | GOVD_SEEN); DECL_SEEN_IN_BIND_EXPR_P (t) = 1; if (DECL_HARD_REGISTER (t) && !is_global_var (t) && cfun) cfun->has_local_explicit_reg_vars = true; } /* Preliminarily mark non-addressed complex variables as eligible for promotion to gimple registers. We'll transform their uses as we find them. We exclude complex types if not optimizing because they can be subject to partial stores in GNU C by means of the __real__ and __imag__ operators and we cannot promote them to total stores (see gimplify_modify_expr_complex_part). */ if (optimize && (TREE_CODE (TREE_TYPE (t)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE) && !TREE_THIS_VOLATILE (t) && (TREE_CODE (t) == VAR_DECL && !DECL_HARD_REGISTER (t)) && !needs_to_live_in_memory (t)) DECL_GIMPLE_REG_P (t) = 1; } gimple_bind = gimple_build_bind (BIND_EXPR_VARS (bind_expr), NULL, BIND_EXPR_BLOCK (bind_expr)); gimple_push_bind_expr (gimple_bind); gimplify_ctxp->save_stack = false; /* Gimplify the body into the GIMPLE_BIND tuple's body. */ body = NULL; gimplify_stmt (&BIND_EXPR_BODY (bind_expr), &body); gimple_bind_set_body (gimple_bind, body); if (gimplify_ctxp->save_stack) { gimple stack_save, stack_restore, gs; gimple_seq cleanup, new_body; /* Save stack on entry and restore it on exit. Add a try_finally block to achieve this. Note that mudflap depends on the format of the emitted code: see mx_register_decls(). */ build_stack_save_restore (&stack_save, &stack_restore); cleanup = new_body = NULL; gimplify_seq_add_stmt (&cleanup, stack_restore); gs = gimple_build_try (gimple_bind_body (gimple_bind), cleanup, GIMPLE_TRY_FINALLY); gimplify_seq_add_stmt (&new_body, stack_save); gimplify_seq_add_stmt (&new_body, gs); gimple_bind_set_body (gimple_bind, new_body); } gimplify_ctxp->save_stack = old_save_stack; gimple_pop_bind_expr (); gimplify_seq_add_stmt (pre_p, gimple_bind); if (temp) { *expr_p = temp; return GS_OK; } *expr_p = NULL_TREE; return GS_ALL_DONE; } /* Gimplify a RETURN_EXPR. If the expression to be returned is not a GIMPLE value, it is assigned to a new temporary and the statement is re-written to return the temporary. PRE_P points to the sequence where side effects that must happen before STMT should be stored. */ static enum gimplify_status gimplify_return_expr (tree stmt, gimple_seq *pre_p) { gimple ret; tree ret_expr = TREE_OPERAND (stmt, 0); tree result_decl, result; if (ret_expr == error_mark_node) return GS_ERROR; if (!ret_expr || TREE_CODE (ret_expr) == RESULT_DECL || ret_expr == error_mark_node) { gimple ret = gimple_build_return (ret_expr); gimple_set_no_warning (ret, TREE_NO_WARNING (stmt)); gimplify_seq_add_stmt (pre_p, ret); return GS_ALL_DONE; } if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))) result_decl = NULL_TREE; else { result_decl = TREE_OPERAND (ret_expr, 0); /* See through a return by reference. */ if (TREE_CODE (result_decl) == INDIRECT_REF) result_decl = TREE_OPERAND (result_decl, 0); gcc_assert ((TREE_CODE (ret_expr) == MODIFY_EXPR || TREE_CODE (ret_expr) == INIT_EXPR) && TREE_CODE (result_decl) == RESULT_DECL); } /* If aggregate_value_p is true, then we can return the bare RESULT_DECL. Recall that aggregate_value_p is FALSE for any aggregate type that is returned in registers. If we're returning values in registers, then we don't want to extend the lifetime of the RESULT_DECL, particularly across another call. In addition, for those aggregates for which hard_function_value generates a PARALLEL, we'll die during normal expansion of structure assignments; there's special code in expand_return to handle this case that does not exist in expand_expr. */ if (!result_decl || aggregate_value_p (result_decl, TREE_TYPE (current_function_decl))) result = result_decl; else if (gimplify_ctxp->return_temp) result = gimplify_ctxp->return_temp; else { result = create_tmp_var (TREE_TYPE (result_decl), NULL); if (TREE_CODE (TREE_TYPE (result)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (result)) == VECTOR_TYPE) DECL_GIMPLE_REG_P (result) = 1; /* ??? With complex control flow (usually involving abnormal edges), we can wind up warning about an uninitialized value for this. Due to how this variable is constructed and initialized, this is never true. Give up and never warn. */ TREE_NO_WARNING (result) = 1; gimplify_ctxp->return_temp = result; } /* Smash the lhs of the MODIFY_EXPR to the temporary we plan to use. Then gimplify the whole thing. */ if (result != result_decl) TREE_OPERAND (ret_expr, 0) = result; gimplify_and_add (TREE_OPERAND (stmt, 0), pre_p); ret = gimple_build_return (result); gimple_set_no_warning (ret, TREE_NO_WARNING (stmt)); gimplify_seq_add_stmt (pre_p, ret); return GS_ALL_DONE; } static void gimplify_vla_decl (tree decl, gimple_seq *seq_p) { /* This is a variable-sized decl. Simplify its size and mark it for deferred expansion. Note that mudflap depends on the format of the emitted code: see mx_register_decls(). */ tree t, addr, ptr_type; gimplify_one_sizepos (&DECL_SIZE (decl), seq_p); gimplify_one_sizepos (&DECL_SIZE_UNIT (decl), seq_p); /* All occurrences of this decl in final gimplified code will be replaced by indirection. Setting DECL_VALUE_EXPR does two things: First, it lets the rest of the gimplifier know what replacement to use. Second, it lets the debug info know where to find the value. */ ptr_type = build_pointer_type (TREE_TYPE (decl)); addr = create_tmp_var (ptr_type, get_name (decl)); DECL_IGNORED_P (addr) = 0; t = build_fold_indirect_ref (addr); SET_DECL_VALUE_EXPR (decl, t); DECL_HAS_VALUE_EXPR_P (decl) = 1; t = built_in_decls[BUILT_IN_ALLOCA]; t = build_call_expr (t, 1, DECL_SIZE_UNIT (decl)); t = fold_convert (ptr_type, t); t = build2 (MODIFY_EXPR, TREE_TYPE (addr), addr, t); gimplify_and_add (t, seq_p); /* Indicate that we need to restore the stack level when the enclosing BIND_EXPR is exited. */ gimplify_ctxp->save_stack = true; } /* Gimplifies a DECL_EXPR node *STMT_P by making any necessary allocation and initialization explicit. */ static enum gimplify_status gimplify_decl_expr (tree *stmt_p, gimple_seq *seq_p) { tree stmt = *stmt_p; tree decl = DECL_EXPR_DECL (stmt); *stmt_p = NULL_TREE; if (TREE_TYPE (decl) == error_mark_node) return GS_ERROR; if ((TREE_CODE (decl) == TYPE_DECL || TREE_CODE (decl) == VAR_DECL) && !TYPE_SIZES_GIMPLIFIED (TREE_TYPE (decl))) gimplify_type_sizes (TREE_TYPE (decl), seq_p); if (TREE_CODE (decl) == VAR_DECL && !DECL_EXTERNAL (decl)) { tree init = DECL_INITIAL (decl); if (TREE_CODE (DECL_SIZE_UNIT (decl)) != INTEGER_CST || (!TREE_STATIC (decl) && flag_stack_check == GENERIC_STACK_CHECK && compare_tree_int (DECL_SIZE_UNIT (decl), STACK_CHECK_MAX_VAR_SIZE) > 0)) gimplify_vla_decl (decl, seq_p); if (init && init != error_mark_node) { if (!TREE_STATIC (decl)) { DECL_INITIAL (decl) = NULL_TREE; init = build2 (INIT_EXPR, void_type_node, decl, init); gimplify_and_add (init, seq_p); ggc_free (init); } else /* We must still examine initializers for static variables as they may contain a label address. */ walk_tree (&init, force_labels_r, NULL, NULL); } /* Some front ends do not explicitly declare all anonymous artificial variables. We compensate here by declaring the variables, though it would be better if the front ends would explicitly declare them. */ if (!DECL_SEEN_IN_BIND_EXPR_P (decl) && DECL_ARTIFICIAL (decl) && DECL_NAME (decl) == NULL_TREE) gimple_add_tmp_var (decl); } return GS_ALL_DONE; } /* Gimplify a LOOP_EXPR. Normally this just involves gimplifying the body and replacing the LOOP_EXPR with goto, but if the loop contains an EXIT_EXPR, we need to append a label for it to jump to. */ static enum gimplify_status gimplify_loop_expr (tree *expr_p, gimple_seq *pre_p) { tree saved_label = gimplify_ctxp->exit_label; tree start_label = create_artificial_label (UNKNOWN_LOCATION); gimplify_seq_add_stmt (pre_p, gimple_build_label (start_label)); gimplify_ctxp->exit_label = NULL_TREE; gimplify_and_add (LOOP_EXPR_BODY (*expr_p), pre_p); gimplify_seq_add_stmt (pre_p, gimple_build_goto (start_label)); if (gimplify_ctxp->exit_label) gimplify_seq_add_stmt (pre_p, gimple_build_label (gimplify_ctxp->exit_label)); gimplify_ctxp->exit_label = saved_label; *expr_p = NULL; return GS_ALL_DONE; } /* Gimplifies a statement list onto a sequence. These may be created either by an enlightened front-end, or by shortcut_cond_expr. */ static enum gimplify_status gimplify_statement_list (tree *expr_p, gimple_seq *pre_p) { tree temp = voidify_wrapper_expr (*expr_p, NULL); tree_stmt_iterator i = tsi_start (*expr_p); while (!tsi_end_p (i)) { gimplify_stmt (tsi_stmt_ptr (i), pre_p); tsi_delink (&i); } if (temp) { *expr_p = temp; return GS_OK; } return GS_ALL_DONE; } /* Compare two case labels. Because the front end should already have made sure that case ranges do not overlap, it is enough to only compare the CASE_LOW values of each case label. */ static int compare_case_labels (const void *p1, const void *p2) { const_tree const case1 = *(const_tree const*)p1; const_tree const case2 = *(const_tree const*)p2; /* The 'default' case label always goes first. */ if (!CASE_LOW (case1)) return -1; else if (!CASE_LOW (case2)) return 1; else return tree_int_cst_compare (CASE_LOW (case1), CASE_LOW (case2)); } /* Sort the case labels in LABEL_VEC in place in ascending order. */ void sort_case_labels (VEC(tree,heap)* label_vec) { size_t len = VEC_length (tree, label_vec); qsort (VEC_address (tree, label_vec), len, sizeof (tree), compare_case_labels); } /* Gimplify a SWITCH_EXPR, and collect a TREE_VEC of the labels it can branch to. */ static enum gimplify_status gimplify_switch_expr (tree *expr_p, gimple_seq *pre_p) { tree switch_expr = *expr_p; gimple_seq switch_body_seq = NULL; enum gimplify_status ret; ret = gimplify_expr (&SWITCH_COND (switch_expr), pre_p, NULL, is_gimple_val, fb_rvalue); if (ret == GS_ERROR || ret == GS_UNHANDLED) return ret; if (SWITCH_BODY (switch_expr)) { VEC (tree,heap) *labels; VEC (tree,heap) *saved_labels; tree default_case = NULL_TREE; size_t i, len; gimple gimple_switch; /* If someone can be bothered to fill in the labels, they can be bothered to null out the body too. */ gcc_assert (!SWITCH_LABELS (switch_expr)); /* save old labels, get new ones from body, then restore the old labels. Save all the things from the switch body to append after. */ saved_labels = gimplify_ctxp->case_labels; gimplify_ctxp->case_labels = VEC_alloc (tree, heap, 8); gimplify_stmt (&SWITCH_BODY (switch_expr), &switch_body_seq); labels = gimplify_ctxp->case_labels; gimplify_ctxp->case_labels = saved_labels; i = 0; while (i < VEC_length (tree, labels)) { tree elt = VEC_index (tree, labels, i); tree low = CASE_LOW (elt); bool remove_element = FALSE; if (low) { /* Discard empty ranges. */ tree high = CASE_HIGH (elt); if (high && tree_int_cst_lt (high, low)) remove_element = TRUE; } else { /* The default case must be the last label in the list. */ gcc_assert (!default_case); default_case = elt; remove_element = TRUE; } if (remove_element) VEC_ordered_remove (tree, labels, i); else i++; } len = i; if (!VEC_empty (tree, labels)) sort_case_labels (labels); if (!default_case) { tree type = TREE_TYPE (switch_expr); /* If the switch has no default label, add one, so that we jump around the switch body. If the labels already cover the whole range of type, add the default label pointing to one of the existing labels. */ if (type == void_type_node) type = TREE_TYPE (SWITCH_COND (switch_expr)); if (len && INTEGRAL_TYPE_P (type) && TYPE_MIN_VALUE (type) && TYPE_MAX_VALUE (type) && tree_int_cst_equal (CASE_LOW (VEC_index (tree, labels, 0)), TYPE_MIN_VALUE (type))) { tree low, high = CASE_HIGH (VEC_index (tree, labels, len - 1)); if (!high) high = CASE_LOW (VEC_index (tree, labels, len - 1)); if (tree_int_cst_equal (high, TYPE_MAX_VALUE (type))) { for (i = 1; i < len; i++) { high = CASE_LOW (VEC_index (tree, labels, i)); low = CASE_HIGH (VEC_index (tree, labels, i - 1)); if (!low) low = CASE_LOW (VEC_index (tree, labels, i - 1)); if ((TREE_INT_CST_LOW (low) + 1 != TREE_INT_CST_LOW (high)) || (TREE_INT_CST_HIGH (low) + (TREE_INT_CST_LOW (high) == 0) != TREE_INT_CST_HIGH (high))) break; } if (i == len) default_case = build3 (CASE_LABEL_EXPR, void_type_node, NULL_TREE, NULL_TREE, CASE_LABEL (VEC_index (tree, labels, 0))); } } if (!default_case) { gimple new_default; default_case = build3 (CASE_LABEL_EXPR, void_type_node, NULL_TREE, NULL_TREE, create_artificial_label (UNKNOWN_LOCATION)); new_default = gimple_build_label (CASE_LABEL (default_case)); gimplify_seq_add_stmt (&switch_body_seq, new_default); } } gimple_switch = gimple_build_switch_vec (SWITCH_COND (switch_expr), default_case, labels); gimplify_seq_add_stmt (pre_p, gimple_switch); gimplify_seq_add_seq (pre_p, switch_body_seq); VEC_free(tree, heap, labels); } else gcc_assert (SWITCH_LABELS (switch_expr)); return GS_ALL_DONE; } static enum gimplify_status gimplify_case_label_expr (tree *expr_p, gimple_seq *pre_p) { struct gimplify_ctx *ctxp; gimple gimple_label; /* Invalid OpenMP programs can play Duff's Device type games with #pragma omp parallel. At least in the C front end, we don't detect such invalid branches until after gimplification. */ for (ctxp = gimplify_ctxp; ; ctxp = ctxp->prev_context) if (ctxp->case_labels) break; gimple_label = gimple_build_label (CASE_LABEL (*expr_p)); VEC_safe_push (tree, heap, ctxp->case_labels, *expr_p); gimplify_seq_add_stmt (pre_p, gimple_label); return GS_ALL_DONE; } /* Build a GOTO to the LABEL_DECL pointed to by LABEL_P, building it first if necessary. */ tree build_and_jump (tree *label_p) { if (label_p == NULL) /* If there's nowhere to jump, just fall through. */ return NULL_TREE; if (*label_p == NULL_TREE) { tree label = create_artificial_label (UNKNOWN_LOCATION); *label_p = label; } return build1 (GOTO_EXPR, void_type_node, *label_p); } /* Gimplify an EXIT_EXPR by converting to a GOTO_EXPR inside a COND_EXPR. This also involves building a label to jump to and communicating it to gimplify_loop_expr through gimplify_ctxp->exit_label. */ static enum gimplify_status gimplify_exit_expr (tree *expr_p) { tree cond = TREE_OPERAND (*expr_p, 0); tree expr; expr = build_and_jump (&gimplify_ctxp->exit_label); expr = build3 (COND_EXPR, void_type_node, cond, expr, NULL_TREE); *expr_p = expr; return GS_OK; } /* A helper function to be called via walk_tree. Mark all labels under *TP as being forced. To be called for DECL_INITIAL of static variables. */ tree force_labels_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED) { if (TYPE_P (*tp)) *walk_subtrees = 0; if (TREE_CODE (*tp) == LABEL_DECL) FORCED_LABEL (*tp) = 1; return NULL_TREE; } /* *EXPR_P is a COMPONENT_REF being used as an rvalue. If its type is different from its canonical type, wrap the whole thing inside a NOP_EXPR and force the type of the COMPONENT_REF to be the canonical type. The canonical type of a COMPONENT_REF is the type of the field being referenced--unless the field is a bit-field which can be read directly in a smaller mode, in which case the canonical type is the sign-appropriate type corresponding to that mode. */ static void canonicalize_component_ref (tree *expr_p) { tree expr = *expr_p; tree type; gcc_assert (TREE_CODE (expr) == COMPONENT_REF); if (INTEGRAL_TYPE_P (TREE_TYPE (expr))) type = TREE_TYPE (get_unwidened (expr, NULL_TREE)); else type = TREE_TYPE (TREE_OPERAND (expr, 1)); /* One could argue that all the stuff below is not necessary for the non-bitfield case and declare it a FE error if type adjustment would be needed. */ if (TREE_TYPE (expr) != type) { #ifdef ENABLE_TYPES_CHECKING tree old_type = TREE_TYPE (expr); #endif int type_quals; /* We need to preserve qualifiers and propagate them from operand 0. */ type_quals = TYPE_QUALS (type) | TYPE_QUALS (TREE_TYPE (TREE_OPERAND (expr, 0))); if (TYPE_QUALS (type) != type_quals) type = build_qualified_type (TYPE_MAIN_VARIANT (type), type_quals); /* Set the type of the COMPONENT_REF to the underlying type. */ TREE_TYPE (expr) = type; #ifdef ENABLE_TYPES_CHECKING /* It is now a FE error, if the conversion from the canonical type to the original expression type is not useless. */ gcc_assert (useless_type_conversion_p (old_type, type)); #endif } } /* If a NOP conversion is changing a pointer to array of foo to a pointer to foo, embed that change in the ADDR_EXPR by converting T array[U]; (T *)&array ==> &array[L] where L is the lower bound. For simplicity, only do this for constant lower bound. The constraint is that the type of &array[L] is trivially convertible to T *. */ static void canonicalize_addr_expr (tree *expr_p) { tree expr = *expr_p; tree addr_expr = TREE_OPERAND (expr, 0); tree datype, ddatype, pddatype; /* We simplify only conversions from an ADDR_EXPR to a pointer type. */ if (!POINTER_TYPE_P (TREE_TYPE (expr)) || TREE_CODE (addr_expr) != ADDR_EXPR) return; /* The addr_expr type should be a pointer to an array. */ datype = TREE_TYPE (TREE_TYPE (addr_expr)); if (TREE_CODE (datype) != ARRAY_TYPE) return; /* The pointer to element type shall be trivially convertible to the expression pointer type. */ ddatype = TREE_TYPE (datype); pddatype = build_pointer_type (ddatype); if (!useless_type_conversion_p (TYPE_MAIN_VARIANT (TREE_TYPE (expr)), pddatype)) return; /* The lower bound and element sizes must be constant. */ if (!TYPE_SIZE_UNIT (ddatype) || TREE_CODE (TYPE_SIZE_UNIT (ddatype)) != INTEGER_CST || !TYPE_DOMAIN (datype) || !TYPE_MIN_VALUE (TYPE_DOMAIN (datype)) || TREE_CODE (TYPE_MIN_VALUE (TYPE_DOMAIN (datype))) != INTEGER_CST) return; /* All checks succeeded. Build a new node to merge the cast. */ *expr_p = build4 (ARRAY_REF, ddatype, TREE_OPERAND (addr_expr, 0), TYPE_MIN_VALUE (TYPE_DOMAIN (datype)), NULL_TREE, NULL_TREE); *expr_p = build1 (ADDR_EXPR, pddatype, *expr_p); /* We can have stripped a required restrict qualifier above. */ if (!useless_type_conversion_p (TREE_TYPE (expr), TREE_TYPE (*expr_p))) *expr_p = fold_convert (TREE_TYPE (expr), *expr_p); } /* *EXPR_P is a NOP_EXPR or CONVERT_EXPR. Remove it and/or other conversions underneath as appropriate. */ static enum gimplify_status gimplify_conversion (tree *expr_p) { tree tem; location_t loc = EXPR_LOCATION (*expr_p); gcc_assert (CONVERT_EXPR_P (*expr_p)); /* Then strip away all but the outermost conversion. */ STRIP_SIGN_NOPS (TREE_OPERAND (*expr_p, 0)); /* And remove the outermost conversion if it's useless. */ if (tree_ssa_useless_type_conversion (*expr_p)) *expr_p = TREE_OPERAND (*expr_p, 0); /* Attempt to avoid NOP_EXPR by producing reference to a subtype. For example this fold (subclass *)&A into &A->subclass avoiding a need for statement. */ if (CONVERT_EXPR_P (*expr_p) && POINTER_TYPE_P (TREE_TYPE (*expr_p)) && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (*expr_p, 0))) && (tem = maybe_fold_offset_to_address (EXPR_LOCATION (*expr_p), TREE_OPERAND (*expr_p, 0), integer_zero_node, TREE_TYPE (*expr_p))) != NULL_TREE) *expr_p = tem; /* If we still have a conversion at the toplevel, then canonicalize some constructs. */ if (CONVERT_EXPR_P (*expr_p)) { tree sub = TREE_OPERAND (*expr_p, 0); /* If a NOP conversion is changing the type of a COMPONENT_REF expression, then canonicalize its type now in order to expose more redundant conversions. */ if (TREE_CODE (sub) == COMPONENT_REF) canonicalize_component_ref (&TREE_OPERAND (*expr_p, 0)); /* If a NOP conversion is changing a pointer to array of foo to a pointer to foo, embed that change in the ADDR_EXPR. */ else if (TREE_CODE (sub) == ADDR_EXPR) canonicalize_addr_expr (expr_p); } /* If we have a conversion to a non-register type force the use of a VIEW_CONVERT_EXPR instead. */ if (CONVERT_EXPR_P (*expr_p) && !is_gimple_reg_type (TREE_TYPE (*expr_p))) *expr_p = fold_build1_loc (loc, VIEW_CONVERT_EXPR, TREE_TYPE (*expr_p), TREE_OPERAND (*expr_p, 0)); return GS_OK; } /* Nonlocal VLAs seen in the current function. */ static struct pointer_set_t *nonlocal_vlas; /* Gimplify a VAR_DECL or PARM_DECL. Returns GS_OK if we expanded a DECL_VALUE_EXPR, and it's worth re-examining things. */ static enum gimplify_status gimplify_var_or_parm_decl (tree *expr_p) { tree decl = *expr_p; /* ??? If this is a local variable, and it has not been seen in any outer BIND_EXPR, then it's probably the result of a duplicate declaration, for which we've already issued an error. It would be really nice if the front end wouldn't leak these at all. Currently the only known culprit is C++ destructors, as seen in g++.old-deja/g++.jason/binding.C. */ if (TREE_CODE (decl) == VAR_DECL && !DECL_SEEN_IN_BIND_EXPR_P (decl) && !TREE_STATIC (decl) && !DECL_EXTERNAL (decl) && decl_function_context (decl) == current_function_decl) { gcc_assert (errorcount || sorrycount); return GS_ERROR; } /* When within an OpenMP context, notice uses of variables. */ if (gimplify_omp_ctxp && omp_notice_variable (gimplify_omp_ctxp, decl, true)) return GS_ALL_DONE; /* If the decl is an alias for another expression, substitute it now. */ if (DECL_HAS_VALUE_EXPR_P (decl)) { tree value_expr = DECL_VALUE_EXPR (decl); /* For referenced nonlocal VLAs add a decl for debugging purposes to the current function. */ if (TREE_CODE (decl) == VAR_DECL && TREE_CODE (DECL_SIZE_UNIT (decl)) != INTEGER_CST && nonlocal_vlas != NULL && TREE_CODE (value_expr) == INDIRECT_REF && TREE_CODE (TREE_OPERAND (value_expr, 0)) == VAR_DECL && decl_function_context (decl) != current_function_decl) { struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp; while (ctx && ctx->region_type == ORT_WORKSHARE) ctx = ctx->outer_context; if (!ctx && !pointer_set_insert (nonlocal_vlas, decl)) { tree copy = copy_node (decl), block; lang_hooks.dup_lang_specific_decl (copy); SET_DECL_RTL (copy, NULL_RTX); TREE_USED (copy) = 1; block = DECL_INITIAL (current_function_decl); TREE_CHAIN (copy) = BLOCK_VARS (block); BLOCK_VARS (block) = copy; SET_DECL_VALUE_EXPR (copy, unshare_expr (value_expr)); DECL_HAS_VALUE_EXPR_P (copy) = 1; } } *expr_p = unshare_expr (value_expr); return GS_OK; } return GS_ALL_DONE; } /* Gimplify the COMPONENT_REF, ARRAY_REF, REALPART_EXPR or IMAGPART_EXPR node *EXPR_P. compound_lval : min_lval '[' val ']' | min_lval '.' ID | compound_lval '[' val ']' | compound_lval '.' ID This is not part of the original SIMPLE definition, which separates array and member references, but it seems reasonable to handle them together. Also, this way we don't run into problems with union aliasing; gcc requires that for accesses through a union to alias, the union reference must be explicit, which was not always the case when we were splitting up array and member refs. PRE_P points to the sequence where side effects that must happen before *EXPR_P should be stored. POST_P points to the sequence where side effects that must happen after *EXPR_P should be stored. */ static enum gimplify_status gimplify_compound_lval (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p, fallback_t fallback) { tree *p; VEC(tree,heap) *stack; enum gimplify_status ret = GS_OK, tret; int i; location_t loc = EXPR_LOCATION (*expr_p); /* Create a stack of the subexpressions so later we can walk them in order from inner to outer. */ stack = VEC_alloc (tree, heap, 10); /* We can handle anything that get_inner_reference can deal with. */ for (p = expr_p; ; p = &TREE_OPERAND (*p, 0)) { restart: /* Fold INDIRECT_REFs now to turn them into ARRAY_REFs. */ if (TREE_CODE (*p) == INDIRECT_REF) *p = fold_indirect_ref_loc (loc, *p); if (handled_component_p (*p)) ; /* Expand DECL_VALUE_EXPR now. In some cases that may expose additional COMPONENT_REFs. */ else if ((TREE_CODE (*p) == VAR_DECL || TREE_CODE (*p) == PARM_DECL) && gimplify_var_or_parm_decl (p) == GS_OK) goto restart; else break; VEC_safe_push (tree, heap, stack, *p); } gcc_assert (VEC_length (tree, stack)); /* Now STACK is a stack of pointers to all the refs we've walked through and P points to the innermost expression. Java requires that we elaborated nodes in source order. That means we must gimplify the inner expression followed by each of the indices, in order. But we can't gimplify the inner expression until we deal with any variable bounds, sizes, or positions in order to deal with PLACEHOLDER_EXPRs. So we do this in three steps. First we deal with the annotations for any variables in the components, then we gimplify the base, then we gimplify any indices, from left to right. */ for (i = VEC_length (tree, stack) - 1; i >= 0; i--) { tree t = VEC_index (tree, stack, i); if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF) { /* Gimplify the low bound and element type size and put them into the ARRAY_REF. If these values are set, they have already been gimplified. */ if (TREE_OPERAND (t, 2) == NULL_TREE) { tree low = unshare_expr (array_ref_low_bound (t)); if (!is_gimple_min_invariant (low)) { TREE_OPERAND (t, 2) = low; tret = gimplify_expr (&TREE_OPERAND (t, 2), pre_p, post_p, is_gimple_reg, fb_rvalue); ret = MIN (ret, tret); } } if (!TREE_OPERAND (t, 3)) { tree elmt_type = TREE_TYPE (TREE_TYPE (TREE_OPERAND (t, 0))); tree elmt_size = unshare_expr (array_ref_element_size (t)); tree factor = size_int (TYPE_ALIGN_UNIT (elmt_type)); /* Divide the element size by the alignment of the element type (above). */ elmt_size = size_binop_loc (loc, EXACT_DIV_EXPR, elmt_size, factor); if (!is_gimple_min_invariant (elmt_size)) { TREE_OPERAND (t, 3) = elmt_size; tret = gimplify_expr (&TREE_OPERAND (t, 3), pre_p, post_p, is_gimple_reg, fb_rvalue); ret = MIN (ret, tret); } } } else if (TREE_CODE (t) == COMPONENT_REF) { /* Set the field offset into T and gimplify it. */ if (!TREE_OPERAND (t, 2)) { tree offset = unshare_expr (component_ref_field_offset (t)); tree field = TREE_OPERAND (t, 1); tree factor = size_int (DECL_OFFSET_ALIGN (field) / BITS_PER_UNIT); /* Divide the offset by its alignment. */ offset = size_binop_loc (loc, EXACT_DIV_EXPR, offset, factor); if (!is_gimple_min_invariant (offset)) { TREE_OPERAND (t, 2) = offset; tret = gimplify_expr (&TREE_OPERAND (t, 2), pre_p, post_p, is_gimple_reg, fb_rvalue); ret = MIN (ret, tret); } } } } /* Step 2 is to gimplify the base expression. Make sure lvalue is set so as to match the min_lval predicate. Failure to do so may result in the creation of large aggregate temporaries. */ tret = gimplify_expr (p, pre_p, post_p, is_gimple_min_lval, fallback | fb_lvalue); ret = MIN (ret, tret); /* And finally, the indices and operands to BIT_FIELD_REF. During this loop we also remove any useless conversions. */ for (; VEC_length (tree, stack) > 0; ) { tree t = VEC_pop (tree, stack); if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF) { /* Gimplify the dimension. */ if (!is_gimple_min_invariant (TREE_OPERAND (t, 1))) { tret = gimplify_expr (&TREE_OPERAND (t, 1), pre_p, post_p, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); } } else if (TREE_CODE (t) == BIT_FIELD_REF) { tret = gimplify_expr (&TREE_OPERAND (t, 1), pre_p, post_p, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); tret = gimplify_expr (&TREE_OPERAND (t, 2), pre_p, post_p, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); } STRIP_USELESS_TYPE_CONVERSION (TREE_OPERAND (t, 0)); /* The innermost expression P may have originally had TREE_SIDE_EFFECTS set which would have caused all the outer expressions in *EXPR_P leading to P to also have had TREE_SIDE_EFFECTS set. */ recalculate_side_effects (t); } /* If the outermost expression is a COMPONENT_REF, canonicalize its type. */ if ((fallback & fb_rvalue) && TREE_CODE (*expr_p) == COMPONENT_REF) { canonicalize_component_ref (expr_p); ret = MIN (ret, GS_OK); } VEC_free (tree, heap, stack); return ret; } /* Gimplify the self modifying expression pointed to by EXPR_P (++, --, +=, -=). PRE_P points to the list where side effects that must happen before *EXPR_P should be stored. POST_P points to the list where side effects that must happen after *EXPR_P should be stored. WANT_VALUE is nonzero iff we want to use the value of this expression in another expression. */ static enum gimplify_status gimplify_self_mod_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p, bool want_value) { enum tree_code code; tree lhs, lvalue, rhs, t1; gimple_seq post = NULL, *orig_post_p = post_p; bool postfix; enum tree_code arith_code; enum gimplify_status ret; location_t loc = EXPR_LOCATION (*expr_p); code = TREE_CODE (*expr_p); gcc_assert (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR || code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR); /* Prefix or postfix? */ if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR) /* Faster to treat as prefix if result is not used. */ postfix = want_value; else postfix = false; /* For postfix, make sure the inner expression's post side effects are executed after side effects from this expression. */ if (postfix) post_p = &post; /* Add or subtract? */ if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) arith_code = PLUS_EXPR; else arith_code = MINUS_EXPR; /* Gimplify the LHS into a GIMPLE lvalue. */ lvalue = TREE_OPERAND (*expr_p, 0); ret = gimplify_expr (&lvalue, pre_p, post_p, is_gimple_lvalue, fb_lvalue); if (ret == GS_ERROR) return ret; /* Extract the operands to the arithmetic operation. */ lhs = lvalue; rhs = TREE_OPERAND (*expr_p, 1); /* For postfix operator, we evaluate the LHS to an rvalue and then use that as the result value and in the postqueue operation. We also make sure to make lvalue a minimal lval, see gcc.c-torture/execute/20040313-1.c for an example where this matters. */ if (postfix) { if (!is_gimple_min_lval (lvalue)) { mark_addressable (lvalue); lvalue = build_fold_addr_expr_loc (input_location, lvalue); gimplify_expr (&lvalue, pre_p, post_p, is_gimple_val, fb_rvalue); lvalue = build_fold_indirect_ref_loc (input_location, lvalue); } ret = gimplify_expr (&lhs, pre_p, post_p, is_gimple_val, fb_rvalue); if (ret == GS_ERROR) return ret; } /* For POINTERs increment, use POINTER_PLUS_EXPR. */ if (POINTER_TYPE_P (TREE_TYPE (lhs))) { rhs = fold_convert_loc (loc, sizetype, rhs); if (arith_code == MINUS_EXPR) rhs = fold_build1_loc (loc, NEGATE_EXPR, TREE_TYPE (rhs), rhs); arith_code = POINTER_PLUS_EXPR; } t1 = build2 (arith_code, TREE_TYPE (*expr_p), lhs, rhs); if (postfix) { gimplify_assign (lvalue, t1, orig_post_p); gimplify_seq_add_seq (orig_post_p, post); *expr_p = lhs; return GS_ALL_DONE; } else { *expr_p = build2 (MODIFY_EXPR, TREE_TYPE (lvalue), lvalue, t1); return GS_OK; } } /* If *EXPR_P has a variable sized type, wrap it in a WITH_SIZE_EXPR. */ static void maybe_with_size_expr (tree *expr_p) { tree expr = *expr_p; tree type = TREE_TYPE (expr); tree size; /* If we've already wrapped this or the type is error_mark_node, we can't do anything. */ if (TREE_CODE (expr) == WITH_SIZE_EXPR || type == error_mark_node) return; /* If the size isn't known or is a constant, we have nothing to do. */ size = TYPE_SIZE_UNIT (type); if (!size || TREE_CODE (size) == INTEGER_CST) return; /* Otherwise, make a WITH_SIZE_EXPR. */ size = unshare_expr (size); size = SUBSTITUTE_PLACEHOLDER_IN_EXPR (size, expr); *expr_p = build2 (WITH_SIZE_EXPR, type, expr, size); } /* Helper for gimplify_call_expr. Gimplify a single argument *ARG_P Store any side-effects in PRE_P. CALL_LOCATION is the location of the CALL_EXPR. */ static enum gimplify_status gimplify_arg (tree *arg_p, gimple_seq *pre_p, location_t call_location) { bool (*test) (tree); fallback_t fb; /* In general, we allow lvalues for function arguments to avoid extra overhead of copying large aggregates out of even larger aggregates into temporaries only to copy the temporaries to the argument list. Make optimizers happy by pulling out to temporaries those types that fit in registers. */ if (is_gimple_reg_type (TREE_TYPE (*arg_p))) test = is_gimple_val, fb = fb_rvalue; else test = is_gimple_lvalue, fb = fb_either; /* If this is a variable sized type, we must remember the size. */ maybe_with_size_expr (arg_p); /* FIXME diagnostics: This will mess up gcc.dg/Warray-bounds.c. */ /* Make sure arguments have the same location as the function call itself. */ protected_set_expr_location (*arg_p, call_location); /* There is a sequence point before a function call. Side effects in the argument list must occur before the actual call. So, when gimplifying arguments, force gimplify_expr to use an internal post queue which is then appended to the end of PRE_P. */ return gimplify_expr (arg_p, pre_p, NULL, test, fb); } /* Gimplify the CALL_EXPR node *EXPR_P into the GIMPLE sequence PRE_P. WANT_VALUE is true if the result of the call is desired. */ static enum gimplify_status gimplify_call_expr (tree *expr_p, gimple_seq *pre_p, bool want_value) { tree fndecl, parms, p; enum gimplify_status ret; int i, nargs; gimple call; bool builtin_va_start_p = FALSE; location_t loc = EXPR_LOCATION (*expr_p); gcc_assert (TREE_CODE (*expr_p) == CALL_EXPR); /* For reliable diagnostics during inlining, it is necessary that every call_expr be annotated with file and line. */ if (! EXPR_HAS_LOCATION (*expr_p)) SET_EXPR_LOCATION (*expr_p, input_location); /* This may be a call to a builtin function. Builtin function calls may be transformed into different (and more efficient) builtin function calls under certain circumstances. Unfortunately, gimplification can muck things up enough that the builtin expanders are not aware that certain transformations are still valid. So we attempt transformation/gimplification of the call before we gimplify the CALL_EXPR. At this time we do not manage to transform all calls in the same manner as the expanders do, but we do transform most of them. */ fndecl = get_callee_fndecl (*expr_p); if (fndecl && DECL_BUILT_IN (fndecl)) { tree new_tree = fold_call_expr (input_location, *expr_p, !want_value); if (new_tree && new_tree != *expr_p) { /* There was a transformation of this call which computes the same value, but in a more efficient way. Return and try again. */ *expr_p = new_tree; return GS_OK; } if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_VA_START) { builtin_va_start_p = TRUE; if (call_expr_nargs (*expr_p) < 2) { error ("too few arguments to function %<va_start%>"); *expr_p = build_empty_stmt (EXPR_LOCATION (*expr_p)); return GS_OK; } if (fold_builtin_next_arg (*expr_p, true)) { *expr_p = build_empty_stmt (EXPR_LOCATION (*expr_p)); return GS_OK; } } } /* There is a sequence point before the call, so any side effects in the calling expression must occur before the actual call. Force gimplify_expr to use an internal post queue. */ ret = gimplify_expr (&CALL_EXPR_FN (*expr_p), pre_p, NULL, is_gimple_call_addr, fb_rvalue); nargs = call_expr_nargs (*expr_p); /* Get argument types for verification. */ fndecl = get_callee_fndecl (*expr_p); parms = NULL_TREE; if (fndecl) parms = TYPE_ARG_TYPES (TREE_TYPE (fndecl)); else if (POINTER_TYPE_P (TREE_TYPE (CALL_EXPR_FN (*expr_p)))) parms = TYPE_ARG_TYPES (TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (*expr_p)))); if (fndecl && DECL_ARGUMENTS (fndecl)) p = DECL_ARGUMENTS (fndecl); else if (parms) p = parms; else p = NULL_TREE; for (i = 0; i < nargs && p; i++, p = TREE_CHAIN (p)) ; /* If the last argument is __builtin_va_arg_pack () and it is not passed as a named argument, decrease the number of CALL_EXPR arguments and set instead the CALL_EXPR_VA_ARG_PACK flag. */ if (!p && i < nargs && TREE_CODE (CALL_EXPR_ARG (*expr_p, nargs - 1)) == CALL_EXPR) { tree last_arg = CALL_EXPR_ARG (*expr_p, nargs - 1); tree last_arg_fndecl = get_callee_fndecl (last_arg); if (last_arg_fndecl && TREE_CODE (last_arg_fndecl) == FUNCTION_DECL && DECL_BUILT_IN_CLASS (last_arg_fndecl) == BUILT_IN_NORMAL && DECL_FUNCTION_CODE (last_arg_fndecl) == BUILT_IN_VA_ARG_PACK) { tree call = *expr_p; --nargs; *expr_p = build_call_array_loc (loc, TREE_TYPE (call), CALL_EXPR_FN (call), nargs, CALL_EXPR_ARGP (call)); /* Copy all CALL_EXPR flags, location and block, except CALL_EXPR_VA_ARG_PACK flag. */ CALL_EXPR_STATIC_CHAIN (*expr_p) = CALL_EXPR_STATIC_CHAIN (call); CALL_EXPR_TAILCALL (*expr_p) = CALL_EXPR_TAILCALL (call); CALL_EXPR_RETURN_SLOT_OPT (*expr_p) = CALL_EXPR_RETURN_SLOT_OPT (call); CALL_FROM_THUNK_P (*expr_p) = CALL_FROM_THUNK_P (call); CALL_CANNOT_INLINE_P (*expr_p) = CALL_CANNOT_INLINE_P (call); SET_EXPR_LOCATION (*expr_p, EXPR_LOCATION (call)); TREE_BLOCK (*expr_p) = TREE_BLOCK (call); /* Set CALL_EXPR_VA_ARG_PACK. */ CALL_EXPR_VA_ARG_PACK (*expr_p) = 1; } } /* Finally, gimplify the function arguments. */ if (nargs > 0) { for (i = (PUSH_ARGS_REVERSED ? nargs - 1 : 0); PUSH_ARGS_REVERSED ? i >= 0 : i < nargs; PUSH_ARGS_REVERSED ? i-- : i++) { enum gimplify_status t; /* Avoid gimplifying the second argument to va_start, which needs to be the plain PARM_DECL. */ if ((i != 1) || !builtin_va_start_p) { t = gimplify_arg (&CALL_EXPR_ARG (*expr_p, i), pre_p, EXPR_LOCATION (*expr_p)); if (t == GS_ERROR) ret = GS_ERROR; } } } /* Verify the function result. */ if (want_value && fndecl && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (fndecl)))) { error_at (loc, "using result of function returning %<void%>"); ret = GS_ERROR; } /* Try this again in case gimplification exposed something. */ if (ret != GS_ERROR) { tree new_tree = fold_call_expr (input_location, *expr_p, !want_value); if (new_tree && new_tree != *expr_p) { /* There was a transformation of this call which computes the same value, but in a more efficient way. Return and try again. */ *expr_p = new_tree; return GS_OK; } } else { *expr_p = error_mark_node; return GS_ERROR; } /* If the function is "const" or "pure", then clear TREE_SIDE_EFFECTS on its decl. This allows us to eliminate redundant or useless calls to "const" functions. */ if (TREE_CODE (*expr_p) == CALL_EXPR) { int flags = call_expr_flags (*expr_p); if (flags & (ECF_CONST | ECF_PURE) /* An infinite loop is considered a side effect. */ && !(flags & (ECF_LOOPING_CONST_OR_PURE))) TREE_SIDE_EFFECTS (*expr_p) = 0; } /* If the value is not needed by the caller, emit a new GIMPLE_CALL and clear *EXPR_P. Otherwise, leave *EXPR_P in its gimplified form and delegate the creation of a GIMPLE_CALL to gimplify_modify_expr. This is always possible because when WANT_VALUE is true, the caller wants the result of this call into a temporary, which means that we will emit an INIT_EXPR in internal_get_tmp_var which will then be handled by gimplify_modify_expr. */ if (!want_value) { /* The CALL_EXPR in *EXPR_P is already in GIMPLE form, so all we have to do is replicate it as a GIMPLE_CALL tuple. */ call = gimple_build_call_from_tree (*expr_p); gimplify_seq_add_stmt (pre_p, call); *expr_p = NULL_TREE; } return ret; } /* Handle shortcut semantics in the predicate operand of a COND_EXPR by rewriting it into multiple COND_EXPRs, and possibly GOTO_EXPRs. TRUE_LABEL_P and FALSE_LABEL_P point to the labels to jump to if the condition is true or false, respectively. If null, we should generate our own to skip over the evaluation of this specific expression. LOCUS is the source location of the COND_EXPR. This function is the tree equivalent of do_jump. shortcut_cond_r should only be called by shortcut_cond_expr. */ static tree shortcut_cond_r (tree pred, tree *true_label_p, tree *false_label_p, location_t locus) { tree local_label = NULL_TREE; tree t, expr = NULL; /* OK, it's not a simple case; we need to pull apart the COND_EXPR to retain the shortcut semantics. Just insert the gotos here; shortcut_cond_expr will append the real blocks later. */ if (TREE_CODE (pred) == TRUTH_ANDIF_EXPR) { location_t new_locus; /* Turn if (a && b) into if (a); else goto no; if (b) goto yes; else goto no; (no:) */ if (false_label_p == NULL) false_label_p = &local_label; /* Keep the original source location on the first 'if'. */ t = shortcut_cond_r (TREE_OPERAND (pred, 0), NULL, false_label_p, locus); append_to_statement_list (t, &expr); /* Set the source location of the && on the second 'if'. */ new_locus = EXPR_HAS_LOCATION (pred) ? EXPR_LOCATION (pred) : locus; t = shortcut_cond_r (TREE_OPERAND (pred, 1), true_label_p, false_label_p, new_locus); append_to_statement_list (t, &expr); } else if (TREE_CODE (pred) == TRUTH_ORIF_EXPR) { location_t new_locus; /* Turn if (a || b) into if (a) goto yes; if (b) goto yes; else goto no; (yes:) */ if (true_label_p == NULL) true_label_p = &local_label; /* Keep the original source location on the first 'if'. */ t = shortcut_cond_r (TREE_OPERAND (pred, 0), true_label_p, NULL, locus); append_to_statement_list (t, &expr); /* Set the source location of the || on the second 'if'. */ new_locus = EXPR_HAS_LOCATION (pred) ? EXPR_LOCATION (pred) : locus; t = shortcut_cond_r (TREE_OPERAND (pred, 1), true_label_p, false_label_p, new_locus); append_to_statement_list (t, &expr); } else if (TREE_CODE (pred) == COND_EXPR) { location_t new_locus; /* As long as we're messing with gotos, turn if (a ? b : c) into if (a) if (b) goto yes; else goto no; else if (c) goto yes; else goto no; */ /* Keep the original source location on the first 'if'. Set the source location of the ? on the second 'if'. */ new_locus = EXPR_HAS_LOCATION (pred) ? EXPR_LOCATION (pred) : locus; expr = build3 (COND_EXPR, void_type_node, TREE_OPERAND (pred, 0), shortcut_cond_r (TREE_OPERAND (pred, 1), true_label_p, false_label_p, locus), shortcut_cond_r (TREE_OPERAND (pred, 2), true_label_p, false_label_p, new_locus)); } else { expr = build3 (COND_EXPR, void_type_node, pred, build_and_jump (true_label_p), build_and_jump (false_label_p)); SET_EXPR_LOCATION (expr, locus); } if (local_label) { t = build1 (LABEL_EXPR, void_type_node, local_label); append_to_statement_list (t, &expr); } return expr; } /* Given a conditional expression EXPR with short-circuit boolean predicates using TRUTH_ANDIF_EXPR or TRUTH_ORIF_EXPR, break the predicate appart into the equivalent sequence of conditionals. */ static tree shortcut_cond_expr (tree expr) { tree pred = TREE_OPERAND (expr, 0); tree then_ = TREE_OPERAND (expr, 1); tree else_ = TREE_OPERAND (expr, 2); tree true_label, false_label, end_label, t; tree *true_label_p; tree *false_label_p; bool emit_end, emit_false, jump_over_else; bool then_se = then_ && TREE_SIDE_EFFECTS (then_); bool else_se = else_ && TREE_SIDE_EFFECTS (else_); /* First do simple transformations. */ if (!else_se) { /* If there is no 'else', turn if (a && b) then c into if (a) if (b) then c. */ while (TREE_CODE (pred) == TRUTH_ANDIF_EXPR) { /* Keep the original source location on the first 'if'. */ location_t locus = EXPR_HAS_LOCATION (expr) ? EXPR_LOCATION (expr) : input_location; TREE_OPERAND (expr, 0) = TREE_OPERAND (pred, 1); /* Set the source location of the && on the second 'if'. */ if (EXPR_HAS_LOCATION (pred)) SET_EXPR_LOCATION (expr, EXPR_LOCATION (pred)); then_ = shortcut_cond_expr (expr); then_se = then_ && TREE_SIDE_EFFECTS (then_); pred = TREE_OPERAND (pred, 0); expr = build3 (COND_EXPR, void_type_node, pred, then_, NULL_TREE); SET_EXPR_LOCATION (expr, locus); } } if (!then_se) { /* If there is no 'then', turn if (a || b); else d into if (a); else if (b); else d. */ while (TREE_CODE (pred) == TRUTH_ORIF_EXPR) { /* Keep the original source location on the first 'if'. */ location_t locus = EXPR_HAS_LOCATION (expr) ? EXPR_LOCATION (expr) : input_location; TREE_OPERAND (expr, 0) = TREE_OPERAND (pred, 1); /* Set the source location of the || on the second 'if'. */ if (EXPR_HAS_LOCATION (pred)) SET_EXPR_LOCATION (expr, EXPR_LOCATION (pred)); else_ = shortcut_cond_expr (expr); else_se = else_ && TREE_SIDE_EFFECTS (else_); pred = TREE_OPERAND (pred, 0); expr = build3 (COND_EXPR, void_type_node, pred, NULL_TREE, else_); SET_EXPR_LOCATION (expr, locus); } } /* If we're done, great. */ if (TREE_CODE (pred) != TRUTH_ANDIF_EXPR && TREE_CODE (pred) != TRUTH_ORIF_EXPR) return expr; /* Otherwise we need to mess with gotos. Change if (a) c; else d; to if (a); else goto no; c; goto end; no: d; end: and recursively gimplify the condition. */ true_label = false_label = end_label = NULL_TREE; /* If our arms just jump somewhere, hijack those labels so we don't generate jumps to jumps. */ if (then_ && TREE_CODE (then_) == GOTO_EXPR && TREE_CODE (GOTO_DESTINATION (then_)) == LABEL_DECL) { true_label = GOTO_DESTINATION (then_); then_ = NULL; then_se = false; } if (else_ && TREE_CODE (else_) == GOTO_EXPR && TREE_CODE (GOTO_DESTINATION (else_)) == LABEL_DECL) { false_label = GOTO_DESTINATION (else_); else_ = NULL; else_se = false; } /* If we aren't hijacking a label for the 'then' branch, it falls through. */ if (true_label) true_label_p = &true_label; else true_label_p = NULL; /* The 'else' branch also needs a label if it contains interesting code. */ if (false_label || else_se) false_label_p = &false_label; else false_label_p = NULL; /* If there was nothing else in our arms, just forward the label(s). */ if (!then_se && !else_se) return shortcut_cond_r (pred, true_label_p, false_label_p, EXPR_HAS_LOCATION (expr) ? EXPR_LOCATION (expr) : input_location); /* If our last subexpression already has a terminal label, reuse it. */ if (else_se) t = expr_last (else_); else if (then_se) t = expr_last (then_); else t = NULL; if (t && TREE_CODE (t) == LABEL_EXPR) end_label = LABEL_EXPR_LABEL (t); /* If we don't care about jumping to the 'else' branch, jump to the end if the condition is false. */ if (!false_label_p) false_label_p = &end_label; /* We only want to emit these labels if we aren't hijacking them. */ emit_end = (end_label == NULL_TREE); emit_false = (false_label == NULL_TREE); /* We only emit the jump over the else clause if we have to--if the then clause may fall through. Otherwise we can wind up with a useless jump and a useless label at the end of gimplified code, which will cause us to think that this conditional as a whole falls through even if it doesn't. If we then inline a function which ends with such a condition, that can cause us to issue an inappropriate warning about control reaching the end of a non-void function. */ jump_over_else = block_may_fallthru (then_); pred = shortcut_cond_r (pred, true_label_p, false_label_p, EXPR_HAS_LOCATION (expr) ? EXPR_LOCATION (expr) : input_location); expr = NULL; append_to_statement_list (pred, &expr); append_to_statement_list (then_, &expr); if (else_se) { if (jump_over_else) { tree last = expr_last (expr); t = build_and_jump (&end_label); if (EXPR_HAS_LOCATION (last)) SET_EXPR_LOCATION (t, EXPR_LOCATION (last)); append_to_statement_list (t, &expr); } if (emit_false) { t = build1 (LABEL_EXPR, void_type_node, false_label); append_to_statement_list (t, &expr); } append_to_statement_list (else_, &expr); } if (emit_end && end_label) { t = build1 (LABEL_EXPR, void_type_node, end_label); append_to_statement_list (t, &expr); } return expr; } /* EXPR is used in a boolean context; make sure it has BOOLEAN_TYPE. */ tree gimple_boolify (tree expr) { tree type = TREE_TYPE (expr); location_t loc = EXPR_LOCATION (expr); if (TREE_CODE (expr) == NE_EXPR && TREE_CODE (TREE_OPERAND (expr, 0)) == CALL_EXPR && integer_zerop (TREE_OPERAND (expr, 1))) { tree call = TREE_OPERAND (expr, 0); tree fn = get_callee_fndecl (call); /* For __builtin_expect ((long) (x), y) recurse into x as well if x is truth_value_p. */ if (fn && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL && DECL_FUNCTION_CODE (fn) == BUILT_IN_EXPECT && call_expr_nargs (call) == 2) { tree arg = CALL_EXPR_ARG (call, 0); if (arg) { if (TREE_CODE (arg) == NOP_EXPR && TREE_TYPE (arg) == TREE_TYPE (call)) arg = TREE_OPERAND (arg, 0); if (truth_value_p (TREE_CODE (arg))) { arg = gimple_boolify (arg); CALL_EXPR_ARG (call, 0) = fold_convert_loc (loc, TREE_TYPE (call), arg); } } } } if (TREE_CODE (type) == BOOLEAN_TYPE) return expr; switch (TREE_CODE (expr)) { case TRUTH_AND_EXPR: case TRUTH_OR_EXPR: case TRUTH_XOR_EXPR: case TRUTH_ANDIF_EXPR: case TRUTH_ORIF_EXPR: /* Also boolify the arguments of truth exprs. */ TREE_OPERAND (expr, 1) = gimple_boolify (TREE_OPERAND (expr, 1)); /* FALLTHRU */ case TRUTH_NOT_EXPR: TREE_OPERAND (expr, 0) = gimple_boolify (TREE_OPERAND (expr, 0)); /* FALLTHRU */ case EQ_EXPR: case NE_EXPR: case LE_EXPR: case GE_EXPR: case LT_EXPR: case GT_EXPR: /* These expressions always produce boolean results. */ TREE_TYPE (expr) = boolean_type_node; return expr; default: /* Other expressions that get here must have boolean values, but might need to be converted to the appropriate mode. */ return fold_convert_loc (loc, boolean_type_node, expr); } } /* Given a conditional expression *EXPR_P without side effects, gimplify its operands. New statements are inserted to PRE_P. */ static enum gimplify_status gimplify_pure_cond_expr (tree *expr_p, gimple_seq *pre_p) { tree expr = *expr_p, cond; enum gimplify_status ret, tret; enum tree_code code; cond = gimple_boolify (COND_EXPR_COND (expr)); /* We need to handle && and || specially, as their gimplification creates pure cond_expr, thus leading to an infinite cycle otherwise. */ code = TREE_CODE (cond); if (code == TRUTH_ANDIF_EXPR) TREE_SET_CODE (cond, TRUTH_AND_EXPR); else if (code == TRUTH_ORIF_EXPR) TREE_SET_CODE (cond, TRUTH_OR_EXPR); ret = gimplify_expr (&cond, pre_p, NULL, is_gimple_condexpr, fb_rvalue); COND_EXPR_COND (*expr_p) = cond; tret = gimplify_expr (&COND_EXPR_THEN (expr), pre_p, NULL, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); tret = gimplify_expr (&COND_EXPR_ELSE (expr), pre_p, NULL, is_gimple_val, fb_rvalue); return MIN (ret, tret); } /* Returns true if evaluating EXPR could trap. EXPR is GENERIC, while tree_could_trap_p can be called only on GIMPLE. */ static bool generic_expr_could_trap_p (tree expr) { unsigned i, n; if (!expr || is_gimple_val (expr)) return false; if (!EXPR_P (expr) || tree_could_trap_p (expr)) return true; n = TREE_OPERAND_LENGTH (expr); for (i = 0; i < n; i++) if (generic_expr_could_trap_p (TREE_OPERAND (expr, i))) return true; return false; } /* Convert the conditional expression pointed to by EXPR_P '(p) ? a : b;' into if (p) if (p) t1 = a; a; else or else t1 = b; b; t1; The second form is used when *EXPR_P is of type void. PRE_P points to the list where side effects that must happen before *EXPR_P should be stored. */ static enum gimplify_status gimplify_cond_expr (tree *expr_p, gimple_seq *pre_p, fallback_t fallback) { tree expr = *expr_p; tree tmp, type, arm1, arm2; enum gimplify_status ret; tree label_true, label_false, label_cont; bool have_then_clause_p, have_else_clause_p; gimple gimple_cond; enum tree_code pred_code; gimple_seq seq = NULL; location_t loc = EXPR_LOCATION (*expr_p); type = TREE_TYPE (expr); /* If this COND_EXPR has a value, copy the values into a temporary within the arms. */ if (! VOID_TYPE_P (type)) { tree result; /* If an rvalue is ok or we do not require an lvalue, avoid creating an addressable temporary. */ if (((fallback & fb_rvalue) || !(fallback & fb_lvalue)) && !TREE_ADDRESSABLE (type)) { if (gimplify_ctxp->allow_rhs_cond_expr /* If either branch has side effects or could trap, it can't be evaluated unconditionally. */ && !TREE_SIDE_EFFECTS (TREE_OPERAND (*expr_p, 1)) && !generic_expr_could_trap_p (TREE_OPERAND (*expr_p, 1)) && !TREE_SIDE_EFFECTS (TREE_OPERAND (*expr_p, 2)) && !generic_expr_could_trap_p (TREE_OPERAND (*expr_p, 2))) return gimplify_pure_cond_expr (expr_p, pre_p); result = tmp = create_tmp_var (TREE_TYPE (expr), "iftmp"); ret = GS_ALL_DONE; } else { tree type = build_pointer_type (TREE_TYPE (expr)); if (TREE_TYPE (TREE_OPERAND (expr, 1)) != void_type_node) TREE_OPERAND (expr, 1) = build_fold_addr_expr_loc (loc, TREE_OPERAND (expr, 1)); if (TREE_TYPE (TREE_OPERAND (expr, 2)) != void_type_node) TREE_OPERAND (expr, 2) = build_fold_addr_expr_loc (loc, TREE_OPERAND (expr, 2)); tmp = create_tmp_var (type, "iftmp"); expr = build3 (COND_EXPR, void_type_node, TREE_OPERAND (expr, 0), TREE_OPERAND (expr, 1), TREE_OPERAND (expr, 2)); result = build_fold_indirect_ref_loc (loc, tmp); } /* Build the then clause, 't1 = a;'. But don't build an assignment if this branch is void; in C++ it can be, if it's a throw. */ if (TREE_TYPE (TREE_OPERAND (expr, 1)) != void_type_node) TREE_OPERAND (expr, 1) = build2 (MODIFY_EXPR, TREE_TYPE (tmp), tmp, TREE_OPERAND (expr, 1)); /* Build the else clause, 't1 = b;'. */ if (TREE_TYPE (TREE_OPERAND (expr, 2)) != void_type_node) TREE_OPERAND (expr, 2) = build2 (MODIFY_EXPR, TREE_TYPE (tmp), tmp, TREE_OPERAND (expr, 2)); TREE_TYPE (expr) = void_type_node; recalculate_side_effects (expr); /* Move the COND_EXPR to the prequeue. */ gimplify_stmt (&expr, pre_p); *expr_p = result; return GS_ALL_DONE; } /* Make sure the condition has BOOLEAN_TYPE. */ TREE_OPERAND (expr, 0) = gimple_boolify (TREE_OPERAND (expr, 0)); /* Break apart && and || conditions. */ if (TREE_CODE (TREE_OPERAND (expr, 0)) == TRUTH_ANDIF_EXPR || TREE_CODE (TREE_OPERAND (expr, 0)) == TRUTH_ORIF_EXPR) { expr = shortcut_cond_expr (expr); if (expr != *expr_p) { *expr_p = expr; /* We can't rely on gimplify_expr to re-gimplify the expanded form properly, as cleanups might cause the target labels to be wrapped in a TRY_FINALLY_EXPR. To prevent that, we need to set up a conditional context. */ gimple_push_condition (); gimplify_stmt (expr_p, &seq); gimple_pop_condition (pre_p); gimple_seq_add_seq (pre_p, seq); return GS_ALL_DONE; } } /* Now do the normal gimplification. */ /* Gimplify condition. */ ret = gimplify_expr (&TREE_OPERAND (expr, 0), pre_p, NULL, is_gimple_condexpr, fb_rvalue); if (ret == GS_ERROR) return GS_ERROR; gcc_assert (TREE_OPERAND (expr, 0) != NULL_TREE); gimple_push_condition (); have_then_clause_p = have_else_clause_p = false; if (TREE_OPERAND (expr, 1) != NULL && TREE_CODE (TREE_OPERAND (expr, 1)) == GOTO_EXPR && TREE_CODE (GOTO_DESTINATION (TREE_OPERAND (expr, 1))) == LABEL_DECL && (DECL_CONTEXT (GOTO_DESTINATION (TREE_OPERAND (expr, 1))) == current_function_decl) /* For -O0 avoid this optimization if the COND_EXPR and GOTO_EXPR have different locations, otherwise we end up with incorrect location information on the branches. */ && (optimize || !EXPR_HAS_LOCATION (expr) || !EXPR_HAS_LOCATION (TREE_OPERAND (expr, 1)) || EXPR_LOCATION (expr) == EXPR_LOCATION (TREE_OPERAND (expr, 1)))) { label_true = GOTO_DESTINATION (TREE_OPERAND (expr, 1)); have_then_clause_p = true; } else label_true = create_artificial_label (UNKNOWN_LOCATION); if (TREE_OPERAND (expr, 2) != NULL && TREE_CODE (TREE_OPERAND (expr, 2)) == GOTO_EXPR && TREE_CODE (GOTO_DESTINATION (TREE_OPERAND (expr, 2))) == LABEL_DECL && (DECL_CONTEXT (GOTO_DESTINATION (TREE_OPERAND (expr, 2))) == current_function_decl) /* For -O0 avoid this optimization if the COND_EXPR and GOTO_EXPR have different locations, otherwise we end up with incorrect location information on the branches. */ && (optimize || !EXPR_HAS_LOCATION (expr) || !EXPR_HAS_LOCATION (TREE_OPERAND (expr, 2)) || EXPR_LOCATION (expr) == EXPR_LOCATION (TREE_OPERAND (expr, 2)))) { label_false = GOTO_DESTINATION (TREE_OPERAND (expr, 2)); have_else_clause_p = true; } else label_false = create_artificial_label (UNKNOWN_LOCATION); gimple_cond_get_ops_from_tree (COND_EXPR_COND (expr), &pred_code, &arm1, &arm2); gimple_cond = gimple_build_cond (pred_code, arm1, arm2, label_true, label_false); gimplify_seq_add_stmt (&seq, gimple_cond); label_cont = NULL_TREE; if (!have_then_clause_p) { /* For if (...) {} else { code; } put label_true after the else block. */ if (TREE_OPERAND (expr, 1) == NULL_TREE && !have_else_clause_p && TREE_OPERAND (expr, 2) != NULL_TREE) label_cont = label_true; else { gimplify_seq_add_stmt (&seq, gimple_build_label (label_true)); have_then_clause_p = gimplify_stmt (&TREE_OPERAND (expr, 1), &seq); /* For if (...) { code; } else {} or if (...) { code; } else goto label; or if (...) { code; return; } else { ... } label_cont isn't needed. */ if (!have_else_clause_p && TREE_OPERAND (expr, 2) != NULL_TREE && gimple_seq_may_fallthru (seq)) { gimple g; label_cont = create_artificial_label (UNKNOWN_LOCATION); g = gimple_build_goto (label_cont); /* GIMPLE_COND's are very low level; they have embedded gotos. This particular embedded goto should not be marked with the location of the original COND_EXPR, as it would correspond to the COND_EXPR's condition, not the ELSE or the THEN arms. To avoid marking it with the wrong location, flag it as "no location". */ gimple_set_do_not_emit_location (g); gimplify_seq_add_stmt (&seq, g); } } } if (!have_else_clause_p) { gimplify_seq_add_stmt (&seq, gimple_build_label (label_false)); have_else_clause_p = gimplify_stmt (&TREE_OPERAND (expr, 2), &seq); } if (label_cont) gimplify_seq_add_stmt (&seq, gimple_build_label (label_cont)); gimple_pop_condition (pre_p); gimple_seq_add_seq (pre_p, seq); if (ret == GS_ERROR) ; /* Do nothing. */ else if (have_then_clause_p || have_else_clause_p) ret = GS_ALL_DONE; else { /* Both arms are empty; replace the COND_EXPR with its predicate. */ expr = TREE_OPERAND (expr, 0); gimplify_stmt (&expr, pre_p); } *expr_p = NULL; return ret; } /* Prepare the node pointed to by EXPR_P, an is_gimple_addressable expression, to be marked addressable. We cannot rely on such an expression being directly markable if a temporary has been created by the gimplification. In this case, we create another temporary and initialize it with a copy, which will become a store after we mark it addressable. This can happen if the front-end passed us something that it could not mark addressable yet, like a Fortran pass-by-reference parameter (int) floatvar. */ static void prepare_gimple_addressable (tree *expr_p, gimple_seq *seq_p) { while (handled_component_p (*expr_p)) expr_p = &TREE_OPERAND (*expr_p, 0); if (is_gimple_reg (*expr_p)) *expr_p = get_initialized_tmp_var (*expr_p, seq_p, NULL); } /* A subroutine of gimplify_modify_expr. Replace a MODIFY_EXPR with a call to __builtin_memcpy. */ static enum gimplify_status gimplify_modify_expr_to_memcpy (tree *expr_p, tree size, bool want_value, gimple_seq *seq_p) { tree t, to, to_ptr, from, from_ptr; gimple gs; location_t loc = EXPR_LOCATION (*expr_p); to = TREE_OPERAND (*expr_p, 0); from = TREE_OPERAND (*expr_p, 1); /* Mark the RHS addressable. Beware that it may not be possible to do so directly if a temporary has been created by the gimplification. */ prepare_gimple_addressable (&from, seq_p); mark_addressable (from); from_ptr = build_fold_addr_expr_loc (loc, from); gimplify_arg (&from_ptr, seq_p, loc); mark_addressable (to); to_ptr = build_fold_addr_expr_loc (loc, to); gimplify_arg (&to_ptr, seq_p, loc); t = implicit_built_in_decls[BUILT_IN_MEMCPY]; gs = gimple_build_call (t, 3, to_ptr, from_ptr, size); if (want_value) { /* tmp = memcpy() */ t = create_tmp_var (TREE_TYPE (to_ptr), NULL); gimple_call_set_lhs (gs, t); gimplify_seq_add_stmt (seq_p, gs); *expr_p = build1 (INDIRECT_REF, TREE_TYPE (to), t); return GS_ALL_DONE; } gimplify_seq_add_stmt (seq_p, gs); *expr_p = NULL; return GS_ALL_DONE; } /* A subroutine of gimplify_modify_expr. Replace a MODIFY_EXPR with a call to __builtin_memset. In this case we know that the RHS is a CONSTRUCTOR with an empty element list. */ static enum gimplify_status gimplify_modify_expr_to_memset (tree *expr_p, tree size, bool want_value, gimple_seq *seq_p) { tree t, from, to, to_ptr; gimple gs; location_t loc = EXPR_LOCATION (*expr_p); /* Assert our assumptions, to abort instead of producing wrong code silently if they are not met. Beware that the RHS CONSTRUCTOR might not be immediately exposed. */ from = TREE_OPERAND (*expr_p, 1); if (TREE_CODE (from) == WITH_SIZE_EXPR) from = TREE_OPERAND (from, 0); gcc_assert (TREE_CODE (from) == CONSTRUCTOR && VEC_empty (constructor_elt, CONSTRUCTOR_ELTS (from))); /* Now proceed. */ to = TREE_OPERAND (*expr_p, 0); to_ptr = build_fold_addr_expr_loc (loc, to); gimplify_arg (&to_ptr, seq_p, loc); t = implicit_built_in_decls[BUILT_IN_MEMSET]; gs = gimple_build_call (t, 3, to_ptr, integer_zero_node, size); if (want_value) { /* tmp = memset() */ t = create_tmp_var (TREE_TYPE (to_ptr), NULL); gimple_call_set_lhs (gs, t); gimplify_seq_add_stmt (seq_p, gs); *expr_p = build1 (INDIRECT_REF, TREE_TYPE (to), t); return GS_ALL_DONE; } gimplify_seq_add_stmt (seq_p, gs); *expr_p = NULL; return GS_ALL_DONE; } /* A subroutine of gimplify_init_ctor_preeval. Called via walk_tree, determine, cautiously, if a CONSTRUCTOR overlaps the lhs of an assignment. Returns non-null if we detect a potential overlap. */ struct gimplify_init_ctor_preeval_data { /* The base decl of the lhs object. May be NULL, in which case we have to assume the lhs is indirect. */ tree lhs_base_decl; /* The alias set of the lhs object. */ alias_set_type lhs_alias_set; }; static tree gimplify_init_ctor_preeval_1 (tree *tp, int *walk_subtrees, void *xdata) { struct gimplify_init_ctor_preeval_data *data = (struct gimplify_init_ctor_preeval_data *) xdata; tree t = *tp; /* If we find the base object, obviously we have overlap. */ if (data->lhs_base_decl == t) return t; /* If the constructor component is indirect, determine if we have a potential overlap with the lhs. The only bits of information we have to go on at this point are addressability and alias sets. */ if (TREE_CODE (t) == INDIRECT_REF && (!data->lhs_base_decl || TREE_ADDRESSABLE (data->lhs_base_decl)) && alias_sets_conflict_p (data->lhs_alias_set, get_alias_set (t))) return t; /* If the constructor component is a call, determine if it can hide a potential overlap with the lhs through an INDIRECT_REF like above. */ if (TREE_CODE (t) == CALL_EXPR) { tree type, fntype = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (t))); for (type = TYPE_ARG_TYPES (fntype); type; type = TREE_CHAIN (type)) if (POINTER_TYPE_P (TREE_VALUE (type)) && (!data->lhs_base_decl || TREE_ADDRESSABLE (data->lhs_base_decl)) && alias_sets_conflict_p (data->lhs_alias_set, get_alias_set (TREE_TYPE (TREE_VALUE (type))))) return t; } if (IS_TYPE_OR_DECL_P (t)) *walk_subtrees = 0; return NULL; } /* A subroutine of gimplify_init_constructor. Pre-evaluate EXPR, force values that overlap with the lhs (as described by *DATA) into temporaries. */ static void gimplify_init_ctor_preeval (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p, struct gimplify_init_ctor_preeval_data *data) { enum gimplify_status one; /* If the value is constant, then there's nothing to pre-evaluate. */ if (TREE_CONSTANT (*expr_p)) { /* Ensure it does not have side effects, it might contain a reference to the object we're initializing. */ gcc_assert (!TREE_SIDE_EFFECTS (*expr_p)); return; } /* If the type has non-trivial constructors, we can't pre-evaluate. */ if (TREE_ADDRESSABLE (TREE_TYPE (*expr_p))) return; /* Recurse for nested constructors. */ if (TREE_CODE (*expr_p) == CONSTRUCTOR) { unsigned HOST_WIDE_INT ix; constructor_elt *ce; VEC(constructor_elt,gc) *v = CONSTRUCTOR_ELTS (*expr_p); for (ix = 0; VEC_iterate (constructor_elt, v, ix, ce); ix++) gimplify_init_ctor_preeval (&ce->value, pre_p, post_p, data); return; } /* If this is a variable sized type, we must remember the size. */ maybe_with_size_expr (expr_p); /* Gimplify the constructor element to something appropriate for the rhs of a MODIFY_EXPR. Given that we know the LHS is an aggregate, we know the gimplifier will consider this a store to memory. Doing this gimplification now means that we won't have to deal with complicated language-specific trees, nor trees like SAVE_EXPR that can induce exponential search behavior. */ one = gimplify_expr (expr_p, pre_p, post_p, is_gimple_mem_rhs, fb_rvalue); if (one == GS_ERROR) { *expr_p = NULL; return; } /* If we gimplified to a bare decl, we can be sure that it doesn't overlap with the lhs, since "a = { .x=a }" doesn't make sense. This will always be true for all scalars, since is_gimple_mem_rhs insists on a temporary variable for them. */ if (DECL_P (*expr_p)) return; /* If this is of variable size, we have no choice but to assume it doesn't overlap since we can't make a temporary for it. */ if (TREE_CODE (TYPE_SIZE (TREE_TYPE (*expr_p))) != INTEGER_CST) return; /* Otherwise, we must search for overlap ... */ if (!walk_tree (expr_p, gimplify_init_ctor_preeval_1, data, NULL)) return; /* ... and if found, force the value into a temporary. */ *expr_p = get_formal_tmp_var (*expr_p, pre_p); } /* A subroutine of gimplify_init_ctor_eval. Create a loop for a RANGE_EXPR in a CONSTRUCTOR for an array. var = lower; loop_entry: object[var] = value; if (var == upper) goto loop_exit; var = var + 1; goto loop_entry; loop_exit: We increment var _after_ the loop exit check because we might otherwise fail if upper == TYPE_MAX_VALUE (type for upper). Note that we never have to deal with SAVE_EXPRs here, because this has already been taken care of for us, in gimplify_init_ctor_preeval(). */ static void gimplify_init_ctor_eval (tree, VEC(constructor_elt,gc) *, gimple_seq *, bool); static void gimplify_init_ctor_eval_range (tree object, tree lower, tree upper, tree value, tree array_elt_type, gimple_seq *pre_p, bool cleared) { tree loop_entry_label, loop_exit_label, fall_thru_label; tree var, var_type, cref, tmp; loop_entry_label = create_artificial_label (UNKNOWN_LOCATION); loop_exit_label = create_artificial_label (UNKNOWN_LOCATION); fall_thru_label = create_artificial_label (UNKNOWN_LOCATION); /* Create and initialize the index variable. */ var_type = TREE_TYPE (upper); var = create_tmp_var (var_type, NULL); gimplify_seq_add_stmt (pre_p, gimple_build_assign (var, lower)); /* Add the loop entry label. */ gimplify_seq_add_stmt (pre_p, gimple_build_label (loop_entry_label)); /* Build the reference. */ cref = build4 (ARRAY_REF, array_elt_type, unshare_expr (object), var, NULL_TREE, NULL_TREE); /* If we are a constructor, just call gimplify_init_ctor_eval to do the store. Otherwise just assign value to the reference. */ if (TREE_CODE (value) == CONSTRUCTOR) /* NB we might have to call ourself recursively through gimplify_init_ctor_eval if the value is a constructor. */ gimplify_init_ctor_eval (cref, CONSTRUCTOR_ELTS (value), pre_p, cleared); else gimplify_seq_add_stmt (pre_p, gimple_build_assign (cref, value)); /* We exit the loop when the index var is equal to the upper bound. */ gimplify_seq_add_stmt (pre_p, gimple_build_cond (EQ_EXPR, var, upper, loop_exit_label, fall_thru_label)); gimplify_seq_add_stmt (pre_p, gimple_build_label (fall_thru_label)); /* Otherwise, increment the index var... */ tmp = build2 (PLUS_EXPR, var_type, var, fold_convert (var_type, integer_one_node)); gimplify_seq_add_stmt (pre_p, gimple_build_assign (var, tmp)); /* ...and jump back to the loop entry. */ gimplify_seq_add_stmt (pre_p, gimple_build_goto (loop_entry_label)); /* Add the loop exit label. */ gimplify_seq_add_stmt (pre_p, gimple_build_label (loop_exit_label)); } /* Return true if FDECL is accessing a field that is zero sized. */ static bool zero_sized_field_decl (const_tree fdecl) { if (TREE_CODE (fdecl) == FIELD_DECL && DECL_SIZE (fdecl) && integer_zerop (DECL_SIZE (fdecl))) return true; return false; } /* Return true if TYPE is zero sized. */ static bool zero_sized_type (const_tree type) { if (AGGREGATE_TYPE_P (type) && TYPE_SIZE (type) && integer_zerop (TYPE_SIZE (type))) return true; return false; } /* A subroutine of gimplify_init_constructor. Generate individual MODIFY_EXPRs for a CONSTRUCTOR. OBJECT is the LHS against which the assignments should happen. ELTS is the CONSTRUCTOR_ELTS of the CONSTRUCTOR. CLEARED is true if the entire LHS object has been zeroed first. */ static void gimplify_init_ctor_eval (tree object, VEC(constructor_elt,gc) *elts, gimple_seq *pre_p, bool cleared) { tree array_elt_type = NULL; unsigned HOST_WIDE_INT ix; tree purpose, value; if (TREE_CODE (TREE_TYPE (object)) == ARRAY_TYPE) array_elt_type = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (object))); FOR_EACH_CONSTRUCTOR_ELT (elts, ix, purpose, value) { tree cref; /* NULL values are created above for gimplification errors. */ if (value == NULL) continue; if (cleared && initializer_zerop (value)) continue; /* ??? Here's to hoping the front end fills in all of the indices, so we don't have to figure out what's missing ourselves. */ gcc_assert (purpose); /* Skip zero-sized fields, unless value has side-effects. This can happen with calls to functions returning a zero-sized type, which we shouldn't discard. As a number of downstream passes don't expect sets of zero-sized fields, we rely on the gimplification of the MODIFY_EXPR we make below to drop the assignment statement. */ if (! TREE_SIDE_EFFECTS (value) && zero_sized_field_decl (purpose)) continue; /* If we have a RANGE_EXPR, we have to build a loop to assign the whole range. */ if (TREE_CODE (purpose) == RANGE_EXPR) { tree lower = TREE_OPERAND (purpose, 0); tree upper = TREE_OPERAND (purpose, 1); /* If the lower bound is equal to upper, just treat it as if upper was the index. */ if (simple_cst_equal (lower, upper)) purpose = upper; else { gimplify_init_ctor_eval_range (object, lower, upper, value, array_elt_type, pre_p, cleared); continue; } } if (array_elt_type) { /* Do not use bitsizetype for ARRAY_REF indices. */ if (TYPE_DOMAIN (TREE_TYPE (object))) purpose = fold_convert (TREE_TYPE (TYPE_DOMAIN (TREE_TYPE (object))), purpose); cref = build4 (ARRAY_REF, array_elt_type, unshare_expr (object), purpose, NULL_TREE, NULL_TREE); } else { gcc_assert (TREE_CODE (purpose) == FIELD_DECL); cref = build3 (COMPONENT_REF, TREE_TYPE (purpose), unshare_expr (object), purpose, NULL_TREE); } if (TREE_CODE (value) == CONSTRUCTOR && TREE_CODE (TREE_TYPE (value)) != VECTOR_TYPE) gimplify_init_ctor_eval (cref, CONSTRUCTOR_ELTS (value), pre_p, cleared); else { tree init = build2 (INIT_EXPR, TREE_TYPE (cref), cref, value); gimplify_and_add (init, pre_p); ggc_free (init); } } } /* Returns the appropriate RHS predicate for this LHS. */ gimple_predicate rhs_predicate_for (tree lhs) { if (is_gimple_reg (lhs)) return is_gimple_reg_rhs_or_call; else return is_gimple_mem_rhs_or_call; } /* Gimplify a C99 compound literal expression. This just means adding the DECL_EXPR before the current statement and using its anonymous decl instead. */ static enum gimplify_status gimplify_compound_literal_expr (tree *expr_p, gimple_seq *pre_p) { tree decl_s = COMPOUND_LITERAL_EXPR_DECL_EXPR (*expr_p); tree decl = DECL_EXPR_DECL (decl_s); /* Mark the decl as addressable if the compound literal expression is addressable now, otherwise it is marked too late after we gimplify the initialization expression. */ if (TREE_ADDRESSABLE (*expr_p)) TREE_ADDRESSABLE (decl) = 1; /* Preliminarily mark non-addressed complex variables as eligible for promotion to gimple registers. We'll transform their uses as we find them. */ if ((TREE_CODE (TREE_TYPE (decl)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (decl)) == VECTOR_TYPE) && !TREE_THIS_VOLATILE (decl) && !needs_to_live_in_memory (decl)) DECL_GIMPLE_REG_P (decl) = 1; /* This decl isn't mentioned in the enclosing block, so add it to the list of temps. FIXME it seems a bit of a kludge to say that anonymous artificial vars aren't pushed, but everything else is. */ if (DECL_NAME (decl) == NULL_TREE && !DECL_SEEN_IN_BIND_EXPR_P (decl)) gimple_add_tmp_var (decl); gimplify_and_add (decl_s, pre_p); *expr_p = decl; return GS_OK; } /* Optimize embedded COMPOUND_LITERAL_EXPRs within a CONSTRUCTOR, return a new CONSTRUCTOR if something changed. */ static tree optimize_compound_literals_in_ctor (tree orig_ctor) { tree ctor = orig_ctor; VEC(constructor_elt,gc) *elts = CONSTRUCTOR_ELTS (ctor); unsigned int idx, num = VEC_length (constructor_elt, elts); for (idx = 0; idx < num; idx++) { tree value = VEC_index (constructor_elt, elts, idx)->value; tree newval = value; if (TREE_CODE (value) == CONSTRUCTOR) newval = optimize_compound_literals_in_ctor (value); else if (TREE_CODE (value) == COMPOUND_LITERAL_EXPR) { tree decl_s = COMPOUND_LITERAL_EXPR_DECL_EXPR (value); tree decl = DECL_EXPR_DECL (decl_s); tree init = DECL_INITIAL (decl); if (!TREE_ADDRESSABLE (value) && !TREE_ADDRESSABLE (decl) && init) newval = optimize_compound_literals_in_ctor (init); } if (newval == value) continue; if (ctor == orig_ctor) { ctor = copy_node (orig_ctor); CONSTRUCTOR_ELTS (ctor) = VEC_copy (constructor_elt, gc, elts); elts = CONSTRUCTOR_ELTS (ctor); } VEC_index (constructor_elt, elts, idx)->value = newval; } return ctor; } /* A subroutine of gimplify_modify_expr. Break out elements of a CONSTRUCTOR used as an initializer into separate MODIFY_EXPRs. Note that we still need to clear any elements that don't have explicit initializers, so if not all elements are initialized we keep the original MODIFY_EXPR, we just remove all of the constructor elements. If NOTIFY_TEMP_CREATION is true, do not gimplify, just return GS_ERROR if we would have to create a temporary when gimplifying this constructor. Otherwise, return GS_OK. If NOTIFY_TEMP_CREATION is false, just do the gimplification. */ static enum gimplify_status gimplify_init_constructor (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p, bool want_value, bool notify_temp_creation) { tree object, ctor, type; enum gimplify_status ret; VEC(constructor_elt,gc) *elts; gcc_assert (TREE_CODE (TREE_OPERAND (*expr_p, 1)) == CONSTRUCTOR); if (!notify_temp_creation) { ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_lvalue, fb_lvalue); if (ret == GS_ERROR) return ret; } object = TREE_OPERAND (*expr_p, 0); ctor = TREE_OPERAND (*expr_p, 1) = optimize_compound_literals_in_ctor (TREE_OPERAND (*expr_p, 1)); type = TREE_TYPE (ctor); elts = CONSTRUCTOR_ELTS (ctor); ret = GS_ALL_DONE; switch (TREE_CODE (type)) { case RECORD_TYPE: case UNION_TYPE: case QUAL_UNION_TYPE: case ARRAY_TYPE: { struct gimplify_init_ctor_preeval_data preeval_data; HOST_WIDE_INT num_type_elements, num_ctor_elements; HOST_WIDE_INT num_nonzero_elements; bool cleared, valid_const_initializer; /* Aggregate types must lower constructors to initialization of individual elements. The exception is that a CONSTRUCTOR node with no elements indicates zero-initialization of the whole. */ if (VEC_empty (constructor_elt, elts)) { if (notify_temp_creation) return GS_OK; break; } /* Fetch information about the constructor to direct later processing. We might want to make static versions of it in various cases, and can only do so if it known to be a valid constant initializer. */ valid_const_initializer = categorize_ctor_elements (ctor, &num_nonzero_elements, &num_ctor_elements, &cleared); /* If a const aggregate variable is being initialized, then it should never be a lose to promote the variable to be static. */ if (valid_const_initializer && num_nonzero_elements > 1 && TREE_READONLY (object) && TREE_CODE (object) == VAR_DECL && (flag_merge_constants >= 2 || !TREE_ADDRESSABLE (object))) { if (notify_temp_creation) return GS_ERROR; DECL_INITIAL (object) = ctor; TREE_STATIC (object) = 1; if (!DECL_NAME (object)) DECL_NAME (object) = create_tmp_var_name ("C"); walk_tree (&DECL_INITIAL (object), force_labels_r, NULL, NULL); /* ??? C++ doesn't automatically append a .<number> to the assembler name, and even when it does, it looks a FE private data structures to figure out what that number should be, which are not set for this variable. I suppose this is important for local statics for inline functions, which aren't "local" in the object file sense. So in order to get a unique TU-local symbol, we must invoke the lhd version now. */ lhd_set_decl_assembler_name (object); *expr_p = NULL_TREE; break; } /* If there are "lots" of initialized elements, even discounting those that are not address constants (and thus *must* be computed at runtime), then partition the constructor into constant and non-constant parts. Block copy the constant parts in, then generate code for the non-constant parts. */ /* TODO. There's code in cp/typeck.c to do this. */ num_type_elements = count_type_elements (type, true); /* If count_type_elements could not determine number of type elements for a constant-sized object, assume clearing is needed. Don't do this for variable-sized objects, as store_constructor will ignore the clearing of variable-sized objects. */ if (num_type_elements < 0 && int_size_in_bytes (type) >= 0) cleared = true; /* If there are "lots" of zeros, then block clear the object first. */ else if (num_type_elements - num_nonzero_elements > CLEAR_RATIO (optimize_function_for_speed_p (cfun)) && num_nonzero_elements < num_type_elements/4) cleared = true; /* ??? This bit ought not be needed. For any element not present in the initializer, we should simply set them to zero. Except we'd need to *find* the elements that are not present, and that requires trickery to avoid quadratic compile-time behavior in large cases or excessive memory use in small cases. */ else if (num_ctor_elements < num_type_elements) cleared = true; /* If there are "lots" of initialized elements, and all of them are valid address constants, then the entire initializer can be dropped to memory, and then memcpy'd out. Don't do this for sparse arrays, though, as it's more efficient to follow the standard CONSTRUCTOR behavior of memset followed by individual element initialization. Also don't do this for small all-zero initializers (which aren't big enough to merit clearing), and don't try to make bitwise copies of TREE_ADDRESSABLE types. */ if (valid_const_initializer && !(cleared || num_nonzero_elements == 0) && !TREE_ADDRESSABLE (type)) { HOST_WIDE_INT size = int_size_in_bytes (type); unsigned int align; /* ??? We can still get unbounded array types, at least from the C++ front end. This seems wrong, but attempt to work around it for now. */ if (size < 0) { size = int_size_in_bytes (TREE_TYPE (object)); if (size >= 0) TREE_TYPE (ctor) = type = TREE_TYPE (object); } /* Find the maximum alignment we can assume for the object. */ /* ??? Make use of DECL_OFFSET_ALIGN. */ if (DECL_P (object)) align = DECL_ALIGN (object); else align = TYPE_ALIGN (type); if (size > 0 && num_nonzero_elements > 1 && !can_move_by_pieces (size, align)) { tree new_tree; if (notify_temp_creation) return GS_ERROR; new_tree = create_tmp_var_raw (type, "C"); gimple_add_tmp_var (new_tree); TREE_STATIC (new_tree) = 1; TREE_READONLY (new_tree) = 1; DECL_INITIAL (new_tree) = ctor; if (align > DECL_ALIGN (new_tree)) { DECL_ALIGN (new_tree) = align; DECL_USER_ALIGN (new_tree) = 1; } walk_tree (&DECL_INITIAL (new_tree), force_labels_r, NULL, NULL); TREE_OPERAND (*expr_p, 1) = new_tree; /* This is no longer an assignment of a CONSTRUCTOR, but we still may have processing to do on the LHS. So pretend we didn't do anything here to let that happen. */ return GS_UNHANDLED; } } /* If the target is volatile and we have non-zero elements initialize the target from a temporary. */ if (TREE_THIS_VOLATILE (object) && !TREE_ADDRESSABLE (type) && num_nonzero_elements > 0) { tree temp = create_tmp_var (TYPE_MAIN_VARIANT (type), NULL); TREE_OPERAND (*expr_p, 0) = temp; *expr_p = build2 (COMPOUND_EXPR, TREE_TYPE (*expr_p), *expr_p, build2 (MODIFY_EXPR, void_type_node, object, temp)); return GS_OK; } if (notify_temp_creation) return GS_OK; /* If there are nonzero elements, pre-evaluate to capture elements overlapping with the lhs into temporaries. We must do this before clearing to fetch the values before they are zeroed-out. */ if (num_nonzero_elements > 0) { preeval_data.lhs_base_decl = get_base_address (object); if (!DECL_P (preeval_data.lhs_base_decl)) preeval_data.lhs_base_decl = NULL; preeval_data.lhs_alias_set = get_alias_set (object); gimplify_init_ctor_preeval (&TREE_OPERAND (*expr_p, 1), pre_p, post_p, &preeval_data); } if (cleared) { /* Zap the CONSTRUCTOR element list, which simplifies this case. Note that we still have to gimplify, in order to handle the case of variable sized types. Avoid shared tree structures. */ CONSTRUCTOR_ELTS (ctor) = NULL; TREE_SIDE_EFFECTS (ctor) = 0; object = unshare_expr (object); gimplify_stmt (expr_p, pre_p); } /* If we have not block cleared the object, or if there are nonzero elements in the constructor, add assignments to the individual scalar fields of the object. */ if (!cleared || num_nonzero_elements > 0) gimplify_init_ctor_eval (object, elts, pre_p, cleared); *expr_p = NULL_TREE; } break; case COMPLEX_TYPE: { tree r, i; if (notify_temp_creation) return GS_OK; /* Extract the real and imaginary parts out of the ctor. */ gcc_assert (VEC_length (constructor_elt, elts) == 2); r = VEC_index (constructor_elt, elts, 0)->value; i = VEC_index (constructor_elt, elts, 1)->value; if (r == NULL || i == NULL) { tree zero = fold_convert (TREE_TYPE (type), integer_zero_node); if (r == NULL) r = zero; if (i == NULL) i = zero; } /* Complex types have either COMPLEX_CST or COMPLEX_EXPR to represent creation of a complex value. */ if (TREE_CONSTANT (r) && TREE_CONSTANT (i)) { ctor = build_complex (type, r, i); TREE_OPERAND (*expr_p, 1) = ctor; } else { ctor = build2 (COMPLEX_EXPR, type, r, i); TREE_OPERAND (*expr_p, 1) = ctor; ret = gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p, post_p, rhs_predicate_for (TREE_OPERAND (*expr_p, 0)), fb_rvalue); } } break; case VECTOR_TYPE: { unsigned HOST_WIDE_INT ix; constructor_elt *ce; if (notify_temp_creation) return GS_OK; /* Go ahead and simplify constant constructors to VECTOR_CST. */ if (TREE_CONSTANT (ctor)) { bool constant_p = true; tree value; /* Even when ctor is constant, it might contain non-*_CST elements, such as addresses or trapping values like 1.0/0.0 - 1.0/0.0. Such expressions don't belong in VECTOR_CST nodes. */ FOR_EACH_CONSTRUCTOR_VALUE (elts, ix, value) if (!CONSTANT_CLASS_P (value)) { constant_p = false; break; } if (constant_p) { TREE_OPERAND (*expr_p, 1) = build_vector_from_ctor (type, elts); break; } /* Don't reduce an initializer constant even if we can't make a VECTOR_CST. It won't do anything for us, and it'll prevent us from representing it as a single constant. */ if (initializer_constant_valid_p (ctor, type)) break; TREE_CONSTANT (ctor) = 0; } /* Vector types use CONSTRUCTOR all the way through gimple compilation as a general initializer. */ for (ix = 0; VEC_iterate (constructor_elt, elts, ix, ce); ix++) { enum gimplify_status tret; tret = gimplify_expr (&ce->value, pre_p, post_p, is_gimple_val, fb_rvalue); if (tret == GS_ERROR) ret = GS_ERROR; } if (!is_gimple_reg (TREE_OPERAND (*expr_p, 0))) TREE_OPERAND (*expr_p, 1) = get_formal_tmp_var (ctor, pre_p); } break; default: /* So how did we get a CONSTRUCTOR for a scalar type? */ gcc_unreachable (); } if (ret == GS_ERROR) return GS_ERROR; else if (want_value) { *expr_p = object; return GS_OK; } else { /* If we have gimplified both sides of the initializer but have not emitted an assignment, do so now. */ if (*expr_p) { tree lhs = TREE_OPERAND (*expr_p, 0); tree rhs = TREE_OPERAND (*expr_p, 1); gimple init = gimple_build_assign (lhs, rhs); gimplify_seq_add_stmt (pre_p, init); *expr_p = NULL; } return GS_ALL_DONE; } } /* Given a pointer value OP0, return a simplified version of an indirection through OP0, or NULL_TREE if no simplification is possible. Note that the resulting type may be different from the type pointed to in the sense that it is still compatible from the langhooks point of view. */ tree gimple_fold_indirect_ref (tree t) { tree type = TREE_TYPE (TREE_TYPE (t)); tree sub = t; tree subtype; STRIP_NOPS (sub); subtype = TREE_TYPE (sub); if (!POINTER_TYPE_P (subtype)) return NULL_TREE; if (TREE_CODE (sub) == ADDR_EXPR) { tree op = TREE_OPERAND (sub, 0); tree optype = TREE_TYPE (op); /* *&p => p */ if (useless_type_conversion_p (type, optype)) return op; /* *(foo *)&fooarray => fooarray[0] */ if (TREE_CODE (optype) == ARRAY_TYPE && TREE_CODE (TYPE_SIZE (TREE_TYPE (optype))) == INTEGER_CST && useless_type_conversion_p (type, TREE_TYPE (optype))) { tree type_domain = TYPE_DOMAIN (optype); tree min_val = size_zero_node; if (type_domain && TYPE_MIN_VALUE (type_domain)) min_val = TYPE_MIN_VALUE (type_domain); if (TREE_CODE (min_val) == INTEGER_CST) return build4 (ARRAY_REF, type, op, min_val, NULL_TREE, NULL_TREE); } /* *(foo *)&complexfoo => __real__ complexfoo */ else if (TREE_CODE (optype) == COMPLEX_TYPE && useless_type_conversion_p (type, TREE_TYPE (optype))) return fold_build1 (REALPART_EXPR, type, op); /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */ else if (TREE_CODE (optype) == VECTOR_TYPE && useless_type_conversion_p (type, TREE_TYPE (optype))) { tree part_width = TYPE_SIZE (type); tree index = bitsize_int (0); return fold_build3 (BIT_FIELD_REF, type, op, part_width, index); } } /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */ if (TREE_CODE (sub) == POINTER_PLUS_EXPR && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST) { tree op00 = TREE_OPERAND (sub, 0); tree op01 = TREE_OPERAND (sub, 1); tree op00type; STRIP_NOPS (op00); op00type = TREE_TYPE (op00); if (TREE_CODE (op00) == ADDR_EXPR && TREE_CODE (TREE_TYPE (op00type)) == VECTOR_TYPE && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (op00type)))) { HOST_WIDE_INT offset = tree_low_cst (op01, 0); tree part_width = TYPE_SIZE (type); unsigned HOST_WIDE_INT part_widthi = tree_low_cst (part_width, 0) / BITS_PER_UNIT; unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT; tree index = bitsize_int (indexi); if (offset / part_widthi <= TYPE_VECTOR_SUBPARTS (TREE_TYPE (op00type))) return fold_build3 (BIT_FIELD_REF, type, TREE_OPERAND (op00, 0), part_width, index); } } /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */ if (TREE_CODE (sub) == POINTER_PLUS_EXPR && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST) { tree op00 = TREE_OPERAND (sub, 0); tree op01 = TREE_OPERAND (sub, 1); tree op00type; STRIP_NOPS (op00); op00type = TREE_TYPE (op00); if (TREE_CODE (op00) == ADDR_EXPR && TREE_CODE (TREE_TYPE (op00type)) == COMPLEX_TYPE && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (op00type)))) { tree size = TYPE_SIZE_UNIT (type); if (tree_int_cst_equal (size, op01)) return fold_build1 (IMAGPART_EXPR, type, TREE_OPERAND (op00, 0)); } } /* *(foo *)fooarrptr => (*fooarrptr)[0] */ if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE && TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (subtype)))) == INTEGER_CST && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (subtype)))) { tree type_domain; tree min_val = size_zero_node; tree osub = sub; sub = gimple_fold_indirect_ref (sub); if (! sub) sub = build1 (INDIRECT_REF, TREE_TYPE (subtype), osub); type_domain = TYPE_DOMAIN (TREE_TYPE (sub)); if (type_domain && TYPE_MIN_VALUE (type_domain)) min_val = TYPE_MIN_VALUE (type_domain); if (TREE_CODE (min_val) == INTEGER_CST) return build4 (ARRAY_REF, type, sub, min_val, NULL_TREE, NULL_TREE); } return NULL_TREE; } /* Given a pointer value OP0, return a simplified version of an indirection through OP0, or NULL_TREE if no simplification is possible. This may only be applied to a rhs of an expression. Note that the resulting type may be different from the type pointed to in the sense that it is still compatible from the langhooks point of view. */ static tree gimple_fold_indirect_ref_rhs (tree t) { return gimple_fold_indirect_ref (t); } /* Subroutine of gimplify_modify_expr to do simplifications of MODIFY_EXPRs based on the code of the RHS. We loop for as long as something changes. */ static enum gimplify_status gimplify_modify_expr_rhs (tree *expr_p, tree *from_p, tree *to_p, gimple_seq *pre_p, gimple_seq *post_p, bool want_value) { enum gimplify_status ret = GS_UNHANDLED; bool changed; do { changed = false; switch (TREE_CODE (*from_p)) { case VAR_DECL: /* If we're assigning from a read-only variable initialized with a constructor, do the direct assignment from the constructor, but only if neither source nor target are volatile since this latter assignment might end up being done on a per-field basis. */ if (DECL_INITIAL (*from_p) && TREE_READONLY (*from_p) && !TREE_THIS_VOLATILE (*from_p) && !TREE_THIS_VOLATILE (*to_p) && TREE_CODE (DECL_INITIAL (*from_p)) == CONSTRUCTOR) { tree old_from = *from_p; enum gimplify_status subret; /* Move the constructor into the RHS. */ *from_p = unshare_expr (DECL_INITIAL (*from_p)); /* Let's see if gimplify_init_constructor will need to put it in memory. */ subret = gimplify_init_constructor (expr_p, NULL, NULL, false, true); if (subret == GS_ERROR) { /* If so, revert the change. */ *from_p = old_from; } else { ret = GS_OK; changed = true; } } break; case INDIRECT_REF: { /* If we have code like *(const A*)(A*)&x where the type of "x" is a (possibly cv-qualified variant of "A"), treat the entire expression as identical to "x". This kind of code arises in C++ when an object is bound to a const reference, and if "x" is a TARGET_EXPR we want to take advantage of the optimization below. */ tree t = gimple_fold_indirect_ref_rhs (TREE_OPERAND (*from_p, 0)); if (t) { *from_p = t; ret = GS_OK; changed = true; } break; } case TARGET_EXPR: { /* If we are initializing something from a TARGET_EXPR, strip the TARGET_EXPR and initialize it directly, if possible. This can't be done if the initializer is void, since that implies that the temporary is set in some non-trivial way. ??? What about code that pulls out the temp and uses it elsewhere? I think that such code never uses the TARGET_EXPR as an initializer. If I'm wrong, we'll die because the temp won't have any RTL. In that case, I guess we'll need to replace references somehow. */ tree init = TARGET_EXPR_INITIAL (*from_p); if (init && !VOID_TYPE_P (TREE_TYPE (init))) { *from_p = init; ret = GS_OK; changed = true; } } break; case COMPOUND_EXPR: /* Remove any COMPOUND_EXPR in the RHS so the following cases will be caught. */ gimplify_compound_expr (from_p, pre_p, true); ret = GS_OK; changed = true; break; case CONSTRUCTOR: /* If we're initializing from a CONSTRUCTOR, break this into individual MODIFY_EXPRs. */ return gimplify_init_constructor (expr_p, pre_p, post_p, want_value, false); case COND_EXPR: /* If we're assigning to a non-register type, push the assignment down into the branches. This is mandatory for ADDRESSABLE types, since we cannot generate temporaries for such, but it saves a copy in other cases as well. */ if (!is_gimple_reg_type (TREE_TYPE (*from_p))) { /* This code should mirror the code in gimplify_cond_expr. */ enum tree_code code = TREE_CODE (*expr_p); tree cond = *from_p; tree result = *to_p; ret = gimplify_expr (&result, pre_p, post_p, is_gimple_lvalue, fb_lvalue); if (ret != GS_ERROR) ret = GS_OK; if (TREE_TYPE (TREE_OPERAND (cond, 1)) != void_type_node) TREE_OPERAND (cond, 1) = build2 (code, void_type_node, result, TREE_OPERAND (cond, 1)); if (TREE_TYPE (TREE_OPERAND (cond, 2)) != void_type_node) TREE_OPERAND (cond, 2) = build2 (code, void_type_node, unshare_expr (result), TREE_OPERAND (cond, 2)); TREE_TYPE (cond) = void_type_node; recalculate_side_effects (cond); if (want_value) { gimplify_and_add (cond, pre_p); *expr_p = unshare_expr (result); } else *expr_p = cond; return ret; } break; case CALL_EXPR: /* For calls that return in memory, give *to_p as the CALL_EXPR's return slot so that we don't generate a temporary. */ if (!CALL_EXPR_RETURN_SLOT_OPT (*from_p) && aggregate_value_p (*from_p, *from_p)) { bool use_target; if (!(rhs_predicate_for (*to_p))(*from_p)) /* If we need a temporary, *to_p isn't accurate. */ use_target = false; else if (TREE_CODE (*to_p) == RESULT_DECL && DECL_NAME (*to_p) == NULL_TREE && needs_to_live_in_memory (*to_p)) /* It's OK to use the return slot directly unless it's an NRV. */ use_target = true; else if (is_gimple_reg_type (TREE_TYPE (*to_p)) || (DECL_P (*to_p) && DECL_REGISTER (*to_p))) /* Don't force regs into memory. */ use_target = false; else if (TREE_CODE (*expr_p) == INIT_EXPR) /* It's OK to use the target directly if it's being initialized. */ use_target = true; else if (!is_gimple_non_addressable (*to_p)) /* Don't use the original target if it's already addressable; if its address escapes, and the called function uses the NRV optimization, a conforming program could see *to_p change before the called function returns; see c++/19317. When optimizing, the return_slot pass marks more functions as safe after we have escape info. */ use_target = false; else use_target = true; if (use_target) { CALL_EXPR_RETURN_SLOT_OPT (*from_p) = 1; mark_addressable (*to_p); } } break; /* If we're initializing from a container, push the initialization inside it. */ case CLEANUP_POINT_EXPR: case BIND_EXPR: case STATEMENT_LIST: { tree wrap = *from_p; tree t; ret = gimplify_expr (to_p, pre_p, post_p, is_gimple_min_lval, fb_lvalue); if (ret != GS_ERROR) ret = GS_OK; t = voidify_wrapper_expr (wrap, *expr_p); gcc_assert (t == *expr_p); if (want_value) { gimplify_and_add (wrap, pre_p); *expr_p = unshare_expr (*to_p); } else *expr_p = wrap; return GS_OK; } case COMPOUND_LITERAL_EXPR: { tree complit = TREE_OPERAND (*expr_p, 1); tree decl_s = COMPOUND_LITERAL_EXPR_DECL_EXPR (complit); tree decl = DECL_EXPR_DECL (decl_s); tree init = DECL_INITIAL (decl); /* struct T x = (struct T) { 0, 1, 2 } can be optimized into struct T x = { 0, 1, 2 } if the address of the compound literal has never been taken. */ if (!TREE_ADDRESSABLE (complit) && !TREE_ADDRESSABLE (decl) && init) { *expr_p = copy_node (*expr_p); TREE_OPERAND (*expr_p, 1) = init; return GS_OK; } } default: break; } } while (changed); return ret; } /* Promote partial stores to COMPLEX variables to total stores. *EXPR_P is a MODIFY_EXPR with a lhs of a REAL/IMAGPART_EXPR of a variable with DECL_GIMPLE_REG_P set. IMPORTANT NOTE: This promotion is performed by introducing a load of the other, unmodified part of the complex object just before the total store. As a consequence, if the object is still uninitialized, an undefined value will be loaded into a register, which may result in a spurious exception if the register is floating-point and the value happens to be a signaling NaN for example. Then the fully-fledged complex operations lowering pass followed by a DCE pass are necessary in order to fix things up. */ static enum gimplify_status gimplify_modify_expr_complex_part (tree *expr_p, gimple_seq *pre_p, bool want_value) { enum tree_code code, ocode; tree lhs, rhs, new_rhs, other, realpart, imagpart; lhs = TREE_OPERAND (*expr_p, 0); rhs = TREE_OPERAND (*expr_p, 1); code = TREE_CODE (lhs); lhs = TREE_OPERAND (lhs, 0); ocode = code == REALPART_EXPR ? IMAGPART_EXPR : REALPART_EXPR; other = build1 (ocode, TREE_TYPE (rhs), lhs); other = get_formal_tmp_var (other, pre_p); realpart = code == REALPART_EXPR ? rhs : other; imagpart = code == REALPART_EXPR ? other : rhs; if (TREE_CONSTANT (realpart) && TREE_CONSTANT (imagpart)) new_rhs = build_complex (TREE_TYPE (lhs), realpart, imagpart); else new_rhs = build2 (COMPLEX_EXPR, TREE_TYPE (lhs), realpart, imagpart); gimplify_seq_add_stmt (pre_p, gimple_build_assign (lhs, new_rhs)); *expr_p = (want_value) ? rhs : NULL_TREE; return GS_ALL_DONE; } /* Gimplify the MODIFY_EXPR node pointed to by EXPR_P. modify_expr : varname '=' rhs | '*' ID '=' rhs PRE_P points to the list where side effects that must happen before *EXPR_P should be stored. POST_P points to the list where side effects that must happen after *EXPR_P should be stored. WANT_VALUE is nonzero iff we want to use the value of this expression in another expression. */ static enum gimplify_status gimplify_modify_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p, bool want_value) { tree *from_p = &TREE_OPERAND (*expr_p, 1); tree *to_p = &TREE_OPERAND (*expr_p, 0); enum gimplify_status ret = GS_UNHANDLED; gimple assign; location_t loc = EXPR_LOCATION (*expr_p); gcc_assert (TREE_CODE (*expr_p) == MODIFY_EXPR || TREE_CODE (*expr_p) == INIT_EXPR); /* Insert pointer conversions required by the middle-end that are not required by the frontend. This fixes middle-end type checking for for example gcc.dg/redecl-6.c. */ if (POINTER_TYPE_P (TREE_TYPE (*to_p))) { STRIP_USELESS_TYPE_CONVERSION (*from_p); if (!useless_type_conversion_p (TREE_TYPE (*to_p), TREE_TYPE (*from_p))) *from_p = fold_convert_loc (loc, TREE_TYPE (*to_p), *from_p); } /* See if any simplifications can be done based on what the RHS is. */ ret = gimplify_modify_expr_rhs (expr_p, from_p, to_p, pre_p, post_p, want_value); if (ret != GS_UNHANDLED) return ret; /* For zero sized types only gimplify the left hand side and right hand side as statements and throw away the assignment. Do this after gimplify_modify_expr_rhs so we handle TARGET_EXPRs of addressable types properly. */ if (zero_sized_type (TREE_TYPE (*from_p)) && !want_value) { gimplify_stmt (from_p, pre_p); gimplify_stmt (to_p, pre_p); *expr_p = NULL_TREE; return GS_ALL_DONE; } /* If the value being copied is of variable width, compute the length of the copy into a WITH_SIZE_EXPR. Note that we need to do this before gimplifying any of the operands so that we can resolve any PLACEHOLDER_EXPRs in the size. Also note that the RTL expander uses the size of the expression to be copied, not of the destination, so that is what we must do here. */ maybe_with_size_expr (from_p); ret = gimplify_expr (to_p, pre_p, post_p, is_gimple_lvalue, fb_lvalue); if (ret == GS_ERROR) return ret; /* As a special case, we have to temporarily allow for assignments with a CALL_EXPR on the RHS. Since in GIMPLE a function call is a toplevel statement, when gimplifying the GENERIC expression MODIFY_EXPR <a, CALL_EXPR <foo>>, we cannot create the tuple GIMPLE_ASSIGN <a, GIMPLE_CALL <foo>>. Instead, we need to create the tuple GIMPLE_CALL <a, foo>. To prevent gimplify_expr from trying to create a new temporary for foo's LHS, we tell it that it should only gimplify until it reaches the CALL_EXPR. On return from gimplify_expr, the newly created GIMPLE_CALL <foo> will be the last statement in *PRE_P and all we need to do here is set 'a' to be its LHS. */ ret = gimplify_expr (from_p, pre_p, post_p, rhs_predicate_for (*to_p), fb_rvalue); if (ret == GS_ERROR) return ret; /* Now see if the above changed *from_p to something we handle specially. */ ret = gimplify_modify_expr_rhs (expr_p, from_p, to_p, pre_p, post_p, want_value); if (ret != GS_UNHANDLED) return ret; /* If we've got a variable sized assignment between two lvalues (i.e. does not involve a call), then we can make things a bit more straightforward by converting the assignment to memcpy or memset. */ if (TREE_CODE (*from_p) == WITH_SIZE_EXPR) { tree from = TREE_OPERAND (*from_p, 0); tree size = TREE_OPERAND (*from_p, 1); if (TREE_CODE (from) == CONSTRUCTOR) return gimplify_modify_expr_to_memset (expr_p, size, want_value, pre_p); if (is_gimple_addressable (from)) { *from_p = from; return gimplify_modify_expr_to_memcpy (expr_p, size, want_value, pre_p); } } /* Transform partial stores to non-addressable complex variables into total stores. This allows us to use real instead of virtual operands for these variables, which improves optimization. */ if ((TREE_CODE (*to_p) == REALPART_EXPR || TREE_CODE (*to_p) == IMAGPART_EXPR) && is_gimple_reg (TREE_OPERAND (*to_p, 0))) return gimplify_modify_expr_complex_part (expr_p, pre_p, want_value); /* Try to alleviate the effects of the gimplification creating artificial temporaries (see for example is_gimple_reg_rhs) on the debug info. */ if (!gimplify_ctxp->into_ssa && DECL_P (*from_p) && DECL_IGNORED_P (*from_p) && DECL_P (*to_p) && !DECL_IGNORED_P (*to_p)) { if (!DECL_NAME (*from_p) && DECL_NAME (*to_p)) DECL_NAME (*from_p) = create_tmp_var_name (IDENTIFIER_POINTER (DECL_NAME (*to_p))); DECL_DEBUG_EXPR_IS_FROM (*from_p) = 1; SET_DECL_DEBUG_EXPR (*from_p, *to_p); } if (TREE_CODE (*from_p) == CALL_EXPR) { /* Since the RHS is a CALL_EXPR, we need to create a GIMPLE_CALL instead of a GIMPLE_ASSIGN. */ assign = gimple_build_call_from_tree (*from_p); if (!gimple_call_noreturn_p (assign)) gimple_call_set_lhs (assign, *to_p); } else { assign = gimple_build_assign (*to_p, *from_p); gimple_set_location (assign, EXPR_LOCATION (*expr_p)); } gimplify_seq_add_stmt (pre_p, assign); if (gimplify_ctxp->into_ssa && is_gimple_reg (*to_p)) { /* If we've somehow already got an SSA_NAME on the LHS, then we've probably modified it twice. Not good. */ gcc_assert (TREE_CODE (*to_p) != SSA_NAME); *to_p = make_ssa_name (*to_p, assign); gimple_set_lhs (assign, *to_p); } if (want_value) { *expr_p = unshare_expr (*to_p); return GS_OK; } else *expr_p = NULL; return GS_ALL_DONE; } /* Gimplify a comparison between two variable-sized objects. Do this with a call to BUILT_IN_MEMCMP. */ static enum gimplify_status gimplify_variable_sized_compare (tree *expr_p) { tree op0 = TREE_OPERAND (*expr_p, 0); tree op1 = TREE_OPERAND (*expr_p, 1); tree t, arg, dest, src; location_t loc = EXPR_LOCATION (*expr_p); arg = TYPE_SIZE_UNIT (TREE_TYPE (op0)); arg = unshare_expr (arg); arg = SUBSTITUTE_PLACEHOLDER_IN_EXPR (arg, op0); src = build_fold_addr_expr_loc (loc, op1); dest = build_fold_addr_expr_loc (loc, op0); t = implicit_built_in_decls[BUILT_IN_MEMCMP]; t = build_call_expr_loc (loc, t, 3, dest, src, arg); *expr_p = build2 (TREE_CODE (*expr_p), TREE_TYPE (*expr_p), t, integer_zero_node); return GS_OK; } /* Gimplify a comparison between two aggregate objects of integral scalar mode as a comparison between the bitwise equivalent scalar values. */ static enum gimplify_status gimplify_scalar_mode_aggregate_compare (tree *expr_p) { location_t loc = EXPR_LOCATION (*expr_p); tree op0 = TREE_OPERAND (*expr_p, 0); tree op1 = TREE_OPERAND (*expr_p, 1); tree type = TREE_TYPE (op0); tree scalar_type = lang_hooks.types.type_for_mode (TYPE_MODE (type), 1); op0 = fold_build1_loc (loc, VIEW_CONVERT_EXPR, scalar_type, op0); op1 = fold_build1_loc (loc, VIEW_CONVERT_EXPR, scalar_type, op1); *expr_p = fold_build2_loc (loc, TREE_CODE (*expr_p), TREE_TYPE (*expr_p), op0, op1); return GS_OK; } /* Gimplify TRUTH_ANDIF_EXPR and TRUTH_ORIF_EXPR expressions. EXPR_P points to the expression to gimplify. Expressions of the form 'a && b' are gimplified to: a && b ? true : false LOCUS is the source location to be put on the generated COND_EXPR. gimplify_cond_expr will do the rest. */ static enum gimplify_status gimplify_boolean_expr (tree *expr_p, location_t locus) { /* Preserve the original type of the expression. */ tree type = TREE_TYPE (*expr_p); *expr_p = build3 (COND_EXPR, type, *expr_p, fold_convert_loc (locus, type, boolean_true_node), fold_convert_loc (locus, type, boolean_false_node)); SET_EXPR_LOCATION (*expr_p, locus); return GS_OK; } /* Gimplifies an expression sequence. This function gimplifies each expression and re-writes the original expression with the last expression of the sequence in GIMPLE form. PRE_P points to the list where the side effects for all the expressions in the sequence will be emitted. WANT_VALUE is true when the result of the last COMPOUND_EXPR is used. */ static enum gimplify_status gimplify_compound_expr (tree *expr_p, gimple_seq *pre_p, bool want_value) { tree t = *expr_p; do { tree *sub_p = &TREE_OPERAND (t, 0); if (TREE_CODE (*sub_p) == COMPOUND_EXPR) gimplify_compound_expr (sub_p, pre_p, false); else gimplify_stmt (sub_p, pre_p); t = TREE_OPERAND (t, 1); } while (TREE_CODE (t) == COMPOUND_EXPR); *expr_p = t; if (want_value) return GS_OK; else { gimplify_stmt (expr_p, pre_p); return GS_ALL_DONE; } } /* Gimplify a SAVE_EXPR node. EXPR_P points to the expression to gimplify. After gimplification, EXPR_P will point to a new temporary that holds the original value of the SAVE_EXPR node. PRE_P points to the list where side effects that must happen before *EXPR_P should be stored. */ static enum gimplify_status gimplify_save_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p) { enum gimplify_status ret = GS_ALL_DONE; tree val; gcc_assert (TREE_CODE (*expr_p) == SAVE_EXPR); val = TREE_OPERAND (*expr_p, 0); /* If the SAVE_EXPR has not been resolved, then evaluate it once. */ if (!SAVE_EXPR_RESOLVED_P (*expr_p)) { /* The operand may be a void-valued expression such as SAVE_EXPRs generated by the Java frontend for class initialization. It is being executed only for its side-effects. */ if (TREE_TYPE (val) == void_type_node) { ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_stmt, fb_none); val = NULL; } else val = get_initialized_tmp_var (val, pre_p, post_p); TREE_OPERAND (*expr_p, 0) = val; SAVE_EXPR_RESOLVED_P (*expr_p) = 1; } *expr_p = val; return ret; } /* Re-write the ADDR_EXPR node pointed to by EXPR_P unary_expr : ... | '&' varname ... PRE_P points to the list where side effects that must happen before *EXPR_P should be stored. POST_P points to the list where side effects that must happen after *EXPR_P should be stored. */ static enum gimplify_status gimplify_addr_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p) { tree expr = *expr_p; tree op0 = TREE_OPERAND (expr, 0); enum gimplify_status ret; location_t loc = EXPR_LOCATION (*expr_p); switch (TREE_CODE (op0)) { case INDIRECT_REF: case MISALIGNED_INDIRECT_REF: do_indirect_ref: /* Check if we are dealing with an expression of the form '&*ptr'. While the front end folds away '&*ptr' into 'ptr', these expressions may be generated internally by the compiler (e.g., builtins like __builtin_va_end). */ /* Caution: the silent array decomposition semantics we allow for ADDR_EXPR means we can't always discard the pair. */ /* Gimplification of the ADDR_EXPR operand may drop cv-qualification conversions, so make sure we add them if needed. */ { tree op00 = TREE_OPERAND (op0, 0); tree t_expr = TREE_TYPE (expr); tree t_op00 = TREE_TYPE (op00); if (!useless_type_conversion_p (t_expr, t_op00)) op00 = fold_convert_loc (loc, TREE_TYPE (expr), op00); *expr_p = op00; ret = GS_OK; } break; case VIEW_CONVERT_EXPR: /* Take the address of our operand and then convert it to the type of this ADDR_EXPR. ??? The interactions of VIEW_CONVERT_EXPR and aliasing is not at all clear. The impact of this transformation is even less clear. */ /* If the operand is a useless conversion, look through it. Doing so guarantees that the ADDR_EXPR and its operand will remain of the same type. */ if (tree_ssa_useless_type_conversion (TREE_OPERAND (op0, 0))) op0 = TREE_OPERAND (op0, 0); *expr_p = fold_convert_loc (loc, TREE_TYPE (expr), build_fold_addr_expr_loc (loc, TREE_OPERAND (op0, 0))); ret = GS_OK; break; default: /* We use fb_either here because the C frontend sometimes takes the address of a call that returns a struct; see gcc.dg/c99-array-lval-1.c. The gimplifier will correctly make the implied temporary explicit. */ /* Make the operand addressable. */ ret = gimplify_expr (&TREE_OPERAND (expr, 0), pre_p, post_p, is_gimple_addressable, fb_either); if (ret == GS_ERROR) break; /* Then mark it. Beware that it may not be possible to do so directly if a temporary has been created by the gimplification. */ prepare_gimple_addressable (&TREE_OPERAND (expr, 0), pre_p); op0 = TREE_OPERAND (expr, 0); /* For various reasons, the gimplification of the expression may have made a new INDIRECT_REF. */ if (TREE_CODE (op0) == INDIRECT_REF) goto do_indirect_ref; mark_addressable (TREE_OPERAND (expr, 0)); /* The FEs may end up building ADDR_EXPRs early on a decl with an incomplete type. Re-build ADDR_EXPRs in canonical form here. */ if (!types_compatible_p (TREE_TYPE (op0), TREE_TYPE (TREE_TYPE (expr)))) *expr_p = build_fold_addr_expr (op0); /* Make sure TREE_CONSTANT and TREE_SIDE_EFFECTS are set properly. */ recompute_tree_invariant_for_addr_expr (*expr_p); /* If we re-built the ADDR_EXPR add a conversion to the original type if required. */ if (!useless_type_conversion_p (TREE_TYPE (expr), TREE_TYPE (*expr_p))) *expr_p = fold_convert (TREE_TYPE (expr), *expr_p); break; } return ret; } /* Gimplify the operands of an ASM_EXPR. Input operands should be a gimple value; output operands should be a gimple lvalue. */ static enum gimplify_status gimplify_asm_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p) { tree expr; int noutputs; const char **oconstraints; int i; tree link; const char *constraint; bool allows_mem, allows_reg, is_inout; enum gimplify_status ret, tret; gimple stmt; VEC(tree, gc) *inputs; VEC(tree, gc) *outputs; VEC(tree, gc) *clobbers; VEC(tree, gc) *labels; tree link_next; expr = *expr_p; noutputs = list_length (ASM_OUTPUTS (expr)); oconstraints = (const char **) alloca ((noutputs) * sizeof (const char *)); inputs = outputs = clobbers = labels = NULL; ret = GS_ALL_DONE; link_next = NULL_TREE; for (i = 0, link = ASM_OUTPUTS (expr); link; ++i, link = link_next) { bool ok; size_t constraint_len; link_next = TREE_CHAIN (link); oconstraints[i] = constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link))); constraint_len = strlen (constraint); if (constraint_len == 0) continue; ok = parse_output_constraint (&constraint, i, 0, 0, &allows_mem, &allows_reg, &is_inout); if (!ok) { ret = GS_ERROR; is_inout = false; } if (!allows_reg && allows_mem) mark_addressable (TREE_VALUE (link)); tret = gimplify_expr (&TREE_VALUE (link), pre_p, post_p, is_inout ? is_gimple_min_lval : is_gimple_lvalue, fb_lvalue | fb_mayfail); if (tret == GS_ERROR) { error ("invalid lvalue in asm output %d", i); ret = tret; } VEC_safe_push (tree, gc, outputs, link); TREE_CHAIN (link) = NULL_TREE; if (is_inout) { /* An input/output operand. To give the optimizers more flexibility, split it into separate input and output operands. */ tree input; char buf[10]; /* Turn the in/out constraint into an output constraint. */ char *p = xstrdup (constraint); p[0] = '='; TREE_VALUE (TREE_PURPOSE (link)) = build_string (constraint_len, p); /* And add a matching input constraint. */ if (allows_reg) { sprintf (buf, "%d", i); /* If there are multiple alternatives in the constraint, handle each of them individually. Those that allow register will be replaced with operand number, the others will stay unchanged. */ if (strchr (p, ',') != NULL) { size_t len = 0, buflen = strlen (buf); char *beg, *end, *str, *dst; for (beg = p + 1;;) { end = strchr (beg, ','); if (end == NULL) end = strchr (beg, '\0'); if ((size_t) (end - beg) < buflen) len += buflen + 1; else len += end - beg + 1; if (*end) beg = end + 1; else break; } str = (char *) alloca (len); for (beg = p + 1, dst = str;;) { const char *tem; bool mem_p, reg_p, inout_p; end = strchr (beg, ','); if (end) *end = '\0'; beg[-1] = '='; tem = beg - 1; parse_output_constraint (&tem, i, 0, 0, &mem_p, &reg_p, &inout_p); if (dst != str) *dst++ = ','; if (reg_p) { memcpy (dst, buf, buflen); dst += buflen; } else { if (end) len = end - beg; else len = strlen (beg); memcpy (dst, beg, len); dst += len; } if (end) beg = end + 1; else break; } *dst = '\0'; input = build_string (dst - str, str); } else input = build_string (strlen (buf), buf); } else input = build_string (constraint_len - 1, constraint + 1); free (p); input = build_tree_list (build_tree_list (NULL_TREE, input), unshare_expr (TREE_VALUE (link))); ASM_INPUTS (expr) = chainon (ASM_INPUTS (expr), input); } } link_next = NULL_TREE; for (link = ASM_INPUTS (expr); link; ++i, link = link_next) { link_next = TREE_CHAIN (link); constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link))); parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints, &allows_mem, &allows_reg); /* If we can't make copies, we can only accept memory. */ if (TREE_ADDRESSABLE (TREE_TYPE (TREE_VALUE (link)))) { if (allows_mem) allows_reg = 0; else { error ("impossible constraint in %<asm%>"); error ("non-memory input %d must stay in memory", i); return GS_ERROR; } } /* If the operand is a memory input, it should be an lvalue. */ if (!allows_reg && allows_mem) { tret = gimplify_expr (&TREE_VALUE (link), pre_p, post_p, is_gimple_lvalue, fb_lvalue | fb_mayfail); mark_addressable (TREE_VALUE (link)); if (tret == GS_ERROR) { if (EXPR_HAS_LOCATION (TREE_VALUE (link))) input_location = EXPR_LOCATION (TREE_VALUE (link)); error ("memory input %d is not directly addressable", i); ret = tret; } } else { tret = gimplify_expr (&TREE_VALUE (link), pre_p, post_p, is_gimple_asm_val, fb_rvalue); if (tret == GS_ERROR) ret = tret; } TREE_CHAIN (link) = NULL_TREE; VEC_safe_push (tree, gc, inputs, link); } for (link = ASM_CLOBBERS (expr); link; ++i, link = TREE_CHAIN (link)) VEC_safe_push (tree, gc, clobbers, link); for (link = ASM_LABELS (expr); link; ++i, link = TREE_CHAIN (link)) VEC_safe_push (tree, gc, labels, link); /* Do not add ASMs with errors to the gimple IL stream. */ if (ret != GS_ERROR) { stmt = gimple_build_asm_vec (TREE_STRING_POINTER (ASM_STRING (expr)), inputs, outputs, clobbers, labels); gimple_asm_set_volatile (stmt, ASM_VOLATILE_P (expr)); gimple_asm_set_input (stmt, ASM_INPUT_P (expr)); gimplify_seq_add_stmt (pre_p, stmt); } return ret; } /* Gimplify a CLEANUP_POINT_EXPR. Currently this works by adding GIMPLE_WITH_CLEANUP_EXPRs to the prequeue as we encounter cleanups while gimplifying the body, and converting them to TRY_FINALLY_EXPRs when we return to this function. FIXME should we complexify the prequeue handling instead? Or use flags for all the cleanups and let the optimizer tighten them up? The current code seems pretty fragile; it will break on a cleanup within any non-conditional nesting. But any such nesting would be broken, anyway; we can't write a TRY_FINALLY_EXPR that starts inside a nesting construct and continues out of it. We can do that at the RTL level, though, so having an optimizer to tighten up try/finally regions would be a Good Thing. */ static enum gimplify_status gimplify_cleanup_point_expr (tree *expr_p, gimple_seq *pre_p) { gimple_stmt_iterator iter; gimple_seq body_sequence = NULL; tree temp = voidify_wrapper_expr (*expr_p, NULL); /* We only care about the number of conditions between the innermost CLEANUP_POINT_EXPR and the cleanup. So save and reset the count and any cleanups collected outside the CLEANUP_POINT_EXPR. */ int old_conds = gimplify_ctxp->conditions; gimple_seq old_cleanups = gimplify_ctxp->conditional_cleanups; gimplify_ctxp->conditions = 0; gimplify_ctxp->conditional_cleanups = NULL; gimplify_stmt (&TREE_OPERAND (*expr_p, 0), &body_sequence); gimplify_ctxp->conditions = old_conds; gimplify_ctxp->conditional_cleanups = old_cleanups; for (iter = gsi_start (body_sequence); !gsi_end_p (iter); ) { gimple wce = gsi_stmt (iter); if (gimple_code (wce) == GIMPLE_WITH_CLEANUP_EXPR) { if (gsi_one_before_end_p (iter)) { /* Note that gsi_insert_seq_before and gsi_remove do not scan operands, unlike some other sequence mutators. */ gsi_insert_seq_before_without_update (&iter, gimple_wce_cleanup (wce), GSI_SAME_STMT); gsi_remove (&iter, true); break; } else { gimple gtry; gimple_seq seq; enum gimple_try_flags kind; if (gimple_wce_cleanup_eh_only (wce)) kind = GIMPLE_TRY_CATCH; else kind = GIMPLE_TRY_FINALLY; seq = gsi_split_seq_after (iter); gtry = gimple_build_try (seq, gimple_wce_cleanup (wce), kind); /* Do not use gsi_replace here, as it may scan operands. We want to do a simple structural modification only. */ *gsi_stmt_ptr (&iter) = gtry; iter = gsi_start (seq); } } else gsi_next (&iter); } gimplify_seq_add_seq (pre_p, body_sequence); if (temp) { *expr_p = temp; return GS_OK; } else { *expr_p = NULL; return GS_ALL_DONE; } } /* Insert a cleanup marker for gimplify_cleanup_point_expr. CLEANUP is the cleanup action required. EH_ONLY is true if the cleanup should only be executed if an exception is thrown, not on normal exit. */ static void gimple_push_cleanup (tree var, tree cleanup, bool eh_only, gimple_seq *pre_p) { gimple wce; gimple_seq cleanup_stmts = NULL; /* Errors can result in improperly nested cleanups. Which results in confusion when trying to resolve the GIMPLE_WITH_CLEANUP_EXPR. */ if (errorcount || sorrycount) return; if (gimple_conditional_context ()) { /* If we're in a conditional context, this is more complex. We only want to run the cleanup if we actually ran the initialization that necessitates it, but we want to run it after the end of the conditional context. So we wrap the try/finally around the condition and use a flag to determine whether or not to actually run the destructor. Thus test ? f(A()) : 0 becomes (approximately) flag = 0; try { if (test) { A::A(temp); flag = 1; val = f(temp); } else { val = 0; } } finally { if (flag) A::~A(temp); } val */ tree flag = create_tmp_var (boolean_type_node, "cleanup"); gimple ffalse = gimple_build_assign (flag, boolean_false_node); gimple ftrue = gimple_build_assign (flag, boolean_true_node); cleanup = build3 (COND_EXPR, void_type_node, flag, cleanup, NULL); gimplify_stmt (&cleanup, &cleanup_stmts); wce = gimple_build_wce (cleanup_stmts); gimplify_seq_add_stmt (&gimplify_ctxp->conditional_cleanups, ffalse); gimplify_seq_add_stmt (&gimplify_ctxp->conditional_cleanups, wce); gimplify_seq_add_stmt (pre_p, ftrue); /* Because of this manipulation, and the EH edges that jump threading cannot redirect, the temporary (VAR) will appear to be used uninitialized. Don't warn. */ TREE_NO_WARNING (var) = 1; } else { gimplify_stmt (&cleanup, &cleanup_stmts); wce = gimple_build_wce (cleanup_stmts); gimple_wce_set_cleanup_eh_only (wce, eh_only); gimplify_seq_add_stmt (pre_p, wce); } } /* Gimplify a TARGET_EXPR which doesn't appear on the rhs of an INIT_EXPR. */ static enum gimplify_status gimplify_target_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p) { tree targ = *expr_p; tree temp = TARGET_EXPR_SLOT (targ); tree init = TARGET_EXPR_INITIAL (targ); enum gimplify_status ret; if (init) { /* TARGET_EXPR temps aren't part of the enclosing block, so add it to the temps list. Handle also variable length TARGET_EXPRs. */ if (TREE_CODE (DECL_SIZE (temp)) != INTEGER_CST) { if (!TYPE_SIZES_GIMPLIFIED (TREE_TYPE (temp))) gimplify_type_sizes (TREE_TYPE (temp), pre_p); gimplify_vla_decl (temp, pre_p); } else gimple_add_tmp_var (temp); /* If TARGET_EXPR_INITIAL is void, then the mere evaluation of the expression is supposed to initialize the slot. */ if (VOID_TYPE_P (TREE_TYPE (init))) ret = gimplify_expr (&init, pre_p, post_p, is_gimple_stmt, fb_none); else { tree init_expr = build2 (INIT_EXPR, void_type_node, temp, init); init = init_expr; ret = gimplify_expr (&init, pre_p, post_p, is_gimple_stmt, fb_none); init = NULL; ggc_free (init_expr); } if (ret == GS_ERROR) { /* PR c++/28266 Make sure this is expanded only once. */ TARGET_EXPR_INITIAL (targ) = NULL_TREE; return GS_ERROR; } if (init) gimplify_and_add (init, pre_p); /* If needed, push the cleanup for the temp. */ if (TARGET_EXPR_CLEANUP (targ)) gimple_push_cleanup (temp, TARGET_EXPR_CLEANUP (targ), CLEANUP_EH_ONLY (targ), pre_p); /* Only expand this once. */ TREE_OPERAND (targ, 3) = init; TARGET_EXPR_INITIAL (targ) = NULL_TREE; } else /* We should have expanded this before. */ gcc_assert (DECL_SEEN_IN_BIND_EXPR_P (temp)); *expr_p = temp; return GS_OK; } /* Gimplification of expression trees. */ /* Gimplify an expression which appears at statement context. The corresponding GIMPLE statements are added to *SEQ_P. If *SEQ_P is NULL, a new sequence is allocated. Return true if we actually added a statement to the queue. */ bool gimplify_stmt (tree *stmt_p, gimple_seq *seq_p) { gimple_seq_node last; if (!*seq_p) *seq_p = gimple_seq_alloc (); last = gimple_seq_last (*seq_p); gimplify_expr (stmt_p, seq_p, NULL, is_gimple_stmt, fb_none); return last != gimple_seq_last (*seq_p); } /* Add FIRSTPRIVATE entries for DECL in the OpenMP the surrounding parallels to CTX. If entries already exist, force them to be some flavor of private. If there is no enclosing parallel, do nothing. */ void omp_firstprivatize_variable (struct gimplify_omp_ctx *ctx, tree decl) { splay_tree_node n; if (decl == NULL || !DECL_P (decl)) return; do { n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl); if (n != NULL) { if (n->value & GOVD_SHARED) n->value = GOVD_FIRSTPRIVATE | (n->value & GOVD_SEEN); else return; } else if (ctx->region_type != ORT_WORKSHARE) omp_add_variable (ctx, decl, GOVD_FIRSTPRIVATE); ctx = ctx->outer_context; } while (ctx); } /* Similarly for each of the type sizes of TYPE. */ static void omp_firstprivatize_type_sizes (struct gimplify_omp_ctx *ctx, tree type) { if (type == NULL || type == error_mark_node) return; type = TYPE_MAIN_VARIANT (type); if (pointer_set_insert (ctx->privatized_types, type)) return; switch (TREE_CODE (type)) { case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE: case REAL_TYPE: case FIXED_POINT_TYPE: omp_firstprivatize_variable (ctx, TYPE_MIN_VALUE (type)); omp_firstprivatize_variable (ctx, TYPE_MAX_VALUE (type)); break; case ARRAY_TYPE: omp_firstprivatize_type_sizes (ctx, TREE_TYPE (type)); omp_firstprivatize_type_sizes (ctx, TYPE_DOMAIN (type)); break; case RECORD_TYPE: case UNION_TYPE: case QUAL_UNION_TYPE: { tree field; for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field)) if (TREE_CODE (field) == FIELD_DECL) { omp_firstprivatize_variable (ctx, DECL_FIELD_OFFSET (field)); omp_firstprivatize_type_sizes (ctx, TREE_TYPE (field)); } } break; case POINTER_TYPE: case REFERENCE_TYPE: omp_firstprivatize_type_sizes (ctx, TREE_TYPE (type)); break; default: break; } omp_firstprivatize_variable (ctx, TYPE_SIZE (type)); omp_firstprivatize_variable (ctx, TYPE_SIZE_UNIT (type)); lang_hooks.types.omp_firstprivatize_type_sizes (ctx, type); } /* Add an entry for DECL in the OpenMP context CTX with FLAGS. */ static void omp_add_variable (struct gimplify_omp_ctx *ctx, tree decl, unsigned int flags) { splay_tree_node n; unsigned int nflags; tree t; if (decl == error_mark_node || TREE_TYPE (decl) == error_mark_node) return; /* Never elide decls whose type has TREE_ADDRESSABLE set. This means there are constructors involved somewhere. */ if (TREE_ADDRESSABLE (TREE_TYPE (decl)) || TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl))) flags |= GOVD_SEEN; n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl); if (n != NULL) { /* We shouldn't be re-adding the decl with the same data sharing class. */ gcc_assert ((n->value & GOVD_DATA_SHARE_CLASS & flags) == 0); /* The only combination of data sharing classes we should see is FIRSTPRIVATE and LASTPRIVATE. */ nflags = n->value | flags; gcc_assert ((nflags & GOVD_DATA_SHARE_CLASS) == (GOVD_FIRSTPRIVATE | GOVD_LASTPRIVATE)); n->value = nflags; return; } /* When adding a variable-sized variable, we have to handle all sorts of additional bits of data: the pointer replacement variable, and the parameters of the type. */ if (DECL_SIZE (decl) && TREE_CODE (DECL_SIZE (decl)) != INTEGER_CST) { /* Add the pointer replacement variable as PRIVATE if the variable replacement is private, else FIRSTPRIVATE since we'll need the address of the original variable either for SHARED, or for the copy into or out of the context. */ if (!(flags & GOVD_LOCAL)) { nflags = flags & GOVD_PRIVATE ? GOVD_PRIVATE : GOVD_FIRSTPRIVATE; nflags |= flags & GOVD_SEEN; t = DECL_VALUE_EXPR (decl); gcc_assert (TREE_CODE (t) == INDIRECT_REF); t = TREE_OPERAND (t, 0); gcc_assert (DECL_P (t)); omp_add_variable (ctx, t, nflags); } /* Add all of the variable and type parameters (which should have been gimplified to a formal temporary) as FIRSTPRIVATE. */ omp_firstprivatize_variable (ctx, DECL_SIZE_UNIT (decl)); omp_firstprivatize_variable (ctx, DECL_SIZE (decl)); omp_firstprivatize_type_sizes (ctx, TREE_TYPE (decl)); /* The variable-sized variable itself is never SHARED, only some form of PRIVATE. The sharing would take place via the pointer variable which we remapped above. */ if (flags & GOVD_SHARED) flags = GOVD_PRIVATE | GOVD_DEBUG_PRIVATE | (flags & (GOVD_SEEN | GOVD_EXPLICIT)); /* We're going to make use of the TYPE_SIZE_UNIT at least in the alloca statement we generate for the variable, so make sure it is available. This isn't automatically needed for the SHARED case, since we won't be allocating local storage then. For local variables TYPE_SIZE_UNIT might not be gimplified yet, in this case omp_notice_variable will be called later on when it is gimplified. */ else if (! (flags & GOVD_LOCAL)) omp_notice_variable (ctx, TYPE_SIZE_UNIT (TREE_TYPE (decl)), true); } else if (lang_hooks.decls.omp_privatize_by_reference (decl)) { gcc_assert ((flags & GOVD_LOCAL) == 0); omp_firstprivatize_type_sizes (ctx, TREE_TYPE (decl)); /* Similar to the direct variable sized case above, we'll need the size of references being privatized. */ if ((flags & GOVD_SHARED) == 0) { t = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (decl))); if (TREE_CODE (t) != INTEGER_CST) omp_notice_variable (ctx, t, true); } } splay_tree_insert (ctx->variables, (splay_tree_key)decl, flags); } /* Notice a threadprivate variable DECL used in OpenMP context CTX. This just prints out diagnostics about threadprivate variable uses in untied tasks. If DECL2 is non-NULL, prevent this warning on that variable. */ static bool omp_notice_threadprivate_variable (struct gimplify_omp_ctx *ctx, tree decl, tree decl2) { splay_tree_node n; if (ctx->region_type != ORT_UNTIED_TASK) return false; n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl); if (n == NULL) { error ("threadprivate variable %qE used in untied task", DECL_NAME (decl)); error_at (ctx->location, "enclosing task"); splay_tree_insert (ctx->variables, (splay_tree_key)decl, 0); } if (decl2) splay_tree_insert (ctx->variables, (splay_tree_key)decl2, 0); return false; } /* Record the fact that DECL was used within the OpenMP context CTX. IN_CODE is true when real code uses DECL, and false when we should merely emit default(none) errors. Return true if DECL is going to be remapped and thus DECL shouldn't be gimplified into its DECL_VALUE_EXPR (if any). */ static bool omp_notice_variable (struct gimplify_omp_ctx *ctx, tree decl, bool in_code) { splay_tree_node n; unsigned flags = in_code ? GOVD_SEEN : 0; bool ret = false, shared; if (decl == error_mark_node || TREE_TYPE (decl) == error_mark_node) return false; /* Threadprivate variables are predetermined. */ if (is_global_var (decl)) { if (DECL_THREAD_LOCAL_P (decl)) return omp_notice_threadprivate_variable (ctx, decl, NULL_TREE); if (DECL_HAS_VALUE_EXPR_P (decl)) { tree value = get_base_address (DECL_VALUE_EXPR (decl)); if (value && DECL_P (value) && DECL_THREAD_LOCAL_P (value)) return omp_notice_threadprivate_variable (ctx, decl, value); } } n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl); if (n == NULL) { enum omp_clause_default_kind default_kind, kind; struct gimplify_omp_ctx *octx; if (ctx->region_type == ORT_WORKSHARE) goto do_outer; /* ??? Some compiler-generated variables (like SAVE_EXPRs) could be remapped firstprivate instead of shared. To some extent this is addressed in omp_firstprivatize_type_sizes, but not effectively. */ default_kind = ctx->default_kind; kind = lang_hooks.decls.omp_predetermined_sharing (decl); if (kind != OMP_CLAUSE_DEFAULT_UNSPECIFIED) default_kind = kind; switch (default_kind) { case OMP_CLAUSE_DEFAULT_NONE: error ("%qE not specified in enclosing parallel", DECL_NAME (lang_hooks.decls.omp_report_decl (decl))); if ((ctx->region_type & ORT_TASK) != 0) error_at (ctx->location, "enclosing task"); else error_at (ctx->location, "enclosing parallel"); /* FALLTHRU */ case OMP_CLAUSE_DEFAULT_SHARED: flags |= GOVD_SHARED; break; case OMP_CLAUSE_DEFAULT_PRIVATE: flags |= GOVD_PRIVATE; break; case OMP_CLAUSE_DEFAULT_FIRSTPRIVATE: flags |= GOVD_FIRSTPRIVATE; break; case OMP_CLAUSE_DEFAULT_UNSPECIFIED: /* decl will be either GOVD_FIRSTPRIVATE or GOVD_SHARED. */ gcc_assert ((ctx->region_type & ORT_TASK) != 0); if (ctx->outer_context) omp_notice_variable (ctx->outer_context, decl, in_code); for (octx = ctx->outer_context; octx; octx = octx->outer_context) { splay_tree_node n2; n2 = splay_tree_lookup (octx->variables, (splay_tree_key) decl); if (n2 && (n2->value & GOVD_DATA_SHARE_CLASS) != GOVD_SHARED) { flags |= GOVD_FIRSTPRIVATE; break; } if ((octx->region_type & ORT_PARALLEL) != 0) break; } if (flags & GOVD_FIRSTPRIVATE) break; if (octx == NULL && (TREE_CODE (decl) == PARM_DECL || (!is_global_var (decl) && DECL_CONTEXT (decl) == current_function_decl))) { flags |= GOVD_FIRSTPRIVATE; break; } flags |= GOVD_SHARED; break; default: gcc_unreachable (); } if ((flags & GOVD_PRIVATE) && lang_hooks.decls.omp_private_outer_ref (decl)) flags |= GOVD_PRIVATE_OUTER_REF; omp_add_variable (ctx, decl, flags); shared = (flags & GOVD_SHARED) != 0; ret = lang_hooks.decls.omp_disregard_value_expr (decl, shared); goto do_outer; } if ((n->value & (GOVD_SEEN | GOVD_LOCAL)) == 0 && (flags & (GOVD_SEEN | GOVD_LOCAL)) == GOVD_SEEN && DECL_SIZE (decl) && TREE_CODE (DECL_SIZE (decl)) != INTEGER_CST) { splay_tree_node n2; tree t = DECL_VALUE_EXPR (decl); gcc_assert (TREE_CODE (t) == INDIRECT_REF); t = TREE_OPERAND (t, 0); gcc_assert (DECL_P (t)); n2 = splay_tree_lookup (ctx->variables, (splay_tree_key) t); n2->value |= GOVD_SEEN; } shared = ((flags | n->value) & GOVD_SHARED) != 0; ret = lang_hooks.decls.omp_disregard_value_expr (decl, shared); /* If nothing changed, there's nothing left to do. */ if ((n->value & flags) == flags) return ret; flags |= n->value; n->value = flags; do_outer: /* If the variable is private in the current context, then we don't need to propagate anything to an outer context. */ if ((flags & GOVD_PRIVATE) && !(flags & GOVD_PRIVATE_OUTER_REF)) return ret; if (ctx->outer_context && omp_notice_variable (ctx->outer_context, decl, in_code)) return true; return ret; } /* Verify that DECL is private within CTX. If there's specific information to the contrary in the innermost scope, generate an error. */ static bool omp_is_private (struct gimplify_omp_ctx *ctx, tree decl) { splay_tree_node n; n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl); if (n != NULL) { if (n->value & GOVD_SHARED) { if (ctx == gimplify_omp_ctxp) { error ("iteration variable %qE should be private", DECL_NAME (decl)); n->value = GOVD_PRIVATE; return true; } else return false; } else if ((n->value & GOVD_EXPLICIT) != 0 && (ctx == gimplify_omp_ctxp || (ctx->region_type == ORT_COMBINED_PARALLEL && gimplify_omp_ctxp->outer_context == ctx))) { if ((n->value & GOVD_FIRSTPRIVATE) != 0) error ("iteration variable %qE should not be firstprivate", DECL_NAME (decl)); else if ((n->value & GOVD_REDUCTION) != 0) error ("iteration variable %qE should not be reduction", DECL_NAME (decl)); } return (ctx == gimplify_omp_ctxp || (ctx->region_type == ORT_COMBINED_PARALLEL && gimplify_omp_ctxp->outer_context == ctx)); } if (ctx->region_type != ORT_WORKSHARE) return false; else if (ctx->outer_context) return omp_is_private (ctx->outer_context, decl); return false; } /* Return true if DECL is private within a parallel region that binds to the current construct's context or in parallel region's REDUCTION clause. */ static bool omp_check_private (struct gimplify_omp_ctx *ctx, tree decl) { splay_tree_node n; do { ctx = ctx->outer_context; if (ctx == NULL) return !(is_global_var (decl) /* References might be private, but might be shared too. */ || lang_hooks.decls.omp_privatize_by_reference (decl)); n = splay_tree_lookup (ctx->variables, (splay_tree_key) decl); if (n != NULL) return (n->value & GOVD_SHARED) == 0; } while (ctx->region_type == ORT_WORKSHARE); return false; } /* Scan the OpenMP clauses in *LIST_P, installing mappings into a new and previous omp contexts. */ static void gimplify_scan_omp_clauses (tree *list_p, gimple_seq *pre_p, enum omp_region_type region_type) { struct gimplify_omp_ctx *ctx, *outer_ctx; struct gimplify_ctx gctx; tree c; ctx = new_omp_context (region_type); outer_ctx = ctx->outer_context; while ((c = *list_p) != NULL) { bool remove = false; bool notice_outer = true; const char *check_non_private = NULL; unsigned int flags; tree decl; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_PRIVATE: flags = GOVD_PRIVATE | GOVD_EXPLICIT; if (lang_hooks.decls.omp_private_outer_ref (OMP_CLAUSE_DECL (c))) { flags |= GOVD_PRIVATE_OUTER_REF; OMP_CLAUSE_PRIVATE_OUTER_REF (c) = 1; } else notice_outer = false; goto do_add; case OMP_CLAUSE_SHARED: flags = GOVD_SHARED | GOVD_EXPLICIT; goto do_add; case OMP_CLAUSE_FIRSTPRIVATE: flags = GOVD_FIRSTPRIVATE | GOVD_EXPLICIT; check_non_private = "firstprivate"; goto do_add; case OMP_CLAUSE_LASTPRIVATE: flags = GOVD_LASTPRIVATE | GOVD_SEEN | GOVD_EXPLICIT; check_non_private = "lastprivate"; goto do_add; case OMP_CLAUSE_REDUCTION: flags = GOVD_REDUCTION | GOVD_SEEN | GOVD_EXPLICIT; check_non_private = "reduction"; goto do_add; do_add: decl = OMP_CLAUSE_DECL (c); if (decl == error_mark_node || TREE_TYPE (decl) == error_mark_node) { remove = true; break; } omp_add_variable (ctx, decl, flags); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION && OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { omp_add_variable (ctx, OMP_CLAUSE_REDUCTION_PLACEHOLDER (c), GOVD_LOCAL | GOVD_SEEN); gimplify_omp_ctxp = ctx; push_gimplify_context (&gctx); OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c) = gimple_seq_alloc (); OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c) = gimple_seq_alloc (); gimplify_and_add (OMP_CLAUSE_REDUCTION_INIT (c), &OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c)); pop_gimplify_context (gimple_seq_first_stmt (OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c))); push_gimplify_context (&gctx); gimplify_and_add (OMP_CLAUSE_REDUCTION_MERGE (c), &OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c)); pop_gimplify_context (gimple_seq_first_stmt (OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c))); OMP_CLAUSE_REDUCTION_INIT (c) = NULL_TREE; OMP_CLAUSE_REDUCTION_MERGE (c) = NULL_TREE; gimplify_omp_ctxp = outer_ctx; } else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE && OMP_CLAUSE_LASTPRIVATE_STMT (c)) { gimplify_omp_ctxp = ctx; push_gimplify_context (&gctx); if (TREE_CODE (OMP_CLAUSE_LASTPRIVATE_STMT (c)) != BIND_EXPR) { tree bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL); TREE_SIDE_EFFECTS (bind) = 1; BIND_EXPR_BODY (bind) = OMP_CLAUSE_LASTPRIVATE_STMT (c); OMP_CLAUSE_LASTPRIVATE_STMT (c) = bind; } gimplify_and_add (OMP_CLAUSE_LASTPRIVATE_STMT (c), &OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c)); pop_gimplify_context (gimple_seq_first_stmt (OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c))); OMP_CLAUSE_LASTPRIVATE_STMT (c) = NULL_TREE; gimplify_omp_ctxp = outer_ctx; } if (notice_outer) goto do_notice; break; case OMP_CLAUSE_COPYIN: case OMP_CLAUSE_COPYPRIVATE: decl = OMP_CLAUSE_DECL (c); if (decl == error_mark_node || TREE_TYPE (decl) == error_mark_node) { remove = true; break; } do_notice: if (outer_ctx) omp_notice_variable (outer_ctx, decl, true); if (check_non_private && region_type == ORT_WORKSHARE && omp_check_private (ctx, decl)) { error ("%s variable %qE is private in outer context", check_non_private, DECL_NAME (decl)); remove = true; } break; case OMP_CLAUSE_IF: OMP_CLAUSE_OPERAND (c, 0) = gimple_boolify (OMP_CLAUSE_OPERAND (c, 0)); /* Fall through. */ case OMP_CLAUSE_SCHEDULE: case OMP_CLAUSE_NUM_THREADS: if (gimplify_expr (&OMP_CLAUSE_OPERAND (c, 0), pre_p, NULL, is_gimple_val, fb_rvalue) == GS_ERROR) remove = true; break; case OMP_CLAUSE_NOWAIT: case OMP_CLAUSE_ORDERED: case OMP_CLAUSE_UNTIED: case OMP_CLAUSE_COLLAPSE: break; case OMP_CLAUSE_DEFAULT: ctx->default_kind = OMP_CLAUSE_DEFAULT_KIND (c); break; default: gcc_unreachable (); } if (remove) *list_p = OMP_CLAUSE_CHAIN (c); else list_p = &OMP_CLAUSE_CHAIN (c); } gimplify_omp_ctxp = ctx; } /* For all variables that were not actually used within the context, remove PRIVATE, SHARED, and FIRSTPRIVATE clauses. */ static int gimplify_adjust_omp_clauses_1 (splay_tree_node n, void *data) { tree *list_p = (tree *) data; tree decl = (tree) n->key; unsigned flags = n->value; enum omp_clause_code code; tree clause; bool private_debug; if (flags & (GOVD_EXPLICIT | GOVD_LOCAL)) return 0; if ((flags & GOVD_SEEN) == 0) return 0; if (flags & GOVD_DEBUG_PRIVATE) { gcc_assert ((flags & GOVD_DATA_SHARE_CLASS) == GOVD_PRIVATE); private_debug = true; } else private_debug = lang_hooks.decls.omp_private_debug_clause (decl, !!(flags & GOVD_SHARED)); if (private_debug) code = OMP_CLAUSE_PRIVATE; else if (flags & GOVD_SHARED) { if (is_global_var (decl)) { struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp->outer_context; while (ctx != NULL) { splay_tree_node on = splay_tree_lookup (ctx->variables, (splay_tree_key) decl); if (on && (on->value & (GOVD_FIRSTPRIVATE | GOVD_LASTPRIVATE | GOVD_PRIVATE | GOVD_REDUCTION)) != 0) break; ctx = ctx->outer_context; } if (ctx == NULL) return 0; } code = OMP_CLAUSE_SHARED; } else if (flags & GOVD_PRIVATE) code = OMP_CLAUSE_PRIVATE; else if (flags & GOVD_FIRSTPRIVATE) code = OMP_CLAUSE_FIRSTPRIVATE; else gcc_unreachable (); clause = build_omp_clause (input_location, code); OMP_CLAUSE_DECL (clause) = decl; OMP_CLAUSE_CHAIN (clause) = *list_p; if (private_debug) OMP_CLAUSE_PRIVATE_DEBUG (clause) = 1; else if (code == OMP_CLAUSE_PRIVATE && (flags & GOVD_PRIVATE_OUTER_REF)) OMP_CLAUSE_PRIVATE_OUTER_REF (clause) = 1; *list_p = clause; lang_hooks.decls.omp_finish_clause (clause); return 0; } static void gimplify_adjust_omp_clauses (tree *list_p) { struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp; tree c, decl; while ((c = *list_p) != NULL) { splay_tree_node n; bool remove = false; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_PRIVATE: case OMP_CLAUSE_SHARED: case OMP_CLAUSE_FIRSTPRIVATE: decl = OMP_CLAUSE_DECL (c); n = splay_tree_lookup (ctx->variables, (splay_tree_key) decl); remove = !(n->value & GOVD_SEEN); if (! remove) { bool shared = OMP_CLAUSE_CODE (c) == OMP_CLAUSE_SHARED; if ((n->value & GOVD_DEBUG_PRIVATE) || lang_hooks.decls.omp_private_debug_clause (decl, shared)) { gcc_assert ((n->value & GOVD_DEBUG_PRIVATE) == 0 || ((n->value & GOVD_DATA_SHARE_CLASS) == GOVD_PRIVATE)); OMP_CLAUSE_SET_CODE (c, OMP_CLAUSE_PRIVATE); OMP_CLAUSE_PRIVATE_DEBUG (c) = 1; } } break; case OMP_CLAUSE_LASTPRIVATE: /* Make sure OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE is set to accurately reflect the presence of a FIRSTPRIVATE clause. */ decl = OMP_CLAUSE_DECL (c); n = splay_tree_lookup (ctx->variables, (splay_tree_key) decl); OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c) = (n->value & GOVD_FIRSTPRIVATE) != 0; break; case OMP_CLAUSE_REDUCTION: case OMP_CLAUSE_COPYIN: case OMP_CLAUSE_COPYPRIVATE: case OMP_CLAUSE_IF: case OMP_CLAUSE_NUM_THREADS: case OMP_CLAUSE_SCHEDULE: case OMP_CLAUSE_NOWAIT: case OMP_CLAUSE_ORDERED: case OMP_CLAUSE_DEFAULT: case OMP_CLAUSE_UNTIED: case OMP_CLAUSE_COLLAPSE: break; default: gcc_unreachable (); } if (remove) *list_p = OMP_CLAUSE_CHAIN (c); else list_p = &OMP_CLAUSE_CHAIN (c); } /* Add in any implicit data sharing. */ splay_tree_foreach (ctx->variables, gimplify_adjust_omp_clauses_1, list_p); gimplify_omp_ctxp = ctx->outer_context; delete_omp_context (ctx); } /* Gimplify the contents of an OMP_PARALLEL statement. This involves gimplification of the body, as well as scanning the body for used variables. We need to do this scan now, because variable-sized decls will be decomposed during gimplification. */ static void gimplify_omp_parallel (tree *expr_p, gimple_seq *pre_p) { tree expr = *expr_p; gimple g; gimple_seq body = NULL; struct gimplify_ctx gctx; gimplify_scan_omp_clauses (&OMP_PARALLEL_CLAUSES (expr), pre_p, OMP_PARALLEL_COMBINED (expr) ? ORT_COMBINED_PARALLEL : ORT_PARALLEL); push_gimplify_context (&gctx); g = gimplify_and_return_first (OMP_PARALLEL_BODY (expr), &body); if (gimple_code (g) == GIMPLE_BIND) pop_gimplify_context (g); else pop_gimplify_context (NULL); gimplify_adjust_omp_clauses (&OMP_PARALLEL_CLAUSES (expr)); g = gimple_build_omp_parallel (body, OMP_PARALLEL_CLAUSES (expr), NULL_TREE, NULL_TREE); if (OMP_PARALLEL_COMBINED (expr)) gimple_omp_set_subcode (g, GF_OMP_PARALLEL_COMBINED); gimplify_seq_add_stmt (pre_p, g); *expr_p = NULL_TREE; } /* Gimplify the contents of an OMP_TASK statement. This involves gimplification of the body, as well as scanning the body for used variables. We need to do this scan now, because variable-sized decls will be decomposed during gimplification. */ static void gimplify_omp_task (tree *expr_p, gimple_seq *pre_p) { tree expr = *expr_p; gimple g; gimple_seq body = NULL; struct gimplify_ctx gctx; gimplify_scan_omp_clauses (&OMP_TASK_CLAUSES (expr), pre_p, find_omp_clause (OMP_TASK_CLAUSES (expr), OMP_CLAUSE_UNTIED) ? ORT_UNTIED_TASK : ORT_TASK); push_gimplify_context (&gctx); g = gimplify_and_return_first (OMP_TASK_BODY (expr), &body); if (gimple_code (g) == GIMPLE_BIND) pop_gimplify_context (g); else pop_gimplify_context (NULL); gimplify_adjust_omp_clauses (&OMP_TASK_CLAUSES (expr)); g = gimple_build_omp_task (body, OMP_TASK_CLAUSES (expr), NULL_TREE, NULL_TREE, NULL_TREE, NULL_TREE, NULL_TREE); gimplify_seq_add_stmt (pre_p, g); *expr_p = NULL_TREE; } /* Gimplify the gross structure of an OMP_FOR statement. */ static enum gimplify_status gimplify_omp_for (tree *expr_p, gimple_seq *pre_p) { tree for_stmt, decl, var, t; enum gimplify_status ret = GS_ALL_DONE; enum gimplify_status tret; gimple gfor; gimple_seq for_body, for_pre_body; int i; for_stmt = *expr_p; gimplify_scan_omp_clauses (&OMP_FOR_CLAUSES (for_stmt), pre_p, ORT_WORKSHARE); /* Handle OMP_FOR_INIT. */ for_pre_body = NULL; gimplify_and_add (OMP_FOR_PRE_BODY (for_stmt), &for_pre_body); OMP_FOR_PRE_BODY (for_stmt) = NULL_TREE; for_body = gimple_seq_alloc (); gcc_assert (TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)) == TREE_VEC_LENGTH (OMP_FOR_COND (for_stmt))); gcc_assert (TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)) == TREE_VEC_LENGTH (OMP_FOR_INCR (for_stmt))); for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)); i++) { t = TREE_VEC_ELT (OMP_FOR_INIT (for_stmt), i); gcc_assert (TREE_CODE (t) == MODIFY_EXPR); decl = TREE_OPERAND (t, 0); gcc_assert (DECL_P (decl)); gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (decl)) || POINTER_TYPE_P (TREE_TYPE (decl))); /* Make sure the iteration variable is private. */ if (omp_is_private (gimplify_omp_ctxp, decl)) omp_notice_variable (gimplify_omp_ctxp, decl, true); else omp_add_variable (gimplify_omp_ctxp, decl, GOVD_PRIVATE | GOVD_SEEN); /* If DECL is not a gimple register, create a temporary variable to act as an iteration counter. This is valid, since DECL cannot be modified in the body of the loop. */ if (!is_gimple_reg (decl)) { var = create_tmp_var (TREE_TYPE (decl), get_name (decl)); TREE_OPERAND (t, 0) = var; gimplify_seq_add_stmt (&for_body, gimple_build_assign (decl, var)); omp_add_variable (gimplify_omp_ctxp, var, GOVD_PRIVATE | GOVD_SEEN); } else var = decl; tret = gimplify_expr (&TREE_OPERAND (t, 1), &for_pre_body, NULL, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); if (ret == GS_ERROR) return ret; /* Handle OMP_FOR_COND. */ t = TREE_VEC_ELT (OMP_FOR_COND (for_stmt), i); gcc_assert (COMPARISON_CLASS_P (t)); gcc_assert (TREE_OPERAND (t, 0) == decl); tret = gimplify_expr (&TREE_OPERAND (t, 1), &for_pre_body, NULL, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); /* Handle OMP_FOR_INCR. */ t = TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i); switch (TREE_CODE (t)) { case PREINCREMENT_EXPR: case POSTINCREMENT_EXPR: t = build_int_cst (TREE_TYPE (decl), 1); t = build2 (PLUS_EXPR, TREE_TYPE (decl), var, t); t = build2 (MODIFY_EXPR, TREE_TYPE (var), var, t); TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i) = t; break; case PREDECREMENT_EXPR: case POSTDECREMENT_EXPR: t = build_int_cst (TREE_TYPE (decl), -1); t = build2 (PLUS_EXPR, TREE_TYPE (decl), var, t); t = build2 (MODIFY_EXPR, TREE_TYPE (var), var, t); TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i) = t; break; case MODIFY_EXPR: gcc_assert (TREE_OPERAND (t, 0) == decl); TREE_OPERAND (t, 0) = var; t = TREE_OPERAND (t, 1); switch (TREE_CODE (t)) { case PLUS_EXPR: if (TREE_OPERAND (t, 1) == decl) { TREE_OPERAND (t, 1) = TREE_OPERAND (t, 0); TREE_OPERAND (t, 0) = var; break; } /* Fallthru. */ case MINUS_EXPR: case POINTER_PLUS_EXPR: gcc_assert (TREE_OPERAND (t, 0) == decl); TREE_OPERAND (t, 0) = var; break; default: gcc_unreachable (); } tret = gimplify_expr (&TREE_OPERAND (t, 1), &for_pre_body, NULL, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); break; default: gcc_unreachable (); } if (var != decl || TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)) > 1) { tree c; for (c = OMP_FOR_CLAUSES (for_stmt); c ; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE && OMP_CLAUSE_DECL (c) == decl && OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c) == NULL) { t = TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i); gcc_assert (TREE_CODE (t) == MODIFY_EXPR); gcc_assert (TREE_OPERAND (t, 0) == var); t = TREE_OPERAND (t, 1); gcc_assert (TREE_CODE (t) == PLUS_EXPR || TREE_CODE (t) == MINUS_EXPR || TREE_CODE (t) == POINTER_PLUS_EXPR); gcc_assert (TREE_OPERAND (t, 0) == var); t = build2 (TREE_CODE (t), TREE_TYPE (decl), decl, TREE_OPERAND (t, 1)); gimplify_assign (decl, t, &OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c)); } } } gimplify_and_add (OMP_FOR_BODY (for_stmt), &for_body); gimplify_adjust_omp_clauses (&OMP_FOR_CLAUSES (for_stmt)); gfor = gimple_build_omp_for (for_body, OMP_FOR_CLAUSES (for_stmt), TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)), for_pre_body); for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)); i++) { t = TREE_VEC_ELT (OMP_FOR_INIT (for_stmt), i); gimple_omp_for_set_index (gfor, i, TREE_OPERAND (t, 0)); gimple_omp_for_set_initial (gfor, i, TREE_OPERAND (t, 1)); t = TREE_VEC_ELT (OMP_FOR_COND (for_stmt), i); gimple_omp_for_set_cond (gfor, i, TREE_CODE (t)); gimple_omp_for_set_final (gfor, i, TREE_OPERAND (t, 1)); t = TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i); gimple_omp_for_set_incr (gfor, i, TREE_OPERAND (t, 1)); } gimplify_seq_add_stmt (pre_p, gfor); return ret == GS_ALL_DONE ? GS_ALL_DONE : GS_ERROR; } /* Gimplify the gross structure of other OpenMP worksharing constructs. In particular, OMP_SECTIONS and OMP_SINGLE. */ static void gimplify_omp_workshare (tree *expr_p, gimple_seq *pre_p) { tree expr = *expr_p; gimple stmt; gimple_seq body = NULL; gimplify_scan_omp_clauses (&OMP_CLAUSES (expr), pre_p, ORT_WORKSHARE); gimplify_and_add (OMP_BODY (expr), &body); gimplify_adjust_omp_clauses (&OMP_CLAUSES (expr)); if (TREE_CODE (expr) == OMP_SECTIONS) stmt = gimple_build_omp_sections (body, OMP_CLAUSES (expr)); else if (TREE_CODE (expr) == OMP_SINGLE) stmt = gimple_build_omp_single (body, OMP_CLAUSES (expr)); else gcc_unreachable (); gimplify_seq_add_stmt (pre_p, stmt); } /* A subroutine of gimplify_omp_atomic. The front end is supposed to have stabilized the lhs of the atomic operation as *ADDR. Return true if EXPR is this stabilized form. */ static bool goa_lhs_expr_p (tree expr, tree addr) { /* Also include casts to other type variants. The C front end is fond of adding these for e.g. volatile variables. This is like STRIP_TYPE_NOPS but includes the main variant lookup. */ STRIP_USELESS_TYPE_CONVERSION (expr); if (TREE_CODE (expr) == INDIRECT_REF) { expr = TREE_OPERAND (expr, 0); while (expr != addr && (CONVERT_EXPR_P (expr) || TREE_CODE (expr) == NON_LVALUE_EXPR) && TREE_CODE (expr) == TREE_CODE (addr) && types_compatible_p (TREE_TYPE (expr), TREE_TYPE (addr))) { expr = TREE_OPERAND (expr, 0); addr = TREE_OPERAND (addr, 0); } if (expr == addr) return true; return (TREE_CODE (addr) == ADDR_EXPR && TREE_CODE (expr) == ADDR_EXPR && TREE_OPERAND (addr, 0) == TREE_OPERAND (expr, 0)); } if (TREE_CODE (addr) == ADDR_EXPR && expr == TREE_OPERAND (addr, 0)) return true; return false; } /* Walk *EXPR_P and replace appearances of *LHS_ADDR with LHS_VAR. If an expression does not involve the lhs, evaluate it into a temporary. Return 1 if the lhs appeared as a subexpression, 0 if it did not, or -1 if an error was encountered. */ static int goa_stabilize_expr (tree *expr_p, gimple_seq *pre_p, tree lhs_addr, tree lhs_var) { tree expr = *expr_p; int saw_lhs; if (goa_lhs_expr_p (expr, lhs_addr)) { *expr_p = lhs_var; return 1; } if (is_gimple_val (expr)) return 0; saw_lhs = 0; switch (TREE_CODE_CLASS (TREE_CODE (expr))) { case tcc_binary: case tcc_comparison: saw_lhs |= goa_stabilize_expr (&TREE_OPERAND (expr, 1), pre_p, lhs_addr, lhs_var); case tcc_unary: saw_lhs |= goa_stabilize_expr (&TREE_OPERAND (expr, 0), pre_p, lhs_addr, lhs_var); break; case tcc_expression: switch (TREE_CODE (expr)) { case TRUTH_ANDIF_EXPR: case TRUTH_ORIF_EXPR: saw_lhs |= goa_stabilize_expr (&TREE_OPERAND (expr, 1), pre_p, lhs_addr, lhs_var); saw_lhs |= goa_stabilize_expr (&TREE_OPERAND (expr, 0), pre_p, lhs_addr, lhs_var); break; default: break; } break; default: break; } if (saw_lhs == 0) { enum gimplify_status gs; gs = gimplify_expr (expr_p, pre_p, NULL, is_gimple_val, fb_rvalue); if (gs != GS_ALL_DONE) saw_lhs = -1; } return saw_lhs; } /* Gimplify an OMP_ATOMIC statement. */ static enum gimplify_status gimplify_omp_atomic (tree *expr_p, gimple_seq *pre_p) { tree addr = TREE_OPERAND (*expr_p, 0); tree rhs = TREE_OPERAND (*expr_p, 1); tree type = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (addr))); tree tmp_load; tmp_load = create_tmp_var (type, NULL); if (TREE_CODE (type) == COMPLEX_TYPE || TREE_CODE (type) == VECTOR_TYPE) DECL_GIMPLE_REG_P (tmp_load) = 1; if (goa_stabilize_expr (&rhs, pre_p, addr, tmp_load) < 0) return GS_ERROR; if (gimplify_expr (&addr, pre_p, NULL, is_gimple_val, fb_rvalue) != GS_ALL_DONE) return GS_ERROR; gimplify_seq_add_stmt (pre_p, gimple_build_omp_atomic_load (tmp_load, addr)); if (gimplify_expr (&rhs, pre_p, NULL, is_gimple_val, fb_rvalue) != GS_ALL_DONE) return GS_ERROR; gimplify_seq_add_stmt (pre_p, gimple_build_omp_atomic_store (rhs)); *expr_p = NULL; return GS_ALL_DONE; } /* Converts the GENERIC expression tree *EXPR_P to GIMPLE. If the expression produces a value to be used as an operand inside a GIMPLE statement, the value will be stored back in *EXPR_P. This value will be a tree of class tcc_declaration, tcc_constant, tcc_reference or an SSA_NAME. The corresponding sequence of GIMPLE statements is emitted in PRE_P and POST_P. Additionally, this process may overwrite parts of the input expression during gimplification. Ideally, it should be possible to do non-destructive gimplification. EXPR_P points to the GENERIC expression to convert to GIMPLE. If the expression needs to evaluate to a value to be used as an operand in a GIMPLE statement, this value will be stored in *EXPR_P on exit. This happens when the caller specifies one of fb_lvalue or fb_rvalue fallback flags. PRE_P will contain the sequence of GIMPLE statements corresponding to the evaluation of EXPR and all the side-effects that must be executed before the main expression. On exit, the last statement of PRE_P is the core statement being gimplified. For instance, when gimplifying 'if (++a)' the last statement in PRE_P will be 'if (t.1)' where t.1 is the result of pre-incrementing 'a'. POST_P will contain the sequence of GIMPLE statements corresponding to the evaluation of all the side-effects that must be executed after the main expression. If this is NULL, the post side-effects are stored at the end of PRE_P. The reason why the output is split in two is to handle post side-effects explicitly. In some cases, an expression may have inner and outer post side-effects which need to be emitted in an order different from the one given by the recursive traversal. For instance, for the expression (*p--)++ the post side-effects of '--' must actually occur *after* the post side-effects of '++'. However, gimplification will first visit the inner expression, so if a separate POST sequence was not used, the resulting sequence would be: 1 t.1 = *p 2 p = p - 1 3 t.2 = t.1 + 1 4 *p = t.2 However, the post-decrement operation in line #2 must not be evaluated until after the store to *p at line #4, so the correct sequence should be: 1 t.1 = *p 2 t.2 = t.1 + 1 3 *p = t.2 4 p = p - 1 So, by specifying a separate post queue, it is possible to emit the post side-effects in the correct order. If POST_P is NULL, an internal queue will be used. Before returning to the caller, the sequence POST_P is appended to the main output sequence PRE_P. GIMPLE_TEST_F points to a function that takes a tree T and returns nonzero if T is in the GIMPLE form requested by the caller. The GIMPLE predicates are in tree-gimple.c. FALLBACK tells the function what sort of a temporary we want if gimplification cannot produce an expression that complies with GIMPLE_TEST_F. fb_none means that no temporary should be generated fb_rvalue means that an rvalue is OK to generate fb_lvalue means that an lvalue is OK to generate fb_either means that either is OK, but an lvalue is preferable. fb_mayfail means that gimplification may fail (in which case GS_ERROR will be returned) The return value is either GS_ERROR or GS_ALL_DONE, since this function iterates until EXPR is completely gimplified or an error occurs. */ enum gimplify_status gimplify_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p, bool (*gimple_test_f) (tree), fallback_t fallback) { tree tmp; gimple_seq internal_pre = NULL; gimple_seq internal_post = NULL; tree save_expr; bool is_statement; location_t saved_location; enum gimplify_status ret; gimple_stmt_iterator pre_last_gsi, post_last_gsi; save_expr = *expr_p; if (save_expr == NULL_TREE) return GS_ALL_DONE; /* If we are gimplifying a top-level statement, PRE_P must be valid. */ is_statement = gimple_test_f == is_gimple_stmt; if (is_statement) gcc_assert (pre_p); /* Consistency checks. */ if (gimple_test_f == is_gimple_reg) gcc_assert (fallback & (fb_rvalue | fb_lvalue)); else if (gimple_test_f == is_gimple_val || gimple_test_f == is_gimple_call_addr || gimple_test_f == is_gimple_condexpr || gimple_test_f == is_gimple_mem_rhs || gimple_test_f == is_gimple_mem_rhs_or_call || gimple_test_f == is_gimple_reg_rhs || gimple_test_f == is_gimple_reg_rhs_or_call || gimple_test_f == is_gimple_asm_val) gcc_assert (fallback & fb_rvalue); else if (gimple_test_f == is_gimple_min_lval || gimple_test_f == is_gimple_lvalue) gcc_assert (fallback & fb_lvalue); else if (gimple_test_f == is_gimple_addressable) gcc_assert (fallback & fb_either); else if (gimple_test_f == is_gimple_stmt) gcc_assert (fallback == fb_none); else { /* We should have recognized the GIMPLE_TEST_F predicate to know what kind of fallback to use in case a temporary is needed to hold the value or address of *EXPR_P. */ gcc_unreachable (); } /* We used to check the predicate here and return immediately if it succeeds. This is wrong; the design is for gimplification to be idempotent, and for the predicates to only test for valid forms, not whether they are fully simplified. */ if (pre_p == NULL) pre_p = &internal_pre; if (post_p == NULL) post_p = &internal_post; /* Remember the last statements added to PRE_P and POST_P. Every new statement added by the gimplification helpers needs to be annotated with location information. To centralize the responsibility, we remember the last statement that had been added to both queues before gimplifying *EXPR_P. If gimplification produces new statements in PRE_P and POST_P, those statements will be annotated with the same location information as *EXPR_P. */ pre_last_gsi = gsi_last (*pre_p); post_last_gsi = gsi_last (*post_p); saved_location = input_location; if (save_expr != error_mark_node && EXPR_HAS_LOCATION (*expr_p)) input_location = EXPR_LOCATION (*expr_p); /* Loop over the specific gimplifiers until the toplevel node remains the same. */ do { /* Strip away as many useless type conversions as possible at the toplevel. */ STRIP_USELESS_TYPE_CONVERSION (*expr_p); /* Remember the expr. */ save_expr = *expr_p; /* Die, die, die, my darling. */ if (save_expr == error_mark_node || (TREE_TYPE (save_expr) && TREE_TYPE (save_expr) == error_mark_node)) { ret = GS_ERROR; break; } /* Do any language-specific gimplification. */ ret = ((enum gimplify_status) lang_hooks.gimplify_expr (expr_p, pre_p, post_p)); if (ret == GS_OK) { if (*expr_p == NULL_TREE) break; if (*expr_p != save_expr) continue; } else if (ret != GS_UNHANDLED) break; ret = GS_OK; switch (TREE_CODE (*expr_p)) { /* First deal with the special cases. */ case POSTINCREMENT_EXPR: case POSTDECREMENT_EXPR: case PREINCREMENT_EXPR: case PREDECREMENT_EXPR: ret = gimplify_self_mod_expr (expr_p, pre_p, post_p, fallback != fb_none); break; case ARRAY_REF: case ARRAY_RANGE_REF: case REALPART_EXPR: case IMAGPART_EXPR: case COMPONENT_REF: case VIEW_CONVERT_EXPR: ret = gimplify_compound_lval (expr_p, pre_p, post_p, fallback ? fallback : fb_rvalue); break; case COND_EXPR: ret = gimplify_cond_expr (expr_p, pre_p, fallback); /* C99 code may assign to an array in a structure value of a conditional expression, and this has undefined behavior only on execution, so create a temporary if an lvalue is required. */ if (fallback == fb_lvalue) { *expr_p = get_initialized_tmp_var (*expr_p, pre_p, post_p); mark_addressable (*expr_p); } break; case CALL_EXPR: ret = gimplify_call_expr (expr_p, pre_p, fallback != fb_none); /* C99 code may assign to an array in a structure returned from a function, and this has undefined behavior only on execution, so create a temporary if an lvalue is required. */ if (fallback == fb_lvalue) { *expr_p = get_initialized_tmp_var (*expr_p, pre_p, post_p); mark_addressable (*expr_p); } break; case TREE_LIST: gcc_unreachable (); case COMPOUND_EXPR: ret = gimplify_compound_expr (expr_p, pre_p, fallback != fb_none); break; case COMPOUND_LITERAL_EXPR: ret = gimplify_compound_literal_expr (expr_p, pre_p); break; case MODIFY_EXPR: case INIT_EXPR: ret = gimplify_modify_expr (expr_p, pre_p, post_p, fallback != fb_none); /* Don't let the end of loop logic change GS_OK to GS_ALL_DONE; gimplify_modify_expr_rhs might have changed the RHS. */ if (ret == GS_OK && *expr_p) continue; break; case TRUTH_ANDIF_EXPR: case TRUTH_ORIF_EXPR: /* Pass the source location of the outer expression. */ ret = gimplify_boolean_expr (expr_p, saved_location); break; case TRUTH_NOT_EXPR: if (TREE_CODE (TREE_TYPE (*expr_p)) != BOOLEAN_TYPE) { tree type = TREE_TYPE (*expr_p); *expr_p = fold_convert (type, gimple_boolify (*expr_p)); ret = GS_OK; break; } ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_val, fb_rvalue); recalculate_side_effects (*expr_p); break; case ADDR_EXPR: ret = gimplify_addr_expr (expr_p, pre_p, post_p); break; case VA_ARG_EXPR: ret = gimplify_va_arg_expr (expr_p, pre_p, post_p); break; CASE_CONVERT: if (IS_EMPTY_STMT (*expr_p)) { ret = GS_ALL_DONE; break; } if (VOID_TYPE_P (TREE_TYPE (*expr_p)) || fallback == fb_none) { /* Just strip a conversion to void (or in void context) and try again. */ *expr_p = TREE_OPERAND (*expr_p, 0); break; } ret = gimplify_conversion (expr_p); if (ret == GS_ERROR) break; if (*expr_p != save_expr) break; /* FALLTHRU */ case FIX_TRUNC_EXPR: /* unary_expr: ... | '(' cast ')' val | ... */ ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_val, fb_rvalue); recalculate_side_effects (*expr_p); break; case INDIRECT_REF: *expr_p = fold_indirect_ref_loc (input_location, *expr_p); if (*expr_p != save_expr) break; /* else fall through. */ case ALIGN_INDIRECT_REF: case MISALIGNED_INDIRECT_REF: ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_reg, fb_rvalue); recalculate_side_effects (*expr_p); break; /* Constants need not be gimplified. */ case INTEGER_CST: case REAL_CST: case FIXED_CST: case STRING_CST: case COMPLEX_CST: case VECTOR_CST: ret = GS_ALL_DONE; break; case CONST_DECL: /* If we require an lvalue, such as for ADDR_EXPR, retain the CONST_DECL node. Otherwise the decl is replaceable by its value. */ /* ??? Should be == fb_lvalue, but ADDR_EXPR passes fb_either. */ if (fallback & fb_lvalue) ret = GS_ALL_DONE; else *expr_p = DECL_INITIAL (*expr_p); break; case DECL_EXPR: ret = gimplify_decl_expr (expr_p, pre_p); break; case BIND_EXPR: ret = gimplify_bind_expr (expr_p, pre_p); break; case LOOP_EXPR: ret = gimplify_loop_expr (expr_p, pre_p); break; case SWITCH_EXPR: ret = gimplify_switch_expr (expr_p, pre_p); break; case EXIT_EXPR: ret = gimplify_exit_expr (expr_p); break; case GOTO_EXPR: /* If the target is not LABEL, then it is a computed jump and the target needs to be gimplified. */ if (TREE_CODE (GOTO_DESTINATION (*expr_p)) != LABEL_DECL) { ret = gimplify_expr (&GOTO_DESTINATION (*expr_p), pre_p, NULL, is_gimple_val, fb_rvalue); if (ret == GS_ERROR) break; } gimplify_seq_add_stmt (pre_p, gimple_build_goto (GOTO_DESTINATION (*expr_p))); break; case PREDICT_EXPR: gimplify_seq_add_stmt (pre_p, gimple_build_predict (PREDICT_EXPR_PREDICTOR (*expr_p), PREDICT_EXPR_OUTCOME (*expr_p))); ret = GS_ALL_DONE; break; case LABEL_EXPR: ret = GS_ALL_DONE; gcc_assert (decl_function_context (LABEL_EXPR_LABEL (*expr_p)) == current_function_decl); gimplify_seq_add_stmt (pre_p, gimple_build_label (LABEL_EXPR_LABEL (*expr_p))); break; case CASE_LABEL_EXPR: ret = gimplify_case_label_expr (expr_p, pre_p); break; case RETURN_EXPR: ret = gimplify_return_expr (*expr_p, pre_p); break; case CONSTRUCTOR: /* Don't reduce this in place; let gimplify_init_constructor work its magic. Buf if we're just elaborating this for side effects, just gimplify any element that has side-effects. */ if (fallback == fb_none) { unsigned HOST_WIDE_INT ix; constructor_elt *ce; tree temp = NULL_TREE; for (ix = 0; VEC_iterate (constructor_elt, CONSTRUCTOR_ELTS (*expr_p), ix, ce); ix++) if (TREE_SIDE_EFFECTS (ce->value)) append_to_statement_list (ce->value, &temp); *expr_p = temp; ret = GS_OK; } /* C99 code may assign to an array in a constructed structure or union, and this has undefined behavior only on execution, so create a temporary if an lvalue is required. */ else if (fallback == fb_lvalue) { *expr_p = get_initialized_tmp_var (*expr_p, pre_p, post_p); mark_addressable (*expr_p); } else ret = GS_ALL_DONE; break; /* The following are special cases that are not handled by the original GIMPLE grammar. */ /* SAVE_EXPR nodes are converted into a GIMPLE identifier and eliminated. */ case SAVE_EXPR: ret = gimplify_save_expr (expr_p, pre_p, post_p); break; case BIT_FIELD_REF: { enum gimplify_status r0, r1, r2; r0 = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_lvalue, fb_either); r1 = gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p, post_p, is_gimple_val, fb_rvalue); r2 = gimplify_expr (&TREE_OPERAND (*expr_p, 2), pre_p, post_p, is_gimple_val, fb_rvalue); recalculate_side_effects (*expr_p); ret = MIN (r0, MIN (r1, r2)); } break; case TARGET_MEM_REF: { enum gimplify_status r0 = GS_ALL_DONE, r1 = GS_ALL_DONE; if (TMR_SYMBOL (*expr_p)) r0 = gimplify_expr (&TMR_SYMBOL (*expr_p), pre_p, post_p, is_gimple_lvalue, fb_either); else if (TMR_BASE (*expr_p)) r0 = gimplify_expr (&TMR_BASE (*expr_p), pre_p, post_p, is_gimple_val, fb_either); if (TMR_INDEX (*expr_p)) r1 = gimplify_expr (&TMR_INDEX (*expr_p), pre_p, post_p, is_gimple_val, fb_rvalue); /* TMR_STEP and TMR_OFFSET are always integer constants. */ ret = MIN (r0, r1); } break; case NON_LVALUE_EXPR: /* This should have been stripped above. */ gcc_unreachable (); case ASM_EXPR: ret = gimplify_asm_expr (expr_p, pre_p, post_p); break; case TRY_FINALLY_EXPR: case TRY_CATCH_EXPR: { gimple_seq eval, cleanup; gimple try_; eval = cleanup = NULL; gimplify_and_add (TREE_OPERAND (*expr_p, 0), &eval); gimplify_and_add (TREE_OPERAND (*expr_p, 1), &cleanup); /* Don't create bogus GIMPLE_TRY with empty cleanup. */ if (gimple_seq_empty_p (cleanup)) { gimple_seq_add_seq (pre_p, eval); ret = GS_ALL_DONE; break; } try_ = gimple_build_try (eval, cleanup, TREE_CODE (*expr_p) == TRY_FINALLY_EXPR ? GIMPLE_TRY_FINALLY : GIMPLE_TRY_CATCH); if (TREE_CODE (*expr_p) == TRY_CATCH_EXPR) gimple_try_set_catch_is_cleanup (try_, TRY_CATCH_IS_CLEANUP (*expr_p)); gimplify_seq_add_stmt (pre_p, try_); ret = GS_ALL_DONE; break; } case CLEANUP_POINT_EXPR: ret = gimplify_cleanup_point_expr (expr_p, pre_p); break; case TARGET_EXPR: ret = gimplify_target_expr (expr_p, pre_p, post_p); break; case CATCH_EXPR: { gimple c; gimple_seq handler = NULL; gimplify_and_add (CATCH_BODY (*expr_p), &handler); c = gimple_build_catch (CATCH_TYPES (*expr_p), handler); gimplify_seq_add_stmt (pre_p, c); ret = GS_ALL_DONE; break; } case EH_FILTER_EXPR: { gimple ehf; gimple_seq failure = NULL; gimplify_and_add (EH_FILTER_FAILURE (*expr_p), &failure); ehf = gimple_build_eh_filter (EH_FILTER_TYPES (*expr_p), failure); gimple_set_no_warning (ehf, TREE_NO_WARNING (*expr_p)); gimplify_seq_add_stmt (pre_p, ehf); ret = GS_ALL_DONE; break; } case OBJ_TYPE_REF: { enum gimplify_status r0, r1; r0 = gimplify_expr (&OBJ_TYPE_REF_OBJECT (*expr_p), pre_p, post_p, is_gimple_val, fb_rvalue); r1 = gimplify_expr (&OBJ_TYPE_REF_EXPR (*expr_p), pre_p, post_p, is_gimple_val, fb_rvalue); TREE_SIDE_EFFECTS (*expr_p) = 0; ret = MIN (r0, r1); } break; case LABEL_DECL: /* We get here when taking the address of a label. We mark the label as "forced"; meaning it can never be removed and it is a potential target for any computed goto. */ FORCED_LABEL (*expr_p) = 1; ret = GS_ALL_DONE; break; case STATEMENT_LIST: ret = gimplify_statement_list (expr_p, pre_p); break; case WITH_SIZE_EXPR: { gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p == &internal_post ? NULL : post_p, gimple_test_f, fallback); gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p, post_p, is_gimple_val, fb_rvalue); } break; case VAR_DECL: case PARM_DECL: ret = gimplify_var_or_parm_decl (expr_p); break; case RESULT_DECL: /* When within an OpenMP context, notice uses of variables. */ if (gimplify_omp_ctxp) omp_notice_variable (gimplify_omp_ctxp, *expr_p, true); ret = GS_ALL_DONE; break; case SSA_NAME: /* Allow callbacks into the gimplifier during optimization. */ ret = GS_ALL_DONE; break; case OMP_PARALLEL: gimplify_omp_parallel (expr_p, pre_p); ret = GS_ALL_DONE; break; case OMP_TASK: gimplify_omp_task (expr_p, pre_p); ret = GS_ALL_DONE; break; case OMP_FOR: ret = gimplify_omp_for (expr_p, pre_p); break; case OMP_SECTIONS: case OMP_SINGLE: gimplify_omp_workshare (expr_p, pre_p); ret = GS_ALL_DONE; break; case OMP_SECTION: case OMP_MASTER: case OMP_ORDERED: case OMP_CRITICAL: { gimple_seq body = NULL; gimple g; gimplify_and_add (OMP_BODY (*expr_p), &body); switch (TREE_CODE (*expr_p)) { case OMP_SECTION: g = gimple_build_omp_section (body); break; case OMP_MASTER: g = gimple_build_omp_master (body); break; case OMP_ORDERED: g = gimple_build_omp_ordered (body); break; case OMP_CRITICAL: g = gimple_build_omp_critical (body, OMP_CRITICAL_NAME (*expr_p)); break; default: gcc_unreachable (); } gimplify_seq_add_stmt (pre_p, g); ret = GS_ALL_DONE; break; } case OMP_ATOMIC: ret = gimplify_omp_atomic (expr_p, pre_p); break; case POINTER_PLUS_EXPR: /* Convert ((type *)A)+offset into &A->field_of_type_and_offset. The second is gimple immediate saving a need for extra statement. */ if (TREE_CODE (TREE_OPERAND (*expr_p, 1)) == INTEGER_CST && (tmp = maybe_fold_offset_to_address (EXPR_LOCATION (*expr_p), TREE_OPERAND (*expr_p, 0), TREE_OPERAND (*expr_p, 1), TREE_TYPE (*expr_p)))) { *expr_p = tmp; break; } /* Convert (void *)&a + 4 into (void *)&a[1]. */ if (TREE_CODE (TREE_OPERAND (*expr_p, 0)) == NOP_EXPR && TREE_CODE (TREE_OPERAND (*expr_p, 1)) == INTEGER_CST && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*expr_p, 0),0))) && (tmp = maybe_fold_offset_to_address (EXPR_LOCATION (*expr_p), TREE_OPERAND (TREE_OPERAND (*expr_p, 0), 0), TREE_OPERAND (*expr_p, 1), TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*expr_p, 0), 0))))) { *expr_p = fold_convert (TREE_TYPE (*expr_p), tmp); break; } /* FALLTHRU */ default: switch (TREE_CODE_CLASS (TREE_CODE (*expr_p))) { case tcc_comparison: /* Handle comparison of objects of non scalar mode aggregates with a call to memcmp. It would be nice to only have to do this for variable-sized objects, but then we'd have to allow the same nest of reference nodes we allow for MODIFY_EXPR and that's too complex. Compare scalar mode aggregates as scalar mode values. Using memcmp for them would be very inefficient at best, and is plain wrong if bitfields are involved. */ { tree type = TREE_TYPE (TREE_OPERAND (*expr_p, 1)); if (!AGGREGATE_TYPE_P (type)) goto expr_2; else if (TYPE_MODE (type) != BLKmode) ret = gimplify_scalar_mode_aggregate_compare (expr_p); else ret = gimplify_variable_sized_compare (expr_p); break; } /* If *EXPR_P does not need to be special-cased, handle it according to its class. */ case tcc_unary: ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_val, fb_rvalue); break; case tcc_binary: expr_2: { enum gimplify_status r0, r1; r0 = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_val, fb_rvalue); r1 = gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p, post_p, is_gimple_val, fb_rvalue); ret = MIN (r0, r1); break; } case tcc_declaration: case tcc_constant: ret = GS_ALL_DONE; goto dont_recalculate; default: gcc_assert (TREE_CODE (*expr_p) == TRUTH_AND_EXPR || TREE_CODE (*expr_p) == TRUTH_OR_EXPR || TREE_CODE (*expr_p) == TRUTH_XOR_EXPR); goto expr_2; } recalculate_side_effects (*expr_p); dont_recalculate: break; } /* If we replaced *expr_p, gimplify again. */ if (ret == GS_OK && (*expr_p == NULL || *expr_p == save_expr)) ret = GS_ALL_DONE; } while (ret == GS_OK); /* If we encountered an error_mark somewhere nested inside, either stub out the statement or propagate the error back out. */ if (ret == GS_ERROR) { if (is_statement) *expr_p = NULL; goto out; } /* This was only valid as a return value from the langhook, which we handled. Make sure it doesn't escape from any other context. */ gcc_assert (ret != GS_UNHANDLED); if (fallback == fb_none && *expr_p && !is_gimple_stmt (*expr_p)) { /* We aren't looking for a value, and we don't have a valid statement. If it doesn't have side-effects, throw it away. */ if (!TREE_SIDE_EFFECTS (*expr_p)) *expr_p = NULL; else if (!TREE_THIS_VOLATILE (*expr_p)) { /* This is probably a _REF that contains something nested that has side effects. Recurse through the operands to find it. */ enum tree_code code = TREE_CODE (*expr_p); switch (code) { case COMPONENT_REF: case REALPART_EXPR: case IMAGPART_EXPR: case VIEW_CONVERT_EXPR: gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, gimple_test_f, fallback); break; case ARRAY_REF: case ARRAY_RANGE_REF: gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, gimple_test_f, fallback); gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p, post_p, gimple_test_f, fallback); break; default: /* Anything else with side-effects must be converted to a valid statement before we get here. */ gcc_unreachable (); } *expr_p = NULL; } else if (COMPLETE_TYPE_P (TREE_TYPE (*expr_p)) && TYPE_MODE (TREE_TYPE (*expr_p)) != BLKmode) { /* Historically, the compiler has treated a bare reference to a non-BLKmode volatile lvalue as forcing a load. */ tree type = TYPE_MAIN_VARIANT (TREE_TYPE (*expr_p)); /* Normally, we do not want to create a temporary for a TREE_ADDRESSABLE type because such a type should not be copied by bitwise-assignment. However, we make an exception here, as all we are doing here is ensuring that we read the bytes that make up the type. We use create_tmp_var_raw because create_tmp_var will abort when given a TREE_ADDRESSABLE type. */ tree tmp = create_tmp_var_raw (type, "vol"); gimple_add_tmp_var (tmp); gimplify_assign (tmp, *expr_p, pre_p); *expr_p = NULL; } else /* We can't do anything useful with a volatile reference to an incomplete type, so just throw it away. Likewise for a BLKmode type, since any implicit inner load should already have been turned into an explicit one by the gimplification process. */ *expr_p = NULL; } /* If we are gimplifying at the statement level, we're done. Tack everything together and return. */ if (fallback == fb_none || is_statement) { /* Since *EXPR_P has been converted into a GIMPLE tuple, clear it out for GC to reclaim it. */ *expr_p = NULL_TREE; if (!gimple_seq_empty_p (internal_pre) || !gimple_seq_empty_p (internal_post)) { gimplify_seq_add_seq (&internal_pre, internal_post); gimplify_seq_add_seq (pre_p, internal_pre); } /* The result of gimplifying *EXPR_P is going to be the last few statements in *PRE_P and *POST_P. Add location information to all the statements that were added by the gimplification helpers. */ if (!gimple_seq_empty_p (*pre_p)) annotate_all_with_location_after (*pre_p, pre_last_gsi, input_location); if (!gimple_seq_empty_p (*post_p)) annotate_all_with_location_after (*post_p, post_last_gsi, input_location); goto out; } #ifdef ENABLE_GIMPLE_CHECKING if (*expr_p) { enum tree_code code = TREE_CODE (*expr_p); /* These expressions should already be in gimple IR form. */ gcc_assert (code != MODIFY_EXPR && code != ASM_EXPR && code != BIND_EXPR && code != CATCH_EXPR && (code != COND_EXPR || gimplify_ctxp->allow_rhs_cond_expr) && code != EH_FILTER_EXPR && code != GOTO_EXPR && code != LABEL_EXPR && code != LOOP_EXPR && code != SWITCH_EXPR && code != TRY_FINALLY_EXPR && code != OMP_CRITICAL && code != OMP_FOR && code != OMP_MASTER && code != OMP_ORDERED && code != OMP_PARALLEL && code != OMP_SECTIONS && code != OMP_SECTION && code != OMP_SINGLE); } #endif /* Otherwise we're gimplifying a subexpression, so the resulting value is interesting. If it's a valid operand that matches GIMPLE_TEST_F, we're done. Unless we are handling some post-effects internally; if that's the case, we need to copy into a temporary before adding the post-effects to POST_P. */ if (gimple_seq_empty_p (internal_post) && (*gimple_test_f) (*expr_p)) goto out; /* Otherwise, we need to create a new temporary for the gimplified expression. */ /* We can't return an lvalue if we have an internal postqueue. The object the lvalue refers to would (probably) be modified by the postqueue; we need to copy the value out first, which means an rvalue. */ if ((fallback & fb_lvalue) && gimple_seq_empty_p (internal_post) && is_gimple_addressable (*expr_p)) { /* An lvalue will do. Take the address of the expression, store it in a temporary, and replace the expression with an INDIRECT_REF of that temporary. */ tmp = build_fold_addr_expr_loc (input_location, *expr_p); gimplify_expr (&tmp, pre_p, post_p, is_gimple_reg, fb_rvalue); *expr_p = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (tmp)), tmp); } else if ((fallback & fb_rvalue) && is_gimple_reg_rhs_or_call (*expr_p)) { /* An rvalue will do. Assign the gimplified expression into a new temporary TMP and replace the original expression with TMP. First, make sure that the expression has a type so that it can be assigned into a temporary. */ gcc_assert (!VOID_TYPE_P (TREE_TYPE (*expr_p))); if (!gimple_seq_empty_p (internal_post) || (fallback & fb_lvalue)) /* The postqueue might change the value of the expression between the initialization and use of the temporary, so we can't use a formal temp. FIXME do we care? */ { *expr_p = get_initialized_tmp_var (*expr_p, pre_p, post_p); if (TREE_CODE (TREE_TYPE (*expr_p)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (*expr_p)) == VECTOR_TYPE) DECL_GIMPLE_REG_P (*expr_p) = 1; } else *expr_p = get_formal_tmp_var (*expr_p, pre_p); } else { #ifdef ENABLE_GIMPLE_CHECKING if (!(fallback & fb_mayfail)) { fprintf (stderr, "gimplification failed:\n"); print_generic_expr (stderr, *expr_p, 0); debug_tree (*expr_p); internal_error ("gimplification failed"); } #endif gcc_assert (fallback & fb_mayfail); /* If this is an asm statement, and the user asked for the impossible, don't die. Fail and let gimplify_asm_expr issue an error. */ ret = GS_ERROR; goto out; } /* Make sure the temporary matches our predicate. */ gcc_assert ((*gimple_test_f) (*expr_p)); if (!gimple_seq_empty_p (internal_post)) { annotate_all_with_location (internal_post, input_location); gimplify_seq_add_seq (pre_p, internal_post); } out: input_location = saved_location; return ret; } /* Look through TYPE for variable-sized objects and gimplify each such size that we find. Add to LIST_P any statements generated. */ void gimplify_type_sizes (tree type, gimple_seq *list_p) { tree field, t; if (type == NULL || type == error_mark_node) return; /* We first do the main variant, then copy into any other variants. */ type = TYPE_MAIN_VARIANT (type); /* Avoid infinite recursion. */ if (TYPE_SIZES_GIMPLIFIED (type)) return; TYPE_SIZES_GIMPLIFIED (type) = 1; switch (TREE_CODE (type)) { case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE: case REAL_TYPE: case FIXED_POINT_TYPE: gimplify_one_sizepos (&TYPE_MIN_VALUE (type), list_p); gimplify_one_sizepos (&TYPE_MAX_VALUE (type), list_p); for (t = TYPE_NEXT_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t)) { TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (type); TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (type); } break; case ARRAY_TYPE: /* These types may not have declarations, so handle them here. */ gimplify_type_sizes (TREE_TYPE (type), list_p); gimplify_type_sizes (TYPE_DOMAIN (type), list_p); /* Ensure VLA bounds aren't removed, for -O0 they should be variables with assigned stack slots, for -O1+ -g they should be tracked by VTA. */ if (TYPE_DOMAIN (type) && INTEGRAL_TYPE_P (TYPE_DOMAIN (type))) { t = TYPE_MIN_VALUE (TYPE_DOMAIN (type)); if (t && TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t)) DECL_IGNORED_P (t) = 0; t = TYPE_MAX_VALUE (TYPE_DOMAIN (type)); if (t && TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t)) DECL_IGNORED_P (t) = 0; } break; case RECORD_TYPE: case UNION_TYPE: case QUAL_UNION_TYPE: for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field)) if (TREE_CODE (field) == FIELD_DECL) { gimplify_one_sizepos (&DECL_FIELD_OFFSET (field), list_p); gimplify_one_sizepos (&DECL_SIZE (field), list_p); gimplify_one_sizepos (&DECL_SIZE_UNIT (field), list_p); gimplify_type_sizes (TREE_TYPE (field), list_p); } break; case POINTER_TYPE: case REFERENCE_TYPE: /* We used to recurse on the pointed-to type here, which turned out to be incorrect because its definition might refer to variables not yet initialized at this point if a forward declaration is involved. It was actually useful for anonymous pointed-to types to ensure that the sizes evaluation dominates every possible later use of the values. Restricting to such types here would be safe since there is no possible forward declaration around, but would introduce an undesirable middle-end semantic to anonymity. We then defer to front-ends the responsibility of ensuring that the sizes are evaluated both early and late enough, e.g. by attaching artificial type declarations to the tree. */ break; default: break; } gimplify_one_sizepos (&TYPE_SIZE (type), list_p); gimplify_one_sizepos (&TYPE_SIZE_UNIT (type), list_p); for (t = TYPE_NEXT_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t)) { TYPE_SIZE (t) = TYPE_SIZE (type); TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (type); TYPE_SIZES_GIMPLIFIED (t) = 1; } } /* A subroutine of gimplify_type_sizes to make sure that *EXPR_P, a size or position, has had all of its SAVE_EXPRs evaluated. We add any required statements to *STMT_P. */ void gimplify_one_sizepos (tree *expr_p, gimple_seq *stmt_p) { tree type, expr = *expr_p; /* We don't do anything if the value isn't there, is constant, or contains A PLACEHOLDER_EXPR. We also don't want to do anything if it's already a VAR_DECL. If it's a VAR_DECL from another function, the gimplifier will want to replace it with a new variable, but that will cause problems if this type is from outside the function. It's OK to have that here. */ if (expr == NULL_TREE || TREE_CONSTANT (expr) || TREE_CODE (expr) == VAR_DECL || CONTAINS_PLACEHOLDER_P (expr)) return; type = TREE_TYPE (expr); *expr_p = unshare_expr (expr); gimplify_expr (expr_p, stmt_p, NULL, is_gimple_val, fb_rvalue); expr = *expr_p; /* Verify that we've an exact type match with the original expression. In particular, we do not wish to drop a "sizetype" in favour of a type of similar dimensions. We don't want to pollute the generic type-stripping code with this knowledge because it doesn't matter for the bulk of GENERIC/GIMPLE. It only matters that TYPE_SIZE_UNIT and friends retain their "sizetype-ness". */ if (TREE_TYPE (expr) != type && TREE_CODE (type) == INTEGER_TYPE && TYPE_IS_SIZETYPE (type)) { tree tmp; gimple stmt; *expr_p = create_tmp_var (type, NULL); tmp = build1 (NOP_EXPR, type, expr); stmt = gimplify_assign (*expr_p, tmp, stmt_p); if (EXPR_HAS_LOCATION (expr)) gimple_set_location (stmt, EXPR_LOCATION (expr)); else gimple_set_location (stmt, input_location); } } /* Gimplify the body of statements pointed to by BODY_P and return a GIMPLE_BIND containing the sequence of GIMPLE statements corresponding to BODY_P. FNDECL is the function decl containing *BODY_P. */ gimple gimplify_body (tree *body_p, tree fndecl, bool do_parms) { location_t saved_location = input_location; gimple_seq parm_stmts, seq; gimple outer_bind; struct gimplify_ctx gctx; timevar_push (TV_TREE_GIMPLIFY); /* Initialize for optimize_insn_for_s{ize,peed}_p possibly called during gimplification. */ default_rtl_profile (); gcc_assert (gimplify_ctxp == NULL); push_gimplify_context (&gctx); /* Unshare most shared trees in the body and in that of any nested functions. It would seem we don't have to do this for nested functions because they are supposed to be output and then the outer function gimplified first, but the g++ front end doesn't always do it that way. */ unshare_body (body_p, fndecl); unvisit_body (body_p, fndecl); if (cgraph_node (fndecl)->origin) nonlocal_vlas = pointer_set_create (); /* Make sure input_location isn't set to something weird. */ input_location = DECL_SOURCE_LOCATION (fndecl); /* Resolve callee-copies. This has to be done before processing the body so that DECL_VALUE_EXPR gets processed correctly. */ parm_stmts = (do_parms) ? gimplify_parameters () : NULL; /* Gimplify the function's body. */ seq = NULL; gimplify_stmt (body_p, &seq); outer_bind = gimple_seq_first_stmt (seq); if (!outer_bind) { outer_bind = gimple_build_nop (); gimplify_seq_add_stmt (&seq, outer_bind); } /* The body must contain exactly one statement, a GIMPLE_BIND. If this is not the case, wrap everything in a GIMPLE_BIND to make it so. */ if (gimple_code (outer_bind) == GIMPLE_BIND && gimple_seq_first (seq) == gimple_seq_last (seq)) ; else outer_bind = gimple_build_bind (NULL_TREE, seq, NULL); *body_p = NULL_TREE; /* If we had callee-copies statements, insert them at the beginning of the function and clear DECL_VALUE_EXPR_P on the parameters. */ if (!gimple_seq_empty_p (parm_stmts)) { tree parm; gimplify_seq_add_seq (&parm_stmts, gimple_bind_body (outer_bind)); gimple_bind_set_body (outer_bind, parm_stmts); for (parm = DECL_ARGUMENTS (current_function_decl); parm; parm = TREE_CHAIN (parm)) if (DECL_HAS_VALUE_EXPR_P (parm)) { DECL_HAS_VALUE_EXPR_P (parm) = 0; DECL_IGNORED_P (parm) = 0; } } if (nonlocal_vlas) { pointer_set_destroy (nonlocal_vlas); nonlocal_vlas = NULL; } pop_gimplify_context (outer_bind); gcc_assert (gimplify_ctxp == NULL); #ifdef ENABLE_TYPES_CHECKING if (!errorcount && !sorrycount) verify_types_in_gimple_seq (gimple_bind_body (outer_bind)); #endif timevar_pop (TV_TREE_GIMPLIFY); input_location = saved_location; return outer_bind; } /* Entry point to the gimplification pass. FNDECL is the FUNCTION_DECL node for the function we want to gimplify. Returns the sequence of GIMPLE statements corresponding to the body of FNDECL. */ void gimplify_function_tree (tree fndecl) { tree oldfn, parm, ret; gimple_seq seq; gimple bind; gcc_assert (!gimple_body (fndecl)); oldfn = current_function_decl; current_function_decl = fndecl; if (DECL_STRUCT_FUNCTION (fndecl)) push_cfun (DECL_STRUCT_FUNCTION (fndecl)); else push_struct_function (fndecl); for (parm = DECL_ARGUMENTS (fndecl); parm ; parm = TREE_CHAIN (parm)) { /* Preliminarily mark non-addressed complex variables as eligible for promotion to gimple registers. We'll transform their uses as we find them. */ if ((TREE_CODE (TREE_TYPE (parm)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (parm)) == VECTOR_TYPE) && !TREE_THIS_VOLATILE (parm) && !needs_to_live_in_memory (parm)) DECL_GIMPLE_REG_P (parm) = 1; } ret = DECL_RESULT (fndecl); if ((TREE_CODE (TREE_TYPE (ret)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (ret)) == VECTOR_TYPE) && !needs_to_live_in_memory (ret)) DECL_GIMPLE_REG_P (ret) = 1; bind = gimplify_body (&DECL_SAVED_TREE (fndecl), fndecl, true); /* The tree body of the function is no longer needed, replace it with the new GIMPLE body. */ seq = gimple_seq_alloc (); gimple_seq_add_stmt (&seq, bind); gimple_set_body (fndecl, seq); /* If we're instrumenting function entry/exit, then prepend the call to the entry hook and wrap the whole function in a TRY_FINALLY_EXPR to catch the exit hook. */ /* ??? Add some way to ignore exceptions for this TFE. */ if (flag_instrument_function_entry_exit && !DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (fndecl) && !flag_instrument_functions_exclude_p (fndecl)) { tree x; gimple new_bind; gimple tf; gimple_seq cleanup = NULL, body = NULL; x = implicit_built_in_decls[BUILT_IN_PROFILE_FUNC_EXIT]; gimplify_seq_add_stmt (&cleanup, gimple_build_call (x, 0)); tf = gimple_build_try (seq, cleanup, GIMPLE_TRY_FINALLY); x = implicit_built_in_decls[BUILT_IN_PROFILE_FUNC_ENTER]; gimplify_seq_add_stmt (&body, gimple_build_call (x, 0)); gimplify_seq_add_stmt (&body, tf); new_bind = gimple_build_bind (NULL, body, gimple_bind_block (bind)); /* Clear the block for BIND, since it is no longer directly inside the function, but within a try block. */ gimple_bind_set_block (bind, NULL); /* Replace the current function body with the body wrapped in the try/finally TF. */ seq = gimple_seq_alloc (); gimple_seq_add_stmt (&seq, new_bind); gimple_set_body (fndecl, seq); } DECL_SAVED_TREE (fndecl) = NULL_TREE; cfun->curr_properties = PROP_gimple_any; current_function_decl = oldfn; pop_cfun (); } /* Some transformations like inlining may invalidate the GIMPLE form for operands. This function traverses all the operands in STMT and gimplifies anything that is not a valid gimple operand. Any new GIMPLE statements are inserted before *GSI_P. */ void gimple_regimplify_operands (gimple stmt, gimple_stmt_iterator *gsi_p) { size_t i, num_ops; tree orig_lhs = NULL_TREE, lhs, t; gimple_seq pre = NULL; gimple post_stmt = NULL; struct gimplify_ctx gctx; push_gimplify_context (&gctx); gimplify_ctxp->into_ssa = gimple_in_ssa_p (cfun); switch (gimple_code (stmt)) { case GIMPLE_COND: gimplify_expr (gimple_cond_lhs_ptr (stmt), &pre, NULL, is_gimple_val, fb_rvalue); gimplify_expr (gimple_cond_rhs_ptr (stmt), &pre, NULL, is_gimple_val, fb_rvalue); break; case GIMPLE_SWITCH: gimplify_expr (gimple_switch_index_ptr (stmt), &pre, NULL, is_gimple_val, fb_rvalue); break; case GIMPLE_OMP_ATOMIC_LOAD: gimplify_expr (gimple_omp_atomic_load_rhs_ptr (stmt), &pre, NULL, is_gimple_val, fb_rvalue); break; case GIMPLE_ASM: { size_t i, noutputs = gimple_asm_noutputs (stmt); const char *constraint, **oconstraints; bool allows_mem, allows_reg, is_inout; oconstraints = (const char **) alloca ((noutputs) * sizeof (const char *)); for (i = 0; i < noutputs; i++) { tree op = gimple_asm_output_op (stmt, i); constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (op))); oconstraints[i] = constraint; parse_output_constraint (&constraint, i, 0, 0, &allows_mem, &allows_reg, &is_inout); gimplify_expr (&TREE_VALUE (op), &pre, NULL, is_inout ? is_gimple_min_lval : is_gimple_lvalue, fb_lvalue | fb_mayfail); } for (i = 0; i < gimple_asm_ninputs (stmt); i++) { tree op = gimple_asm_input_op (stmt, i); constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (op))); parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints, &allows_mem, &allows_reg); if (TREE_ADDRESSABLE (TREE_TYPE (TREE_VALUE (op))) && allows_mem) allows_reg = 0; if (!allows_reg && allows_mem) gimplify_expr (&TREE_VALUE (op), &pre, NULL, is_gimple_lvalue, fb_lvalue | fb_mayfail); else gimplify_expr (&TREE_VALUE (op), &pre, NULL, is_gimple_asm_val, fb_rvalue); } } break; default: /* NOTE: We start gimplifying operands from last to first to make sure that side-effects on the RHS of calls, assignments and ASMs are executed before the LHS. The ordering is not important for other statements. */ num_ops = gimple_num_ops (stmt); orig_lhs = gimple_get_lhs (stmt); for (i = num_ops; i > 0; i--) { tree op = gimple_op (stmt, i - 1); if (op == NULL_TREE) continue; if (i == 1 && (is_gimple_call (stmt) || is_gimple_assign (stmt))) gimplify_expr (&op, &pre, NULL, is_gimple_lvalue, fb_lvalue); else if (i == 2 && is_gimple_assign (stmt) && num_ops == 2 && get_gimple_rhs_class (gimple_expr_code (stmt)) == GIMPLE_SINGLE_RHS) gimplify_expr (&op, &pre, NULL, rhs_predicate_for (gimple_assign_lhs (stmt)), fb_rvalue); else if (i == 2 && is_gimple_call (stmt)) { if (TREE_CODE (op) == FUNCTION_DECL) continue; gimplify_expr (&op, &pre, NULL, is_gimple_call_addr, fb_rvalue); } else gimplify_expr (&op, &pre, NULL, is_gimple_val, fb_rvalue); gimple_set_op (stmt, i - 1, op); } lhs = gimple_get_lhs (stmt); /* If the LHS changed it in a way that requires a simple RHS, create temporary. */ if (lhs && !is_gimple_reg (lhs)) { bool need_temp = false; if (is_gimple_assign (stmt) && num_ops == 2 && get_gimple_rhs_class (gimple_expr_code (stmt)) == GIMPLE_SINGLE_RHS) gimplify_expr (gimple_assign_rhs1_ptr (stmt), &pre, NULL, rhs_predicate_for (gimple_assign_lhs (stmt)), fb_rvalue); else if (is_gimple_reg (lhs)) { if (is_gimple_reg_type (TREE_TYPE (lhs))) { if (is_gimple_call (stmt)) { i = gimple_call_flags (stmt); if ((i & ECF_LOOPING_CONST_OR_PURE) || !(i & (ECF_CONST | ECF_PURE))) need_temp = true; } if (stmt_can_throw_internal (stmt)) need_temp = true; } } else { if (is_gimple_reg_type (TREE_TYPE (lhs))) need_temp = true; else if (TYPE_MODE (TREE_TYPE (lhs)) != BLKmode) { if (is_gimple_call (stmt)) { tree fndecl = gimple_call_fndecl (stmt); if (!aggregate_value_p (TREE_TYPE (lhs), fndecl) && !(fndecl && DECL_RESULT (fndecl) && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))) need_temp = true; } else need_temp = true; } } if (need_temp) { tree temp = create_tmp_var (TREE_TYPE (lhs), NULL); if (TREE_CODE (TREE_TYPE (lhs)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (lhs)) == VECTOR_TYPE) DECL_GIMPLE_REG_P (temp) = 1; if (TREE_CODE (orig_lhs) == SSA_NAME) orig_lhs = SSA_NAME_VAR (orig_lhs); if (gimple_in_ssa_p (cfun)) temp = make_ssa_name (temp, NULL); gimple_set_lhs (stmt, temp); post_stmt = gimple_build_assign (lhs, temp); if (TREE_CODE (lhs) == SSA_NAME) SSA_NAME_DEF_STMT (lhs) = post_stmt; } } break; } if (gimple_referenced_vars (cfun)) for (t = gimplify_ctxp->temps; t ; t = TREE_CHAIN (t)) add_referenced_var (t); if (!gimple_seq_empty_p (pre)) { if (gimple_in_ssa_p (cfun)) { gimple_stmt_iterator i; for (i = gsi_start (pre); !gsi_end_p (i); gsi_next (&i)) mark_symbols_for_renaming (gsi_stmt (i)); } gsi_insert_seq_before (gsi_p, pre, GSI_SAME_STMT); } if (post_stmt) gsi_insert_after (gsi_p, post_stmt, GSI_NEW_STMT); pop_gimplify_context (NULL); } /* Expands EXPR to list of gimple statements STMTS. If SIMPLE is true, force the result to be either ssa_name or an invariant, otherwise just force it to be a rhs expression. If VAR is not NULL, make the base variable of the final destination be VAR if suitable. */ tree force_gimple_operand (tree expr, gimple_seq *stmts, bool simple, tree var) { tree t; enum gimplify_status ret; gimple_predicate gimple_test_f; struct gimplify_ctx gctx; *stmts = NULL; if (is_gimple_val (expr)) return expr; gimple_test_f = simple ? is_gimple_val : is_gimple_reg_rhs; push_gimplify_context (&gctx); gimplify_ctxp->into_ssa = gimple_in_ssa_p (cfun); gimplify_ctxp->allow_rhs_cond_expr = true; if (var) expr = build2 (MODIFY_EXPR, TREE_TYPE (var), var, expr); if (TREE_CODE (expr) != MODIFY_EXPR && TREE_TYPE (expr) == void_type_node) { gimplify_and_add (expr, stmts); expr = NULL_TREE; } else { ret = gimplify_expr (&expr, stmts, NULL, gimple_test_f, fb_rvalue); gcc_assert (ret != GS_ERROR); } if (gimple_referenced_vars (cfun)) for (t = gimplify_ctxp->temps; t ; t = TREE_CHAIN (t)) add_referenced_var (t); pop_gimplify_context (NULL); return expr; } /* Invokes force_gimple_operand for EXPR with parameters SIMPLE_P and VAR. If some statements are produced, emits them at GSI. If BEFORE is true. the statements are appended before GSI, otherwise they are appended after it. M specifies the way GSI moves after insertion (GSI_SAME_STMT or GSI_CONTINUE_LINKING are the usual values). */ tree force_gimple_operand_gsi (gimple_stmt_iterator *gsi, tree expr, bool simple_p, tree var, bool before, enum gsi_iterator_update m) { gimple_seq stmts; expr = force_gimple_operand (expr, &stmts, simple_p, var); if (!gimple_seq_empty_p (stmts)) { if (gimple_in_ssa_p (cfun)) { gimple_stmt_iterator i; for (i = gsi_start (stmts); !gsi_end_p (i); gsi_next (&i)) mark_symbols_for_renaming (gsi_stmt (i)); } if (before) gsi_insert_seq_before (gsi, stmts, m); else gsi_insert_seq_after (gsi, stmts, m); } return expr; } #include "gt-gimplify.h"
U.h
/* * Author: Salvatore Mandra (salvatore.mandra@nasa.gov) * * Copyright © 2021, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. All * rights reserved. * * The HybridQ: A Hybrid Simulator for Quantum Circuits platform is licensed * under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the * License at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ #ifndef HYBRIDQ__U_HPP #define HYBRIDQ__U_HPP #include "pack.h" #include "utils.h" namespace hybridq::U { template <std::size_t log2_pack_size, typename float_type, typename... Positions> int apply(float_type *psi_re_ptr, float_type *psi_im_ptr, const float_type *U_ptr, const std::size_t state_size_ptr, Positions &&...pos) { // Check if pointer are correctly aligned if (reinterpret_cast<std::size_t>(psi_re_ptr) % 32 or reinterpret_cast<std::size_t>(psi_im_ptr) % 32) return 1; // Get size of pack static const std::size_t pack_size = 1uL << log2_pack_size; // Get pack_type using pack_type = typename __pack__<float_type, pack_size>::value_type; // Get number of positions static const std::size_t n_pos = sizeof...(pos); // Check that all positions are positive numbers if (not [](auto &&...x) { return ((x >= 0) & ...); }(pos...)) return 1; // Check that all positions are above log2_pack_size if ([](auto &&...x) { return ((static_cast<std::size_t>(x) < log2_pack_size) + ...); }(pos...) != 0) return 1; // Recast to the right size auto *psi_re = reinterpret_cast<pack_type *>(psi_re_ptr); auto *psi_im = reinterpret_cast<pack_type *>(psi_im_ptr); const std::size_t state_size = state_size_ptr >> log2_pack_size; // Split in real and imaginary parts static const std::size_t U_size = 1uL << n_pos; const auto U_re = subset<0, 2 * U_size * U_size, 2>(U_ptr); const auto U_im = subset<1, 2 * U_size * U_size, 2>(U_ptr); // Shift positions const auto shift_pos = [](auto &&pos) { std::array<std::size_t, n_pos> shift_pos; for (std::size_t i = 0; i < n_pos; ++i) shift_pos[i] = pos[i] - log2_pack_size; return shift_pos; }(std::array{pos...}); // Get zero static const auto _zero = __pack__<float_type, pack_size>::get(0); #pragma omp parallel for for (std::size_t i = 0; i < (state_size >> n_pos); ++i) { // Get indexes to expand const auto _pos = expand(i, shift_pos); // Buffer real and imaginary parts from state const auto _psi_re = get(psi_re, _pos); const auto _psi_im = get(psi_im, _pos); // Compute matrix multiplication for (std::size_t i = 0; i < U_size; ++i) { auto _re{_zero}; auto _im{_zero}; for (std::size_t j = 0; j < U_size; ++j) { const auto _U_re = U_re[i * U_size + j]; const auto _U_im = U_im[i * U_size + j]; _re += _U_re * _psi_re[j] - _U_im * _psi_im[j]; _im += _U_re * _psi_im[j] + _U_im * _psi_re[j]; } psi_re[_pos[i]] = _re; psi_im[_pos[i]] = _im; } } return 0; } template <std::size_t log2_pack_size, typename float_type, typename Positions, std::size_t n_pos = array_size_v<Positions>, std::size_t... I> int apply(float_type *psi_re_ptr, float_type *psi_im_ptr, const float_type *U_ptr, Positions &&pos, const std::size_t state_size_ptr, std::index_sequence<I...>) { return apply<log2_pack_size>(psi_re_ptr, psi_im_ptr, U_ptr, state_size_ptr, pos[I]...); } template <std::size_t log2_pack_size, typename float_type, typename Positions, std::size_t n_pos = array_size_v<Positions>> int apply(float_type *psi_re_ptr, float_type *psi_im_ptr, const float_type *U_ptr, Positions &&pos, const std::size_t state_size_ptr) { return apply<log2_pack_size>(psi_re_ptr, psi_im_ptr, U_ptr, pos, state_size_ptr, std::make_index_sequence<n_pos>{}); } template <std::size_t log2_pack_size, typename float_type, typename index_type> int apply(float_type *psi_re_ptr, float_type *psi_im_ptr, const float_type *U_ptr, const index_type *pos, const std::size_t state_size_ptr, const std::size_t n_pos) { // Check if pointer are correctly aligned if (reinterpret_cast<std::size_t>(psi_re_ptr) % 32 or reinterpret_cast<std::size_t>(psi_im_ptr) % 32) return 1; // Get size of pack const std::size_t pack_size = 1uL << log2_pack_size; // Get U_Size const std::size_t U_size = 1uL << n_pos; // Get pack_type using pack_type = typename __pack__<float_type, pack_size>::value_type; // Check that all positions are positive numbers for (std::size_t i = 0; i < n_pos; ++i) if (pos[i] < 0 or static_cast<std::size_t>(pos[i]) < log2_pack_size) return 1; // Recast to the right size auto *psi_re = reinterpret_cast<pack_type *>(psi_re_ptr); auto *psi_im = reinterpret_cast<pack_type *>(psi_im_ptr); const std::size_t state_size = state_size_ptr >> log2_pack_size; // Compute offset std::size_t offset[n_pos]; for (std::size_t i = 0; i < n_pos; ++i) { offset[i] = log2_pack_size; for (std::size_t j = i + 1; j < n_pos; ++j) offset[i] += (pos[j] < pos[i]); } // Allocate buffers pack_type _psi_re[U_size]; pack_type _psi_im[U_size]; std::size_t _pos[U_size]; // Generator of positions auto _get_position = [&pos, &offset, n_pos](std::size_t i, std::size_t j) { std::size_t y{i}; for (std::size_t i = 0; i < n_pos; ++i) { const std::size_t p = pos[i] - offset[i]; const std::size_t y_mask = (1uL << p) - 1; y = ((y & ~y_mask) << 1) ^ (y & y_mask) ^ (((j >> i) & 1uL) << p); } return y; }; #pragma omp parallel for private(_psi_re, _psi_im, _pos) for (std::size_t i = 0; i < (state_size >> n_pos); ++i) { // Get positions for (std::size_t j = 0; j < U_size; ++j) _pos[j] = _get_position(i, j); // Load buffer for (std::size_t j = 0; j < U_size; ++j) { _psi_re[j] = psi_re[_pos[j]]; _psi_im[j] = psi_im[_pos[j]]; } // Compute matrix multiplication for (std::size_t i = 0; i < U_size; ++i) { auto _re = pack_type{0}; auto _im = pack_type{0}; for (std::size_t j = 0; j < U_size; ++j) { const auto _U_re = U_ptr[2 * i * U_size + 2 * j]; const auto _U_im = U_ptr[2 * i * U_size + 2 * j + 1]; _re += _U_re * _psi_re[j] - _U_im * _psi_im[j]; _im += _U_re * _psi_im[j] + _U_im * _psi_re[j]; } // Update state psi_re[_pos[i]] = _re; psi_im[_pos[i]] = _im; } } return 0; } } // namespace hybridq::U #endif
LPfold.c
/* * local pair probabilities for RNA secondary structures * * Stephan Bernhart, Ivo L Hofacker * Vienna RNA package */ /* * todo: compute energy z-score for each window * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <float.h> /* #defines FLT_MAX ... */ #include "ViennaRNA/datastructures/basic.h" #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/params/default.h" #include "ViennaRNA/fold_vars.h" #include "ViennaRNA/plotting/probabilities.h" #include "ViennaRNA/part_func.h" #include "ViennaRNA/params/basic.h" #include "ViennaRNA/loops/all.h" #include "ViennaRNA/LPfold.h" #include "ViennaRNA/Lfold.h" #include "ViennaRNA/alphabet.h" #include "ViennaRNA/part_func_window.h" /* ################################# # GLOBAL VARIABLES # ################################# */ typedef struct { int bpp_print; /* 1 if pairing probabilities should be written to file-handle, 0 if they are returned as vrna_ep_t */ int up_print; /* 1 if unpaired probabilities should be written to file-handle, 0 if they are returned as array */ FILE *fp_pU; double **pU; FLT_OR_DBL bpp_cutoff; FILE *fp_bpp; vrna_ep_t *bpp; unsigned int bpp_max_size; unsigned int bpp_size; vrna_ep_t *stack_prob; unsigned int stack_prob_size; unsigned int stack_prob_max_size; } default_cb_data; typedef struct { FLT_OR_DBL *prml; FLT_OR_DBL *prm_l; FLT_OR_DBL *prm_l1; double **pU; double **pUO; double **pUI; double **pUM; double **pUH; } helper_arrays; /* soft constraint contributions function (interior-loops) */ typedef FLT_OR_DBL (sc_int)(vrna_fold_compound_t *, int, int, int, int); /* QI5 contribution function for unpaired probability computations */ typedef void (add_QI5)(FLT_OR_DBL **, int, int, FLT_OR_DBL, FLT_OR_DBL); /* ################################# # PRIVATE VARIABLES # ################################# */ #ifndef VRNA_DISABLE_BACKWARD_COMPATIBILITY #ifdef _OPENMP #include <omp.h> #endif /* some backward compatibility stuff */ PRIVATE vrna_fold_compound_t *backward_compat_compound = NULL; PRIVATE int backward_compat = 0; #ifdef _OPENMP #pragma omp threadprivate(backward_compat_compound, backward_compat) #endif #endif /* ################################# # PRIVATE FUNCTION DECLARATIONS # ################################# */ PRIVATE void alloc_helper_arrays(vrna_fold_compound_t *vc, int ulength, helper_arrays *aux_arrays, unsigned int options); PRIVATE void free_helper_arrays(vrna_fold_compound_t *vc, int ulength, helper_arrays *aux_arrays, unsigned int options); PRIVATE void compute_probs(vrna_fold_compound_t *vc, int j, helper_arrays *aux_arrays, int ulength, vrna_probs_window_callback *cb, void *data, unsigned int options, int *ov); PRIVATE void make_ptypes(vrna_fold_compound_t *vc, int j); PRIVATE void probability_correction(vrna_fold_compound_t *vc, int i); #if 0 PRIVATE vrna_ep_t * get_deppp(vrna_fold_compound_t *vc, vrna_ep_t *pl, int start); #endif PRIVATE void compute_pU(vrna_fold_compound_t *vc, int k, int ulength, helper_arrays *aux_arrays, vrna_probs_window_callback *cb, void *data, unsigned int options); PRIVATE FLT_OR_DBL * compute_stack_probabilities(vrna_fold_compound_t *vc, int start); PRIVATE void return_pU(int size, int i, int max_size, helper_arrays *aux_arrays, vrna_probs_window_callback *cb, void *data, unsigned int options); PRIVATE void print_bpp_callback(FLT_OR_DBL *pr, int size, int k, void *data); PRIVATE void store_bpp_callback(FLT_OR_DBL *pr, int size, int k, void *data); #if 0 PRIVATE void store_stack_prob_callback(FLT_OR_DBL *pr, int size, int k, void *data); #endif PRIVATE void print_pU_callback(double *pU, int size, int k, int ulength, unsigned int type, void *data); PRIVATE void store_pU_callback(double *pU, int size, int k, int ulength, unsigned int type, void *data); PRIVATE void backward_compat_callback(FLT_OR_DBL *pr, int pr_size, int i, int max, unsigned int type, void *data); PRIVATE FLT_OR_DBL sc_contribution(vrna_fold_compound_t *vc, int i, int j, int k, int l); PRIVATE FLT_OR_DBL sc_dummy(vrna_fold_compound_t *vc, int i, int j, int k, int l); /* ################################# # BEGIN OF FUNCTION DEFINITIONS # ################################# */ PUBLIC vrna_ep_t * vrna_pfl_fold(const char *sequence, int window_size, int max_bp_span, float cutoff) { default_cb_data data; data.fp_pU = NULL; data.pU = NULL; data.bpp_cutoff = (FLT_OR_DBL)cutoff; data.fp_bpp = NULL; data.bpp = NULL; data.bpp_max_size = 0; data.bpp_size = 0; data.stack_prob = NULL; data.stack_prob_max_size = 0; data.stack_prob_size = 0; data.bpp_print = 0; data.up_print = 0; vrna_pfl_fold_cb(sequence, window_size, max_bp_span, &backward_compat_callback, (void *)&data); /* resize pair probability list to actual size */ data.bpp = (vrna_ep_t *)vrna_realloc(data.bpp, sizeof(vrna_ep_t) * (data.bpp_size + 1)); data.bpp[data.bpp_size].i = 0; data.bpp[data.bpp_size].j = 0; data.bpp[data.bpp_size].type = VRNA_PLIST_TYPE_BASEPAIR; data.bpp[data.bpp_size].p = 0; return data.bpp; } PUBLIC double ** vrna_pfl_fold_up(const char *sequence, int ulength, int window_size, int max_bp_span) { unsigned int i; double **pU; default_cb_data data; pU = NULL; if (sequence) { i = strlen(sequence); pU = (double **)vrna_alloc(sizeof(double *) * (i + 2)); data.fp_pU = NULL; data.pU = pU; data.bpp_cutoff = 0.; data.fp_bpp = NULL; data.bpp = NULL; data.bpp_max_size = 0; data.bpp_size = 0; data.stack_prob = NULL; data.stack_prob_max_size = 0; data.stack_prob_size = 0; data.bpp_print = 0; data.up_print = 0; vrna_pfl_fold_up_cb(sequence, ulength, window_size, max_bp_span, &backward_compat_callback, (void *)&data); } return pU; } PRIVATE void alloc_helper_arrays(vrna_fold_compound_t *vc, int ulength, helper_arrays *aux_arrays, unsigned int options) { int i, n; n = vc->length; aux_arrays->pU = NULL; aux_arrays->pUO = NULL; aux_arrays->pUH = NULL; aux_arrays->pUI = NULL; aux_arrays->pUM = NULL; aux_arrays->prm_l = (FLT_OR_DBL *)vrna_alloc(sizeof(FLT_OR_DBL) * (n + 2)); aux_arrays->prm_l1 = (FLT_OR_DBL *)vrna_alloc(sizeof(FLT_OR_DBL) * (n + 2)); aux_arrays->prml = (FLT_OR_DBL *)vrna_alloc(sizeof(FLT_OR_DBL) * (n + 2)); if ((options & VRNA_PROBS_WINDOW_UP) && (ulength > 0)) { aux_arrays->pU = (double **)vrna_alloc((n + 1) * sizeof(double *)); for (i = 1; i <= n; i++) aux_arrays->pU[i] = (double *)vrna_alloc((MAX2(MAXLOOP, ulength) + 2) * sizeof(double)); if (options & VRNA_PROBS_WINDOW_UP_SPLIT) { aux_arrays->pUO = (double **)vrna_alloc((n + 1) * sizeof(double *)); aux_arrays->pUI = (double **)vrna_alloc((n + 1) * sizeof(double *)); aux_arrays->pUM = (double **)vrna_alloc((n + 1) * sizeof(double *)); aux_arrays->pUH = (double **)vrna_alloc((n + 1) * sizeof(double *)); for (i = 1; i <= n; i++) { aux_arrays->pUH[i] = (double *)vrna_alloc((MAX2(MAXLOOP, ulength) + 2) * sizeof(double)); aux_arrays->pUI[i] = (double *)vrna_alloc((MAX2(MAXLOOP, ulength) + 2) * sizeof(double)); aux_arrays->pUO[i] = (double *)vrna_alloc((MAX2(MAXLOOP, ulength) + 2) * sizeof(double)); aux_arrays->pUM[i] = (double *)vrna_alloc((MAX2(MAXLOOP, ulength) + 2) * sizeof(double)); } } } } PRIVATE void free_helper_arrays(vrna_fold_compound_t *vc, int ulength, helper_arrays *aux_arrays, unsigned int options) { int i, n; n = vc->length; free(aux_arrays->prm_l); free(aux_arrays->prm_l1); free(aux_arrays->prml); if ((options & VRNA_PROBS_WINDOW_UP) && (ulength > 0)) { for (i = 1; i <= n; i++) free(aux_arrays->pU[i]); free(aux_arrays->pU); if (options & VRNA_PROBS_WINDOW_UP_SPLIT) { for (i = 1; i <= n; i++) { free(aux_arrays->pUH[i]); free(aux_arrays->pUI[i]); free(aux_arrays->pUO[i]); free(aux_arrays->pUM[i]); } free(aux_arrays->pUH); free(aux_arrays->pUI); free(aux_arrays->pUO); free(aux_arrays->pUM); } } } PRIVATE void return_pU(int size, int i, int max_size, helper_arrays *aux_arrays, vrna_probs_window_callback *cb, void *data, unsigned int options) { if (options & VRNA_PROBS_WINDOW_UP_SPLIT) { cb(aux_arrays->pUO[i], size, i, max_size, VRNA_PROBS_WINDOW_UP | VRNA_EXT_LOOP, data); cb(aux_arrays->pUH[i], size, i, max_size, VRNA_PROBS_WINDOW_UP | VRNA_HP_LOOP, data); cb(aux_arrays->pUI[i], size, i, max_size, VRNA_PROBS_WINDOW_UP | VRNA_INT_LOOP, data); cb(aux_arrays->pUM[i], size, i, max_size, VRNA_PROBS_WINDOW_UP | VRNA_MB_LOOP, data); } else { cb(aux_arrays->pU[i], size, i, max_size, VRNA_PROBS_WINDOW_UP | VRNA_ANY_LOOP, data); } } PRIVATE INLINE void allocate_dp_matrices(vrna_fold_compound_t *vc, int i, unsigned int options) { char **ptype; int winSize; FLT_OR_DBL **pR, **q, **qb, **qm, **qm2, **QI5, **qmb, **q2l; vrna_mx_pf_t *mx; vrna_hc_t *hc; vrna_sc_t *sc; mx = vc->exp_matrices; pR = mx->pR; q = mx->q_local; qb = mx->qb_local; qm = mx->qm_local; qm2 = mx->qm2_local; QI5 = mx->QI5; qmb = mx->qmb; q2l = mx->q2l; ptype = vc->ptype_local; winSize = vc->window_size; hc = vc->hc; /* allocate new part of arrays */ pR[i] = (FLT_OR_DBL *)vrna_alloc((winSize + 1) * sizeof(FLT_OR_DBL)); pR[i] -= i; q[i] = (FLT_OR_DBL *)vrna_alloc((winSize + 1) * sizeof(FLT_OR_DBL)); q[i] -= i; qb[i] = (FLT_OR_DBL *)vrna_alloc((winSize + 1) * sizeof(FLT_OR_DBL)); qb[i] -= i; qm[i] = (FLT_OR_DBL *)vrna_alloc((winSize + 1) * sizeof(FLT_OR_DBL)); qm[i] -= i; if (options & VRNA_PROBS_WINDOW_UP) { qm2[i] = (FLT_OR_DBL *)vrna_alloc((winSize + 1) * sizeof(FLT_OR_DBL)); qm2[i] -= i; QI5[i] = (FLT_OR_DBL *)vrna_alloc((winSize + 1) * sizeof(FLT_OR_DBL)); qmb[i] = (FLT_OR_DBL *)vrna_alloc((winSize + 1) * sizeof(FLT_OR_DBL)); q2l[i] = (FLT_OR_DBL *)vrna_alloc((winSize + 1) * sizeof(FLT_OR_DBL)); } hc->matrix_local[i] = (unsigned char *)vrna_alloc((winSize + 1) * sizeof(unsigned char)); ptype[i] = (char *)vrna_alloc((winSize + 1) * sizeof(char)); ptype[i] -= i; switch (vc->type) { case VRNA_FC_TYPE_SINGLE: sc = vc->sc; if (sc) { if (sc->exp_energy_bp_local) sc->exp_energy_bp_local[i] = (FLT_OR_DBL *)vrna_alloc((winSize + 1) * sizeof(FLT_OR_DBL)); if (sc->exp_energy_up) sc->exp_energy_up[i] = (FLT_OR_DBL *)vrna_alloc((winSize + 1) * sizeof(FLT_OR_DBL)); vrna_sc_update(vc, i, VRNA_OPTION_PF | VRNA_OPTION_WINDOW); } break; case VRNA_FC_TYPE_COMPARATIVE: break; } } PRIVATE INLINE void free_dp_matrices(vrna_fold_compound_t *vc, unsigned int options) { size_t i; char **ptype; int n, winSize; FLT_OR_DBL **pR, **q, **qb, **qm, **qm2, **QI5, **qmb, **q2l; vrna_mx_pf_t *mx; vrna_hc_t *hc; vrna_sc_t *sc; n = (int)vc->length; winSize = vc->window_size; mx = vc->exp_matrices; pR = mx->pR; q = mx->q_local; qb = mx->qb_local; qm = mx->qm_local; ptype = vc->ptype_local; hc = vc->hc; sc = vc->sc; for (i = MAX2(1, n - (winSize + MAXLOOP)); i <= n; i++) { free(pR[i] + i); free(q[i] + i); free(qb[i] + i); free(qm[i] + i); pR[i] = NULL; q[i] = NULL; qb[i] = NULL; qm[i] = NULL; if (options & VRNA_PROBS_WINDOW_UP) { qm2 = mx->qm2_local; QI5 = mx->QI5; qmb = mx->qmb; q2l = mx->q2l; free(qm2[i] + i); free(QI5[i]); free(qmb[i]); free(q2l[i]); qm2[i] = NULL; QI5[i] = NULL; qmb[i] = NULL; q2l[i] = NULL; } free(hc->matrix_local[i]); hc->matrix_local[i] = NULL; free(ptype[i] + i); ptype[i] = NULL; if (sc) { if (sc->exp_energy_up) free(sc->exp_energy_up[i]); if (sc->exp_energy_bp_local) free(sc->exp_energy_bp_local[i]); } } } PRIVATE INLINE void init_dp_matrices(vrna_fold_compound_t *vc, unsigned int options) { int j, max_j, winSize; winSize = vc->window_size; max_j = MIN2((int)vc->length, 2 * winSize + MAXLOOP + 2); for (j = 1; j <= max_j; j++) allocate_dp_matrices(vc, j, options); } PRIVATE INLINE void rotate_dp_matrices(vrna_fold_compound_t *vc, int j, unsigned int options) { size_t i; char **ptype; int winSize, length; FLT_OR_DBL **pR, **q, **qb, **qm, **qm2, **QI5, **qmb, **q2l; vrna_mx_pf_t *mx; vrna_hc_t *hc; vrna_sc_t *sc; length = vc->length; winSize = vc->window_size; mx = vc->exp_matrices; pR = mx->pR; q = mx->q_local; qb = mx->qb_local; qm = mx->qm_local; ptype = vc->ptype_local; hc = vc->hc; sc = vc->sc; if (j > 2 * winSize + MAXLOOP + 1) { i = (size_t)j - (2 * winSize + MAXLOOP + 1); /* free arrays may be faster than pointer rotation and reset to 0 values */ free(pR[i] + i); free(q[i] + i); free(qb[i] + i); free(qm[i] + i); pR[i] = NULL; q[i] = NULL; qb[i] = NULL; qm[i] = NULL; if (options & VRNA_PROBS_WINDOW_UP) { qm2 = mx->qm2_local; QI5 = mx->QI5; qmb = mx->qmb; q2l = mx->q2l; free(qm2[i] + i); free(QI5[i]); free(qmb[i]); free(q2l[i]); qm2[i] = NULL; QI5[i] = NULL; qmb[i] = NULL; q2l[i] = NULL; } free(hc->matrix_local[i]); hc->matrix_local[i] = NULL; free(ptype[i] + i); ptype[i] = NULL; if (sc) { if (sc->exp_energy_up) { free(sc->exp_energy_up[i]); sc->exp_energy_up[i] = NULL; } if (sc->exp_energy_bp_local) { free(sc->exp_energy_bp_local[i]); sc->exp_energy_bp_local[i] = NULL; } } if (j + 1 <= length) /* get arrays for next round */ allocate_dp_matrices(vc, j + 1, options); } } PRIVATE INLINE void init_constraints(vrna_fold_compound_t *fc, unsigned int options) { int j, max_j, winSize; winSize = fc->window_size; max_j = MIN2((int)fc->length, 2 * winSize + MAXLOOP + 2); for (j = 1; j <= max_j; j++) { make_ptypes(fc, j); vrna_hc_update(fc, j, VRNA_CONSTRAINT_WINDOW_UPDATE_5); vrna_sc_update(fc, j, VRNA_OPTION_PF | VRNA_OPTION_WINDOW); } } PRIVATE INLINE void rotate_constraints(vrna_fold_compound_t *fc, int j, unsigned int options) { if (j + 1 <= fc->length) { make_ptypes(fc, j + 1); vrna_hc_update(fc, j + 1, VRNA_CONSTRAINT_WINDOW_UPDATE_5); vrna_sc_update(fc, j + 1, VRNA_OPTION_PF | VRNA_OPTION_WINDOW); } } PUBLIC int vrna_probs_window(vrna_fold_compound_t *vc, int ulength, unsigned int options, vrna_probs_window_callback *cb, void *data) { unsigned char hc_decompose; int n, i, j, k, maxl, ov, winSize, pairSize, turn; FLT_OR_DBL temp, Qmax, qbt1, **q, **qb, **qm, **qm2, **pR; double max_real, *Fwindow; vrna_exp_param_t *pf_params; vrna_md_t *md; vrna_mx_pf_t *matrices; vrna_hc_t *hc; helper_arrays aux_arrays; vrna_mx_pf_aux_el_t aux_mx_el; vrna_mx_pf_aux_ml_t aux_mx_ml; ov = 0; Qmax = 0; if ((!vc) || (!cb)) return 0; /* failure */ if (!vrna_fold_compound_prepare(vc, VRNA_OPTION_PF | VRNA_OPTION_WINDOW)) { vrna_message_warning("vrna_probs_window: " "Failed to prepare vrna_fold_compound"); return 0; /* failure */ } /* here space for initializing everything */ n = vc->length; pf_params = vc->exp_params; md = &(pf_params->model_details); matrices = vc->exp_matrices; winSize = vc->window_size; pairSize = md->max_bp_span; turn = md->min_loop_size; q = matrices->q_local; qb = matrices->qb_local; qm = matrices->qm_local; qm2 = matrices->qm2_local; pR = matrices->pR; hc = vc->hc; alloc_helper_arrays(vc, ulength, &aux_arrays, options); Fwindow = (options & VRNA_PROBS_WINDOW_PF) ? (double *)vrna_alloc(sizeof(double) * (winSize + 1)) : NULL; /* very short molecule ? */ if (n < turn + 2) { if ((options & VRNA_PROBS_WINDOW_UP) && (ulength > 0)) { for (i = 1; i <= n; i++) { maxl = MIN2(MAX2(MAXLOOP, ulength), n); if (options & VRNA_PROBS_WINDOW_UP_SPLIT) { for (j = 0; j <= maxl; j++) { aux_arrays.pUO[i][j] = 1.; aux_arrays.pUH[i][j] = 0.; aux_arrays.pUI[i][j] = 0.; aux_arrays.pUM[i][j] = 0.; } } else { for (j = 0; j <= maxl; j++) aux_arrays.pU[i][j] = 1.; } return_pU(maxl, i, ulength, &aux_arrays, cb, data, options); } } free_helper_arrays(vc, ulength, &aux_arrays, options); return 1; /* success */ } init_dp_matrices(vc, options); init_constraints(vc, options); /* init auxiliary arrays for fast exterior/multibranch loops */ aux_mx_el = vrna_exp_E_ext_fast_init(vc); aux_mx_ml = vrna_exp_E_ml_fast_init(vc); max_real = (sizeof(FLT_OR_DBL) == sizeof(float)) ? FLT_MAX : DBL_MAX; /* start recursions */ for (j = turn + 2; j <= n + winSize; j++) { if (j <= n) { vrna_exp_E_ext_fast_update(vc, j, aux_mx_el); for (i = j - turn - 1; i >= MAX2(1, (j - winSize + 1)); i--) { hc_decompose = hc->matrix_local[i][j - i]; qbt1 = 0.; /* * construction of partition function of segment i,j * firstly that given i bound to j : qb(i,j) */ if (hc_decompose) { /* process hairpin loop(s) */ qbt1 += vrna_exp_E_hp_loop(vc, i, j); /* process interior loop(s) */ qbt1 += vrna_exp_E_int_loop(vc, i, j); /* process multibranch loop(s) */ qbt1 += vrna_exp_E_mb_loop_fast(vc, i, j, aux_mx_ml); } qb[i][j] = qbt1; /* Multibranch loop */ qm[i][j] = vrna_exp_E_ml_fast(vc, i, j, aux_mx_ml); if ((options & VRNA_PROBS_WINDOW_UP) && (ulength > 0)) { /* new qm2 computation done here */ const FLT_OR_DBL *qqm = vrna_exp_E_ml_fast_qqm(aux_mx_ml); temp = 0.0; for (k = i + 1; k <= j; k++) temp += qm[i][k - 1] * qqm[k]; qm2[i][j] = temp; } /* Exterior loop */ q[i][j] = temp = vrna_exp_E_ext_fast(vc, i, j, aux_mx_el); if (temp > Qmax) { Qmax = temp; if (Qmax > max_real / 10.) { vrna_message_warning("vrna_probs_window: " "Q close to overflow: %d %d %g\n", i, j, temp); } } if (temp >= max_real) { vrna_message_warning("vrna_probs_window: " "overflow while computing partition function for segment q[%d,%d]\n" "use larger pf_scale", i, j); vrna_exp_E_ml_fast_free(aux_mx_ml); vrna_exp_E_ext_fast_free(aux_mx_el); free_helper_arrays(vc, ulength, &aux_arrays, options); return 0; /* failure */ } } /* end for i */ /* * here we return the partition function for subsegments [i...j] in terms * of ensemble free energies G_ij = -RT * ln(Q_ij) in kcal/mol */ if (options & VRNA_PROBS_WINDOW_PF) { int start = MAX2(1, j - winSize + 1); Fwindow -= start; for (i = start; i <= j; i++) Fwindow[i] = (double)(-log(q[i][j]) - (j - i + 1) * log(pf_params->pf_scale)) * pf_params->kT / 1000.0; cb(Fwindow, j, start, winSize, VRNA_PROBS_WINDOW_PF, data); Fwindow += start; } /* * just as a general service, I save here the free energy of the windows * no output is generated, however,... */ if ((j >= winSize) && (options & VRNA_PROBS_WINDOW_UP)) { FLT_OR_DBL eee = 0.; eee = (FLT_OR_DBL)(-log(q[j - winSize + 1][j]) - winSize * log(pf_params->pf_scale)) * pf_params->kT / 1000.0; /* we could return this to the user via callback cb() if we were nice */ aux_arrays.pU[j][0] = eee; } /* rotate auxiliary arrays */ vrna_exp_E_ext_fast_rotate(aux_mx_el); vrna_exp_E_ml_fast_rotate(aux_mx_ml); } if (j > winSize) { compute_probs(vc, j, &aux_arrays, ulength, cb, data, options, &ov); if ((options & VRNA_PROBS_WINDOW_UP) && (j > winSize + MAXLOOP + 1)) compute_pU(vc, j - winSize - MAXLOOP - 1, ulength, &aux_arrays, cb, data, options); if (j > 2 * winSize + MAXLOOP + 1) { int start = j - (2 * winSize + MAXLOOP + 1); probability_correction(vc, start); if (options & VRNA_PROBS_WINDOW_BPP) { cb(pR[start], MIN2(start + winSize, n), start, winSize, VRNA_PROBS_WINDOW_BPP, data); } if (options & VRNA_PROBS_WINDOW_STACKP) { int start = j - (2 * winSize - MAXLOOP); if (start > 1) { FLT_OR_DBL *stack_probs = compute_stack_probabilities(vc, start); stack_probs -= start + 1; cb(stack_probs, MIN2(n - start + turn, pairSize), start, winSize, VRNA_PROBS_WINDOW_STACKP, data); stack_probs += start + 1; free(stack_probs); } } rotate_dp_matrices(vc, j, options); rotate_constraints(vc, j, options); } } /* end if (do_backtrack) */ } /* end for j */ /* finish output */ if (options & VRNA_PROBS_WINDOW_UP) for (j = MAX2(1, n - MAXLOOP); j <= n; j++) compute_pU(vc, j, ulength, &aux_arrays, cb, data, options); for (j = MAX2(n - winSize - MAXLOOP, 1); j <= n; j++) { probability_correction(vc, j); if (options & VRNA_PROBS_WINDOW_BPP) { cb(pR[j], MIN2(j + winSize, n), j, winSize, VRNA_PROBS_WINDOW_BPP, data); } if ((options & VRNA_PROBS_WINDOW_STACKP) && j < n) { int start = j; if (start > 1) { FLT_OR_DBL *stack_probs = compute_stack_probabilities(vc, start); stack_probs -= start + 1; cb(stack_probs, MIN2(n - start + turn, pairSize), start, winSize, VRNA_PROBS_WINDOW_STACKP, data); stack_probs += start + 1; free(stack_probs); } } } if (ov > 0) { vrna_message_warning("vrna_probs_window: " "%d overflows occurred while backtracking;\n" "you might try a smaller pf_scale than %g\n", ov, pf_params->pf_scale); } free_dp_matrices(vc, options); free_helper_arrays(vc, ulength, &aux_arrays, options); /* free memory occupied by auxiliary arrays for fast exterior/multibranch loops */ vrna_exp_E_ml_fast_free(aux_mx_ml); vrna_exp_E_ext_fast_free(aux_mx_el); free(Fwindow); return 1; /* success */ } PRIVATE FLT_OR_DBL sc_contribution(vrna_fold_compound_t *vc, int i, int j, int k, int l) { FLT_OR_DBL q; vrna_sc_t *sc; q = 1.; sc = vc->sc; if (sc->exp_energy_up) q *= sc->exp_energy_up[i + 1][k - i - 1] * sc->exp_energy_up[l + 1][j - l - 1]; if (sc->exp_energy_bp_local) q *= sc->exp_energy_bp_local[i][j - i]; if ((sc->exp_energy_stack) && (i + 1 == k) && (l + 1 == j)) { q *= sc->exp_energy_stack[i] * sc->exp_energy_stack[k] * sc->exp_energy_stack[l] * sc->exp_energy_stack[j]; } if (sc->f) q *= sc->f(i, j, k, l, VRNA_DECOMP_PAIR_IL, sc->data); return q; } PRIVATE FLT_OR_DBL sc_dummy(vrna_fold_compound_t *vc, int i, int j, int k, int l) { return 1.; } PRIVATE void add_QI5_contribution(FLT_OR_DBL **QI5, int i, int j, FLT_OR_DBL q, FLT_OR_DBL qkl) { QI5[i][j] += q * qkl; } PRIVATE void add_QI5_dummy(FLT_OR_DBL **QI5, int i, int j, FLT_OR_DBL q, FLT_OR_DBL qkl) { return; } PRIVATE void compute_probs(vrna_fold_compound_t *vc, int j, helper_arrays *aux_arrays, int ulength, vrna_probs_window_callback *cb, void *data, unsigned int options, int *ov) { char **ptype; short *S1; int start_i, i, k, l, n, m, winSize, turn, type, type_2, tt, *rtype; FLT_OR_DBL *prml, *prm_l, *prm_l1, **pR, **QI5, **qmb, **q2l, **qb, **q, **qm, *scale, *expMLbase, expMLclosing, temp, prm_MLb, prmt1, prmt, *tmp, Qmax; double max_real; vrna_exp_param_t *pf_params; vrna_md_t *md; vrna_hc_t *hc; vrna_sc_t *sc; sc_int *sc_int_f; add_QI5 *add_QI5_f; max_real = (sizeof(FLT_OR_DBL) == sizeof(float)) ? FLT_MAX : DBL_MAX; prml = aux_arrays->prml; prm_l = aux_arrays->prm_l; prm_l1 = aux_arrays->prm_l1; n = vc->length; winSize = vc->window_size; S1 = vc->sequence_encoding; ptype = vc->ptype_local; pf_params = vc->exp_params; md = &(pf_params->model_details); turn = md->min_loop_size; rtype = &(md->rtype[0]); expMLclosing = pf_params->expMLclosing; scale = vc->exp_matrices->scale; expMLbase = vc->exp_matrices->expMLbase; hc = vc->hc; sc = vc->sc; pR = vc->exp_matrices->pR; QI5 = vc->exp_matrices->QI5; qmb = vc->exp_matrices->qmb; q2l = vc->exp_matrices->q2l; q = vc->exp_matrices->q_local; qb = vc->exp_matrices->qb_local; qm = vc->exp_matrices->qm_local; Qmax = 0; /* assign helper functions */ if (sc) sc_int_f = &sc_contribution; else sc_int_f = &sc_dummy; if (options & VRNA_PROBS_WINDOW_UP) add_QI5_f = &add_QI5_contribution; else add_QI5_f = &add_QI5_dummy; /* start recursion */ /* * i=j-winSize; * initialize multiloopfs */ for (k = j - winSize; k <= MIN2(n, j); k++) { prml[k] = 0; prm_l[k] = 0; /* prm_l1[k]=0; others stay */ } k = j - winSize; prm_l1[k] = 0; for (l = k + turn + 1; l <= MIN2(n, k + winSize - 1); l++) { int a; pR[k][l] = 0; /* set zero at start */ type = vrna_get_ptype_window(k, l + k, ptype); if (qb[k][l] == 0) continue; /* Exterior loop cases */ if (hc->matrix_local[k][l - k] & VRNA_CONSTRAINT_CONTEXT_EXT_LOOP) { for (a = MAX2(1, l - winSize + 2); a < MIN2(k, n - winSize + 2); a++) pR[k][l] += q[a][k - 1] * q[l + 1][a + winSize - 1] / q[a][a + winSize - 1]; if (l - k + 1 == winSize) { pR[k][l] += 1. / q[k][l]; } else { if (k + winSize - 1 <= n) /* k outermost */ pR[k][l] += q[l + 1][k + winSize - 1] / q[k][k + winSize - 1]; if (l - winSize + 1 >= 1) /* l outermost */ pR[k][l] += q[l - winSize + 1][k - 1] / q[l - winSize + 1][l]; } pR[k][l] *= vrna_exp_E_ext_stem(type, (k > 1) ? S1[k - 1] : -1, (l < n) ? S1[l + 1] : -1, pf_params); } if (hc->matrix_local[k][l - k] & VRNA_CONSTRAINT_CONTEXT_INT_LOOP_ENC) { FLT_OR_DBL ppp; type_2 = rtype[vrna_get_ptype_window(k, l + k, ptype)]; ppp = 0.; start_i = k - MAXLOOP - 1; if (start_i < l - winSize + 1) start_i = l - winSize + 1; if (start_i < 1) start_i = 1; int u1 = 0; short sk1, sl1, si1; sk1 = S1[k - 1]; sl1 = S1[l + 1]; for (i = k - 1; i >= start_i; i--, u1++) { int max_m = i + winSize - 1; if (hc->up_int[i + 1] < u1) break; si1 = S1[i + 1]; if (max_m > l + MAXLOOP - u1 + 1) max_m = l + MAXLOOP - u1 + 1; if (max_m > n) max_m = n; for (m = l + 1; m <= max_m; m++) { int u2 = m - l - 1; if (hc->up_int[l + 1] < u2) break; if (hc->matrix_local[i][m - i] & VRNA_CONSTRAINT_CONTEXT_INT_LOOP) { type = vrna_get_ptype_window(i, m + i, ptype); if (pR[i][m] > 0) { temp = pR[i][m] * exp_E_IntLoop(u1, u2, type, type_2, si1, S1[m - 1], sk1, sl1, pf_params) * sc_int_f(vc, i, m, k, l) * scale[u1 + u2 + 2]; add_QI5_f(QI5, i, k - i - 1, temp, qb[k][l]); add_QI5_f(QI5, l, m - l - 1, temp, qb[k][l]); ppp += temp; } } } } pR[k][l] += ppp; } } /* 3. bonding k,l as substem of multi-loop enclosed by i,m */ prm_MLb = 0.; if (k > 1) { /* sonst nix! */ for (l = MIN2(n - 1, k + winSize - 2); l >= k + turn + 1; l--) { FLT_OR_DBL ppp; /* opposite direction */ m = l + 1; prmt = prmt1 = 0.0; for (i = MAX2(1, l - winSize + 2); i < k - 1 /* turn */; i++) { if (hc->matrix_local[i][m - i] & VRNA_CONSTRAINT_CONTEXT_MB_LOOP) { tt = rtype[vrna_get_ptype_window(i, m + i, ptype)]; ppp = pR[i][m] * exp_E_MLstem(tt, S1[m - 1], S1[i + 1], pf_params) * qm[i + 1][k - 1]; if (sc) if (sc->exp_energy_bp_local) ppp *= sc->exp_energy_bp_local[i][m - i]; prmt += ppp; } } prmt *= expMLclosing; prml[m] = prmt; if (hc->matrix_local[k - 1][m - k + 1] & VRNA_CONSTRAINT_CONTEXT_MB_LOOP) { tt = rtype[vrna_get_ptype_window(k - 1, m + k - 1, ptype)]; prmt1 = pR[k - 1][m] * expMLclosing * exp_E_MLstem(tt, S1[l], S1[k], pf_params); if (sc) if (sc->exp_energy_bp_local) prmt1 *= sc->exp_energy_bp_local[k - 1][m - k + 1]; } /* k-1 is unpaired */ if (hc->up_ml[k - 1]) { ppp = prm_l1[m] * expMLbase[1]; if (sc) if (sc->exp_energy_up) ppp *= sc->exp_energy_up[k - 1][1]; prm_l[m] = ppp + prmt1; } else { /* skip configuration where k-1 is unpaired */ prm_l[m] = prmt1; } /* m is unpaired */ if (hc->up_ml[m]) { ppp = prm_MLb * expMLbase[1]; if (sc) if (sc->exp_energy_up) ppp *= sc->exp_energy_up[m][1]; prm_MLb = ppp + prml[m]; } else { prm_MLb = prml[m]; } /* * same as: prm_MLb = 0; * for (i=n; i>k; i--) prm_MLb += prml[i]*expMLbase[k-i-1]; */ prml[m] = prml[m] + prm_l[m]; if (qb[k][l] == 0.) continue; if (hc->matrix_local[k][l - k] & VRNA_CONSTRAINT_CONTEXT_MB_LOOP_ENC) { tt = vrna_get_ptype_window(k, l + k, ptype); if (options & VRNA_PROBS_WINDOW_UP) { double dang; /* coefficient for computations of unpairedarrays */ dang = qb[k][l] * exp_E_MLstem(tt, (k > 1) ? S1[k - 1] : -1, (l < n) ? S1[l + 1] : -1, pf_params) * scale[2]; for (m = MIN2(k + winSize - 2, n); m >= l + 2; m--) { qmb[l][m - l - 1] += prml[m] * dang; q2l[l][m - l - 1] += (prml[m] - prm_l[m]) * dang; } } temp = prm_MLb; for (m = MIN2(k + winSize - 2, n); m >= l + 2; m--) temp += prml[m] * qm[l + 1][m - 1]; temp *= exp_E_MLstem(tt, (k > 1) ? S1[k - 1] : -1, (l < n) ? S1[l + 1] : -1, pf_params) * scale[2]; pR[k][l] += temp; } if (pR[k][l] > Qmax) { Qmax = pR[k][l]; if (Qmax > max_real / 10.) vrna_message_warning("P close to overflow: %d %d %g %g\n", i, m, pR[k][l], qb[k][l]); } if (pR[k][l] >= max_real) { (*ov)++; pR[k][l] = FLT_MAX; } } /* end for (l=..) */ } tmp = prm_l1; aux_arrays->prm_l1 = prm_l; aux_arrays->prm_l = tmp; } PRIVATE void probability_correction(vrna_fold_compound_t *vc, int i) { int j, howoften, pairdist, turn, n, winSize; FLT_OR_DBL **qb, **pR; n = vc->length; winSize = vc->window_size; turn = vc->exp_params->model_details.min_loop_size; howoften = 0; /* how many samples do we have for this pair */ qb = vc->exp_matrices->qb_local; pR = vc->exp_matrices->pR; for (j = i + turn; j < MIN2(i + winSize, n + 1); j++) { pairdist = (j - i + 1); /* 4cases */ howoften = MIN2(winSize - pairdist + 1, i); /* pairdist,start */ howoften = MIN2(howoften, n - j + 1); /* end */ howoften = MIN2(howoften, n - winSize + 1); /* windowsize */ pR[i][j] *= qb[i][j] / howoften; } return; } PRIVATE void make_ptypes(vrna_fold_compound_t *vc, int i) { /* make new entries in ptype array */ char **ptype; const short *S; int j, type, pairSize, n; vrna_md_t *md; ptype = vc->ptype_local; md = &(vc->exp_params->model_details); pairSize = md->max_bp_span; S = vc->sequence_encoding2; n = vc->length; for (j = i; j <= MIN2(i + pairSize, n); j++) { type = md->pair[S[i]][S[j]]; ptype[i][j] = (char)type; } return; } #if 0 PRIVATE vrna_ep_t * get_deppp(vrna_fold_compound_t *vc, vrna_ep_t *pl, int start) { /* compute dependent pair probabilities */ int i, j, count = 0; double tmp; vrna_ep_t *temp; char **ptype; short *S1; FLT_OR_DBL **qb, *scale; int *rtype, turn, pairsize, length; vrna_exp_param_t *pf_params; S1 = vc->sequence_encoding; pf_params = vc->exp_params; ptype = vc->ptype_local; qb = vc->exp_matrices->qb_local; scale = vc->exp_matrices->scale; rtype = &(pf_params->model_details.rtype[0]); turn = pf_params->model_details.min_loop_size; pairsize = pf_params->model_details.max_bp_span; length = vc->length; temp = (vrna_ep_t *)vrna_alloc(pairsize * sizeof(vrna_ep_t)); /* holds temporary deppp */ for (j = start + turn; j < MIN2(start + pairsize, length); j++) { if ((qb[start][j] * qb[start - 1][(j + 1)]) > 10e-200) { int type = ptype[start - 1][j + 1]; int type_2 = rtype[(unsigned char)ptype[start][j]]; tmp = qb[start][j] / qb[start - 1][(j + 1)] * exp_E_IntLoop(0, 0, type, type_2, S1[start], S1[j], S1[start - 1], S1[j + 1], pf_params) * scale[2]; temp[count].i = start; temp[count].j = j; temp[count++].p = tmp; } } /* write it to list of deppps */ for (i = 0; pl[i].i != 0; i++); pl = (vrna_ep_t *)vrna_realloc(pl, (i + count + 1) * sizeof(vrna_ep_t)); for (j = 0; j < count; j++) { pl[i + j].i = temp[j].i; pl[i + j].j = temp[j].j; pl[i + j].p = temp[j].p; } pl[i + count].i = 0; pl[i + count].j = 0; pl[i + count].p = 0; free(temp); return pl; } #endif PRIVATE FLT_OR_DBL * compute_stack_probabilities(vrna_fold_compound_t *vc, int start) { /* compute dependent pair probabilities */ char **ptype; short *S1; int j, max_j, *rtype, turn, pairsize, length, type, type_2; FLT_OR_DBL **qb, *scale, *probs; double tmp; vrna_exp_param_t *pf_params; length = vc->length; S1 = vc->sequence_encoding; pf_params = vc->exp_params; ptype = vc->ptype_local; qb = vc->exp_matrices->qb_local; scale = vc->exp_matrices->scale; rtype = &(pf_params->model_details.rtype[0]); turn = pf_params->model_details.min_loop_size; pairsize = pf_params->model_details.max_bp_span; max_j = MIN2(start + pairsize, length) - 1; probs = (FLT_OR_DBL *)vrna_alloc(sizeof(FLT_OR_DBL) * (max_j - start + 1)); for (j = start + turn + 1; j <= max_j; j++) { if ((qb[start][j] * qb[start - 1][(j + 1)]) > 10e-200) { type = vrna_get_ptype_window(start - 1, j + 1 + start - 1, ptype); type_2 = rtype[vrna_get_ptype_window(start, j + start, ptype)]; tmp = qb[start][j] / qb[start - 1][(j + 1)] * exp_E_IntLoop(0, 0, type, type_2, S1[start], S1[j], S1[start - 1], S1[j + 1], pf_params) * scale[2]; probs[j - start - 1] = tmp; } } return probs; } /* * Here: Space for questions... */ PRIVATE void compute_pU(vrna_fold_compound_t *vc, int k, int ulength, helper_arrays *aux_arrays, vrna_probs_window_callback *cb, void *data, unsigned int options) { /* * here, we try to add a function computing all unpaired probabilities starting at some i, * going down to $unpaired, to be unpaired, i.e. a list with entries from 1 to unpaired for * every i, with the probability of a stretch of length x, starting at i-x+1, to be unpaired */ char **ptype; short *S1; int startu, i5, j3, len, obp, *rtype, turn, winSize, n, leftmost, rightmost, tt; FLT_OR_DBL expMLclosing, *expMLbase, **q, **qm, **qm2, *scale, **pR, **QI5, **q2l, **qmb; double qqq, temp, *QBE, *QBI, *QBM, *QBH, **pU, **pUO, **pUH, **pUI, **pUM; vrna_exp_param_t *pf_params; vrna_hc_t *hc; vrna_sc_t *sc; n = vc->length; winSize = vc->window_size; S1 = vc->sequence_encoding; pf_params = vc->exp_params; ptype = vc->ptype_local; rtype = &(pf_params->model_details.rtype[0]); scale = vc->exp_matrices->scale; q = vc->exp_matrices->q_local; qm = vc->exp_matrices->qm_local; qm2 = vc->exp_matrices->qm2_local; expMLbase = vc->exp_matrices->expMLbase; expMLclosing = pf_params->expMLclosing; pR = vc->exp_matrices->pR; QI5 = vc->exp_matrices->QI5; q2l = vc->exp_matrices->q2l; qmb = vc->exp_matrices->qmb; turn = pf_params->model_details.min_loop_size; hc = vc->hc; sc = vc->sc; pU = aux_arrays->pU; pUO = aux_arrays->pUO; pUH = aux_arrays->pUH; pUI = aux_arrays->pUI; pUM = aux_arrays->pUM; QBE = (double *)vrna_alloc((MAX2(ulength, MAXLOOP) + 2) * sizeof(double)); QBM = (double *)vrna_alloc((MAX2(ulength, MAXLOOP) + 2) * sizeof(double)); QBI = (double *)vrna_alloc((MAX2(ulength, MAXLOOP) + 2) * sizeof(double)); QBH = (double *)vrna_alloc((MAX2(ulength, MAXLOOP) + 2) * sizeof(double)); /* * first, we will * for k<=ulength, pU[k][k]=0, because no bp can enclose it */ /* compute pu[k+ulength][ulength] */ for (i5 = MAX2(k + ulength - winSize + 1, 1); i5 <= k; i5++) { for (j3 = k + ulength + 1; j3 <= MIN2(n, i5 + winSize - 1); j3++) { /* Multiloops */ if (hc->matrix_local[i5][j3 - i5] & VRNA_CONSTRAINT_CONTEXT_MB_LOOP) { tt = rtype[vrna_get_ptype_window(i5, j3 + i5, ptype)]; temp = 0.; /* * (.. >-----|..........) * i5 j j+ulength j3 */ /* (..{}{}-----|......) */ if ((hc->up_ml[k + 1] >= j3 - k - 1) && (i5 < k)) { qqq = qm2[i5 + 1][k] * expMLbase[j3 - k - 1]; if (sc) { if (sc->exp_energy_up) qqq *= sc->exp_energy_up[k + 1][j3 - k - 1]; if (sc->f) qqq *= sc->f(i5, j3, i5 + 1, k, VRNA_DECOMP_PAIR_ML, sc->data); } temp += qqq; } /* (..|-----|{}{}) */ if ((hc->up_ml[i5 + 1] >= k + ulength - i5) && (j3 - 1 > k + ulength)) { qqq = qm2[k + ulength + 1][j3 - 1] * expMLbase[k + ulength - i5]; if (sc) { if (sc->exp_energy_up) qqq *= sc->exp_energy_up[i5 + 1][k + ulength - i5]; if (sc->f) qqq *= sc->f(i5, j3, k + ulength + 1, j3, VRNA_DECOMP_PAIR_ML, sc->data); } temp += qqq; } /* ({}|-----|{}) */ if ((hc->up_ml[k + 1] >= ulength) && (i5 < k) && (j3 - 1 > k + ulength)) { qqq = qm[i5 + 1][k] * qm[k + ulength + 1][j3 - 1] * expMLbase[ulength]; if (sc) { if (sc->exp_energy_up) qqq *= sc->exp_energy_up[k + 1][ulength]; if (sc->f) qqq *= sc->f(i5, j3, k, k + ulength + 1, VRNA_DECOMP_PAIR_ML_OUTSIDE, sc->data); } temp += qqq; } /* add dangles, multloopclosing etc. */ qqq = exp_E_MLstem(tt, S1[j3 - 1], S1[i5 + 1], pf_params) * scale[2] * expMLclosing; if (sc) if (sc->exp_energy_bp_local) qqq *= sc->exp_energy_bp_local[i5][j3 - i5]; temp *= qqq; pU[k + ulength][ulength] += temp * pR[i5][j3]; if (options & VRNA_PROBS_WINDOW_UP_SPLIT) pUM[k + ulength][ulength] += temp * pR[i5][j3]; } /* add hairpins */ if (hc->matrix_local[i5][j3 - i5] & VRNA_CONSTRAINT_CONTEXT_HP_LOOP) { temp = vrna_exp_E_hp_loop(vc, i5, j3); pU[k + ulength][ulength] += temp * pR[i5][j3]; if (options & VRNA_PROBS_WINDOW_UP_SPLIT) pUH[k + ulength][ulength] += temp * pR[i5][j3]; } } } /* Add Interior loop contribution to QBE (and QBI) */ temp = 0.; for (len = winSize; len > MAX2(ulength, MAXLOOP); len--) temp += QI5[k][len]; for (; len > 0; len--) { temp += QI5[k][len]; QBI[len] += temp; QBE[len] += temp; } /* Add Hairpin loop contribution to QBE (and QBH) */ temp = 0.; for (obp = MIN2(n, k + winSize - 1); obp > k + ulength; obp--) temp += pR[k][obp] * vrna_exp_E_hp_loop(vc, k, obp); for (obp = MIN2(n, MIN2(k + winSize - 1, k + ulength)); obp > k + 1; obp--) { temp += pR[k][obp] * vrna_exp_E_hp_loop(vc, k, obp); QBH[obp - k - 1] += temp; QBE[obp - k - 1] += temp; } /* * Add up Multiloopterms qmb[l][m]+=prml[m]*dang; * q2l[l][m]+=(prml[m]-prm_l[m])*dang; */ temp = 0.; /* add (()()____) type cont. to I3 */ if (sc && sc->exp_energy_up) { for (len = winSize; len >= ulength; len--) if (hc->up_ml[k + 1] >= len) { temp += q2l[k][len] * expMLbase[len] * sc->exp_energy_up[k + 1][len]; } for (; len > 0; len--) { if (hc->up_ml[k + 1] >= len) { temp += q2l[k][len] * expMLbase[len] * sc->exp_energy_up[k + 1][len]; } QBM[len] += temp; QBE[len] += temp; } } else { for (len = winSize; len >= ulength; len--) if (hc->up_ml[k + 1] >= len) temp += q2l[k][len] * expMLbase[len]; for (; len > 0; len--) { if (hc->up_ml[k + 1] >= len) temp += q2l[k][len] * expMLbase[len]; QBM[len] += temp; QBE[len] += temp; } } /* add (()___()) */ for (len = 1; len < ulength; len++) { if (hc->up_ml[k + 1] >= len) { for (obp = k + len + turn; obp <= MIN2(n, k + winSize - 1); obp++) { temp = qmb[k][obp - k - 1] * qm[k + len + 1 /*2*/][obp - 1] * expMLbase[len]; if (sc) if (sc->exp_energy_up) temp *= sc->exp_energy_up[k + 1][len]; QBM[len] += temp; QBE[len] += temp; } } } /* add (___()()) */ for (len = 1; len < ulength; len++) { if (hc->up_ml[k + 1] >= len) { for (obp = k + len + turn + turn; obp <= MIN2(n, k + winSize - 1); obp++) { if (hc->matrix_local[k][obp - k] & VRNA_CONSTRAINT_CONTEXT_MB_LOOP) { tt = rtype[vrna_get_ptype_window(k, obp + k, ptype)]; temp = exp_E_MLstem(tt, S1[obp - 1], S1[k + 1], pf_params) * scale[2] * expMLbase[len] * expMLclosing * pR[k][obp] * qm2[k + len + 1][obp - 1]; /* k:obp */ if (sc) { if (sc->exp_energy_up) temp *= sc->exp_energy_up[k + 1][len]; if (sc->exp_energy_bp) temp *= sc->exp_energy_bp_local[k][obp - k]; } QBM[len] += temp; QBE[len] += temp; } } } } /* * After computing all these contributions in QBE[len], that k is paired * and the unpaired stretch is AT LEAST len long, we start to add that to * the old unpaired thingies; */ for (len = 1; len <= MIN2(MAX2(ulength, MAXLOOP), n - k); len++) pU[k + len][len] += pU[k + len][len + 1] + QBE[len]; if (options & VRNA_PROBS_WINDOW_UP_SPLIT) { for (len = 1; len <= MIN2(MAX2(ulength, MAXLOOP), n - k); len++) { pUH[k + len][len] += pUH[k + len][len + 1] + QBH[len]; pUM[k + len][len] += pUM[k + len][len + 1] + QBM[len]; pUI[k + len][len] += pUI[k + len][len + 1] + QBI[len]; } /* open chain */ if ((ulength >= winSize) && (k >= ulength) && (hc->up_ext[k - winSize + 1] >= winSize)) pUO[k][winSize] = scale[winSize] / q[k - winSize + 1][k]; } /* open chain */ if ((ulength >= winSize) && (k >= ulength) && (hc->up_ext[k - winSize + 1] >= winSize)) { if (sc && sc->exp_energy_up) { pU[k][winSize] = scale[winSize] * sc->exp_energy_up[k][winSize] / q[k - winSize + 1][k]; } else { pU[k][winSize] = scale[winSize] / q[k - winSize + 1][k]; } } /* * now the not enclosed by any base pair terms for whatever it is we do not need anymore... * ... which should be e.g; k, again */ for (startu = MIN2(ulength, k); startu > 0; startu--) { temp = 0.; /* check whether soft constraint unpaired contributions available */ if (sc && sc->exp_energy_up) { if (hc->up_ext[k - startu + 1] >= startu) { for (i5 = MAX2(1, k - winSize + 2); i5 <= MIN2(k - startu, n - winSize + 1); i5++) temp += q[i5][k - startu] * q[k + 1][i5 + winSize - 1] * scale[startu] * sc->exp_energy_up[k - startu + 1][startu] / q[i5][i5 + winSize - 1]; /* the 2 Cases where the borders are on the edge of the interval */ if ((k >= winSize) && (startu + 1 <= winSize)) { temp += q[k - winSize + 1][k - startu] * scale[startu] * sc->exp_energy_up[k - startu + 1][startu] / q[k - winSize + 1][k]; } if ((k <= n - winSize + startu) && (k - startu >= 0) && (k < n) && (startu + 1 <= winSize)) { temp += q[k + 1][k - startu + winSize] * scale[startu] * sc->exp_energy_up[k - startu + 1][startu] / q[k - startu + 1][k - startu + winSize]; } } } else { if (hc->up_ext[k - startu + 1] >= startu) { for (i5 = MAX2(1, k - winSize + 2); i5 <= MIN2(k - startu, n - winSize + 1); i5++) temp += q[i5][k - startu] * q[k + 1][i5 + winSize - 1] * scale[startu] / q[i5][i5 + winSize - 1]; /* the 2 Cases where the borders are on the edge of the interval */ if ((k >= winSize) && (startu + 1 <= winSize)) temp += q[k - winSize + 1][k - startu] * scale[startu] / q[k - winSize + 1][k]; if ((k <= n - winSize + startu) && (k - startu >= 0) && (k < n) && (startu + 1 <= winSize)) temp += q[k + 1][k - startu + winSize] * scale[startu] / q[k - startu + 1][k - startu + winSize]; } } /* Divide by number of possible windows */ leftmost = MAX2(1, k - winSize + 1); rightmost = MIN2(n - winSize + 1, k - startu + 1); pU[k][startu] += temp; pU[k][startu] /= (rightmost - leftmost + 1); if (options & VRNA_PROBS_WINDOW_UP_SPLIT) { pUO[k][startu] += temp; /* Do we want to make a distinction between those? */ pUO[k][startu] /= (rightmost - leftmost + 1); pUH[k][startu] /= (rightmost - leftmost + 1); pUI[k][startu] /= (rightmost - leftmost + 1); pUM[k][startu] /= (rightmost - leftmost + 1); } } free(QBE); free(QBI); free(QBH); free(QBM); /* call return callback */ return_pU(MIN2(ulength, k), k, ulength, aux_arrays, cb, data, options); return; } PRIVATE void print_bpp_callback(FLT_OR_DBL *pr, int size, int k, void *data) { int j; FILE *fp = ((default_cb_data *)data)->fp_bpp; FLT_OR_DBL cutoff = ((default_cb_data *)data)->bpp_cutoff; for (j = k + 1; j <= size; j++) { if (pr[j] < cutoff) continue; fprintf(fp, "%d %d %g\n", k, j, pr[j]); } } PRIVATE void store_bpp_callback(FLT_OR_DBL *pr, int size, int k, void *data) { int j; vrna_ep_t *pl = ((default_cb_data *)data)->bpp; unsigned int pl_size = ((default_cb_data *)data)->bpp_size; unsigned int pl_max_size = ((default_cb_data *)data)->bpp_max_size; FLT_OR_DBL cutoff = ((default_cb_data *)data)->bpp_cutoff; if (pl_max_size == 0) { /* init if necessary */ pl_max_size = 100; pl = (vrna_ep_t *)vrna_realloc(pl, sizeof(vrna_ep_t) * pl_max_size); } for (j = k + 1; j <= size; j++) { if (pr[j] < cutoff) continue; /* resize vrna_ep_t memory if necessary */ if (pl_size >= pl_max_size - 1) { pl_max_size *= 1.5; pl = (vrna_ep_t *)vrna_realloc(pl, sizeof(vrna_ep_t) * pl_max_size); } pl[pl_size].i = k; pl[pl_size].j = j; pl[pl_size].type = VRNA_PLIST_TYPE_BASEPAIR; pl[pl_size++].p = pr[j]; } /* mark end of vrna_ep_t */ pl[pl_size].i = 0; pl[pl_size].j = 0; pl[pl_size].type = VRNA_PLIST_TYPE_BASEPAIR; pl[pl_size].p = 0.; /* update data */ ((default_cb_data *)data)->bpp = pl; ((default_cb_data *)data)->bpp_size = pl_size; ((default_cb_data *)data)->bpp_max_size = pl_max_size; } #if 0 PRIVATE void store_stack_prob_callback(FLT_OR_DBL *pr, int size, int k, void *data) { int j; vrna_ep_t *pl = ((default_cb_data *)data)->stack_prob; unsigned int pl_size = ((default_cb_data *)data)->stack_prob_size; unsigned int pl_max_size = ((default_cb_data *)data)->stack_prob_max_size; FLT_OR_DBL cutoff = ((default_cb_data *)data)->bpp_cutoff; if (pl_max_size == 0) { /* init if necessary */ pl_max_size = 100; pl = (vrna_ep_t *)vrna_realloc(pl, sizeof(vrna_ep_t) * pl_max_size); } for (j = k + 1; j <= size; j++) { if (pr[j] < cutoff) continue; /* resize vrna_ep_t memory if necessary */ if (pl_size >= pl_max_size - 1) { pl_max_size *= 1.5; pl = (vrna_ep_t *)vrna_realloc(pl, sizeof(vrna_ep_t) * pl_max_size); } pl[pl_size].i = k; pl[pl_size].j = j; pl[pl_size].type = VRNA_PLIST_TYPE_BASEPAIR; pl[pl_size++].p = pr[j]; } /* mark end of vrna_ep_t */ pl[pl_size].i = 0; pl[pl_size].j = 0; pl[pl_size].type = VRNA_PLIST_TYPE_BASEPAIR; pl[pl_size].p = 0.; /* update data */ ((default_cb_data *)data)->stack_prob = pl; ((default_cb_data *)data)->stack_prob_size = pl_size; ((default_cb_data *)data)->stack_prob_max_size = pl_max_size; } #endif PRIVATE void print_pU_callback(double *pU, int size, int k, int ulength, unsigned int type, void *data) { if (type & VRNA_PROBS_WINDOW_UP) { int i; FILE *fp = ((default_cb_data *)data)->fp_pU; fprintf(fp, "%d\t", k); for (i = 1; i < size; i++) fprintf(fp, "%.7g\t", pU[i]); fprintf(fp, "%.7g", pU[size]); if ((type & VRNA_ANY_LOOP) == VRNA_ANY_LOOP) fprintf(fp, "\n"); else if (type & VRNA_EXT_LOOP) fprintf(fp, "\tE\n"); else if (type & VRNA_HP_LOOP) fprintf(fp, "\tH\n"); else if (type & VRNA_INT_LOOP) fprintf(fp, "\tI\n"); else if (type & VRNA_MB_LOOP) fprintf(fp, "\tM\n"); else vrna_message_warning("unknown loop type"); } } PRIVATE void store_pU_callback(double *pU, int size, int k, int ulength, unsigned int type, void *data) { int i; double **pU_storage = ((default_cb_data *)data)->pU; if ((type & VRNA_PROBS_WINDOW_UP) && ((type & VRNA_ANY_LOOP) == VRNA_ANY_LOOP)) { pU_storage[k] = (double *)vrna_alloc(sizeof(double) * (ulength + 1)); for (i = 1; i <= size; i++) pU_storage[k][i] = pU[i]; } } PRIVATE void backward_compat_callback(FLT_OR_DBL *pr, int pr_size, int i, int max, unsigned int type, void *data) { default_cb_data *d = (default_cb_data *)data; if (type & VRNA_PROBS_WINDOW_BPP) { if (d->bpp_print) print_bpp_callback(pr, pr_size, i, data); else store_bpp_callback(pr, pr_size, i, data); } else if (type & VRNA_PROBS_WINDOW_UP) { if (d->up_print) print_pU_callback(pr, pr_size, i, max, type, data); else store_pU_callback(pr, pr_size, i, max, type, data); } } #ifndef VRNA_DISABLE_BACKWARD_COMPATIBILITY /* *########################################### *# deprecated functions below # *########################################### */ PRIVATE void putoutpU_prob_old(double **pU, int length, int ulength, FILE *fp, int energies, vrna_exp_param_t *parameters); PRIVATE void putoutpU_prob_bin_old(double **pU, int length, int ulength, FILE *fp, int energies, vrna_exp_param_t *parameters); PRIVATE vrna_ep_t * wrap_pf_foldLP(char *sequence, int winSize, int pairSize, float cutoffb, double **pU, vrna_ep_t **dpp2, FILE *pUfp, FILE *spup, vrna_exp_param_t *parameters) { int ulength, r; vrna_fold_compound_t *vc; vrna_md_t md; default_cb_data data; vc = NULL; ulength = 0; /* * if present, extract model details from provided parameters variable, * to properly initialize the fold compound. Otherwise use default * settings taken from deprecated global variables */ if (parameters) vrna_md_copy(&md, &(parameters->model_details)); else set_model_details(&md); md.compute_bpp = 1; /* turn on base pair probability computations */ md.window_size = winSize; /* set size of sliding window */ md.max_bp_span = pairSize; /* set maximum base pair span */ vc = vrna_fold_compound(sequence, &md, VRNA_OPTION_DEFAULT | VRNA_OPTION_WINDOW); /* * if present, attach a copy of the parameters structure instead of the * default parameters but take care of re-setting it to (initialized) * model details */ free(vc->exp_params); if (parameters) { vrna_md_copy(&(parameters->model_details), &(vc->params->model_details)); vc->exp_params = vrna_exp_params_copy(parameters); } else { vc->exp_params = vrna_exp_params(&(vc->params->model_details)); } /* propagate global pf_scale into vc->exp_params */ vc->exp_params->pf_scale = pf_scale; if (backward_compat_compound && backward_compat) vrna_fold_compound_free(backward_compat_compound); backward_compat_compound = vc; backward_compat = 1; iindx = backward_compat_compound->iindx; /* for backward compatibility and Perl wrapper */ if (pU) ulength = (int)pU[0][0] + 0.49; data.fp_pU = pUfp; data.pU = pU; data.bpp_cutoff = (FLT_OR_DBL)cutoffb; data.fp_bpp = spup; data.bpp = NULL; data.bpp_max_size = 0; data.bpp_size = 0; data.stack_prob = NULL; data.stack_prob_max_size = 0; data.stack_prob_size = 0; data.bpp_print = (spup) ? 1 : 0; data.up_print = (pUfp) ? 1 : 0; unsigned int options = VRNA_PROBS_WINDOW_BPP; /* always compute base pair probabilities */ if (dpp2 && (*dpp2)) options |= VRNA_PROBS_WINDOW_STACKP; if (ulength > 0) options |= VRNA_PROBS_WINDOW_UP; r = vrna_probs_window(vc, ulength, options, &backward_compat_callback, (void *)&data); if (!r) return NULL; if (dpp2 && (*dpp2)) { data.stack_prob = (vrna_ep_t *)vrna_realloc(data.stack_prob, sizeof(vrna_ep_t) * (data.stack_prob_size + 1)); data.stack_prob[data.stack_prob_size].i = 0; data.stack_prob[data.stack_prob_size].j = 0; data.stack_prob[data.stack_prob_size].type = VRNA_PLIST_TYPE_BASEPAIR; data.stack_prob[data.stack_prob_size].p = 0; free(*dpp2); /* free already occupied memory */ *dpp2 = data.stack_prob; } if (!spup) { data.bpp = (vrna_ep_t *)vrna_realloc(data.bpp, sizeof(vrna_ep_t) * (data.bpp_size + 1)); data.bpp[data.bpp_size].i = 0; data.bpp[data.bpp_size].j = 0; data.bpp[data.bpp_size].type = VRNA_PLIST_TYPE_BASEPAIR; data.bpp[data.bpp_size].p = 0; return data.bpp; } else { return NULL; } } PUBLIC void init_pf_foldLP(int length) { /* DO NOTHING */ } PUBLIC void update_pf_paramsLP(int length) { if (backward_compat_compound && backward_compat) { vrna_md_t md; set_model_details(&md); vrna_exp_params_reset(backward_compat_compound, &md); /* compatibility with RNAup, may be removed sometime */ pf_scale = backward_compat_compound->exp_params->pf_scale; } } PUBLIC void update_pf_paramsLP_par(int length, vrna_exp_param_t *parameters) { if (backward_compat_compound && backward_compat) { vrna_md_t md; if (parameters) { vrna_exp_params_subst(backward_compat_compound, parameters); } else { set_model_details(&md); vrna_exp_params_reset(backward_compat_compound, &md); } /* compatibility with RNAup, may be removed sometime */ pf_scale = backward_compat_compound->exp_params->pf_scale; } } PUBLIC vrna_ep_t * pfl_fold(char *sequence, int winSize, int pairSize, float cutoffb, double **pU, vrna_ep_t **dpp2, FILE *pUfp, FILE *spup) { return wrap_pf_foldLP(sequence, winSize, pairSize, cutoffb, pU, dpp2, pUfp, spup, NULL); } PUBLIC vrna_ep_t * pfl_fold_par(char *sequence, int winSize, int pairSize, float cutoffb, double **pU, vrna_ep_t **dpp2, FILE *pUfp, FILE *spup, vrna_exp_param_t *parameters) { return wrap_pf_foldLP(sequence, winSize, pairSize, cutoffb, pU, dpp2, pUfp, spup, parameters); } PUBLIC void putoutpU_prob(double **pU, int length, int ulength, FILE *fp, int energies) { if (backward_compat_compound && backward_compat) putoutpU_prob_old(pU, length, ulength, fp, energies, backward_compat_compound->exp_params); else vrna_message_warning("putoutpU_prob: Not doing anything! First, run pfl_fold()!"); } PUBLIC void putoutpU_prob_par(double **pU, int length, int ulength, FILE *fp, int energies, vrna_exp_param_t *parameters) { if ((pU) && (fp) && (parameters)) putoutpU_prob_old(pU, length, ulength, fp, energies, parameters); } PRIVATE void putoutpU_prob_old(double **pU, int length, int ulength, FILE *fp, int energies, vrna_exp_param_t *parameters) { /* put out unpaireds */ int i, k; double temp, kT = parameters->kT / 1000.0; if (energies) fprintf(fp, "#opening energies\n #i$\tl="); else fprintf(fp, "#unpaired probabilities\n #i$\tl="); for (i = 1; i <= ulength; i++) fprintf(fp, "%d\t", i); fprintf(fp, "\n"); for (k = 1; k <= length; k++) { fprintf(fp, "%d\t", k); for (i = 1; i <= ulength; i++) { if (i > k) { fprintf(fp, "NA\t"); continue; } if (energies) temp = -log(pU[k][i]) * kT; else temp = pU[k][i]; fprintf(fp, "%.7g\t", temp); } fprintf(fp, "\n"); free(pU[k]); } fflush(fp); } PUBLIC void putoutpU_prob_bin(double **pU, int length, int ulength, FILE *fp, int energies) { if (backward_compat_compound && backward_compat) putoutpU_prob_bin_old(pU, length, ulength, fp, energies, backward_compat_compound->exp_params); else vrna_message_warning("putoutpU_prob_bin: Not doing anything! First, run pfl_fold()!"); } PUBLIC void putoutpU_prob_bin_par(double **pU, int length, int ulength, FILE *fp, int energies, vrna_exp_param_t *parameters) { if ((pU) && (fp) && (parameters)) putoutpU_prob_bin_old(pU, length, ulength, fp, energies, parameters); } PRIVATE void putoutpU_prob_bin_old(double **pU, int length, int ulength, FILE *fp, int energies, vrna_exp_param_t *parameters) { /* put out unpaireds */ int i, k, *p; double kT = parameters->kT / 1000.0; p = (int *)vrna_alloc(sizeof(int) * 1); /* write first line */ p[0] = ulength; /* u length */ fwrite(p, sizeof(int), 1, fp); p[0] = length; /* seq length */ fwrite(p, sizeof(int), 1, fp); for (k = 3; k <= (length + 20); k++) { /* all the other lines are set to 1000000 because we are at ulength=0 */ p[0] = 1000000; fwrite(p, sizeof(int), 1, fp); } /* data */ for (i = 1; i <= ulength; i++) { for (k = 1; k <= 11; k++) { /* write first ten entries to 1000000 */ p[0] = 1000000; fwrite(p, sizeof(int), 1, fp); } for (k = 1; k <= length; k++) { /* write data now */ if (i > k) { p[0] = 1000000; /* check if u > pos */ fwrite(p, sizeof(int), 1, fp); continue; } else { p[0] = (int)rint(100 * (-log(pU[k][i]) * kT)); fwrite(p, sizeof(int), 1, fp); } } for (k = 1; k <= 9; k++) { /* finish by writing the last 10 entries */ p[0] = 1000000; fwrite(p, sizeof(int), 1, fp); } } /* free pU array; */ for (k = 1; k <= length; k++) free(pU[k]); free(p); fflush(fp); } #endif
pmv-OpenMP-a.c
#include <stdlib.h> #include <stdio.h> #include <time.h> //#define PRINT_ALL #define VECTOR_GLOBAL //#define VECTOR_DYNAMIC #ifdef VECTOR_GLOBAL #define MAX 1073741824 //=2^10 double v[MAX], m[MAX][MAX], r[MAX]; #endif int main(int argc,char** argv){ if (argc<2){ printf("Faltan nº componentes del vector \n"); exit(-1); } struct timespec cgt1,cgt2; double ncgt; //para tiempo de ejecución int i, j; unsigned int N = atoi(argv[1]); // Máximo N =2^32 -1=4294967295 (sizeof(unsigned int) = 4 B) #ifdef VECTOR_GLOBAL if (N>MAX) N=MAX; #endif #ifdef VECTOR_DYNAMIC double *v, **m, *r; v = (double*) malloc(N*sizeof(double)); // malloc necesita el tamaño en bytes m = (double**) malloc(N*sizeof(double*)); //si no hay espacio suficiente malloc devuelve NULL for (i=0; i<N; i++) m[i] = (double*) malloc(N*sizeof(double)); r = (double*) malloc(N*sizeof(double)); if ((v==NULL) || (m==NULL) || (r==NULL)) { printf("Error en la reserva de espacio para los vectores\n"); exit(-2); } #endif //Inicializar vector y matriz #pragma omp parallel for for (i=0; i<N; i++) { v[i] = N*0.1+ i*0.1; for (j=0; j<N; j++) m[i][j] = v[i]*0.1+j*0.1; } //Comprobamos la incialización #ifdef PRINT_ALL printf(" Vector:\n"); for (i=0; i<N; i++) { printf("\t%f", v[i]); } printf("\n\n Matriz: \n"); for (i=0; i<N; i++) { for (j=0; j<N; j++) printf("\t%f", m[i][j]); printf("\n\n"); } #endif clock_gettime(CLOCK_REALTIME,&cgt1); //Calcular el producto int sum; #pragma omp parallel for private(j, sum) for (i=0; i<N; i++) { sum = 0; for (j=0; j<N; j++) sum += m[i][j]*v[j]; r[i] = sum; } clock_gettime(CLOCK_REALTIME,&cgt2); ncgt = (double) (cgt2.tv_sec - cgt1.tv_sec) + (double) ((cgt2.tv_nsec - cgt1.tv_nsec)/(1.e+9)); //Imprimir resultado del producto printf("\n Resultado:\n"); #ifdef PRINT_ALL for (i=0; i<N; i++) { printf("\t%f", r[i]); } printf("\n"); #else printf("Primer valor: %f \t Último valor: %f \n", r[0], r[N-1]); #endif printf("\n Tiempo de ejecución(s): %11.9f\n", ncgt); #ifdef VECTOR_DYNAMIC free(v); // libera el espacio reservado para v free(m); // libera el espacio reservado para m free(r); #endif return 0; }
numint_uniform_grid.c
/* Copyright 2014-2018 The PySCF Developers. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * * Fast numerical integration on uniform grids. * (See also cp2k multigrid algorithm) * * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <assert.h> #include <complex.h> #include "config.h" #include "cint.h" #include "np_helper/np_helper.h" #include "gto/grid_ao_drv.h" #include "vhf/fblas.h" #ifndef __USE_ISOC99 #define rint(x) (int)round(x) #endif #define PLAIN 0 #define HERMITIAN 1 #define ANTIHERMI 2 #define SYMMETRIC 3 #define OF_CMPLX 2 #define EIJCUTOFF 60 #define EXPMAX 700 #define EXPMIN -700 #define MAX_THREADS 256 #define PTR_EXPDROP 16 #define SQUARE(x) (*(x) * *(x) + *(x+1) * *(x+1) + *(x+2) * *(x+2)) double CINTsquare_dist(const double *r1, const double *r2); double CINTcommon_fac_sp(int l); static const int _LEN_CART[] = { 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136 }; static const int _CUM_LEN_CART[] = { 1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 286, 364, 455, 560, 680, 816, }; static int _MAX_RR_SIZE[] = { 1, 4, 12, 30, 60, 120, 210, 350, 560, 840, 1260, 1800, 2520, 3465, 4620, 6160, 8008, 10296, 13104, 16380, 20475, }; /* * WHEREX_IF_L_INC1 = [xyz2addr(x,y,z) for x,y,z in loopcart(L_MAX) if x > 0] * WHEREY_IF_L_INC1 = [xyz2addr(x,y,z) for x,y,z in loopcart(L_MAX) if y > 0] * WHEREZ_IF_L_INC1 = [xyz2addr(x,y,z) for x,y,z in loopcart(L_MAX) if z > 0] */ static const int _UPIDY[] = { 1, 3, 4, 6, 7, 8, 10, 11, 12, 13, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103, 105,106,107,108,109,110,111,112,113,114,115,116,117,118, 120,121,122,123,124,125,126,127,128,129,130,131,132,133,134, }; static const int _UPIDZ[] = { 2, 4, 5, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 20, 22, 23, 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104, 106,107,108,109,110,111,112,113,114,115,116,117,118,119, 121,122,123,124,125,126,127,128,129,130,131,132,133,134,135, }; #define WHEREX_IF_L_INC1(i) i #define WHEREY_IF_L_INC1(i) _UPIDY[i] #define WHEREZ_IF_L_INC1(i) _UPIDZ[i] #define STARTX_IF_L_DEC1(l) 0 #define STARTY_IF_L_DEC1(l) (((l)<2)?0:_LEN_CART[(l)-2]) #define STARTZ_IF_L_DEC1(l) (_LEN_CART[(l)-1]-1) void GTOplain_vrr2d_ket_inc1(double *out, const double *g, double *rirj, int li, int lj); /* (li+lj,0) => (li,lj) */ // Input g is used as buffer in the iterations. // Ensure size of g > _MAX_RR_SIZE[li+lj] static void _plain_vrr2d(double *out, double *g, double *gbuf2, int li, int lj, double *ri, double *rj) { const int nmax = li + lj; double *g00, *g01, *gswap, *pg00, *pg01; int row_01, col_01, row_00, col_00; int i, j; double rirj[3]; rirj[0] = ri[0] - rj[0]; rirj[1] = ri[1] - rj[1]; rirj[2] = ri[2] - rj[2]; g00 = gbuf2; g01 = g; for (j = 1; j < lj; j++) { gswap = g00; g00 = g01; g01 = gswap; pg00 = g00; pg01 = g01; for (i = li; i <= nmax-j; i++) { GTOplain_vrr2d_ket_inc1(pg01, pg00, rirj, i, j); row_01 = _LEN_CART[i]; col_01 = _LEN_CART[j]; row_00 = _LEN_CART[i ]; col_00 = _LEN_CART[j-1]; pg00 += row_00*col_00; pg01 += row_01*col_01; } } GTOplain_vrr2d_ket_inc1(out, g01, rirj, li, lj); } /* * rcut is the distance over which the integration (from rcut to infty) is * smaller than the required precision * integral ~= \int_{rcut}^infty r^{l+2} exp(-alpha r^2) dr * * * if l is odd: * integral = \sum_n (l+1)!!/(l+3-2n)!! * rcut^{l+3-2n}/(2 alpha)^n * * exp(-alpha {rcut}^2) * * * elif l is even and rcut > 1: * integral < [\sum_{n<=l/2+1} (l+1)!!/(l+3-2n)!! * rcut^{l+3-2n}/(2 alpha)^n * + 1/(2 alpha)^(l/2+2)] * exp(-alpha {rcut}^2) * * * elif l is even and rcut < 1: * integral < [\sum_{n<=l/2+1} (l+1)!!/(l+3-2n)!! * rcut^{l+3-2n}/(2 alpha)^n] * exp(-alpha {rcut}^2) * + (l+1)!! / (2 alpha)^{l/2+1} * \sqrt(pi/alpha)/2 */ static double gto_rcut(double alpha, int l, double c, double log_prec) { double log_c = log(fabs(c)); double prod = 0; double r = 10.; double log_2a = log(2*alpha); double log_r = log(r); if (2*log_r + log_2a > 1) { // r^2 >~ 3/(2a) prod = (l+1) * log_r - log_2a; } else { prod = -(l+4)/2 * log_2a; } //log_r = .5 * (prod / alpha); //if (2*log_r + log_2a > 1) { // prod = (l+1) * log_r - log_2a; //} else { // prod = -(l+4)/2 * log_2a; //} prod += log_c - log_prec; if (prod < alpha) { // if rcut < 1, estimating based on exp^{-a*rcut^2} prod = log_c - log_prec; } if (prod > 0) { r = sqrt(prod / alpha); } else { r = 0; } return r; } static int _has_overlap(int nx0, int nx1, int nx_per_cell) { return nx0 < nx1 + 3; } static int _num_grids_on_x(int nimgx, int nx0, int nx1, int nx_per_cell) { int ngridx; if (nimgx == 1) { ngridx = nx1 - nx0; } else if (nimgx == 2 && !_has_overlap(nx0, nx1, nx_per_cell)) { ngridx = nx1 - nx0 + nx_per_cell; } else { ngridx = nx_per_cell; } return ngridx; } static int _orth_components(double *xs_exp, int *img_slice, int *grid_slice, double a, double b, double cutoff, double xi, double xj, double ai, double aj, int periodic, int nx_per_cell, int topl, int offset, int submesh, double *cache) { double aij = ai + aj; double xij = (ai * xi + aj * xj) / aij; double heights_inv = b; double xij_frac = xij * heights_inv; double edge0 = xij_frac - cutoff * heights_inv; double edge1 = xij_frac + cutoff * heights_inv; if (edge0 == edge1) { // cutoff may be so small that it does not provide difference to edge0 and // edge1. When edge0 and edge1 are right on the edge of the box (== integer), // nimg0 may be equal to nimg1 and nimg can be 0. Skip this extreme condition. return 0; } int nimg0 = 0; int nimg1 = 1; // If submesh is not identical to mesh, it means the product of the basis // functions should be completely inside the unit cell. Only one image needs to // be considered. if (offset != 0 || submesh != nx_per_cell) { // |i> is the steep function and centered inside image 0. Moving |j> all around // will not change the center of |ij>. The periodic system can be treated as // non-periodic system so that only one image needs to be considered. nimg0 = (int)floor(xij_frac); nimg1 = nimg0 + 1; edge0 = MAX(edge0, nimg0); edge1 = MIN(edge1, nimg1); } else if (periodic) { nimg0 = (int)floor(edge0); nimg1 = (int)ceil (edge1); } int nimg = nimg1 - nimg0; int nmx0 = nimg0 * nx_per_cell; int nmx1 = nimg1 * nx_per_cell; int nmx = nmx1 - nmx0; int nx0 = (int)floor(edge0 * nx_per_cell); int nx1 = (int)ceil (edge1 * nx_per_cell); int nx0_edge; int nx1_edge; // to ensure nx0, nx1 being inside the unit cell if (periodic) { nx0 = (nx0 - nmx0) % nx_per_cell; nx1 = (nx1 - nmx0) % nx_per_cell; if (nx1 == 0) { nx1 = nx_per_cell; } } // If only 1 image is required, after drawing the grids to the unit cell // as above, the periodic system can be treated as a non-periodic // system, which requires [nx0:nx1] being inside submesh. It is // necessary because xij+/-cutoff may be out of the submesh for periodic // systems when offset and submesh are specified. if (nimg == 1) { nx0 = MIN(nx0, offset + submesh); nx0 = MAX(nx0, offset); nx1 = MIN(nx1, offset + submesh); nx1 = MAX(nx1, offset); nx0_edge = nx0; nx1_edge = nx1; } else { nx0_edge = 0; nx1_edge = nmx; } img_slice[0] = nimg0; img_slice[1] = nimg1; grid_slice[0] = nx0; grid_slice[1] = nx1; int ngridx = _num_grids_on_x(nimg, nx0, nx1, nx_per_cell); if (ngridx == 0) { return 0; } int i, m, l; double *px0; double *gridx = cache; double *xs_all = cache + nmx; if (nimg == 1) { xs_all = xs_exp; } int grid_close_to_xij = rint(xij_frac * nx_per_cell) - nmx0; grid_close_to_xij = MIN(grid_close_to_xij, nx1_edge); grid_close_to_xij = MAX(grid_close_to_xij, nx0_edge); double img0_x = a * nimg0; double dx = a / nx_per_cell; double base_x = img0_x + dx * grid_close_to_xij; double x0xij = base_x - xij; double _x0x0 = -aij * x0xij * x0xij; if (_x0x0 < EXPMIN) { return 0; } double _dxdx = -aij * dx * dx; double _x0dx = -2 * aij * x0xij * dx; double exp_dxdx = exp(_dxdx); double exp_2dxdx = exp_dxdx * exp_dxdx; double exp_x0dx = exp(_x0dx + _dxdx); double exp_x0x0 = exp(_x0x0); for (i = grid_close_to_xij; i < nx1_edge; i++) { xs_all[i] = exp_x0x0; exp_x0x0 *= exp_x0dx; exp_x0dx *= exp_2dxdx; } exp_x0dx = exp(_dxdx - _x0dx); exp_x0x0 = exp(_x0x0); for (i = grid_close_to_xij-1; i >= nx0_edge; i--) { exp_x0x0 *= exp_x0dx; exp_x0dx *= exp_2dxdx; xs_all[i] = exp_x0x0; } if (topl > 0) { double x0xi = img0_x - xi; for (i = nx0_edge; i < nx1_edge; i++) { gridx[i] = x0xi + i * dx; } for (l = 1; l <= topl; l++) { px0 = xs_all + (l-1) * nmx; for (i = nx0_edge; i < nx1_edge; i++) { px0[nmx+i] = px0[i] * gridx[i]; } } } if (nimg > 1) { for (l = 0; l <= topl; l++) { px0 = xs_all + l * nmx; for (i = 0; i < nx_per_cell; i++) { xs_exp[l*nx_per_cell+i] = px0[i]; } for (m = 1; m < nimg; m++) { px0 = xs_all + l * nmx + m*nx_per_cell; for (i = 0; i < nx_per_cell; i++) { xs_exp[l*nx_per_cell+i] += px0[i]; } } } } return ngridx; } static int _init_orth_data(double **xs_exp, double **ys_exp, double **zs_exp, int *img_slice, int *grid_slice, int *offset, int *submesh, int *mesh, int topl, int dimension, double cutoff, double ai, double aj, double *ri, double *rj, double *a, double *b, double *cache) { int l1 = topl + 1; *xs_exp = cache; *ys_exp = *xs_exp + l1 * mesh[0]; *zs_exp = *ys_exp + l1 * mesh[1]; int data_size = l1 * (mesh[0] + mesh[1] + mesh[2]); cache += data_size; int ngridx = _orth_components(*xs_exp, img_slice, grid_slice, a[0], b[0], cutoff, ri[0], rj[0], ai, aj, (dimension>=1), mesh[0], topl, offset[0], submesh[0], cache); if (ngridx == 0) { return 0; } int ngridy = _orth_components(*ys_exp, img_slice+2, grid_slice+2, a[4], b[4], cutoff, ri[1], rj[1], ai, aj, (dimension>=2), mesh[1], topl, offset[1], submesh[1], cache); if (ngridy == 0) { return 0; } int ngridz = _orth_components(*zs_exp, img_slice+4, grid_slice+4, a[8], b[8], cutoff, ri[2], rj[2], ai, aj, (dimension>=3), mesh[2], topl, offset[2], submesh[2], cache); if (ngridz == 0) { return 0; } return data_size; } static void _orth_ints(double *out, double *weights, int floorl, int topl, double fac, double *xs_exp, double *ys_exp, double *zs_exp, int *img_slice, int *grid_slice, int *offset, int *submesh, int *mesh, double *cache) { int l1 = topl + 1; int nimgx0 = img_slice[0]; int nimgx1 = img_slice[1]; int nimgy0 = img_slice[2]; int nimgy1 = img_slice[3]; int nimgz0 = img_slice[4]; int nimgz1 = img_slice[5]; int nimgx = nimgx1 - nimgx0; int nimgy = nimgy1 - nimgy0; int nimgz = nimgz1 - nimgz0; int nx0 = grid_slice[0]; int nx1 = grid_slice[1]; int ny0 = grid_slice[2]; int ny1 = grid_slice[3]; int nz0 = grid_slice[4]; int nz1 = grid_slice[5]; int ngridx = _num_grids_on_x(nimgx, nx0, nx1, mesh[0]); int ngridy = _num_grids_on_x(nimgy, ny0, ny1, mesh[1]); //int ngridz = _num_grids_on_x(nimgz, nz0, nz1, mesh[2]); const char TRANS_N = 'N'; const double D0 = 0; const double D1 = 1; int xcols = mesh[1] * mesh[2]; int ycols = mesh[2]; double *weightyz = cache; double *weightz = weightyz + l1*xcols; double *pz, *pweightz; double val; int lx, ly, lz; int l, i, n; //TODO: optimize the case in which nimgy << mesh[1] and nimgz << mesh[2] if (nimgx == 1) { dgemm_(&TRANS_N, &TRANS_N, &xcols, &l1, &ngridx, &fac, weights+nx0*xcols, &xcols, xs_exp+nx0, mesh, &D0, weightyz, &xcols); } else if (nimgx == 2 && !_has_overlap(nx0, nx1, mesh[0])) { dgemm_(&TRANS_N, &TRANS_N, &xcols, &l1, &nx1, &fac, weights, &xcols, xs_exp, mesh, &D0, weightyz, &xcols); ngridx = mesh[0] - nx0; dgemm_(&TRANS_N, &TRANS_N, &xcols, &l1, &ngridx, &fac, weights+nx0*xcols, &xcols, xs_exp+nx0, mesh, &D1, weightyz, &xcols); } else { dgemm_(&TRANS_N, &TRANS_N, &xcols, &l1, mesh, &fac, weights, &xcols, xs_exp, mesh, &D0, weightyz, &xcols); } if (nimgy == 1) { for (lx = 0; lx <= topl; lx++) { dgemm_(&TRANS_N, &TRANS_N, &ycols, &l1, &ngridy, &D1, weightyz+lx*xcols+ny0*ycols, &ycols, ys_exp+ny0, mesh+1, &D0, weightz+lx*l1*ycols, &ycols); // call _orth_dot_z if ngridz << nimgz } } else if (nimgy == 2 && !_has_overlap(ny0, ny1, mesh[1])) { ngridy = mesh[1] - ny0; for (lx = 0; lx <= topl; lx++) { dgemm_(&TRANS_N, &TRANS_N, &ycols, &l1, &ny1, &D1, weightyz+lx*xcols, &ycols, ys_exp, mesh+1, &D0, weightz+lx*l1*ycols, &ycols); dgemm_(&TRANS_N, &TRANS_N, &ycols, &l1, &ngridy, &D1, weightyz+lx*xcols+ny0*ycols, &ycols, ys_exp+ny0, mesh+1, &D1, weightz+lx*l1*ycols, &ycols); // call _orth_dot_z if ngridz << nimgz } } else { for (lx = 0; lx <= topl; lx++) { dgemm_(&TRANS_N, &TRANS_N, &ycols, &l1, mesh+1, &D1, weightyz+lx*xcols, &ycols, ys_exp, mesh+1, &D0, weightz+lx*l1*ycols, &ycols); } } if (nimgz == 1) { for (n = 0, l = floorl; l <= topl; l++) { for (lx = l; lx >= 0; lx--) { for (ly = l - lx; ly >= 0; ly--, n++) { lz = l - lx - ly; pz = zs_exp + lz * mesh[2]; pweightz = weightz + (lx * l1 + ly) * mesh[2]; val = 0; for (i = nz0; i < nz1; i++) { val += pweightz[i] * pz[i]; } out[n] = val; } } } } else if (nimgz == 2 && !_has_overlap(nz0, nz1, mesh[2])) { for (n = 0, l = floorl; l <= topl; l++) { for (lx = l; lx >= 0; lx--) { for (ly = l - lx; ly >= 0; ly--, n++) { lz = l - lx - ly; pz = zs_exp + lz * mesh[2]; pweightz = weightz + (lx * l1 + ly) * mesh[2]; val = 0; for (i = 0; i < nz1; i++) { val += pweightz[i] * pz[i]; } for (i = nz0; i < mesh[2]; i++) { val += pweightz[i] * pz[i]; } out[n] = val; } } } } else { for (n = 0, l = floorl; l <= topl; l++) { for (lx = l; lx >= 0; lx--) { for (ly = l - lx; ly >= 0; ly--, n++) { lz = l - lx - ly; pz = zs_exp + lz * mesh[2]; pweightz = weightz + (lx * l1 + ly) * mesh[2]; val = 0; for (i = 0; i < mesh[2]; i++) { val += pweightz[i] * pz[i]; } out[n] = val; } } } } } int NUMINTeval_lda_orth(double *weights, double *out, int comp, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int floorl = li; int topl = li + lj; int offset_g1d = _CUM_LEN_CART[floorl] - _LEN_CART[floorl]; int len_g3d = _CUM_LEN_CART[topl] - offset_g1d; double cutoff = gto_rcut(ai+aj, topl, fac, log_prec); double *g3d = cache; cache += len_g3d; int img_slice[6]; int grid_slice[6]; double *xs_exp, *ys_exp, *zs_exp; int data_size = _init_orth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, submesh, mesh, topl, dimension, cutoff, ai, aj, ri, rj, a, b, cache); if (data_size == 0) { return 0; } cache += data_size; _orth_ints(g3d, weights, floorl, topl, fac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); cache = g3d + _MAX_RR_SIZE[topl]; _plain_vrr2d(out, g3d, cache, li, lj, ri, rj); return 1; } static void _rr_nablax_i(double *out, double *li_up, double *li_down, int li, int lj, double ai) { int di = _LEN_CART[li]; int di1 = _LEN_CART[li+1]; int dj = _LEN_CART[lj]; int li_1 = li - 1; int i, j, lx, ly; double fac = -2 * ai; for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { out[di*j+i] += li_up[di1*j+WHEREX_IF_L_INC1(i)] * fac; } } if (li_1 >= 0) { di1 = _LEN_CART[li_1]; for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { //lz = li_1 - lx - ly; fac = lx + 1; for (j = 0; j < dj; j++) { out[di*j+WHEREX_IF_L_INC1(i)] += li_down[di1*j+i] * fac; } } } } } static void _rr_nablay_i(double *out, double *li_up, double *li_down, int li, int lj, double ai) { int di = _LEN_CART[li]; int di1 = _LEN_CART[li+1]; int dj = _LEN_CART[lj]; int li_1 = li - 1; int i, j, lx, ly; double fac = -2 * ai; for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { out[di*j+i] += li_up[di1*j+WHEREY_IF_L_INC1(i)] * fac; } } if (li_1 >= 0) { di1 = _LEN_CART[li_1]; for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { //lz = li_1 - lx - ly; fac = ly + 1; for (j = 0; j < dj; j++) { out[di*j+WHEREY_IF_L_INC1(i)] += li_down[di1*j+i] * fac; } } } } } static void _rr_nablaz_i(double *out, double *li_up, double *li_down, int li, int lj, double ai) { int di = _LEN_CART[li]; int di1 = _LEN_CART[li+1]; int dj = _LEN_CART[lj]; int li_1 = li - 1; int i, j, lx, ly, lz; double fac = -2 * ai; for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { out[di*j+i] += li_up[di1*j+WHEREZ_IF_L_INC1(i)] * fac; } } if (li_1 >= 0) { di1 = _LEN_CART[li_1]; for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { lz = li_1 - lx - ly; fac = lz + 1; for (j = 0; j < dj; j++) { out[di*j+WHEREZ_IF_L_INC1(i)] += li_down[di1*j+i] * fac; } } } } } static void _plain_vrr2d_updown(double *out_up, double *out_down, double *g, double *gbuf2, int li, int lj, double *ri, double *rj) { int nmax = li + 1 + lj; int li_1 = MAX(li - 1, 0); double *g00, *g01, *gswap, *pg00, *pg01; int row_01, col_01, row_00, col_00; int i, j; double rirj[3]; rirj[0] = ri[0] - rj[0]; rirj[1] = ri[1] - rj[1]; rirj[2] = ri[2] - rj[2]; g00 = gbuf2; g01 = g; for (j = 1; j < lj; j++) { gswap = g00; g00 = g01; g01 = gswap; pg00 = g00; pg01 = g01; for (i = li_1; i <= nmax-j; i++) { GTOplain_vrr2d_ket_inc1(pg01, pg00, rirj, i, j); row_01 = _LEN_CART[i]; col_01 = _LEN_CART[j]; row_00 = _LEN_CART[i ]; col_00 = _LEN_CART[j-1]; pg00 += row_00*col_00; pg01 += row_01*col_01; } } if (li == 0) { g01 += _LEN_CART[MAX(lj-1, 0)]; } else { GTOplain_vrr2d_ket_inc1(out_down, g01, rirj, li_1, lj); g01 += (_LEN_CART[li_1] + _LEN_CART[li]) * _LEN_CART[MAX(lj-1, 0)]; } GTOplain_vrr2d_ket_inc1(out_up, g01, rirj, li+1, lj); } int NUMINTeval_gga_orth(double *weights, double *out, int comp, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int floorl = MAX(li - 1, 0); int topl = li + 1 + lj; int di = _LEN_CART[li]; int dj = _LEN_CART[lj]; double cutoff = gto_rcut(ai+aj, topl, fac, log_prec); double *out_up = cache; double *out_down = out_up + _LEN_CART[li+1] * dj; double *g3d = out_down + di * dj; cache = g3d + _MAX_RR_SIZE[topl]; int img_slice[6]; int grid_slice[6]; double *xs_exp, *ys_exp, *zs_exp; int data_size = _init_orth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, submesh, mesh, topl, dimension, cutoff, ai, aj, ri, rj, a, b, cache); if (data_size == 0) { return 0; } cache += data_size; size_t ngrids = ((size_t)mesh[0]) * mesh[1] * mesh[2]; double *vx = weights + ngrids; double *vy = vx + ngrids; double *vz = vy + ngrids; _orth_ints(g3d, weights, li, li+lj, fac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); _plain_vrr2d(out, g3d, cache, li, lj, ri, rj); _orth_ints(g3d, vx, floorl, topl, fac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); _plain_vrr2d_updown(out_up, out_down, g3d, cache, li, lj, ri, rj); _rr_nablax_i(out, out_up, out_down, li, lj, ai); _orth_ints(g3d, vy, floorl, topl, fac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); _plain_vrr2d_updown(out_up, out_down, g3d, cache, li, lj, ri, rj); _rr_nablay_i(out, out_up, out_down, li, lj, ai); _orth_ints(g3d, vz, floorl, topl, fac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); _plain_vrr2d_updown(out_up, out_down, g3d, cache, li, lj, ri, rj); _rr_nablaz_i(out, out_up, out_down, li, lj, ai); return 1; } static int _MAX_AFFINE_SIZE[] = { 1, 8, 32, 108, 270, 640, 1280, 2500, 4375, 7560, 12096, 19208, 28812, 43008, 61440, 87480, }; /* * x = a00 x' + a10 y' + a20 z' * y = a01 x' + a11 y' + a21 z' * z = a02 x' + a12 y' + a22 z' * Given f(x',y',z') use the above equations to evaluate f(x,y,z) */ static void _affine_trans(double *out, double *int3d, double *a, int floorl, int topl, double *cache) { if (topl == 0) { out[0] = int3d[0]; return; } int lx, ly, lz, l, m, n, i; int l1, l1l1, l1l1l1, lll; double *old = int3d; double *new = cache + _MAX_AFFINE_SIZE[topl]; double *oldx, *oldy, *oldz, *newx, *tmp; double vx, vy, vz; if (floorl == 0) { out[0] = int3d[0]; out += 1; } for (m = 1, l = topl; m <= topl; m++, l--) { l1 = l + 1; l1l1 = l1 * l1; lll = l * l * l; l1l1l1 = l1l1 * l1; newx = new; // attach x for (i = STARTX_IF_L_DEC1(m); i < _LEN_CART[m-1]; i++) { oldx = old + i * l1l1l1 + l1l1; oldy = old + i * l1l1l1 + l1; oldz = old + i * l1l1l1 + 1; for (n = 0, lx = 0; lx < l; lx++) { for (ly = 0; ly < l; ly++) { for (lz = 0; lz < l; lz++, n++) { vx = oldx[lx*l1l1+ly*l1+lz]; vy = oldy[lx*l1l1+ly*l1+lz]; vz = oldz[lx*l1l1+ly*l1+lz]; newx[n] = vx * a[0] + vy * a[3] + vz * a[6]; } } } newx += lll; } // attach y for (i = STARTY_IF_L_DEC1(m); i < _LEN_CART[m-1]; i++) { oldx = old + i * l1l1l1 + l1l1; oldy = old + i * l1l1l1 + l1; oldz = old + i * l1l1l1 + 1; for (n = 0, lx = 0; lx < l; lx++) { for (ly = 0; ly < l; ly++) { for (lz = 0; lz < l; lz++, n++) { vx = oldx[lx*l1l1+ly*l1+lz]; vy = oldy[lx*l1l1+ly*l1+lz]; vz = oldz[lx*l1l1+ly*l1+lz]; newx[n] = vx * a[1] + vy * a[4] + vz * a[7]; } } } newx += lll; } // attach z i = STARTZ_IF_L_DEC1(m); oldx = old + i * l1l1l1 + l1l1; oldy = old + i * l1l1l1 + l1; oldz = old + i * l1l1l1 + 1; for (n = 0, lx = 0; lx < l; lx++) { for (ly = 0; ly < l; ly++) { for (lz = 0; lz < l; lz++, n++) { vx = oldx[lx*l1l1+ly*l1+lz]; vy = oldy[lx*l1l1+ly*l1+lz]; vz = oldz[lx*l1l1+ly*l1+lz]; newx[n] = vx * a[2] + vy * a[5] + vz * a[8]; } } } if (floorl <= m) { for (i = 0; i < _LEN_CART[m]; i++) { out[i] = new[i * lll]; } out += _LEN_CART[m]; } if (m == 1) { old = new; new = cache; } else { tmp = old; old = new; new = tmp; } } } static void _reverse_affine_trans(double *out3d, double *in, double *a, int floorl, int topl, double *cache) { if (topl == 0) { out3d[0] = in[0]; return; } int lx, ly, lz, l, m, n, i; int l1, l1l1, l1l1l1, lll; double *cart = in; double *old = cache; double *new = cache + _MAX_AFFINE_SIZE[topl]; double *oldx, *newx, *newy, *newz, *tmp; for (l = floorl; l <= topl; l++) { cart += _LEN_CART[l]; } for (l = 1, m = topl; l <= topl; l++, m--) { l1 = l + 1; l1l1 = l1 * l1; lll = l * l * l; l1l1l1 = l1l1 * l1; if (l == topl) { new = out3d; } for (n = 0; n < l1l1l1*_LEN_CART[m-1]; n++) { new[n] = 0; } if (floorl <= m) { cart -= _LEN_CART[m]; for (i = 0; i < _LEN_CART[m]; i++) { old[i * lll] = cart[i]; } } oldx = old; // attach x for (i = STARTX_IF_L_DEC1(m); i < _LEN_CART[m-1]; i++) { newx = new + i * l1l1l1 + l1l1; newy = new + i * l1l1l1 + l1; newz = new + i * l1l1l1 + 1; for (n = 0, lx = 0; lx < l; lx++) { for (ly = 0; ly < l; ly++) { for (lz = 0; lz < l; lz++, n++) { newx[lx*l1l1+ly*l1+lz] += a[0] * oldx[n]; newy[lx*l1l1+ly*l1+lz] += a[3] * oldx[n]; newz[lx*l1l1+ly*l1+lz] += a[6] * oldx[n]; } } } oldx += lll; } // attach y for (i = STARTY_IF_L_DEC1(m); i < _LEN_CART[m-1]; i++) { newx = new + i * l1l1l1 + l1l1; newy = new + i * l1l1l1 + l1; newz = new + i * l1l1l1 + 1; for (n = 0, lx = 0; lx < l; lx++) { for (ly = 0; ly < l; ly++) { for (lz = 0; lz < l; lz++, n++) { newx[lx*l1l1+ly*l1+lz] += a[1] * oldx[n]; newy[lx*l1l1+ly*l1+lz] += a[4] * oldx[n]; newz[lx*l1l1+ly*l1+lz] += a[7] * oldx[n]; } } } oldx += lll; } // attach z i = STARTZ_IF_L_DEC1(m); newx = new + i * l1l1l1 + l1l1; newy = new + i * l1l1l1 + l1; newz = new + i * l1l1l1 + 1; for (n = 0, lx = 0; lx < l; lx++) { for (ly = 0; ly < l; ly++) { for (lz = 0; lz < l; lz++, n++) { newx[lx*l1l1+ly*l1+lz] += a[2] * oldx[n]; newy[lx*l1l1+ly*l1+lz] += a[5] * oldx[n]; newz[lx*l1l1+ly*l1+lz] += a[8] * oldx[n]; } } } tmp = new; new = old; old = tmp; } if (floorl == 0) { out3d[0] = in[0]; } } static int _nonorth_components(double *xs_exp, int *img_slice, int *grid_slice, double *b, int periodic, int nx_per_cell, int topl, int offset, int submesh, double xi_frac, double xij_frac, double cutoff) { double heights_inv = sqrt(SQUARE(b)); double edge0 = xij_frac - cutoff * heights_inv; double edge1 = xij_frac + cutoff * heights_inv; if (edge0 == edge1) { // cutoff may be so small that it does not provide difference to edge0 and // edge1. When edge0 and edge1 are right on the edge of the box (== integer), // nimg0 may be equal to nimg1 and nimg can be 0. Skip this extreme condition. return 0; } int nimg0 = 0; int nimg1 = 1; // If submesh is not identical to mesh, it means the product of the basis // functions should be completely inside the unit cell. Only one image needs to // be considered. if (offset != 0 || submesh != nx_per_cell) { // |i> is the steep function and centered inside image 0. Moving |j> all around // will not change the center of |ij>. The periodic system can be treated as // non-periodic system so that only one image needs to be considered. nimg0 = (int)floor(xij_frac); nimg1 = nimg0 + 1; edge0 = MAX(edge0, nimg0); edge1 = MIN(edge1, nimg1); } else if (periodic) { nimg0 = (int)floor(edge0); nimg1 = (int)ceil (edge1); } int nimg = nimg1 - nimg0; int nmx0 = nimg0 * nx_per_cell; int nx0 = (int)floor(edge0 * nx_per_cell); int nx1 = (int)ceil (edge1 * nx_per_cell); if (nimg == 1) { nx0 = MIN(nx0, nmx0 + offset + submesh); nx0 = MAX(nx0, nmx0 + offset); nx1 = MIN(nx1, nmx0 + offset + submesh); nx1 = MAX(nx1, nmx0 + offset); } img_slice[0] = nimg0; img_slice[1] = nimg1; grid_slice[0] = nx0; grid_slice[1] = nx1; int nx = nx1 - nx0; if (nx <= 0) { return 0; } int i, l; double x0; double dx = 1. / nx_per_cell; double *pxs_exp; for (i = 0; i < nx; i++) { xs_exp[i] = 1; } for (l = 1; l <= topl; l++) { pxs_exp = xs_exp + (l-1) * nx; x0 = nx0 * dx - xi_frac; for (i = 0; i < nx; i++, x0+=dx) { xs_exp[l*nx+i] = x0 * pxs_exp[i]; } } return nx; } static void _nonorth_dot_z(double *val, double *weights, int meshz, int nz0, int nz1, int grid_close_to_zij, double e_z0z0, double e_z0dz, double e_dzdz, double _z0dz, double _dzdz) { int iz, iz1; if (e_z0z0 == 0) { for (iz = 0; iz < nz1-nz0; iz++) { val[iz] = 0; } return; } double exp_2dzdz = e_dzdz * e_dzdz; double exp_z0z0, exp_z0dz; exp_z0z0 = e_z0z0; exp_z0dz = e_z0dz * e_dzdz; //:iz1 = grid_close_to_zij % meshz + meshz; //:for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) { //: if (iz1 >= meshz) { //: iz1 -= meshz; //: } //: val[iz] = weights[iz1] * exp_z0z0; //: exp_z0z0 *= exp_z0dz; //: exp_z0dz *= exp_2dzdz; //:} iz1 = grid_close_to_zij % meshz; if (iz1 < 0) { iz1 += meshz; } iz = grid_close_to_zij-nz0; while (iz+meshz-iz1 < nz1-nz0) { for (; iz1 < meshz; iz1++, iz++) { val[iz] = weights[iz1] * exp_z0z0; exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; } iz1 = 0; } for (; iz < nz1-nz0; iz++, iz1++) { val[iz] = weights[iz1] * exp_z0z0; exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; } exp_z0z0 = e_z0z0; if (e_z0dz != 0) { exp_z0dz = e_dzdz / e_z0dz; } else { exp_z0dz = exp(_dzdz - _z0dz); } //:iz1 = (grid_close_to_zij-1) % meshz; //:for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) { //: if (iz1 < 0) { //: iz1 += meshz; //: } //: exp_z0z0 *= exp_z0dz; //: exp_z0dz *= exp_2dzdz; //: val[iz] = weights[iz1] * exp_z0z0; //:} iz1 = (grid_close_to_zij-1) % meshz; if (iz1 < 0) { iz1 += meshz; } iz = grid_close_to_zij-nz0 - 1; while (iz-iz1 >= 0) { for (; iz1 >= 0; iz1--, iz--) { exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; val[iz] = weights[iz1] * exp_z0z0; } iz1 = meshz - 1; } for (; iz >= 0; iz--, iz1--) { exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; val[iz] = weights[iz1] * exp_z0z0; } } static void _nonorth_dot_z_1img(double *val, double *weights, int meshz, int nz0, int nz1, int grid_close_to_zij, double e_z0z0, double e_z0dz, double e_dzdz, double _z0dz, double _dzdz) { int iz, iz1; if (e_z0z0 == 0) { for (iz = 0; iz < nz1-nz0; iz++) { val[iz] = 0; } return; } double exp_2dzdz = e_dzdz * e_dzdz; double exp_z0z0, exp_z0dz; exp_z0z0 = e_z0z0; exp_z0dz = e_z0dz * e_dzdz; iz1 = grid_close_to_zij % meshz; if (iz1 < 0) { iz1 += meshz; } for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) { val[iz] = weights[iz1] * exp_z0z0; exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; } exp_z0z0 = e_z0z0; if (e_z0dz != 0) { exp_z0dz = e_dzdz / e_z0dz; } else { exp_z0dz = exp(_dzdz - _z0dz); } iz1 = (grid_close_to_zij-1) % meshz; if (iz1 < 0) { iz1 += meshz; } for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) { exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; val[iz] = weights[iz1] * exp_z0z0; } } static void _nonorth_ints(double *out, double *weights, double fac, double aij, int topl, int dimension, double *a, double *rij_frac, int *mesh, int *img_slice, int *grid_slice, double *xs_exp, double *ys_exp, double *zs_exp, double *cache) { int l1 = topl + 1; int l1l1 = l1 * l1; int l1l1l1 = l1l1 * l1; int nx0 = grid_slice[0]; int nx1 = grid_slice[1]; int ny0 = grid_slice[2]; int ny1 = grid_slice[3]; int nz0 = grid_slice[4]; int nz1 = grid_slice[5]; int ngridx = nx1 - nx0; int ngridy = ny1 - ny0; int ngridz = nz1 - nz0; //int nimgx0 = img_slice[0]; //int nimgx1 = img_slice[1]; //int nimgy0 = img_slice[2]; //int nimgy1 = img_slice[3]; int nimgz0 = img_slice[4]; int nimgz1 = img_slice[5]; //int nimgx = nimgx1 - nimgx0; //int nimgy = nimgy1 - nimgy0; int nimgz = nimgz1 - nimgz0; const char TRANS_T = 'T'; const char TRANS_N = 'N'; const double D0 = 0; const double D1 = 1; // aa = einsum('ij,kj->ik', a, a) //double aa[9]; //int n3 = 3; //dgemm_(&TRANS_T, &TRANS_N, &n3, &n3, &n3, // &aij, a, &n3, a, &n3, &D0, aa, &n3); double aa_xx = aij * (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); double aa_xy = aij * (a[0] * a[3] + a[1] * a[4] + a[2] * a[5]); double aa_xz = aij * (a[0] * a[6] + a[1] * a[7] + a[2] * a[8]); double aa_yy = aij * (a[3] * a[3] + a[4] * a[4] + a[5] * a[5]); double aa_yz = aij * (a[3] * a[6] + a[4] * a[7] + a[5] * a[8]); double aa_zz = aij * (a[6] * a[6] + a[7] * a[7] + a[8] * a[8]); int ix, iy, ix1, iy1, n; double dx = 1. / mesh[0]; double dy = 1. / mesh[1]; double dz = 1. / mesh[2]; double *cache_xyz = cache; double *weight_x = cache_xyz + l1l1l1; double *weight_z = weight_x + l1l1 * ngridx; double *weight_yz = weight_z + l1 * ngridz; double *pweights; //int grid_close_to_xij = rint(rij_frac[0] * mesh[0]); int grid_close_to_yij = rint(rij_frac[1] * mesh[1]); int grid_close_to_zij = rint(rij_frac[2] * mesh[2]); //grid_close_to_xij = MIN(grid_close_to_xij, nx1); //grid_close_to_xij = MAX(grid_close_to_xij, nx0); grid_close_to_yij = MIN(grid_close_to_yij, ny1); grid_close_to_yij = MAX(grid_close_to_yij, ny0); grid_close_to_zij = MIN(grid_close_to_zij, nz1); grid_close_to_zij = MAX(grid_close_to_zij, nz0); double img0_x = 0; double img0_y = 0; double img0_z = 0; double base_x = img0_x;// + dx * grid_close_to_xij; double base_y = img0_y + dy * grid_close_to_yij; double base_z = img0_z + dz * grid_close_to_zij; double x0xij = base_x - rij_frac[0]; double y0yij = base_y - rij_frac[1]; double z0zij = base_z - rij_frac[2]; double _dydy = -dy * dy * aa_yy; double _dzdz = -dz * dz * aa_zz; double _dydz = -dy * dz * aa_yz * 2; double exp_dydy = exp(_dydy); double exp_2dydy = exp_dydy * exp_dydy; double exp_dzdz = exp(_dzdz); double exp_dydz = exp(_dydz); double exp_dydz_i = (exp_dydz == 0) ? 0 : 1./exp_dydz; double x1xij, tmpx, tmpy, tmpz; double _xyz0xyz0, _xyz0dy, _xyz0dz, _z0dz; double exp_xyz0xyz0, exp_xyz0dz; double exp_y0dy, exp_z0z0, exp_z0dz; ix1 = nx0 % mesh[0] + mesh[0]; for (ix = nx0; ix < nx1; ix++, ix1++) { if (ix1 >= mesh[0]) { ix1 -= mesh[0]; } x1xij = x0xij + ix*dx; tmpx = x1xij * aa_xx + y0yij * aa_xy + z0zij * aa_xz; tmpy = x1xij * aa_xy + y0yij * aa_yy + z0zij * aa_yz; tmpz = x1xij * aa_xz + y0yij * aa_yz + z0zij * aa_zz; _xyz0xyz0 = -x1xij * tmpx - y0yij * tmpy - z0zij * tmpz; if (_xyz0xyz0 < EXPMIN) { // _xyz0dy (and _xyz0dz) can be very big, even greater than the effective range // of exp function (and produce inf). When exp_xyz0xyz0 is 0 and exp_xyz0dy is // inf, the product will be ill-defined. |_xyz0dy| should be smaller than // |_xyz0xyz0| in any situations. exp_xyz0xyz0 should dominate the product // exp_xyz0xyz0 * exp_xyz0dy. When exp_xyz0xyz0 is 0, the product should be 0. // All the rest exp products should be smaller than exp_xyz0xyz0 and can be // neglected. pweights = weight_x + (ix-nx0)*l1l1; for (n = 0; n < l1l1; n++) { pweights[n] = 0; } continue; } _xyz0dy = -2 * dy * tmpy; _xyz0dz = -2 * dz * tmpz; exp_xyz0xyz0 = fac * exp(_xyz0xyz0); exp_xyz0dz = exp(_xyz0dz); //exp_xyz0dy = exp(_xyz0dy); //exp_y0dy = exp_xyz0dy * exp_dydy; exp_y0dy = exp(_xyz0dy + _dydy); exp_z0z0 = exp_xyz0xyz0; exp_z0dz = exp_xyz0dz; _z0dz = _xyz0dz; iy1 = grid_close_to_yij % mesh[1] + mesh[1]; for (iy = grid_close_to_yij; iy < ny1; iy++, iy1++) { if (iy1 >= mesh[1]) { iy1 -= mesh[1]; } pweights = weights + (ix1 * mesh[1] + iy1) * mesh[2]; if (nimgz == 1) { _nonorth_dot_z_1img(weight_yz+(iy-ny0)*ngridz, pweights, mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } else { _nonorth_dot_z(weight_yz+(iy-ny0)*ngridz, pweights, mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } _z0dz += _dydz; exp_z0z0 *= exp_y0dy; exp_z0dz *= exp_dydz; exp_y0dy *= exp_2dydy; } exp_y0dy = exp(_dydy - _xyz0dy); exp_z0z0 = exp_xyz0xyz0; exp_z0dz = exp_xyz0dz; _z0dz = _xyz0dz; iy1 = (grid_close_to_yij-1) % mesh[1]; for (iy = grid_close_to_yij-1; iy >= ny0; iy--, iy1--) { if (iy1 < 0) { iy1 += mesh[1]; } exp_z0z0 *= exp_y0dy; exp_y0dy *= exp_2dydy; _z0dz -= _dydz; if (exp_dydz != 0) { exp_z0dz *= exp_dydz_i; } else { exp_z0dz = exp(_z0dz); } pweights = weights + (ix1 * mesh[1] + iy1) * mesh[2]; if (nimgz == 1) { _nonorth_dot_z_1img(weight_yz+(iy-ny0)*ngridz, pweights, mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } else { _nonorth_dot_z(weight_yz+(iy-ny0)*ngridz, pweights, mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } } dgemm_(&TRANS_N, &TRANS_N, &ngridz, &l1, &ngridy, &D1, weight_yz, &ngridz, ys_exp, &ngridy, &D0, weight_z, &ngridz); dgemm_(&TRANS_T, &TRANS_N, &l1, &l1, &ngridz, &D1, zs_exp, &ngridz, weight_z, &ngridz, &D0, weight_x+(ix-nx0)*l1l1, &l1); } dgemm_(&TRANS_N, &TRANS_N, &l1l1, &l1, &ngridx, &D1, weight_x, &l1l1, xs_exp, &ngridx, &D0, out, &l1l1); } static void _make_rij_frac(double *ri_frac, double *rij_frac, double *ri, double *rj, double ai, double aj, double *a, double *b) { double aij = ai + aj; double rij[3]; rij[0] = (ai * ri[0] + aj * rj[0]) / aij; rij[1] = (ai * ri[1] + aj * rj[1]) / aij; rij[2] = (ai * ri[2] + aj * rj[2]) / aij; // rij_frac = einsum('ij,j->ik', b, rij) rij_frac[0] = rij[0] * b[0] + rij[1] * b[1] + rij[2] * b[2]; rij_frac[1] = rij[0] * b[3] + rij[1] * b[4] + rij[2] * b[5]; rij_frac[2] = rij[0] * b[6] + rij[1] * b[7] + rij[2] * b[8]; ri_frac[0] = ri[0] * b[0] + ri[1] * b[1] + ri[2] * b[2]; ri_frac[1] = ri[0] * b[3] + ri[1] * b[4] + ri[2] * b[5]; ri_frac[2] = ri[0] * b[6] + ri[1] * b[7] + ri[2] * b[8]; } static int _init_nonorth_data(double **xs_exp, double **ys_exp, double **zs_exp, int *img_slice, int *grid_slice, int *offset, int *submesh, int *mesh, int topl, int dimension, double cutoff, double *a, double *b, double *ri_frac, double *rij_frac, double *cache) { int l1 = topl + 1; *xs_exp = cache; int ngridx = _nonorth_components(*xs_exp, img_slice, grid_slice, b, (dimension>=1), mesh[0], topl, offset[0], submesh[0], ri_frac[0], rij_frac[0], cutoff); if (ngridx == 0) { return 0; } *ys_exp = *xs_exp + l1 * ngridx; int ngridy = _nonorth_components(*ys_exp, img_slice+2, grid_slice+2, b+3, (dimension>=2), mesh[1], topl, offset[1], submesh[1], ri_frac[1], rij_frac[1], cutoff); if (ngridy == 0) { return 0; } *zs_exp = *ys_exp + l1 * ngridy; int ngridz = _nonorth_components(*zs_exp, img_slice+4, grid_slice+4, b+6, (dimension>=3), mesh[2], topl, offset[2], submesh[2], ri_frac[2], rij_frac[2], cutoff); if (ngridz == 0) { return 0; } int data_size = l1 * (ngridx + ngridy + ngridz); return data_size; } int NUMINTeval_lda_nonorth(double *weights, double *out, int comp, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int floorl = li; int topl = li + lj; int l1 = topl + 1; double aij = ai + aj; double cutoff = gto_rcut(aij, topl, fac, log_prec); int img_slice[6]; int grid_slice[6]; double ri_frac[3]; double rij_frac[3]; double *xs_exp, *ys_exp, *zs_exp; _make_rij_frac(ri_frac, rij_frac, ri, rj, ai, aj, a, b); int data_size = _init_nonorth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, mesh, mesh, topl, dimension, cutoff, a, b, ri_frac, rij_frac, cache); if (data_size == 0) { return 0; } cache += data_size; double *g3d = cache; double *buf = g3d + l1 * l1 * l1; cache = buf + _MAX_RR_SIZE[topl]; _nonorth_ints(g3d, weights, fac, aij, topl, dimension, a, rij_frac, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); _affine_trans(buf, g3d, a, floorl, topl, cache); _plain_vrr2d(out, buf, cache, li, lj, ri, rj); return 1; } int NUMINTeval_gga_nonorth(double *weights, double *out, int comp, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int floorl = MAX(li - 1, 0); int topl = li + 1 + lj; int l1 = topl + 1; double aij = ai + aj; double cutoff = gto_rcut(aij, topl, fac, log_prec); int img_slice[6]; int grid_slice[6]; double ri_frac[3]; double rij_frac[3]; double *xs_exp, *ys_exp, *zs_exp; _make_rij_frac(ri_frac, rij_frac, ri, rj, ai, aj, a, b); int data_size = _init_nonorth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, mesh, mesh, topl, dimension, cutoff, a, b, ri_frac, rij_frac, cache); if (data_size == 0) { return 0; } cache += data_size; int dj = _LEN_CART[lj]; double *g3d = cache; double *buf = g3d + l1 * l1 * l1; double *out_up = cache; double *out_down = out_up + _LEN_CART[li+1] * dj; cache = buf + _MAX_RR_SIZE[topl]; size_t ngrids = ((size_t)mesh[0]) * mesh[1] * mesh[2]; double *vx = weights + ngrids; double *vy = vx + ngrids; double *vz = vy + ngrids; _nonorth_ints(g3d, weights, fac, aij, li+lj, dimension, a, rij_frac, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); _affine_trans(buf, g3d, a, li, li+lj, cache); _plain_vrr2d(out, buf, cache, li, lj, ri, rj); _nonorth_ints(g3d, vx, fac, aij, topl, dimension, a, rij_frac, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); _affine_trans(buf, g3d, a, floorl, topl, cache); _plain_vrr2d_updown(out_up, out_down, buf, cache, li, lj, ri, rj); _rr_nablax_i(out, out_up, out_down, li, lj, ai); _nonorth_ints(g3d, vy, fac, aij, topl, dimension, a, rij_frac, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); _affine_trans(buf, g3d, a, floorl, topl, cache); _plain_vrr2d_updown(out_up, out_down, buf, cache, li, lj, ri, rj); _rr_nablay_i(out, out_up, out_down, li, lj, ai); _nonorth_ints(g3d, vz, fac, aij, topl, dimension, a, rij_frac, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); _affine_trans(buf, g3d, a, floorl, topl, cache); _plain_vrr2d_updown(out_up, out_down, buf, cache, li, lj, ri, rj); _rr_nablaz_i(out, out_up, out_down, li, lj, ai); return 1; } static void _apply_ints(int (*eval_ints)(), double *weights, double *mat, size_t *dims, int comp, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, int *shls, int *atm, int *bas, double *env, double *cache) { int i_sh = shls[0]; int j_sh = shls[1]; int li = bas(ANG_OF, i_sh); int lj = bas(ANG_OF, j_sh); double *ri = env + atm(PTR_COORD, bas(ATOM_OF, i_sh)); double *rj = env + atm(PTR_COORD, bas(ATOM_OF, j_sh)); double ai = env[bas(PTR_EXP, i_sh)]; double aj = env[bas(PTR_EXP, j_sh)]; double ci = env[bas(PTR_COEFF, i_sh)]; double cj = env[bas(PTR_COEFF, j_sh)]; double aij = ai + aj; double rrij = CINTsquare_dist(ri, rj); double eij = (ai * aj / aij) * rrij; if (eij > EIJCUTOFF) { return; } fac *= exp(-eij) * ci * cj * CINTcommon_fac_sp(li) * CINTcommon_fac_sp(lj); if (fac < env[PTR_EXPDROP]) { return; } int di = _LEN_CART[li]; int dj = _LEN_CART[lj]; double *out = cache; cache += comp * di * dj; int value = (*eval_ints)(weights, out, comp, li, lj, ai, aj, ri, rj, fac, log_prec, dimension, a, b, offset, submesh, mesh, cache); if (value != 0) { size_t naoi = dims[0]; size_t naoj = dims[1]; int i, j, ic; for (ic = 0; ic < comp; ic++) { for (j = 0; j < dj; j++) { for (i = 0; i < di; i++) { mat[j*naoi+i] += out[j*di+i]; } } mat += naoi * naoj; out += di * dj; } } } static int _nonorth_cache_size(int *mesh, int l) { int dcart = _LEN_CART[l]; int deriv = 1; int topl = l + l + deriv; int l1 = topl + 1; const int nimgs = 1; int cache_size = 0; cache_size += l1 * (mesh[0] + mesh[1] + mesh[2]) * nimgs; cache_size += mesh[1] * mesh[2]; // * nimgs * nimgs cache_size += l1 * mesh[2] * nimgs; cache_size += l1 * l1 * mesh[0]; cache_size = MAX(cache_size, _MAX_AFFINE_SIZE[topl]*2); cache_size += l1 * l1 * l1; cache_size += _MAX_RR_SIZE[topl]; return dcart*dcart + cache_size; } static int _max_cache_size(int (*fsize)(), int *shls_slice, int *bas, int *mesh) { int i, n; int i0 = MIN(shls_slice[0], shls_slice[2]); int i1 = MAX(shls_slice[1], shls_slice[3]); int cache_size = 0; for (i = i0; i < i1; i++) { n = (*fsize)(mesh, bas(ANG_OF, i)); cache_size = MAX(cache_size, n); } return cache_size+1000000; } static void shift_bas(double *env_loc, double *env, double *Ls, int ptr, int iL) { env_loc[ptr+0] = env[ptr+0] + Ls[iL*3+0]; env_loc[ptr+1] = env[ptr+1] + Ls[iL*3+1]; env_loc[ptr+2] = env[ptr+2] + Ls[iL*3+2]; } // Numerical integration for uncontracted Cartesian basis // F_mat needs to be initialized as 0 void NUMINT_fill2c(int (*eval_ints)(), double *weights, double *F_mat, int comp, int hermi, int *shls_slice, int *ao_loc, double log_prec, int dimension, int nimgs, double *Ls, double *a, double *b, int *offset, int *submesh, int *mesh, int *atm, int natm, int *bas, int nbas, double *env, int nenv) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int nish = ish1 - ish0; const int njsh = jsh1 - jsh0; const size_t naoi = ao_loc[ish1] - ao_loc[ish0]; const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; const int cache_size = _max_cache_size(_nonorth_cache_size, shls_slice, bas, mesh); if (dimension == 0) { nimgs = 1; } #pragma omp parallel { size_t ncij = comp * naoi * naoj; size_t nijsh = nish * njsh; size_t dims[] = {naoi, naoj}; size_t ijm; int ish, jsh, ij, m, i0, j0; int shls[2]; double *cache = malloc(sizeof(double) * cache_size); double *env_loc = malloc(sizeof(double)*nenv); NPdcopy(env_loc, env, nenv); int ptrxyz; #pragma omp for schedule(dynamic) for (ijm = 0; ijm < nimgs*nijsh; ijm++) { m = ijm / nijsh; ij = ijm % nijsh; ish = ij / njsh; jsh = ij % njsh; if (hermi != PLAIN && ish > jsh) { // fill up only upper triangle of F_mat continue; } ish += ish0; jsh += jsh0; shls[0] = ish; shls[1] = jsh; i0 = ao_loc[ish] - ao_loc[ish0]; j0 = ao_loc[jsh] - ao_loc[jsh0]; if (dimension != 0) { ptrxyz = atm(PTR_COORD, bas(ATOM_OF,jsh)); shift_bas(env_loc, env, Ls, ptrxyz, m); } _apply_ints(eval_ints, weights, F_mat+m*ncij+j0*naoi+i0, dims, comp, 1., log_prec, dimension, a, b, offset, submesh, mesh, shls, atm, bas, env_loc, cache); } free(cache); free(env_loc); } } /************************************************* * * rho * *************************************************/ void GTOreverse_vrr2d_ket_inc1(double *g01, double *g00, double *rirj, int li, int lj); /* (li,lj) => (li+lj,0) */ void GTOreverse_vrr2d_ket(double *g00, double *g01, int li, int lj, double *ri, double *rj) { int nmax = li + lj; double *out = g00; double *gswap, *pg00, *pg01; int row_01, col_01, row_00, col_00, row_g; int i, j, n; double rirj[3]; rirj[0] = ri[0] - rj[0]; rirj[1] = ri[1] - rj[1]; rirj[2] = ri[2] - rj[2]; for (j = lj; j > 0; j--) { col_01 = _LEN_CART[j]; col_00 = _LEN_CART[j-1]; row_g = _CUM_LEN_CART[nmax+1-j] - _CUM_LEN_CART[li] + _LEN_CART[li]; for (n = 0; n < row_g*col_00; n++) { g00[n] = 0; } pg00 = g00; pg01 = g01; for (i = li; i <= nmax-j; i++) { GTOreverse_vrr2d_ket_inc1(pg01, pg00, rirj, i, j); row_01 = _LEN_CART[i]; row_00 = _LEN_CART[i]; pg00 += row_00 * col_00; pg01 += row_01 * col_01; } gswap = g00; g00 = g01; g01 = gswap; } if (out != g01) { row_g = _CUM_LEN_CART[nmax] - _CUM_LEN_CART[li] + _LEN_CART[li]; for (n = 0; n < row_g; n++) { out[n] = g01[n]; } } } static void _cart_to_xyz(double *dm_xyz, double *dm_cart, int floorl, int topl, int l1) { int l1l1 = l1 * l1; int l, lx, ly, lz, n; for (n = 0, l = floorl; l <= topl; l++) { for (lx = l; lx >= 0; lx--) { for (ly = l - lx; ly >= 0; ly--, n++) { lz = l - lx - ly; dm_xyz[lx*l1l1+ly*l1+lz] += dm_cart[n]; } } } } static void _orth_rho(double *rho, double *dm_xyz, double fac, int topl, int *offset, int *submesh, int *mesh, int *img_slice, int *grid_slice, double *xs_exp, double *ys_exp, double *zs_exp, double *cache) { int l1 = topl + 1; int l1l1 = l1 * l1; int nimgx0 = img_slice[0]; int nimgx1 = img_slice[1]; int nimgy0 = img_slice[2]; int nimgy1 = img_slice[3]; int nimgz0 = img_slice[4]; int nimgz1 = img_slice[5]; int nimgx = nimgx1 - nimgx0; int nimgy = nimgy1 - nimgy0; int nimgz = nimgz1 - nimgz0; int nx0 = MAX(grid_slice[0], offset[0]); int nx1 = MIN(grid_slice[1], offset[0]+submesh[0]); int ny0 = MAX(grid_slice[2], offset[1]); int ny1 = MIN(grid_slice[3], offset[1]+submesh[1]); int nz0 = MAX(grid_slice[4], offset[2]); int nz1 = MIN(grid_slice[5], offset[2]+submesh[2]); int ngridx = _num_grids_on_x(nimgx, nx0, nx1, mesh[0]); int ngridy = _num_grids_on_x(nimgy, ny0, ny1, mesh[1]); int ngridz = _num_grids_on_x(nimgz, nz0, nz1, mesh[2]); if (ngridx == 0 || ngridy == 0 || ngridz == 0) { return; } const char TRANS_N = 'N'; const char TRANS_T = 'T'; const double D0 = 0; const double D1 = 1; int xcols = submesh[1] * submesh[2]; double *xyr = cache; double *xqr = xyr + l1l1 * submesh[2]; int i, l; if (nimgz == 1) { for (l = 0; l <= topl; l++) { for (i = offset[2]; i < nz0; i++) { zs_exp[l*mesh[2]+i] = 0; } for (i = nz1; i < offset[2]+submesh[2]; i++) { zs_exp[l*mesh[2]+i] = 0; } } } else if (nimgz == 2 && !_has_overlap(nz0, nz1, mesh[2])) { for (l = 0; l <= topl; l++) { for (i = nz1; i < nz0; i++) { zs_exp[l*mesh[2]+i] = 0; } } } dgemm_(&TRANS_N, &TRANS_N, submesh+2, &l1l1, &l1, &fac, zs_exp+offset[2], mesh+2, dm_xyz, &l1, &D0, xyr, submesh+2); if (nimgy == 1) { for (l = 0; l <= topl; l++) { for (i = 0; i < (ny0-offset[1])*submesh[2]; i++) { xqr[l*xcols+i] = 0; } for (i = (ny1-offset[1])*submesh[2]; i < xcols; i++) { xqr[l*xcols+i] = 0; } dgemm_(&TRANS_N, &TRANS_T, submesh+2, &ngridy, &l1, &D1, xyr+l*l1*submesh[2], submesh+2, ys_exp+ny0, mesh+1, &D0, xqr+l*xcols+(ny0-offset[1])*submesh[2], submesh+2); } } else if (nimgy == 2 && !_has_overlap(ny0, ny1, mesh[1])) { for (l = 0; l <= topl; l++) { ngridy = ny1 - offset[1]; dgemm_(&TRANS_N, &TRANS_T, submesh+2, &ngridy, &l1, &D1, xyr+l*l1*submesh[2], submesh+2, ys_exp+offset[1], mesh+1, &D0, xqr+l*xcols, submesh+2); for (i = (ny1-offset[1])*submesh[2]; i < (ny0-offset[1])*submesh[2]; i++) { xqr[l*xcols+i] = 0; } ngridy = offset[1] + submesh[1] - ny0; dgemm_(&TRANS_N, &TRANS_T, submesh+2, &ngridy, &l1, &D1, xyr+l*l1*submesh[2], submesh+2, ys_exp+ny0, mesh+1, &D0, xqr+l*xcols+(ny0-offset[1])*submesh[2], submesh+2); } } else { for (l = 0; l <= topl; l++) { dgemm_(&TRANS_N, &TRANS_T, submesh+2, submesh+1, &l1, &D1, xyr+l*l1*submesh[2], submesh+2, ys_exp+offset[1], mesh+1, &D0, xqr+l*xcols, submesh+2); } } if (nimgx == 1) { dgemm_(&TRANS_N, &TRANS_T, &xcols, &ngridx, &l1, &D1, xqr, &xcols, xs_exp+nx0, mesh, &D1, rho+(nx0-offset[0])*xcols, &xcols); } else if (nimgx == 2 && !_has_overlap(nx0, nx1, mesh[0])) { ngridx = nx1 - offset[2]; dgemm_(&TRANS_N, &TRANS_T, &xcols, &ngridx, &l1, &D1, xqr, &xcols, xs_exp+offset[0], mesh, &D1, rho, &xcols); ngridx = offset[0] + submesh[0] - nx0; dgemm_(&TRANS_N, &TRANS_T, &xcols, &ngridx, &l1, &D1, xqr, &xcols, xs_exp+nx0, mesh, &D1, rho+(nx0-offset[0])*xcols, &xcols); } else { dgemm_(&TRANS_N, &TRANS_T, &xcols, submesh, &l1, &D1, xqr, &xcols, xs_exp+offset[0], mesh, &D1, rho, &xcols); } } static void _dm_vrr6d(double *dm_cart, double *dm, size_t naoi, int li, int lj, double *ri, double *rj, double *cache) { int di = _LEN_CART[li]; int dj = _LEN_CART[lj]; double *dm_6d = cache; int i, j; for (j = 0; j < dj; j++) { for (i = 0; i < di; i++) { dm_6d[j*di+i] = dm[j*naoi+i]; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li, lj, ri, rj); } void NUMINTrho_lda_orth(double *rho, double *dm, int comp, size_t naoi, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int topl = li + lj; int l1 = topl + 1; int l1l1l1 = l1 * l1 * l1; double cutoff = gto_rcut(ai+aj, topl, fac, log_prec); int img_slice[6]; int grid_slice[6]; double *xs_exp, *ys_exp, *zs_exp; int data_size = _init_orth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, submesh, mesh, topl, dimension, cutoff, ai, aj, ri, rj, a, b, cache); if (data_size == 0) { return; } cache += data_size; double *dm_xyz = cache; cache += l1l1l1; double *dm_cart = cache; double *dm_6d = dm_cart + _MAX_RR_SIZE[topl]; _dm_vrr6d(dm_cart, dm, naoi, li, lj, ri, rj, dm_6d); NPdset0(dm_xyz, l1l1l1); _cart_to_xyz(dm_xyz, dm_cart, li, topl, l1); _orth_rho(rho, dm_xyz, fac, topl, offset, submesh, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); } void NUMINTrho_gga_orth(double *rho, double *dm, int comp, size_t naoi, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int topl = li + 1 + lj; int l1 = topl + 1; int l1l1l1 = l1 * l1 * l1; double cutoff = gto_rcut(ai+aj, topl, fac, log_prec); int img_slice[6]; int grid_slice[6]; double *xs_exp, *ys_exp, *zs_exp; int data_size = _init_orth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, submesh, mesh, topl, dimension, cutoff, ai, aj, ri, rj, a, b, cache); if (data_size == 0) { return; } cache += data_size; size_t ngrids = ((size_t)submesh[0]) * submesh[1] * submesh[2]; double *rhox = rho + ngrids; double *rhoy = rhox + ngrids; double *rhoz = rhoy + ngrids; double *dm_xyz = cache; cache += l1l1l1; double *dm_cart = cache; double *dm_6d = dm_cart + _MAX_RR_SIZE[topl]; int di = _LEN_CART[li]; int dj = _LEN_CART[lj]; int i, j, lx, ly, lz; _dm_vrr6d(dm_cart, dm, naoi, li, lj, ri, rj, dm_6d); lx = l1 - 1; NPdset0(dm_xyz, lx * lx * lx); _cart_to_xyz(dm_xyz, dm_cart, li, topl-1, lx); _orth_rho(rho, dm_xyz, fac, li+lj, offset, submesh, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); int di1 = _LEN_CART[li+1]; int li_1 = li - 1; int di_1 = _LEN_CART[MAX(0, li_1)]; double ai2 = -2 * ai; double fac_li; NPdset0(dm_6d, di1*dj); for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { dm_6d[di1*j+WHEREX_IF_L_INC1(i)] = dm[naoi*j+i] * ai2; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj); NPdset0(dm_xyz, l1l1l1); _cart_to_xyz(dm_xyz, dm_cart, li+1, topl, l1); if (li_1 >= 0) { for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { fac_li = lx + 1; for (j = 0; j < dj; j++) { dm_6d[di_1*j+i] = dm[naoi*j+WHEREX_IF_L_INC1(i)] * fac_li; } } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj); _cart_to_xyz(dm_xyz, dm_cart, li_1, topl-2, l1); } _orth_rho(rhox, dm_xyz, fac, topl, offset, submesh, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); NPdset0(dm_6d, _LEN_CART[li+1] * dj); for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { dm_6d[di1*j+WHEREY_IF_L_INC1(i)] = dm[naoi*j+i] * ai2; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj); NPdset0(dm_xyz, l1l1l1); _cart_to_xyz(dm_xyz, dm_cart, li+1, topl, l1); if (li_1 >= 0) { for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { fac_li = ly + 1; for (j = 0; j < dj; j++) { dm_6d[di_1*j+i] = dm[naoi*j+WHEREY_IF_L_INC1(i)] * fac_li; } } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj); _cart_to_xyz(dm_xyz, dm_cart, li_1, topl-2, l1); } _orth_rho(rhoy, dm_xyz, fac, topl, offset, submesh, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); NPdset0(dm_6d, _LEN_CART[li+1] * dj); for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { dm_6d[di1*j+WHEREZ_IF_L_INC1(i)] = dm[naoi*j+i] * ai2; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj); NPdset0(dm_xyz, l1l1l1); _cart_to_xyz(dm_xyz, dm_cart, li+1, topl, l1); if (li_1 >= 0) { for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { lz = li_1 - lx - ly; fac_li = lz + 1; for (j = 0; j < dj; j++) { dm_6d[di_1*j+i] = dm[naoi*j+WHEREZ_IF_L_INC1(i)] * fac_li; } } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj); _cart_to_xyz(dm_xyz, dm_cart, li_1, topl-2, l1); } _orth_rho(rhoz, dm_xyz, fac, topl, offset, submesh, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); } static void _nonorth_rho_z(double *rho, double *rhoz, int offset, int meshz, int nz0, int nz1, int grid_close_to_zij, double e_z0z0, double e_z0dz, double e_dzdz, double _z0dz, double _dzdz) { if (e_z0z0 == 0) { return; } double exp_2dzdz = e_dzdz * e_dzdz; double exp_z0z0, exp_z0dz; int iz, iz1; rho -= offset; // for the original indexing rho[iz1-offset] exp_z0z0 = e_z0z0; exp_z0dz = e_z0dz * e_dzdz; iz1 = grid_close_to_zij % meshz + meshz; for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) { if (iz1 >= meshz) { iz1 -= meshz; } rho[iz1] += rhoz[iz] * exp_z0z0; exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; } exp_z0z0 = e_z0z0; if (e_z0dz != 0) { exp_z0dz = e_dzdz / e_z0dz; } else { exp_z0dz = exp(_dzdz - _z0dz); } iz1 = (grid_close_to_zij-1) % meshz; for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) { if (iz1 < 0) { iz1 += meshz; } exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; rho[iz1] += rhoz[iz] * exp_z0z0; } } static void _nonorth_rho_z_1img(double *rho, double *rhoz, int offset, int meshz, int nz0, int nz1, int grid_close_to_zij, double e_z0z0, double e_z0dz, double e_dzdz, double _z0dz, double _dzdz) { if (e_z0z0 == 0) { return; } double exp_2dzdz = e_dzdz * e_dzdz; double exp_z0z0, exp_z0dz; int iz, iz1; rho -= offset; // for the original indexing rho[iz1-offset] exp_z0z0 = e_z0z0; exp_z0dz = e_z0dz * e_dzdz; iz1 = grid_close_to_zij % meshz; if (iz1 < 0) { iz1 += meshz; } for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) { rho[iz1] += rhoz[iz] * exp_z0z0; exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; } exp_z0z0 = e_z0z0; if (e_z0dz != 0) { exp_z0dz = e_dzdz / e_z0dz; } else { exp_z0dz = exp(_dzdz - _z0dz); } iz1 = (grid_close_to_zij-1) % meshz; if (iz1 < 0) { iz1 += meshz; } for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) { exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; rho[iz1] += rhoz[iz] * exp_z0z0; } } static void _nonorth_rho_z_with_mask(double *rho, double *rhoz, char *skip, int offset, int submeshz, int meshz, int nz0, int nz1, int grid_close_to_zij, double e_z0z0, double e_z0dz, double e_dzdz, double _z0dz, double _dzdz) { if (e_z0z0 == 0) { return; } double exp_2dzdz = e_dzdz * e_dzdz; double exp_z0z0, exp_z0dz; int iz, iz1; rho -= offset; // for the original indexing rho[iz1-offset] exp_z0z0 = e_z0z0; exp_z0dz = e_z0dz * e_dzdz; iz1 = grid_close_to_zij % meshz + meshz; for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) { if (iz1 >= meshz) { iz1 -= meshz; } if (!skip[iz]) { rho[iz1] += rhoz[iz] * exp_z0z0; } exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; } exp_z0z0 = e_z0z0; if (e_z0dz != 0) { exp_z0dz = e_dzdz / e_z0dz; } else { exp_z0dz = exp(_dzdz - _z0dz); } iz1 = (grid_close_to_zij-1) % meshz; for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) { if (iz1 < 0) { iz1 += meshz; } exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; if (!skip[iz]) { rho[iz1] += rhoz[iz] * exp_z0z0; } } } static int _make_grid_mask(char *skip, int nx0, int nx1, int mesh, int offset, int submesh) { if (offset == 0 && submesh == mesh) { // allows nimg > 1 return 0; } else if (offset <= nx0 && nx1 <= offset+submesh) { // requires nimg == 1 return 0; } int i, i1; i1 = nx0 % mesh + mesh; for (i = 0; i < nx1-nx0; i++, i1++) { if (i1 >= mesh) { i1 -= mesh; } if (offset <= i1 && i1 < offset+submesh) { skip[i] = 0; } else { skip[i] = 1; } } return 1; } static void _nonorth_rho(double *rho, double *dm_xyz, double fac, double aij, int topl, int dimension, double *a, double *rij_frac, double *xs_exp, double *ys_exp, double *zs_exp, int *img_slice, int *grid_slice, int *offset, int *submesh, int *mesh, double *cache) { int l1 = topl + 1; int l1l1 = l1 * l1; int nx0 = grid_slice[0]; int nx1 = grid_slice[1]; int ny0 = grid_slice[2]; int ny1 = grid_slice[3]; int nz0 = grid_slice[4]; int nz1 = grid_slice[5]; int ngridx = nx1 - nx0; int ngridy = ny1 - ny0; int ngridz = nz1 - nz0; //int nimgx0 = img_slice[0]; //int nimgx1 = img_slice[1]; //int nimgy0 = img_slice[2]; //int nimgy1 = img_slice[3]; int nimgz0 = img_slice[4]; int nimgz1 = img_slice[5]; //int nimgx = nimgx1 - nimgx0; //int nimgy = nimgy1 - nimgy0; int nimgz = nimgz1 - nimgz0; const char TRANS_T = 'T'; const char TRANS_N = 'N'; const double D0 = 0; const double D1 = 1; const int inc1 = 1; // aa = einsum('ij,kj->ik', a, a) //double aa[9]; //int n3 = 3; //dgemm_(&TRANS_T, &TRANS_N, &n3, &n3, &n3, // &aij, a, &n3, a, &n3, &D0, aa, &n3); double aa_xx = aij * (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); double aa_xy = aij * (a[0] * a[3] + a[1] * a[4] + a[2] * a[5]); double aa_xz = aij * (a[0] * a[6] + a[1] * a[7] + a[2] * a[8]); double aa_yy = aij * (a[3] * a[3] + a[4] * a[4] + a[5] * a[5]); double aa_yz = aij * (a[3] * a[6] + a[4] * a[7] + a[5] * a[8]); double aa_zz = aij * (a[6] * a[6] + a[7] * a[7] + a[8] * a[8]); int ix, iy, ix1, iy1; double dx = 1. / mesh[0]; double dy = 1. / mesh[1]; double dz = 1. / mesh[2]; //int grid_close_to_xij = rint(rij_frac[0] * mesh[0]); int grid_close_to_yij = rint(rij_frac[1] * mesh[1]); int grid_close_to_zij = rint(rij_frac[2] * mesh[2]); //grid_close_to_xij = MIN(grid_close_to_xij, nx1); //grid_close_to_xij = MAX(grid_close_to_xij, nx0); grid_close_to_yij = MIN(grid_close_to_yij, ny1); grid_close_to_yij = MAX(grid_close_to_yij, ny0); grid_close_to_zij = MIN(grid_close_to_zij, nz1); grid_close_to_zij = MAX(grid_close_to_zij, nz0); double img0_x = 0; double img0_y = 0; double img0_z = 0; double base_x = img0_x;// + dx * grid_close_to_xij; double base_y = img0_y + dy * grid_close_to_yij; double base_z = img0_z + dz * grid_close_to_zij; double x0xij = base_x - rij_frac[0]; double y0yij = base_y - rij_frac[1]; double z0zij = base_z - rij_frac[2]; double _dydy = -dy * dy * aa_yy; double _dzdz = -dz * dz * aa_zz; double _dydz = -dy * dz * aa_yz * 2; double exp_dydy = exp(_dydy); double exp_2dydy = exp_dydy * exp_dydy; double exp_dzdz = exp(_dzdz); double exp_dydz = exp(_dydz); double exp_dydz_i = (exp_dydz == 0) ? 0 : 1./exp_dydz; double x1xij, tmpx, tmpy, tmpz; double _xyz0xyz0, _xyz0dy, _xyz0dz, _z0dz; double exp_xyz0xyz0, exp_xyz0dz; double exp_y0dy, exp_z0z0, exp_z0dz; int xcols = ngridy * ngridz; double *xyr = cache; double *xqr = xyr + l1l1 * ngridz; double *rhoz = xqr + l1 * ngridy * ngridz; double *prho; int l; char x_skip[ngridx]; char y_skip[ngridy]; char z_skip[ngridz]; int with_x_mask = _make_grid_mask(x_skip, nx0, nx1, mesh[0], offset[0], submesh[0]); int with_y_mask = _make_grid_mask(y_skip, ny0, ny1, mesh[1], offset[1], submesh[1]); int with_z_mask = _make_grid_mask(z_skip, nz0, nz1, mesh[2], offset[2], submesh[2]); dgemm_(&TRANS_N, &TRANS_N, &ngridz, &l1l1, &l1, &D1, zs_exp, &ngridz, dm_xyz, &l1, &D0, xyr, &ngridz); for (l = 0; l <= topl; l++) { dgemm_(&TRANS_N, &TRANS_T, &ngridz, &ngridy, &l1, &D1, xyr+l*l1*ngridz, &ngridz, ys_exp, &ngridy, &D0, xqr+l*xcols, &ngridz); } ix1 = nx0 % mesh[0] + mesh[0]; for (ix = 0; ix < nx1-nx0; ix++, ix1++) { if (ix1 >= mesh[0]) { ix1 -= mesh[0]; } if (with_x_mask && x_skip[ix]) { continue; } x1xij = x0xij + (nx0+ix)*dx; tmpx = x1xij * aa_xx + y0yij * aa_xy + z0zij * aa_xz; tmpy = x1xij * aa_xy + y0yij * aa_yy + z0zij * aa_yz; tmpz = x1xij * aa_xz + y0yij * aa_yz + z0zij * aa_zz; _xyz0xyz0 = -x1xij * tmpx - y0yij * tmpy - z0zij * tmpz; if (_xyz0xyz0 < EXPMIN) { continue; } _xyz0dy = -2 * dy * tmpy; _xyz0dz = -2 * dz * tmpz; exp_xyz0xyz0 = fac * exp(_xyz0xyz0); exp_xyz0dz = exp(_xyz0dz); //exp_xyz0dy = exp(_xyz0dy); //exp_y0dy = exp_xyz0dy * exp_dydy; exp_y0dy = exp(_xyz0dy + _dydy); exp_z0z0 = exp_xyz0xyz0; exp_z0dz = exp_xyz0dz; _z0dz = _xyz0dz; iy1 = grid_close_to_yij % mesh[1] + mesh[1]; for (iy = grid_close_to_yij-ny0; iy < ny1-ny0; iy++, iy1++) { if (exp_z0z0 == 0) { break; } if (iy1 >= mesh[1]) { iy1 -= mesh[1]; } if (!with_y_mask || !y_skip[iy]) { dgemm_(&TRANS_N, &TRANS_T, &ngridz, &inc1, &l1, &D1, xqr+iy*ngridz, &xcols, xs_exp+ix, &ngridx, &D0, rhoz, &ngridz); prho = rho + ((ix1-offset[0])*submesh[1] + iy1-offset[1]) * submesh[2]; if (nimgz == 1) { _nonorth_rho_z_1img(prho, rhoz, offset[2], mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } else if (with_z_mask) { _nonorth_rho_z_with_mask(prho, rhoz, z_skip, offset[2], submesh[2], mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } else { _nonorth_rho_z(prho, rhoz, offset[2], mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } } _z0dz += _dydz; exp_z0z0 *= exp_y0dy; exp_z0dz *= exp_dydz; exp_y0dy *= exp_2dydy; } exp_y0dy = exp(_dydy - _xyz0dy); exp_z0z0 = exp_xyz0xyz0; exp_z0dz = exp_xyz0dz; _z0dz = _xyz0dz; iy1 = (grid_close_to_yij-1) % mesh[1]; for (iy = grid_close_to_yij-ny0-1; iy >= 0; iy--, iy1--) { exp_z0z0 *= exp_y0dy; if (exp_z0z0 == 0) { break; } _z0dz -= _dydz; if (exp_dydz != 0) { exp_z0dz *= exp_dydz_i; } else { exp_z0dz = exp(_z0dz); } exp_y0dy *= exp_2dydy; if (iy1 < 0) { iy1 += mesh[1]; } if (!with_y_mask || !y_skip[iy]) { dgemm_(&TRANS_N, &TRANS_T, &ngridz, &inc1, &l1, &D1, xqr+iy*ngridz, &xcols, xs_exp+ix, &ngridx, &D0, rhoz, &ngridz); prho = rho + ((ix1-offset[0])*submesh[1] + iy1-offset[1]) * submesh[2]; if (nimgz == 1) { _nonorth_rho_z_1img(prho, rhoz, offset[2], mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } else if (with_z_mask) { _nonorth_rho_z_with_mask(prho, rhoz, z_skip, offset[2], submesh[2], mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } else { _nonorth_rho_z(prho, rhoz, offset[2], mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } } } } } void NUMINTrho_lda_nonorth(double *rho, double *dm, int comp, size_t naoi, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int floorl = li; int topl = li + lj; int l1 = topl + 1; double aij = ai + aj; double cutoff = gto_rcut(aij, topl, fac, log_prec); int img_slice[6]; int grid_slice[6]; double ri_frac[3]; double rij_frac[3]; double *xs_exp, *ys_exp, *zs_exp; _make_rij_frac(ri_frac, rij_frac, ri, rj, ai, aj, a, b); int data_size = _init_nonorth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, submesh, mesh, topl, dimension, cutoff, a, b, ri_frac, rij_frac, cache); if (data_size == 0) { return; } cache += data_size; double *dm_xyz = cache; cache += l1 * l1 * l1; double *dm_cart = cache; double *dm_cache = dm_cart + _CUM_LEN_CART[topl]; _dm_vrr6d(dm_cart, dm, naoi, li, lj, ri, rj, dm_cart+_MAX_RR_SIZE[topl]); _reverse_affine_trans(dm_xyz, dm_cart, a, floorl, topl, dm_cache); _nonorth_rho(rho, dm_xyz, fac, aij, topl, dimension, a, rij_frac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); } static void _merge_dm_xyz_updown(double *dm_xyz, double *dm_xyz1, int l1) { int l0 = l1 - 2; int l1l1 = l1 * l1; int l0l0 = l0 * l0; int i, j, k; for (i = 0; i < l0; i++) { for (j = 0; j < l0; j++) { for (k = 0; k < l0; k++) { dm_xyz[i*l1l1+j*l1+k] += dm_xyz1[i*l0l0+j*l0+k]; } } } } void NUMINTrho_gga_nonorth(double *rho, double *dm, int comp, size_t naoi, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int topl = li + 1 + lj; int l1 = topl + 1; int l1l1 = l1 * l1; double aij = ai + aj; double cutoff = gto_rcut(aij, topl, fac, log_prec); int img_slice[6]; int grid_slice[6]; double ri_frac[3]; double rij_frac[3]; double *xs_exp, *ys_exp, *zs_exp; _make_rij_frac(ri_frac, rij_frac, ri, rj, ai, aj, a, b); int data_size = _init_nonorth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, submesh, mesh, topl, dimension, cutoff, a, b, ri_frac, rij_frac, cache); if (data_size == 0) { return; } cache += data_size; size_t ngrids = ((size_t)submesh[0]) * submesh[1] * submesh[2]; double *rhox = rho + ngrids; double *rhoy = rhox + ngrids; double *rhoz = rhoy + ngrids; double *dm_xyz = cache; double *dm_xyz1 = dm_xyz + l1l1 * l1; cache += l1l1 * l1 * 2; double *dm_cart = cache; double *dm_6d = dm_cart + _MAX_RR_SIZE[topl]; int di = _LEN_CART[li]; int dj = _LEN_CART[lj]; int i, j, lx, ly, lz; _dm_vrr6d(dm_cart, dm, naoi, li, lj, ri, rj, dm_6d); lx = l1 - 1; _reverse_affine_trans(dm_xyz, dm_cart, a, li, li+lj, dm_6d); _nonorth_rho(rho, dm_xyz, fac, aij, li+lj, dimension, a, rij_frac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); int di1 = _LEN_CART[li+1]; int li_1 = li - 1; int di_1 = _LEN_CART[MAX(0, li_1)]; double ai2 = -2 * ai; double fac_li; NPdset0(dm_6d, _LEN_CART[li+1] * dj); for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { dm_6d[di1*j+WHEREX_IF_L_INC1(i)] = dm[naoi*j+i] * ai2; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj); _reverse_affine_trans(dm_xyz, dm_cart, a, li+1, topl, dm_6d); if (li_1 >= 0) { for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { fac_li = lx + 1; for (j = 0; j < dj; j++) { dm_6d[di_1*j+i] = dm[naoi*j+WHEREX_IF_L_INC1(i)] * fac_li; } } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj); _reverse_affine_trans(dm_xyz1, dm_cart, a, li_1, topl-2, dm_6d); _merge_dm_xyz_updown(dm_xyz, dm_xyz1, l1); } _nonorth_rho(rhox, dm_xyz, fac, aij, topl, dimension, a, rij_frac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); NPdset0(dm_6d, _LEN_CART[li+1] * dj); for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { dm_6d[di1*j+WHEREY_IF_L_INC1(i)] = dm[naoi*j+i] * ai2; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj); _reverse_affine_trans(dm_xyz, dm_cart, a, li+1, topl, dm_6d); if (li_1 >= 0) { for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { fac_li = ly + 1; for (j = 0; j < dj; j++) { dm_6d[di_1*j+i] = dm[naoi*j+WHEREY_IF_L_INC1(i)] * fac_li; } } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj); _reverse_affine_trans(dm_xyz1, dm_cart, a, li_1, topl-2, dm_6d); _merge_dm_xyz_updown(dm_xyz, dm_xyz1, l1); } _nonorth_rho(rhoy, dm_xyz, fac, aij, topl, dimension, a, rij_frac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); NPdset0(dm_6d, _LEN_CART[li+1] * dj); for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { dm_6d[di1*j+WHEREZ_IF_L_INC1(i)] = dm[naoi*j+i] * ai2; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj); _reverse_affine_trans(dm_xyz, dm_cart, a, li+1, topl, dm_6d); if (li_1 >= 0) { for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { lz = li_1 - lx - ly; fac_li = lz + 1; for (j = 0; j < dj; j++) { dm_6d[di_1*j+i] = dm[naoi*j+WHEREZ_IF_L_INC1(i)] * fac_li; } } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj); _reverse_affine_trans(dm_xyz1, dm_cart, a, li_1, topl-2, dm_6d); _merge_dm_xyz_updown(dm_xyz, dm_xyz1, l1); } _nonorth_rho(rhoz, dm_xyz, fac, aij, topl, dimension, a, rij_frac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); } static void _apply_rho(void (*eval_rho)(), double *rho, double *dm, size_t *dims, int comp, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, int *shls, int *atm, int natm, int *bas, int nbas, double *env, double *cache) { const size_t naoi = dims[0]; const int i_sh = shls[0]; const int j_sh = shls[1]; const int li = bas(ANG_OF, i_sh); const int lj = bas(ANG_OF, j_sh); double *ri = env + atm(PTR_COORD, bas(ATOM_OF, i_sh)); double *rj = env + atm(PTR_COORD, bas(ATOM_OF, j_sh)); double ai = env[bas(PTR_EXP, i_sh)]; double aj = env[bas(PTR_EXP, j_sh)]; double ci = env[bas(PTR_COEFF, i_sh)]; double cj = env[bas(PTR_COEFF, j_sh)]; double aij = ai + aj; double rrij = CINTsquare_dist(ri, rj); double eij = (ai * aj / aij) * rrij; if (eij > EIJCUTOFF) { return; } double fac = exp(-eij) * ci * cj * CINTcommon_fac_sp(li) * CINTcommon_fac_sp(lj); if (fac < env[PTR_EXPDROP]) { return; } (*eval_rho)(rho, dm, comp, naoi, li, lj, ai, aj, ri, rj, fac, log_prec, dimension, a, b, offset, submesh, mesh, cache); } static int _rho_cache_size(int l, int comp, int *mesh) { int l1 = l * 2 + 1; int cache_size = 0; cache_size += l1 * mesh[1] * mesh[2]; cache_size += l1 * l1 * mesh[2] * 2; cache_size = MAX(cache_size, 3*_MAX_RR_SIZE[l*2]); cache_size = MAX(cache_size, _CUM_LEN_CART[l*2]+2*_MAX_AFFINE_SIZE[l*2]); cache_size += l1 * (mesh[0] + mesh[1] + mesh[2]); cache_size += l1 * l1 * l1; return cache_size + 1000000; } /* * F_dm are a set of uncontracted cartesian density matrices * Note rho is updated inplace. */ void NUMINT_rho_drv(void (*eval_rho)(), double *rho, double *F_dm, int comp, int hermi, int *shls_slice, int *ao_loc, double log_prec, int dimension, int nimgs, double *Ls, double *a, double *b, int *offset, int *submesh, int *mesh, int *atm, int natm, int *bas, int nbas, double *env, int nenv) { int ish0 = shls_slice[0]; int ish1 = shls_slice[1]; int jsh0 = shls_slice[2]; int jsh1 = shls_slice[3]; int nish = ish1 - ish0; int njsh = jsh1 - jsh0; size_t naoi = ao_loc[ish1] - ao_loc[ish0]; size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; size_t nao2 = naoi * naoi; int lmax = 0; int ib; for (ib = 0; ib < nbas; ib++) { lmax = MAX(lmax, bas(ANG_OF, ib)); } int cache_size = _rho_cache_size(lmax, comp, submesh); size_t ngrids = ((size_t)submesh[0]) * submesh[1] * submesh[2]; if (dimension == 0) { nimgs = 1; } double *rhobufs[MAX_THREADS]; #pragma omp parallel { size_t ncij = naoi * naoj; size_t nijsh = nish * njsh; size_t dims[] = {naoi, naoj}; size_t ijm; int ish, jsh, ij, m, i0, j0; int shls[2]; double *cache = malloc(sizeof(double) * cache_size); double *env_loc = malloc(sizeof(double)*nenv); NPdcopy(env_loc, env, nenv); int ptrxyz; int thread_id = omp_get_thread_num(); double *rho_priv, *pdm; if (thread_id == 0) { rho_priv = rho; } else { rho_priv = calloc(comp*ngrids, sizeof(double)); } rhobufs[thread_id] = rho_priv; if (hermi) { // Note hermitian character of the density matrices can only be found by // rearranging the repeated images: // dmR - dmR[::-1].transpose(0,2,1) == 0 #pragma omp for schedule(static) for (m = 0; m < nimgs; m++) { pdm = F_dm + m * nao2; for (j0 = 1; j0 < naoi; j0++) { for (i0 = 0; i0 < j0; i0++) { pdm[j0*naoi+i0] *= 2; pdm[i0*naoi+j0] = 0; } } } } #pragma omp for schedule(dynamic) for (ijm = 0; ijm < nimgs*nijsh; ijm++) { m = ijm / nijsh; ij = ijm % nijsh; ish = ij / njsh; jsh = ij % njsh; if (hermi != PLAIN && ish > jsh) { continue; } ish += ish0; jsh += jsh0; shls[0] = ish; shls[1] = jsh; i0 = ao_loc[ish] - ao_loc[ish0]; j0 = ao_loc[jsh] - ao_loc[jsh0]; if (dimension != 0) { ptrxyz = atm(PTR_COORD, bas(ATOM_OF,ish)); shift_bas(env_loc, env, Ls, ptrxyz, m); } _apply_rho(eval_rho, rho_priv, F_dm+m*ncij+j0*naoi+i0, dims, comp, log_prec, dimension, a, b, offset, submesh, mesh, shls, atm, natm, bas, nbas, env_loc, cache); } NPomp_dsum_reduce_inplace(rhobufs, comp*ngrids); free(cache); free(env_loc); if (thread_id != 0) { free(rho_priv); } } }
fitzhugh_1961.c
#include "fitzhugh_1961.h" GET_CELL_MODEL_DATA(init_cell_model_data) { if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { sv[0] = 0.000000f; //V millivolt sv[1] = 0.000000f; //h dimensionless } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = i; for (int j = 0; j < num_steps; ++j) { solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu(real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu(rY, rDY, stim_current); for(int i = 0; i < NEQ; i++) sv[i] = dt*rDY[i] + rY[i]; } void RHS_cpu(const real *sv, real *rDY_, real stim_current) { //State variables const real V_old_ = sv[0]; const real h_old_ = sv[1]; //Parameters const real alpha = -0.100000000000000e+00f; const real gamma = 3.000000000000000e+00f; const real epsilon = 5.000000000000000e-03f; real calc_I_stim = stim_current; rDY_[0] = (( V_old_*(V_old_ - alpha)*(1.00000 - V_old_) - h_old_) + calc_I_stim); rDY_[1] = epsilon*(V_old_ - gamma*h_old_); }
be5d49_gcc_so4.c
#define _POSIX_C_SOURCE 200809L #define START_TIMER(S) \ struct timeval start_##S, end_##S; \ gettimeofday(&start_##S, NULL); #define STOP_TIMER(S, T) \ gettimeofday(&end_##S, NULL); \ T->S += (double)(end_##S.tv_sec - start_##S.tv_sec) + (double)(end_##S.tv_usec - start_##S.tv_usec) / 1000000; #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "xmmintrin.h" #include "pmmintrin.h" #include <stdio.h> #include "omp.h" #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) struct dataobj { void *restrict data; int *size; int *npsize; int *dsize; int *hsize; int *hofs; int *oofs; }; struct profiler { double section0; double section1; }; void bf0(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict u_vec, struct dataobj *restrict vp_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, const int t0, const int t1, const int t2, const int x0_blk0_size, const int x_M, const int x_m, const int y0_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int sp_zi_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int time, const int tw); int Kernel(struct dataobj *restrict block_sizes_vec, struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict u_vec, struct dataobj *restrict vp_vec, const int sp_zi_m, const int time_M, const int time_m, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int nthreads_nonaffine, struct profiler *timers) { int(*restrict block_sizes) __attribute__((aligned(64))) = (int(*))block_sizes_vec->data; int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data; float(*restrict save_src_u)[save_src_u_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_u_vec->size[1]])save_src_u_vec->data; int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data; int(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data; int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data; float(*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__((aligned(64))) = (float(*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]])u_vec->data; /* Flush denormal numbers to zero in hardware */ _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); int xb_size = block_sizes[0]; int y0_blk0_size = block_sizes[3]; int x0_blk0_size = block_sizes[2]; int yb_size = block_sizes[1]; printf(" Tiles: %d, %d ::: Blocks %d, %d \n", xb_size, yb_size, x0_blk0_size, y0_blk0_size); //for (int time = time_m, t0 = (time + 2)%(3), t1 = (time)%(3), t2 = (time + 1)%(3); time <= time_M; time += 1, t0 = (time + 2)%(3), t1 = (time)%(3), t2 = (time + 1)%(3)) //{ int sf = 2; int t_blk_size = 2 * sf * (time_M - time_m); START_TIMER(section0) for (int t_blk = time_m; t_blk < sf * (time_M - time_m); t_blk += sf * t_blk_size) // for each t block { for (int xb = x_m; xb <= (x_M + sf * (time_M - time_m)); xb += xb_size + 1) { for (int yb = y_m; yb <= (y_M + sf * (time_M - time_m)); yb += yb_size + 1) { for (int time = t_blk, t0 = (time + 2) % (3), t1 = (time) % (3), t2 = (time + 1) % (3); time <= 1 + min(t_blk + t_blk_size - 1, sf * (time_M - time_m)); time += sf, t0 = (((time / sf) % (time_M - time_m + 1)) + 2) % (3), t1 = (((time / sf) % (time_M - time_m + 1))) % (3), t2 = (((time / sf) % (time_M - time_m + 1)) + 1) % (3)) { int tw = ((time / sf) % (time_M - time_m + 1)); bf0(damp_vec, dt, u_vec, vp_vec, nnz_sp_source_mask_vec, sp_source_mask_vec, save_src_u_vec, source_id_vec, source_mask_vec, t0, t1, t2, x0_blk0_size, x_M - (x_M - x_m + 1) % (x0_blk0_size), x_m, y0_blk0_size, y_M - (y_M - y_m + 1) % (y0_blk0_size), y_m, z_M, z_m, sp_zi_m, nthreads, xb, yb, xb_size, yb_size, time, tw); //bf0(damp_vec, dt, u_vec, vp_vec, t0, t1, t2, x0_blk0_size, x_M - (x_M - x_m + 1) % (x0_blk0_size), x_m, (y_M - y_m + 1) % (y0_blk0_size), y_M, y_M - (y_M - y_m + 1) % (y0_blk0_size) + 1, z_M, z_m, nthreads); //bf0(damp_vec, dt, u_vec, vp_vec, t0, t1, t2, (x_M - x_m + 1) % (x0_blk0_size), x_M, x_M - (x_M - x_m + 1) % (x0_blk0_size) + 1, y0_blk0_size, y_M - (y_M - y_m + 1) % (y0_blk0_size), y_m, z_M, z_m, nthreads); //bf0(damp_vec, dt, u_vec, vp_vec, t0, t1, t2, (x_M - x_m + 1) % (x0_blk0_size), x_M, x_M - (x_M - x_m + 1) % (x0_blk0_size) + 1, (y_M - y_m + 1) % (y0_blk0_size), y_M, y_M - (y_M - y_m + 1) % (y0_blk0_size) + 1, z_M, z_m, nthreads); } } } /* End section0 */ } STOP_TIMER(section0, timers) for (int time = time_m, t2 = (time + 1) % (3); time <= time_M; time += 1, t2 = (time + 1) % (3)) { START_TIMER(section1) /* Begin section1 */ /* End section1 */ STOP_TIMER(section1, timers) } return 0; } void bf0(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict u_vec, struct dataobj *restrict vp_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, const int t0, const int t1, const int t2, const int x0_blk0_size, const int x_M, const int x_m, const int y0_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int sp_zi_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int time, const int tw) { float(*restrict damp)[damp_vec->size[1]][damp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[damp_vec->size[1]][damp_vec->size[2]])damp_vec->data; float(*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__((aligned(64))) = (float(*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]])u_vec->data; float(*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[vp_vec->size[1]][vp_vec->size[2]])vp_vec->data; int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data; float(*restrict save_src_u)[save_src_u_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_u_vec->size[1]])save_src_u_vec->data; int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data; int(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data; int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data; if (x0_blk0_size == 0 || y0_blk0_size == 0) { return; } #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(2) schedule(dynamic, 1) for (int x0_blk0 = max((x_m + time), xb); x0_blk0 <= min((x_M + time), (xb + xb_size)); x0_blk0 += x0_blk0_size) { for (int y0_blk0 = max((y_m + time), yb); y0_blk0 <= min((y_M + time), (yb + yb_size)); y0_blk0 += y0_blk0_size) { for (int x = x0_blk0; x <= min(min((x_M + time), (xb + xb_size)), (x0_blk0 + x0_blk0_size - 1)); x++) { for (int y = y0_blk0; y <= min(min((y_M + time), (yb + yb_size)), (y0_blk0 + y0_blk0_size - 1)); y++) { #pragma omp simd aligned(damp, u, vp : 32) for (int z = z_m; z <= z_M; z += 1) { float r8 = 1.0/dt; float r7 = 1.0/(dt*dt); float r6 = 1.0/(vp[x - time + 4][y - time + 4][z + 4]*vp[x - time + 4][y - time + 4][z + 4]); u[t2][x - time + 4][y - time + 4][z + 4] = (r6*(-r7*(u[t0][x - time + 4][y - time + 4][z + 4] - 2.0F*u[t1][x - time + 4][y - time + 4][z + 4])) + r8*(damp[x - time + 1][y - time + 1][z + 1]*u[t1][x - time + 4][y - time + 4][z + 4]) - 3.70370379e-4F*(u[t1][x - time + 2][y - time + 4][z + 4] + u[t1][x - time + 4][y - time + 2][z + 4] + u[t1][x - time + 4][y - time + 4][z + 2] + u[t1][x - time + 4][y - time + 4][z + 6] + u[t1][x - time + 4][y - time + 6][z + 4] + u[t1][x - time + 6][y - time + 4][z + 4]) + 5.92592607e-3F*(u[t1][x - time + 3][y - time + 4][z + 4] + u[t1][x - time + 4][y - time + 3][z + 4] + u[t1][x - time + 4][y - time + 4][z + 3] + u[t1][x - time + 4][y - time + 4][z + 5] + u[t1][x - time + 4][y - time + 5][z + 4] + u[t1][x - time + 5][y - time + 4][z + 4]) - 3.33333341e-2F*u[t1][x - time + 4][y - time + 4][z + 4])/(r6*r7 + r8*damp[x - time + 1][y - time + 1][z + 1]); } #pragma omp simd aligned(damp, u, vp : 32) for (int sp_zi = sp_zi_m; sp_zi <= nnz_sp_source_mask[x - time][y - time] - 1; sp_zi += 1) { int zind = sp_source_mask[x - time][y - time][sp_zi]; float r0 = save_src_u[tw][source_id[x - time][y - time][zind]]; // * source_mask[x - time][y - time][zind]; u[t2][x - time + 4][y - time + 4][zind + 4] += r0; } } } } } } }
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 16; tile_size[3] = 512; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
DRB009-lastprivatemissing-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* This loop has loop-carried output-dependence due to x=... at line 59. The problem can be solved by using lastprivate(x). Data race pair: x@59 vs. x@59 */ #include "omprace.h" #include <omp.h> #include <stdio.h> int main(int argc, char* argv[]) { omprace_init(); int i,x; int len = 10000; #pragma omp parallel for private (i) for (i=0;i<len;i++) x=i; printf("x=%d",x); omprace_fini(); return 0; }
4.race1.c
// RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s #include <omp.h> #define N 4 int main() { int A[N][N][N][N][N][N][N][N][N]; #pragma omp parallel for for (int i = 1; i < N; i++) for (int j = 1; j < N; j++) for (int k = 1; k < N; k++) for (int l = 1; l < N; l++) for (int m = 1; m < N; m++) for (int n = 1; n < N; n++) for (int o = 1; o < N; o++) for (int p = 1; p < N; p++) for (int q = 1; q < N; q++) A[i][j][k][l][m][n][o][p][q] += A[i - 1][j][k][l][m][n][o][p][q]; } // CHECK: Data Race detected // END
cryptocontext.h
/** * @file cryptocontext.h -- Control for encryption operations. * @author TPOC: contact@palisade-crypto.org * * @section LICENSE * * @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT)) * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SRC_DEMO_PRE_CRYPTOCONTEXT_H_ #define SRC_DEMO_PRE_CRYPTOCONTEXT_H_ #include "palisade.h" #include "cryptocontexthelper.h" #include "cryptotiming.h" namespace lbcrypto { template<typename Element> class CryptoContextFactory; template<typename Element> class CryptoContextImpl; template<typename Element> using CryptoContext = shared_ptr<CryptoContextImpl<Element>>; /** * @brief CryptoContextImpl * * A CryptoContextImpl is the object used to access the PALISADE library * * All PALISADE functionality is accessed by way of an instance of a CryptoContextImpl; we say that various objects are * "created in" a context, and can only be used in the context in which they were created * * All PALISADE methods are accessed through CryptoContextImpl methods. Guards are implemented to make certain that * only valid objects that have been created in the context are used * * Contexts are created using the CryptoContextFactory, and can be serialized and recovered from a serialization */ template<typename Element> class CryptoContextImpl : public Serializable { friend class CryptoContextFactory<Element>; private: shared_ptr<LPCryptoParameters<Element>> params; /*!< crypto parameters used for this context */ shared_ptr<LPPublicKeyEncryptionScheme<Element>> scheme; /*!< algorithm used; accesses all crypto methods */ static std::map<string,std::vector<LPEvalKey<Element>>> evalMultKeyMap; /*!< cached evalmult keys, by secret key UID */ static std::map<string,shared_ptr<std::map<usint,LPEvalKey<Element>>>> evalSumKeyMap; /*!< cached evalsum keys, by secret key UID */ static std::map<string,shared_ptr<std::map<usint,LPEvalKey<Element>>>> evalAutomorphismKeyMap; /*!< cached evalautomorphism keys, by secret key UID */ bool doTiming; vector<TimingInfo>* timeSamples; /** * TypeCheck makes sure that an operation between two ciphertexts is permitted * @param a * @param b */ void TypeCheck(ConstCiphertext<Element> a, ConstCiphertext<Element> b) const { if( a == NULL || b == NULL ) PALISADE_THROW( type_error, "Null Ciphertext"); if( a->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContext"); if( a->GetCryptoContext() != b->GetCryptoContext() ) PALISADE_THROW( type_error, "Ciphertexts were not created in the same CryptoContext"); if( a->GetKeyTag() != b->GetKeyTag() ) PALISADE_THROW( type_error, "Ciphertexts were not encrypted with same keys" ); if( a->GetEncodingType() != b->GetEncodingType() ) { stringstream ss; ss << "Ciphertext encoding types " << a->GetEncodingType(); ss << " and " << b->GetEncodingType(); ss << " do not match"; PALISADE_THROW( type_error, ss.str() ); } } /** * TypeCheck makes sure that an operation between a ciphertext and a plaintext is permitted * @param a * @param b */ void TypeCheck(ConstCiphertext<Element> a, ConstPlaintext b) const { if( a == NULL ) PALISADE_THROW( type_error, "Null Ciphertext"); if( b == NULL ) PALISADE_THROW( type_error, "Null Plaintext"); if( a->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContext"); if( a->GetEncodingType() != b->GetEncodingType() ) { stringstream ss; ss << "Ciphertext encoding type " << a->GetEncodingType(); ss << " and Plaintext encoding type " << b->GetEncodingType(); ss << " do not match"; PALISADE_THROW( type_error, ss.str() ); } } /** * TypeCheck makes sure that an operation between two ciphertexts is permitted * @param a * @param b */ void TypeCheck(const RationalCiphertext<Element>& a, const RationalCiphertext<Element>& b) const { if( a.GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContextImpl"); if( a.GetCryptoContext() != b.GetCryptoContext() ) PALISADE_THROW( type_error, "Ciphertexts were not created in the same CryptoContextImpl"); if( a.GetKeyTag() != b.GetKeyTag() ) PALISADE_THROW( type_error, "Ciphertexts were not encrypted with same keys" ); if( a.GetNumerator()->GetEncodingType() != b.GetNumerator()->GetEncodingType() ) { stringstream ss; ss << "RationalCiphertext encoding types " << a.GetNumerator()->GetEncodingType(); ss << " and " << b.GetNumerator()->GetEncodingType(); ss << " do not match"; PALISADE_THROW( type_error, ss.str() ); } } /** * TypeCheck makes sure that an operation between a ciphertext and a plaintext is permitted * @param a * @param b */ void TypeCheck(const RationalCiphertext<Element>& a, ConstPlaintext b) const { if( b == NULL ) PALISADE_THROW( type_error, "Null Plaintext"); if( a.GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContextImpl"); if( a.GetNumerator()->GetEncodingType() != b->GetEncodingType() ){ stringstream ss; ss << "RationalCiphertext encoding type " << a.GetNumerator()->GetEncodingType(); ss << " and Plaintext encoding type " << b->GetEncodingType(); ss << " do not match"; PALISADE_THROW( type_error, ss.str() ); } } bool Mismatched(const CryptoContext<Element> a) const { if( a.get() != this ) { return true; } return false; } public: /** * CryptoContextImpl constructor from pointers to parameters and scheme * @param params - pointer to CryptoParameters * @param scheme - pointer to Crypto Scheme */ CryptoContextImpl(LPCryptoParameters<Element> *params = 0, LPPublicKeyEncryptionScheme<Element> *scheme = 0) { this->params.reset(params); this->scheme.reset(scheme); this->doTiming = false; this->timeSamples = 0; } /** * CryptoContextImpl constructor from shared pointers to parameters and scheme * @param params - shared pointer to CryptoParameters * @param scheme - sharedpointer to Crypto Scheme */ CryptoContextImpl(shared_ptr<LPCryptoParameters<Element>> params, shared_ptr<LPPublicKeyEncryptionScheme<Element>> scheme) { this->params = params; this->scheme = scheme; this->doTiming = false; this->timeSamples = 0; } /** * Copy constructor * @param c - source */ CryptoContextImpl(const CryptoContextImpl<Element>& c) { params = c.params; scheme = c.scheme; doTiming = c.doTiming; timeSamples = c.timeSamples; } /** * Assignment * @param rhs - assigning from * @return this */ CryptoContextImpl<Element>& operator=(const CryptoContextImpl<Element>& rhs) { params = rhs.params; scheme = rhs.scheme; doTiming = rhs.doTiming; timeSamples = rhs.timeSamples; return *this; } /** * A CryptoContextImpl is only valid if the shared pointers are both valid */ operator bool() const { return bool(params) && bool(scheme); } /** * Private methods to compare two contexts; this is only used internally and is not generally available * @param a - operand 1 * @param b - operand 2 * @return true if the implementations have identical parms and scheme */ friend bool operator==(const CryptoContextImpl<Element>& a, const CryptoContextImpl<Element>& b) { // Identical if the parameters and the schemes are identical... the exact same object, // OR the same type and the same values if( a.params.get() == b.params.get() ) { return true; } else { if( typeid(*a.params.get()) != typeid(*b.params.get()) ) { return false; } if( *a.params.get() != *b.params.get() ) return false; } if( a.scheme.get() == b.scheme.get() ) { return true; } else { if( typeid(*a.scheme.get()) != typeid(*b.scheme.get()) ) { return false; } if( *a.scheme.get() != *b.scheme.get() ) return false; } return true; } friend bool operator!=(const CryptoContextImpl<Element>& a, const CryptoContextImpl<Element>& b) { return !( a == b ); } // TIMING METHODS /** * StartTiming method activates timing of CryptoMethods * * @param timeSamples points to a vector in which timing samples will be stored */ void StartTiming(vector<TimingInfo>* timeSamples) { this->timeSamples = timeSamples; doTiming = true; } /* * StopTiming - turns off timing */ void StopTiming() { doTiming = false; } /** * ResumeTiming - re-enables timing with existing TimingInfo vector */ void ResumeTiming() { doTiming = true; } /** * ResetTiming - erases measurements */ void ResetTiming() { this->timeSamples->clear(); } static bool SerializeEvalMultKey(Serialized* serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool SerializeEvalMultKey(Serialized* serObj, const string& id) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool SerializeEvalMultKey(Serialized* serObj, const CryptoContext<Element> cc) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool DeserializeEvalMultKey(Serialized* serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); /** * SerializeEvalMultKey for a single EvalMult key or all EvalMult keys * * @param ser - stream to serialize to * @param sertype - type of serialization * @param id for key to serialize - if empty string, serialize them all * @return true on success */ template<typename ST> static bool SerializeEvalMultKey(std::ostream& ser, const ST&, string id = ""); /** * SerializeEvalMultKey for all EvalMultKeys made in a given context * * @param cc whose keys should be serialized * @param ser - stream to serialize to * @param sertype - type of serialization * @return true on success (false on failure or no keys found) */ template<typename ST> static bool SerializeEvalMultKey(std::ostream& ser, const ST&, const CryptoContext<Element> cc); /** * DeserializeEvalMultKey deserialize all keys in the serialization * deserialized keys silently replace any existing matching keys * deserialization will create CryptoContextImpl if necessary * * @param serObj - stream with a serialization * @return true on success */ template<typename ST> static bool DeserializeEvalMultKey(std::istream& ser, const ST&); /** * ClearEvalMultKeys - flush EvalMultKey cache */ static void ClearEvalMultKeys(); /** * ClearEvalMultKeys - flush EvalMultKey cache for a given id * @param id */ static void ClearEvalMultKeys(const string& id); /** * ClearEvalMultKeys - flush EvalMultKey cache for a given context * @param cc */ static void ClearEvalMultKeys(const CryptoContext<Element> cc); /** * InsertEvalMultKey - add the given vector of keys to the map, replacing the existing vector if there * @param vectorToInsert */ static void InsertEvalMultKey(const std::vector<LPEvalKey<Element>>& vectorToInsert); static bool SerializeEvalSumKey(Serialized* serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool SerializeEvalSumKey(Serialized* serObj, const string& id) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool SerializeEvalSumKey(Serialized* serObj, const CryptoContext<Element> cc) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool DeserializeEvalSumKey(const Serialized& serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); /** * SerializeEvalSumKey for a single EvalSum key or all of the EvalSum keys * * @param ser - stream to serialize to * @param sertype - type of serialization * @param id - key to serialize; empty string means all keys * @return true on success */ template<typename ST> static bool SerializeEvalSumKey(std::ostream& ser, const ST& sertype, string id = ""); /** * SerializeEvalSumKey for all of the EvalSum keys for a context * * @param ser - stream to serialize to * @param sertype - type of serialization * @param cc - context * @return true on success */ template<typename ST> static bool SerializeEvalSumKey(std::ostream& ser, const ST& sertype, const CryptoContext<Element> cc); /** * DeserializeEvalSumKey deserialize all keys in the serialization * deserialized keys silently replace any existing matching keys * deserialization will create CryptoContextImpl if necessary * * @param ser - stream to serialize from * @param sertype - type of serialization * @return true on success */ template<typename ST> static bool DeserializeEvalSumKey(std::istream& ser, const ST& sertype); /** * ClearEvalSumKeys - flush EvalSumKey cache */ static void ClearEvalSumKeys(); /** * ClearEvalSumKeys - flush EvalSumKey cache for a given id * @param id */ static void ClearEvalSumKeys(const string& id); /** * ClearEvalSumKeys - flush EvalSumKey cache for a given context * @param cc */ static void ClearEvalSumKeys(const CryptoContext<Element> cc); /** * InsertEvalSumKey - add the given map of keys to the map, replacing the existing map if there * @param mapToInsert */ static void InsertEvalSumKey(const shared_ptr<std::map<usint,LPEvalKey<Element>>> mapToInsert); static bool SerializeEvalAutomorphismKey(Serialized* serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool SerializeEvalAutomorphismKey(Serialized* serObj, const string& id) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool SerializeEvalAutomorphismKey(Serialized* serObj, const CryptoContext<Element> cc) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static bool DeserializeEvalAutomorphismKey(const Serialized& serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); /** * SerializeEvalAutomorphismKey for a single EvalAuto key or all of the EvalAuto keys * * @param ser - stream to serialize to * @param sertype - type of serialization * @param id - key to serialize; empty string means all keys * @return true on success */ template<typename ST> static bool SerializeEvalAutomorphismKey(std::ostream& ser, const ST& sertype, string id = ""); /** * SerializeEvalAutomorphismKey for all of the EvalAuto keys for a context * * @param ser - stream to serialize to * @param sertype - type of serialization * @param cc - context * @return true on success */ template<typename ST> static bool SerializeEvalAutomorphismKey(std::ostream& ser, const ST& sertype, const CryptoContext<Element> cc); /** * DeserializeEvalAutomorphismKey deserialize all keys in the serialization * deserialized keys silently replace any existing matching keys * deserialization will create CryptoContextImpl if necessary * * @param ser - stream to serialize from * @param sertype - type of serialization * @return true on success */ template<typename ST> static bool DeserializeEvalAutomorphismKey(std::istream& ser, const ST& sertype); /** * ClearEvalAutomorphismKeys - flush EvalAutomorphismKey cache */ static void ClearEvalAutomorphismKeys(); /** * ClearEvalAutomorphismKeys - flush EvalAutomorphismKey cache for a given id * @param id */ static void ClearEvalAutomorphismKeys(const string& id); /** * ClearEvalAutomorphismKeys - flush EvalAutomorphismKey cache for a given context * @param cc */ static void ClearEvalAutomorphismKeys(const CryptoContext<Element> cc); /** * InsertEvalAutomorphismKey - add the given map of keys to the map, replacing the existing map if there * @param mapToInsert */ static void InsertEvalAutomorphismKey(const shared_ptr<std::map<usint,LPEvalKey<Element>>> mapToInsert); // TURN FEATURES ON /** * Enable a particular feature for use with this CryptoContextImpl * @param feature - the feature that should be enabled */ void Enable(PKESchemeFeature feature) { scheme->Enable(feature); } /** * Enable several features at once * @param featureMask - bitwise or of several PKESchemeFeatures */ void Enable(usint featureMask) { scheme->Enable(featureMask); } // GETTERS /** * Getter for Scheme * @return scheme */ const shared_ptr<LPPublicKeyEncryptionScheme<Element>> GetEncryptionAlgorithm() const { return scheme; } /** * Getter for CryptoParams * @return params */ const shared_ptr<LPCryptoParameters<Element>> GetCryptoParameters() const { return params; } /** * Getter for element params * @return */ const shared_ptr<typename Element::Params> GetElementParams() const { return params->GetElementParams(); } /** * Getter for encoding params * @return */ const EncodingParams GetEncodingParams() const { return params->GetEncodingParams(); } /** * Get the cyclotomic order used for this context * * @return */ const usint GetCyclotomicOrder() const { return params->GetElementParams()->GetCyclotomicOrder(); } /** * Get the ring dimension used for this context * * @return */ const usint GetRingDimension() const { return params->GetElementParams()->GetRingDimension(); } /** * Get the ciphertext modulus used for this context * * @return */ const typename Element::Integer& GetModulus() const { return params->GetElementParams()->GetModulus(); } /** * Get the ciphertext modulus used for this context * * @return */ const typename Element::Integer& GetRootOfUnity() const { return params->GetElementParams()->GetRootOfUnity(); } /** * KeyGen generates a key pair using this algorithm's KeyGen method * @return a public/secret key pair */ LPKeyPair<Element> KeyGen() { TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->KeyGen(CryptoContextFactory<Element>::GetContextForPointer(this), false); if( doTiming ) { timeSamples->push_back( TimingInfo(OpKeyGen, TOC_US(t)) ); } return r; } /** * KeyGen generates a Multiparty key pair using this algorithm's KeyGen method from two keys * @param pk first public key used to coordinate the creation of later public keys. * @return a public/secret key pair */ LPKeyPair<Element> MultipartyKeyGen( const LPPublicKey<Element> pk, bool makeSparse=false, bool pre=false) { TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->MultipartyKeyGen(CryptoContextFactory<Element>::GetContextForPointer(this), pk, makeSparse, pre); if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyKeyGenKey, TOC_US(t)) ); } return r; } /** * KeyGen generates a Multiparty key pair using a vector of secret keys * @param secretKeys a vector of the secret keys to be used for multiparty computation. * @return a public/secret key pair */ LPKeyPair<Element> MultipartyKeyGen( const vector<LPPrivateKey<Element>>& secretKeys) { TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->MultipartyKeyGen(CryptoContextFactory<Element>::GetContextForPointer(this), secretKeys, false); if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyKeyGenKeyvec, TOC_US(t)) ); } return r; } /** * Lead Multiparty Decryption method for PALISADE multiparty operations. * This should be performed by exactly one of the clients. * All other clients should perform the MultipartyDecryptMain operation. * @param privateKey the secret key of the lead decryption client * @param ciphertext vector of encrypted ciphertext * @return vector of partially decrypted ciphertexts */ vector<Ciphertext<Element>> MultipartyDecryptLead( const LPPrivateKey<Element> privateKey, const vector<Ciphertext<Element>>& ciphertext) const { if( privateKey == NULL || Mismatched(privateKey->GetCryptoContext()) ) throw std::logic_error("Information passed to MultipartyDecryptLead was not generated with this crypto context"); vector<Ciphertext<Element>> newCiphertext; TimeVar t; if( doTiming ) TIC(t); for( size_t i = 0; i < ciphertext.size(); i++ ) { if( ciphertext[i] == NULL || Mismatched(ciphertext[i]->GetCryptoContext()) ) throw std::logic_error("A ciphertext passed to MultipartyDecryptLead was not generated with this crypto context"); newCiphertext.push_back( GetEncryptionAlgorithm()->MultipartyDecryptLead(privateKey, ciphertext[i]) ); } if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyDecryptLead, TOC_US(t)) ); } return newCiphertext; } /** * Multiparty decryption method for PALISADE multiparty operations. * The lead multiparty decryption operation should be performed by exactly one of the clients. * All other clients should perform this MultipartyDecryptMain operation. * @param privateKey - for decryption * @param ciphertext - vector of encrypted ciphertext * @return vector of partially decrypted ciphertexts */ vector<Ciphertext<Element>> MultipartyDecryptMain( const LPPrivateKey<Element> privateKey, const vector<Ciphertext<Element>>& ciphertext) const { if( privateKey == NULL || Mismatched(privateKey->GetCryptoContext()) ) throw std::logic_error("Information passed to MultipartyDecryptMain was not generated with this crypto context"); vector<Ciphertext<Element>> newCiphertext; TimeVar t; if( doTiming ) TIC(t); for( size_t i = 0; i < ciphertext.size(); i++ ) { if( ciphertext[i] == NULL || Mismatched(ciphertext[i]->GetCryptoContext()) ) throw std::logic_error("A ciphertext passed to MultipartyDecryptMain was not generated with this crypto context"); newCiphertext.push_back( GetEncryptionAlgorithm()->MultipartyDecryptMain(privateKey, ciphertext[i]) ); } if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyDecryptMain, TOC_US(t)) ); } return newCiphertext; } /** * Final multiparty decryption method to fuse the partially decrypted ciphertexts into a decrypted plaintext. * The lead multiparty decryption operation should be performed by exactly one of the clients. * All other clients should perform the MultipartyDecryptMain operation. * @param partialCiphertextVec - vector of partially decrypted ciphertexts. * @param plaintext - pointer to destination for the result of decryption * @param doPadding - true if input plaintext was padded; causes unpadding on last piece of ciphertext * @return size of plaintext */ DecryptResult MultipartyDecryptFusion( const vector<Ciphertext<Element>>& partialCiphertextVec, Plaintext *plaintext) const { DecryptResult result; //Make sure we're processing ciphertexts. size_t last_ciphertext = partialCiphertextVec.size(); if ( last_ciphertext < 1 ) return result; TimeVar t; if( doTiming ) TIC(t); for( size_t i = 0; i < last_ciphertext; i++ ) { if (partialCiphertextVec[i] == NULL || Mismatched(partialCiphertextVec[i]->GetCryptoContext())) throw std::logic_error("A ciphertext passed to MultipartyDecryptFusion was not generated with this crypto context"); if (partialCiphertextVec[i]->GetEncodingType() != partialCiphertextVec[0]->GetEncodingType()) throw std::logic_error("Ciphertexts passed to MultipartyDecryptFusion have mismatched encoding types"); } // determine which type of plaintext that you need to decrypt into Plaintext decrypted = GetPlaintextForDecrypt(partialCiphertextVec[0]->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); result = GetEncryptionAlgorithm()->MultipartyDecryptFusion(partialCiphertextVec, &decrypted->GetElement<NativePoly>()); if (result.isValid == false) return result; decrypted->Decode(); *plaintext = decrypted; if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyDecryptFusion, TOC_US(t)) ); } return result; } /** * SparseKeyGen generates a key pair with special structure, and without full entropy, * for use in special cases like Ring Reduction * @return a public/secret key pair */ LPKeyPair<Element> SparseKeyGen() { TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->KeyGen(CryptoContextFactory<Element>::GetContextForPointer(this), true); if( doTiming ) { timeSamples->push_back( TimingInfo(OpSparseKeyGen, TOC_US(t)) ); } return r; } /** * ReKeyGen produces an Eval Key that PALISADE can use for Proxy Re Encryption * @param newKey (public) * @param oldKey (private) * @return new evaluation key */ LPEvalKey<Element> ReKeyGen( const LPPublicKey<Element> newKey, const LPPrivateKey<Element> oldKey) const { if( newKey == NULL || oldKey == NULL || Mismatched(newKey->GetCryptoContext()) || Mismatched(oldKey->GetCryptoContext()) ) throw std::logic_error("Keys passed to ReKeyGen were not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->ReKeyGen(newKey, oldKey); if( doTiming ) { timeSamples->push_back( TimingInfo(OpReKeyGenPubPri, TOC_US(t)) ); } return r; } /** * ReKeyGen produces an Eval Key that PALISADE can use for Proxy Re Encryption * NOTE this functionality has been completely removed from PALISADE * @param newKey (private) * @param oldKey (private) * @return new evaluation key */ LPEvalKey<Element> ReKeyGen( const LPPrivateKey<Element> newKey, const LPPrivateKey<Element> oldKey) const __attribute__ ((deprecated("functionality removed from PALISADE"))); /** * EvalMultKeyGen creates a key that can be used with the PALISADE EvalMult operator * @param key * @return new evaluation key */ void EvalMultKeyGen(const LPPrivateKey<Element> key); /** * EvalMultsKeyGen creates a vector evalmult keys that can be used with the PALISADE EvalMult operator * 1st key (for s^2) is used for multiplication of ciphertexts of depth 1 * 2nd key (for s^3) is used for multiplication of ciphertexts of depth 2, etc. * * @param key * @return a vector of evaluation keys */ void EvalMultKeysGen(const LPPrivateKey<Element> key); /** * GetEvalMultKeyVector fetches the eval mult keys for a given KeyID * @param keyID * @return key vector from ID */ static const vector<LPEvalKey<Element>>& GetEvalMultKeyVector(const string& keyID); /** * GetEvalMultKeys * @return map of all the keys */ static const std::map<string,std::vector<LPEvalKey<Element>>>& GetAllEvalMultKeys(); /** * KeySwitchGen creates a key that can be used with the PALISADE KeySwitch operation * @param key1 * @param key2 * @return new evaluation key */ LPEvalKey<Element> KeySwitchGen( const LPPrivateKey<Element> key1, const LPPrivateKey<Element> key2) const { if( key1 == NULL || key2 == NULL || Mismatched(key1->GetCryptoContext()) || Mismatched(key2->GetCryptoContext()) ) throw std::logic_error("Keys passed to KeySwitchGen were not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->KeySwitchGen(key1, key2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpKeySwitchGen, TOC_US(t)) ); } return r; } /** * Encrypt a plaintext using a given public key * @param publicKey * @param plaintext * @return ciphertext (or null on failure) */ Ciphertext<Element> Encrypt( const LPPublicKey<Element> publicKey, Plaintext plaintext) { if( publicKey == NULL ) throw std::logic_error("null key passed to Encrypt"); if( plaintext == NULL ) throw std::logic_error("null plaintext passed to Encrypt"); if( Mismatched(publicKey->GetCryptoContext()) ) throw std::logic_error("key passed to Encrypt was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); Ciphertext<Element> ciphertext = GetEncryptionAlgorithm()->Encrypt(publicKey, plaintext->GetElement<Element>()); if (ciphertext) { ciphertext->SetEncodingType( plaintext->GetEncodingType() ); } if( doTiming ) { timeSamples->push_back( TimingInfo(OpEncryptPub, TOC_US(t)) ); } return ciphertext; } /** * Encrypt a plaintext using a given private key * @param privateKey * @param plaintext * @return ciphertext (or null on failure) */ Ciphertext<Element> Encrypt( const LPPrivateKey<Element> privateKey, Plaintext plaintext) const { if( privateKey == NULL || Mismatched(privateKey->GetCryptoContext()) ) throw std::logic_error("key passed to Encrypt was not generated with this crypto context"); if( plaintext == NULL ) throw std::logic_error("null plaintext passed to Encrypt"); TimeVar t; if( doTiming ) TIC(t); Ciphertext<Element> ciphertext = GetEncryptionAlgorithm()->Encrypt(privateKey, plaintext->GetElement<Element>()); if (ciphertext) { ciphertext->SetEncodingType( plaintext->GetEncodingType() ); } if( doTiming ) { timeSamples->push_back( TimingInfo(OpEncryptPriv, TOC_US(t)) ); } return ciphertext; } /** * Encrypt a matrix of Plaintext * @param publicKey - for encryption * @param plaintext - to encrypt * @param doEncryption encrypts if true, embeds (encodes) the plaintext into cryptocontext if false * @return a vector of pointers to Ciphertexts created by encrypting the plaintext */ shared_ptr<Matrix<RationalCiphertext<Element>>> EncryptMatrix( const LPPublicKey<Element> publicKey, Matrix<Plaintext> &plaintext) { if (publicKey == NULL || Mismatched(publicKey->GetCryptoContext())) throw std::logic_error("key passed to EncryptMatrix was not generated with this crypto context"); auto zeroAlloc = [=]() { return RationalCiphertext<Element>(publicKey->GetCryptoContext(), true); }; shared_ptr<Matrix<RationalCiphertext<Element>>> cipherResults(new Matrix<RationalCiphertext<Element>> (zeroAlloc, plaintext.GetRows(), plaintext.GetCols())); TimeVar t; if( doTiming ) TIC(t); for (size_t row = 0; row < plaintext.GetRows(); row++) { for (size_t col = 0; col < plaintext.GetCols(); col++) { if( plaintext(row,col)->Encode() == false ) return 0; Ciphertext<Element> ciphertext = GetEncryptionAlgorithm()->Encrypt(publicKey, plaintext(row,col)->GetElement<Element>()); if (ciphertext) { ciphertext->SetEncodingType( plaintext(row,col)->GetEncodingType() ); } (*cipherResults)(row, col).SetNumerator(ciphertext); } } if( doTiming ) { timeSamples->push_back( TimingInfo(OpEncryptMatrixPlain, TOC_US(t)) ); } return cipherResults; } /** * Encrypt a matrix of Plaintext * @param publicKey - for encryption * @param plaintext - to encrypt * @param doEncryption encrypts if true, embeds (encodes) the plaintext into cryptocontext if false * @return a vector of pointers to Ciphertexts created by encrypting the plaintext */ Matrix<Ciphertext<Element>> EncryptMatrixCiphertext( const LPPublicKey<Element> publicKey, Matrix<Plaintext> &plaintext) { if (publicKey == NULL || Mismatched(publicKey->GetCryptoContext())) throw std::logic_error("key passed to EncryptMatrix was not generated with this crypto context"); auto zeroAlloc = [=]() { return Ciphertext<Element>(new CiphertextImpl<Element>(publicKey->GetCryptoContext())); }; Matrix<Ciphertext<Element>> cipherResults(zeroAlloc, plaintext.GetRows(), plaintext.GetCols()); TimeVar t; if( doTiming ) TIC(t); for (size_t row = 0; row < plaintext.GetRows(); row++) { for (size_t col = 0; col < plaintext.GetCols(); col++) { if( plaintext(row,col)->Encode() == false ) throw std::logic_error("Plaintext is not encoded"); Ciphertext<Element> ciphertext = GetEncryptionAlgorithm()->Encrypt(publicKey, plaintext(row,col)->GetElement<Element>()); if (ciphertext) { ciphertext->SetEncodingType( plaintext(row,col)->GetEncodingType() ); } cipherResults(row, col) = (ciphertext); } } if( doTiming ) { timeSamples->push_back( TimingInfo(OpEncryptMatrixPlain, TOC_US(t)) ); } return cipherResults; } /** * Perform an encryption by reading plaintext from a stream, serializing each piece of ciphertext, * and writing the serializations to an output stream * @param publicKey - the encryption key in use * @param instream - where to read the input from * @param ostream - where to write the serialization to * @param doEncryption encrypts if true, embeds (encodes) the plaintext into cryptocontext if false * @return */ void EncryptStream( const LPPublicKey<Element> publicKey, std::istream& instream, std::ostream& outstream) const __attribute__ ((deprecated("serialization changed, see wiki for details"))); // PLAINTEXT FACTORY METHODS // FIXME to be deprecated in 2.0 /** * MakeScalarPlaintext constructs a ScalarEncoding in this context * @param value * @param isSigned * @return plaintext */ Plaintext MakeScalarPlaintext(int64_t value) const { auto p = PlaintextFactory::MakePlaintext( Scalar, this->GetElementParams(), this->GetEncodingParams(), value ); return p; } /** * MakeStringPlaintext constructs a StringEncoding in this context * @param str * @return plaintext */ Plaintext MakeStringPlaintext(const string& str) const { auto p = PlaintextFactory::MakePlaintext( String, this->GetElementParams(), this->GetEncodingParams(), str ); return p; } /** * MakeIntegerPlaintext constructs an IntegerEncoding in this context * @param value * @return plaintext */ Plaintext MakeIntegerPlaintext(int64_t value) const { auto p = PlaintextFactory::MakePlaintext( Integer, this->GetElementParams(), this->GetEncodingParams(), value ); return p; } /** * MakeIntegerPlaintext constructs a FractionalEncoding in this context * @param value * @param truncatedBits limit on fractional * @return plaintext */ Plaintext MakeFractionalPlaintext(int64_t value, size_t truncatedBits = 0) const { auto p = PlaintextFactory::MakePlaintext( Fractional, this->GetElementParams(), this->GetEncodingParams(), value, truncatedBits ); return p; } /** * MakeCoefPackedPlaintext constructs a CoefPackedEncoding in this context * @param value * @return plaintext */ Plaintext MakeCoefPackedPlaintext(const vector<int64_t>& value) const { auto p = PlaintextFactory::MakePlaintext( CoefPacked, this->GetElementParams(), this->GetEncodingParams(), value ); return p; } /** * MakePackedPlaintext constructs a PackedEncoding in this context * @param value * @return plaintext */ Plaintext MakePackedPlaintext(const vector<int64_t>& value) const { auto p = PlaintextFactory::MakePlaintext( Packed, this->GetElementParams(), this->GetEncodingParams(), value ); return p; } /** * MakePlaintext static that takes a cc and calls the Plaintext Factory * @param encoding * @param cc * @param value * @return */ template<typename Value1> static Plaintext MakePlaintext(PlaintextEncodings encoding, CryptoContext<Element> cc, const Value1& value) { return PlaintextFactory::MakePlaintext( encoding, cc->GetElementParams(), cc->GetEncodingParams(), value ); } template<typename Value1, typename Value2> static Plaintext MakePlaintext(PlaintextEncodings encoding, CryptoContext<Element> cc, const Value1& value, const Value2& value2) { return PlaintextFactory::MakePlaintext( encoding, cc->GetElementParams(), cc->GetEncodingParams(), value, value2 ); } static Plaintext GetPlaintextForDecrypt(PlaintextEncodings pte, shared_ptr<typename Element::Params> evp, EncodingParams ep) { shared_ptr<typename NativePoly::Params> vp( new typename NativePoly::Params(evp->GetCyclotomicOrder(), ep->GetPlaintextModulus(), 1) ); return PlaintextFactory::MakePlaintext(pte, vp, ep); } public: /** * Decrypt a single ciphertext into the appropriate plaintext * * @param privateKey - decryption key * @param ciphertext - ciphertext to decrypt * @param plaintext - resulting plaintext object pointer is here * @return */ DecryptResult Decrypt( const LPPrivateKey<Element> privateKey, ConstCiphertext<Element> ciphertext, Plaintext* plaintext) { if( privateKey == NULL || Mismatched(privateKey->GetCryptoContext()) ) throw std::logic_error("Information passed to Decrypt was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); // determine which type of plaintext that you need to decrypt into Plaintext decrypted = GetPlaintextForDecrypt(ciphertext->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); DecryptResult result = GetEncryptionAlgorithm()->Decrypt(privateKey, ciphertext, &decrypted->GetElement<NativePoly>()); if (result.isValid == false) return result; decrypted->Decode(); if( doTiming ) { timeSamples->push_back( TimingInfo(OpDecrypt, TOC_US(t)) ); } *plaintext = decrypted; return result; } /** * Decrypt method for a matrix of ciphertexts * @param privateKey - for decryption * @param ciphertext - matrix of encrypted ciphertexts * @param plaintext - pointer to the destination martrix of plaintexts * @return size of plaintext */ DecryptResult DecryptMatrix( const LPPrivateKey<Element> privateKey, const shared_ptr<Matrix<RationalCiphertext<Element>>> ciphertext, shared_ptr<Matrix<Plaintext>> *numerator, shared_ptr<Matrix<Plaintext>> *denominator) const { // edge case if ((ciphertext->GetCols()== 0) && (ciphertext->GetRows() == 0)) return DecryptResult(); if (privateKey == NULL || Mismatched(privateKey->GetCryptoContext())) throw std::runtime_error("Information passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (*ciphertext)(0, 0).GetNumerator(); // need to build matrices for the result Plaintext ptx = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); auto zeroPackingAlloc = [=]() { return Plaintext(ptx); }; *numerator = shared_ptr<Matrix<Plaintext>>( new Matrix<Plaintext>(zeroPackingAlloc, ciphertext->GetRows(), ciphertext->GetCols()) ); *denominator = shared_ptr<Matrix<Plaintext>>( new Matrix<Plaintext>(zeroPackingAlloc, ciphertext->GetRows(), ciphertext->GetCols()) ); TimeVar t; if( doTiming ) TIC(t); for (size_t row = 0; row < ciphertext->GetRows(); row++) { for (size_t col = 0; col < ciphertext->GetCols(); col++) { if (Mismatched((*ciphertext)(row, col).GetCryptoContext())) throw std::runtime_error("A ciphertext passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (*ciphertext)(row, col).GetNumerator(); // determine which type of plaintext that you need to decrypt into Plaintext decryptedNumerator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); DecryptResult resultN = GetEncryptionAlgorithm()->Decrypt(privateKey, ctN, &decryptedNumerator->GetElement<NativePoly>()); if (resultN.isValid == false) return resultN; (**numerator)(row,col) = decryptedNumerator; (**numerator)(row,col)->Decode(); Plaintext decryptedDenominator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); if( (*ciphertext)(row,col).GetIntegerFlag() == true ) { decryptedDenominator->GetElement<Poly>().SetValuesToZero(); decryptedDenominator->GetElement<Poly>().at(0) = 1; } else { const Ciphertext<Element> ctD = (*ciphertext)(row, col).GetDenominator(); DecryptResult resultD = GetEncryptionAlgorithm()->Decrypt(privateKey, ctD, &decryptedDenominator->GetElement<NativePoly>()); if (resultD.isValid == false) return resultD; (**denominator)(row,col) = decryptedDenominator; } (**denominator)(row, col)->Decode(); } } if( doTiming ) { timeSamples->push_back( TimingInfo(OpDecryptMatrixPlain, TOC_US(t)) ); } return DecryptResult((**numerator)((*numerator)->GetRows()-1,(*numerator)->GetCols()-1)->GetLength()); } /** * Decrypt method for a matrix of ciphertexts * @param privateKey - for decryption * @param ciphertext - matrix of encrypted ciphertexts * @param plaintext - pointer to the destination martrix of plaintexts * @return size of plaintext */ DecryptResult DecryptMatrixCiphertext( const LPPrivateKey<Element> privateKey, const Matrix<Ciphertext<Element>> ciphertext, Matrix<Plaintext> *numerator) const { // edge case if ((ciphertext.GetCols()== 0) && (ciphertext.GetRows() == 0)) return DecryptResult(); if (privateKey == NULL || Mismatched(privateKey->GetCryptoContext())) throw std::runtime_error("Information passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (ciphertext)(0, 0); // need to build matrices for the result // Plaintext ptx = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); // auto zeroPackingAlloc = [=]() { return Plaintext(ptx); }; // numerator = new Matrix<Plaintext>(zeroPackingAlloc, ciphertext.GetRows(), ciphertext.GetCols()); TimeVar t; if( doTiming ) TIC(t); for (size_t row = 0; row < ciphertext.GetRows(); row++) { for (size_t col = 0; col < ciphertext.GetCols(); col++) { if (Mismatched( (ciphertext(row, col))->GetCryptoContext() )) throw std::runtime_error("A ciphertext passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (ciphertext)(row, col); // determine which type of plaintext that you need to decrypt into Plaintext decryptedNumerator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); DecryptResult resultN = GetEncryptionAlgorithm()->Decrypt(privateKey, ctN, &decryptedNumerator->GetElement<NativePoly>()); if (resultN.isValid == false) return resultN; (*numerator)(row,col) = decryptedNumerator; (*numerator)(row,col)->Decode(); } } if( doTiming ) { timeSamples->push_back( TimingInfo(OpDecryptMatrixPlain, TOC_US(t)) ); } return DecryptResult((*numerator)( numerator->GetRows()-1, numerator->GetCols()-1)->GetLength()); } /** * Decrypt method for numerators in a matrix of ciphertexts (packed encoding) * @param privateKey - for decryption * @param ciphertext - matrix of encrypted ciphertexts * @param plaintext - pointer to the destination martrix of plaintexts * @return size of plaintext */ DecryptResult DecryptMatrixNumerator( const LPPrivateKey<Element> privateKey, const shared_ptr<Matrix<RationalCiphertext<Element>>> ciphertext, shared_ptr<Matrix<Plaintext>> *numerator) const { // edge case if ((ciphertext->GetCols() == 0) && (ciphertext->GetRows() == 0)) return DecryptResult(); if (privateKey == NULL || Mismatched(privateKey->GetCryptoContext())) throw std::runtime_error("Information passed to DecryptMatrix was not generated with this crypto context"); TimeVar t; if (doTiming) TIC(t); //force all precomputations to take place in advance if( Mismatched((*ciphertext)(0, 0).GetCryptoContext()) ) throw std::runtime_error("A ciphertext passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (*ciphertext)(0, 0).GetNumerator(); // need to build a numerator matrix for the result Plaintext ptx = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); auto zeroPackingAlloc = [=]() { return Plaintext(ptx); }; *numerator = shared_ptr<Matrix<Plaintext>>( new Matrix<Plaintext>(zeroPackingAlloc, ciphertext->GetRows(), ciphertext->GetCols()) ); Plaintext decryptedNumerator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); DecryptResult resultN = GetEncryptionAlgorithm()->Decrypt(privateKey, ctN, &decryptedNumerator->GetElement<NativePoly>()); if (resultN.isValid == false) return resultN; (**numerator)(0, 0) = decryptedNumerator; (**numerator)(0, 0)->Decode(); for (size_t row = 0; row < ciphertext->GetRows(); row++) { #pragma omp parallel for for (size_t col = 0; col < ciphertext->GetCols(); col++) { if (row + col > 0) { if( Mismatched((*ciphertext)(row, col).GetCryptoContext()) ) throw std::runtime_error("A ciphertext passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (*ciphertext)(row, col).GetNumerator(); Plaintext decryptedNumerator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); GetEncryptionAlgorithm()->Decrypt(privateKey, ctN, &decryptedNumerator->GetElement<NativePoly>()); (**numerator)(row, col) = decryptedNumerator; (**numerator)(row, col)->Decode(); } } } if (doTiming) { timeSamples->push_back(TimingInfo(OpDecryptMatrixPacked, TOC_US(t))); } return DecryptResult((**numerator)((*numerator)->GetRows() - 1, (*numerator)->GetCols() - 1)->GetLength()); } /** * read instream for a sequence of serialized ciphertext; deserialize it, decrypt it, and write it to outstream * @param privateKey - reference to the decryption key * @param instream - input stream with sequence of serialized ciphertexts * @param outstream - output stream for plaintext * @return total bytes processed */ size_t DecryptStream( const LPPrivateKey<Element> privateKey, std::istream& instream, std::ostream& outstream) __attribute__ ((deprecated("serialization changed, see wiki for details"))); /** * ReEncrypt - Proxy Re Encryption mechanism for PALISADE * @param evalKey - evaluation key from the PRE keygen method * @param ciphertext - vector of shared pointers to encrypted Ciphertext * @param publicKey the public key of the recipient of the re-encrypted ciphertext. * @return vector of shared pointers to re-encrypted ciphertexts */ Ciphertext<Element> ReEncrypt( LPEvalKey<Element> evalKey, ConstCiphertext<Element> ciphertext, const LPPublicKey<Element> publicKey = nullptr) const { if( evalKey == NULL || Mismatched(evalKey->GetCryptoContext()) ) throw std::logic_error("Information passed to ReEncrypt was not generated with this crypto context"); if( ciphertext == NULL || Mismatched(ciphertext->GetCryptoContext()) ) throw std::logic_error("The ciphertext passed to ReEncrypt was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); Ciphertext<Element> newCiphertext = GetEncryptionAlgorithm()->ReEncrypt(evalKey, ciphertext, publicKey); if( doTiming ) { timeSamples->push_back( TimingInfo(OpReEncrypt, TOC_US(t)) ); } return newCiphertext; } /** * read instream for a serialized ciphertext. deserialize, re-encrypt, serialize, and write to outstream * @param evalKey - reference to the re-encryption key * @param instream - input stream with sequence of serialized ciphertext * @param outstream - output stream with sequence of serialized re-encrypted ciphertext */ void ReEncryptStream( const LPEvalKey<Element> evalKey, std::istream& instream, std::ostream& outstream, const LPPublicKey<Element> publicKey = nullptr) __attribute__ ((deprecated("serialization changed, see wiki for details"))); /** * EvalAdd - PALISADE EvalAdd method for a pair of ciphertexts * @param ct1 * @param ct2 * @return new ciphertext for ct1 + ct2 */ Ciphertext<Element> EvalAdd(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { TypeCheck(ct1, ct2); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalAdd(ct1, ct2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAdd, TOC_US(t)) ); } return rv; } /** * EvalAddMatrix - PALISADE EvalAdd method for a pair of matrices of ciphertexts * @param ct1 * @param ct2 * @return new matrix for ct1 + ct2 */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalAddMatrix(const shared_ptr<Matrix<RationalCiphertext<Element>>> ct1, const shared_ptr<Matrix<RationalCiphertext<Element>>> ct2) const { TypeCheck((*ct1)(0,0), (*ct2)(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<RationalCiphertext<Element>> rv = *ct1 + *ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAddMatrix, TOC_US(t)) ); } shared_ptr<Matrix<RationalCiphertext<Element>>> a(new Matrix<RationalCiphertext<Element>>(rv)); return a; } /** * EvalAddMatrix - PALISADE EvalAdd method for a pair of matrices of ciphertexts * @param ct1 * @param ct2 * @return new matrix for ct1 + ct2 */ Matrix<Ciphertext<Element>> EvalAddMatrix(const Matrix<Ciphertext<Element>> &ct1, const Matrix<Ciphertext<Element>> &ct2) const { TypeCheck(ct1(0,0), ct2(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<Ciphertext<Element>> rv = ct1 + ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAddMatrix, TOC_US(t)) ); } // Matrix<Ciphertext<Element>> a(rv); return rv; } /** * EvalSub - PALISADE EvalSub method for a pair of ciphertexts * @param ct1 * @param ct2 * @return new ciphertext for ct1 - ct2 */ Ciphertext<Element> EvalSub(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { TypeCheck(ct1, ct2); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalSub(ct1, ct2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalSub, TOC_US(t)) ); } return rv; } /** * EvalSubMatrix - PALISADE EvalSub method for a pair of matrices of ciphertexts * @param ct1 * @param ct2 * @return new matrix for ct1 + ct2 */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalSubMatrix(const shared_ptr<Matrix<RationalCiphertext<Element>>> ct1, const shared_ptr<Matrix<RationalCiphertext<Element>>> ct2) const { TypeCheck((*ct1)(0,0), (*ct2)(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<RationalCiphertext<Element>> rv = *ct1 - *ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalSubMatrix, TOC_US(t)) ); } shared_ptr<Matrix<RationalCiphertext<Element>>> a(new Matrix<RationalCiphertext<Element>>(rv)); return a; } /** * EvalSubMatrix - PALISADE EvalSub method for a pair of matrices of ciphertexts * @param ct1 * @param ct2 * @return new matrix for ct1 + ct2 */ Matrix<Ciphertext<Element>> EvalSubMatrix(const Matrix<Ciphertext<Element>> &ct1, const Matrix<Ciphertext<Element>> &ct2) const { TypeCheck(ct1(0,0), ct2(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<Ciphertext<Element>> rv = ct1 - ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalSubMatrix, TOC_US(t)) ); } Matrix<Ciphertext<Element>> a(rv); return a; } /** * EvalAdd - PALISADE EvalAdd method for a ciphertext and plaintext * @param ciphertext * @param plaintext * @return new ciphertext for ciphertext + plaintext */ Ciphertext<Element> EvalAdd(ConstCiphertext<Element> ciphertext, ConstPlaintext plaintext) const { TypeCheck(ciphertext, plaintext); TimeVar t; if( doTiming ) TIC(t); plaintext->SetFormat(EVALUATION); auto rv = GetEncryptionAlgorithm()->EvalAdd(ciphertext, plaintext); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAddPlain, TOC_US(t)) ); } return rv; } inline Ciphertext<Element> EvalAdd(ConstPlaintext plaintext, ConstCiphertext<Element> ciphertext) const { return EvalAdd(ciphertext, plaintext); } /** * EvalSubPlain - PALISADE EvalSub method for a ciphertext and plaintext * @param ciphertext * @param plaintext * @return new ciphertext for ciphertext - plaintext */ Ciphertext<Element> EvalSub(ConstCiphertext<Element> ciphertext, ConstPlaintext plaintext) const { TypeCheck(ciphertext, plaintext); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalSub(ciphertext, plaintext); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalSubPlain, TOC_US(t)) ); } return rv; } inline Ciphertext<Element> EvalSub(ConstPlaintext plaintext, ConstCiphertext<Element> ciphertext) const { return EvalSub(ciphertext, plaintext); } /** * EvalMult - PALISADE EvalMult method for a pair of ciphertexts - with key switching * @param ct1 * @param ct2 * @return new ciphertext for ct1 * ct2 */ Ciphertext<Element> EvalMult(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { TypeCheck(ct1, ct2); auto ek = GetEvalMultKeyVector(ct1->GetKeyTag()); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMult(ct1, ct2, ek[0]); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMult, TOC_US(t)) ); } return rv; } /** * EvalMult - PALISADE EvalMult method for a pair of ciphertexts - no key switching (relinearization) * @param ct1 * @param ct2 * @return new ciphertext for ct1 * ct2 */ Ciphertext<Element> EvalMultNoRelin(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { TypeCheck(ct1, ct2); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMult(ct1, ct2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMult, TOC_US(t)) ); } return rv; } /** * EvalMultMany - PALISADE function for evaluating multiplication on ciphertext followed by relinearization operation (at the end). * It computes the multiplication in a binary tree manner. Also, it reduces the number of * elements in the ciphertext to two after each multiplication. * Currently it assumes that the consecutive two input arguments have * total depth smaller than the supported depth. Otherwise, it throws an error. * * @param cipherTextList is the ciphertext list. * * @return new ciphertext. */ Ciphertext<Element> EvalMultMany(const vector<Ciphertext<Element>>& ct) const{ const auto ek = GetEvalMultKeyVector(ct[0]->GetKeyTag()); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMultMany(ct, ek); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMultMany, TOC_US(t)) ); } return rv; } /** * Function for evaluating multiplication on ciphertext followed by relinearization operation. * Currently it assumes that the input arguments have total depth smaller than the supported depth. Otherwise, it throws an error. * * @param ct1 first input ciphertext. * @param ct2 second input ciphertext. * * @return new ciphertext */ Ciphertext<Element> EvalMultAndRelinearize(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { const auto ek = GetEvalMultKeyVector(ct1->GetKeyTag()); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMultAndRelinearize(ct1, ct2, ek); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMult, TOC_US(t)) ); } return rv; } /** * EvalMult - PALISADE EvalMult method for plaintext * ciphertext * @param pt2 * @param ct1 * @return new ciphertext for ct1 * pt2 */ inline Ciphertext<Element> EvalMult(ConstPlaintext pt2, ConstCiphertext<Element> ct1) const { return EvalMult(ct1, pt2); } /** * EvalShiftRight - works only for Fractional Encoding * @param pt2 * @param ct1 * @return new ciphertext for ct1 * pt2 */ Ciphertext<Element> EvalRightShift(ConstCiphertext<Element> ct1, size_t divisor) const { if( ct1 && ct1->GetEncodingType() != Fractional ) { stringstream ss; ss << "A " << Fractional << " encoded ciphertext is required for the EvalRightShift operation"; PALISADE_THROW( type_error, ss.str() ); } Plaintext plaintextShift = MakeFractionalPlaintext(0,divisor); TypeCheck(ct1, plaintextShift); double start = 0; if( doTiming ) start = currentDateTime(); auto rv = EvalMult(ct1, plaintextShift); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalRightShift, currentDateTime() - start) ); } return rv; } /** * EvalMult - PALISADE EvalMult method for plaintext * ciphertext * @param ct1 * @param pt2 * @return new ciphertext for ct1 * pt2 */ Ciphertext<Element> EvalMult(ConstCiphertext<Element> ct1, ConstPlaintext pt2) const { TypeCheck(ct1, pt2); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMult(ct1, pt2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMult, TOC_US(t)) ); } return rv; } /** * EvalMultMatrix - PALISADE EvalMult method for two matrices of ciphertext * @param ct1 * @param ct2 * @return new matrix for ct1 * ct2 */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalMultMatrix(const shared_ptr<Matrix<RationalCiphertext<Element>>> ct1, const shared_ptr<Matrix<RationalCiphertext<Element>>> ct2) const { TypeCheck((*ct1)(0,0), (*ct2)(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<RationalCiphertext<Element>> rv = *ct1 * *ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMultMatrix, TOC_US(t)) ); } shared_ptr<Matrix<RationalCiphertext<Element>>> a(new Matrix<RationalCiphertext<Element>>(rv)); return a; } /** * EvalSub - PALISADE Negate method for a ciphertext * @param ct * @return new ciphertext -ct */ Ciphertext<Element> EvalNegate(ConstCiphertext<Element> ct) const { if (ct == NULL || Mismatched(ct->GetCryptoContext()) ) throw std::logic_error("Information passed to EvalNegate was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalNegate(ct); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalNeg, TOC_US(t)) ); } return rv; } /** * EvalSub - PALISADE Negate method for a ciphertext * @param ct * @return new ciphertext -ct */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalNegateMatrix(const shared_ptr<Matrix<RationalCiphertext<Element>>> ct) const { if (ct == NULL || Mismatched((*ct)(0,0).GetCryptoContext()) ) throw std::logic_error("Information passed to EvalNegateMatrix was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); shared_ptr<Matrix<RationalCiphertext<Element>>> m( new Matrix<RationalCiphertext<Element>>(ct->GetAllocator(), ct->GetRows(), ct->GetCols())); for( size_t r = 0; r < m->GetRows(); r++ ) for( size_t c = 0; c < m->GetCols(); c++ ) (*m)(r,c) = -((*ct)(r,c)); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalNegMatrix, TOC_US(t)) ); } return m; } /** * Generate automophism keys for a given private key * * @param publicKey original public key. * @param origPrivateKey original private key. * @param indexList list of automorphism indices to be computed * @return returns the evaluation keys; index 0 of the vector corresponds to plaintext index 2, index 1 to plaintex index 3, etc. */ shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalAutomorphismKeyGen(const LPPublicKey<Element> publicKey, const LPPrivateKey<Element> origPrivateKey, const std::vector<usint> &indexList) const { if( publicKey == NULL || origPrivateKey == NULL ) PALISADE_THROW( type_error, "Null Keys"); if( publicKey->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Key was not created in this CryptoContextImpl"); if( publicKey->GetCryptoContext() != origPrivateKey->GetCryptoContext() ) PALISADE_THROW( type_error, "Keys were not created in the same CryptoContextImpl"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalAutomorphismKeyGen(publicKey, origPrivateKey, indexList); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAutomorphismKeyGen, TOC_US(t)) ); } return rv; } /** * Function for evaluating automorphism of ciphertext at index i * * @param ciphertext the input ciphertext. * @param i automorphism index * @param &evalKeys - reference to the vector of evaluation keys generated by EvalAutomorphismKeyGen. * @return resulting ciphertext */ Ciphertext<Element> EvalAutomorphism(ConstCiphertext<Element> ciphertext, usint i, const std::map<usint, LPEvalKey<Element>> &evalKeys) const { auto mf = evalKeys.begin(); if( mf == evalKeys.end() ) PALISADE_THROW( type_error, "Empty key map"); auto tk = mf->second; if( ciphertext == NULL || tk == NULL ) PALISADE_THROW( type_error, "Null inputs"); if( ciphertext->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContextImpl"); if( ciphertext->GetCryptoContext() != tk->GetCryptoContext() ) PALISADE_THROW( type_error, "Items were not created in the same CryptoContextImpl"); if( ciphertext->GetKeyTag() != tk->GetKeyTag() ) PALISADE_THROW( type_error, "Items were not encrypted with same keys" ); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalAutomorphism(ciphertext, i, evalKeys); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAutomorphismI, TOC_US(t)) ); } return rv; } /** * Generate automophism keys for a given private key; Uses the private key for encryption * * @param privateKey private key. * @param indexList list of automorphism indices to be computed * @return returns the evaluation keys */ shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalAutomorphismKeyGen(const LPPrivateKey<Element> privateKey, const std::vector<usint> &indexList) const { if( privateKey == NULL ) PALISADE_THROW( type_error, "Null input"); if( privateKey->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Key was not created in this CryptoContextImpl"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalAutomorphismKeyGen(privateKey, indexList); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAutomorphismK, TOC_US(t)) ); } return rv; } /** * EvalSumKeyGen Generates the key map to be used by evalsum * * @param privateKey private key. * @param publicKey public key (used in NTRU schemes). */ void EvalSumKeyGen( const LPPrivateKey<Element> privateKey, const LPPublicKey<Element> publicKey = nullptr); /** * GetEvalSumKey returns the map * * @return the EvalSum key map */ static const std::map<usint, LPEvalKey<Element>>& GetEvalSumKeyMap(const string& id); static const std::map<string,shared_ptr<std::map<usint, LPEvalKey<Element>>>>& GetAllEvalSumKeys(); /** * Function for evaluating a sum of all components * * @param ciphertext the input ciphertext. * @param batchSize size of the batch * @return resulting ciphertext */ Ciphertext<Element> EvalSum(ConstCiphertext<Element> ciphertext, usint batchSize) const; /** * EvalSumKeyGen Generates the key map to be used by evalsum * * @param privateKey private key. * @param indexList list of indices. * @param publicKey public key (used in NTRU schemes). */ void EvalAtIndexKeyGen(const LPPrivateKey<Element> privateKey, const std::vector<int32_t> &indexList, const LPPublicKey<Element> publicKey = nullptr); /** * Merges multiple ciphertexts with encrypted results in slot 0 into a single ciphertext * The slot assignment is done based on the order of ciphertexts in the vector * * @param ciphertextVector vector of ciphertexts to be merged. * @param &evalKeys - reference to the map of evaluation keys generated by EvalAutomorphismKeyGen. * @return resulting ciphertext */ Ciphertext<Element> EvalMerge(const vector<Ciphertext<Element>> &ciphertextVector) const; /** * GetEvalAutomorphismKey returns the map * * @return the EvalAutomorphism key map */ static const std::map<usint, LPEvalKey<Element>>& GetEvalAutomorphismKeyMap(const string& id); static const std::map<string,shared_ptr<std::map<usint, LPEvalKey<Element>>>>& GetAllEvalAutomorphismKeys(); /** * Moves i-th slot to slot 0 * * @param ciphertext. * @param i the index. * @return resulting ciphertext */ Ciphertext<Element> EvalAtIndex(ConstCiphertext<Element> ciphertext, int32_t index) const; /** * Evaluates inner product in batched encoding * * @param ciphertext1 first vector. * @param ciphertext2 second vector. * @param batchSize size of the batch to be summed up * @return resulting ciphertext */ Ciphertext<Element> EvalInnerProduct(ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2, usint batchSize) const; /** * Evaluates inner product in batched encoding * * @param ciphertext1 first vector. * @param ciphertext2 second vector. * @param batchSize size of the batch to be summed up * @return resulting ciphertext */ Ciphertext<Element> EvalInnerProduct(ConstCiphertext<Element> ciphertext1, ConstPlaintext ciphertext2, usint batchSize) const; /** * EvalCrossCorrelation - Computes the sliding sum of inner products (known as * as cross-correlation, sliding inner product, or sliding dot product in * image processing * @param x - first vector of row vectors * @param y - second vector of row vectors * @param batchSize - batch size for packed encoding * @param indexStart - starting index in the vectors of row vectors * @param length - length of the slice in the vectors of row vectors; default is 0 meaning to use the full length of the vector * @return sum(x_i*y_i), i.e., a sum of inner products */ Ciphertext<Element> EvalCrossCorrelation(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize, usint indexStart = 0, usint length = 0) const; /** * EvalLinRegressBatched- Computes the parameter vector for linear regression using the least squares method * Supported only in batched mode; currently works only for two regressors * @param x - matrix of regressors * @param y - vector of dependent variables * @return the parameter vector using (x^T x)^{-1} x^T y (using least squares method) */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalLinRegressBatched(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize) const; /** * EvalLinRegression - Computes the parameter vector for linear regression using the least squares method * @param x - matrix of regressors * @param y - vector of dependent variables * @return the parameter vector using (x^T x)^{-1} x^T y (using least squares method) */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalLinRegression(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y) const { TypeCheck((*x)(0,0), (*y)(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalLinRegression(x, y); if( doTiming ) { timeSamples->push_back( TimingInfo(OpLinRegression, TOC_US(t)) ); } return rv; } /** * KeySwitch - PALISADE KeySwitch method * @param keySwitchHint - reference to KeySwitchHint * @param ciphertext - vector of ciphertext * @return new CiphertextImpl after applying key switch */ Ciphertext<Element> KeySwitch( const LPEvalKey<Element> keySwitchHint, ConstCiphertext<Element> ciphertext) const { if( keySwitchHint == NULL || Mismatched(keySwitchHint->GetCryptoContext()) ) throw std::logic_error("Key passed to KeySwitch was not generated with this crypto context"); if( ciphertext == NULL || Mismatched(ciphertext->GetCryptoContext()) ) throw std::logic_error("Ciphertext passed to KeySwitch was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->KeySwitch(keySwitchHint, ciphertext); if( doTiming ) { timeSamples->push_back( TimingInfo(OpKeySwitch, TOC_US(t)) ); } return rv; } /** * ModReduce - PALISADE ModReduce method * @param ciphertext - vector of ciphertext * @return vector of mod reduced ciphertext */ Ciphertext<Element> ModReduce(ConstCiphertext<Element> ciphertext) const { if( ciphertext == NULL || Mismatched(ciphertext->GetCryptoContext()) ) throw std::logic_error("Information passed to ModReduce was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->ModReduce(ciphertext); if( doTiming ) { timeSamples->push_back( TimingInfo(OpModReduce, TOC_US(t)) ); } return rv; } /** * ModReduce - PALISADE ModReduce method * @param ciphertext - vector of ciphertext * @return vector of mod reduced ciphertext */ RationalCiphertext<Element> ModReduceRational(RationalCiphertext<Element> ciphertext) const { TimeVar t; if( doTiming ) TIC(t); Ciphertext<Element> n = GetEncryptionAlgorithm()->ModReduce(ciphertext.GetNumerator()); Ciphertext<Element> d = GetEncryptionAlgorithm()->ModReduce(ciphertext.GetDenominator()); if( doTiming ) { timeSamples->push_back( TimingInfo(OpModReduce, TOC_US(t)) ); } return RationalCiphertext<Element>(n,d); } /** * ModReduce - PALISADE ModReduce method * @param ciphertext - vector of ciphertext * @return vector of mod reduced ciphertext */ shared_ptr<Matrix<RationalCiphertext<Element>>> ModReduceMatrix(shared_ptr<Matrix<RationalCiphertext<Element>>> ciphertext) const { // needs context check TimeVar t; if( doTiming ) TIC(t); shared_ptr<Matrix<RationalCiphertext<Element>>> m( new Matrix<RationalCiphertext<Element>>(ciphertext->GetAllocator(), ciphertext->GetRows(), ciphertext->GetCols())); for( size_t r = 0; r < m->GetRows(); r++ ) for( size_t c = 0; c < m->GetCols(); c++ ) (*m)(r,c) = ModReduceRational((*ciphertext)(r,c)); if( doTiming ) { timeSamples->push_back( TimingInfo(OpModReduceMatrix, TOC_US(t)) ); } return m; } /** * LevelReduce - PALISADE LevelReduce method * @param cipherText1 * @param linearKeySwitchHint * @return vector of level reduced ciphertext */ Ciphertext<Element> LevelReduce(ConstCiphertext<Element> cipherText1, const LPEvalKeyNTRU<Element> linearKeySwitchHint) const { if( cipherText1 == NULL || linearKeySwitchHint == NULL || Mismatched(cipherText1->GetCryptoContext()) || Mismatched(linearKeySwitchHint->GetCryptoContext()) ) { throw std::logic_error("Information passed to LevelReduce was not generated with this crypto context"); } TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->LevelReduce(cipherText1, linearKeySwitchHint); if( doTiming ) { timeSamples->push_back( TimingInfo(OpLevelReduce, TOC_US(t)) ); } return rv; } /** * RingReduce - PALISADE RingReduce method * @param ciphertext - vector of ciphertext * @param keySwitchHint - the keySwitchHint from original private key to sparse private key * @return vector of ring-reduced ciphertexts */ Ciphertext<Element> RingReduce( ConstCiphertext<Element> ciphertext, const LPEvalKey<Element> keySwitchHint) const { if( keySwitchHint == NULL || Mismatched(keySwitchHint->GetCryptoContext()) ) throw std::logic_error("Key passed to RingReduce was not generated with this crypto context"); if( ciphertext == NULL || Mismatched(ciphertext->GetCryptoContext()) ) throw std::logic_error("Ciphertext passed to RingReduce was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto newCiphertext = GetEncryptionAlgorithm()->RingReduce(ciphertext, keySwitchHint); if( doTiming ) { timeSamples->push_back( TimingInfo(OpRingReduce, TOC_US(t)) ); } return newCiphertext; } /** * ComposedEvalMult - PALISADE composed evalmult * @param ciphertext1 - vector for first cipher text * @param ciphertext2 - vector for second cipher text * @param quadKeySwitchHint - is the quadratic key switch hint from original private key to the quadratic key * return vector of resulting ciphertext */ Ciphertext<Element> ComposedEvalMult( ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2) const { if( ciphertext1 == NULL || ciphertext2 == NULL || ciphertext1->GetKeyTag() != ciphertext2->GetKeyTag() || Mismatched(ciphertext1->GetCryptoContext()) ) throw std::logic_error("Ciphertexts passed to ComposedEvalMult were not generated with this crypto context"); auto ek = GetEvalMultKeyVector(ciphertext1->GetKeyTag()); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->ComposedEvalMult(ciphertext1, ciphertext2, ek[0]); if( doTiming ) { timeSamples->push_back( TimingInfo(OpComposedEvalMult, TOC_US(t)) ); } return rv; } static LPPublicKey<Element> deserializePublicKey(const Serialized& serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static LPPrivateKey<Element> deserializeSecretKey(const Serialized& serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static LPEvalKey<Element> deserializeEvalKey(const Serialized& serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); static LPEvalKey<Element> deserializeEvalKeyInContext(const Serialized& serObj, CryptoContext<Element> cc) __attribute__ ((deprecated("serialization changed, see wiki for details"))); template <class Archive> void save( Archive & ar, std::uint32_t const version ) const { ar( ::cereal::make_nvp("cc", params) ); ar( ::cereal::make_nvp("kt", scheme) ); } template <class Archive> void load( Archive & ar, std::uint32_t const version ) { if( version > SerializedVersion() ) { PALISADE_THROW(deserialize_error, "serialized object version " + std::to_string(version) + " is from a later version of the library"); } ar( ::cereal::make_nvp("cc", params) ); ar( ::cereal::make_nvp("kt", scheme) ); // NOTE: a pointer to this object will be wrapped in a shared_ptr, and is a "CryptoContext". // PALISADE relies on the notion that identical CryptoContextImpls are not duplicated in memory // Once we deserialize this object, we must check to see if there is a matching object // for this object that's already existing in memory // if it DOES exist, use it. If it does NOT exist, add this to the cache of all contexts // That functionality gets handled in the Deserialize wrapper for CryptoContext } std::string SerializedObjectName() const { return "CryptoContext"; } static uint32_t SerializedVersion() { return 1; } }; /** * @brief CryptoObject * * A class to aid in referring to the crypto context that an object belongs to */ template<typename Element> class CryptoObject { protected: CryptoContext<Element> context; /*!< crypto context this object belongs to */ string keyTag; /*!< tag used to find the evaluation key needed for SHE/FHE operations */ public: CryptoObject(CryptoContext<Element> cc = 0, const string& tag = "") : context(cc), keyTag(tag) {} CryptoObject(const CryptoObject& rhs) { context = rhs.context; keyTag = rhs.keyTag; } CryptoObject(const CryptoObject&& rhs) { context = std::move(rhs.context); keyTag = std::move(rhs.keyTag); } virtual ~CryptoObject() {} const CryptoObject& operator=(const CryptoObject& rhs) { this->context = rhs.context; this->keyTag = rhs.keyTag; return *this; } const CryptoObject& operator=(const CryptoObject&& rhs) { this->context = std::move(rhs.context); this->keyTag = std::move(rhs.keyTag); return *this; } bool operator==(const CryptoObject& rhs) const { return context.get() == rhs.context.get() && keyTag == rhs.keyTag; } CryptoContext<Element> GetCryptoContext() const { return context; } const shared_ptr<LPCryptoParameters<Element>> GetCryptoParameters() const { return context->GetCryptoParameters(); } const EncodingParams GetEncodingParameters() const { return context->GetCryptoParameters()->GetEncodingParams(); } const string GetKeyTag() const { return keyTag; } void SetKeyTag(const string& tag) { keyTag = tag; } template <class Archive> void save( Archive & ar, std::uint32_t const version ) const { ar( ::cereal::make_nvp("cc", context) ); ar( ::cereal::make_nvp("kt", keyTag) ); } template <class Archive> void load( Archive & ar, std::uint32_t const version ) { if( version > SerializedVersion() ) { PALISADE_THROW(deserialize_error, "serialized object version " + std::to_string(version) + " is from a later version of the library"); } ar( ::cereal::make_nvp("cc", context) ); ar( ::cereal::make_nvp("kt", keyTag) ); context = CryptoContextFactory<Element>::GetContext(context->GetCryptoParameters(),context->GetEncryptionAlgorithm()); } std::string SerializedObjectName() const { return "CryptoObject"; } static uint32_t SerializedVersion() { return 1; } }; /** * @brief CryptoContextFactory * * A class that contains static methods to generate new crypto contexts from user parameters * */ template<typename Element> class CryptoContextFactory { static vector<CryptoContext<Element>> AllContexts; public: static void ReleaseAllContexts(); static int GetContextCount(); static CryptoContext<Element> GetSingleContext(); static CryptoContext<Element> GetContext( shared_ptr<LPCryptoParameters<Element>> params, shared_ptr<LPPublicKeyEncryptionScheme<Element>> scheme); static CryptoContext<Element> GetContextForPointer(CryptoContextImpl<Element>* cc); static const vector<CryptoContext<Element>>& GetAllContexts(); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme * @param params ring parameters * @param plaintextModulus plaintext modulus * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param delta - the plaintext scaling parameter floor(q/t) in BFV * @param mode - mode for generating secret keys (RLWE vs OPTIMIZED) * @param bigmodulus - large modulus used in tensoring of homomorphic multiplication * @param bigrootofunity - root of unity for bigmodulus * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @param bigmodulusarb - additional large modulus for bigmoduls for the case of general (non-power-of-two) cyclotomics * @param bigrootofunityarb - root of unity for bigmodulusarb * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV(shared_ptr<typename Element::Params> params, const PlaintextModulus plaintextmodulus, usint relinWindow, float stDev, const std::string& delta, MODE mode = RLWE, const std::string& bigmodulus = "0", const std::string& bigrootofunity = "0", int depth = 0, int assuranceMeasure = 0, float securityLevel = 0, const std::string& bigmodulusarb = "0", const std::string& bigrootofunityarb = "0", int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme * @param params ring parameters * @param encodingParams plaintext encoding parameters * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param delta - the plaintext scaling parameter floor(q/t) in BFV * @param mode - mode for generating secret keys (RLWE vs OPTIMIZED) * @param bigmodulus - large modulus used in tensoring of homomorphic multiplication * @param bigrootofunity - root of unity for bigmodulus * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @param bigmodulusarb - additional large modulus for bigmoduls for the case of general (non-power-of-two) cyclotomics * @param bigrootofunityarb - root of unity for bigmodulusarb * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV(shared_ptr<typename Element::Params> params, EncodingParams encodingParams, usint relinWindow, float stDev, const std::string& delta, MODE mode = RLWE, const std::string& bigmodulus = "0", const std::string& bigrootofunity = "0", int depth = 0, int assuranceMeasure = 0, float securityLevel = 0, const std::string& bigmodulusarb = "0", const std::string& bigrootofunityarb = "0", int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel root Hermite factor (lattice security parameter) * @param relinWindow bits in the base of digits in key switching/relinearization * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV( const PlaintextModulus plaintextModulus, float securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel standard security level * @param relinWindow bits in the base of digits in key switching/relinearization * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV( const PlaintextModulus plaintextModulus, SecurityLevel securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel root Hermite factor (lattice security parameter) * @param distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV( EncodingParams encodingParams, float securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel standard security level * @param distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV( EncodingParams encodingParams, SecurityLevel securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFVrns Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel root Hermite factor (lattice security parameter) * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window (bits in the base for digits) used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrns( const PlaintextModulus plaintextModulus, float securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrns Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel standard secuirity level * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window (bits in the base for digits) used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrns( const PlaintextModulus plaintextModulus, SecurityLevel securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrns Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel root Hermite factor (lattice security parameter) * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrns( EncodingParams encodingParams, float securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrns Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel standard security level * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrns( EncodingParams encodingParams, SecurityLevel securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrnsB Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel root Hermite factor (lattice security parameter) * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrnsB( const PlaintextModulus plaintextModulus, float securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrnsB Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel standard security level * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrnsB( const PlaintextModulus plaintextModulus, SecurityLevel securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrnsB Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel root Hermite factor (lattice security parameter) * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrnsB( EncodingParams encodingParams, float securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrnsB Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel standard security level * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrnsB( EncodingParams encodingParams, SecurityLevel securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BGV Scheme * @param params ring parameters * @param plaintextModulus plaintext modulus * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param depth of supported computation circuit (not used; for future use) * @return new context */ static CryptoContext<Element> genCryptoContextBGV(shared_ptr<typename Element::Params> params, const PlaintextModulus plaintextmodulus, usint relinWindow, float stDev, MODE mode = RLWE, int depth = 1); /** * construct a PALISADE CryptoContextImpl for the BGV Scheme * @param params ring parameters * @param encodingParams plaintext encoding parameters * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param depth of supported computation circuit (not used; for future use) * @return new context */ static CryptoContext<Element> genCryptoContextBGV(shared_ptr<typename Element::Params> params, EncodingParams encodingParams, usint relinWindow, float stDev, MODE mode = RLWE, int depth = 1); /** * construct a PALISADE CryptoContextImpl for the StehleSteinfeld Scheme * @param params ring parameters * @param plaintextModulus plaintext modulus * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param stdDev distribution parameter for secret key distribution * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @return new context */ static CryptoContext<Element> genCryptoContextStehleSteinfeld(shared_ptr<typename Element::Params> params, const PlaintextModulus plaintextmodulus, usint relinWindow, float stDev, float stDevStSt, int depth = 1, int assuranceMeasure = 9, float securityLevel = 1.006); /** * construct a PALISADE CryptoContextImpl for the StehleSteinfeld Scheme * @param params ring parameters * @param encodingParams plaintext encoding parameters * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param stdDev distribution parameter for secret key distribution * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @return new context */ static CryptoContext<Element> genCryptoContextStehleSteinfeld(shared_ptr<typename Element::Params> params, EncodingParams encodingParams, usint relinWindow, float stDev, float stDevStSt, int depth = 1, int assuranceMeasure = 9, float securityLevel = 1.006); /** * construct a PALISADE CryptoContextImpl for the Null Scheme * @param m cyclotomic order (ring dimension n = m/2 for power-of-two cyclotomics) * @param plaintextModulus plaintext modulus * @return */ static CryptoContext<Element> genCryptoContextNull(unsigned int m, const PlaintextModulus ptModulus); /** * construct a PALISADE CryptoContextImpl for the Null Scheme * @param m cyclotomic order (ring dimension n = m/2 for power-of-two cyclotomics) * @param encodingParams plaintext encoding parameters * @return */ static CryptoContext<Element> genCryptoContextNull(unsigned int m, EncodingParams encodingParams); static CryptoContext<Element> DeserializeAndCreateContext(const Serialized& serObj) __attribute__ ((deprecated("serialization changed, see wiki for details"))); }; } #endif /* SRC_DEMO_PRE_CRYPTOCONTEXT_H_ */
CPULauncher.h
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ---------------------------------------------------------------------------- #pragma once #include <vector> #include "open3d/core/AdvancedIndexing.h" #include "open3d/core/Indexer.h" #include "open3d/core/Tensor.h" #include "open3d/core/kernel/ParallelUtil.h" #include "open3d/utility/Logging.h" namespace open3d { namespace core { namespace kernel { class CPULauncher { public: /// Fills tensor[:][i] with element_kernel(i). /// /// \param indexer The input tensor and output tensor to the indexer are the /// same (as a hack), since the tensor are filled in-place. /// \param element_kernel A function that takes pointer location and /// workload_idx, computes the value to fill, and fills the value at the /// pointer location. template <typename func_t> static void LaunchIndexFillKernel(const Indexer& indexer, func_t element_kernel) { #pragma omp parallel for schedule(static) for (int64_t workload_idx = 0; workload_idx < indexer.NumWorkloads(); ++workload_idx) { element_kernel(indexer.GetInputPtr(0, workload_idx), workload_idx); } } template <typename func_t> static void LaunchUnaryEWKernel(const Indexer& indexer, func_t element_kernel) { #pragma omp parallel for schedule(static) for (int64_t workload_idx = 0; workload_idx < indexer.NumWorkloads(); ++workload_idx) { element_kernel(indexer.GetInputPtr(0, workload_idx), indexer.GetOutputPtr(workload_idx)); } } template <typename func_t> static void LaunchBinaryEWKernel(const Indexer& indexer, func_t element_kernel) { #pragma omp parallel for schedule(static) for (int64_t workload_idx = 0; workload_idx < indexer.NumWorkloads(); ++workload_idx) { element_kernel(indexer.GetInputPtr(0, workload_idx), indexer.GetInputPtr(1, workload_idx), indexer.GetOutputPtr(workload_idx)); } } template <typename func_t> static void LaunchAdvancedIndexerKernel(const AdvancedIndexer& indexer, func_t element_kernel) { #pragma omp parallel for schedule(static) for (int64_t workload_idx = 0; workload_idx < indexer.NumWorkloads(); ++workload_idx) { element_kernel(indexer.GetInputPtr(workload_idx), indexer.GetOutputPtr(workload_idx)); } } template <typename scalar_t, typename func_t> static void LaunchReductionKernelSerial(const Indexer& indexer, func_t element_kernel) { for (int64_t workload_idx = 0; workload_idx < indexer.NumWorkloads(); ++workload_idx) { element_kernel(indexer.GetInputPtr(0, workload_idx), indexer.GetOutputPtr(workload_idx)); } } /// Create num_threads workers to compute partial reductions and then reduce /// to the final results. This only applies to reduction op with one output. template <typename scalar_t, typename func_t> static void LaunchReductionKernelTwoPass(const Indexer& indexer, func_t element_kernel, scalar_t identity) { if (indexer.NumOutputElements() > 1) { utility::LogError( "Internal error: two-pass reduction only works for " "single-output reduction ops."); } int64_t num_workloads = indexer.NumWorkloads(); int64_t num_threads = GetMaxThreads(); int64_t workload_per_thread = (num_workloads + num_threads - 1) / num_threads; std::vector<scalar_t> thread_results(num_threads, identity); #pragma omp parallel for schedule(static) for (int64_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) { int64_t start = thread_idx * workload_per_thread; int64_t end = std::min(start + workload_per_thread, num_workloads); for (int64_t workload_idx = start; workload_idx < end; ++workload_idx) { element_kernel(indexer.GetInputPtr(0, workload_idx), &thread_results[thread_idx]); } } void* output_ptr = indexer.GetOutputPtr(0); for (int64_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) { element_kernel(&thread_results[thread_idx], output_ptr); } } template <typename scalar_t, typename func_t> static void LaunchReductionParallelDim(const Indexer& indexer, func_t element_kernel) { // Prefers outer dimension >= num_threads. const int64_t* indexer_shape = indexer.GetMasterShape(); const int64_t num_dims = indexer.NumDims(); int64_t num_threads = GetMaxThreads(); // Init best_dim as the outer-most non-reduction dim. int64_t best_dim = num_dims - 1; while (best_dim >= 0 && indexer.IsReductionDim(best_dim)) { best_dim--; } for (int64_t dim = best_dim; dim >= 0 && !indexer.IsReductionDim(dim); --dim) { if (indexer_shape[dim] >= num_threads) { best_dim = dim; break; } else if (indexer_shape[dim] > indexer_shape[best_dim]) { best_dim = dim; } } if (best_dim == -1) { utility::LogError( "Internal error: all dims are reduction dims, use " "LaunchReductionKernelTwoPass instead."); } #pragma omp parallel for schedule(static) for (int64_t i = 0; i < indexer_shape[best_dim]; ++i) { Indexer sub_indexer(indexer); sub_indexer.ShrinkDim(best_dim, i, 1); LaunchReductionKernelSerial<scalar_t>(sub_indexer, element_kernel); } } /// General kernels with non-conventional indexers template <typename func_t> static void LaunchGeneralKernel(int64_t n, func_t element_kernel) { #pragma omp parallel for schedule(static) for (int64_t workload_idx = 0; workload_idx < n; ++workload_idx) { element_kernel(workload_idx); } } }; } // namespace kernel } // namespace core } // namespace open3d
solver.c
#include"SimpleMOC_header.h" /* Efficient version of attenuate fluxes which determines the change in angular * flux along a particular track across a fine axial region and tallies the * contribution to the scalar flux in the fine axial region. This function * assumes a quadratic source, which is calculated on the fly using neighboring * source values. * * This version decomposes the work into many for loops for efficient SIMD * instructions and to reduce register pressure. For a more descriptive * (but less effiient) version of the code in terms of the underlying physics, * see alt_attenuate_fluxes which solves the problem in a more naive, * straightforward manner. */ void attenuate_fluxes( Track * track, bool forward, Source * QSR, Input * I_in, Params * params_in, float ds, float mu, float az_weight, AttenuateVars * A ) { Input I = *I_in; Params params = *params_in; // unload attenuate vars float * restrict q0 = A->q0; float * restrict q1 = A->q1; float * restrict q2 = A->q2; float * restrict sigT = A->sigT; float * restrict tau = A->tau; float * restrict sigT2 = A->sigT2; float * restrict expVal = A->expVal; float * restrict reuse = A->reuse; float * restrict flux_integral = A->flux_integral; float * restrict tally = A->tally; float * restrict t1 = A->t1; float * restrict t2 = A->t2; float * restrict t3 = A->t3; float * restrict t4 = A->t4; // compute fine axial interval spacing float dz = I.height / (I.fai * I.decomp_assemblies_ax * I.cai); // compute z height in cell float zin = track->z_height - dz * ( (int)( track->z_height / dz ) + 0.5f ); // compute fine axial region ID int fine_id = (int) ( track->z_height / dz ) % I.fai; // compute weight (azimuthal * polar) // NOTE: real app would also have volume weight component float weight = track->p_weight * az_weight; float mu2 = mu * mu; // load fine source region flux vector float * FSR_flux = QSR -> fine_flux[fine_id]; if( fine_id == 0 ) { // adjust z height to account for edge zin -= dz; // cycle over energy groups #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) { // load neighboring sources float y1 = QSR->fine_source[fine_id][g]; float y2 = QSR->fine_source[fine_id+1][g]; float y3 = QSR->fine_source[fine_id+2][g]; // do quadratic "fitting" float c0 = y2; float c1 = (y1 - y3) / (2.f*dz); float c2 = (y1 - 2.f*y2 + y3) / (2.f*dz*dz); // calculate q0, q1, q2 q0[g] = c0 + c1*zin + c2*zin*zin; q1[g] = c1 + 2.f*c2*zin; q2[g] = c2; } } else if ( fine_id == I.fai - 1 ) { // adjust z height to account for edge zin += dz; // cycle over energy groups #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) { // load neighboring sources float y1 = QSR->fine_source[fine_id-2][g]; float y2 = QSR->fine_source[fine_id-1][g]; float y3 = QSR->fine_source[fine_id][g]; // do quadratic "fitting" float c0 = y2; float c1 = (y1 - y3) / (2.f*dz); float c2 = (y1 - 2.f*y2 + y3) / (2.f*dz*dz); // calculate q0, q1, q2 q0[g] = c0 + c1*zin + c2*zin*zin; q1[g] = c1 + 2.f*c2*zin; q2[g] = c2; } } else { // cycle over energy groups #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) { // load neighboring sources float y1 = QSR->fine_source[fine_id-1][g]; float y2 = QSR->fine_source[fine_id][g]; float y3 = QSR->fine_source[fine_id+1][g]; // do quadratic "fitting" float c0 = y2; float c1 = (y1 - y3) / (2.f*dz); float c2 = (y1 - 2.f*y2 + y3) / (2.f*dz*dz); // calculate q0, q1, q2 q0[g] = c0 + c1*zin + c2*zin*zin; q1[g] = c1 + 2.f*c2*zin; q2[g] = c2; } } // cycle over energy groups #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) { // load total cross section sigT[g] = QSR->sigT[g]; // calculate common values for efficiency tau[g] = sigT[g] * ds; sigT2[g] = sigT[g] * sigT[g]; } // cycle over energy groups #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) expVal[g] = interpolateTable( params.expTable, tau[g] ); // Flux Integral // Re-used Term #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) { reuse[g] = tau[g] * (tau[g] - 2.f) + 2.f * expVal[g] / (sigT[g] * sigT2[g]); } float * psi; if(forward) psi = track->f_psi; else psi = track->b_psi; //#pragma vector nontemporal #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) { // add contribution to new source flux flux_integral[g] = (q0[g] * tau[g] + (sigT[g] * psi[g] - q0[g]) * expVal[g]) / sigT2[g] + q1[g] * mu * reuse[g] + q2[g] * mu2 * (tau[g] * (tau[g] * (tau[g] - 3.f) + 6.f) - 6.f * expVal[g]) / (3.f * sigT2[g] * sigT2[g]); } #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) { // Prepare tally tally[g] = weight * flux_integral[g]; } #ifdef OPENMP omp_set_lock(QSR->locks + fine_id); #endif #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) { FSR_flux[g] += tally[g]; } #ifdef OPENMP omp_unset_lock(QSR->locks + fine_id); #endif // Term 1 #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) { t1[g] = q0[g] * expVal[g] / sigT[g]; } // Term 2 #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) { t2[g] = q1[g] * mu * (tau[g] - expVal[g]) / sigT2[g]; } // Term 3 #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) { t3[g] = q2[g] * mu2 * reuse[g]; } // Term 4 #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) { t4[g] = psi[g] * (1.f - expVal[g]); } // Total psi #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I.n_egroups; g++) { psi[g] = t1[g] + t2[g] + t3[g] + t4[g]; } } // single direction transport sweep void transport_sweep( Params * params, Input * I ) { if(I->mype==0) printf("Starting transport sweep ...\n"); // calculate the height of a node's domain and of each FSR double node_delta_z = I->height / I->decomp_assemblies_ax; double fine_delta_z = node_delta_z / (I->cai * I->fai); /* loop over tracks (implicitly azimuthal angles, tracks in azimuthal * angles, polar angles, and z stacked rays) */ //print_Input_struct( I ); long segments_processed = 0; #pragma omp parallel default(none) \ shared( I, params, node_delta_z, fine_delta_z ) \ reduction(+ : segments_processed ) { #ifdef OPENMP int thread = omp_get_thread_num(); int nthreads = omp_get_num_threads(); unsigned int seed = time(NULL) * (thread+1); #endif //print_Input_struct( I ); #ifdef PAPI int eventset = PAPI_NULL; int num_papi_events; #pragma omp critical { counter_init(&eventset, &num_papi_events, I); } #endif AttenuateVars A; float * ptr = (float * ) malloc( I->n_egroups * 14 * sizeof(float)); A.q0 = ptr; ptr += I->n_egroups; A.q1 = ptr; ptr += I->n_egroups; A.q2 = ptr; ptr += I->n_egroups; A.sigT = ptr; ptr += I->n_egroups; A.tau = ptr; ptr += I->n_egroups; A.sigT2 = ptr; ptr += I->n_egroups; A.expVal = ptr; ptr += I->n_egroups; A.reuse = ptr; ptr += I->n_egroups; A.flux_integral = ptr; ptr += I->n_egroups; A.tally = ptr; ptr += I->n_egroups; A.t1 = ptr; ptr += I->n_egroups; A.t2 = ptr; ptr += I->n_egroups; A.t3 = ptr; ptr += I->n_egroups; A.t4 = ptr; #pragma omp for schedule( dynamic ) for (long i = 0; i < I->ntracks_2D; i++) { #if TIMING_INFO | 0 // print progress #ifdef OPENMP if(I->mype==0 && thread == 0) { printf("\rAttenuating Tracks... (%.0lf%% completed)", (i / ( (double)I->ntracks_2D / (double) nthreads )) / (double) nthreads * 100.0); } #else if( i % 50 == 0) if(I->mype==0) printf("%s%ld%s%ld\n","2D Tracks Completed = ", i," / ", I->ntracks_2D ); #endif #endif // treat positive-z traveling rays first bool pos_z_dir = true; for( int j = 0; j < I->n_polar_angles; j++) { if( j == I->n_polar_angles / 2 ) pos_z_dir = false; float p_angle = params->polar_angles[j]; float mu = cos(p_angle); // start with all z stacked rays int begin_stacked = 0; int end_stacked = I->z_stacked; for( int n = 0; n < params->tracks_2D[i].n_segments; n++) { // calculate distance traveled in cell if segment completed float s_full = params->tracks_2D[i].segments[n].length / sin(p_angle); // allocate varaible for distance traveled in an FSR float ds = 0; // loop over remaining z-stacked rays for( int k = begin_stacked; k < end_stacked; k++) { // initialize s to full length float s = s_full; // select current track Track * track = &params->tracks[i][j][k]; // set flag for completeion of segment bool seg_complete = false; // calculate interval int curr_interval; if( pos_z_dir) curr_interval = get_pos_interval(track->z_height, fine_delta_z); else curr_interval = get_neg_interval(track->z_height, fine_delta_z); while( !seg_complete ) { // flag to reset z position bool reset = false; /* calculate new height based on s * (distance traveled in FSR) */ float z = track->z_height + s * cos(p_angle); // check if still in same FSR (fine axial interval) int new_interval; if( pos_z_dir ) new_interval = get_pos_interval(z, fine_delta_z); else new_interval = get_neg_interval(z, fine_delta_z); if( new_interval == curr_interval ) { seg_complete = true; ds = s; } // otherwise, we need to recalculate distances else { // correct z if( pos_z_dir ) { curr_interval++; z = fine_delta_z * (float) curr_interval; } else{ curr_interval--; z = fine_delta_z * (float) curr_interval; } // calculate distance travelled in FSR (ds) ds = (z - track->z_height) / cos(p_angle); // update track length remaining s -= ds; /* check remaining track length to protect * against potential roundoff errors */ if( s <= 0 ) seg_complete = true; // check if out of bounds or track complete if( z <= 0 || z >= node_delta_z ) { // mark segment as completed seg_complete = true; // remember to no longer treat this track if ( pos_z_dir ) end_stacked--; else begin_stacked++; // reset z height reset = true; } } // pick a random FSR (cache miss expected) #ifdef OPENMP long QSR_id = rand_r(&seed) % I->n_source_regions_per_node; #else long QSR_id = rand() % I->n_source_regions_per_node; #endif /* update sources and fluxes from attenuation * over FSR */ if( I->axial_exp == 2 ) { attenuate_fluxes( track, true, &params->sources[QSR_id], I, params, ds, mu, params->tracks_2D[i].az_weight, &A ); segments_processed++; } else if( I->axial_exp == 0 ) { attenuate_FSR_fluxes( track, true, &params->sources[QSR_id], I, params, ds, mu, params->tracks_2D[i].az_weight, &A ); segments_processed++; } else { printf("Error: invalid axial expansion order"); printf("\n Please input 0 or 2\n"); exit(1); } // update with new z height or reset if finished if( n == params->tracks_2D[i].n_segments - 1 || reset) { if( pos_z_dir) track->z_height = I->axial_z_sep * k; else track->z_height = I->axial_z_sep * (k+1); } else track->z_height = z; } } } } } #ifdef OPENMP if(thread == 0 && I->mype==0) printf("\n"); #endif #ifdef PAPI if( thread == 0 ) { printf("\n"); border_print(); center_print("PAPI COUNTER RESULTS", 79); border_print(); printf("Count \tSmybol \tDescription\n"); } { #pragma omp barrier } counter_stop(&eventset, num_papi_events, I); #endif } I->segments_processed = segments_processed; return; } // run one full transport sweep, return k void two_way_transport_sweep( Params * params, Input * I ) { if(I->mype==0) printf("Starting transport sweep ...\n"); // calculate the height of a node's domain and of each FSR double node_delta_z = I->height / I->decomp_assemblies_ax; int num_intervals = (I->cai * I->fai); double fine_delta_z = node_delta_z / num_intervals; /* loop over tracks (implicitly azimuthal angles, tracks in azimuthal * angles, polar angles, and z stacked rays) */ long segments_processed = 0; #pragma omp parallel default(none) \ shared( I, params, node_delta_z, fine_delta_z, num_intervals ) \ reduction(+ : segments_processed ) { #ifdef OPENMP int thread = omp_get_thread_num(); int nthreads = omp_get_num_threads(); unsigned int seed = time(NULL) * (thread+1); #endif //print_Input_struct( I ); #ifdef PAPI int eventset = PAPI_NULL; int num_papi_events; #pragma omp critical { counter_init(&eventset, &num_papi_events, I); } #endif AttenuateVars A; float * ptr = (float * ) malloc( I->n_egroups * 14 * sizeof(float)); A.q0 = ptr; ptr += I->n_egroups; A.q1 = ptr; ptr += I->n_egroups; A.q2 = ptr; ptr += I->n_egroups; A.sigT = ptr; ptr += I->n_egroups; A.tau = ptr; ptr += I->n_egroups; A.sigT2 = ptr; ptr += I->n_egroups; A.expVal = ptr; ptr += I->n_egroups; A.reuse = ptr; ptr += I->n_egroups; A.flux_integral = ptr; ptr += I->n_egroups; A.tally = ptr; ptr += I->n_egroups; A.t1 = ptr; ptr += I->n_egroups; A.t2 = ptr; ptr += I->n_egroups; A.t3 = ptr; ptr += I->n_egroups; A.t4 = ptr; #pragma omp for schedule( dynamic ) for (long i = 0; i < I->ntracks_2D; i++) { // print progress #ifdef OPENMP if(I->mype==0 && thread == 0) { printf("\rAttenuating Tracks... (%.0lf%% completed)", (i / ( (double)I->ntracks_2D / (double) nthreads )) / (double) nthreads * 100.0); } #else if( i % 50 == 0) if(I->mype==0) printf("%s%ld%s%ld\n","2D Tracks Completed = ", i," / ", I->ntracks_2D ); #endif // allocate arrays for segment storage FIXME double ** seg_dist = malloc( I->z_stacked * sizeof(double *) ); Source *** seg_src = malloc( I->z_stacked * sizeof(Source**) ); int * seg_idx = malloc( I->z_stacked * sizeof(int) ); int * seg_size = malloc( I->z_stacked * sizeof(int) ); // fill matrix with arrays FIXME for( int k = 0; k < I->z_stacked; k++) { seg_size[k] = 2 * I->segments_per_track; seg_dist[k] = malloc( seg_size[k] * sizeof(double) ); seg_src[k] = malloc( seg_size[k] * sizeof(Source *) ); seg_idx[k] = 0; } // treat positive-z traveling rays first bool pos_z_dir = true; for( int j = 0; j < I->n_polar_angles; j++) { if( j == I->n_polar_angles / 2 ) pos_z_dir = false; float p_angle = params->polar_angles[j]; float mu = cos(p_angle); // start with all z stacked rays int begin_stacked = 0; int end_stacked = I->z_stacked; // reset semgnet indexes for( int k = 0; k < I->z_stacked; k++) seg_idx[k] = 0; for( int n = 0; n < params->tracks_2D[i].n_segments; n++) { // calculate distance traveled in cell if segment completed float s_full = params->tracks_2D[i].segments[n].length / sin(p_angle); // allocate varaible for distance traveled in an FSR float ds = 0; // loop over remaining z-stacked rays int tracks_completed = 0; for( int k = begin_stacked; k < end_stacked; k++) { // select current track Track * track = &params->tracks[i][j][k]; // determine current axial interval int interval = (int) track->z_height / fine_delta_z; // calculate distance to domain boundary float bound_dist; if( pos_z_dir) bound_dist = (node_delta_z - track->z_height) / mu; else bound_dist = -track->z_height / mu; // determine track length float s; if( s_full < bound_dist ) s = s_full; else { // note completion of track s = bound_dist; tracks_completed++; } // set flag for completeion of segment bool seg_complete = false; while( !seg_complete ) { // initialize tracking variables long QSR_id = interval + num_intervals * n; float ds; float z; // calculate z height of next fine axial interval float fai_z_height; if( pos_z_dir ) fai_z_height = (interval + 1) * fine_delta_z ; else fai_z_height = interval * fine_delta_z; // calculate z distance to next fine axial interval float z_dist_to_fai = fai_z_height - track->z_height; /* calculate total distance (s) to fine axial * interval */ float s_dist_to_fai = z_dist_to_fai / mu; // determine if a fine axial interval is crossed if( s_dist_to_fai < s ) { if( pos_z_dir ) interval++; else interval--; ds = s_dist_to_fai; z = track->z_height + z_dist_to_fai; } else { ds = s; z = track->z_height + s * mu; } /* shorten remaining segment length and check if * completed (accounting for potential roundoff) */ s -= ds; if( s <= 0 || interval < 0 || interval >= num_intervals) seg_complete = true; // pick a random FSR (cache miss expected) #ifdef OPENMP QSR_id = rand_r(&seed) % I->n_source_regions_per_node; #else QSR_id = rand() % I->n_source_regions_per_node; #endif /* update sources and fluxes from attenuation * over FSR */ if( I->axial_exp == 2 ) { attenuate_fluxes( track, true, &params->sources[QSR_id], I, params, ds, mu, params->tracks_2D[i].az_weight, &A ); segments_processed++; } else if( I->axial_exp == 0 ) attenuate_FSR_fluxes( track, true, &params->sources[QSR_id], I, params, ds, mu, params->tracks_2D[i].az_weight, &A ); else { printf("Error: invalid axial expansion order"); printf("\n Please input 0 or 2\n"); exit(1); } // update track height track->z_height = z; // save segment length and source FIXME seg_dist[k][seg_idx[k]] = ds; seg_src[k][seg_idx[k]] = &params->sources[QSR_id]; seg_idx[k]++; // check if array needs to grow FIXME if( seg_idx[k] >= seg_size[k] ) { seg_size[k] *= 2; seg_dist[k] = (double *) realloc( seg_dist[k], seg_size[k] * sizeof(double) ); seg_src[k] = (Source **) realloc( seg_src[k], seg_size[k] * sizeof(Source *) ); } } } if(pos_z_dir) end_stacked -= tracks_completed; else begin_stacked += tracks_completed; } // loop over all z stacked rays again for( int k = 0; k < I->z_stacked; k++ ) { for( int n = seg_idx[k]-1; n >= 0; n--) { // load distance float ds = seg_dist[k][n]; // select current track Track * track = &params->tracks[i][j][k]; // update sources and fluxes from attenuation over FSR if( I->axial_exp == 2 ) { attenuate_fluxes( track, false, seg_src[k][n], I, params, ds, -mu, params->tracks_2D[i].az_weight, &A ); segments_processed++; } else if( I->axial_exp == 0 ) attenuate_FSR_fluxes( track, false, seg_src[k][n], I, params, ds, -mu, params->tracks_2D[i].az_weight, &A ); // update z height track->z_height -= ds * mu; } } /* Update all tracks with correct starting z location again * NOTE: this is only here to acocunt for roundoff error */ for( int k = 0; k < I->z_stacked; k++) { Track * track = &params->tracks[i][j][k]; if( pos_z_dir) track->z_height = I->axial_z_sep * k; else track->z_height = I->axial_z_sep * (k+1); } } // free memory for( int k = 0; k < I->z_stacked; k++) { free(seg_dist[k]); free(seg_src[k]); } free(seg_dist); free(seg_src); free(seg_idx); free(seg_size); } #ifdef OPENMP if(thread == 0 && I->mype==0) printf("\n"); #endif #ifdef PAPI if( thread == 0 ) { printf("\n"); border_print(); center_print("PAPI COUNTER RESULTS", 79); border_print(); printf("Count \tSmybol \tDescription\n"); } { #pragma omp barrier } counter_stop(&eventset, num_papi_events, I); #endif } //printf("Number of segments processed: %ld\n", segments_processed); I->segments_processed = segments_processed; return; } /* returns integer number for axial interval for tracks traveling in the * positive direction */ int get_pos_interval( float z, float dz) { int interval = (int) (z/dz); return interval; } /* returns integer number for axial interval for tracks traveling in the * negative direction */ int get_neg_interval( float z, float dz) { int interval = (int) ( ceilf( z / dz ) ); return interval; } int calc_next_fai( float z, float dz, bool pos_dir) { int interval = z/dz; float lower_z = dz * (float) interval; if(pos_dir) return interval + 1; else return interval; } /* Determines the change in angular flux along a particular track across a fine * axial region and tallies the contribution to the scalar flux in the fine * axial region. This function assumes a quadratic source, which is calculated * on the fly using neighboring source values. * * This legacy function is unused since it is less efficient than the current * attenuate_fluxes function. However, it provides a more straightforward * description of the underlying physical problem. */ void alt_attenuate_fluxes( Track * track, bool forward, Source * QSR, Input * I, Params * params, float ds, float mu, float az_weight ) { // compute fine axial interval spacing float dz = I->height / (I->fai * I->decomp_assemblies_ax * I->cai); // compute z height in cell float zin = track->z_height - dz * ( (int)( track->z_height / dz ) + 0.5 ); // compute fine axial region ID int fine_id = (int) ( track->z_height / dz ) % I->fai; // compute weight (azimuthal * polar) // NOTE: real app would also have volume weight component float weight = track->p_weight * az_weight; float mu2 = mu * mu; // load fine source region flux vector float * FSR_flux = QSR -> fine_flux[fine_id]; // cycle over energy groups for( int g = 0; g < I->n_egroups; g++) { // load total cross section float sigT = QSR->sigT[g]; // define source parameters float q0, q1, q2; // calculate source components if( fine_id == 0 ) { // load neighboring sources float y2 = QSR->fine_source[fine_id][g]; float y3 = QSR->fine_source[fine_id+1][g]; // do linear "fitting" float c0 = y2; float c1 = (y3 - y2) / dz; // calculate q0, q1, q2 q0 = c0 + c1*zin; q1 = c1; q2 = 0; } else if( fine_id == I->fai - 1 ) { // load neighboring sources float y1 = QSR->fine_source[fine_id-1][g]; float y2 = QSR->fine_source[fine_id][g]; // do linear "fitting" float c0 = y2; float c1 = (y2 - y1) / dz; // calculate q0, q1, q2 q0 = c0 + c1*zin; q1 = c1; q2 = 0; } else { // load neighboring sources float y1 = QSR->fine_source[fine_id-1][g]; float y2 = QSR->fine_source[fine_id][g]; float y3 = QSR->fine_source[fine_id+1][g]; // do quadratic "fitting" float c0 = y2; float c1 = (y1 - y3) / (2*dz); float c2 = (y1 - 2*y2 + y3) / (2*dz*dz); // calculate q0, q1, q2 q0 = c0 + c1*zin + c2*zin*zin; q1 = c1 + 2*c2*zin; q2 = c2; } // calculate common values for efficiency float tau = sigT * ds; float sigT2 = sigT * sigT; // compute exponential ( 1 - exp(-x) ) using table lookup float expVal = interpolateTable( params->expTable, tau ); // load correct angular flux vector float * psi; if(forward) psi = track->f_psi; else psi = track->b_psi; // add contribution to new source flux float flux_integral = (q0 * tau + (sigT * psi[g] - q0) * expVal) / sigT2 + q1 * mu * (tau * (tau - 2) + 2 * expVal) / (sigT * sigT2) + q2 * mu2 * (tau * (tau * (tau - 3) + 6) - 6 * expVal) / (3 * sigT2 * sigT2); #pragma omp atomic FSR_flux[g] += weight * flux_integral; // update angular flux psi[g] = psi[g] * (1.0 - expVal) + q0 * expVal / sigT + q1 * mu * (tau - expVal) / sigT2 + q2 * mu2 * (tau * (tau - 2) + 2 * expVal) / (sigT2 * sigT); } } /* Determines the change in angular flux along a particular track across a fine * axial region and tallies the contribution to the scalar flux in the fine * axial region. This function assumes a constant source. */ void attenuate_FSR_fluxes( Track * track, bool forward, Source * FSR, Input * I, Params * params_in, float ds, float mu, float az_weight, AttenuateVars *A) { // upack attenuate vars struct float * restrict tally = A->tally; float * restrict expVal = A->expVal; float * restrict sigT = A->sigT; float * restrict tau = A->tau; Params params = * params_in; // compute fine axial interval spacing float dz = I->height / (I->fai * I->decomp_assemblies_ax * I->cai); // compute z height in cell float zin = track->z_height - dz * ( (int)( track->z_height / dz ) + 0.5f ); // compute fine axial region ID int fine_id = (int) ( track->z_height / dz ) % I->fai; // compute weight (azimuthal * polar) // NOTE: real app would also have volume weight component float weight = track->p_weight * az_weight * mu; // load fine source region flux vector float * FSR_flux = FSR -> fine_flux[fine_id]; // cycle over energy groups #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I->n_egroups; g++) { // load total cross section sigT[g] = FSR->sigT[g]; tau[g] = sigT[g] * ds; } // compute exponential ( 1 - exp(-x) ) using table lookup #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for(int g = 0; g < I->n_egroups; g++) { expVal[g] = interpolateTable( params.expTable, tau[g] ); } float * psi; if(forward) psi = track->f_psi; else psi = track->b_psi; #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I->n_egroups; g++) { // compute angular flux attenuation float q = FSR->fine_source[fine_id][g] / sigT[g]; float delta_psi = (psi[g] - q) * expVal[g]; // add contribution to new source flux tally[g] = weight * delta_psi; // update angular flux psi[g] -= delta_psi; } #ifdef OPENMP omp_set_lock(&FSR->locks[fine_id]); #endif #ifdef INTEL #pragma simd #elif defined IBM #pragma simd_level(10) #endif for( int g = 0; g < I->n_egroups; g++) { FSR_flux[g] += tally[g]; } #ifdef OPENMP omp_unset_lock(&FSR->locks[fine_id]); #endif } /* Renormalizes scalar and angular flux for next transport sweep iteration. * Calculation requires multiple pair-wise sums and a reduction accross all * nodes. */ void renormalize_flux( Params params, Input I, CommGrid grid ) { if( I.mype == 0 ) printf("Renormalizing Flux...\n"); float node_fission_rate = 0; #ifdef OPENMP #pragma omp parallel default(none) shared(params, I, grid) \ reduction(+ : node_fission_rate) { #endif // tally total fission rate (pair-wise sum) float * fission_rates = malloc( I.n_source_regions_per_node * sizeof(float) ); float * fine_fission_rates = malloc( I.fai * sizeof(float) ); float * g_fission_rates = malloc( I.n_egroups * sizeof(float) ); // accumulate total fission rate on node domain #pragma omp for schedule(dynamic) for( int i = 0; i < I.n_source_regions_per_node; i++) { Source src = params.sources[i]; for( int j = 0; j < I.fai; j++) { for( int g = 0; g < I.n_egroups; g++) g_fission_rates[g] = src.fine_flux[j][g] * src.vol * src.XS[g][0]; fine_fission_rates[j] = pairwise_sum( g_fission_rates, I.n_egroups ); } fission_rates[i] = pairwise_sum( fine_fission_rates, I.fai ); } node_fission_rate = pairwise_sum(fission_rates, I.n_source_regions_per_node); // free allocated memory free(fission_rates); free(fine_fission_rates); free(g_fission_rates); #ifdef OPENMP } #endif #ifdef MPI // accumulate total fission rate by MPI Allreduce float total_fission_rate = 0; MPI_Barrier(grid.cart_comm_3d); MPI_Allreduce( &node_fission_rate, // Send Buffer &total_fission_rate, // Receive Buffer 1, // Element Count MPI_FLOAT, // Element Type MPI_SUM, // Reduciton Operation Type grid.cart_comm_3d ); // MPI Communicator MPI_Barrier(grid.cart_comm_3d); #else float total_fission_rate = node_fission_rate; #endif // normalize fluxes by fission reaction rate float norm_factor = 1.0 / total_fission_rate; #pragma omp parallel for default(none) \ shared(I, params) private(norm_factor) schedule(dynamic) for( int i = 0; i < I.n_source_regions_per_node; i++) { Source * src = &params.sources[i]; float adjust = norm_factor * 4 * M_PI * I.fai / src->vol; for( int k = 0; k < I.fai; k++) for( int g = 0; g < I.n_egroups; g++) src->fine_flux[k][g] *= adjust; } // normalize boundary fluxes by same factor #pragma omp parallel for default(none) \ shared(I, params) private(norm_factor) schedule(dynamic) for( long i = 0; i < I.ntracks_2D; i++) for( int j = 0; j < I.n_polar_angles; j++) for( int k = 0; k < I.z_stacked; k++) for( int g = 0; g < I.n_egroups; g++) { params.tracks[i][j][k].f_psi[g] *= norm_factor; params.tracks[i][j][k].b_psi[g] *= norm_factor; } if( I.mype == 0 ) printf("Renormalizing Flux Complete.\n"); return; } /* Updates sources for next iteration by computing scattering and fission * components. Calculation includes multiple pair-wise sums and reductions * accross all nodes */ float update_sources( Params params, Input I, float keff ) { // source residual float residual; // calculate inverse multiplication facotr for efficiency float inverse_k = 1.0 / keff; // allocate residual arrays float * group_res = (float *) malloc(I.n_egroups * sizeof(float)); float * fine_res = (float *) malloc(I.fai * sizeof(float)); float * residuals = (float *) malloc(I.n_source_regions_per_node * sizeof(float)); // allocate arrays for summation float * fission_rates = malloc(I.n_egroups * sizeof(float)); float * scatter_rates = malloc(I.n_egroups * sizeof(float)); // cycle through all coarse axial intervals to update source for( long i = 0; i < I.n_source_regions_per_node; i++) { Source src = params.sources[i]; // cycle thorugh all fine axial regions to calculate new source for( int j = 0; j < I.fai; j++) { // calculate total fission source and scattering source float fission_source; float scatter_source; // compute total fission source for( int g = 0; g < I.n_egroups; g++ ) fission_rates[g] = src.fine_flux[j][g] * src.XS[g][0]; fission_source = pairwise_sum( fission_rates, (long) I.n_egroups); // normalize fission source by multiplication factor fission_source *= inverse_k; // compute scattering and new total source for each group for( int g = 0; g < I.n_egroups; g++ ) { for( int g2 = 0; g2 < I.n_egroups; g2++ ) { // compute scatter source originating from g2 -> g scatter_rates[g2] = src.scattering_matrix[g][g2] * src.fine_flux[j][g2]; } scatter_source = pairwise_sum(scatter_rates, (long) I.n_egroups); // compuate new total source float chi = src.XS[g][2]; // calculate new fine source float newSrc = (fission_source * chi + scatter_source) / (4.0 * M_PI); // calculate residual float oldSrc = src.fine_source[j][g]; group_res[g] = (newSrc - oldSrc) * (newSrc - oldSrc) / (oldSrc * oldSrc); /* calculate new source in fine axial interval assuming * isotropic source components */ src.fine_source[j][g] = newSrc; } fine_res[j] = pairwise_sum(group_res, (long) I.n_egroups); } residuals[i] = pairwise_sum(fine_res, (long) I.fai); } // calculate source residual residual = pairwise_sum(residuals, I.n_source_regions_per_node); // free memory free(fission_rates); free(scatter_rates); free(group_res); free(fine_res); free(residuals); // NOTE: See code around line 600 of CPUSolver.cpp in ClosedMOC/ OpenMOC return residual; } /* Computes globall k-effective using multiple pair-wise summations and finally * a reduction accross all nodes */ float compute_keff(Params params, Input I, CommGrid grid) { // allocate temporary memory float * sigma = malloc( I.n_egroups * sizeof(float) ); float * group_rates = malloc( I.n_egroups * sizeof(float) ); float * fine_rates = malloc( I.fai * sizeof(float) ); float * QSR_rates = malloc( I.n_source_regions_per_node * sizeof(float) ); /////////////////////////////////////////////////////////////////////////// // compute total absorption rate, looping over source regions for( long i = 0; i < I.n_source_regions_per_node; i++) { // load absorption XS data Source src = params.sources[i]; for( int g = 0; g < I.n_egroups; g++) sigma[g] = src.XS[g][1]; for( int j = 0; j < I.fai; j++ ) { // calculate absorption rates float * fine_flux = src.fine_flux[j]; for( int g = 0; g < I.n_egroups; g++) group_rates[g] = sigma[g] * fine_flux[g]; // sum absorption over all energy groups fine_rates[j] = pairwise_sum( group_rates, (long) I.n_egroups ); } // sum absorption over all fine axial intervals QSR_rates[i] = pairwise_sum( fine_rates, (long) I.fai ); } // sum absorption over all source regions in a node float node_abs = pairwise_sum( QSR_rates, I.n_source_regions_per_node); /////////////////////////////////////////////////////////////////////////// // compute total absorption rate, looping over source regions for( long i = 0; i < I.n_source_regions_per_node; i++) { // load nuSigmaF XS data Source src = params.sources[i]; for( int g = 0; g < I.n_egroups; g++) sigma[g] = src.XS[g][0]; for( int j = 0; j < I.fai; j++ ) { // calculate absorption rates float * fine_flux = src.fine_flux[j]; for( int g = 0; g < I.n_egroups; g++) group_rates[g] = sigma[g] * fine_flux[g]; // sum fission over all energy groups fine_rates[j] = pairwise_sum( group_rates, (long) I.n_egroups ); } // sum fission over all fine axial intervals QSR_rates[i] = pairwise_sum( fine_rates, (long) I.fai ); } // sum fission over all source regions in a node float node_fission = pairwise_sum( QSR_rates, I.n_source_regions_per_node); /////////////////////////////////////////////////////////////////////////// // MPi Reduction float tot_abs = 0; float tot_fission = 0; float leakage = 0; #ifdef MPI // Total Absorption Reduction MPI_Reduce( &node_abs, // Send Buffer &tot_abs, // Receive Buffer 1, // Element Count MPI_FLOAT, // Element Type MPI_SUM, // Reduciton Operation Type 0, // Master Rank grid.cart_comm_3d ); // MPI Communicator // Total Fission Reduction MPI_Reduce( &node_fission, // Send Buffer &tot_fission, // Receive Buffer 1, // Element Count MPI_FLOAT, // Element Type MPI_SUM, // Reduciton Operation Type 0, // Master Rank grid.cart_comm_3d ); // MPI Communicator // Total Leakage Reduction MPI_Reduce( params.leakage, // Send Buffer &leakage, // Receive Buffer 1, // Element Count MPI_FLOAT, // Element Type MPI_SUM, // Reduciton Operation Type 0, // Master Rank grid.cart_comm_3d ); // MPI Communicator MPI_Barrier(grid.cart_comm_3d); // calculate keff float keff = tot_fission/ (tot_abs + leakage); #else float keff = node_fission / (node_abs + *params.leakage); #endif /////////////////////////////////////////////////////////////////////////// // free memory free(sigma); free(group_rates); free(fine_rates); free(QSR_rates); return keff; } /* Interpolates a formed exponential table to compute ( 1- exp(-x) ) * at the desired x value */ float interpolateTable( Table table, float x) { // check to ensure value is in domain if( x > table.maxVal ) return 1.0f; else { int interval = (int) ( x / table.dx + 0.5f * table.dx ); /* if( interval >= table.N || interval < 0) { printf( "Interval = %d\n", interval); printf( "N = %d\n", table.N); printf( "x = %f\n", x); printf( "dx = %f\n", table.dx); exit(1); } */ float slope = table.values[ 2 * interval ]; float intercept = table.values[ 2 * interval + 1 ]; float val = slope * x + intercept; return val; } }
main.c
#include "rsbench.h" int main(int argc, char * argv[]) { // ===================================================================== // Initialization & Command Line Read-In // ===================================================================== int version = 10; double start, stop; unsigned long iseed = 0; #ifdef VERIFICATION iseed = 42; #else iseed = time(NULL); #endif // Process CLI Fields Input input = read_CLI( argc, argv ); // Set number of OpenMP Threads omp_set_num_threads(input.nthreads); // ===================================================================== // Print-out of Input Summary // ===================================================================== logo(version); center_print("INPUT SUMMARY", 79); border_print(); print_input_summary(input); // ===================================================================== // Prepare Pole Paremeter Grids // ===================================================================== border_print(); center_print("INITIALIZATION", 79); border_print(); start = omp_get_wtime(); // Allocate & fill energy grids printf("Generating resonance distributions...\n"); int * n_poles = generate_n_poles( input, &iseed ); // Allocate & fill Window grids printf("Generating window distributions...\n"); int * n_windows = generate_n_windows( input, &iseed ); // Get material data printf("Loading Hoogenboom-Martin material data...\n"); Materials materials = get_materials( input, &iseed ); // Prepare full resonance grid printf("Generating resonance parameter grid...\n"); Pole ** poles = generate_poles( input, n_poles, &iseed ); // Prepare full Window grid printf("Generating window parameter grid...\n"); Window ** windows = generate_window_params( input, n_windows, n_poles, &iseed); // Prepare 0K Resonances printf("Generating 0K l_value data...\n"); double ** pseudo_K0RS = generate_pseudo_K0RS( input, &iseed ); CalcDataPtrs data; data.n_poles = n_poles; data.n_windows = n_windows; data.materials = materials; data.poles = poles; data.windows = windows; data.pseudo_K0RS = pseudo_K0RS; stop = omp_get_wtime(); printf("Initialization Complete. (%.2lf seconds)\n", stop-start); // ===================================================================== // Cross Section (XS) Parallel Lookup Simulation Begins // ===================================================================== border_print(); center_print("SIMULATION", 79); border_print(); printf("Beginning Simulation.\n"); #ifndef STATUS printf("Calculating XS's...\n"); #endif #ifdef PAPI /* initialize papi with one thread here */ if ( PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT){ fprintf(stderr, "PAPI library init error!\n"); exit(1); } #endif start = omp_get_wtime(); unsigned long vhash = 0; long g_abrarov = 0; long g_alls = 0; #pragma omp parallel default(none) \ shared(input, data) \ reduction(+:g_abrarov, g_alls, vhash) { double * xs = (double *) calloc(4, sizeof(double)); int thread = omp_get_thread_num(); long abrarov = 0; long alls = 0; #ifdef PAPI int eventset = PAPI_NULL; int num_papi_events; #pragma omp critical { counter_init(&eventset, &num_papi_events); } #endif complex double * sigTfactors = (complex double *) malloc( input.numL * sizeof(complex double) ); #pragma omp for schedule(dynamic) for( int p = 0; p < input.particles; p++ ) { // Particles are seeded by their particle ID unsigned long seed = ((unsigned long) p+ (unsigned long)1)* (unsigned long) 13371337; // Randomly pick an energy and material for the particle double E = rn(&seed); int mat = pick_mat(&seed); #ifdef STATUS if( thread == 0 && p % 35 == 0 ) printf("\rCalculating XS's... (%.0lf%% completed)", (p / ( (double)input.particles / (double) input.nthreads )) / (double) input.nthreads * 100.0); #endif for( int i = 0; i < input.lookups; i++ ) { double macro_xs[4] = {0}; calculate_macro_xs( macro_xs, mat, E, input, data, sigTfactors, &abrarov, &alls ); // Results are copied onto heap to avoid some compiler // flags (-flto) from optimizing out function call memcpy(xs, macro_xs, 4*sizeof(double)); // Verification hash calculation // This method provides a consistent hash accross // architectures and compilers. #ifdef VERIFICATION char line[256]; sprintf(line, "%.2le %d %.2le %.2le %.2le %.2le", E, mat, macro_xs[0], macro_xs[1], macro_xs[2], macro_xs[3]); unsigned long long vhash_local = hash(line, 10000); vhash += vhash_local; #endif // Randomly pick next energy and material for the particle // Also incorporates results from macro_xs lookup to // enforce loop dependency. // In a real MC app, this dependency is expressed in terms // of branching physics sampling, whereas here we are just // artificially enforcing this dependence based on altering // the seed for( int x = 0; x < 4; x++ ) { if( macro_xs[x] > 0 ) seed += 1337*p; else seed += 42; } E = rn(&seed); mat = pick_mat(&seed); } } free(sigTfactors); // Accumulate global counters g_abrarov = abrarov; g_alls = alls; #ifdef PAPI if( thread == 0 ) { printf("\n"); border_print(); center_print("PAPI COUNTER RESULTS", 79); border_print(); printf("Count \tSmybol \tDescription\n"); } { #pragma omp barrier } counter_stop(&eventset, num_papi_events); #endif } // Final hash step vhash = vhash % 1000000; stop = omp_get_wtime(); #ifndef PAPI printf("\nSimulation Complete.\n"); #endif // ===================================================================== // Print / Save Results and Exit // ===================================================================== border_print(); center_print("RESULTS", 79); border_print(); printf("Threads: %d\n", input.nthreads); if( input.doppler) printf("Slow Faddeeva: %.2lf%%\n", (double) g_abrarov/g_alls * 100.f); printf("Runtime: %.3lf seconds\n", stop-start); printf("Lookups: "); fancy_int(input.lookups*input.particles); printf("Lookups/s: "); fancy_int((double) input.lookups*input.particles / (stop-start)); #ifdef VERIFICATION unsigned long long large = 425149; unsigned long long small = 830419; if( input.HM == LARGE ) { if( vhash == large ) printf("Verification checksum: %lu (Valid)\n", vhash); else printf("Verification checksum: %lu (WARNING - INAVALID CHECKSUM!)\n", vhash); } else if( input.HM == SMALL ) { if( vhash == small ) printf("Verification checksum: %lu (Valid)\n", vhash); else printf("Verification checksum: %lu (WARNING - INAVALID CHECKSUM!)\n", vhash); } #endif border_print(); return 0; }
voronoinoise.h
#pragma once #ifndef VORONOI_NOISE_H #define VORONOI_NOISE_H #include "noisecommon.h" #define DEFAULT_VORONOI_FREQUENCY 1.0 #define DEFAULT_VORONOI_DISPLACEMENT 1.0 #define DEFAULT_VORONOI_SEED 0 #define DEFAULT_VORONOI_ENABLE_DISTANCE true #define DEFAULT_VORONOI_POSITION_X 0.0 #define DEFAULT_VORONOI_POSITION_Y 0.0 #define DEFAULT_VORONOI_POSITION_Z 0.0 #define DEFAULT_VORONOI_STEP 0.01 #define DEFAULT_VORONOI_PARALLEL false struct VoronoiNoise { float frequency; float displacement; int seed; unsigned char enable_distance; float position[3]; float step; bool parallel; float *(*voronoi_func)(struct VoronoiNoise *, size_t, size_t, size_t); }; static inline float *voronoi_noise_eval_1d(struct VoronoiNoise *voronoi_noise, size_t x_size); static inline float *voronoi_noise_eval_2d(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size); static inline float *voronoi_noise_eval_3d(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size, size_t z_size); static inline float voronoi_noise_eval_3d_single(struct VoronoiNoise *voronoi_noise, float x_pos, float y_pos, float z_pos); static inline float *voronoi_noise_eval_3d_fallback(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size, size_t z_size); static inline float *voronoi_noise_eval_3d_sse2(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size, size_t z_size); static inline float *voronoi_noise_eval_3d_sse4_1(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size, size_t z_size); static inline float *voronoi_noise_eval_3d_avx(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size, size_t z_size); static inline float *voronoi_noise_eval_3d_avx2(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size, size_t z_size); static inline float *voronoi_noise_eval_3d_avx512(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size, size_t z_size); static inline void voronoi_noise_init(struct VoronoiNoise *voronoi_noise) { voronoi_noise->frequency = DEFAULT_VORONOI_FREQUENCY; voronoi_noise->displacement = DEFAULT_VORONOI_DISPLACEMENT; voronoi_noise->seed = DEFAULT_VORONOI_SEED; voronoi_noise->enable_distance = DEFAULT_VORONOI_ENABLE_DISTANCE; voronoi_noise->position[0] = DEFAULT_VORONOI_POSITION_X; voronoi_noise->position[1] = DEFAULT_VORONOI_POSITION_Y; voronoi_noise->position[2] = DEFAULT_VORONOI_POSITION_Z; voronoi_noise->step = DEFAULT_VORONOI_STEP; voronoi_noise->parallel = DEFAULT_VORONOI_PARALLEL; switch (detect_simd_support()) { #ifdef ARCH_32_64 case SIMD_AVX512F: voronoi_noise->voronoi_func = &voronoi_noise_eval_3d_fallback; break; case SIMD_AVX2: voronoi_noise->voronoi_func = &voronoi_noise_eval_3d_avx2; break; case SIMD_AVX: voronoi_noise->voronoi_func = &voronoi_noise_eval_3d_avx; break; case SIMD_SSE4_1: voronoi_noise->voronoi_func = &voronoi_noise_eval_3d_sse4_1; break; case SIMD_SSE2: voronoi_noise->voronoi_func = &voronoi_noise_eval_3d_sse2; break; #else case SIMD_NEON: voronoi_noise->voronoi_func = &voronoi_noise_eval_3d_fallback; break; #endif default: voronoi_noise->voronoi_func = &voronoi_noise_eval_3d_fallback; break; } } static inline float *voronoi_noise_eval_1d(struct VoronoiNoise *voronoi_noise, size_t x_size) { return voronoi_noise->voronoi_func(voronoi_noise, x_size, 1, 1); } static inline float *voronoi_noise_eval_2d(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size) { return voronoi_noise->voronoi_func(voronoi_noise, x_size, y_size, 1); } static inline float *voronoi_noise_eval_3d(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size, size_t z_size) { return voronoi_noise->voronoi_func(voronoi_noise, x_size, y_size, z_size); } static inline float voronoi_noise_eval_3d_single(struct VoronoiNoise *voronoi_noise, float x_pos, float y_pos, float z_pos) { float x = (voronoi_noise->position[0] + (x_pos * voronoi_noise->step)) * voronoi_noise->frequency; float y = (voronoi_noise->position[1] + (y_pos * voronoi_noise->step)) * voronoi_noise->frequency; float z = (voronoi_noise->position[2] + (z_pos * voronoi_noise->step)) * voronoi_noise->frequency; int x_int = (x > 0.0 ? (int)x : (int)x - 1); int y_int = (y > 0.0 ? (int)y : (int)y - 1); int z_int = (z > 0.0 ? (int)z : (int)z - 1); float min_dist = 2147483647.0; float x_candidate = 0; float y_candidate = 0; float z_candidate = 0; for (int z_cur = z_int - 2; z_cur <= z_int + 2; z_cur++) { for (int y_cur = y_int - 2; y_cur <= y_int + 2; y_cur++) { for (int x_cur = x_int - 2; x_cur <= x_int + 2; x_cur++) { float x_pos = x_cur + value_noise_3d(x_cur, y_cur, z_cur, voronoi_noise->seed); float y_pos = y_cur + value_noise_3d(x_cur, y_cur, z_cur, voronoi_noise->seed + 1); float z_pos = z_cur + value_noise_3d(x_cur, y_cur, z_cur, voronoi_noise->seed + 2); float x_dist = x_pos - x; float y_dist = y_pos - y; float z_dist = z_pos - z; float dist = x_dist * x_dist + y_dist * y_dist + z_dist * z_dist; if (dist < min_dist) { min_dist = dist; x_candidate = x_pos; y_candidate = y_pos; z_candidate = z_pos; } } } } float value; if (voronoi_noise->enable_distance) { float x_dist = x_candidate - x; float y_dist = y_candidate - y; float z_dist = z_candidate - z; value = sqrt(x_dist * x_dist + y_dist * y_dist + z_dist * z_dist) * SQRT_3 - 1.0; } else value = 0.0; return value + (voronoi_noise->displacement * value_noise_3d((int)floor(x_candidate), (int)floor(y_candidate), (int)floor(z_candidate), voronoi_noise->seed)); } static inline float *voronoi_noise_eval_3d_fallback(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size, size_t z_size) { #ifdef CUSTOM_ALLOCATOR float *noise_set = malloc(sizeof(float) * x_size * y_size * z_size); #else float *noise_set = noise_allocate(sizeof(float), sizeof(float) * x_size * y_size * z_size); #endif #pragma omp parallel for collapse(3) if (voronoi_noise->parallel) for (int z_dim = 0; z_dim < z_size; z_dim++) { for (int y_dim = 0; y_dim < y_size; y_dim++) { for (int x_dim = 0; x_dim < x_size; x_dim++) { float x = (voronoi_noise->position[0] + (x_dim * voronoi_noise->step)) * voronoi_noise->frequency; float y = (voronoi_noise->position[1] + (y_dim * voronoi_noise->step)) * voronoi_noise->frequency; float z = (voronoi_noise->position[2] + (z_dim * voronoi_noise->step)) * voronoi_noise->frequency; int x_int = (x > 0.0 ? (int)x : (int)x - 1); int y_int = (y > 0.0 ? (int)y : (int)y - 1); int z_int = (z > 0.0 ? (int)z : (int)z - 1); float min_dist = 2147483647.0; float x_candidate = 0; float y_candidate = 0; float z_candidate = 0; for (int z_cur = z_int - 2; z_cur <= z_int + 2; z_cur++) { for (int y_cur = y_int - 2; y_cur <= y_int + 2; y_cur++) { for (int x_cur = x_int - 2; x_cur <= x_int + 2; x_cur++) { float x_pos = x_cur + value_noise_3d(x_cur, y_cur, z_cur, voronoi_noise->seed); float y_pos = y_cur + value_noise_3d(x_cur, y_cur, z_cur, voronoi_noise->seed + 1); float z_pos = z_cur + value_noise_3d(x_cur, y_cur, z_cur, voronoi_noise->seed + 2); float x_dist = x_pos - x; float y_dist = y_pos - y; float z_dist = z_pos - z; float dist = x_dist * x_dist + y_dist * y_dist + z_dist * z_dist; if (dist < min_dist) { min_dist = dist; x_candidate = x_pos; y_candidate = y_pos; z_candidate = z_pos; } } } } float value; if (voronoi_noise->enable_distance) { float x_dist = x_candidate - x; float y_dist = y_candidate - y; float z_dist = z_candidate - z; value = sqrt(x_dist * x_dist + y_dist * y_dist + z_dist * z_dist) * SQRT_3 - 1.0; } else value = 0.0; *(noise_set + (x_dim + (y_dim * x_size) + (z_dim * (x_size * y_size)))) = value + (voronoi_noise->displacement * value_noise_3d((int)floor(x_candidate), (int)floor(y_candidate), (int)floor(z_candidate), voronoi_noise->seed)); } } } return noise_set; } #ifdef ARCH_32_64 static inline float *voronoi_noise_eval_3d_sse2(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size, size_t z_size) { float *noise_set = noise_allocate(sizeof(__m128), sizeof(float) * x_size * y_size * z_size); #pragma omp parallel for collapse(3) if (voronoi_noise->parallel) for (int z_dim = 0; z_dim < z_size; z_dim++) { for (int y_dim = 0; y_dim < y_size; y_dim++) { for (int x_dim = 0; x_dim < x_size; x_dim += 4) { __m128 x_vec = _mm_mul_ps(_mm_add_ps(_mm_set1_ps(voronoi_noise->position[0]), _mm_mul_ps(_mm_set_ps(x_dim + 3.0, x_dim + 2.0, x_dim + 1.0, x_dim), _mm_set1_ps(voronoi_noise->step))), _mm_set1_ps(voronoi_noise->frequency)); float y = (voronoi_noise->position[1] * voronoi_noise->frequency) + (y_dim * voronoi_noise->step); float z = (voronoi_noise->position[2] * voronoi_noise->frequency) + (z_dim * voronoi_noise->step); __m128i x_int; for (int x_num = 0; x_num < 4; x_num++) *(((int32_t *)&x_int) + x_num) = (*(((float *)&x_vec) + x_num) > 0.0 ? (int)*(((float *)&x_vec) + x_num) : (int)*(((float *)&x_vec) + x_num) - 1); int y_int = (y > 0.0 ? (int)y : (int)y - 1); int z_int = (z > 0.0 ? (int)z : (int)z - 1); __m128 min_dist = _mm_set1_ps(2147483647.0); __m128 x_candidate = _mm_setzero_ps(); __m128 y_candidate = _mm_setzero_ps(); __m128 z_candidate = _mm_setzero_ps(); for (int z_cur = z_int - 2; z_cur <= z_int + 2; z_cur++) { for (int y_cur = y_int - 2; y_cur <= y_int + 2; y_cur++) { for (int x_cur = -2; x_cur <= 2; x_cur++) { __m128i x_cur_temp = _mm_add_epi32(x_int, _mm_set1_epi32(x_cur)); __m128 x_pos = _mm_add_ps(_mm_cvtepi32_ps(x_cur_temp), value_noise_3d_sse2(x_cur_temp, y_cur, z_cur, voronoi_noise->seed)); __m128 y_pos = _mm_add_ps(_mm_set1_ps((float)y_cur), value_noise_3d_sse2(x_cur_temp, y_cur, z_cur, voronoi_noise->seed + 1)); __m128 z_pos = _mm_add_ps(_mm_set1_ps((float)z_cur), value_noise_3d_sse2(x_cur_temp, y_cur, z_cur, voronoi_noise->seed + 2)); __m128 x_dist = _mm_sub_ps(x_pos, x_vec); __m128 y_dist = _mm_sub_ps(y_pos, _mm_set1_ps(y)); __m128 z_dist = _mm_sub_ps(z_pos, _mm_set1_ps(z)); __m128 dist = _mm_add_ps(_mm_mul_ps(x_dist, x_dist), _mm_add_ps(_mm_mul_ps(y_dist, y_dist), _mm_mul_ps(z_dist, z_dist))); for (int check_num = 0; check_num < 4; check_num++) { float dist_extract = *(((float *)&dist) + check_num); float min_dist_extract = *(((float *)&min_dist) + check_num); if (dist_extract < min_dist_extract) { *(((float *)&min_dist) + check_num) = dist_extract; *(((float *)&x_candidate) + check_num) = *(((float *)&x_pos) + check_num); *(((float *)&y_candidate) + check_num) = *(((float *)&y_pos) + check_num); *(((float *)&z_candidate) + check_num) = *(((float *)&z_pos) + check_num); } } } } } __m128 value; if (voronoi_noise->enable_distance) { __m128 x_dist = _mm_sub_ps(x_candidate, x_vec); __m128 y_dist = _mm_sub_ps(y_candidate, _mm_set1_ps(y)); __m128 z_dist = _mm_sub_ps(z_candidate, _mm_set1_ps(z)); value = _mm_sub_ps(_mm_mul_ps(_mm_sqrt_ps(_mm_add_ps(_mm_mul_ps(x_dist, x_dist), _mm_add_ps(_mm_mul_ps(y_dist, y_dist), _mm_mul_ps(z_dist, z_dist)))), _mm_set1_ps(SQRT_3)), _mm_set1_ps(1.0)); } else value = _mm_setzero_ps(); for (int floor_candidate_num = 0; floor_candidate_num < 4; floor_candidate_num++) { *(((float *)&x_candidate) + floor_candidate_num) = floor(*(((float *)&x_candidate) + floor_candidate_num)); *(((float *)&y_candidate) + floor_candidate_num) = floor(*(((float *)&y_candidate) + floor_candidate_num)); *(((float *)&z_candidate) + floor_candidate_num) = floor(*(((float *)&z_candidate) + floor_candidate_num)); } _mm_store_ps(noise_set + (x_dim + (y_dim * x_size) + (z_dim * (x_size * y_size))), _mm_add_ps(value, _mm_mul_ps(_mm_set1_ps(voronoi_noise->displacement), value_noise_3d_sse2_full(_mm_cvtps_epi32(x_candidate), _mm_cvtps_epi32(y_candidate), _mm_cvtps_epi32(z_candidate), voronoi_noise->seed)))); } } } return noise_set; } static inline float *voronoi_noise_eval_3d_sse4_1(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size, size_t z_size) { float *noise_set = noise_allocate(sizeof(__m128), sizeof(float) * x_size * y_size * z_size); #pragma omp parallel for collapse(3) if (voronoi_noise->parallel) for (int z_dim = 0; z_dim < z_size; z_dim++) { for (int y_dim = 0; y_dim < y_size; y_dim++) { for (int x_dim = 0; x_dim < x_size; x_dim += 4) { __m128 x_vec = _mm_mul_ps(_mm_add_ps(_mm_set1_ps(voronoi_noise->position[0]), _mm_mul_ps(_mm_set_ps(x_dim + 3.0, x_dim + 2.0, x_dim + 1.0, x_dim), _mm_set1_ps(voronoi_noise->step))), _mm_set1_ps(voronoi_noise->frequency)); float y = (voronoi_noise->position[1] * voronoi_noise->frequency) + (y_dim * voronoi_noise->step); float z = (voronoi_noise->position[2] * voronoi_noise->frequency) + (z_dim * voronoi_noise->step); __m128i x_int = _mm_cvtps_epi32(_mm_floor_ps(_mm_blendv_ps(_mm_sub_ps(x_vec, _mm_set1_ps(1.0)), x_vec, _mm_cmp_ps(x_vec, _mm_setzero_ps(), _CMP_GT_OQ)))); int y_int = (y > 0.0 ? (int)y : (int)y - 1); int z_int = (z > 0.0 ? (int)z : (int)z - 1); __m128 min_dist = _mm_set1_ps(2147483647.0); __m128 x_candidate = _mm_setzero_ps(); __m128 y_candidate = _mm_setzero_ps(); __m128 z_candidate = _mm_setzero_ps(); for (int z_cur = z_int - 2; z_cur <= z_int + 2; z_cur++) { for (int y_cur = y_int - 2; y_cur <= y_int + 2; y_cur++) { for (int x_cur = -2; x_cur <= 2; x_cur++) { __m128i x_cur_temp = _mm_add_epi32(x_int, _mm_set1_epi32(x_cur)); __m128 x_pos = _mm_add_ps(_mm_cvtepi32_ps(x_cur_temp), value_noise_3d_sse4_1(x_cur_temp, y_cur, z_cur, voronoi_noise->seed)); __m128 y_pos = _mm_add_ps(_mm_set1_ps((float)y_cur), value_noise_3d_sse4_1(x_cur_temp, y_cur, z_cur, voronoi_noise->seed + 1)); __m128 z_pos = _mm_add_ps(_mm_set1_ps((float)z_cur), value_noise_3d_sse4_1(x_cur_temp, y_cur, z_cur, voronoi_noise->seed + 2)); __m128 x_dist = _mm_sub_ps(x_pos, x_vec); __m128 y_dist = _mm_sub_ps(y_pos, _mm_set1_ps(y)); __m128 z_dist = _mm_sub_ps(z_pos, _mm_set1_ps(z)); __m128 dist = _mm_add_ps(_mm_mul_ps(x_dist, x_dist), _mm_add_ps(_mm_mul_ps(y_dist, y_dist), _mm_mul_ps(z_dist, z_dist))); __m128 dist_cmp_mask = _mm_cmp_ps(dist, min_dist, _CMP_LT_OQ); min_dist = _mm_blendv_ps(min_dist, dist, dist_cmp_mask); x_candidate = _mm_blendv_ps(x_candidate, x_pos, dist_cmp_mask); y_candidate = _mm_blendv_ps(y_candidate, y_pos, dist_cmp_mask); z_candidate = _mm_blendv_ps(z_candidate, z_pos, dist_cmp_mask); } } } __m128 value; if (voronoi_noise->enable_distance) { __m128 x_dist = _mm_sub_ps(x_candidate, x_vec); __m128 y_dist = _mm_sub_ps(y_candidate, _mm_set1_ps(y)); __m128 z_dist = _mm_sub_ps(z_candidate, _mm_set1_ps(z)); value = _mm_sub_ps(_mm_mul_ps(_mm_sqrt_ps(_mm_add_ps(_mm_mul_ps(x_dist, x_dist), _mm_add_ps(_mm_mul_ps(y_dist, y_dist), _mm_mul_ps(z_dist, z_dist)))), _mm_set1_ps(SQRT_3)), _mm_set1_ps(1.0)); } else value = _mm_setzero_ps(); _mm_store_ps(noise_set + (x_dim + (y_dim * x_size) + (z_dim * (x_size * y_size))), _mm_add_ps(value, _mm_mul_ps(_mm_set1_ps(voronoi_noise->displacement), value_noise_3d_sse4_1_full(_mm_cvtps_epi32(_mm_floor_ps(x_candidate)), _mm_cvtps_epi32(_mm_floor_ps(y_candidate)), _mm_cvtps_epi32(_mm_floor_ps(z_candidate)), voronoi_noise->seed)))); } } } return noise_set; } static inline float *voronoi_noise_eval_3d_avx(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size, size_t z_size) { float *noise_set = noise_allocate(sizeof(__m256), sizeof(float) * x_size * y_size * z_size); #pragma omp parallel for collapse(3) if (voronoi_noise->parallel) for (int z_dim = 0; z_dim < z_size; z_dim++) { for (int y_dim = 0; y_dim < y_size; y_dim++) { for (int x_dim = 0; x_dim < x_size; x_dim += 8) { __m256 x_vec = _mm256_mul_ps(_mm256_add_ps(_mm256_set1_ps(voronoi_noise->position[0]), _mm256_mul_ps(_mm256_set_ps(x_dim + 7.0, x_dim + 6.0, x_dim + 5.0, x_dim + 4.0, x_dim + 3.0, x_dim + 2.0, x_dim + 1.0, x_dim), _mm256_set1_ps(voronoi_noise->step))), _mm256_set1_ps(voronoi_noise->frequency)); float y = (voronoi_noise->position[1] + (y_dim * voronoi_noise->step)) * voronoi_noise->frequency; float z = (voronoi_noise->position[2] + (z_dim * voronoi_noise->step)) * voronoi_noise->frequency; __m256i x_int = _mm256_cvtps_epi32(_mm256_floor_ps(_mm256_blendv_ps(_mm256_sub_ps(x_vec, _mm256_set1_ps(1.0)), x_vec, _mm256_cmp_ps(x_vec, _mm256_setzero_ps(), _CMP_GT_OQ)))); int y_int = (y > 0.0 ? (int)y : (int)y - 1); int z_int = (z > 0.0 ? (int)z : (int)z - 1); __m256 min_dist = _mm256_set1_ps(2147483647.0); __m256 x_candidate = _mm256_setzero_ps(); __m256 y_candidate = _mm256_setzero_ps(); __m256 z_candidate = _mm256_setzero_ps(); for (int z_cur = z_int - 2; z_cur <= z_int + 2; z_cur++) { for (int y_cur = y_int - 2; y_cur <= y_int + 2; y_cur++) { for (int x_cur = -2; x_cur <= 2; x_cur++) { __m128i x_cur_temp_low = _mm_add_epi32(_mm256_extractf128_si256(x_int, 0), _mm_set1_epi32(x_cur)); __m128i x_cur_temp_high = _mm_add_epi32(_mm256_extractf128_si256(x_int, 1), _mm_set1_epi32(x_cur)); __m256i x_cur_temp = _mm256_set_m128i(x_cur_temp_high, x_cur_temp_low); __m256 x_pos = _mm256_add_ps(_mm256_cvtepi32_ps(x_cur_temp), value_noise_3d_avx(x_cur_temp, y_cur, z_cur, voronoi_noise->seed)); __m256 y_pos = _mm256_add_ps(_mm256_set1_ps((float)y_cur), value_noise_3d_avx(x_cur_temp, y_cur, z_cur, voronoi_noise->seed + 1)); __m256 z_pos = _mm256_add_ps(_mm256_set1_ps((float)z_cur), value_noise_3d_avx(x_cur_temp, y_cur, z_cur, voronoi_noise->seed + 2)); __m256 x_dist = _mm256_sub_ps(x_pos, x_vec); __m256 y_dist = _mm256_sub_ps(y_pos, _mm256_set1_ps(y)); __m256 z_dist = _mm256_sub_ps(z_pos, _mm256_set1_ps(z)); __m256 dist = _mm256_add_ps(_mm256_mul_ps(x_dist, x_dist), _mm256_add_ps(_mm256_mul_ps(y_dist, y_dist), _mm256_mul_ps(z_dist, z_dist))); __m256 dist_cmp_mask = _mm256_cmp_ps(dist, min_dist, _CMP_LT_OQ); min_dist = _mm256_blendv_ps(min_dist, dist, dist_cmp_mask); x_candidate = _mm256_blendv_ps(x_candidate, x_pos, dist_cmp_mask); y_candidate = _mm256_blendv_ps(y_candidate, y_pos, dist_cmp_mask); z_candidate = _mm256_blendv_ps(z_candidate, z_pos, dist_cmp_mask); } } } __m256 value; if (voronoi_noise->enable_distance) { __m256 x_dist = _mm256_sub_ps(x_candidate, x_vec); __m256 y_dist = _mm256_sub_ps(y_candidate, _mm256_set1_ps(y)); __m256 z_dist = _mm256_sub_ps(z_candidate, _mm256_set1_ps(z)); value = _mm256_sub_ps(_mm256_mul_ps(_mm256_sqrt_ps(_mm256_add_ps(_mm256_mul_ps(x_dist, x_dist), _mm256_add_ps(_mm256_mul_ps(y_dist, y_dist), _mm256_mul_ps(z_dist, z_dist)))), _mm256_set1_ps(SQRT_3)), _mm256_set1_ps(1.0)); } else value = _mm256_setzero_ps(); _mm256_store_ps(noise_set + (x_dim + (y_dim * x_size) + (z_dim * (x_size * y_size))), _mm256_add_ps(value, _mm256_mul_ps(_mm256_set1_ps(voronoi_noise->displacement), value_noise_3d_avx_full(_mm256_cvtps_epi32(_mm256_floor_ps(x_candidate)), _mm256_cvtps_epi32(_mm256_floor_ps(y_candidate)), _mm256_cvtps_epi32(_mm256_floor_ps(z_candidate)), voronoi_noise->seed)))); } } } return noise_set; } static inline float *voronoi_noise_eval_3d_avx2(struct VoronoiNoise *voronoi_noise, size_t x_size, size_t y_size, size_t z_size) { float *noise_set = noise_allocate(sizeof(__m256), sizeof(float) * x_size * y_size * z_size); #pragma omp parallel for collapse(3) if (voronoi_noise->parallel) for (int z_dim = 0; z_dim < z_size; z_dim++) { for (int y_dim = 0; y_dim < y_size; y_dim++) { for (int x_dim = 0; x_dim < x_size; x_dim += 8) { __m256 x_vec = _mm256_mul_ps(_mm256_add_ps(_mm256_set1_ps(voronoi_noise->position[0]), _mm256_mul_ps(_mm256_set_ps(x_dim + 7.0, x_dim + 6.0, x_dim + 5.0, x_dim + 4.0, x_dim + 3.0, x_dim + 2.0, x_dim + 1.0, x_dim), _mm256_set1_ps(voronoi_noise->step))), _mm256_set1_ps(voronoi_noise->frequency)); float y = (voronoi_noise->position[1] + (y_dim * voronoi_noise->step)) * voronoi_noise->frequency; float z = (voronoi_noise->position[2] + (z_dim * voronoi_noise->step)) * voronoi_noise->frequency; __m256i x_int = _mm256_cvtps_epi32(_mm256_floor_ps(_mm256_blendv_ps(_mm256_sub_ps(x_vec, _mm256_set1_ps(1.0)), x_vec, _mm256_cmp_ps(x_vec, _mm256_setzero_ps(), _CMP_GT_OQ)))); int y_int = (y > 0.0 ? (int)y : (int)y - 1); int z_int = (z > 0.0 ? (int)z : (int)z - 1); __m256 min_dist = _mm256_set1_ps(2147483647.0); __m256 x_candidate = _mm256_setzero_ps(); __m256 y_candidate = _mm256_setzero_ps(); __m256 z_candidate = _mm256_setzero_ps(); for (int z_cur = z_int - 2; z_cur <= z_int + 2; z_cur++) { for (int y_cur = y_int - 2; y_cur <= y_int + 2; y_cur++) { for (int x_cur = -2; x_cur <= 2; x_cur++) { __m256i x_cur_temp = _mm256_add_epi32(x_int, _mm256_set1_epi32(x_cur)); __m256 x_pos = _mm256_add_ps(_mm256_cvtepi32_ps(x_cur_temp), value_noise_3d_avx2(x_cur_temp, y_cur, z_cur, voronoi_noise->seed)); __m256 y_pos = _mm256_add_ps(_mm256_set1_ps((float)y_cur), value_noise_3d_avx2(x_cur_temp, y_cur, z_cur, voronoi_noise->seed + 1)); __m256 z_pos = _mm256_add_ps(_mm256_set1_ps((float)z_cur), value_noise_3d_avx2(x_cur_temp, y_cur, z_cur, voronoi_noise->seed + 2)); __m256 x_dist = _mm256_sub_ps(x_pos, x_vec); __m256 y_dist = _mm256_sub_ps(y_pos, _mm256_set1_ps(y)); __m256 z_dist = _mm256_sub_ps(z_pos, _mm256_set1_ps(z)); __m256 dist = _mm256_add_ps(_mm256_mul_ps(x_dist, x_dist), _mm256_add_ps(_mm256_mul_ps(y_dist, y_dist), _mm256_mul_ps(z_dist, z_dist))); __m256 dist_cmp_mask = _mm256_cmp_ps(dist, min_dist, _CMP_LT_OQ); min_dist = _mm256_blendv_ps(min_dist, dist, dist_cmp_mask); x_candidate = _mm256_blendv_ps(x_candidate, x_pos, dist_cmp_mask); y_candidate = _mm256_blendv_ps(y_candidate, y_pos, dist_cmp_mask); z_candidate = _mm256_blendv_ps(z_candidate, z_pos, dist_cmp_mask); } } } __m256 value; if (voronoi_noise->enable_distance) { __m256 x_dist = _mm256_sub_ps(x_candidate, x_vec); __m256 y_dist = _mm256_sub_ps(y_candidate, _mm256_set1_ps(y)); __m256 z_dist = _mm256_sub_ps(z_candidate, _mm256_set1_ps(z)); value = _mm256_sub_ps(_mm256_mul_ps(_mm256_sqrt_ps(_mm256_add_ps(_mm256_mul_ps(x_dist, x_dist), _mm256_add_ps(_mm256_mul_ps(y_dist, y_dist), _mm256_mul_ps(z_dist, z_dist)))), _mm256_set1_ps(SQRT_3)), _mm256_set1_ps(1.0)); } else value = _mm256_setzero_ps(); _mm256_store_ps(noise_set + (x_dim + (y_dim * x_size) + (z_dim * (x_size * y_size))), _mm256_add_ps(value, _mm256_mul_ps(_mm256_set1_ps(voronoi_noise->displacement), value_noise_3d_avx2_full(_mm256_cvtps_epi32(_mm256_floor_ps(x_candidate)), _mm256_cvtps_epi32(_mm256_floor_ps(y_candidate)), _mm256_cvtps_epi32(_mm256_floor_ps(z_candidate)), voronoi_noise->seed)))); } } } return noise_set; } #endif #endif // VORONOI_NOISE_H
quiz.c
#include <stdio.h> #include <omp.h> #define ORDRE 3 int main(){ int A[ORDRE][ORDRE]={{0,1,-1},{3,0,2},{1,1,0}}, B[ORDRE][ORDRE]={{1,0,5},{-1,1,0},{0,4,1}}; int i, j, k, somme, C[ORDRE][ORDRE]; for (i=0; i<ORDRE; i++){ for (j=0; j<ORDRE; j++){ C[i][j] = 0; omp_set_num_threads(ORDRE); #pragma omp parallel for (k=0; k<ORDRE; k++){ #pragma omp atomic C[i][j] += A[i][k]*B[k][j]; } } } printf(" A B C\n"); for (i=0; i<ORDRE; i++){ for (j=0; j<ORDRE; j++) printf(" %4d", A[i][j]); for (j=0; j<ORDRE; j++) printf(" %4d", B[i][j]); for (j=0; j<ORDRE; j++) printf(" %4d", C[i][j]); printf("\n"); } return 0; }
DRB040-truedepsingleelement-var-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Data race pair: a[i]@63:5 vs. a[0]@63:15 */ #include <stdlib.h> #include <omp.h> int main(int argc,char *argv[]) { int len = 1000; int i; if (argc > 1) len = atoi(argv[1]); int a[len]; a[0] = 2; #pragma omp parallel for private (i) for (i = 0; i <= len - 1; i += 1) { a[i] = i; } for (i = 0; i <= len - 1; i += 1) { a[i] = a[i] + a[0]; } for (i = 0; i <= len - 1; i += 1) { printf("%d\n",a[i]); } return 0; }
GB_binop__eq_fc64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__eq_fc64) // A.*B function (eWiseMult): GB (_AemultB_08__eq_fc64) // A.*B function (eWiseMult): GB (_AemultB_02__eq_fc64) // A.*B function (eWiseMult): GB (_AemultB_04__eq_fc64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__eq_fc64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__eq_fc64) // C+=b function (dense accum): GB (_Cdense_accumb__eq_fc64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__eq_fc64) // C=scalar+B GB (_bind1st__eq_fc64) // C=scalar+B' GB (_bind1st_tran__eq_fc64) // C=A+scalar GB (_bind2nd__eq_fc64) // C=A'+scalar GB (_bind2nd_tran__eq_fc64) // C type: bool // A type: GxB_FC64_t // A pattern? 0 // B type: GxB_FC64_t // B pattern? 0 // BinaryOp: cij = GB_FC64_eq (aij, bij) #define GB_ATYPE \ GxB_FC64_t #define GB_BTYPE \ GxB_FC64_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ GxB_FC64_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ GxB_FC64_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = (creal (GBX (Ax, pA, A_iso)) != 0) || (cimag (GBX (Ax, pA, A_iso)) != 0) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = (creal (GBX (Bx, pB, B_iso)) != 0) || (cimag (GBX (Bx, pB, B_iso)) != 0) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_FC64_eq (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_EQ || GxB_NO_FC64 || GxB_NO_EQ_FC64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__eq_fc64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__eq_fc64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__eq_fc64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type GxB_FC64_t GxB_FC64_t bwork = (*((GxB_FC64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__eq_fc64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; GxB_FC64_t alpha_scalar ; GxB_FC64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((GxB_FC64_t *) alpha_scalar_in)) ; beta_scalar = (*((GxB_FC64_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__eq_fc64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__eq_fc64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__eq_fc64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__eq_fc64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__eq_fc64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; GxB_FC64_t x = (*((GxB_FC64_t *) x_input)) ; GxB_FC64_t *Bx = (GxB_FC64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; GxB_FC64_t bij = GBX (Bx, p, false) ; Cx [p] = GB_FC64_eq (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__eq_fc64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; GxB_FC64_t *Ax = (GxB_FC64_t *) Ax_input ; GxB_FC64_t y = (*((GxB_FC64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; GxB_FC64_t aij = GBX (Ax, p, false) ; Cx [p] = GB_FC64_eq (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_FC64_eq (x, aij) ; \ } GrB_Info GB (_bind1st_tran__eq_fc64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ GxB_FC64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t x = (*((const GxB_FC64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_FC64_eq (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__eq_fc64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t y = (*((const GxB_FC64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
paint.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP AAA IIIII N N TTTTT % % P P A A I NN N T % % PPPP AAAAA I N N N T % % P A A I N NN T % % P A A IIIII N N T % % % % % % Methods to Paint on an Image % % % % Software Design % % Cristy % % July 1998 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/draw.h" #include "MagickCore/draw-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/resource_.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F l o o d f i l l P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FloodfillPaintImage() changes the color value of any pixel that matches % target and is an immediate neighbor. If the method FillToBorderMethod is % specified, the color value is changed for any neighbor pixel that does not % match the bordercolor member of image. % % By default target must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. The fuzz member of % image defines how much tolerance is acceptable to consider two colors as % the same. For example, set fuzz to 10 and the color red at intensities of % 100 and 102 respectively are now interpreted as the same color for the % purposes of the floodfill. % % The format of the FloodfillPaintImage method is: % % MagickBooleanType FloodfillPaintImage(Image *image, % const DrawInfo *draw_info,const PixelInfo target, % const ssize_t x_offset,const ssize_t y_offset, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o target: the RGB value of the target color. % % o x_offset,y_offset: the starting location of the operation. % % o invert: paint any pixel that does not match the target color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType FloodfillPaintImage(Image *image, const DrawInfo *draw_info,const PixelInfo *target,const ssize_t x_offset, const ssize_t y_offset,const MagickBooleanType invert, ExceptionInfo *exception) { #define MaxStacksize 524288UL #define PushSegmentStack(up,left,right,delta) \ { \ if (s >= (segment_stack+MaxStacksize)) \ ThrowBinaryException(DrawError,"SegmentStackOverflow",image->filename) \ else \ { \ if ((((up)+(delta)) >= 0) && (((up)+(delta)) < (ssize_t) image->rows)) \ { \ s->x1=(double) (left); \ s->y1=(double) (up); \ s->x2=(double) (right); \ s->y2=(double) (delta); \ s++; \ } \ } \ } CacheView *floodplane_view, *image_view; Image *floodplane_image; MagickBooleanType skip, status; MemoryInfo *segment_info; PixelInfo fill_color, pixel; register SegmentInfo *s; SegmentInfo *segment_stack; ssize_t offset, start, x1, x2, y; /* Check boundary conditions. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns)) return(MagickFalse); if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows)) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); if ((image->alpha_trait == UndefinedPixelTrait) && (draw_info->fill.alpha_trait != UndefinedPixelTrait)) (void) SetImageAlpha(image,OpaqueAlpha,exception); /* Set floodfill state. */ floodplane_image=CloneImage(image,0,0,MagickTrue, exception); if (floodplane_image == (Image *) NULL) return(MagickFalse); floodplane_image->alpha_trait=UndefinedPixelTrait; floodplane_image->colorspace=GRAYColorspace; (void) QueryColorCompliance("#000",AllCompliance, &floodplane_image->background_color,exception); (void) SetImageBackgroundColor(floodplane_image,exception); segment_info=AcquireVirtualMemory(MaxStacksize,sizeof(*segment_stack)); if (segment_info == (MemoryInfo *) NULL) { floodplane_image=DestroyImage(floodplane_image); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } segment_stack=(SegmentInfo *) GetVirtualMemoryBlob(segment_info); /* Push initial segment on stack. */ status=MagickTrue; start=0; s=segment_stack; PushSegmentStack(y_offset,x_offset,x_offset,1); PushSegmentStack(y_offset+1,x_offset,x_offset,-1); GetPixelInfo(image,&pixel); image_view=AcquireVirtualCacheView(image,exception); floodplane_view=AcquireAuthenticCacheView(floodplane_image,exception); while (s > segment_stack) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; /* Pop segment off stack. */ s--; x1=(ssize_t) s->x1; x2=(ssize_t) s->x2; offset=(ssize_t) s->y2; y=(ssize_t) s->y1+offset; /* Recolor neighboring pixels. */ p=GetCacheViewVirtualPixels(image_view,0,y,(size_t) (x1+1),1,exception); q=GetCacheViewAuthenticPixels(floodplane_view,0,y,(size_t) (x1+1),1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; p+=x1*GetPixelChannels(image); q+=x1*GetPixelChannels(floodplane_image); for (x=x1; x >= 0; x--) { if (GetPixelGray(floodplane_image,q) != 0) break; GetPixelInfoPixel(image,p,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert) break; SetPixelGray(floodplane_image,QuantumRange,q); p-=GetPixelChannels(image); q-=GetPixelChannels(floodplane_image); } if (SyncCacheViewAuthenticPixels(floodplane_view,exception) == MagickFalse) break; skip=x >= x1 ? MagickTrue : MagickFalse; if (skip == MagickFalse) { start=x+1; if (start < x1) PushSegmentStack(y,start,x1-1,-offset); x=x1+1; } do { if (skip == MagickFalse) { if (x < (ssize_t) image->columns) { p=GetCacheViewVirtualPixels(image_view,x,y,image->columns-x,1, exception); q=GetCacheViewAuthenticPixels(floodplane_view,x,y,image->columns- x,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for ( ; x < (ssize_t) image->columns; x++) { if (GetPixelGray(floodplane_image,q) != 0) break; GetPixelInfoPixel(image,p,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert) break; SetPixelGray(floodplane_image,QuantumRange,q); p+=GetPixelChannels(image); q+=GetPixelChannels(floodplane_image); } status=SyncCacheViewAuthenticPixels(floodplane_view,exception); if (status == MagickFalse) break; } PushSegmentStack(y,start,x-1,offset); if (x > (x2+1)) PushSegmentStack(y,x2+1,x-1,-offset); } skip=MagickFalse; x++; if (x <= x2) { p=GetCacheViewVirtualPixels(image_view,x,y,(size_t) (x2-x+1),1, exception); q=GetCacheViewAuthenticPixels(floodplane_view,x,y,(size_t) (x2-x+1),1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for ( ; x <= x2; x++) { if (GetPixelGray(floodplane_image,q) != 0) break; GetPixelInfoPixel(image,p,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert) break; p+=GetPixelChannels(image); q+=GetPixelChannels(floodplane_image); } } start=x; } while (x <= x2); } status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; /* Tile fill color onto floodplane. */ if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(floodplane_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelGray(floodplane_image,p) != 0) { GetFillColor(draw_info,x,y,&fill_color,exception); SetPixelViaPixelInfo(image,&fill_color,q); } p+=GetPixelChannels(floodplane_image); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } floodplane_view=DestroyCacheView(floodplane_view); image_view=DestroyCacheView(image_view); segment_info=RelinquishVirtualMemory(segment_info); floodplane_image=DestroyImage(floodplane_image); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G r a d i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GradientImage() applies a continuously smooth color transitions along a % vector from one color to another. % % Note, the interface of this method will change in the future to support % more than one transistion. % % The format of the GradientImage method is: % % MagickBooleanType GradientImage(Image *image,const GradientType type, % const SpreadMethod method,const PixelInfo *start_color, % const PixelInfo *stop_color,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the gradient type: linear or radial. % % o spread: the gradient spread meathod: pad, reflect, or repeat. % % o start_color: the start color. % % o stop_color: the stop color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GradientImage(Image *image, const GradientType type,const SpreadMethod method,const StopInfo *stops, const size_t number_stops,ExceptionInfo *exception) { const char *artifact; DrawInfo *draw_info; GradientInfo *gradient; MagickBooleanType status; /* Set gradient start-stop end points. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(stops != (const StopInfo *) NULL); assert(number_stops > 0); draw_info=AcquireDrawInfo(); gradient=(&draw_info->gradient); gradient->type=type; gradient->bounding_box.width=image->columns; gradient->bounding_box.height=image->rows; artifact=GetImageArtifact(image,"gradient:bounding-box"); if (artifact != (const char *) NULL) (void) ParseAbsoluteGeometry(artifact,&gradient->bounding_box); gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=(double) image->rows-1; artifact=GetImageArtifact(image,"gradient:direction"); if (artifact != (const char *) NULL) { GravityType direction; direction=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,artifact); switch (direction) { case NorthWestGravity: { gradient->gradient_vector.x1=(double) image->columns-1; gradient->gradient_vector.y1=(double) image->rows-1; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=0.0; break; } case NorthGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=(double) image->rows-1; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=0.0; break; } case NorthEastGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=(double) image->rows-1; gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=0.0; break; } case WestGravity: { gradient->gradient_vector.x1=(double) image->columns-1; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=0.0; break; } case EastGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=0.0; break; } case SouthWestGravity: { gradient->gradient_vector.x1=(double) image->columns-1; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=(double) image->rows-1; break; } case SouthGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=(double) image->columns-1; break; } case SouthEastGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=(double) image->rows-1; break; } default: break; } } artifact=GetImageArtifact(image,"gradient:angle"); if (artifact != (const char *) NULL) gradient->angle=StringToDouble(artifact,(char **) NULL); artifact=GetImageArtifact(image,"gradient:vector"); if (artifact != (const char *) NULL) (void) sscanf(artifact,"%lf%*[ ,]%lf%*[ ,]%lf%*[ ,]%lf", &gradient->gradient_vector.x1,&gradient->gradient_vector.y1, &gradient->gradient_vector.x2,&gradient->gradient_vector.y2); if ((GetImageArtifact(image,"gradient:angle") == (const char *) NULL) && (GetImageArtifact(image,"gradient:direction") == (const char *) NULL) && (GetImageArtifact(image,"gradient:extent") == (const char *) NULL) && (GetImageArtifact(image,"gradient:vector") == (const char *) NULL)) if ((type == LinearGradient) && (gradient->gradient_vector.y2 != 0.0)) gradient->gradient_vector.x2=0.0; gradient->center.x=(double) gradient->gradient_vector.x2/2.0; gradient->center.y=(double) gradient->gradient_vector.y2/2.0; artifact=GetImageArtifact(image,"gradient:center"); if (artifact != (const char *) NULL) (void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->center.x, &gradient->center.y); artifact=GetImageArtifact(image,"gradient:angle"); if ((type == LinearGradient) && (artifact != (const char *) NULL)) { double sine, cosine, distance; /* Reference https://drafts.csswg.org/css-images-3/#linear-gradients. */ sine=sin((double) DegreesToRadians(gradient->angle-90.0)); cosine=cos((double) DegreesToRadians(gradient->angle-90.0)); distance=fabs((double) (image->columns-1.0)*cosine)+ fabs((double) (image->rows-1.0)*sine); gradient->gradient_vector.x1=0.5*((image->columns-1.0)-distance*cosine); gradient->gradient_vector.y1=0.5*((image->rows-1.0)-distance*sine); gradient->gradient_vector.x2=0.5*((image->columns-1.0)+distance*cosine); gradient->gradient_vector.y2=0.5*((image->rows-1.0)+distance*sine); } gradient->radii.x=(double) MagickMax((image->columns-1.0),(image->rows-1.0))/ 2.0; gradient->radii.y=gradient->radii.x; artifact=GetImageArtifact(image,"gradient:extent"); if (artifact != (const char *) NULL) { if (LocaleCompare(artifact,"Circle") == 0) { gradient->radii.x=(double) MagickMax((image->columns-1.0), (image->rows-1.0))/2.0; gradient->radii.y=gradient->radii.x; } if (LocaleCompare(artifact,"Diagonal") == 0) { gradient->radii.x=(double) (sqrt((double) (image->columns-1.0)* (image->columns-1.0)+(image->rows-1.0)*(image->rows-1.0)))/2.0; gradient->radii.y=gradient->radii.x; } if (LocaleCompare(artifact,"Ellipse") == 0) { gradient->radii.x=(double) (image->columns-1.0)/2.0; gradient->radii.y=(double) (image->rows-1.0)/2.0; } if (LocaleCompare(artifact,"Maximum") == 0) { gradient->radii.x=(double) MagickMax((image->columns-1.0), (image->rows-1.0))/2.0; gradient->radii.y=gradient->radii.x; } if (LocaleCompare(artifact,"Minimum") == 0) { gradient->radii.x=(double) (MagickMin((image->columns-1.0), (image->rows-1.0)))/2.0; gradient->radii.y=gradient->radii.x; } } artifact=GetImageArtifact(image,"gradient:radii"); if (artifact != (const char *) NULL) (void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->radii.x, &gradient->radii.y); gradient->radius=MagickMax(gradient->radii.x,gradient->radii.y); gradient->spread=method; /* Define the gradient to fill between the stops. */ gradient->number_stops=number_stops; gradient->stops=(StopInfo *) AcquireQuantumMemory(gradient->number_stops, sizeof(*gradient->stops)); if (gradient->stops == (StopInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memcpy(gradient->stops,stops,(size_t) number_stops* sizeof(*stops)); /* Draw a gradient on the image. */ status=DrawGradientImage(image,draw_info,exception); draw_info=DestroyDrawInfo(draw_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O i l P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OilPaintImage() applies a special effect filter that simulates an oil % painting. Each pixel is replaced by the most frequent color occurring % in a circular region defined by radius. % % The format of the OilPaintImage method is: % % Image *OilPaintImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the circular neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ static size_t **DestroyHistogramThreadSet(size_t **histogram) { register ssize_t i; assert(histogram != (size_t **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (histogram[i] != (size_t *) NULL) histogram[i]=(size_t *) RelinquishMagickMemory(histogram[i]); histogram=(size_t **) RelinquishMagickMemory(histogram); return(histogram); } static size_t **AcquireHistogramThreadSet(const size_t count) { register ssize_t i; size_t **histogram, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); histogram=(size_t **) AcquireQuantumMemory(number_threads,sizeof(*histogram)); if (histogram == (size_t **) NULL) return((size_t **) NULL); (void) memset(histogram,0,number_threads*sizeof(*histogram)); for (i=0; i < (ssize_t) number_threads; i++) { histogram[i]=(size_t *) AcquireQuantumMemory(count,sizeof(**histogram)); if (histogram[i] == (size_t *) NULL) return(DestroyHistogramThreadSet(histogram)); } return(histogram); } MagickExport Image *OilPaintImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { #define NumberPaintBins 256 #define OilPaintImageTag "OilPaint/Image" CacheView *image_view, *paint_view; Image *linear_image, *paint_image; MagickBooleanType status; MagickOffsetType progress; size_t **histograms, width; ssize_t center, y; /* Initialize painted image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=GetOptimalKernelWidth2D(radius,sigma); linear_image=CloneImage(image,0,0,MagickTrue,exception); paint_image=CloneImage(image,0,0,MagickTrue,exception); if ((linear_image == (Image *) NULL) || (paint_image == (Image *) NULL)) { if (linear_image != (Image *) NULL) linear_image=DestroyImage(linear_image); if (paint_image != (Image *) NULL) linear_image=DestroyImage(paint_image); return((Image *) NULL); } if (SetImageStorageClass(paint_image,DirectClass,exception) == MagickFalse) { linear_image=DestroyImage(linear_image); paint_image=DestroyImage(paint_image); return((Image *) NULL); } histograms=AcquireHistogramThreadSet(NumberPaintBins); if (histograms == (size_t **) NULL) { linear_image=DestroyImage(linear_image); paint_image=DestroyImage(paint_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Oil paint image. */ status=MagickTrue; progress=0; center=(ssize_t) GetPixelChannels(linear_image)*(linear_image->columns+width)* (width/2L)+GetPixelChannels(linear_image)*(width/2L); image_view=AcquireVirtualCacheView(linear_image,exception); paint_view=AcquireAuthenticCacheView(paint_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(linear_image,paint_image,linear_image->rows,1) #endif for (y=0; y < (ssize_t) linear_image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register size_t *histogram; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (width/2L),linear_image->columns+width,width,exception); q=QueueCacheViewAuthenticPixels(paint_view,0,y,paint_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } histogram=histograms[GetOpenMPThreadId()]; for (x=0; x < (ssize_t) linear_image->columns; x++) { register ssize_t i, u; size_t count; ssize_t j, k, n, v; /* Assign most frequent color. */ k=0; j=0; count=0; (void) memset(histogram,0,NumberPaintBins* sizeof(*histogram)); for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { n=(ssize_t) ScaleQuantumToChar(ClampToQuantum(GetPixelIntensity( linear_image,p+GetPixelChannels(linear_image)*(u+k)))); histogram[n]++; if (histogram[n] > count) { j=k+u; count=histogram[n]; } } k+=(ssize_t) (linear_image->columns+width); } for (i=0; i < (ssize_t) GetPixelChannels(linear_image); i++) { PixelChannel channel = GetPixelChannelChannel(linear_image,i); PixelTrait traits = GetPixelChannelTraits(linear_image,channel); PixelTrait paint_traits=GetPixelChannelTraits(paint_image,channel); if ((traits == UndefinedPixelTrait) || (paint_traits == UndefinedPixelTrait)) continue; if ((paint_traits & CopyPixelTrait) != 0) { SetPixelChannel(paint_image,channel,p[center+i],q); continue; } SetPixelChannel(paint_image,channel,p[j*GetPixelChannels(linear_image)+ i],q); } p+=GetPixelChannels(linear_image); q+=GetPixelChannels(paint_image); } if (SyncCacheViewAuthenticPixels(paint_view,exception) == MagickFalse) status=MagickFalse; if (linear_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(linear_image,OilPaintImageTag,progress++, linear_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } paint_view=DestroyCacheView(paint_view); image_view=DestroyCacheView(image_view); histograms=DestroyHistogramThreadSet(histograms); linear_image=DestroyImage(linear_image); if (status == MagickFalse) paint_image=DestroyImage(paint_image); return(paint_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p a q u e P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpaquePaintImage() changes any pixel that matches color with the color % defined by fill argument. % % By default color must match a particular pixel color exactly. However, in % many cases two colors may differ by a small amount. Fuzz defines how much % tolerance is acceptable to consider two colors as the same. For example, % set fuzz to 10 and the color red at intensities of 100 and 102 respectively % are now interpreted as the same color. % % The format of the OpaquePaintImage method is: % % MagickBooleanType OpaquePaintImage(Image *image,const PixelInfo *target, % const PixelInfo *fill,const MagickBooleanType invert, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o target: the RGB value of the target color. % % o fill: the replacement color. % % o invert: paint any pixel that does not match the target color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OpaquePaintImage(Image *image, const PixelInfo *target,const PixelInfo *fill,const MagickBooleanType invert, ExceptionInfo *exception) { #define OpaquePaintImageTag "Opaque/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo conform_fill, conform_target, zero; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(target != (PixelInfo *) NULL); assert(fill != (PixelInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); ConformPixelInfo(image,fill,&conform_fill,exception); ConformPixelInfo(image,target,&conform_target,exception); /* Make image color opaque. */ status=MagickTrue; progress=0; GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,&conform_target) != invert) { PixelTrait traits; traits=GetPixelChannelTraits(image,RedPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelRed(image,(Quantum) conform_fill.red,q); traits=GetPixelChannelTraits(image,GreenPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelGreen(image,(Quantum) conform_fill.green,q); traits=GetPixelChannelTraits(image,BluePixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelBlue(image,(Quantum) conform_fill.blue,q); traits=GetPixelChannelTraits(image,BlackPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelBlack(image,(Quantum) conform_fill.black,q); traits=GetPixelChannelTraits(image,AlphaPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelAlpha(image,(Quantum) conform_fill.alpha,q); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,OpaquePaintImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p a r e n t P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransparentPaintImage() changes the opacity value associated with any pixel % that matches color to the value defined by opacity. % % By default color must match a particular pixel color exactly. However, in % many cases two colors may differ by a small amount. Fuzz defines how much % tolerance is acceptable to consider two colors as the same. For example, % set fuzz to 10 and the color red at intensities of 100 and 102 respectively % are now interpreted as the same color. % % The format of the TransparentPaintImage method is: % % MagickBooleanType TransparentPaintImage(Image *image, % const PixelInfo *target,const Quantum opacity, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o target: the target color. % % o opacity: the replacement opacity value. % % o invert: paint any pixel that does not match the target color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType TransparentPaintImage(Image *image, const PixelInfo *target,const Quantum opacity,const MagickBooleanType invert, ExceptionInfo *exception) { #define TransparentPaintImageTag "Transparent/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo zero; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(target != (PixelInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); /* Make image color transparent. */ status=MagickTrue; progress=0; GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert) SetPixelAlpha(image,opacity,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TransparentPaintImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p a r e n t P a i n t I m a g e C h r o m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransparentPaintImageChroma() changes the opacity value associated with any % pixel that matches color to the value defined by opacity. % % As there is one fuzz value for the all the channels, TransparentPaintImage() % is not suitable for the operations like chroma, where the tolerance for % similarity of two color component (RGB) can be different. Thus we define % this method to take two target pixels (one low and one high) and all the % pixels of an image which are lying between these two pixels are made % transparent. % % The format of the TransparentPaintImageChroma method is: % % MagickBooleanType TransparentPaintImageChroma(Image *image, % const PixelInfo *low,const PixelInfo *high,const Quantum opacity, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o low: the low target color. % % o high: the high target color. % % o opacity: the replacement opacity value. % % o invert: paint any pixel that does not match the target color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType TransparentPaintImageChroma(Image *image, const PixelInfo *low,const PixelInfo *high,const Quantum opacity, const MagickBooleanType invert,ExceptionInfo *exception) { #define TransparentPaintImageTag "Transparent/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(high != (PixelInfo *) NULL); assert(low != (PixelInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); /* Make image color transparent. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType match; PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); match=((pixel.red >= low->red) && (pixel.red <= high->red) && (pixel.green >= low->green) && (pixel.green <= high->green) && (pixel.blue >= low->blue) && (pixel.blue <= high->blue)) ? MagickTrue : MagickFalse; if (match != invert) SetPixelAlpha(image,opacity,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TransparentPaintImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
GB_unaryop__minv_int32_int8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_int32_int8 // op(A') function: GB_tran__minv_int32_int8 // C type: int32_t // A type: int8_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = GB_IMINV_SIGNED (aij, 32) #define GB_ATYPE \ int8_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_SIGNED (x, 32) ; // casting #define GB_CASTING(z, x) \ int32_t z = (int32_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_INT32 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_int32_int8 ( int32_t *restrict Cx, const int8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_int32_int8 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
pointer2Array3.c
// array types from a parameter list have to be converted to corresponding pointer types // to avoid segmentation fault. // Kernel is extracted from cg of npb2.3 omp c benchmarks. static int colidx[100][100][50]; static void makea (int colidx[100][100][50]) { int i,j,k; #pragma omp parallel for private(i,j,k) for (i = 0; i < 100; i++) for (j = 0; j < 100; j++) for (k = 0; k < 50; k++) colidx[i][j][k] = 0; } int main() { makea(colidx); }
pressure_splitting_builder_and_solver.h
/* ============================================================================== Kratos A General Purpose Software for Multi-Physics Finite Element Analysis Version 1.0 (Released on march 05, 2007). Copyright 2007 Pooyan Dadvand, Riccardo Rossi pooyan@cimne.upc.edu rrossi@cimne.upc.edu CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following condition: Distribution of this code for any commercial purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNER. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================== */ /* * File: pressure_splitting_builder_and_solver.h * Author: jcotela * * Created on 18 February 2010, 15:07 */ #if !defined(KRATOS_PRESSURE_SPLITTING_BUILDER_AND_SOLVER_H) #define KRATOS_PRESSURE_SPLITTING_BUILDER_AND_SOLVER_H /* System includes */ //#include <set> #ifdef _OPENMP #include <omp.h> #endif #include "utilities/openmp_utils.h" /* External includes */ #include <boost/smart_ptr.hpp> #include <boost/numeric/ublas/matrix_sparse.hpp> #include <boost/numeric/ublas/matrix_proxy.hpp> /* Project includes */ #include "includes/define.h" #include "solving_strategies/builder_and_solvers/builder_and_solver.h" namespace Kratos { ///@addtogroup IncompressibleFluidApplication ///@{ ///@name Kratos classes ///@{ /// A builder and solver scheme based on separating pressure and velocity Dofs /** The PressureSplittingBuilderAndSolver class is intended to solve the velocity and pressure degrees of freedom separately, thanks to a Pressure Schur complement type decomposition. Given a system equation of the type \f[ \left[ \begin{array}{cc} S & G \\ D & L \end{array} \right] \left[ \begin{array}{c} \delta u \\ \delta p \end{array} \right] = \left[ \begin{array}{c} r_u \\ r_p \end{array} \right] \f] This class divides the system and solves it as \f[ S \delta u = r_u - G \, \delta p \f] \f[ \left( L - D S^{-1} G \right) \, \delta p = r_p - D {S}^{-1} \, r_u \f] where \f$ S^{-1} \f$ is approximated by \f$ \left( Diag \left( S \right) \right)^{-1} \f$. The method implemented by this class is described in J. Cotela, R. Rossi, E. Onate and P. Dadvand A Comparison of Different Parallel Techinques Applied to the Solution of the Navier-Stokes Equations. Second International Conference on Parallel, Grid and Cloud Computing in Engineering, 2011. This class is intended to work with ASGS and VMS elements. @see ASGS2D, ASGS3D, VMS */ template< class TSparseSpace, class TDenseSpace , //= DenseSpace<double>, class TLinearSolver //= LinearSolver<TSparseSpace,TDenseSpace> > class PressureSplittingBuilderAndSolver: public BuilderAndSolver< TSparseSpace,TDenseSpace,TLinearSolver > { /* Please note that this builder and solver splits the system matrix * in 4 blocks and stores them separately. The system matrix A given as * input (to preserve the same function signatures as other builder and * solvers) is used here to store the matrix of the pressure equation. */ public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION( PressureSplittingBuilderAndSolver ); // Type Definitions typedef BuilderAndSolver<TSparseSpace,TDenseSpace, TLinearSolver> BaseType; typedef typename BaseType::TSchemeType TSchemeType; typedef typename BaseType::TDataType TDataType; typedef Dof<TDataType> TDofType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType; typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType; typedef typename BaseType::NodesArrayType NodesArrayType; typedef typename BaseType::ElementsArrayType ElementsArrayType; typedef typename BaseType::ConditionsArrayType ConditionsArrayType; typedef typename BaseType::ElementsContainerType ElementsContainerType; typedef std::size_t KeyType; // For Dof->GetVariable().Key() typedef boost::numeric::ublas::vector<int> IndexVector; typedef OpenMPUtils::PartitionVector PartitionVector; // UBLAS matrix access types typedef typename TSystemMatrixType::iterator1 OuterIt; typedef typename TSystemMatrixType::iterator2 InnerIt; typedef typename boost::numeric::ublas::matrix_row< TSystemMatrixType > RowType; ///@} ///@name Life Cycle ///@{ /// Constructor /** @param pNewVelLinearSystemSolver pointer to the solver for the velocity system(s). @param pNewPressLinearSystemSolver pointer to the solver for the pressure system. @param VelocityCorrection If > 0, explicitly solve the velocity to be divergence-free at each step. @param UseInexactNewton If true, dynamically set the linear iterative solver tolerance for the pressure system. @param NonLinearTol Only used if InexactNewton == true, otherwise the solver will use it's own tolerance. @param MaxTolFactor Inexact Newton parameter @param Gamma Inexact Newton parameter */ PressureSplittingBuilderAndSolver( typename TLinearSolver::Pointer pNewVelLinearSystemSolver, // Velocity solver, stored internally typename TLinearSolver::Pointer pNewPressLinearSystemSolver, // Pressure solver, stored by the base class unsigned int VelocityCorrection, // If > 0, explicitly solve the velocity to be divergence-free at each step bool UseInexactNewton, // If true, dynamically set the linear iterative solver tolerance for the pressure system double NonLinearTol = 1e-3, // Only used if InexactNewton == true, otherwise the solver will use it's own tolerance double MaxTolFactor = 0.1, double Gamma = 0.9): BuilderAndSolver< TSparseSpace,TDenseSpace,TLinearSolver >(pNewPressLinearSystemSolver), mpVelLinearSystemSolver(pNewVelLinearSystemSolver), mDofSetChanged(true), mVelocityCorrection(VelocityCorrection), mInexactNewton(UseInexactNewton), mMaxTolFactor(MaxTolFactor), mGamma(Gamma), mFirstIteration(true), // mVelTolFactor(0), mPressTolFactor(0), // mLastVelRHSNorm(0), mLastPressRHSNorm(0) { mSmallTol = 0.5*NonLinearTol; } /// Destructor virtual ~PressureSplittingBuilderAndSolver() {} ///@} ///@name Operations ///@{ /// Build System /** @param pScheme Pointer to the time Scheme. @param rModelPart Reference to the ModelPart that contains the problem. @param A Reference to the space reserved for the (pressure) system matrix. @param b Reference to the space reserved for the RHS vector. */ void Build( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& b) { KRATOS_TRY if (!pScheme) KRATOS_THROW_ERROR(std::runtime_error, "No scheme provided!", ""); // Get elements and conditions ElementsArrayType& rElements = rModelPart.Elements(); ConditionsArrayType& rConditions = rModelPart.Conditions(); // resetting to zero the vector of reactions TSparseSpace::SetToZero( *(BaseType::mpReactionsVector) ); // Reset internally stored matrices TSparseSpace::SetToZero( *mpS ); TSparseSpace::SetToZero( *mpG ); TSparseSpace::SetToZero( *mpD ); TSparseSpace::SetToZero( *mpL ); #ifndef _OPENMP // Define contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0,0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); // Will store the position of each Dof in the system Element::EquationIdVectorType EquationIds; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); // Assemble contributions from elements for( typename ElementsArrayType::ptr_iterator pElem = rElements.ptr_begin(); pElem != rElements.ptr_end(); pElem++) { // Get Elemental Contributions pScheme->CalculateSystemContributions(*pElem,LHS_Contribution, RHS_Contribution,EquationIds,CurrentProcessInfo); //assemble the elemental contribution Assemble(b,LHS_Contribution,RHS_Contribution,EquationIds); // clean local elemental memory pScheme->CleanMemory(*pElem); } LHS_Contribution.resize(0,0,false); RHS_Contribution.resize(0,false); // assemble all conditions for ( typename ConditionsArrayType::ptr_iterator pCond = rConditions.ptr_begin(); pCond != rConditions.ptr_end(); pCond++) { // Get condition Contributions pScheme->Condition_CalculateSystemContributions(*pCond,LHS_Contribution, RHS_Contribution,EquationIds,CurrentProcessInfo); // Assemble condition contribution Assemble(b,LHS_Contribution,RHS_Contribution,EquationIds); } #else //creating an array of lock variables of the size of the system matrix int TotalSize = BaseType::mEquationSystemSize; std::vector< omp_lock_t > lock_array(TotalSize); for(int i = 0; i<TotalSize; i++) omp_init_lock( &lock_array[i] ); //create a partition of the element array int NumThreads = OpenMPUtils::GetNumThreads(); PartitionVector ElementPartition; OpenMPUtils::DivideInPartitions(rElements.size(),NumThreads,ElementPartition); // double start_prod = omp_get_wtime(); #pragma omp parallel { int k = OpenMPUtils::ThisThread(); //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0,0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different terms Element::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); typename ElementsArrayType::ptr_iterator ElemBegin = rElements.ptr_begin()+ElementPartition[k]; typename ElementsArrayType::ptr_iterator ElemEnd = rElements.ptr_begin()+ElementPartition[k+1]; // assemble all elements for (typename ElementsArrayType::ptr_iterator pElem = ElemBegin; pElem != ElemEnd; pElem++) { //calculate elemental contribution pScheme->CalculateSystemContributions(*pElem,LHS_Contribution,RHS_Contribution,EquationId,CurrentProcessInfo); //assemble the elemental contribution Assemble(b,LHS_Contribution,RHS_Contribution,EquationId,lock_array); // clean local elemental memory pScheme->CleanMemory(*pElem); } } PartitionVector ConditionPartition; OpenMPUtils::DivideInPartitions(rConditions.size(),NumThreads,ConditionPartition); #pragma omp parallel { int k = OpenMPUtils::ThisThread(); //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0,0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Condition::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); typename ConditionsArrayType::ptr_iterator CondBegin = rConditions.ptr_begin()+ConditionPartition[k]; typename ConditionsArrayType::ptr_iterator CondEnd = rConditions.ptr_begin()+ConditionPartition[k+1]; // assemble all conditions for (typename ConditionsArrayType::ptr_iterator pCond = CondBegin; pCond != CondEnd; pCond++) { //calculate condition contribution pScheme->Condition_CalculateSystemContributions(*pCond,LHS_Contribution,RHS_Contribution,EquationId,CurrentProcessInfo); //assemble condition contribution Assemble(b,LHS_Contribution,RHS_Contribution,EquationId,lock_array); } } // double stop_prod = omp_get_wtime(); // std::cout << "time: " << stop_prod - start_prod << std::endl; for(int i = 0; i< TotalSize; i++) omp_destroy_lock(&lock_array[i]); #endif /* Build the pressure system matrix */ CalculateSystemMatrix(A); KRATOS_CATCH(""); } /// Build Left Hand Side only /** @param pScheme Pointer to the time Scheme. @param rModelPart Reference to the ModelPart that contains the problem. @param A Reference to the space reserved for the (pressure) system matrix. */ void BuildLHS( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A) { KRATOS_TRY; if (!pScheme) KRATOS_THROW_ERROR(std::runtime_error, "No scheme provided!", ""); // Get elements and conditions ElementsArrayType& rElements = rModelPart.Elements(); ConditionsArrayType& rConditions = rModelPart.Conditions(); // resetting to zero the vector of reactions TSparseSpace::SetToZero(*(BaseType::mpReactionsVector)); // Reset internally stored matrices TSparseSpace::SetToZero( *mpS ); TSparseSpace::SetToZero( *mpG ); TSparseSpace::SetToZero( *mpD ); TSparseSpace::SetToZero( *mpL ); // Define contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); // Will store the position of each Dof in the system Element::EquationIdVectorType EquationIds; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); //#ifndef _OPENMP // Assemble contributions from elements for (typename ElementsArrayType::ptr_iterator pElem = rElements.ptr_begin(); pElem != rElements.ptr_end(); pElem++) { // Get Elemental Contributions pScheme->Calculate_LHS_Contribution(*pElem, LHS_Contribution, EquationIds, CurrentProcessInfo); //assemble the elemental contribution AssembleLHS(LHS_Contribution, EquationIds); // clean local elemental memory pScheme->CleanMemory(*pElem); } LHS_Contribution.resize(0, 0, false); // assemble all conditions for ( typename ConditionsArrayType::ptr_iterator pCond = rConditions.ptr_begin(); pCond != rConditions.ptr_end(); pCond++) { // Get Elemental Contributions pScheme->Condition_Calculate_LHS_Contribution(*pCond, LHS_Contribution, EquationIds, CurrentProcessInfo); //assemble the elemental contribution AssembleLHS(LHS_Contribution, EquationIds); } //#else // // DO MP VERSION HERE //#endif /* Build the pressure system matrix */ CalculateSystemMatrix(A); KRATOS_CATCH(""); } /// Build Left Hand Side with extra columns, including fixed Dofs. /** @param pScheme Pointer to the time Scheme. @param rModelPart Reference to the ModelPart that contains the problem. @param A Reference to the space reserved for the (pressure) system matrix. */ void BuildLHS_CompleteOnFreeRows( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A) { KRATOS_TRY; if (!pScheme) KRATOS_THROW_ERROR(std::runtime_error, "No scheme provided!", ""); // Get elements and conditions ElementsArrayType& rElements = rModelPart.Elements(); ConditionsArrayType& rConditions = rModelPart.Conditions(); // resetting to zero the vector of reactions TSparseSpace::SetToZero(*(BaseType::mpReactionsVector)); // Reset internally stored matrices TSparseSpace::SetToZero( *mpS ); TSparseSpace::SetToZero( *mpG ); TSparseSpace::SetToZero( *mpD ); TSparseSpace::SetToZero( *mpL ); // Define contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); // Will store the position of each Dof in the system Element::EquationIdVectorType EquationIds; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); //#ifndef _OPENMP // Assemble contributions from elements for (typename ElementsArrayType::ptr_iterator pElem = rElements.ptr_begin(); pElem != rElements.ptr_end(); pElem++) { // Get Elemental Contributions pScheme->Calculate_LHS_Contribution(*pElem, LHS_Contribution, EquationIds, CurrentProcessInfo); //assemble the elemental contribution AssembleLHS_CompleteOnFreeRows(LHS_Contribution, EquationIds); // clean local elemental memory pScheme->CleanMemory(*pElem); } LHS_Contribution.resize(0, 0, false); // assemble all conditions for (typename ConditionsArrayType::ptr_iterator pCond = rConditions.ptr_begin(); pCond != rConditions.ptr_end(); pCond++) { // Get Elemental Contributions pScheme->Condition_Calculate_LHS_Contribution(*pCond, LHS_Contribution, EquationIds, CurrentProcessInfo); //assemble the elemental contribution AssembleLHS_CompleteOnFreeRows(LHS_Contribution, EquationIds); } //#else // // DO MP VERSION HERE //#endif /* Build the pressure system matrix */ CalculateSystemMatrix(A); KRATOS_CATCH(""); } /// Solve one iteration. /** The solution is done in several steps, similar to fractional step methods. \n 1- Compute an intermediate velocity. \n 2- Compute the end-of-step pressure. \n 3- Obtain end-of-step velocity. @param A Reference to the space reserved for the (pressure) system matrix. @param Dx Reference to the space reserved for the vector of unknowns. @param b Reference to the space reserved for the RHS vector. */ void SystemSolve( TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) { KRATOS_TRY; double NormB; if (TSparseSpace::Size(b) != 0) NormB = TSparseSpace::TwoNorm(b); else NormB = 0; if (NormB != 0.0) { /* Solve current iteration in several steps */ // Initialize required variables and pointers TSystemVectorPointerType pDVel(new TSystemVectorType(mVelFreeDofs)); TSystemVectorType& rDVel = *pDVel; TSystemVectorPointerType pVelRHS(new TSystemVectorType(mVelFreeDofs)); TSystemVectorType& rVelRHS = *pVelRHS; for (unsigned int i = 0; i < mVelFreeDofs; i++) { rDVel[i] = 0.0; rVelRHS[i] = b[i]; } TSystemVectorPointerType pDPress(new TSystemVectorType(mPressFreeDofs)); TSystemVectorType& rDPress = *pDPress; TSystemVectorPointerType pPressRHS(new TSystemVectorType(mPressFreeDofs)); TSystemVectorType& rPressRHS = *pPressRHS; for (unsigned int i = 0, j=mVelFreeDofs; i < mPressFreeDofs; i++,j++) { rDPress[i] = 0.0; rPressRHS[i] = b[j]; } TSystemMatrixType& rS = *mpS; // Create a reference to the velocity system matrix // 1. Compute intermediate velocity // axpy_prod(*mpG, -rDPress, rVelRHS, false); // if (mInexactNewton == true) // { // double VelRHSNorm = TSparseSpace::TwoNorm(rVelRHS); // if(mFirstIteration == true) { // SetInitialTolerance(VelRHSNorm,mVelTolFactor); // } else { // UpdateTolerance(mLastVelRHSNorm,VelRHSNorm,mVelTolFactor); // } // mLastVelRHSNorm = VelRHSNorm; // } mpVelLinearSystemSolver->Solve(rS, rDVel, rVelRHS); // 2. Compute Pressure Variation #ifndef _OPENMP axpy_prod(*mpD, -rDVel, rPressRHS, false); #else Parallel_ProductAdd(*mpD, -rDVel, rPressRHS); #endif if (mInexactNewton == true) { double PressRHSNorm = TSparseSpace::TwoNorm(rPressRHS); if(mFirstIteration == true) { SetInitialTolerance(PressRHSNorm,mPressTolFactor); } else { UpdateTolerance(mLastPressRHSNorm,PressRHSNorm,mPressTolFactor); } mLastPressRHSNorm = PressRHSNorm; } BaseType::mpLinearSystemSolver->Solve(A, rDPress, rPressRHS); // 3. Determine End of Step velocity if ( mVelocityCorrection > 0) { TSparseSpace::Mult(*mpG, rDPress,rVelRHS); if ( mVelocityCorrection == 1 ) { for (unsigned int m = 0; m < mVelFreeDofs; m++) rDVel[m] -= (*mpIDiagS)[m]*rVelRHS[m]; } else if ( mVelocityCorrection == 2 ) { TSystemVectorPointerType pVelUpdate(new TSystemVectorType(mVelFreeDofs)); TSystemVectorType& rVelUpdate = *pVelUpdate; for (unsigned int i = 0; i < mVelFreeDofs; i++) rVelUpdate[i] = 0.0; mpVelLinearSystemSolver->Solve(rS, rVelUpdate, rVelRHS); noalias(rDVel) -= rVelUpdate; } } // Preconditioner // A = *mpL - A; // noalias(rPressRHS) = prod(A,rPressRHS); // Copy the solution to output variable for (unsigned int i = 0; i < mVelFreeDofs; i++) Dx[i] = rDVel[i]; for (unsigned int i = 0; i < mPressFreeDofs; i++) Dx[mVelFreeDofs + i] = rDPress[i]; if (mFirstIteration == true) mFirstIteration = false; } else TSparseSpace::SetToZero(Dx); //prints informations about the current time if (this->GetEchoLevel() > 1) { std::cout << *(BaseType::mpLinearSystemSolver) << std::endl; } KRATOS_CATCH(""); } /// Build and Solve system /** @param pScheme Pointer to the time Scheme. @param rModelPart Reference to the ModelPart that contains the problem. @param A Reference to the space reserved for the (pressure) system matrix. @param Dx Reference to the space reserved for the vector of unknowns. @param b Reference to the space reserved for the RHS vector. */ void BuildAndSolve( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) { KRATOS_TRY std::cout << "Building system" << std::endl; Build(pScheme, rModelPart, A, b); // //does nothing...dirichlet conditions are naturally dealt with in defining the residual // ApplyDirichletConditions(pScheme,rModelPart,A,Dx,b); if (this->GetEchoLevel() == 3) { std::cout << "before the solution of the system" << std::endl; std::cout << "System Matrix = " << A << std::endl; std::cout << "unknowns vector = " << Dx << std::endl; std::cout << "RHS vector = " << b << std::endl; } std::cout << "Solving System" << std::endl; SystemSolve(A, Dx, b); if (this->GetEchoLevel() == 3) { std::cout << "after the solution of the system" << std::endl; std::cout << "System Matrix = " << A << std::endl; std::cout << "unknowns vector = " << Dx << std::endl; std::cout << "RHS vector = " << b << std::endl; } KRATOS_CATCH(""); } /// Solve System for updated Right Hand Side /** @param pScheme Pointer to the time Scheme. @param rModelPart Reference to the ModelPart that contains the problem. @param A Reference to the space reserved for the (pressure) system matrix. @param Dx Reference to the space reserved for the vector of unknowns. @param b Reference to the space reserved for the RHS vector. */ void BuildRHSAndSolve( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) { KRATOS_TRY BuildRHS(pScheme,rModelPart,b); SystemSolve(A,Dx,b); KRATOS_CATCH(""); } /// Build Right Hand Side only /** @param pScheme Pointer to the time Scheme. @param rModelPart Reference to the ModelPart that contains the problem. @param b Reference to the space reserved for the RHS vector. */ void BuildRHS( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& b) { KRATOS_TRY; if (!pScheme) KRATOS_THROW_ERROR(std::runtime_error, "No scheme provided!", ""); // Get elements and conditions ElementsArrayType& rElements = rModelPart.Elements(); // ConditionsArrayType& rConditions = rModelPart.Conditions(); // resetting to zero the vector of reactions TSparseSpace::SetToZero(*(BaseType::mpReactionsVector)); //create a partition of the element array int NumThreads = OpenMPUtils::GetNumThreads(); PartitionVector ElementPartition; OpenMPUtils::DivideInPartitions(rElements.size(),NumThreads,ElementPartition); // Note that to assemble the LHS we use locks to avoid data races in OpenMP // Here we use #pragma omp atomic, as we need to write a double as oposed to // a row in a matrix #pragma omp parallel { int k = OpenMPUtils::ThisThread(); //contributions to the system LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different terms Element::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); typename ElementsArrayType::ptr_iterator ElemBegin = rElements.ptr_begin()+ElementPartition[k]; typename ElementsArrayType::ptr_iterator ElemEnd = rElements.ptr_begin()+ElementPartition[k+1]; // assemble all elements for (typename ElementsArrayType::ptr_iterator pElem = ElemBegin; pElem != ElemEnd; pElem++) { //calculate elemental contribution pScheme->Calculate_RHS_Contribution(*pElem,RHS_Contribution,EquationId,CurrentProcessInfo); //assemble the elemental contribution AssembleRHS(b,RHS_Contribution,EquationId/*,lock_array*/); // clean local elemental memory pScheme->CleanMemory(*pElem); } } // PartitionVector ConditionPartition; // OpenMPUtils::DivideInPartitions(rConditions.size(),NumThreads,ConditionPartition); // #pragma omp parallel // { // int k = OpenMPUtils::ThisThread(); // //contributions to the system // LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); // Condition::EquationIdVectorType EquationId; // ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); // typename ConditionsArrayType::ptr_iterator CondBegin = rConditions.ptr_begin()+ConditionPartition[k]; // typename ConditionsArrayType::ptr_iterator CondEnd = rConditions.ptr_begin()+ConditionPartition[k+1]; // // assemble all conditions // for (typename ConditionsArrayType::ptr_iterator pCond = CondBegin; pCond != CondEnd; pCond++) // { // //calculate condition contribution // pScheme->Condition_Calculate_RHS_Contribution(*pCond,RHS_Contribution,EquationId,CurrentProcessInfo); // //assemble condition contribution // AssembleRHS(b,RHS_Contribution,EquationId/*,lock_array*/); // } // } KRATOS_CATCH(""); } /// Identify Dofs and store pointers to them /** * Generates a list of the degrees of freedom in the model. * @param pScheme A pointer to the solution scheme * @param rModelPart A reference to the model part that contains the dofs */ void SetUpDofSet( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart) { /* Scalar implementation. There is a working OpenMP version after this, which has been commented out because Getting the list of Dofs is not thread-safe. (See find() in pointer_vector_set.h) */ KRATOS_TRY; std::cout << "Setting up degrees of freedom" << std::endl; //Gets the array of elements from the modeler ElementsArrayType& pElements = rModelPart.Elements(); ConditionsArrayType& pConditions = rModelPart.Conditions(); BaseType::mDofSet.clear(); // = DofsArrayType(); ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); Element::DofsVectorType ElementalDofList; for (typename ElementsArrayType::ptr_iterator it = pElements.ptr_begin(); it != pElements.ptr_end(); ++it) { // gets list of Dof involved on every element pScheme->GetElementalDofList(*it, ElementalDofList, CurrentProcessInfo); for (typename Element::DofsVectorType::iterator i = ElementalDofList.begin(); i != ElementalDofList.end(); ++i) { BaseType::mDofSet.push_back(i->get()); } } //taking into account conditions for (typename ConditionsArrayType::ptr_iterator it = pConditions.ptr_begin(); it != pConditions.ptr_end(); ++it) { // gets list of Dof involved on every element pScheme->GetConditionDofList(*it, ElementalDofList, CurrentProcessInfo); for (typename Element::DofsVectorType::iterator i = ElementalDofList.begin(); i != ElementalDofList.end(); ++i) { BaseType::mDofSet.push_back(i->get()); } } BaseType::mDofSet.Unique(); //throws an execption if there are no Degrees of freedom involved in the analysis if (BaseType::mDofSet.size() == 0) KRATOS_THROW_ERROR(std::logic_error, "No degrees of freedom!", ""); BaseType::mDofSetIsInitialized = true; mDofSetChanged = true; KRATOS_CATCH(""); } // { // KRATOS_TRY; // // std::cout << "Setting up degrees of freedom" << std::endl; // //Gets the array of elements from the modeler // ElementsArrayType& pElements = rModelPart.Elements(); // ConditionsArrayType& pConditions = rModelPart.Conditions(); // // BaseType::mDofSet = DofsArrayType(); // // ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); // // int NumThreads = OpenMPUtils::GetNumThreads(); // PartitionVector ElemPartition; // PartitionVector CondPartition; // // OpenMPUtils::DivideInPartitions(pElements.size(),NumThreads,ElemPartition); // OpenMPUtils::DivideInPartitions(pConditions.size(),NumThreads,CondPartition); // // std::vector< DofsArrayType > DofContainer(NumThreads); // // #pragma omp parallel // { // int k = OpenMPUtils::ThisThread(); // Element::DofsVectorType ElementalDofList; // // for (typename ElementsArrayType::ptr_iterator it = pElements.ptr_begin() + ElemPartition[k]; // it != pElements.ptr_begin() + ElemPartition[k+1]; ++it) { // // gets list of Dof involved on every element // pScheme->GetElementalDofList(*it, ElementalDofList, CurrentProcessInfo); // // for (typename Element::DofsVectorType::iterator i = ElementalDofList.begin(); // i != ElementalDofList.end(); ++i) { // DofContainer[k].push_back(*i); // } // } // // //taking into account conditions // for (typename ConditionsArrayType::ptr_iterator it = pConditions.ptr_begin() + CondPartition[k]; // it != pConditions.ptr_begin() + CondPartition[k+1]; ++it) { // // gets list of Dof involved on every element // pScheme->GetConditionDofList(*it, ElementalDofList, CurrentProcessInfo); // // for (typename Element::DofsVectorType::iterator i = ElementalDofList.begin(); // i != ElementalDofList.end(); ++i) { // DofContainer[k].push_back(*i); // } // } // // // Remove duplicates in the partial list // // (try to do as much work as possible in the parallel region) // DofContainer[k].Unique(); // } // // // Generate a single list // for (int k = 0; k < NumThreads ; k++) // for( typename DofsArrayType::ptr_iterator itDof = DofContainer[k].ptr_begin(); // itDof != DofContainer[k].ptr_end(); itDof++) { // BaseType::mDofSet.push_back(*itDof); // } // // BaseType::mDofSet.Unique(); // // //throws an execption if there are no Degrees of freedom involved in the analysis // if (BaseType::mDofSet.size() == 0) // KRATOS_THROW_ERROR(std::logic_error, "No degrees of freedom!", ""); // // BaseType::mDofSetIsInitialized = true; // mDofSetChanged = true; // // KRATOS_CATCH(""); // } /// Organise Dofs, separating fixed and free nodes. /** * This function orders the degrees of freedom of the system. * To prepare for uncoupled solution, the numeration is assigned as follows: * free velocity dofs, free pressure dofs, fixed velocity dofs and fixed pressure dofs * This ordering allows us to set up separated dof counters for each dof type. * They will be used to keep track of the type (variable and fixity) of each dof * during dof loops. * @param rModelPart A reference to the model part that contains the dofs */ void SetUpSystem(ModelPart& rModelPart) { KRATOS_TRY; unsigned int FreeId = 0; unsigned int FixedId = BaseType::mDofSet.size(); for (typename DofsArrayType::iterator itDof = BaseType::mDofSet.begin(); itDof != BaseType::mDofSet.end(); itDof++) { KeyType CurrVar = itDof->GetVariable().Key(); if ((CurrVar == VELOCITY_X) || (CurrVar == VELOCITY_Y) || (CurrVar == VELOCITY_Z)) { if (itDof->IsFree()) itDof->SetEquationId(FreeId++); } else { if (itDof->IsFixed()) itDof->SetEquationId(--FixedId); } } mVelFreeDofs = FreeId; mVelFixedDofsEnd = FixedId; for (typename DofsArrayType::iterator itDof = BaseType::mDofSet.begin(); itDof != BaseType::mDofSet.end(); itDof++) { KeyType CurrVar = itDof->GetVariable().Key(); if ((CurrVar == VELOCITY_X) || (CurrVar == VELOCITY_Y) || (CurrVar == VELOCITY_Z)) { if (itDof->IsFixed()) itDof->SetEquationId(--FixedId); } else { if (itDof->IsFree()) itDof->SetEquationId(FreeId++); } } // mVelDofsNum += (mVelFixedDofsEnd - FreeId); mPressFreeDofs = FreeId - mVelFreeDofs; BaseType::mEquationSystemSize = mVelFreeDofs + mPressFreeDofs; KRATOS_CATCH(""); } /// Initialize pointers to system vectors and matrices, check sizes. /** * Initialize pointers to the different vectors involved, check that they * have the correct size. * @param pA Pointer to the space reserved for the (pressure) system matrix. * @param pDx Pointer to the space reserved for the vector of unknowns. * @param pb Pointer to the space reserved for the RHS vector. * @param rElements Reference to the container of the model's elements. * @param rConditions Reference to the container of the model's conditions. * @param rCurrentProcessInfo Reference to the ProcessInfo of the ModelPart. */ void ResizeAndInitializeVectors( typename TSchemeType::Pointer pScheme, TSystemMatrixPointerType& pA, TSystemVectorPointerType& pDx, TSystemVectorPointerType& pb, ModelPart& r_model_part ) { KRATOS_TRY; if (pA == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemMatrixPointerType pNewA = TSystemMatrixPointerType(new TSystemMatrixType(0, 0)); pA.swap(pNewA); } if (pDx == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewDx = TSystemVectorPointerType(new TSystemVectorType(0)); pDx.swap(pNewDx); } if (pb == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewb = TSystemVectorPointerType(new TSystemVectorType(0)); pb.swap(pNewb); } if (BaseType::mpReactionsVector == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewReactionsVector = TSystemVectorPointerType(new TSystemVectorType(0)); BaseType::mpReactionsVector.swap(pNewReactionsVector); } // Member Matrices if (mpS == NULL) { TSystemMatrixPointerType pNewS(new TSystemMatrixType(0, 0)); mpS.swap(pNewS); } if (mpD == NULL) { TSystemMatrixPointerType pNewD(new TSystemMatrixType(0, 0)); mpD.swap(pNewD); } if (mpG == NULL) { TSystemMatrixPointerType pNewG(new TSystemMatrixType(0, 0)); mpG.swap(pNewG); } if (mpL == NULL) { TSystemMatrixPointerType pNewL(new TSystemMatrixType(0, 0)); mpL.swap(pNewL); } if (mpIDiagS == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewIDiagS = TSystemVectorPointerType(new TSystemVectorType(0)); mpIDiagS.swap(pNewIDiagS); } TSystemMatrixType& A = *pA; TSystemVectorType& Dx = *pDx; TSystemVectorType& b = *pb; TSystemMatrixType& S = *mpS; TSystemMatrixType& G = *mpG; TSystemMatrixType& D = *mpD; TSystemMatrixType& L = *mpL; TSystemVectorType& IDiagS = *mpIDiagS; //resizing the system vectors and matrix if (BaseType::GetReshapeMatrixFlag() == true || // if we must remesh mDofSetChanged == true || // if the dof set has changed S.size1() == 0 || D.size1() == 0 || G.size1() == 0 || L.size1() == 0 || A.size1() == 0 ) //if the matrices are not initialized { S.resize(mVelFreeDofs, mVelFreeDofs, false); G.resize(mVelFreeDofs, mPressFreeDofs, false); D.resize(mPressFreeDofs, mVelFreeDofs, false); L.resize(mPressFreeDofs, mPressFreeDofs, false); ConstructMatrixStructure(pScheme, S, D, G, L, r_model_part); A.resize(mPressFreeDofs, mPressFreeDofs, false); IDiagS.resize(mVelFreeDofs); AllocateSystemMatrix(A); ConstructSystemMatrix(A); mDofSetChanged = false; } else { // I do the check only for A, as the remaining matrices are private. // They are managed by this class, so they shouldn't change size spontaneously if (A.size1() != mPressFreeDofs || A.size2() != mPressFreeDofs ) { KRATOS_WATCH("it should not come here!!!!!!!! ... this is SLOW"); A.resize(mPressFreeDofs, mPressFreeDofs, false); IDiagS.resize(mVelFreeDofs); AllocateSystemMatrix(A); ConstructSystemMatrix(A); mDofSetChanged = false; } } if (Dx.size() != BaseType::mEquationSystemSize) Dx.resize(BaseType::mEquationSystemSize, false); if (b.size() != BaseType::mEquationSystemSize) b.resize(BaseType::mEquationSystemSize, false); //if needed resize the vector for the calculation of reactions if (BaseType::mCalculateReactionsFlag == true) { unsigned int ReactionsVectorSize = BaseType::mDofSet.size() - BaseType::mEquationSystemSize; if (BaseType::mpReactionsVector->size() != ReactionsVectorSize) BaseType::mpReactionsVector->resize(ReactionsVectorSize, false); } KRATOS_CATCH(""); } void InitializeSolutionStep( ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) { KRATOS_TRY; mFirstIteration = true; KRATOS_CATCH(""); } void FinalizeSolutionStep( ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) {} /// Calculate Reactions /** @param pScheme Pointer to the time Scheme. @param rModelPart Reference to the ModelPart that contains the problem. @param A Reference to the space reserved for the (pressure) system matrix. @param Dx Reference to the space reserved for the vector of unknowns. @param b Reference to the space reserved for the RHS vector. */ void CalculateReactions( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) { //refresh RHS to have the correct reactions BuildRHS(pScheme, rModelPart, b); int systemsize = BaseType::mEquationSystemSize; TSystemVectorType& rReactionsVector = *BaseType::mpReactionsVector; int NumThreads = OpenMPUtils::GetNumThreads(); OpenMPUtils::PartitionVector DofPartition; OpenMPUtils::DivideInPartitions(BaseType::mDofSet.size(),NumThreads,DofPartition); //updating variables #pragma omp parallel { int i; // Position of the Dof in the Reaction vector int k = OpenMPUtils::ThisThread(); typename DofsArrayType::ptr_iterator DofsBegin = BaseType::mDofSet.ptr_begin() + DofPartition[k]; typename DofsArrayType::ptr_iterator DofsEnd = BaseType::mDofSet.ptr_begin() + DofPartition[k+1]; for (typename DofsArrayType::ptr_iterator itDof = DofsBegin; itDof != DofsEnd; itDof++) { if ( (*itDof)->IsFixed() ) { i = (*itDof)->EquationId() - systemsize; (*itDof)->GetSolutionStepReactionValue() = rReactionsVector[i]; } else { i = (*itDof)->EquationId(); (*itDof)->GetSolutionStepReactionValue() = -b[i]; } } } } void ApplyDirichletConditions( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) {} void ApplyPointLoads( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& b) {} /// Free memory used by class members once no longer needed. /** * this function is intended to be called at the end of the solution * step to clean up memory storage not needed. */ void Clear() { this->mDofSet.clear(); // = DofsArrayType(); if (this->mpReactionsVector != NULL) TSparseSpace::Clear((this->mpReactionsVector)); if (this->mpS != NULL) TSparseSpace::Clear((this->mpS)); if (this->mpG != NULL) TSparseSpace::Clear((this->mpG)); if (this->mpD != NULL) TSparseSpace::Clear((this->mpD)); if (this->mpL != NULL) TSparseSpace::Clear((this->mpL)); if (this->mpIDiagS != NULL) TSparseSpace::Clear((this->mpIDiagS)); if (this->GetEchoLevel() > 0) { std::cout << "PressureSplittingBuilderAndSolver Clear Function called" << std::endl; } } /// Force a recalculation of the graph for the pressure system matrix /** * Provides a way to modify the system matrix from outside the buider and solver. * Use carefully. Remember that this should be called before Build(), where * the matrix will be filled. If the DofSet changes between time steps, the * system matrix will be reformed internally, so this function should only be used * if the system matrix structure changes inside the time step. * @param A Reference to the space reserved for the (pressure) system matrix. */ inline void ReshapeSystemMatrix(TSystemMatrixType& A) { AllocateSystemMatrix(A); ConstructSystemMatrix(A); } ///@} Operations protected: /// Compute graphs for the different matrices involved in the problem virtual void ConstructMatrixStructure( typename TSchemeType::Pointer pScheme, TSystemMatrixType& S, TSystemMatrixType& D, TSystemMatrixType& G, TSystemMatrixType& L, ModelPart& rModelPart) { std::vector< std::vector<std::size_t> > indicesS(mVelFreeDofs); std::vector< std::vector<std::size_t> > indicesG(mVelFreeDofs); std::vector< std::vector<std::size_t> > indicesD(mPressFreeDofs); std::vector< std::vector<std::size_t> > indicesL(mPressFreeDofs); Element::EquationIdVectorType ids; ids.reserve(16); // 16 as initial capacity: 4 Dofs per node assumed // Identify and collect the indices of non-zero terms in each matrix for (typename ElementsContainerType::const_iterator itElem = rModelPart.ElementsBegin(); itElem != rModelPart.ElementsEnd(); itElem++) { pScheme->EquationId( *(itElem.base()) , ids, CurrentProcessInfo); for (std::size_t i = 0; i < ids.size(); i++) if (ids[i] < mVelFreeDofs) { std::vector<std::size_t>& RowS = indicesS[ids[i]]; std::vector<std::size_t>& RowG = indicesG[ids[i]]; for (std::size_t j = 0; j < ids.size(); j++) { if (ids[j] < mVelFreeDofs) AddUnique(RowS, ids[j]); else if (ids[j] < BaseType::mEquationSystemSize) AddUnique(RowG, ids[j] - mVelFreeDofs); } } else if (ids[i] < BaseType::mEquationSystemSize) { std::vector<std::size_t>& RowD = indicesD[ids[i] - mVelFreeDofs]; std::vector<std::size_t>& RowL = indicesL[ids[i] - mVelFreeDofs]; for (std::size_t j = 0; j < ids.size(); j++) { if (ids[j] < mVelFreeDofs) AddUnique(RowD, ids[j]); else if (ids[j] < BaseType::mEquationSystemSize) AddUnique(RowL, ids[j] - mVelFreeDofs); } } } // Do the same for conditions for (typename ConditionsArrayType::const_iterator itCond = rModelPart.ConditionsBegin(); itCond != rModelPart.ConditionsEnd(); itCond++) { pScheme->Condition_EquationId( *(itCond.base()), ids, CurrentProcessInfo); for (std::size_t i = 0; i < ids.size(); i++) if (ids[i] < mVelFreeDofs) { std::vector<std::size_t>& RowS = indicesS[ids[i]]; std::vector<std::size_t>& RowG = indicesG[ids[i]]; for (std::size_t j = 0; j < ids.size(); j++) { if (ids[j] < mVelFreeDofs) AddUnique(RowS, ids[j]); else if (ids[j] < BaseType::mEquationSystemSize) AddUnique(RowG, ids[j] - mVelFreeDofs); } } else if (ids[i] < BaseType::mEquationSystemSize) { std::vector<std::size_t>& RowD = indicesD[ids[i] - mVelFreeDofs]; std::vector<std::size_t>& RowL = indicesL[ids[i] - mVelFreeDofs]; for (std::size_t j = 0; j < ids.size(); j++) { if (ids[j] < mVelFreeDofs) AddUnique(RowD, ids[j]); else if (ids[j] < BaseType::mEquationSystemSize) AddUnique(RowL, ids[j] - mVelFreeDofs); } } } // Allocate memory and initialize matrices with zeros int NumTermsS = 0; // Counters for non-zero terms int NumTermsG = 0; int NumTermsD = 0; int NumTermsL = 0; for (std::size_t i = 0; i < indicesS.size(); i++) NumTermsS += indicesS[i].size(); S.reserve(NumTermsS, false); for (std::size_t i = 0; i < indicesG.size(); i++) NumTermsG += indicesG[i].size(); G.reserve(NumTermsG, false); for (std::size_t i = 0; i < indicesD.size(); i++) NumTermsD += indicesD[i].size(); D.reserve(NumTermsD, false); for (std::size_t i = 0; i < indicesL.size(); i++) NumTermsL += indicesL[i].size(); L.reserve(NumTermsL, false); // Create the matrix structure, filling it with zeros AllocateSpace(S, indicesS); AllocateSpace(G, indicesG); AllocateSpace(D, indicesD); AllocateSpace(L, indicesL); } private: /// Add a matrix position to the list (check that it hasn't been used before) void AddUnique( std::vector<std::size_t>& Row, const std::size_t& Candidate) { std::vector<std::size_t>::iterator i = Row.begin(); std::vector<std::size_t>::iterator endit = Row.end(); while ( i != endit && (*i) != Candidate) i++; if( i == endit ) Row.push_back(Candidate); } /* * Assembly functions */ // ALL ASSEMBLY FUNCTIONS NEED OPENMP. CONSIDER ADDING Assemble_OnFreeRows /// Add terms from an elemental matrix to system matrices #ifndef _OPENMP void Assemble( TSystemVectorType& b, LocalSystemMatrixType& LHS_Contribution, LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId) { unsigned int ContributionSize = EquationId.size(); for (unsigned int i = 0; i < ContributionSize; i++) { unsigned int Global_i = EquationId[i]; if (Global_i < mVelFreeDofs) { for (unsigned int j = 0; j < ContributionSize; j++) { unsigned int Global_j = EquationId[j]; if (Global_j < mVelFreeDofs) { mpS->operator()(Global_i, Global_j) += LHS_Contribution(i, j); } else if (Global_j < BaseType::mEquationSystemSize) { mpG->operator()(Global_i, Global_j - mVelFreeDofs) += LHS_Contribution(i, j); } } b[Global_i] += RHS_Contribution[i]; } else if (Global_i < BaseType::mEquationSystemSize) { for (unsigned int j = 0; j < ContributionSize; j++) { unsigned int Global_j = EquationId[j]; if (Global_j < mVelFreeDofs) { mpD->operator()(Global_i - mVelFreeDofs, Global_j) += LHS_Contribution(i, j); } else if (Global_j < BaseType::mEquationSystemSize) { mpL->operator()(Global_i - mVelFreeDofs, Global_j - mVelFreeDofs) += LHS_Contribution(i, j); } } b[Global_i] += RHS_Contribution[i]; } } } #else void Assemble( TSystemVectorType& b, const LocalSystemMatrixType& LHS_Contribution, const LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId, std::vector< omp_lock_t >& lock_array) { unsigned int ContributionSize = EquationId.size(); for (unsigned int i = 0; i < ContributionSize; i++) { unsigned int Global_i = EquationId[i]; if ( Global_i < mVelFreeDofs ) { omp_set_lock(&lock_array[Global_i]); for (unsigned int j = 0; j < ContributionSize; j++) { unsigned int Global_j = EquationId[j]; if (Global_j < mVelFreeDofs) { mpS->operator()(Global_i, Global_j) += LHS_Contribution(i, j); } else if (Global_j < BaseType::mEquationSystemSize) { mpG->operator()(Global_i, Global_j - mVelFreeDofs) += LHS_Contribution(i, j); } } b[Global_i] += RHS_Contribution[i]; omp_unset_lock(&lock_array[Global_i]); } else if (Global_i < BaseType::mEquationSystemSize) { omp_set_lock(&lock_array[Global_i]); for (unsigned int j = 0; j < ContributionSize; j++) { unsigned int Global_j = EquationId[j]; if (Global_j < mVelFreeDofs) { mpD->operator()(Global_i - mVelFreeDofs, Global_j) += LHS_Contribution(i, j); } else if (Global_j < BaseType::mEquationSystemSize) { mpL->operator()(Global_i - mVelFreeDofs, Global_j - mVelFreeDofs) += LHS_Contribution(i, j); } } b[Global_i] += RHS_Contribution[i]; omp_unset_lock(&lock_array[Global_i]); } } } #endif /// Add terms from an elemental matrix to system matrices (LHS only) void AssembleLHS( LocalSystemMatrixType& LHS_Contribution, Element::EquationIdVectorType& EquationId) { TSystemMatrixType& rS = *mpS; TSystemMatrixType& rD = *mpD; TSystemMatrixType& rG = *mpG; TSystemMatrixType& rL = *mpL; unsigned int ContributionSize = EquationId.size(); for( unsigned int i = 0; i < ContributionSize; i++) { unsigned int Global_i = EquationId[i]; if ( Global_i < mVelFreeDofs ) { for( unsigned int j = 0; j < ContributionSize; j++) { unsigned int Global_j = EquationId[j]; if( Global_j < mVelFreeDofs) { rS(Global_i,Global_j) += LHS_Contribution(i,j); } else if( Global_j < BaseType::mEquationSystemSize) { rG(Global_i,Global_j - mVelFreeDofs) += LHS_Contribution(i,j); } } } else if( Global_i < BaseType::mEquationSystemSize ) { for( unsigned int j = 0; j < ContributionSize; j++) { unsigned int Global_j = EquationId[j]; if( Global_j < mVelFreeDofs) { rD(Global_i - mVelFreeDofs, Global_j) += LHS_Contribution(i,j); } else if( Global_j < BaseType::mEquationSystemSize) { rL(Global_i - mVelFreeDofs, Global_j - mVelFreeDofs) += LHS_Contribution(i,j); } } } } } void AssembleLHS_CompleteOnFreeRows( LocalSystemMatrixType& LHS_Contribution, Element::EquationIdVectorType& EquationId) { unsigned int ContributionSize = EquationId.size(); for( unsigned int i = 0; i < ContributionSize; i++) { unsigned int Global_i = EquationId[i]; if ( Global_i < mVelFreeDofs ) { for( unsigned int j = 0; j < ContributionSize; j++) { unsigned int Global_j = EquationId[j]; if( Global_j < mVelFreeDofs) { mpS->operator()(Global_i,Global_j) += LHS_Contribution(i,j); } else { mpG->operator()(Global_i,Global_j - mVelFreeDofs) += LHS_Contribution(i,j); } } } else if( Global_i < BaseType::mEquationSystemSize ) { for( unsigned int j = 0; j < ContributionSize; j++) { unsigned int Global_j = EquationId[j]; if( Global_j < mVelFreeDofs) { mpD->operator()(Global_i - mVelFreeDofs, Global_j) += LHS_Contribution(i,j); } else { mpL->operator()(Global_i - mVelFreeDofs, Global_j - mVelFreeDofs) += LHS_Contribution(i,j); } } } } } /// Asseble local contribution to the right hand side vector /** * Asseble local contribution to the right hand side vector * * @param b Reference to RHS vector * @param RHS_Contribution local RHS contibution * @param EquationId Global ids of the local contribution */ void AssembleRHS( TSystemVectorType& b, LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId) { unsigned int ContributionSize = EquationId.size(); for (unsigned int i = 0; i < ContributionSize; i++) { unsigned int Global_i = EquationId[i]; if ( Global_i < BaseType::mEquationSystemSize ) { #pragma omp atomic b[Global_i] += RHS_Contribution[i]; } else if (BaseType::mCalculateReactionsFlag) // == true { #pragma omp atomic BaseType::mpReactionsVector->operator[](Global_i - BaseType::mEquationSystemSize) -= RHS_Contribution[i]; } } } /** * Pressure System matrix functions * Compute L - D*Inv(Diag(S))*G */ #ifndef _OPENMP void AllocateSystemMatrix(TSystemMatrixType& A) { /* All non-zero positions in A = L - D*Inv(Diag(S))*G have to be stored. * This method allocates the required memory based on the shapes of * member matrices mpD (Divergence operator), mpG (Gradient Operator) * and mpL (stabilization term) */ TSystemMatrixType& rG = *mpG; TSystemMatrixType& rD = *mpD; TSystemMatrixType& rL = *mpL; std::size_t NumTerms = 0; std::vector<int> mask(rL.size2(),-1); // Keeps track of used cols in a given row. // When a col is used, mask[col] is filled with row num. for( OuterIt RowD = rD.begin1(), RowL = rL.begin1() ; RowD != rD.end1(); RowD++, RowL++) { // Find terms filled by the matrix product for( InnerIt ItD = RowD.begin(); ItD != RowD.end() ; ItD++ ) { RowType RowG(rG,ItD.index2()); for( typename RowType::iterator ItG = RowG.begin(); ItG != RowG.end(); ItG++ ) { if( mask[ItG.index()] != int (ItD.index1()) ) // Cast to int to avoid a compilation warning, as index1() returns an unsigned int { mask[ItG.index()] = ItD.index1(); NumTerms++; } } } // Find extra terms introduced by matrix difference for( InnerIt ItL = RowL.begin(); ItL != RowL.end(); ItL++ ) { if( mask[ItL.index2()] != int (ItL.index1()) ) // Cast to int to avoid a compilation warning, as index1() returns an unsigned int { mask[ItL.index2()] = ItL.index1(); NumTerms++; } } } A.reserve(NumTerms); } #else // we can't allocate in parallel!! void AllocateSystemMatrix(TSystemMatrixType& A) {} #endif /// Identify non-zero tems in the system matrix void ConstructSystemMatrix( TSystemMatrixType& A) { // Retrieve matrices TSystemMatrixType& rG = *mpG; TSystemMatrixType& rD = *mpD; TSystemMatrixType& rL = *mpL; PartitionVector Partition; int NumThreads = OpenMPUtils::GetNumThreads(); OpenMPUtils::DivideInPartitions(A.size1(),NumThreads,Partition); for( int k = 0 ; k < NumThreads ; k++) { // This code is serial, the pragma is here to ensure that each // row block is assigned to the processor that will fill it #pragma omp parallel if( OpenMPUtils::ThisThread() == k) { IndexVector Next = IndexVector(mPressFreeDofs); //IndexVector& Next = *pNext; // Keeps track of which columns were filled for(unsigned int m = 0; m < mPressFreeDofs; m++) Next[m] = -1; std::size_t NumTerms = 0; // Full positions in a row std::vector<unsigned int> UsedCols = std::vector<unsigned int>(); //std::vector<unsigned int>& UsedCols = *pUsedCols; UsedCols.reserve(mPressFreeDofs); for( int RowIndex = Partition[k] ; RowIndex != Partition[k+1] ; RowIndex++ ) { RowType RowD(rD,RowIndex); RowType RowL(rL,RowIndex); int head = -2; std::size_t Length = 0; // Terms filled by L for( typename RowType::iterator ItL = RowL.begin(); ItL != RowL.end(); ItL++ ) { if( Next[ItL.index()] == -1) { Next[ItL.index()] = head; head = ItL.index(); Length++; } } // Additional terms due to D*Inv(Diag(S))*G for( typename RowType::iterator ItD = RowD.begin(); ItD != RowD.end(); ItD++ ) { RowType RowG(rG,ItD.index()); for( typename RowType::iterator ItG = RowG.begin(); ItG != RowG.end(); ItG++ ) { if( Next[ItG.index()] == -1) { Next[ItG.index()] = head; head = ItG.index(); Length++; } } } // Identify full terms for ordering for( std::size_t i = 0; i < Length; i++) { if( Next[head] != -1 ) { UsedCols.push_back(head); NumTerms++; } int temp = head; head = Next[head]; // Clear 'Next' for next iteration Next[temp] = -1; } // Sort Column indices SortCols(UsedCols,NumTerms); // Store row in matrix, clean temporary variables for( unsigned int i = 0; i < NumTerms; i++) { A.push_back(RowIndex,UsedCols[i],0); } NumTerms = 0; UsedCols.resize(0,false); } } } } /// Compute the Pressure System Matrix /** * Compute the System Matrix A = L - D*Inv(Diag(S))*G. The multiplication * is performed in random order, so each row will be stored in a temporary * variable, ordered and copied in input matrix A. */ void CalculateSystemMatrix( TSystemMatrixType& A) { // Retrieve matrices TSystemMatrixType& rS = *mpS; TSystemMatrixType& rG = *mpG; TSystemMatrixType& rD = *mpD; TSystemMatrixType& rL = *mpL; // Compute Inv(Diag(S)) TSystemVectorType& rIDiagS = *mpIDiagS; int DiagSize = int(mVelFreeDofs); // to avoid comparison between int & unsigned int #pragma omp parallel for for( int i = 0; i < DiagSize; i++) rIDiagS[i] = 1.0/rS(i,i); PartitionVector Partition; int NumThreads = OpenMPUtils::GetNumThreads(); OpenMPUtils::DivideInPartitions(A.size1(),NumThreads,Partition); #pragma omp parallel { int k = OpenMPUtils::ThisThread(); TSystemVectorPointerType pCurrentRow( new TSystemVectorType(mPressFreeDofs) ); TSystemVectorType& CurrentRow = *pCurrentRow; // Values for current row for (unsigned int i = 0; i < mPressFreeDofs; i++) CurrentRow[i] = 0.0; IndexVector Next = IndexVector(mPressFreeDofs) ; //IndexVector& Next = *pNext; // Keeps track of which columns were filled for(unsigned int m=0; m < mPressFreeDofs; m++) Next[m] = -1; std::size_t NumTerms = 0; // Full positions in a row std::vector<unsigned int> UsedCols = std::vector<unsigned int>(); //std::vector<unsigned int>& UsedCols = *pUsedCols; UsedCols.reserve(mPressFreeDofs); for( int RowIndex = Partition[k] ; RowIndex != Partition[k+1] ; RowIndex++ ) { RowType RowD(rD,RowIndex); RowType RowL(rL,RowIndex); int head = -2; std::size_t Length = 0; // Write L in A for( typename RowType::iterator ItL = RowL.begin(); ItL != RowL.end(); ItL++ ) { CurrentRow(ItL.index()) = *ItL; if( Next[ItL.index()] == -1) { Next[ItL.index()] = head; head = ItL.index(); Length++; } } // Substract D*Inv(Diag(S))*G for( typename RowType::iterator ItD = RowD.begin(); ItD != RowD.end(); ItD++ ) { RowType RowG(rG,ItD.index()); for( typename RowType::iterator ItG = RowG.begin(); ItG != RowG.end(); ItG++ ) { CurrentRow[ItG.index()] -= (*ItD) * rIDiagS[ItD.index()] * (*ItG); if( Next[ItG.index()] == -1) { Next[ItG.index()] = head; head = ItG.index(); Length++; } } } // Identify full terms for ordering for( std::size_t i = 0; i < Length; i++) { if( Next[head] != -1 ) { UsedCols.push_back(head); NumTerms++; } int temp = head; head = Next[head]; // Clear 'Next' for next iteration Next[temp] = -1; } // Sort Column indices SortCols(UsedCols,NumTerms); // Fill matrix row, then clean temporary variables. RowType RowA(A,RowIndex); std::size_t n = 0; unsigned int Col; for( typename RowType::iterator ItA = RowA.begin(); ItA != RowA.end(); ItA++) { Col = UsedCols[n++]; *ItA = CurrentRow[Col]; CurrentRow[Col] = 0; } NumTerms = 0; UsedCols.resize(0,false); } } } /// Helper function for Sytem matrix functions void SortCols( std::vector<unsigned int>& ColList, std::size_t& NumCols) { bool swap = true; unsigned int d = NumCols; int temp; while( swap || d > 1 ) { swap = false; d = (d+1)/2; for( unsigned int i=0; i<(NumCols - d); i++) if( ColList[i+d] < ColList[i] ) { temp = ColList[i+d]; ColList[i+d] = ColList[i]; ColList[i] = temp; swap = true; } } } /// allocate space for member matrices void AllocateSpace( // unsigned int AllocateSpace( // Commented version checks for empty rows in the matrix TSystemMatrixType& A, std::vector< std::vector<std::size_t> >& indices) { // unsigned int NumEmptyRows = 0; // Keeps track of empty rows for error checking (they can be a symptom of insuficient boundary conditions) int NumThreads = OpenMPUtils::GetNumThreads(); PartitionVector MatrixPartition; OpenMPUtils::DivideInPartitions(indices.size(),NumThreads,MatrixPartition); for( int k=0; k < NumThreads; k++ ) { // First touch: Make the thread that will manipulate each partition // be the one that initializes it, so the relevant variables will // belong to it. #pragma omp parallel if( OpenMPUtils::ThisThread() == k ) { for( int i = MatrixPartition[k]; i < MatrixPartition[k+1]; i++ ) { std::vector<std::size_t>& Row = indices[i]; std::sort(Row.begin(), Row.end()); for(std::vector<std::size_t>::iterator it= Row.begin(); it != Row.end() ; it++) { A.push_back(i,*it,0.00); } // if(Row.begin() == Row.end()) NumEmptyRows++; Row.clear(); } } } // return NumEmptyRows; } #ifdef _OPENMP /// y += A*x in parallel void Parallel_ProductAdd( const TSystemMatrixType& A, const TSystemVectorType& in, TSystemVectorType& out) { //create partition PartitionVector partition; int number_of_threads = OpenMPUtils::GetNumThreads(); OpenMPUtils::DivideInPartitions(A.filled1()-1,number_of_threads,partition); #pragma omp parallel { int thread_id = omp_get_thread_num(); unsigned int number_of_rows = partition[thread_id+1] - partition[thread_id]; typename compressed_matrix<TDataType>::index_array_type::const_iterator row_iter_begin = A.index1_data().begin()+partition[thread_id]; typename compressed_matrix<TDataType>::index_array_type::const_iterator index_2_begin = A.index2_data().begin()+*row_iter_begin; typename compressed_matrix<TDataType>::value_array_type::const_iterator value_begin = A.value_data().begin()+*row_iter_begin; partial_product_add(number_of_rows, row_iter_begin, index_2_begin, value_begin, in, partition[thread_id], out); } } /// calculates partial product for Parallel_ProductAdd void partial_product_add( unsigned int number_of_rows, typename compressed_matrix<TDataType>::index_array_type::const_iterator row_begin, typename compressed_matrix<TDataType>::index_array_type::const_iterator index2_begin, typename compressed_matrix<TDataType>::value_array_type::const_iterator value_begin, const TSystemVectorType& input_vec, unsigned int output_begin_index, TSystemVectorType& output_vec) { unsigned int kkk = output_begin_index; typename TSystemMatrixType::index_array_type::const_iterator row_it = row_begin; for(unsigned int k = 0; k < number_of_rows; k++) { unsigned int RowBegin = *row_it; unsigned int RowEnd = *(++row_it); TDataType t = TDataType(); for(unsigned int i = RowBegin; i < RowEnd; i++) t += *value_begin++ * ( input_vec[*index2_begin++]); output_vec[kkk++] += t; } } #endif /// Set initial iterative solver tolerance using inexact Newton criteria void SetInitialTolerance( double RHSNorm, double& TolFactor) { TolFactor = mMaxTolFactor; (BaseType::mpLinearSystemSolver)->SetTolerance(mMaxTolFactor); std::cout << "Set iterative solver tolerance to " << TolFactor << std::endl; } /// Correct iterative solver tolerance using inexact Newton criteria void UpdateTolerance( double OldRHSNorm, double NewRHSNorm, double& TolFactor) { const double MaxDecreaseFactor = 0.1; double CandidateFactor = mGamma*(NewRHSNorm*NewRHSNorm)/(OldRHSNorm*OldRHSNorm); std::cout << "Norm Ratio: " << NewRHSNorm/OldRHSNorm << std::endl; double CandidateFactor_LimitedDecrease = mGamma*TolFactor*TolFactor; if (CandidateFactor_LimitedDecrease < MaxDecreaseFactor) { TolFactor = (CandidateFactor < mMaxTolFactor) ? CandidateFactor : mMaxTolFactor; } else { double Temp = (CandidateFactor > CandidateFactor_LimitedDecrease) ? CandidateFactor : CandidateFactor_LimitedDecrease; TolFactor = (Temp < mMaxTolFactor) ? Temp : mMaxTolFactor; } if (TolFactor < mSmallTol) TolFactor = mSmallTol; (BaseType::mpLinearSystemSolver)->SetTolerance(TolFactor); std::cout << "Corrected iterative solver tolerance to " << TolFactor << std::endl; } // Total number of Dofs: BaseType::mEquationSystemSize; /// Position of 1st Free Pressure Dof unsigned int mVelFreeDofs; /// Position of 1st Fixed Pressure Dof unsigned int mVelFixedDofsEnd; unsigned int mPressFreeDofs; /// System Matrix for the momentum equation TSystemMatrixPointerType mpS; /// Discrete Divergence operator TSystemMatrixPointerType mpD; /// Discrete Gradient operator TSystemMatrixPointerType mpG; /// Stabilization term TSystemMatrixPointerType mpL; /// Inv(Diag(S)), stored as a vector TSystemVectorPointerType mpIDiagS; /// Linear solver for velocity system (pressure solver stored in base class) typename TLinearSolver::Pointer mpVelLinearSystemSolver; /// Flag for matrix reconstruction bool mDofSetChanged; /// Choice of method to ensure that velocity solution is divergence free /** Ensure that velocity is divergence free after each iteration * 0: Do not force (iteration process will eventually reach correct solution) * 1: By solving the system Diag(S)*dv = -G*dp * 2: By solving the full system S*dv = -G*dp */ unsigned int mVelocityCorrection; // Variables for inexact Newton tolerance control /// Use Inexact Newton method bool mInexactNewton; /// used to compute maximum solution tolerance in Inexact Newton double mMaxTolFactor; /// Minimum solution tolerance for inexact Newton: 0.5*NonLinearTol double mSmallTol; /// Inexact Newton parameter double mGamma; /// Keeps track of the first iteration in each step bool mFirstIteration; // double mVelTolFactor; /// Inexact Newton pressure tolerance factor double mPressTolFactor; // double mLastVelRHSNorm; /// Inexact Newton pressure tolerance factor double mLastPressRHSNorm; }; ///@} // Kratos classes ///@} group } #endif /* KRATOS_PRESSURE_SPLITTING_BUILDER_AND_SOLVER_H */
bd.c
#include <stdlib.h> #include <stdio.h> #include <unistd.h> // access #include <math.h> #include <assert.h> #include "timer.h" #include "bd.h" #include <omp.h> #define NTHREADS 24 #define M_PI 3.14159265358979323846 #define my_EPS 0.000000001 void get_indices(int index, int *i, int *j, int *k, int b){ int ib, ib2; ib = index%(b); ib2 = index%(b*b); *k = ib; *i = (index-ib2)/(b*b); *j = (ib2-*k)/b; return; } struct box { int head; }; // it is possible to use smaller boxes and more complex neighbor patterns #define NUM_BOX_NEIGHBORS 14 int box_neighbors[NUM_BOX_NEIGHBORS][3] = { {-1,-1,-1}, {-1,-1, 0}, {-1,-1,+1}, {-1, 0,-1}, {-1, 0, 0}, {-1, 0,+1}, {-1,+1,-1}, {-1,+1, 0}, {-1,+1,+1}, { 0,-1,-1}, { 0,-1, 0}, { 0,-1,+1}, { 0, 0,-1}, { 0, 0, 0} // will calculate within the box interactions }; int bd(int npos, double * restrict pos_orig, double * restrict buf, const int *types, double L, double * restrict pos, int* restrict next, double* restrict forces, double f_const) { // Initialisations required for INTERACTION FUNCTION******** NOTE: Can take input to bd itself!!! double krepul = 100, a=1, a_sq, phi=0.2, f; a_sq = a*a; int boxdim;// boxdim is number of cells in L double cutoff2; int numpairs_p; cutoff2 = 4;// cutoff < L/boxdim boxdim =(int)(L/cutoff2)*a;//(int)(L/cutoff2*0.8); printf("L = %lf cutoff2 = %lf boxdim = %d\n", L, cutoff2, boxdim); struct box b[boxdim][boxdim][boxdim]; struct box *bp; struct box *neigh_bp; // box indices int idx, idy, idz, index, box2, ib2; int neigh_idx, neigh_idy, neigh_idz; // allocate implied linked list int p1, p2, j, i; double d2, dx, dy, dz, s; box2 = boxdim*boxdim; //*****************************************END initialisations*********************************** if (boxdim < 4 || cutoff2 > (L/boxdim)*(L/boxdim)) { printf("interactions: bad input parameters\n"); // return 1; } double t0, t_init_cells = 0, t_assign_to_cells=0, t_update_pos=0, t_force=0; for (int step=0; step<INTERVAL_LEN; step++) { // Calculation of interaction per time step t0 = time_in_seconds(); // allocate memory for particles in each box // #pragma omp parallel for schedule(static) private(idx, idy, idz, ib2) shared(b, boxdim, box2) // for (index=0; index<boxdim*box2; index++){ // idz = index%(boxdim); // ib2 = index%(box2); // idx = (index-ib2)/(box2); // idy = (ib2-idz)/boxdim; // b[idx][idy][idz].head=-1; // } for (idx=0; idx<boxdim; idx++){ for (idy=0; idy<boxdim; idy++){ for (idz=0; idz<boxdim; idz++){ b[idx][idy][idz].head=-1; } } } t_init_cells += time_in_seconds()-t0; t0 = time_in_seconds(); // traverse all particles and assign to boxes #pragma omp parallel for schedule(static) private(i, idx, idy, idz, bp) shared(b, next) num_threads(NTHREADS) for (i=0; i<npos; i++) { if (pos_orig[3*i] >= 0){pos[3*i]= fmod(pos_orig[3*i], L);}// OR SINCE PARTICLES moving slowly.. change to -L else {// pos_orig[i] is negative pos[3*i] = L-fmod(-1*pos_orig[3*i], L); } if (pos_orig[3*i+1] >= 0){pos[3*i+1]= fmod(pos_orig[3*i+1], L);}// OR SINCE PARTICLES moving slowly.. change to -L else {// pos_orig[i] is negative pos[3*i+1] = L-fmod(-1*pos_orig[3*i+1], L); } if (pos_orig[3*i+2] >= 0){pos[3*i+2]= fmod(pos_orig[3*i+2], L);}// OR SINCE PARTICLES moving slowly.. change to -L else {// pos_orig[i] is negative pos[3*i+2] = L-fmod(-1*pos_orig[3*i+2], L); } if (pos[3*i]<0){printf("pos_orig = %lf pos defect = %lf and i = %d and L =%lf\n", pos_orig[3*i], pos[3*i], i, L);} // initialize entry of implied linked list next[i] = -1; forces[3*i+0] = 0; forces[3*i+1] = 0; forces[3*i+2] = 0; // re-initialising interaction forces at each time step // which box does the particle belong to? // assumes particles have positions within [0,L]^3 idx = (int)(pos[3*i ]/L*boxdim); idy = (int)(pos[3*i+1]/L*boxdim); idz = (int)(pos[3*i+2]/L*boxdim); // add to beginning of implied linked list bp = &b[idx][idy][idz]; // next[i] = bp->head; // next = previous (my notation) // #pragma omp critical // { next[i] = bp->head; // next = previous (my notation) bp->head = i; // head = latest (my notation) // } } t_assign_to_cells += time_in_seconds()-t0; t0 = time_in_seconds(); #pragma omp parallel for schedule(static) private(j, neigh_idx, neigh_idy, neigh_idz, neigh_bp, p1, p2, dx, dy, dz, d2, s, f, idx, idy, idz, ib2, bp) shared(b, box_neighbors, boxdim, L, pos, forces, krepul, a, a_sq, next, box2) num_threads(NTHREADS) for (index=0; index<boxdim*box2; index++){ idz = index%(boxdim); ib2 = index%(box2); idx = (index-ib2)/(box2); idy = (ib2-idz)/boxdim; bp = &b[idx][idy][idz]; // interactions within and other boxes #pragma omp parallel for schedule(static) private(j, neigh_idx, neigh_idy, neigh_idz, neigh_bp, p1, p2, dx, dy, dz, d2, s, f) shared(bp, b, box_neighbors, boxdim, L, pos, forces, krepul, a, a_sq, next, idx, idy, idz)// num_threads(NTHREADS) for (j=0; j<NUM_BOX_NEIGHBORS; j++) { neigh_idx = (idx + box_neighbors[j][0] + boxdim) % boxdim; neigh_idy = (idy + box_neighbors[j][1] + boxdim) % boxdim; neigh_idz = (idz + box_neighbors[j][2] + boxdim) % boxdim; neigh_bp = &b[neigh_idx][neigh_idy][neigh_idz]; // when using boxes, the minimum image computation is // known beforehand, thus we can compute position offsets // to compensate for wraparound when computing distances double xoffset = 0.; double yoffset = 0.; double zoffset = 0.; if (idx + box_neighbors[j][0] == -1) xoffset = -L; if (idy + box_neighbors[j][1] == -1) yoffset = -L; if (idz + box_neighbors[j][2] == -1) zoffset = -L; if (idx + box_neighbors[j][0] == boxdim) xoffset = L; if (idy + box_neighbors[j][1] == boxdim) yoffset = L; if (idz + box_neighbors[j][2] == boxdim) zoffset = L; // NOTE: modifying the function to update the forces p1 = neigh_bp->head; while (p1 != -1) { p2 = bp->head; while (p2 != -1) { // compute distance vector dx = pos[3*p1+0] - pos[3*p2+0] + xoffset; dy = pos[3*p1+1] - pos[3*p2+1] + yoffset; dz = pos[3*p1+2] - pos[3*p2+2] + zoffset; d2 = dx*dx+dy*dy+dz*dz+my_EPS; if ( d2<4.0*a_sq) { s = sqrt(d2); f = krepul*(2*a-s); #pragma omp atomic forces[3*p1+0] += f*dx/s; #pragma omp atomic forces[3*p1+1] += f*dy/s; #pragma omp atomic forces[3*p1+2] += f*dz/s; #pragma omp atomic forces[3*p2+0] -= f*dx/s; #pragma omp atomic forces[3*p2+1] -= f*dy/s; #pragma omp atomic forces[3*p2+2] -= f*dz/s; } p2 = next[p2]; } p1 = next[p1]; } } } t_force += time_in_seconds() - t0; t0 = time_in_seconds(); // generate random values from standard normal distribution // note: this MKL function is sequential but vectorized vdRngGaussian(VSL_RNG_METHOD_GAUSSIAN_BOXMULLER, stream, 3*npos, buf, 0., 1.); // update positions with Brownian displacements #pragma omp parallel for schedule(static) shared(pos_orig) private(i) num_threads(NTHREADS) for (int i=0; i<3*npos; i++) { pos_orig[i] += forces[i]*DELTAT+f_const*buf[i]; } t_update_pos += time_in_seconds() - t0; } printf("--------------------------------------------------------\n"); printf("Time: %f for initiating the cell head \n", t_init_cells); printf("Time: %f for assigning particles to cells \n", t_assign_to_cells); printf("Time: %f for force calculations \n", t_force); printf("Time: %f for pos update \n", t_update_pos); printf("--------------------------------------------------------\n"); return 0; }
exponential.h
#ifndef MATH_EXPONENTIAL_H #define MATH_EXPONENTIAL_H namespace math { namespace exponential { struct Phase { arma::vec wavenumbers; explicit inline Phase(const arma::uword dim) : wavenumbers(arma::zeros<arma::vec>(dim)) {} explicit inline Phase(const arma::vec & wavenumbers) : wavenumbers(wavenumbers) {} cx_double at(const arma::vec & position) const { if (position.n_elem != this->wavenumbers.n_elem) { throw Error( "Different dimension between the position and exponential term"); } return std::exp( arma::sum((this->wavenumbers * cx_double{0.0, 1.0}) % position)); } inline Phase conj() const { return Phase(arma::conj(this->wavenumbers)); } Phase operator*(const Phase & phase) const { const arma::vec new_wavenumbers = this->wavenumbers + phase.wavenumbers; return Phase(new_wavenumbers); } Phase & operator=(const Phase &) = default; }; template<typename T> struct Term { T coef; arma::Col<T> wavenumbers; template<typename U> std::common_type_t<T, U> at(const arma::Col<U> & position) const { if (position.n_elem != this->wavenumbers.n_elem) { throw Error( "Different dimension between the position and exponential term"); } return coef * std::exp(arma::sum(this->wavenumbers % position)); } explicit inline Term(const arma::uword dim, const T coef = T(0.0)) : coef(coef), wavenumbers(arma::zeros<arma::Col<T>>(dim)) {} inline Term(const T coef, const arma::Col<T> & wavenumbers) : coef(coef), wavenumbers(wavenumbers) {} inline arma::uword dim() const { return this->wavenumbers.n_elem; } inline Term<T> derivative(const arma::uword index) const { return {this->wavenumbers(index) * this->coef, this->wavenumbers}; } inline Term<T> derivative(const arma::uvec & index) const { return {arma::prod(this->wavenumbers % index) * index}; } inline Phase phase() const { return Phase(arma::imag(this->wavenumbers)); } template<typename U> Term<std::common_type_t<T, U>> operator*(const Term<U> & term) const { return {this->coef * term.coef, this->wavenumbers + term.wavenumbers}; } template<typename U> Term<std::common_type_t<T, U>> operator/(const Term<U> & term) const { return {this->coef / term.coef, this->wavenumbers - term.wavenumbers}; } Term & operator=(const Term &) = default; }; } template<typename T> struct Exponential { arma::Col<T> coefs; arma::Mat<T> wavenumbers; explicit inline Exponential(const arma::uword dim, const T coef = T(0.0)) : coefs(arma::Col<T>{coef}), wavenumbers(arma::zeros<arma::Mat<T>>(dim, 1)) {} explicit inline Exponential(const exponential::Term<T> & term) : coefs(arma::Col<T>{term.coef}), wavenumbers(arma::conv_to<arma::Mat<T>>::from(term.wavenumbers)) {} explicit inline Exponential(const arma::Col<T> & coefs, const arma::Mat<T> wavenumbers) : coefs(coefs), wavenumbers(wavenumbers) { if (coefs.n_elem != wavenumbers.n_cols) { throw Error("Different number of terms between coefs and wavenumbers"); } } template<typename U> std::common_type_t<T, U> at(const arma::Col<U> & position) const { if (position.n_elem != wavenumbers.n_rows) { throw Error("different dimension between position and exponential term"); } auto wavenumbers_with_position = arma::conv_to<arma::Mat<std::common_type_t<T, U>>>::from( this->wavenumbers); wavenumbers_with_position.each_col() %= position; return arma::sum( this->coefs % arma::exp(arma::sum(wavenumbers_with_position)).st() ); } inline exponential::Term<T> term(arma::uword index) const { if (index >= this->coefs.n_elem) { throw Error("The specified exponential term does not exist"); } return exponential::Term<T>(this->coefs(index), this->wavenumbers.col(index)); } inline arma::uword dim() const { return this->wavenumbers.n_rows; } inline Exponential<T> derivative(const arma::uword index) const { if (index >= this->dim()) { throw Error("Derivative operator out of bound"); } return Exponential<T>(this->coefs % this->wavenumbers.row(index).st(), this->wavenumbers); } template<typename U> Exponential<std::common_type_t<T, U>> operator+(const Exponential<U> & B) const { if (this->dim() != B.dim()) { throw Error("Different dimension between added exponential terms"); } const arma::Col<std::common_type_t<T, U>> new_this_coefs = arma::conv_to<arma::Col<std::common_type_t<T, U>>>::from( this->coefs); const arma::Col<std::common_type_t<T, U>> new_B_coefs = arma::conv_to<arma::Col<std::common_type_t<T, U>>>::from( B.coefs); const arma::Mat<std::common_type_t<T, U>> new_this_wavenumbers = arma::conv_to<arma::Mat<std::common_type_t<T, U>>>::from( this->wavenumbers); const arma::Mat<std::common_type_t<T, U>> new_B_wavenumbers = arma::conv_to<arma::Mat<std::common_type_t<T, U>>>::from( B.wavenumbers); return Exponential<std::common_type_t<T, U>>( arma::join_cols(new_this_coefs, new_B_coefs), arma::join_rows(new_this_wavenumbers, new_B_wavenumbers)); } template<typename U> Exponential<std::common_type_t<T, U>> operator+(const exponential::Term<U> & B) const { return *this + Exponential(B); } template<typename U> Exponential<std::common_type_t<T, U>> operator+(const U B) const { return *this + Exponential(this->dim(), std::common_type_t<T, U>(B)); } template<typename U> Exponential<std::common_type_t<T, U>> operator*(const exponential::Term<U> & B) const { if (this->dim() != B.dim()) { throw Error("Different dimension between added exponential terms"); } auto new_wavenumbers = arma::conv_to<arma::Mat<std::common_type_t<T, U>>>::from( this->wavenumbers); new_wavenumbers.each_col() += B.wavenumbers; const arma::Col<std::common_type_t<T, U>> new_coefs = this->coefs * B.coef; return Exponential<std::common_type_t<T,U>>(new_coefs, new_wavenumbers); } template<typename U> Exponential<std::common_type_t<T, U>> operator*(const Exponential<U> & B) const { Exponential <std::common_type_t<T, U>> result_0 = (*this) * B.term(0); #pragma omp parallel for for (arma::uword i = 1; i < B.coefs.n_elem; i++) { result_0 = result_0 + (*this) * B.term(i); } return result_0; } template<typename U> Exponential<std::common_type_t<T, U>> operator*(const U B) const { return {this->coefs * B, this->wavenumbers}; } template<typename U> Exponential<std::common_type_t<T, U>> operator-(const Exponential<U> & B) const { return *this + B * (-1.0); } template<typename U> Exponential<std::common_type_t<T, U>> operator-(const U B) const { return *this + (-B); } template<typename U> Exponential<std::common_type_t<T, U>> operator/(const U B) const { return *(this) * (1.0 / B); } template<typename U> Exponential<std::common_type_t<T, U>> operator/(const exponential::Term<T> & B) const { auto new_wavenumbers = arma::conv_to<arma::Mat<std::common_type_t<T, U>>>::from( this->wavenumbers); new_wavenumbers.each_col() -= B.wavenumbers; const arma::Col<std::common_type_t<T, U>> new_coefs = this->coefs / B.coef; return Exponential<std::common_type_t<T, U>>(new_coefs, new_wavenumbers); } Exponential & operator=(const Exponential &) = default; }; } #endif //MATH_EXPONENTIAL_H
GB_binop__bclr_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__bclr_uint8) // A.*B function (eWiseMult): GB (_AemultB_08__bclr_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__bclr_uint8) // A.*B function (eWiseMult): GB (_AemultB_04__bclr_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bclr_uint8) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bclr_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__bclr_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bclr_uint8) // C=scalar+B GB (_bind1st__bclr_uint8) // C=scalar+B' GB (_bind1st_tran__bclr_uint8) // C=A+scalar GB (_bind2nd__bclr_uint8) // C=A'+scalar GB (_bind2nd_tran__bclr_uint8) // C type: uint8_t // A type: uint8_t // A pattern? 0 // B type: uint8_t // B pattern? 0 // BinaryOp: cij = GB_BITCLR (aij, bij, uint8_t, 8) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint8_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint8_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_BITCLR (x, y, uint8_t, 8) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BCLR || GxB_NO_UINT8 || GxB_NO_BCLR_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__bclr_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__bclr_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bclr_uint8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint8_t uint8_t bwork = (*((uint8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bclr_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint8_t alpha_scalar ; uint8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ; beta_scalar = (*((uint8_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__bclr_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bclr_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__bclr_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bclr_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bclr_uint8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = GBX (Bx, p, false) ; Cx [p] = GB_BITCLR (x, bij, uint8_t, 8) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bclr_uint8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = GBX (Ax, p, false) ; Cx [p] = GB_BITCLR (aij, y, uint8_t, 8) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITCLR (x, aij, uint8_t, 8) ; \ } GrB_Info GB (_bind1st_tran__bclr_uint8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITCLR (aij, y, uint8_t, 8) ; \ } GrB_Info GB (_bind2nd_tran__bclr_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
util.c
#include <stdio.h> #include <stdlib.h> #include <math.h> void zero4d(int dim1, int dim2, int dim3, int dim4, double * a) { int i; #pragma omp parallel for private(i) schedule(static) for (i=0;i<(dim1*dim2*dim3*dim4);i++) a[i] = 0.0; return; } void rand4d(int dim1, int dim2, int dim3, int dim4, double * a) { printf("begin rand4d\n"); for (int i=0;i<(dim1*dim2*dim3*dim4);i++) a[i] = (double) rand()/RAND_MAX; printf(" end rand4d\n"); fflush(stdout); return; } void copy4d(int dim1, int dim2, int dim3, int dim4, double * in, double * out) { for (int i=0;i<(dim1*dim2*dim3*dim4);i++) out[i] = in[i]; return; } void init4d(int dim1, int dim2, int dim3, int dim4, double * a) { double shift1, shift2, shift3; if (dim1<100 && dim2<100 && dim3<100 && dim4<100) shift1 = 0.001; else shift1 = 0.0001; shift2 = shift1*shift1; shift3 = shift2*shift1; for (int i=0;i<dim1;i++) for (int j=0;j<dim2;j++) for (int k=0;k<dim3;k++) for (int l=0;l<dim4;l++) a[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l] = (double) (i + j*shift1 + k*shift2 + l*shift3); return; } double diff4d(int dim1, int dim2, int dim3, int dim4, double * a, double * b) { double error = 0.0; for (int i=0;i<dim1;i++) for (int j=0;j<dim2;j++) for (int k=0;k<dim3;k++) for (int l=0;l<dim4;l++) { error += fabs( a[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l] - b[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); } return error; } void print4d(int dim1, int dim2, int dim3, int dim4, double * a) { for (int i=0;i<dim1;i++) for (int j=0;j<dim2;j++) for (int k=0;k<dim3;k++) for (int l=0;l<dim4;l++) { printf("[%2d,%2d,%2d,%2d] = ",i,j,k,l); printf("%20.14lf ",a[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); printf("\n"); } return; } void print4d2(int dim1, int dim2, int dim3, int dim4, double * a, double * b) { for (int i=0;i<dim1;i++) for (int j=0;j<dim2;j++) for (int k=0;k<dim3;k++) for (int l=0;l<dim4;l++) { printf("[%2d,%2d,%2d,%2d] = ",i,j,k,l); printf("%20.14lf ",a[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); printf("%20.14lf ",b[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); printf("\n"); } return; } void print4d3(int dim1, int dim2, int dim3, int dim4, double * a, double * b, double * c) { for (int i=0;i<dim1;i++) for (int j=0;j<dim2;j++) for (int k=0;k<dim3;k++) for (int l=0;l<dim4;l++) { printf("[%2d,%2d,%2d,%2d] = ",i,j,k,l); printf("%20.14lf ",a[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); printf("%20.14lf ",b[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); printf("%20.14lf ",c[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); printf("\n"); } return; }
8850.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4096x4096. */ #include "convolution-2d.h" /* Array initialization. */ static void init_array (int ni, int nj, DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj)) { // printf("Initializing Array\n"); int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nj; j++) { A[i][j] = ((DATA_TYPE) (i + j) / nj); } } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, int nj, DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nj; j++) { fprintf(stderr, DATA_PRINTF_MODIFIER, B[i][j]); if ((i * NJ + j) % 20 == 0) fprintf(stderr, "\n"); } fprintf(stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_conv2d(int ni, int nj, DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj), DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj)) { int i, j; #pragma scop #pragma omp target teams distribute parallel for private(j) for (i = 1; i < _PB_NI - 1; ++i) { #pragma omp target teams distribute for (j = 1; j < _PB_NJ - 1; ++j) { B[i][j] = 0.2 * A[i-1][j-1] + 0.5 * A[i-1][j] + -0.8 * A[i-1][j+1] + -0.3 * A[ i ][j-1] + 0.6 * A[ i ][j] + -0.9 * A[ i ][j+1] + 0.4 * A[i+1][j-1] + 0.7 * A[i+1][j] + 0.1 * A[i+1][j+1]; } } #pragma endscop // printf("Kernal computation complete !!\n"); } int main(int argc, char** argv) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; /* Variable declaration/allocation. */ POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NJ, ni, nj); POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NI, NJ, ni, nj); /* Initialize array(s). */ init_array (ni, nj, POLYBENCH_ARRAY(A)); /* Start timer. */ //polybench_start_instruments; polybench_timer_start(); /* Run kernel. */ kernel_conv2d (ni, nj, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B)); /* Stop and print timer. */ polybench_timer_stop(); polybench_timer_print(); //polybench_stop_instruments; //polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(ni, nj, POLYBENCH_ARRAY(B))); /* Be clean. */ POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(B); return 0; }
subopt.c
/* * suboptimal folding - Stefan Wuchty, Walter Fontana & Ivo Hofacker * * Vienna RNA package */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <ctype.h> #include <string.h> #include <math.h> #include "ViennaRNA/fold.h" #include "ViennaRNA/constraints/hard.h" #include "ViennaRNA/constraints/soft.h" #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/utils/strings.h" #include "ViennaRNA/params/default.h" #include "ViennaRNA/fold_vars.h" #include "ViennaRNA/datastructures/lists.h" #include "ViennaRNA/eval.h" #include "ViennaRNA/params/basic.h" #include "ViennaRNA/loops/all.h" #include "ViennaRNA/cofold.h" #include "ViennaRNA/gquad.h" #include "ViennaRNA/alphabet.h" #include "ViennaRNA/subopt.h" #include "ViennaRNA/loops/external_hc.inc" #include "ViennaRNA/loops/hairpin_hc.inc" #include "ViennaRNA/loops/internal_hc.inc" #include "ViennaRNA/loops/multibranch_hc.inc" #include "ViennaRNA/loops/external_sc.inc" #include "ViennaRNA/loops/hairpin_sc.inc" #include "ViennaRNA/loops/internal_sc.inc" #include "ViennaRNA/loops/multibranch_sc.inc" /* hack */ #include "ViennaRNA/color_output.inc" #ifdef _OPENMP #include <omp.h> #endif #ifdef __GNUC__ # define INLINE inline #else # define INLINE #endif #define true 1 #define false 0 typedef struct { struct hc_ext_def_dat hc_dat_ext; vrna_callback_hc_evaluate *hc_eval_ext; struct hc_hp_def_dat hc_dat_hp; vrna_callback_hc_evaluate *hc_eval_hp; struct hc_int_def_dat hc_dat_int; eval_hc *hc_eval_int; struct hc_mb_def_dat hc_dat_mb; vrna_callback_hc_evaluate *hc_eval_mb; struct sc_f5_dat sc_dat_ext; struct sc_hp_dat sc_dat_hp; struct sc_int_dat sc_dat_int; struct sc_mb_dat sc_dat_mb; } constraint_helpers; /** * @brief Sequence interval stack element used in subopt.c */ typedef struct INTERVAL { int i; int j; int array_flag; } INTERVAL; typedef struct { char *structure; LIST *Intervals; int partial_energy; int is_duplex; /* int best_energy; */ /* best attainable energy */ } STATE; typedef struct { LIST *Intervals; LIST *Stack; int nopush; } subopt_env; struct old_subopt_dat { unsigned long max_sol; unsigned long n_sol; vrna_subopt_solution_t *SolutionList; FILE *fp; int cp; }; /* ################################# # GLOBAL VARIABLES # ################################# */ PUBLIC int subopt_sorted = 0; /* output sorted by energy */ PUBLIC int density_of_states[MAXDOS + 1]; PUBLIC double print_energy = 9999; /* printing threshold for use with logML */ /* ################################# # PRIVATE VARIABLES # ################################# */ /* some backward compatibility stuff */ PRIVATE int backward_compat = 0; PRIVATE vrna_fold_compound_t *backward_compat_compound = NULL; #ifdef _OPENMP #pragma omp threadprivate(backward_compat_compound, backward_compat) #endif /* ################################# # PRIVATE FUNCTION DECLARATIONS # ################################# */ PRIVATE void init_constraint_helpers(vrna_fold_compound_t *fc, constraint_helpers *d); PRIVATE void free_constraint_helpers(constraint_helpers *d); #ifndef VRNA_DISABLE_BACKWARD_COMPATIBILITY PRIVATE vrna_subopt_solution_t * wrap_subopt(char *seq, char *structure, vrna_param_t *parameters, int delta, int is_constrained, int is_circular, FILE *fp); #endif PRIVATE void make_pair(int i, int j, STATE *state); /* mark a gquadruplex in the resulting dot-bracket structure */ PRIVATE void make_gquad(int i, int L, int l[3], STATE *state); PRIVATE INTERVAL * make_interval(int i, int j, int ml); PRIVATE STATE * make_state(LIST *Intervals, char *structure, int partial_energy, int is_duplex, int length); PRIVATE STATE * copy_state(STATE *state); PRIVATE void print_state(STATE *state); PRIVATE void UNUSED print_stack(LIST *list); PRIVATE LIST * make_list(void); PRIVATE void push(LIST *list, void *data); PRIVATE void * pop(LIST *list); PRIVATE int best_attainable_energy(vrna_fold_compound_t *fc, STATE *state); PRIVATE void scan_interval(vrna_fold_compound_t *fc, int i, int j, int array_flag, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat); PRIVATE INLINE void scan_mb(vrna_fold_compound_t *fc, int i, int j, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat); PRIVATE INLINE void scan_m1(vrna_fold_compound_t *fc, int i, int j, int array_flag, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat); PRIVATE INLINE void scan_pair(vrna_fold_compound_t *fc, int i, int j, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat); PRIVATE INLINE void scan_ext(vrna_fold_compound_t *fc, int i, int j, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat); PRIVATE INLINE void scan_circular(vrna_fold_compound_t *fc, int i, int j, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat); PRIVATE INLINE void scan_fms5(vrna_fold_compound_t *fc, unsigned int i, unsigned int strand, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat); PRIVATE INLINE void scan_fms3(vrna_fold_compound_t *fc, unsigned int i, unsigned int strand, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat); PRIVATE INLINE void scan_gquad(vrna_fold_compound_t *fc, int i, int j, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat); PRIVATE void free_interval_node(INTERVAL *node); PRIVATE void free_state_node(STATE *node); PRIVATE void push_back(LIST *Stack, STATE *state); PRIVATE char * get_structure(STATE *state); PRIVATE int compare(const void *a, const void *b); PRIVATE int compare_en(const void *a, const void *b); PRIVATE void make_output(vrna_subopt_solution_t *SL, int cp, FILE *fp); PRIVATE void repeat(vrna_fold_compound_t *fc, int i, int j, STATE *state, int part_energy, int temp_energy, int best_energy, int threshold, subopt_env *env, constraint_helpers *constraints_dat); PRIVATE void repeat_gquad(vrna_fold_compound_t *fc, int i, int j, STATE *state, int part_energy, int temp_energy, int best_energy, int threshold, subopt_env *env, constraint_helpers *constraints_dat); PRIVATE void old_subopt_print(const char *structure, float energy, void *data); PRIVATE void old_subopt_store(const char *structure, float energy, void *data); PRIVATE void old_subopt_store_compressed(const char *structure, float energy, void *data); /* ################################# # BEGIN OF FUNCTION DEFINITIONS # ################################# */ PUBLIC vrna_subopt_solution_t * vrna_subopt(vrna_fold_compound_t *fc, int delta, int sorted, FILE *fp) { struct old_subopt_dat data; vrna_subopt_callback *cb; data.SolutionList = NULL; data.max_sol = 128; data.n_sol = 0; data.fp = fp; data.cp = fc->cutpoint; if (fc) { /* SolutionList stores the suboptimal structures found */ data.SolutionList = (vrna_subopt_solution_t *)vrna_alloc(data.max_sol * sizeof(vrna_subopt_solution_t)); /* end initialize ------------------------------------------------------- */ if (fp) { float min_en; char *SeQ, *energies = NULL; min_en = vrna_mfe(fc, NULL); SeQ = vrna_cut_point_insert(fc->sequence, fc->cutpoint); energies = vrna_strdup_printf(" %6.2f %6.2f", min_en, (float)delta / 100.); print_structure(fp, SeQ, energies); free(SeQ); free(energies); vrna_mx_mfe_free(fc); } cb = old_subopt_store; if (fp) cb = (sorted) ? old_subopt_store_compressed : old_subopt_print; /* call subopt() */ vrna_subopt_cb(fc, delta, cb, (void *)&data); if (sorted) { /* sort structures by energy */ if (data.n_sol > 0) { int (*compare_fun)(const void *a, const void *b); switch (sorted) { case VRNA_SORT_BY_ENERGY_ASC: compare_fun = compare_en; break; default: /* a.k.a. VRNA_SORT_BY_ENERGY_LEXICOGRAPHIC_ASC */ compare_fun = compare; break; } qsort(data.SolutionList, data.n_sol - 1, sizeof(vrna_subopt_solution_t), compare_fun); } if (fp) make_output(data.SolutionList, fc->cutpoint, fp); } if (fp) { /* we've printed everything -- free solutions */ vrna_subopt_solution_t *sol; for (sol = data.SolutionList; sol->structure != NULL; sol++) free(sol->structure); free(data.SolutionList); data.SolutionList = NULL; } } return data.SolutionList; } PUBLIC void vrna_subopt_cb(vrna_fold_compound_t *fc, int delta, vrna_subopt_callback *cb, void *data) { subopt_env *env; STATE *state; INTERVAL *interval; unsigned int *so, *ss; int maxlevel, count, partial_energy, old_dangles, logML, dangle_model, length, circular, threshold; double structure_energy, min_en, eprint; char *struc, *structure; float correction; vrna_param_t *P; vrna_md_t *md; int minimal_energy; int Fc; int *f5; constraint_helpers constraints_dat; vrna_fold_compound_prepare(fc, VRNA_OPTION_MFE); length = fc->length; so = fc->strand_order; ss = fc->strand_start; P = fc->params; md = &(P->model_details); /* * do mfe folding to get fill arrays and get ground state energy * in case dangles is neither 0 or 2, set dangles=2 while folding */ circular = md->circ; logML = md->logML; old_dangles = dangle_model = md->dangles; if (md->uniq_ML != 1) /* failsafe mechanism to enforce valid fM1 array */ md->uniq_ML = 1; /* temporarily set dangles to 2 if necessary */ if ((md->dangles != 0) && (md->dangles != 2)) md->dangles = 2; struc = (char *)vrna_alloc(sizeof(char) * (length + 1)); min_en = vrna_mfe(fc, struc); /* restore dangle model */ md->dangles = old_dangles; /* re-evaluate in case we're using logML etc */ min_en = vrna_eval_structure(fc, struc); f5 = fc->matrices->f5; Fc = fc->matrices->Fc; free(struc); eprint = print_energy + min_en; correction = (min_en < 0) ? -0.1 : 0.1; /* Initialize ------------------------------------------------------------ */ init_constraint_helpers(fc, &constraints_dat); maxlevel = 0; count = 0; partial_energy = 0; /* Initialize the stack ------------------------------------------------- */ minimal_energy = (circular) ? Fc : f5[length]; threshold = minimal_energy + delta; if (threshold >= INF) { vrna_message_warning("Energy range too high, limiting to reasonable value"); threshold = INF - EMAX; } /* init env data structure */ env = (subopt_env *)vrna_alloc(sizeof(subopt_env)); env->Stack = NULL; env->nopush = true; env->Stack = make_list(); /* anchor */ env->Intervals = make_list(); /* initial state: */ interval = make_interval(1, length, 0); /* interval [1,length,0] */ push(env->Intervals, interval); env->nopush = false; state = make_state(env->Intervals, NULL, partial_energy, 0, length); /* state->best_energy = minimal_energy; */ push(env->Stack, state); env->nopush = false; /* end initialize ------------------------------------------------------- */ while (1) { /* forever, til nothing remains on stack */ maxlevel = (env->Stack->count > maxlevel ? env->Stack->count : maxlevel); if (LST_EMPTY(env->Stack)) { /* * we are done! clean up and quit * fprintf(stderr, "maxlevel: %d\n", maxlevel); */ lst_kill(env->Stack, free_state_node); cb(NULL, 0, data); /* NULL (last time to call callback function */ break; } /* pop the last element ---------------------------------------------- */ state = pop(env->Stack); /* current state to work with */ if (LST_EMPTY(state->Intervals)) { int e; /* state has no intervals left: we got a solution */ count++; structure = get_structure(state); structure_energy = state->partial_energy / 100.; #ifdef CHECK_ENERGY structure_energy = vrna_eval_structure(fc, structure); if (!logML) { if ((double)(state->partial_energy / 100.) != structure_energy) { vrna_message_error("%s %6.2f %6.2f", structure, state->partial_energy / 100., structure_energy); exit(1); } } #endif if (logML || (dangle_model == 1) || (dangle_model == 3)) /* recalc energy */ structure_energy = vrna_eval_structure(fc, structure); e = (int)((structure_energy - min_en) * 10. - correction); /* avoid rounding errors */ if (e > MAXDOS) e = MAXDOS; density_of_states[e]++; if (structure_energy <= eprint) { char *outstruct = vrna_cut_point_insert(structure, (fc->strands > 1) ? ss[so[1]] : -1); cb((const char *)outstruct, structure_energy, data); free(outstruct); } free(structure); } else { /* get (and remove) next interval of state to analyze */ interval = pop(state->Intervals); scan_interval(fc, interval->i, interval->j, interval->array_flag, threshold, state, env, &constraints_dat); free_interval_node(interval); /* free the current interval */ } free_state_node(state); /* free the current state */ } /* end of while (1) */ /* cleanup memory */ free_constraint_helpers(&constraints_dat); free(env); } /* ##################################### # BEGIN OF STATIC HELPER FUNCTIONS # ##################################### */ PRIVATE void init_constraint_helpers(vrna_fold_compound_t *fc, constraint_helpers *d) { /* hard constraints first */ d->hc_eval_ext = prepare_hc_ext_def(fc, &(d->hc_dat_ext)); d->hc_eval_hp = prepare_hc_hp_def(fc, &(d->hc_dat_hp)); d->hc_eval_int = prepare_hc_int_def(fc, &(d->hc_dat_int)); d->hc_eval_mb = prepare_hc_mb_def(fc, &(d->hc_dat_mb)); init_sc_f5(fc, &(d->sc_dat_ext)); init_sc_hp(fc, &(d->sc_dat_hp)); init_sc_int(fc, &(d->sc_dat_int)); init_sc_mb(fc, &(d->sc_dat_mb)); } PRIVATE void free_constraint_helpers(constraint_helpers *d) { /* currently only required for comparative folding soft constraints, but here for consistency reasons */ free_sc_f5(&(d->sc_dat_ext)); free_sc_hp(&(d->sc_dat_hp)); free_sc_int(&(d->sc_dat_int)); free_sc_mb(&(d->sc_dat_mb)); } /* * --------------------------------------------------------------------------- * List routines-------------------------------------------------------------- *--------------------------------------------------------------------------- */ PRIVATE void make_pair(int i, int j, STATE *state) { state->structure[i - 1] = '('; state->structure[j - 1] = ')'; } PRIVATE void make_gquad(int i, int L, int l[3], STATE *state) { int x; for (x = 0; x < L; x++) { state->structure[i - 1 + x] = '+'; state->structure[i - 1 + x + L + l[0]] = '+'; state->structure[i - 1 + x + 2 * L + l[0] + l[1]] = '+'; state->structure[i - 1 + x + 3 * L + l[0] + l[1] + l[2]] = '+'; } } PRIVATE INTERVAL * make_interval(int i, int j, int array_flag) { INTERVAL *interval; interval = lst_newnode(sizeof(INTERVAL)); interval->i = i; interval->j = j; interval->array_flag = array_flag; return interval; } PRIVATE void free_interval_node(INTERVAL *node) { lst_freenode(node); } PRIVATE void free_state_node(STATE *node) { free(node->structure); if (node->Intervals) lst_kill(node->Intervals, lst_freenode); lst_freenode(node); } PRIVATE STATE * make_state(LIST *Intervals, char *structure, int partial_energy, int is_duplex, int length) { STATE *state; state = lst_newnode(sizeof(STATE)); if (Intervals) state->Intervals = Intervals; else state->Intervals = lst_init(); if (structure) { state->structure = structure; } else { int i; state->structure = (char *)vrna_alloc(length + 1); for (i = 0; i < length; i++) state->structure[i] = '.'; } state->partial_energy = partial_energy; return state; } PRIVATE STATE * copy_state(STATE *state) { STATE *new_state; void *after; INTERVAL *new_interval, *next; new_state = lst_newnode(sizeof(STATE)); new_state->Intervals = lst_init(); new_state->partial_energy = state->partial_energy; /* new_state->best_energy = state->best_energy; */ if (state->Intervals->count) { after = LST_HEAD(new_state->Intervals); for (next = lst_first(state->Intervals); next; next = lst_next(next)) { new_interval = lst_newnode(sizeof(INTERVAL)); *new_interval = *next; lst_insertafter(new_state->Intervals, new_interval, after); after = new_interval; } } new_state->structure = strdup(state->structure); if (!new_state->structure) vrna_message_error("out of memory"); return new_state; } /*@unused @*/ PRIVATE void print_state(STATE *state) { INTERVAL *next; if (state->Intervals->count) { printf("%d intervals:\n", state->Intervals->count); for (next = lst_first(state->Intervals); next; next = lst_next(next)) printf("[%d,%d],%d ", next->i, next->j, next->array_flag); printf("\n"); } printf("partial structure: %s\n", state->structure); printf("\n"); printf(" partial_energy: %d\n", state->partial_energy); /* printf(" best_energy: %d\n", state->best_energy); */ (void)fflush(stdout); } /*@unused @*/ PRIVATE void print_stack(LIST *list) { void *rec; printf("================\n"); printf("%d states\n", list->count); for (rec = lst_first(list); rec; rec = lst_next(rec)) { printf("state-----------\n"); print_state(rec); } printf("================\n"); } PRIVATE LIST * make_list(void) { return lst_init(); } PRIVATE void push(LIST *list, void *data) { lst_insertafter(list, data, LST_HEAD(list)); } /* * PRIVATE void * push_stack(STATE *state) { */ /* keep the stack sorted by energy * STATE *after, *next; * nopush = false; * next = after = LST_HEAD(Stack); * while ( next = lst_next(next)) { * if ( next->best_energy >= state->best_energy ) break; * after = next; * } * lst_insertafter(Stack, state, after); * } */ PRIVATE void * pop(LIST *list) { void *data; data = lst_deletenext(list, LST_HEAD(list)); return data; } /* * --------------------------------------------------------------------------- * auxiliary routines--------------------------------------------------------- *--------------------------------------------------------------------------- */ PRIVATE int best_attainable_energy(vrna_fold_compound_t *fc, STATE *state) { /* evaluation of best possible energy attainable within remaining intervals */ register int sum; INTERVAL *next; vrna_md_t *md; vrna_mx_mfe_t *matrices; int *indx; md = &(fc->params->model_details); matrices = fc->matrices; indx = fc->jindx; sum = state->partial_energy; /* energy of already found elements */ for (next = lst_first(state->Intervals); next; next = lst_next(next)) { if (next->array_flag == 0) sum += (md->circ) ? matrices->Fc : matrices->f5[next->j]; else if (next->array_flag == 1) sum += matrices->fML[indx[next->j] + next->i]; else if (next->array_flag == 2) sum += matrices->c[indx[next->j] + next->i]; else if (next->array_flag == 3) sum += matrices->fM1[indx[next->j] + next->i]; else if (next->array_flag == 4) sum += matrices->fms5[next->j][next->i]; else if (next->array_flag == 5) sum += matrices->fms3[next->j][next->i]; else if (next->array_flag == 6) sum += matrices->ggg[indx[next->j] + next->i]; } return sum; } PRIVATE void push_back(LIST *Stack, STATE *state) { push(Stack, copy_state(state)); return; } PRIVATE char * get_structure(STATE *state) { char *structure; structure = strdup(state->structure); return structure; } PRIVATE int compare(const void *a, const void *b) { if (((vrna_subopt_solution_t *)a)->energy > ((vrna_subopt_solution_t *)b)->energy) return 1; if (((vrna_subopt_solution_t *)a)->energy < ((vrna_subopt_solution_t *)b)->energy) return -1; return strcmp(((vrna_subopt_solution_t *)a)->structure, ((vrna_subopt_solution_t *)b)->structure); } PRIVATE int compare_en(const void *a, const void *b) { if (((vrna_subopt_solution_t *)a)->energy > ((vrna_subopt_solution_t *)b)->energy) return 1; if (((vrna_subopt_solution_t *)a)->energy < ((vrna_subopt_solution_t *)b)->energy) return -1; return 0; } PRIVATE void make_output(vrna_subopt_solution_t *SL, int cp, FILE *fp) /* prints stuff */ { vrna_subopt_solution_t *sol; for (sol = SL; sol->structure != NULL; sol++) { char *e_string = vrna_strdup_printf(" %6.2f", sol->energy); char *ss = vrna_db_unpack(sol->structure); char *s = vrna_cut_point_insert(ss, cp); print_structure(fp, s, e_string); free(s); free(ss); free(e_string); } } PRIVATE STATE * derive_new_state(int i, int j, STATE *s, int e, int flag) { STATE *s_new = copy_state(s); INTERVAL *ival = make_interval(i, j, flag); push(s_new->Intervals, ival); s_new->partial_energy += e; return s_new; } PRIVATE void fork_state(int i, int j, STATE *s, int e, int flag, subopt_env *env) { STATE *s_new = derive_new_state(i, j, s, e, flag); push(env->Stack, s_new); env->nopush = false; } PRIVATE void fork_int_state(int i, int j, int p, int q, STATE *s, int e, subopt_env *env) { STATE *s_new = derive_new_state(p, q, s, e, 2); make_pair(i, j, s_new); make_pair(p, q, s_new); push(env->Stack, s_new); env->nopush = false; } PRIVATE void fork_state_pair(int i, int j, STATE *s, int e, subopt_env *env) { STATE *new_state; new_state = copy_state(s); make_pair(i, j, new_state); new_state->partial_energy += e; push(env->Stack, new_state); env->nopush = false; } PRIVATE void fork_two_states_pair(int i, int j, int k, STATE *s, int e, int flag1, int flag2, subopt_env *env) { INTERVAL *interval1, *interval2; STATE *new_state; new_state = copy_state(s); interval1 = make_interval(i + 1, k - 1, flag1); interval2 = make_interval(k, j - 1, flag2); if (k - i < j - k) { /* push larger interval first */ push(new_state->Intervals, interval1); push(new_state->Intervals, interval2); } else { push(new_state->Intervals, interval2); push(new_state->Intervals, interval1); } make_pair(i, j, new_state); new_state->partial_energy += e; push(env->Stack, new_state); env->nopush = false; } PRIVATE void fork_state_pair_interval(int i, int j, int k, int l, STATE *s, int e, int flag, subopt_env *env) { INTERVAL *interval; STATE *new_state; new_state = copy_state(s); interval = make_interval(k, l, flag); push(new_state->Intervals, interval); make_pair(i, j, new_state); new_state->partial_energy += e; push(env->Stack, new_state); env->nopush = false; } PRIVATE void fork_two_states_pair_ms(int i, int j, int sn1, int sn2, STATE *s, int e, subopt_env *env) { INTERVAL *interval1, *interval2; STATE *new_state; new_state = copy_state(s); interval1 = make_interval(i + 1, sn1, 4); interval2 = make_interval(j - 1, sn2, 5); push(new_state->Intervals, interval1); push(new_state->Intervals, interval2); make_pair(i, j, new_state); new_state->partial_energy += e; push(env->Stack, new_state); env->nopush = false; } PRIVATE void fork_two_states(int i, int j, int p, int q, STATE *s, int e, int flag1, int flag2, subopt_env *env) { INTERVAL *interval1, *interval2; STATE *new_state; new_state = copy_state(s); interval1 = make_interval(i, j, flag1); interval2 = make_interval(p, q, flag2); if ((j - i) < (q - p)) { push(new_state->Intervals, interval1); push(new_state->Intervals, interval2); } else { push(new_state->Intervals, interval2); push(new_state->Intervals, interval1); } new_state->partial_energy += e; push(env->Stack, new_state); env->nopush = false; } PRIVATE void scan_interval(vrna_fold_compound_t *fc, int i, int j, int array_flag, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat) { /* real backtrack routine */ /* * array_flag = 0: trace back in f5-array * array_flag = 1: trace back in fML-array * array_flag = 2: trace back in repeat() * array_flag = 3: trace back in fM1-array */ env->nopush = true; switch (array_flag) { case 0: scan_ext(fc, i, j, threshold, state, env, constraints_dat); break; case 1: scan_mb(fc, i, j, threshold, state, env, constraints_dat); /* fall through */ case 3: scan_m1(fc, i, j, array_flag, threshold, state, env, constraints_dat); break; case 2: scan_pair(fc, i, j, threshold, state, env, constraints_dat); return; case 4: scan_fms5(fc, i, j, threshold, state, env, constraints_dat); break; case 5: scan_fms3(fc, i, j, threshold, state, env, constraints_dat); break; case 6: scan_gquad(fc, i, j, threshold, state, env, constraints_dat); return; } if (env->nopush) { push_back(env->Stack, state); env->nopush = false; } } PRIVATE INLINE void scan_mb(vrna_fold_compound_t *fc, int i, int j, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat) { char *ptype; short *S1, s5, s3; unsigned int *sn, *so; int k, type, dangle_model, element_energy, best_energy, *c, *fML, *ggg, *indx, with_gquad, turn, stopp, k1j; vrna_param_t *P; vrna_md_t *md; struct hc_mb_def_dat *hc_dat; vrna_callback_hc_evaluate *evaluate; struct sc_mb_dat *sc_dat; sc_mb_red_cb *sc_red_stem; sc_mb_red_cb *sc_decomp_ml; STATE *temp_state; sn = fc->strand_number; so = fc->strand_order; indx = fc->jindx; ptype = fc->ptype; S1 = fc->sequence_encoding; P = fc->params; md = &(P->model_details); dangle_model = md->dangles; with_gquad = md->gquad; turn = md->min_loop_size; c = fc->matrices->c; fML = fc->matrices->fML; ggg = fc->matrices->ggg; hc_dat = &(constraints_dat->hc_dat_mb); evaluate = constraints_dat->hc_eval_mb; sc_dat = &(constraints_dat->sc_dat_mb); sc_red_stem = constraints_dat->sc_dat_mb.red_stem; sc_decomp_ml = constraints_dat->sc_dat_mb.decomp_ml; best_energy = best_attainable_energy(fc, state); /* .. on remaining intervals */ if ((j < i + turn + 1) && (sn[i] == so[j])) { if (env->nopush) { push_back(env->Stack, state); env->nopush = false; } return; } if ((sn[i - 1] == sn[i]) && (sn[j] == sn[j + 1])) { /*backtrack in FML only if multiloop is possible*/ for (k = i + turn + 1; k <= j - 1 - turn; k++) { /* Multiloop decomposition if i,j contains more than 1 stack */ if ((with_gquad) && (sn[k] == sn[k + 1]) && (fML[indx[k] + i] != INF) && (ggg[indx[j] + k + 1] != INF)) { element_energy = E_MLstem(0, -1, -1, P); if (fML[indx[k] + i] + ggg[indx[j] + k + 1] + element_energy + best_energy <= threshold) { temp_state = derive_new_state(i, k, state, 0, 1); env->nopush = false; repeat_gquad(fc, k + 1, j, temp_state, element_energy, fML[indx[k] + i], best_energy, threshold, env, constraints_dat); free_state_node(temp_state); } } k1j = indx[j] + k + 1; if ((evaluate(i, j, k, k + 1, VRNA_DECOMP_ML_ML_STEM, hc_dat)) && (fML[indx[k] + i] != INF) && (c[k1j] != INF)) { type = vrna_get_ptype(k1j, ptype); switch (dangle_model) { case 0: s5 = s3 = -1; break; default: s5 = (sn[i - 1] == sn[i]) ? S1[k] : -1; s3 = (sn[j] == sn[j + 1]) ? S1[j + 1] : -1; break; } element_energy = E_MLstem(type, s5, s3, P); if (sc_decomp_ml) element_energy += sc_decomp_ml(i, j, k, k + 1, sc_dat); if (sc_red_stem) element_energy += sc_red_stem(k + 1, j, k + 1, j, sc_dat); if (fML[indx[k] + i] + c[k1j] + element_energy + best_energy <= threshold) { temp_state = derive_new_state(i, k, state, 0, 1); env->nopush = false; repeat(fc, k + 1, j, temp_state, element_energy, fML[indx[k] + i], best_energy, threshold, env, constraints_dat); free_state_node(temp_state); } } } } stopp = j - 1 - turn; int up = 1; for (k = i; k <= stopp; k++, up++) { k1j = indx[j] + k + 1; /* Multiloop decomposition if i,j contains only 1 stack */ if ((with_gquad) && (ggg[k1j] != INF) && (sn[i] == sn[j])) { element_energy = E_MLstem(0, -1, -1, P) + P->MLbase * up; if (sc_red_stem) element_energy += sc_red_stem(i, j, k + 1, j, sc_dat); if (ggg[k1j] + element_energy + best_energy <= threshold) { repeat_gquad(fc, k + 1, j, state, element_energy, 0, best_energy, threshold, env, constraints_dat); } } if (evaluate(i, j, k + 1, j, VRNA_DECOMP_ML_STEM, hc_dat)) { if (c[k1j] != INF) { type = vrna_get_ptype(k1j, ptype); switch (dangle_model) { case 0: s5 = s3 = -1; break; default: s5 = (sn[k - 1] == sn[k]) ? S1[k] : -1; s3 = (sn[j] == sn[j + 1]) ? S1[j + 1] : -1; break; } element_energy = E_MLstem(type, s5, s3, P); element_energy += P->MLbase * up; if (sc_red_stem) element_energy += sc_red_stem(i, j, k + 1, j, sc_dat); if (c[k1j] + element_energy + best_energy <= threshold) { repeat(fc, k + 1, j, state, element_energy, 0, best_energy, threshold, env, constraints_dat); } } } } } PRIVATE INLINE void scan_m1(vrna_fold_compound_t *fc, int i, int j, int array_flag, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat) { char *ptype; short *S1; unsigned int *sn, *so; int fi, cij, ij, type, dangle_model, element_energy, best_energy, *c, *fML, *fM1, *ggg, length, *indx, circular, with_gquad, turn; vrna_param_t *P; vrna_md_t *md; struct hc_mb_def_dat *hc_dat; vrna_callback_hc_evaluate *evaluate; struct sc_mb_dat *sc_dat; sc_mb_red_cb *sc_red_stem; sc_mb_red_cb *sc_red_ml; length = fc->length; sn = fc->strand_number; so = fc->strand_order; indx = fc->jindx; ptype = fc->ptype; S1 = fc->sequence_encoding; P = fc->params; md = &(P->model_details); dangle_model = md->dangles; circular = md->circ; with_gquad = md->gquad; turn = md->min_loop_size; c = fc->matrices->c; fML = fc->matrices->fML; fM1 = fc->matrices->fM1; ggg = fc->matrices->ggg; hc_dat = &(constraints_dat->hc_dat_mb); evaluate = constraints_dat->hc_eval_mb; sc_dat = &(constraints_dat->sc_dat_mb); sc_red_stem = constraints_dat->sc_dat_mb.red_stem; sc_red_ml = constraints_dat->sc_dat_mb.red_ml; best_energy = best_attainable_energy(fc, state); /* .. on remaining intervals */ if ((j < i + turn + 1) && (sn[i] == so[j])) { if (env->nopush) { push_back(env->Stack, state); env->nopush = false; } return; } ij = indx[j] + i; if ((evaluate(i, j, i, j - 1, VRNA_DECOMP_ML_ML, hc_dat)) && (((array_flag == 3) && (fM1[indx[j - 1] + i] != INF)) || (fML[indx[j - 1] + i] != INF))) { element_energy = P->MLbase; if (sc_red_ml) element_energy += sc_red_ml(i, j, i, j - 1, sc_dat); if (array_flag == 3) fi = element_energy + fM1[indx[j - 1] + i]; else fi = element_energy + fML[indx[j - 1] + i]; if (fi + best_energy <= threshold) fork_state(i, j - 1, state, element_energy, array_flag, env); } if (evaluate(i, j, i, j, VRNA_DECOMP_ML_STEM, hc_dat)) { /* i,j may pair */ cij = c[ij]; if (cij != INF) { type = vrna_get_ptype(ij, ptype); switch (dangle_model) { case 0: element_energy = E_MLstem(type, -1, -1, P); break; default: element_energy = E_MLstem(type, (((i > 1) && (sn[i - 1] == sn[i])) || circular) ? S1[i - 1] : -1, (((j < length) && (sn[j] == sn[j + 1])) || circular) ? S1[j + 1] : -1, P); break; } if (sc_red_stem) element_energy += sc_red_stem(i, j, i, j, sc_dat); cij += element_energy; if (cij + best_energy <= threshold) { repeat(fc, i, j, state, element_energy, 0, best_energy, threshold, env, constraints_dat); } } } else if ((with_gquad) && (ggg[ij] != INF)) { element_energy = E_MLstem(0, -1, -1, P); if (sc_red_stem) element_energy += sc_red_stem(i, j, i, j, sc_dat); if (ggg[ij] + element_energy + best_energy <= threshold) { repeat_gquad(fc, i, j, state, element_energy, 0, best_energy, threshold, env, constraints_dat); } } return; } PRIVATE INLINE void scan_pair(vrna_fold_compound_t *fc, int i, int j, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat) { unsigned int *sn, turn, noLP; int best_energy; sn = fc->strand_number; turn = fc->params->model_details.min_loop_size; noLP = fc->params->model_details.noLP; best_energy = best_attainable_energy(fc, state); /* .. on remaining intervals */ if ((j < i + turn + 1) && (sn[i] == sn[j])) { if (env->nopush) { push_back(env->Stack, state); env->nopush = false; } return; } repeat(fc, i, j, state, 0, 0, best_energy, threshold, env, constraints_dat); if (env->nopush) if (!noLP) vrna_message_warning("%d,%d\nOops, no solution in repeat!", i, j); } PRIVATE INLINE void scan_ext(vrna_fold_compound_t *fc, int i, int j, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat) { char *ptype; short *S1, s5, s3; unsigned int *sn, *so; int k, type, dangle_model, element_energy, best_energy, *f5, *c, *ggg, length, *indx, circular, with_gquad, turn, kj, tmp_en; vrna_param_t *P; vrna_md_t *md; struct hc_ext_def_dat *hc_dat; vrna_callback_hc_evaluate *evaluate; struct sc_f5_dat *sc_dat; sc_f5_cb *sc_red_ext; sc_f5_cb *sc_red_stem; sc_f5_cb *sc_decomp_stem; STATE *temp_state; length = fc->length; sn = fc->strand_number; so = fc->strand_order; indx = fc->jindx; ptype = fc->ptype; S1 = fc->sequence_encoding; P = fc->params; md = &(P->model_details); dangle_model = md->dangles; circular = md->circ; with_gquad = md->gquad; turn = md->min_loop_size; f5 = fc->matrices->f5; c = fc->matrices->c; ggg = fc->matrices->ggg; if (circular) { scan_circular(fc, i, j, threshold, state, env, constraints_dat); return; } hc_dat = &(constraints_dat->hc_dat_ext); evaluate = constraints_dat->hc_eval_ext; sc_dat = &(constraints_dat->sc_dat_ext); sc_red_ext = sc_dat->red_ext5; sc_red_stem = sc_dat->red_stem5; sc_decomp_stem = sc_dat->decomp_stem5; best_energy = best_attainable_energy(fc, state); /* .. on remaining intervals */ if (i > 1) vrna_message_error("Error while backtracking!"); if ((j < i + turn + 1) && (sn[i] == so[j])) { /* * minimal structure element * do not forget to add f5[j], since it may contain pseudo energies from soft constraining */ state->partial_energy += f5[j]; if (env->nopush) { push_back(env->Stack, state); env->nopush = false; } return; } if ((evaluate(1, j, 1, j - 1, VRNA_DECOMP_EXT_EXT, hc_dat)) && (f5[j - 1] != INF)) { tmp_en = 0; if (sc_red_ext) tmp_en += sc_red_ext(j, 1, j - 1, sc_dat); if (f5[j - 1] + tmp_en + best_energy <= threshold) /* no basepair, nibbling of 3'-end */ fork_state(i, j - 1, state, tmp_en, 0, env); } for (k = j - turn - 1; k > 1; k--) { kj = indx[j] + k; if ((with_gquad) && (sn[k - 1] == sn[j]) && (f5[k - 1] != INF) && (ggg[kj] != INF)) { element_energy = 0; if (sc_decomp_stem) element_energy += sc_decomp_stem(j, k - 1, k, sc_dat); if (f5[k - 1] + ggg[kj] + element_energy + best_energy <= threshold) { temp_state = derive_new_state(1, k - 1, state, 0, 0); env->nopush = false; /* backtrace the quadruplex */ repeat_gquad(fc, k, j, temp_state, element_energy, f5[k - 1], best_energy, threshold, env, constraints_dat); free_state_node(temp_state); } } if ((evaluate(1, j, k - 1, k, VRNA_DECOMP_EXT_EXT_STEM, hc_dat)) && (f5[k - 1] != INF) && (c[kj] != INF)) { type = vrna_get_ptype(kj, ptype); /* k and j pair */ switch (dangle_model) { case 0: s5 = s3 = -1; break; default: s5 = (sn[k - 1] == sn[k]) ? S1[k - 1] : -1; s3 = ((j < length) && (sn[j] == sn[j + 1])) ? S1[j + 1] : -1; break; } element_energy = vrna_E_ext_stem(type, s5, s3, P); if (sc_decomp_stem) element_energy += sc_decomp_stem(j, k - 1, k, sc_dat); if (f5[k - 1] + c[kj] + element_energy + best_energy <= threshold) { temp_state = derive_new_state(1, k - 1, state, 0, 0); env->nopush = false; repeat(fc, k, j, temp_state, element_energy, f5[k - 1], best_energy, threshold, env, constraints_dat); free_state_node(temp_state); } } } kj = indx[j] + 1; if ((with_gquad) && (sn[1] == sn[j]) && (ggg[kj] != INF)) { element_energy = 0; if (sc_red_stem) element_energy += sc_red_stem(j, 1, j, sc_dat); if (ggg[kj] + element_energy + best_energy <= threshold) { /* backtrace the quadruplex */ repeat_gquad(fc, 1, j, state, element_energy, 0, best_energy, threshold, env, constraints_dat); } } if ((evaluate(1, j, 1, j, VRNA_DECOMP_EXT_STEM, hc_dat)) && (c[kj] != INF)) { type = vrna_get_ptype(kj, ptype); s5 = -1; switch (dangle_model) { case 0: s3 = -1; break; default: s3 = (j < length) && (sn[j] == sn[j + 1]) ? S1[j + 1] : -1; break; } element_energy = vrna_E_ext_stem(type, s5, s3, P); if (sc_red_stem) element_energy += sc_red_stem(j, 1, j, sc_dat); if (c[kj] + element_energy + best_energy <= threshold) { repeat(fc, 1, j, state, element_energy, 0, best_energy, threshold, env, constraints_dat); } } } PRIVATE INLINE void scan_circular(vrna_fold_compound_t *fc, int i, int j, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat) { unsigned char *hard_constraints; char *ptype; short *S1; int k, l, p, q, tmp_en, best_energy, *c, *fML, *fM1, Fc, FcH, FcI, FcM, *fM2, length, *indx, *rtype, turn, kl, type, tmpE, u1, qmin, u2, type_2, tmpE2; vrna_param_t *P; vrna_md_t *md; vrna_hc_t *hc; vrna_sc_t *sc; struct hc_ext_def_dat *hc_dat_ext; struct hc_int_def_dat *hc_dat_int; struct hc_mb_def_dat *hc_dat_mb; vrna_callback_hc_evaluate *evaluate_ext; eval_hc *evaluate_int; vrna_callback_hc_evaluate *evaluate_mb; struct sc_int_dat *sc_dat_int; struct sc_mb_dat *sc_dat_mb; sc_int_cb *sc_int_pair_ext; sc_mb_red_cb *sc_mb_decomp_ml; STATE *new_state; INTERVAL *new_interval; length = fc->length; indx = fc->jindx; ptype = fc->ptype; S1 = fc->sequence_encoding; P = fc->params; md = &(P->model_details); rtype = &(md->rtype[0]); turn = md->min_loop_size; c = fc->matrices->c; fML = fc->matrices->fML; fM1 = fc->matrices->fM1; Fc = fc->matrices->Fc; FcH = fc->matrices->FcH; FcI = fc->matrices->FcI; FcM = fc->matrices->FcM; fM2 = fc->matrices->fM2; hc = fc->hc; hard_constraints = hc->mx; sc = fc->sc; hc_dat_ext = &(constraints_dat->hc_dat_ext); hc_dat_int = &(constraints_dat->hc_dat_int); hc_dat_mb = &(constraints_dat->hc_dat_mb); evaluate_ext = constraints_dat->hc_eval_ext; evaluate_int = constraints_dat->hc_eval_int; evaluate_mb = constraints_dat->hc_eval_mb; sc_dat_int = &(constraints_dat->sc_dat_int); sc_dat_mb = &(constraints_dat->sc_dat_mb); sc_int_pair_ext = constraints_dat->sc_dat_int.pair_ext; sc_mb_decomp_ml = constraints_dat->sc_dat_mb.decomp_ml; best_energy = best_attainable_energy(fc, state); /* .. on remaining intervals */ if (i > 1) vrna_message_error("Error while backtracking!"); if (j < i + turn + 1) { /* minimal structure element */ state->partial_energy += Fc; if (env->nopush) { push_back(env->Stack, state); env->nopush = false; } return; } /* * if we've done everything right, we will never reach this point more than once * right after the initilization of the stack with ([1,n], empty, 0) * lets check, if we can have an open chain without breaking the threshold * this is an ugly work-arround cause in case of an open chain we do not have to * backtrack anything further... */ if (evaluate_ext(1, length, 1, length, VRNA_DECOMP_EXT_UP, hc_dat_ext)) { tmp_en = 0; if (sc) { if (sc->energy_up) tmp_en += sc->energy_up[1][length]; if (sc->f) tmp_en += sc->f(1, j, 1, j, VRNA_DECOMP_EXT_UP, sc->data); } if (tmp_en <= threshold) { new_state = derive_new_state(1, 2, state, 0, 0); new_state->partial_energy = 0; push(env->Stack, new_state); env->nopush = false; } } /* * ok, lets check if we can do an exterior hairpin without breaking the threshold * best energy should be 0 if we are here */ if (FcH + best_energy <= threshold) { /* * lets search for all exterior hairpin cases, that fit into our threshold barrier * we use index k,l to avoid confusion with i,j index of our state... * if we reach here, i should be 1 and j should be n respectively */ for (k = i; k < j; k++) { if (hc->up_hp[1] < k) break; for (l = j; l >= k + turn + 1; l--) { kl = indx[l] + k; if (c[kl] != INF) { tmpE = vrna_E_hp_loop(fc, l, k); if (c[kl] + tmpE + best_energy <= threshold) /* * what we really have to do is something like this, isn't it? * we have to create a new state, with interval [k,l], then we * add our loop energy as initial energy of this state and put * the state onto the stack R... for further refinement... * we also denote this new interval to be scanned in C */ fork_state(k, l, state, tmpE, 2, env); } } } } /* now lets see, if we can do an exterior interior loop without breaking the threshold */ if (FcI + best_energy <= threshold) { /* now we search for our exterior interior loop possibilities */ for (k = i; k < j; k++) { for (l = j; l >= k + turn + 1; l--) { kl = indx[l] + k; /* just confusing these indices ;-) */ if ((hard_constraints[length * k + l] & VRNA_CONSTRAINT_CONTEXT_INT_LOOP) && (c[kl] != INF)) { type = rtype[vrna_get_ptype(kl, ptype)]; for (p = l + 1; p < j; p++) { u1 = p - l - 1; if (u1 + k - 1 > MAXLOOP) break; if (hc->up_int[l + 1] < u1) break; qmin = u1 + k - 1 + j - MAXLOOP; if (qmin < p + turn + 1) qmin = p + turn + 1; for (q = j; q >= qmin; q--) { if (hc->up_int[q + 1] < (j - q + k - 1)) break; if ((evaluate_int(k, l, p, q, hc_dat_int)) && (c[indx[q] + p] != INF)) { type_2 = rtype[vrna_get_ptype(indx[q] + p, ptype)]; u2 = k - 1 + j - q; if (u1 + u2 > MAXLOOP) continue; tmpE = E_IntLoop(u1, u2, type, type_2, S1[l + 1], S1[k - 1], S1[p - 1], S1[q + 1], P); if (sc_int_pair_ext) tmpE += sc_int_pair_ext(k, l, p, q, sc_dat_int); if (c[kl] + c[indx[q] + p] + tmpE + best_energy <= threshold) /* * ok, similar to the hairpin stuff, we add new states onto the stack R * but in contrast to the hairpin decomposition, we have to add two new * intervals, enclosed by k,l and p,q respectively and we also have to * add the partial energy, that comes from the exterior interior loop */ fork_two_states(k, l, p, q, state, tmpE, 2, 2, env); } } } } } } } /* and last but not least, we have a look, if we can do an exterior multiloop within the energy threshold */ if (FcM <= threshold) { /* * this decomposition will be somehow more complicated...so lets see what we do here... * first we want to find out which split inidices we can use without exceeding the threshold */ for (k = turn + 1; k < j - 2 * turn; k++) { if ((evaluate_mb(1, j, k, k + 1, VRNA_DECOMP_ML_ML_ML, hc_dat_mb)) && (fML[indx[k] + 1] != INF) && (fM2[k + 1] != INF)) { tmpE2 = fML[indx[k] + 1] + fM2[k + 1] + P->MLclosing; if (sc_mb_decomp_ml) { tmpE2 += sc_mb_decomp_ml(1, j, k, k + 1, sc_dat_mb); } if (tmpE2 + best_energy <= threshold) { /* * grmpfh, we have found a possible split index k so we have to split fM2 and fML now * lets do it first in fM2 anyway */ for (l = k + turn + 2; l < j - turn - 1; l++) { if ((evaluate_mb(k + 1, j, l, l + 1, VRNA_DECOMP_ML_ML_ML, hc_dat_mb)) && (fM1[indx[l] + k + 1] != INF) && (fM1[indx[j] + l + 1] != INF)) { tmpE2 = fM1[indx[l] + k + 1] + fM1[indx[j] + l + 1]; if (sc_mb_decomp_ml) tmpE2 += sc_mb_decomp_ml(k + 1, j, l, l + 1, sc_dat_mb); if (tmpE2 + fML[indx[k] + 1] + P->MLclosing <= threshold) { /* * we've (hopefully) found a valid decomposition of fM2 and therefor we have all * three intervals for our new state to be pushed on stack R */ new_state = copy_state(state); /* first interval leads for search in fML array */ new_interval = make_interval(1, k, 1); push(new_state->Intervals, new_interval); env->nopush = false; /* next, we have the first interval that has to be traced in fM1 */ new_interval = make_interval(k + 1, l, 3); push(new_state->Intervals, new_interval); env->nopush = false; /* and the last of our three intervals is also one to be traced within fM1 array... */ new_interval = make_interval(l + 1, j, 3); push(new_state->Intervals, new_interval); env->nopush = false; /* mmh, we add the energy for closing the multiloop now... */ new_state->partial_energy += P->MLclosing; /* next we push our state onto the R stack */ push(env->Stack, new_state); env->nopush = false; } } /* else we search further... */ } /* ok, we have to decompose fML now... */ } } } } } PRIVATE INLINE void scan_fms5(vrna_fold_compound_t *fc, unsigned int i, unsigned int strand, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat) { char *ptype; short *S1, s5, s3; unsigned int k, type, *sn, *se, end; int dangle_model, element_energy, best_energy, *c, *ggg, **fms5, *indx, with_gquad, turn; vrna_param_t *P; vrna_md_t *md; struct hc_ext_def_dat *hc_dat; vrna_callback_hc_evaluate *evaluate; struct sc_f5_dat *sc_dat; sc_ext_red_cb *sc_red_ext; sc_ext_red_cb *sc_red_stem; sc_ext_red_cb *sc_decomp; STATE *temp_state; sn = fc->strand_number; se = fc->strand_end; indx = fc->jindx; ptype = fc->ptype; S1 = fc->sequence_encoding; P = fc->params; md = &(P->model_details); dangle_model = md->dangles; with_gquad = md->gquad; turn = md->min_loop_size; c = fc->matrices->c; ggg = fc->matrices->ggg; fms5 = fc->matrices->fms5; hc_dat = &(constraints_dat->hc_dat_ext); evaluate = constraints_dat->hc_eval_ext; sc_dat = &(constraints_dat->sc_dat_ext); sc_red_ext = sc_dat->red_ext; sc_red_stem = sc_dat->red_stem; sc_decomp = sc_dat->decomp; best_energy = best_attainable_energy(fc, state); /* .. on remaining intervals */ end = se[strand]; /* no more pairs if too close to strand boundary ? */ if (i + turn + 1 > se[strand]) { state->partial_energy += fms5[strand][i]; if (env->nopush) { push_back(env->Stack, state); env->nopush = false; } return; } /* find split in fms5 */ if ((evaluate(i, end, i + 1, end, VRNA_DECOMP_EXT_EXT, hc_dat)) && (fms5[strand][i] != INF)) { element_energy = 0; if (sc_red_ext) element_energy += sc_red_ext(i, end, i + 1, end, sc_dat); if (fms5[strand][i + 1] + element_energy + best_energy <= threshold) /* no basepair, nibbling of 5'-end */ fork_state(i + 1, strand, state, element_energy, 4, env); } if (evaluate(i, end, i, end, VRNA_DECOMP_EXT_STEM, hc_dat)) { type = vrna_get_ptype(indx[end] + i, ptype); switch (dangle_model) { case 2: s5 = ((i > 1) && (sn[i - 1] == sn[i])) ? S1[i - 1] : -1; s3 = -1; break; default: s5 = -1; s3 = -1; break; } element_energy = vrna_E_ext_stem(type, s5, s3, P); if (sc_red_stem) element_energy += sc_red_stem(i, end, i, end, sc_dat); if (c[indx[end] + i] + element_energy + best_energy <= threshold) { repeat(fc, i, end, state, element_energy, 0, best_energy, threshold, env, constraints_dat); } } if ((with_gquad) && (ggg[indx[end] + i] != INF)) { element_energy = 0; if (sc_red_stem) element_energy += sc_red_stem(i, end, i, end, sc_dat); if (ggg[indx[end] + i] + element_energy + best_energy <= threshold) { repeat_gquad(fc, i, end, state, element_energy, 0, best_energy, threshold, env, constraints_dat); } } for (k = i + turn + 1; k < end; k++) { if ((with_gquad) && (fms5[strand][k + 1] != INF) && (ggg[indx[k] + i] != INF)) { element_energy = 0; if (sc_decomp) element_energy += sc_decomp(i, end, k, k + 1, sc_dat); if (sc_red_stem) element_energy += sc_red_stem(i, k, i, k, sc_dat); if (fms5[strand][k + 1] + ggg[indx[k] + i] + element_energy + best_energy <= threshold) { temp_state = derive_new_state(k + 1, strand, state, 0, 4); env->nopush = false; repeat_gquad(fc, i, k, temp_state, element_energy, fms5[strand][k + 1], best_energy, threshold, env, constraints_dat); free_state_node(temp_state); } } if (evaluate(i, end, k, k + 1, VRNA_DECOMP_EXT_STEM_EXT, hc_dat)) { type = vrna_get_ptype(indx[k] + i, ptype); switch (dangle_model) { case 2: s5 = ((i > 1) && (sn[i - 1] == sn[i])) ? S1[i - 1] : -1; s3 = (sn[k] == sn[k + 1]) ? S1[k + 1] : -1; break; default: s5 = -1; s3 = -1; break; } element_energy = vrna_E_ext_stem(type, s5, s3, P); if (sc_decomp) element_energy += sc_decomp(i, end, k, k + 1, sc_dat); if (sc_red_stem) element_energy += sc_red_stem(i, k, i, k, sc_dat); if (fms5[strand][k + 1] + c[indx[k] + i] + element_energy + best_energy <= threshold) { temp_state = derive_new_state(k + 1, strand, state, 0, 4); env->nopush = false; repeat(fc, i, k, temp_state, element_energy, fms5[strand][k + 1], best_energy, threshold, env, constraints_dat); free_state_node(temp_state); } } } } PRIVATE INLINE void scan_fms3(vrna_fold_compound_t *fc, unsigned int i, unsigned int strand, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat) { char *ptype; short *S1, s5, s3; unsigned int *sn, *ss, start, k, type; int dangle_model, element_energy, best_energy, *c, *ggg, **fms3, length, *indx, with_gquad, turn; vrna_param_t *P; vrna_md_t *md; struct hc_ext_def_dat *hc_dat; vrna_callback_hc_evaluate *evaluate; struct sc_f5_dat *sc_dat; sc_ext_red_cb *sc_red_ext; sc_ext_red_cb *sc_red_stem; sc_ext_red_cb *sc_decomp; STATE *temp_state; length = fc->length; sn = fc->strand_number; ss = fc->strand_start; indx = fc->jindx; ptype = fc->ptype; S1 = fc->sequence_encoding; P = fc->params; md = &(P->model_details); dangle_model = md->dangles; with_gquad = md->gquad; turn = md->min_loop_size; c = fc->matrices->c; ggg = fc->matrices->ggg; fms3 = fc->matrices->fms3; start = ss[strand]; hc_dat = &(constraints_dat->hc_dat_ext); evaluate = constraints_dat->hc_eval_ext; sc_dat = &(constraints_dat->sc_dat_ext); sc_red_ext = sc_dat->red_ext; sc_red_stem = sc_dat->red_stem; sc_decomp = sc_dat->decomp; best_energy = best_attainable_energy(fc, state); /* .. on remaining intervals */ /* no more pairs if too close to strand boundary ? */ if (i < ss[strand] + turn + 1) { state->partial_energy += fms3[strand][i]; if (env->nopush) { push_back(env->Stack, state); env->nopush = false; } return; } if ((evaluate(start, i, start, i - 1, VRNA_DECOMP_EXT_EXT, hc_dat)) && (fms3[strand][i - 1] != INF)) { element_energy = 0; if (sc_red_ext) element_energy += sc_red_ext(start, i, start, i - 1, sc_dat); if (fms3[strand][i - 1] + element_energy + best_energy <= threshold) /* no basepair, nibbling of 5'-end */ fork_state(i - 1, strand, state, element_energy, 5, env); } if (evaluate(start, i, start, i, VRNA_DECOMP_EXT_STEM, hc_dat)) { type = vrna_get_ptype(indx[i] + start, ptype); switch (dangle_model) { case 2: s5 = -1; s3 = ((i < length) && (sn[i] == sn[i + 1])) ? S1[i + 1] : -1; break; default: s5 = s3 = -1; break; } element_energy = vrna_E_ext_stem(type, s5, s3, P); if (sc_red_stem) element_energy += sc_red_stem(start, i, start, i, sc_dat); if (c[indx[i] + start] + element_energy + best_energy <= threshold) { repeat(fc, start, i, state, element_energy, 0, best_energy, threshold, env, constraints_dat); } } if ((with_gquad) && (ggg[indx[i] + start] != INF)) { element_energy = 0; if (sc_red_stem) element_energy += sc_red_stem(start, i, start, i, sc_dat); if (ggg[indx[i] + start] + element_energy + best_energy <= threshold) { repeat_gquad(fc, start, i, state, element_energy, 0, best_energy, threshold, env, constraints_dat); } } for (k = start; k < i - turn; k++) { if ((with_gquad) && (fms3[strand][k] != INF) && (ggg[indx[i] + k + 1] != INF)) { element_energy = 0; if (sc_decomp) element_energy += sc_decomp(start, i, k, k + 1, sc_dat); if (sc_red_stem) element_energy += sc_red_stem(k + 1, i, k + 1, i, sc_dat); if (fms3[strand][k] + ggg[indx[i] + k + 1] + element_energy + best_energy <= threshold) { temp_state = derive_new_state(k, strand, state, 0, 5); env->nopush = false; repeat_gquad(fc, k + 1, i, temp_state, element_energy, fms3[strand][k], best_energy, threshold, env, constraints_dat); free_state_node(temp_state); } } if (evaluate(start, i, k, k + 1, VRNA_DECOMP_EXT_EXT_STEM, hc_dat)) { type = vrna_get_ptype(indx[i] + k + 1, ptype); switch (dangle_model) { case 2: s5 = (sn[k] == sn[k + 1]) ? S1[k] : -1; s3 = ((i < length) && (sn[i] == sn[i + 1])) ? S1[i + 1] : -1; break; default: s5 = s3 = -1; break; } element_energy = vrna_E_ext_stem(type, s5, s3, P); if (sc_decomp) element_energy += sc_decomp(start, i, k, k + 1, sc_dat); if (sc_red_stem) element_energy += sc_red_stem(k + 1, i, k + 1, i, sc_dat); if (fms3[strand][k] + c[indx[i] + k + 1] + element_energy + best_energy <= threshold) { temp_state = derive_new_state(k, strand, state, 0, 5); env->nopush = false; repeat(fc, k + 1, i, temp_state, element_energy, fms3[strand][k], best_energy, threshold, env, constraints_dat); free_state_node(temp_state); } } } } PRIVATE INLINE void scan_gquad(vrna_fold_compound_t *fc, int i, int j, int threshold, STATE *state, subopt_env *env, constraint_helpers *constraints_dat) { int best_energy; best_energy = best_attainable_energy(fc, state); /* .. on remaining intervals */ /* we have a gquad */ repeat_gquad(fc, i, j, state, 0, 0, best_energy, threshold, env, constraints_dat); if (env->nopush) vrna_message_warning("%d,%d\nOops, no solution in gquad-repeat!", i, j); } PRIVATE void repeat_gquad(vrna_fold_compound_t *fc, int i, int j, STATE *state, int part_energy, int temp_energy, int best_energy, int threshold, subopt_env *env, constraint_helpers *constraints_dat) { short *S1; unsigned int *sn; int *ggg, *indx, element_energy, cnt, *L, *l, num_gquads; vrna_param_t *P; indx = fc->jindx; sn = fc->strand_number; ggg = fc->matrices->ggg; S1 = fc->sequence_encoding; P = fc->params; /* find all gquads that fit into the energy range and the interval [i,j] */ STATE *new_state; best_energy += part_energy; /* energy of current structural element */ best_energy += temp_energy; /* energy from unpushed interval */ if (sn[i] == sn[j]) { element_energy = ggg[indx[j] + i]; if ((element_energy != INF) && (element_energy + best_energy <= threshold)) { /* find out how many gquads we might expect in the interval [i,j] */ num_gquads = get_gquad_count(S1, i, j); num_gquads++; L = (int *)vrna_alloc(sizeof(int) * num_gquads); l = (int *)vrna_alloc(sizeof(int) * num_gquads * 3); L[0] = -1; get_gquad_pattern_exhaustive(S1, i, j, P, L, l, threshold - best_energy); for (cnt = 0; L[cnt] != -1; cnt++) { new_state = copy_state(state); make_gquad(i, L[cnt], &(l[3 * cnt]), new_state); new_state->partial_energy += part_energy; new_state->partial_energy += element_energy; /* new_state->best_energy = * hairpin[unpaired] + element_energy + best_energy; */ push(env->Stack, new_state); env->nopush = false; } free(L); free(l); } } best_energy -= part_energy; best_energy -= temp_energy; return; } PRIVATE void repeat(vrna_fold_compound_t *fc, int i, int j, STATE *state, int part_energy, int temp_energy, int best_energy, int threshold, subopt_env *env, constraint_helpers *constraints_dat) { /* * routine to find stacks, bulges, internal loops and multiloops * within interval closed by basepair i,j */ char *ptype; short *S1; unsigned int n, *sn, *se, nick; int ij, k, p, q, energy, new, mm, no_close, type, type_2, element_energy, *c, *fML, *fM1, *ggg, **fms5, **fms3, rt, *indx, *rtype, noGUclosure, noLP, with_gquad, dangle_model, turn, minq, eee, aux_eee, cnt, *ps, *qs, *en, tmp_en; vrna_param_t *P; vrna_md_t *md; vrna_hc_t *hc; struct hc_int_def_dat *hc_dat_int; struct hc_ext_def_dat *hc_dat_ext; struct hc_mb_def_dat *hc_dat_mb; eval_hc *evaluate_int; vrna_callback_hc_evaluate *evaluate_ext; vrna_callback_hc_evaluate *evaluate_mb; struct sc_int_dat *sc_dat_int; struct sc_mb_dat *sc_dat_mb; sc_int_cb *sc_int_pair; sc_mb_pair_cb *sc_mb_pair; sc_mb_red_cb *sc_mb_decomp_ml; STATE *new_state; n = fc->length; S1 = fc->sequence_encoding; ptype = fc->ptype; indx = fc->jindx; sn = fc->strand_number; se = fc->strand_end; P = fc->params; md = &(P->model_details); rtype = &(md->rtype[0]); noGUclosure = md->noGUclosure; noLP = md->noLP; with_gquad = md->gquad; dangle_model = md->dangles; turn = md->min_loop_size; c = fc->matrices->c; fML = fc->matrices->fML; fM1 = fc->matrices->fM1; ggg = fc->matrices->ggg; fms5 = fc->matrices->fms5; fms3 = fc->matrices->fms3; hc = fc->hc; hc_dat_ext = &(constraints_dat->hc_dat_ext); hc_dat_int = &(constraints_dat->hc_dat_int); hc_dat_mb = &(constraints_dat->hc_dat_mb); evaluate_ext = constraints_dat->hc_eval_ext; evaluate_int = constraints_dat->hc_eval_int; evaluate_mb = constraints_dat->hc_eval_mb; sc_dat_int = &(constraints_dat->sc_dat_int); sc_dat_mb = &(constraints_dat->sc_dat_mb); sc_int_pair = constraints_dat->sc_dat_int.pair; sc_mb_pair = constraints_dat->sc_dat_mb.pair; sc_mb_decomp_ml = constraints_dat->sc_dat_mb.decomp_ml; ij = indx[j] + i; type = vrna_get_ptype(ij, ptype); /* * if (type==0) fprintf(stderr, "repeat: Warning: %d %d can't pair\n", i,j); */ no_close = (((type == 3) || (type == 4)) && noGUclosure); if ((noLP) && (i + turn + 2 < j)) { /* always consider the structure with additional stack */ if (evaluate_int(i, j, i + 1, j - 1, hc_dat_int)) { type_2 = rtype[vrna_get_ptype(indx[j - 1] + i + 1, ptype)]; energy = 0; energy = E_IntLoop(0, 0, type, type_2, S1[i + 1], S1[j - 1], S1[i + 1], S1[j - 1], P); if (sc_int_pair) { energy += sc_int_pair(i, j, i + 1, j - 1, sc_dat_int); } new_state = derive_new_state(i + 1, j - 1, state, part_energy + energy, 2); make_pair(i, j, new_state); make_pair(i + 1, j - 1, new_state); /* new_state->best_energy = new + best_energy; */ push(env->Stack, new_state); env->nopush = false; if (i == 1 || state->structure[i - 2] != '(' || state->structure[j] != ')') /* adding a stack is the only possible structure */ return; } } best_energy += part_energy; /* energy of current structural element */ best_energy += temp_energy; /* energy from unpushed interval */ if (hc->mx[n * i + j] & VRNA_CONSTRAINT_CONTEXT_INT_LOOP) { for (p = i + 1; p <= MIN2(j - 2 - turn, i + MAXLOOP + 1); p++) { minq = j - i + p - MAXLOOP - 2; if (minq < p + 1 + turn) minq = p + 1 + turn; if (hc->up_int[i + 1] < (p - i - 1)) break; for (q = j - 1; q >= minq; q--) { if (hc->up_int[q + 1] < (j - q - 1)) break; /* skip stack if noLP, since we've already processed it above */ if ((noLP) && (p == i + 1) && (q == j - 1)) continue; if (!(hc->mx[n * p + q] & VRNA_CONSTRAINT_CONTEXT_INT_LOOP_ENC)) continue; if (c[indx[q] + p] == INF) continue; type_2 = vrna_get_ptype(indx[q] + p, ptype); if (noGUclosure) if (no_close || (type_2 == 3) || (type_2 == 4)) if ((p > i + 1) || (q < j - 1)) continue; if (evaluate_int(i, j, p, q, hc_dat_int)) { energy = E_IntLoop(p - i - 1, j - q - 1, type, rtype[type_2], S1[i + 1], S1[j - 1], S1[p - 1], S1[q + 1], P); new = energy + c[indx[q] + p]; if (sc_int_pair) energy += sc_int_pair(i, j, p, q, sc_dat_int); new = energy + c[indx[q] + p]; if (new + best_energy <= threshold) /* stack, bulge, or interior loop */ fork_int_state(i, j, p, q, state, part_energy + energy, env); } /*end of if block */ } /* end of q-loop */ } /* end of p-loop */ } /* base pair (i,j) encloses a loop with strand nick? */ if ((sn[i] != sn[j]) && (evaluate_ext(i, j, i, j, VRNA_DECOMP_EXT_STEM, hc_dat_ext))) { rt = rtype[type]; element_energy = P->DuplexInit; switch (dangle_model) { case 0: element_energy += vrna_E_ext_stem(rt, -1, -1, P); break; default: element_energy += vrna_E_ext_stem(rt, (sn[j - 1] == sn[j]) ? S1[j - 1] : -1, (sn[i] == sn[i + 1]) ? S1[i + 1] : -1, P); break; } if (sn[i] != sn[i + 1]) { if ((sn[j - 1] != sn[j]) && (i + 1 == j)) { if (element_energy + best_energy <= threshold) { fork_state_pair(i, j, state, part_energy + element_energy, env); } } else if (sn[j - 1] == sn[j]) { if (fms3[sn[i + 1]][j - 1] + element_energy + best_energy <= threshold) { /* continue backtracking in fms3[sn[i + 1]][j - 1] */ fork_state_pair_interval(i, j, j - 1, sn[i + 1], state, part_energy + element_energy, 5, env); } } } else if (sn[j - 1] != sn[j]) { if (fms5[sn[j - 1]][i + 1] + element_energy + best_energy <= threshold) { /* continue backtracking in fms5[sn[j - 1]][i + 1] */ fork_state_pair_interval(i, j, i + 1, sn[j - 1], state, part_energy + element_energy, 4, env); } } else { energy = 0; if (se[sn[i]] > i) energy += fms5[sn[i]][i + 1]; if (j - 1 > se[sn[i]]) energy += fms3[sn[se[sn[i]] + 1]][j - 1]; if (energy + element_energy + best_energy <= threshold) { fork_two_states_pair_ms(i, j, sn[i], sn[se[sn[i]] + 1], state, part_energy + element_energy, env); } nick = se[sn[i]] + 1; while (sn[nick] != sn[j]) { energy = 0; if (i + 1 <= se[sn[nick]]) energy += fms5[sn[nick]][i + 1]; if (se[sn[nick]] + 1 <= j - 1) energy += fms3[sn[se[sn[nick]] + 1]][j - 1]; if (energy + element_energy + best_energy <= threshold) { fork_two_states_pair_ms(i, j, sn[nick], sn[se[sn[nick]] + 1], state, part_energy + element_energy, env); } nick = se[sn[nick]] + 1; } } } mm = P->MLclosing; rt = rtype[type]; if (evaluate_mb(i, j, i + 1, j - 1, VRNA_DECOMP_PAIR_ML, hc_dat_mb)) { element_energy = mm; switch (dangle_model) { case 0: element_energy = E_MLstem(rt, -1, -1, P) + mm; break; default: element_energy = E_MLstem(rt, S1[j - 1], S1[i + 1], P) + mm; break; } if (sc_mb_pair) element_energy += sc_mb_pair(i, j, sc_dat_mb); /* multiloop decomposition */ for (k = i + turn + 2; k <= j - turn - 2; k++) { if (evaluate_mb(i + 1, j - 1, k - 1, k, VRNA_DECOMP_ML_ML_ML, hc_dat_mb)) { eee = fML[indx[k - 1] + i + 1]; if ((eee != INF) && (fM1[indx[j - 1] + k] != INF)) { eee += fM1[indx[j - 1] + k] + best_energy; aux_eee = element_energy; if (sc_mb_decomp_ml) aux_eee += sc_mb_decomp_ml(i + 1, j - 1, k - 1, k, sc_dat_mb); if ((eee + aux_eee) <= threshold) fork_two_states_pair(i, j, k, state, part_energy + aux_eee, 1, 3, env); } } } } if (sn[i] == sn[j]) { if (!no_close) { element_energy = vrna_E_hp_loop(fc, i, j); if (element_energy != INF) { if (element_energy + best_energy <= threshold) /* hairpin structure */ fork_state_pair(i, j, state, part_energy + element_energy, env); } } if (with_gquad) { /* now we have to find all loops where (i,j) encloses a gquad in an interior loops style */ ps = qs = en = NULL; en = E_GQuad_IntLoop_exhaustive(i, j, &ps, &qs, type, S1, ggg, threshold - best_energy, indx, P); for (cnt = 0; ps[cnt] != -1; cnt++) { if ((hc->up_int[i + 1] >= ps[cnt] - i - 1) && (hc->up_int[qs[cnt] + 1] >= j - qs[cnt] - 1)) { tmp_en = en[cnt]; if (sc_int_pair) tmp_en += sc_int_pair(i, j, ps[cnt], qs[cnt], sc_dat_int); new_state = derive_new_state(ps[cnt], qs[cnt], state, tmp_en + part_energy, 6); make_pair(i, j, new_state); /* new_state->best_energy = new + best_energy; */ push(env->Stack, new_state); env->nopush = false; } } free(en); free(ps); free(qs); } } best_energy -= part_energy; best_energy -= temp_energy; return; } PRIVATE void old_subopt_print(const char *structure, float energy, void *data) { struct old_subopt_dat *d = (struct old_subopt_dat *)data; if (structure && d->fp) { char *e_string = vrna_strdup_printf(" %6.2f", energy); print_structure(d->fp, structure, e_string); free(e_string); } } PRIVATE void old_subopt_store(const char *structure, float energy, void *data) { struct old_subopt_dat *d = (struct old_subopt_dat *)data; /* store solution */ if (d->n_sol + 1 == d->max_sol) { d->max_sol *= 2; d->SolutionList = (vrna_subopt_solution_t *)vrna_realloc(d->SolutionList, d->max_sol * sizeof(vrna_subopt_solution_t)); } if (structure) { d->SolutionList[d->n_sol].energy = energy; d->SolutionList[d->n_sol++].structure = strdup(structure); } else { d->SolutionList[d->n_sol].energy = 0; d->SolutionList[d->n_sol++].structure = NULL; } } PRIVATE void old_subopt_store_compressed(const char *structure, float energy, void *data) { struct old_subopt_dat *d = (struct old_subopt_dat *)data; /* store solution */ if (d->n_sol + 1 == d->max_sol) { d->max_sol *= 2; d->SolutionList = (vrna_subopt_solution_t *)vrna_realloc(d->SolutionList, d->max_sol * sizeof(vrna_subopt_solution_t)); } if (structure) { d->SolutionList[d->n_sol].energy = energy; if (d->cp > 0) { int cp = d->cp; char *s = vrna_cut_point_remove(structure, &cp); d->SolutionList[d->n_sol++].structure = vrna_db_pack(s); free(s); } else { d->SolutionList[d->n_sol++].structure = vrna_db_pack(structure); } } else { d->SolutionList[d->n_sol].energy = 0; d->SolutionList[d->n_sol++].structure = NULL; } } /* * ########################################### * # deprecated functions below # *########################################### */ #ifndef VRNA_DISABLE_BACKWARD_COMPATIBILITY PUBLIC SOLUTION * subopt(char *seq, char *structure, int delta, FILE *fp) { return wrap_subopt(seq, structure, NULL, delta, fold_constrained, 0, fp); } PUBLIC SOLUTION * subopt_circ(char *seq, char *structure, int delta, FILE *fp) { return wrap_subopt(seq, structure, NULL, delta, fold_constrained, 1, fp); } PUBLIC SOLUTION * subopt_par(char *seq, char *structure, vrna_param_t *parameters, int delta, int is_constrained, int is_circular, FILE *fp) { return wrap_subopt(seq, structure, parameters, delta, is_constrained, is_circular, fp); } PRIVATE SOLUTION * wrap_subopt(char *string, char *structure, vrna_param_t *parameters, int delta, int is_constrained, int is_circular, FILE *fp) { vrna_fold_compound_t *fc; vrna_param_t *P; char *seq; #ifdef _OPENMP /* Explicitly turn off dynamic threads */ omp_set_dynamic(0); #endif /* we need the parameter structure for hard constraints */ if (parameters) { P = vrna_params_copy(parameters); } else { vrna_md_t md; set_model_details(&md); md.temperature = temperature; P = vrna_params(&md); } P->model_details.circ = is_circular; P->model_details.uniq_ML = uniq_ML = 1; /* * what about cofold sequences here? Is it safe to call the below cut_point_insert() ? * dirty hack to reinsert the '&' according to the global variable 'cut_point' */ seq = vrna_cut_point_insert(string, cut_point); fc = vrna_fold_compound(seq, &(P->model_details), ((is_circular == 0) ? VRNA_OPTION_HYBRID : VRNA_OPTION_DEFAULT)); if (parameters) { /* replace params if necessary */ free(fc->params); fc->params = P; } else { free(P); } /* handle hard constraints in pseudo dot-bracket format if passed via simple interface */ if (is_constrained && structure) { unsigned int constraint_options = 0; constraint_options |= VRNA_CONSTRAINT_DB | VRNA_CONSTRAINT_DB_PIPE | VRNA_CONSTRAINT_DB_DOT | VRNA_CONSTRAINT_DB_X | VRNA_CONSTRAINT_DB_ANG_BRACK | VRNA_CONSTRAINT_DB_RND_BRACK | VRNA_CONSTRAINT_DB_INTRAMOL | VRNA_CONSTRAINT_DB_INTERMOL; vrna_constraints_add(fc, (const char *)structure, constraint_options); } if (backward_compat_compound && backward_compat) vrna_fold_compound_free(backward_compat_compound); backward_compat_compound = fc; backward_compat = 1; /* cleanup */ free(seq); return vrna_subopt(fc, delta, subopt_sorted, fp); } #endif /* * --------------------------------------------------------------------------- * Well, that is the end!---------------------------------------------------- *--------------------------------------------------------------------------- */
NDArray.h
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ #ifndef NDARRAY_H #define NDARRAY_H #include <initializer_list> #include <functional> #include <shape.h> #include "NativeOpExcutioner.h" #include <memory/Workspace.h> #include <indexing/NDIndex.h> #include <indexing/IndicesList.h> #include <graph/Intervals.h> #include <array/DataType.h> #include <stdint.h> #include <array/ArrayOptions.h> #include <array/ArrayType.h> #include <array/ResultSet.h> namespace nd4j { template<typename T> class ND4J_EXPORT NDArray; ND4J_EXPORT NDArray<float> operator-(const float, const NDArray<float>&); ND4J_EXPORT NDArray<float16> operator-(const float16, const NDArray<float16>&); ND4J_EXPORT NDArray<double> operator-(const double, const NDArray<double>&); ND4J_EXPORT NDArray<float> operator+(const float, const NDArray<float>&); ND4J_EXPORT NDArray<float16> operator+(const float16, const NDArray<float16>&); ND4J_EXPORT NDArray<double> operator+(const double, const NDArray<double>&); template<typename T> NDArray<T> mmul(const NDArray<T>&, const NDArray<T>&); template<typename T> class NDArray { protected: /** * if true then array doesn't own buffer and simply points to another's buffer */ bool _isView = false; /** * pointer on flattened data array in memory */ T *_buffer = nullptr; /** * contains shape info: matrix rank, numbers of elements per each dimension, dimensions strides, element-wise-stride, c-like or fortan-like order */ Nd4jLong *_shapeInfo = nullptr; /** * pointer on externally allocated memory where _buffer and _shapeInfo are stored */ nd4j::memory::Workspace* _workspace = nullptr; /** * alternative buffers for special computational devices (like GPUs for CUDA) */ T* _bufferD = nullptr; Nd4jLong *_shapeInfoD = nullptr; /** * indicates whether user allocates memory for _buffer/_shapeInfo by himself, in opposite case the memory must be allocated from outside */ bool _isShapeAlloc = false; bool _isBuffAlloc = false; /** * Field to store cached length */ Nd4jLong _length = -1L; /** * type of array elements */ DataType _dataType = DataType_FLOAT; std::string toStringValue(T value); public: static NDArray<T>* createEmpty(nd4j::memory::Workspace* workspace = nullptr); static NDArray<T>* valueOf(const std::initializer_list<Nd4jLong>& shape, const T value, const char order = 'c'); static NDArray<T>* valueOf(const std::vector<Nd4jLong>& shape, const T value, const char order = 'c'); static NDArray<T>* linspace(const T from, const T to, const Nd4jLong numElements); static NDArray<T>* scalar(const T value); /** * default constructor, do not allocate memory, memory for array is passed from outside */ NDArray(T *buffer = nullptr, Nd4jLong* shapeInfo = nullptr, nd4j::memory::Workspace* workspace = nullptr); NDArray(std::initializer_list<Nd4jLong> shape, nd4j::memory::Workspace* workspace = nullptr); /** * Constructor for scalar NDArray */ NDArray(T scalar); /** * copy constructor */ NDArray(const NDArray<T>& other); /** * move constructor */ NDArray(NDArray<T>&& other) noexcept; #ifndef __JAVACPP_HACK__ // this method only available out of javacpp /** * This constructor creates vector of T * * @param values */ NDArray(std::initializer_list<T> values, nd4j::memory::Workspace* workspace = nullptr); NDArray(std::vector<T> &values, nd4j::memory::Workspace* workspace = nullptr); #endif /** * constructor, create empty array stored at given workspace */ NDArray(nd4j::memory::Workspace* workspace); /** * this constructor creates new NDArray with shape matching "other" array, do not copy "other" elements into new array */ NDArray(const NDArray<T> *other, const bool copyStrides = false, nd4j::memory::Workspace* workspace = nullptr); /** * constructor creates new NDArray using shape information from "shapeInfo", set all elements in new array to be zeros, if copyStrides is true then use stride values from "shapeInfo", else calculate strides independently */ NDArray(const Nd4jLong* shapeInfo, const bool copyStrides = false, nd4j::memory::Workspace* workspace = nullptr); /** * this constructor creates new array using shape information contained in vector argument */ NDArray(const char order, const std::vector<Nd4jLong> &shape, nd4j::memory::Workspace* workspace = nullptr); /** * This constructor creates new array with elements copied from data and using shape information stored in shape * * PLEASE NOTE: data will be copied AS IS, without respect to specified order. You must ensure order match here. */ NDArray(const char order, const std::vector<Nd4jLong> &shape, const std::vector<T> &data, nd4j::memory::Workspace* workspace = nullptr); /** * this constructor creates new array using given buffer (without memory allocating) and shape information stored in shape */ NDArray(T *buffer, const char order, const std::vector<Nd4jLong> &shape , nd4j::memory::Workspace* workspace = nullptr); /** * copy assignment operator */ NDArray<T>& operator=(const NDArray<T>& other); /** * move assignment operator */ NDArray<T>& operator=(NDArray<T>&& other) noexcept; /** * assignment operator, assigns the same scalar to all array elements */ NDArray<T>& operator=(const T scalar); /** * operators for memory allocation and deletion */ void* operator new(size_t i); void operator delete(void* p); /** * method replaces existing buffer/shapeinfo, AND releases original pointers (if releaseExisting TRUE) */ void replacePointers(T *buffer, Nd4jLong *shapeInfo, const bool releaseExisting = true); /** * create a new array by replicating current array by repeats times along given dimension * dimension - dimension along which to repeat elements * repeats - number of repetitions */ NDArray<T>* repeat(int dimension, const std::vector<Nd4jLong>& repeats) const; /** * This method returns quantized copy of given array * * @param array * @return */ static NDArray<T> quantize(NDArray<T> &array); /** * This method returns quantized copy of given array * * @param array * @return */ static NDArray<T>* quantize(NDArray<T> *array); /** * fill target array by repeating current array * dimension - dimension along which to repeat elements */ void repeat(int dimension, NDArray<T>& target) const; /** * return _dataType; */ DataType dataType() const; /** * creates array which is view of this array */ NDArray<T>* getView(); /** * creates array which points on certain sub-range of this array, sub-range is defined by given indices */ NDArray<T> *subarray(IndicesList& indices) const; NDArray<T> *subarray(IndicesList& indices, std::vector<Nd4jLong>& strides) const; NDArray<T>* subarray(const std::initializer_list<NDIndex*>& idx) const; NDArray<T>* subarray(const Intervals& idx) const; /** * cast array elements to given dtype */ NDArray<T>* cast(DataType dtype); void cast(NDArray<T>* target, DataType dtype); /** * returns _workspace */ nd4j::memory::Workspace* getWorkspace() const { return _workspace; } /** * returns _buffer */ T* getBuffer() const; T* buffer(); /** * returns _shapeInfo */ Nd4jLong* shapeInfo(); Nd4jLong* getShapeInfo() const; /** * if _bufferD==nullptr return _buffer, else return _bufferD */ T* specialBuffer(); /** * Returns True if it's legally empty NDArray, or false otherwise * @return */ FORCEINLINE bool isEmpty() const; /** * if _shapeInfoD==nullptr return _shapeInfo, else return _shapeInfoD */ Nd4jLong* specialShapeInfo(); /** * set values for _bufferD and _shapeInfoD */ void setSpecialBuffers(T * buffer, Nd4jLong *shape); /** * permutes (in-place) the dimensions in array according to "dimensions" array */ bool permutei(const std::initializer_list<int>& dimensions); bool permutei(const std::vector<int>& dimensions); bool permutei(const int* dimensions, const int rank); bool permutei(const std::initializer_list<Nd4jLong>& dimensions); bool permutei(const std::vector<Nd4jLong>& dimensions); bool permutei(const Nd4jLong* dimensions, const int rank); bool isFinite(); bool hasNaNs(); bool hasInfs(); /** * permutes the dimensions in array according to "dimensions" array, new array points on _buffer of this array */ NDArray<T>* permute(const std::initializer_list<int>& dimensions) const; NDArray<T>* permute(const std::vector<int>& dimensions) const; NDArray<T>* permute(const int* dimensions, const int rank) const; void permute(const int* dimensions, const int rank, NDArray<T>& target) const; void permute(const std::vector<int>& dimensions, NDArray<T>& target) const; NDArray<T>* permute(const std::initializer_list<Nd4jLong>& dimensions) const; NDArray<T>* permute(const std::vector<Nd4jLong>& dimensions) const; NDArray<T>* permute(const Nd4jLong* dimensions, const int rank) const; void permute(const Nd4jLong* dimensions, const int rank, NDArray<T>& target) const; void permute(const std::vector<Nd4jLong>& dimensions, NDArray<T>& target) const; /** * This method streamlines given view or permuted array, and reallocates buffer */ void streamline(char order = 'a'); /** * check whether array is contiguous in memory */ bool isContiguous(); /** * prints information about array shape * msg - message to print out */ void printShapeInfo(const char * msg = nullptr) const; /** * prints buffer elements * msg - message to print out * limit - number of array elements to print out */ void printBuffer(const char* msg = nullptr, Nd4jLong limit = -1); /** * prints buffer elements, takes into account offset between elements (element-wise-stride) * msg - message to print out * limit - number of array elements to print out */ void printIndexedBuffer(const char* msg = nullptr, Nd4jLong limit = -1) const; std::string asIndexedString(Nd4jLong limit = -1); std::string asString(Nd4jLong limit = -1); /** * this method assigns values of given array to this one */ void assign(const NDArray<T>* other); /** * this method assigns values of given array to this one */ void assign(const NDArray<T>& other); /** * this method assigns given value to all elements in array */ void assign(const T value); /** * returns new copy of this array, optionally in different order */ NDArray<T> *dup(const char newOrder = 'a'); /** * returns sum of all elements of array */ T sumNumber() const; /** * returns mean number of array */ T meanNumber() const; /** * This method explicitly enforces new shape for this NDArray, old shape/stride information is lost */ void enforce(const std::initializer_list<Nd4jLong> &dimensions, char order = 'a'); void enforce(std::vector<Nd4jLong> &dimensions, char order = 'a'); /** * calculates sum along dimension(s) in this array and save it to created reduced array * dimensions - array of dimensions to calculate sum over * keepDims - if true then put unities in place of reduced dimensions */ NDArray<T> *sum(const std::vector<int> &dimensions) const; /** * method reduces array by excluding its shapes along dimensions present in given dimensions vector, result is stored in new array to be returned * dimensions - array of dimensions to reduce along * keepDims - if true then put unities in place of reduced dimensions */ template<typename OpName> NDArray<T>* reduceAlongDimension(const std::vector<int>& dimensions, const bool keepDims = false, const bool supportOldShapes = false) const; template<typename OpName> NDArray<T>* reduceAlongDimension(const std::initializer_list<int>& dimensions, const bool keepDims = false, const bool supportOldShapes = false) const; template<typename OpName> NDArray<T> reduceAlongDims(const std::vector<int>& dimensions, const bool keepDims = false, const bool supportOldShapes = false) const; /** * method reduces array by excluding its shapes along dimensions present in given dimensions vector * target - where to save result of reducing * dimensions - array of dimensions to reduce along * keepDims - if true then put unities in place of reduced dimensions * extras - extra parameters */ template<typename OpName> void reduceAlongDimension(NDArray<T>* target, const std::vector<int>& dimensions, const bool keepDims = false, const bool supportOldShapes = false, T *extras = nullptr) const; /** * return variance of array elements set * biasCorrected - if true bias correction will be applied */ template<typename OpName> T varianceNumber(bool biasCorrected = true); /** * apply scalar operation to array * extraParams - extra parameters for operation */ template<typename OpName> T reduceNumber(T *extraParams = nullptr) const; /** * returns element index which corresponds to some condition imposed by operation * extraParams - extra parameters for operation */ template<typename OpName> Nd4jLong indexReduceNumber(T *extraParams = nullptr); /** * returns index of max element in a given array (optionally: along given dimension(s)) * dimensions - optional vector with dimensions */ Nd4jLong argMax(std::initializer_list<int> dimensions = {}); /** * apply OpName transformation directly to array * extraParams - extra parameters for operation */ template<typename OpName> void applyTransform(T *extraParams = nullptr); /** * apply OpName transformation to array and store result in target * target - where to store result * extraParams - extra parameters for operation */ template<typename OpName> void applyTransform(NDArray<T> *target, T *extraParams = nullptr); /** * apply OpName transformation to this array and store result in new array being returned * extraParams - extra parameters for operation */ template<typename OpName> NDArray<T> transform(T *extraParams = nullptr) const; /** * apply pairwise OpName transformation based on "this" and "other" arras elements, store result in this array * other - second array necessary for pairwise operation * extraParams - extra parameters for operation */ template<typename OpName> void applyPairwiseTransform(NDArray<T> *other, T *extraParams); /** * apply pairwise OpName transformation based on "this" and "other" arras elements, store result in target array * other - second array necessary for pairwise operation * target - where to store result * extraParams - extra parameters for operation */ template<typename OpName> void applyPairwiseTransform(NDArray<T> *other, NDArray<T> *target, T *extraParams); /** * apply operation which requires broadcasting, broadcast a smaller array (tad) along bigger one (this) * tad - array to broadcast * dimensions - dimensions array to broadcast along * target - where to store result * extraParams - extra parameters for operation */ template<typename OpName> void applyBroadcast(std::initializer_list<int> dimensions, const NDArray<T>* tad, NDArray<T>* target = nullptr, T* extraArgs = nullptr); template <typename OpName> void applyBroadcast(std::vector<int> &dimensions, const NDArray<T> *tad, NDArray<T> *target = nullptr, T *extraArgs = nullptr); /** * apply operation which requires broadcasting, broadcast one tensor along another, also this method checks the possibility of broadcasting * other - input array * extraParams - extra parameters for operation */ template <typename OpName> NDArray<T> applyTrueBroadcast(const NDArray<T>& other, T *extraArgs = nullptr) const; template <typename OpName> NDArray<T>* applyTrueBroadcast(const NDArray<T>* other, T *extraArgs = nullptr) const; /** * apply operation which requires broadcasting, broadcast one tensor along another, also this method checks the possibility of broadcasting * other - input array * target - where to store result * checkTargetShape - if true check whether target shape is suitable for broadcasting * extraParams - extra parameters for operation */ template <typename OpName> void applyTrueBroadcast(const NDArray<T>* other, NDArray<T>* target, const bool checkTargetShape = true, T *extraArgs = nullptr) const; /** * apply a scalar operation to an array * scalar - input scalar * target - where to store result * extraParams - extra parameters for operation */ template<typename OpName> void applyScalar(T scalar, NDArray<T>* target = nullptr, T *extraParams = nullptr) const; /** * apply a scalar operation to an array * scalar - input array which is simple scalar * target - where to store result * extraParams - extra parameters for operation */ template<typename OpName> void applyScalar(NDArray<T>& scalar, NDArray<T>* target = nullptr, T *extraParams = nullptr) const; #ifndef __JAVACPP_HACK__ /** * apply operation "func" to an array * func - what operation to apply * target - where to store result */ void applyLambda(const std::function<T(T)>& func, NDArray<T>* target = nullptr); void applyIndexedLambda(const std::function<T(Nd4jLong, T)>& func, NDArray<T>* target = nullptr); /** * apply pairwise operation "func" to an array * other - input array * func - what pairwise operation to apply * target - where to store result */ void applyPairwiseLambda(const NDArray<T>* other, const std::function<T(T, T)>& func, NDArray<T>* target = nullptr); void applyIndexedPairwiseLambda(NDArray<T>* other, const std::function<T(Nd4jLong, T, T)>& func, NDArray<T>* target = nullptr); void applyTriplewiseLambda(NDArray<T>* second, NDArray<T> *third, const std::function<T(T, T, T)>& func, NDArray<T>* target = nullptr); #endif /** * apply OpName random operation to array * buffer - pointer on RandomBuffer * y - optional input array * z - optional input array * extraArgs - extra parameters for operation */ template<typename OpName> void applyRandom(nd4j::random::RandomBuffer *buffer, NDArray<T>* y = nullptr, NDArray<T>* z = nullptr, T* extraArgs = nullptr); /** * apply transpose operation to the copy of this array, that is this array remains unaffected */ NDArray<T>* transpose() const; NDArray<T> transp() const; /** * perform transpose operation and store result in target, this array remains unaffected * target - where to store result */ void transpose(NDArray<T>& target) const; /** * apply in-place transpose operation to this array, so this array becomes transposed */ void transposei(); /** * return array pointing on certain range of this array * index - the number of array to be returned among set of possible arrays * dimensions - array of dimensions to point on */ NDArray<T>* tensorAlongDimension(Nd4jLong index, const std::initializer_list<int>& dimensions) const; NDArray<T>* tensorAlongDimension(Nd4jLong index, const std::vector<int>& dimensions) const; /** * returns the number of arrays pointing on specified dimension(s) * dimensions - array of dimensions to point on */ Nd4jLong tensorsAlongDimension(const std::initializer_list<int> dimensions) const ; Nd4jLong tensorsAlongDimension(const std::vector<int>& dimensions) const ; /** * returns true if elements of two arrays are equal to within given epsilon value * other - input array to compare * eps - epsilon, this value defines the precision of elements comparison */ bool equalsTo(const NDArray<T> *other, T eps = (T) 1e-5f) const; bool equalsTo(NDArray<T> &other, T eps = (T) 1e-5f) const; /** * add given row vector to all rows of this array * row - row vector to add */ void addiRowVector(const NDArray<T> *row); /** * add given row vector to all rows of this array, store result in target * row - row vector to add * target - where to store result */ void addRowVector(const NDArray<T> *row, NDArray<T>* target) const; /** * subtract given row vector from all rows of this array, store result in target * row - row vector to subtract * target - where to store result */ void subRowVector(const NDArray<T> *row, NDArray<T>* target) const; /** * multiply all rows of this array on given row vector, store result in target * row - row vector to multiply on * target - where to store result */ void mulRowVector(const NDArray<T> *row, NDArray<T>* target) const; /** * divide all rows of this array on given row vector, store result in target * row - row vector to divide on * target - where to store result */ void divRowVector(const NDArray<T> *row, NDArray<T>* target) const; /** * add given column vector to all columns of this array, store result in target * column - column vector to add * target - where to store result */ void addColumnVector(const NDArray<T> *column, NDArray<T>* target) const; /** * add given column vector to all columns of this array, this array becomes affected (in-place operation) * column - column vector to add */ void addiColumnVector(const NDArray<T> *column); /** * multiply all columns of this array on given column vector, this array becomes affected (in-place operation) * column - column vector to multiply on */ void muliColumnVector(const NDArray<T> *column); /** * returns number of bytes used by _buffer & _shapeInfo */ Nd4jLong memoryFootprint(); /** * these methods suited for FlatBuffers use */ std::vector<T> getBufferAsVector(); std::vector<Nd4jLong> getShapeAsVector(); std::vector<Nd4jLong> getShapeInfoAsVector(); std::vector<int64_t> getShapeInfoAsFlatVector(); /** * set new order and shape in case of suitable array length (in-place operation) * order - order to set * shape - shape to set * * if there was permute applied before or there are weird strides, then new buffer is allocated for array */ bool reshapei(const char order, const std::initializer_list<Nd4jLong>& shape); bool reshapei(const char order, const std::vector<Nd4jLong>& shape); bool reshapei(const std::initializer_list<Nd4jLong>& shape); bool reshapei(const std::vector<Nd4jLong>& shape); /** * creates new array with corresponding order and shape, new array will point on _buffer of this array * order - order to set * shape - shape to set * * if permute have been applied before or there are weird strides, then new buffer is allocated for new array */ NDArray<T>* reshape(const char order, const std::vector<Nd4jLong>& shape) const; /** * calculate strides and set given order * order - order to set */ void updateStrides(const char order); /** * change an array by repeating it the number of times given by reps (in-place operation) * repeats - contains numbers of repetitions */ void tilei(const std::vector<Nd4jLong>& repeats); /** * returns new array which is created by repeating of this array the number of times given by reps * repeats - contains numbers of repetitions */ NDArray<T> tile(const std::vector<Nd4jLong>& repeats) const; /** * change an array by repeating it the number of times given by reps (in-place operation) * repeats - contains numbers of repetitions * target - where to store result */ void tile(const std::vector<Nd4jLong>& repeats, NDArray<T>& target) const; /** * change an array by repeating it the number of times to acquire the new shape which is the same as target shape * target - where to store result */ void tile(NDArray<T>& target) const; /** * returns an array which is result of broadcasting of this and other arrays * other - input array */ NDArray<T>* broadcast(const NDArray<T>& other); /** * check whether array's rows (arg=0) or columns (arg=1) create orthogonal basis * arg - 0 -> row, 1 -> column */ bool hasOrthonormalBasis(const int arg); /** * check whether array is identity matrix */ bool isIdentityMatrix(); /** * check whether array is unitary matrix */ bool isUnitary(); /** * reduces dimensions in this array relying on index operation OpName * dimensions - vector of dimensions to reduce along * extraArgs - extra parameters for operation */ template<typename OpName> NDArray<T>* applyIndexReduce(const std::vector<int>& dimensions, const T *extraParams = nullptr) const; /** * reduces dimensions in array relying on index operation OpName * target - where to store result * dimensions - vector of dimensions to reduce along * extraArgs - extra parameters for operation */ template<typename OpName> void applyIndexReduce(const NDArray<T>* target, const std::vector<int>& dimensions, const T *extraParams = nullptr) const; /** * apply reduce3 operation OpName to this and other array, return result in new output array * other - input array * extraArgs - extra parameters for operation */ template<typename OpName> NDArray<T>* applyReduce3(const NDArray<T>* other, const T* extraParams = nullptr) const; /** * apply reduce3 operation OpName to this and other array, return result in new output array * other - input array * dimensions - vector of dimensions to reduce along (tads not axis) * extraArgs - extra parameters for operation */ template<typename OpName> NDArray<T>* applyAllReduce3(const NDArray<T>* other, const std::vector<int>& dimensions, const T* extraParams = nullptr) const; /** * apply reduce3 (exec) operation OpName to this and other array, return result in new output array * other - input array * dimensions - vector of dimensions to reduce along (same as reduceAlongDimension) * extraArgs - extra parameters for operation */ template<typename OpName> NDArray<T>* applyReduce3(const NDArray<T>* other, const std::vector<int>& dimensions, const T* extraParams = nullptr) const; /** * returns variance along given dimensions * biasCorrected - if true bias correction will be applied * dimensions - vector of dimensions to calculate variance along */ template<typename OpName> NDArray<T>* varianceAlongDimension(const bool biasCorrected, const std::vector<int>& dimensions) const; template<typename OpName> NDArray<T>* varianceAlongDimension(const bool biasCorrected, const std::initializer_list<int>& dimensions) const; template<typename OpName> void varianceAlongDimension(const NDArray<T>* target, const bool biasCorrected, const std::vector<int>& dimensions); template<typename OpName> void varianceAlongDimension(const NDArray<T>* target, const bool biasCorrected, const std::initializer_list<int>& dimensions); /** * operator returns sub-array with buffer pointing at this->_buffer with offset defined by given intervals * idx - intervals of indexes which define the sub-arrays to point on * keepUnitiesInShape - if false then eliminate unities from resulting array shape, for example {1,a,1,b} -> {a,b} */ NDArray<T> operator()(const Intervals& idx, bool keepUnitiesInShape = false) const; /** * operator returns sub-array with buffer pointing at this->_buffer with offset defined by given intervals * idx - intervals of indexes which define the sub-arrays to point on, idx has form {dim0Start,dim0End, dim1Start,dim1End, ....} and length (2 * this->rankOf()) * when (dimStart == dimEnd) then whole range will be used for current dimension * keepUnitiesInShape - if false then eliminate unities from resulting array shape, for example {1,a,1,b} -> {a,b} */ NDArray<T> operator()(const Nd4jLong* idx, bool keepUnitiesInShape = false) const; /** * addition operator: array + other * other - input array to add */ NDArray<T> operator+(const NDArray<T>& other) const; /** * addition operator: array + scalar * scalar - input scalar to add */ NDArray<T> operator+(const T scalar) const; /** * friend functions which implement addition operator: scalar + array * scalar - input scalar to add */ friend NDArray<float> nd4j::operator+(const float scalar, const NDArray<float>& arr); friend NDArray<float16> nd4j::operator+(const float16 scalar, const NDArray<float16>& arr); friend NDArray<double> nd4j::operator+(const double scalar, const NDArray<double>& arr); /** * addition unary operator array += other * other - input array to add */ void operator+=(const NDArray<T>& other); /** * subtraction unary operator array -= other * other - input array to add */ void operator-=(const NDArray<T>& other); void operator+=(const T other); void operator-=(const T other); /** * subtraction operator: array - other * other - input array to subtract */ NDArray<T> operator-(const NDArray<T>& other) const; /** * subtraction operator: array - scalar * scalar - input scalar to subtract */ NDArray<T> operator-(const T& scalar) const; /** * negative operator, it changes sign of all array elements on opposite */ NDArray<T> operator-() const; /** * friend functions which implement subtraction operator: scalar - array * scalar - input scalar to subtract */ friend NDArray<float> nd4j::operator-(const float scalar, const NDArray<float>& arr); friend NDArray<float16> nd4j::operator-(const float16 scalar, const NDArray<float16>& arr); friend NDArray<double> nd4j::operator-(const double scalar, const NDArray<double>& arr); /** * pairwise multiplication operator: array * other * other - input array to multiply on */ NDArray<T> operator*(const NDArray<T>& other) const; /** * multiplication operator: array * scalar * scalar - input scalar to multiply on */ NDArray<T> operator*(const T scalar) const; /** * pairwise multiplication unary operator array *= other * other - input array to multiply on */ void operator*=(const NDArray<T>& other); /** * multiplication unary operator array *= scalar * scalar - input scalar to multiply on */ void operator*=(const T scalar); /** * pairwise division operator: array / other * other - input array to divide on */ NDArray<T> operator/(const NDArray<T>& other) const; /** * division operator: array / scalar * scalar - input scalar to divide each array element on */ NDArray<T> operator/(const T scalar) const; /** * pairwise division unary operator: array /= other * other - input array to divide on */ void operator/=(const NDArray<T>& other); /** * division unary operator: array /= scalar * scalar - input scalar to divide on */ void operator/=(const T scalar); /** * friend function which implements mathematical multiplication of two arrays * left - input array * right - input array */ friend NDArray<T> mmul<>(const NDArray<T>& left, const NDArray<T>& right); /** * this method assigns elements of other array to the sub-array of this array defined by given intervals * other - input array to assign elements from * idx - intervals of indexes which define the sub-array */ void assign(const NDArray<T>& other, const Intervals& idx); /** * return vector containing _buffer as flat binary array */ std::vector<int8_t> asByteVector(); /** * makes array to be identity matrix (not necessarily square), that is set all diagonal elements = 1, rest = 0 */ void setIdentity(); /** * swaps the contents of tow arrays, * PLEASE NOTE: method doesn't take into account the shapes of arrays, shapes may be different except one condition: arrays lengths must be the same */ void swapUnsafe(NDArray<T>& other); /** * return vector with buffer which points on corresponding diagonal elements of array * type - means of vector to be returned: column ('c') or row ('r') */ NDArray<T>* diagonal(const char type ) const; /** * fill matrix with given value starting from specified diagonal in given direction, works only with 2D matrix * * diag - diagonal starting from matrix is filled. * diag = 0 corresponds to main diagonal, * diag < 0 below main diagonal * diag > 0 above main diagonal * direction - in what direction to fill matrix. There are 2 possible directions: * 'u' - fill up, mathematically this corresponds to lower triangular matrix * 'l' - fill down, mathematically this corresponds to upper triangular matrix */ void setValueInDiagMatrix(const T& value, const int diag, const char direction); /** * change an array by repeating it the number of times in order to acquire new shape equal to the input shape * * shape - contains new shape to broadcast array to * target - optional argument, if target != nullptr the resulting array will be placed in target, in opposite case tile operation is done in place */ void tileToShape(const std::vector<Nd4jLong>& shape, NDArray<T>* target = nullptr); void tileToShape(const std::initializer_list<Nd4jLong>& shape, NDArray<T>* target = nullptr); template <typename N> NDArray<N>* asT(); /** * calculates the trace of an array, that is sum of elements on main diagonal = sum array[i, i, i, ...] */ T getTrace() const; /** * fill array linearly as follows: arr[0] = from, arr[1] = from+step, arr[2] = from+2*step, ... */ void linspace(const T from, const T step = 1.0f); NDArray<T>* createUninitialized() const; ResultSet<T>* multipleTensorsAlongDimension(const std::vector<int>& indices, const std::vector<int>& dimensions) const; ResultSet<T>* allTensorsAlongDimension(const std::vector<int>& dimensions) const; ResultSet<T>* allTensorsAlongDimension(const std::initializer_list<int>& dimensions) const; ResultSet<T>* allExamples()const ; template <typename OpName> void saveResultOfBroadcast(const NDArray<T>& x, const NDArray<T>& y, const bool checkThisShape = false); /** * default destructor */ ~NDArray() noexcept; /** * set _shapeInfo */ FORCEINLINE void setShapeInfo(Nd4jLong *shapeInfo); /** * set _buffer */ FORCEINLINE void setBuffer(T* buffer); /** * set _isBuffAlloc and _isShapeAlloc */ FORCEINLINE void triggerAllocationFlag(bool bufferAllocated, bool shapeAllocated); /** * returns the value of "dim" dimension */ Nd4jLong sizeAt(const int dim) const; /** * returns order of array */ FORCEINLINE char ordering() const; /** * return _isView */ FORCEINLINE bool isView(); /** * returns shape portion of shapeInfo */ FORCEINLINE Nd4jLong* shapeOf() const; /** * returns strides portion of shapeInfo */ FORCEINLINE Nd4jLong* stridesOf() const; /** * returns rank of array */ FORCEINLINE int rankOf() const; /** * returns length of array */ FORCEINLINE Nd4jLong lengthOf() const; /** * returns number of rows in array */ FORCEINLINE Nd4jLong rows() const; /** * returns number of columns in array */ FORCEINLINE Nd4jLong columns() const; /** * returns size of array elements type */ FORCEINLINE int sizeOfT() const; /** * returns element-wise-stride */ FORCEINLINE Nd4jLong ews() const; // returns true if arrays have same shape FORCEINLINE bool isSameShape(const NDArray<T> *other) const; FORCEINLINE bool isSameShape(NDArray<T> &other) const; FORCEINLINE bool isSameShape(const std::initializer_list<Nd4jLong>& shape) const; FORCEINLINE bool isSameShape(const std::vector<Nd4jLong>& shape) const; /** * returns true if these two NDArrays have same rank, dimensions, strides, ews and order */ FORCEINLINE bool isSameShapeStrict(const NDArray<T> *other) const; /** * returns true if buffer && shapeInfo were defined (non nullptr) */ FORCEINLINE bool nonNull() const; /** * returns array element with given index from linear buffer * i - element index in array */ FORCEINLINE T getScalar(const Nd4jLong i) const; /** * returns array element with given index, takes into account offset between elements (element-wise-stride) * i - element index in array */ FORCEINLINE T getIndexedScalar(const Nd4jLong i) const; /** * returns element with given indexes from 2D array * i - number of row * j - number of column */ FORCEINLINE T getScalar(const Nd4jLong i, const Nd4jLong j) const; /** * returns element with given indexes from 3D array * i - height * j - width * k - depth */ FORCEINLINE T getScalar(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) const; /** * assigns given scalar to array element by given index, takes into account offset between elements (element-wise-stride) * i - element index in array * value - scalar value to assign */ FORCEINLINE void putIndexedScalar(const Nd4jLong i, const T value); /** * assigns given scalar to array element by given index, regards array buffer as linear * i - element index in array * value - scalar value to assign */ FORCEINLINE void putScalar(const Nd4jLong i, const T value); /** * assigns given scalar to 2D array element by given indexes * i - number of row * j - number of row * value - scalar value to assign */ FORCEINLINE void putScalar(const Nd4jLong i, const Nd4jLong j, const T value); /** * assigns given scalar to 3D array element by given indexes * i - height * j - width * k - depth * value - scalar value to assign */ FORCEINLINE void putScalar(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k, const T value); /** * returns true if array is 2D */ FORCEINLINE bool isMatrix() const; /** * returns true if array is vector */ FORCEINLINE bool isVector() const; /** * returns true if array is column vector */ FORCEINLINE bool isColumnVector() const; /** * returns true if array is row vector */ FORCEINLINE bool isRowVector() const; /** * returns true if array is scalar */ FORCEINLINE bool isScalar() const; /** * inline accessing operator for matrix, i - absolute index */ FORCEINLINE T operator()(const Nd4jLong i) const; /** * inline modifying operator for matrix, i - absolute index */ FORCEINLINE T& operator()(const Nd4jLong i); /** * inline accessing operator for 2D array, i - row, j - column */ FORCEINLINE T operator()(const Nd4jLong i, const Nd4jLong j) const; /** * inline modifying operator for 2D array, i - row, j - column */ FORCEINLINE T& operator()(const Nd4jLong i, const Nd4jLong j); /** * inline accessing operator for 3D array, i - height, j - width, k - depth */ FORCEINLINE T operator()(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) const; /** * inline modifying operator for 3D array, i - height, j - width, k - depth */ FORCEINLINE T& operator()(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k); /** * inline modifying operator for 4D array, i - height, j - width, k - depth */ FORCEINLINE T& operator()(const Nd4jLong t, const Nd4jLong u, const Nd4jLong v, const Nd4jLong w); /** * inline accessing operator for 4D array, i - height, j - width, k - depth */ FORCEINLINE T operator()(const Nd4jLong t, const Nd4jLong u, const Nd4jLong v, const Nd4jLong w) const; template <typename T2> FORCEINLINE std::vector<T2> asVectorT(); FORCEINLINE bool isAttached(); NDArray<T>* detach(); FORCEINLINE bool operator == (const NDArray<T> &other) const; }; ////////////////////////////////////////////////////////////////////////// ///// IMLEMENTATION OF INLINE METHODS ///// ////////////////////////////////////////////////////////////////////////// template <typename T> template <typename T2> std::vector<T2> NDArray<T>::asVectorT() { std::vector<T2> result(this->lengthOf()); #pragma omp parallel for simd for (int e = 0; e < this->lengthOf(); e++) result[e] = static_cast<T2>(this->getIndexedScalar(e)); return result; } template<typename T> bool NDArray<T>::isAttached() { return this->_workspace != nullptr; } ////////////////////////////////////////////////////////////////////////// template<typename T> void NDArray<T>::setShapeInfo(Nd4jLong *shapeInfo) { if(_isShapeAlloc && _workspace == nullptr) delete []_shapeInfo; _shapeInfo = shapeInfo; _isShapeAlloc = false; if (shapeInfo != nullptr) this->_length = shape::length(shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> void NDArray<T>::setBuffer(T* buffer) { if(_isBuffAlloc && _workspace == nullptr) delete []_buffer; _buffer = buffer; _isBuffAlloc = false; } ////////////////////////////////////////////////////////////////////////// template<typename T> void NDArray<T>::triggerAllocationFlag(bool bufferAllocated, bool shapeAllocated) { _isBuffAlloc = bufferAllocated; _isShapeAlloc = shapeAllocated; } ////////////////////////////////////////////////////////////////////////// template<typename T> char NDArray<T>::ordering() const { return shape::order(_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isView() { return _isView; } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong* NDArray<T>::shapeOf() const { return shape::shapeOf(_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong* NDArray<T>::stridesOf() const { return shape::stride(_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> int NDArray<T>::rankOf() const { if (isEmpty()) return 0; return shape::rank(_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong NDArray<T>::lengthOf() const { return _length; } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong NDArray<T>::rows() const { if (this->rankOf() == 1) return 1; if (this->rankOf() > 2) throw std::runtime_error("Array with rank > 2 can't have rows"); return shapeOf()[0]; } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong NDArray<T>::columns() const { if (this->rankOf() == 1) return this->lengthOf(); if (this->rankOf() > 2) throw std::runtime_error("Array with rank > 2 can't have columns"); return shapeOf()[1]; } ////////////////////////////////////////////////////////////////////////// template<typename T> int NDArray<T>::sizeOfT() const { return sizeof(T); } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong NDArray<T>::ews() const { if (this->isEmpty() || this->rankOf() == 0) return 1; return shape::elementWiseStride(_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::nonNull() const { if (isEmpty()) return true; return this->_buffer != nullptr && this->_shapeInfo != nullptr; } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isMatrix() const { if (isEmpty()) return false; return shape::isMatrix(this->_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isVector() const { if (isEmpty()) return false; return !isScalar() && shape::isVector(this->_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isColumnVector() const { if (isEmpty()) return false; return !isScalar() && shape::isColumnVector(this->_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isRowVector() const { if (isEmpty()) return false; // 1D edge case if (shape::rank(this->_shapeInfo) == 1) return true; return !isScalar() && shape::isRowVector(this->_shapeInfo); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isScalar() const { return shape::isScalar(this->_shapeInfo); } // accessing operator for matrix, i - absolute index template<typename T> T NDArray<T>::operator()(const Nd4jLong i) const { if (i >= shape::length(_shapeInfo)) throw std::invalid_argument("NDArray::operator(i): dinput index is out of array length !"); auto ews = shape::elementWiseStride(_shapeInfo); char order = ordering(); if(ews == 1 && order == 'c') return _buffer[i]; else if(ews > 1 && order == 'c') return _buffer[i*ews]; else { Nd4jLong idx[MAX_RANK]; shape::ind2subC(rankOf(), shapeOf(), i, idx); Nd4jLong offset = shape::getOffset(0, shapeOf(), stridesOf(), idx, rankOf()); return _buffer[offset]; } } ////////////////////////////////////////////////////////////////////////// // modifying operator for matrix, i - absolute index template<typename T> T& NDArray<T>::operator()(const Nd4jLong i) { if (i >= shape::length(_shapeInfo)) throw std::invalid_argument("NDArray::operator(i): input index is out of array length !"); auto ews = shape::elementWiseStride(_shapeInfo); auto order = ordering(); if(ews == 1 && order == 'c') return _buffer[i]; else if(ews > 1 && order == 'c') return _buffer[i*ews]; else { Nd4jLong idx[MAX_RANK]; shape::ind2subC(rankOf(), shapeOf(), i, idx); auto offset = shape::getOffset(0, shapeOf(), stridesOf(), idx, rankOf()); return _buffer[offset]; } } ////////////////////////////////////////////////////////////////////////// // accessing operator for 2D matrix, i - row, j - column template<typename T> T NDArray<T>::operator()(const Nd4jLong i, const Nd4jLong j) const { if (rankOf() != 2 || i >= shapeOf()[0] || j >= shapeOf()[1]) throw std::invalid_argument("NDArray::operator(i,j): one of input indexes is out of array length or rank!=2 !"); Nd4jLong coords[2] = {i, j}; auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf()); return _buffer[xOffset]; } ////////////////////////////////////////////////////////////////////////// // modifying operator for 2D matrix, i - row, j - column template<typename T> T& NDArray<T>::operator()(const Nd4jLong i, const Nd4jLong j) { if (rankOf() != 2 || i >= shapeOf()[0] || j >= shapeOf()[1]) throw std::invalid_argument("NDArray::operator(i,j): one of input indexes is out of array length or rank!=2 !"); Nd4jLong coords[2] = {i, j}; auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf()); return _buffer[xOffset]; } ////////////////////////////////////////////////////////////////////////// // accessing operator for 3D array, i - row, j - column template<typename T> T NDArray<T>::operator()(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) const { if (rankOf() != 3 || i >= shapeOf()[0] || j >= shapeOf()[1] || j >= shapeOf()[2]) throw std::invalid_argument("NDArray::operator(i,j,k): one of input indexes is out of array length or rank!=3 !"); Nd4jLong coords[3] = {i, j, k}; auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf()); return _buffer[xOffset]; } ////////////////////////////////////////////////////////////////////////// // modifying operator for 3D array template<typename T> T& NDArray<T>::operator()(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) { if (rankOf() != 3 || i >= shapeOf()[0] || j >= shapeOf()[1] || k >= shapeOf()[2]) throw std::invalid_argument("NDArray::operator(i,j,k): one of input indexes is out of array length or rank!=3 !"); Nd4jLong coords[3] = {i, j, k}; auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf()); return _buffer[xOffset]; } template<typename T> T NDArray<T>::operator()(const Nd4jLong t, const Nd4jLong u, const Nd4jLong v, const Nd4jLong w) const { if (rankOf() != 4 || t >= shapeOf()[0] || u >= shapeOf()[1] || v >= shapeOf()[2] || w >= shapeOf()[3]) throw std::invalid_argument("NDArray::operator(t,u,v,w): one of input indexes is out of array length or rank!=4 !"); Nd4jLong coords[4] = {t, u, v, w}; auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf()); return _buffer[xOffset]; } template<typename T> T& NDArray<T>::operator()(const Nd4jLong t, const Nd4jLong u, const Nd4jLong v, const Nd4jLong w) { if (rankOf() != 4 || t >= shapeOf()[0] || u >= shapeOf()[1] || v >= shapeOf()[2] || w >= shapeOf()[3]) throw std::invalid_argument("NDArray::operator(t,u,v,w): one of input indexes is out of array length or rank!=4 !"); Nd4jLong coords[4] = {t, u, v, w}; auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf()); return _buffer[xOffset]; } ////////////////////////////////////////////////////////////////////////// // Return value from linear buffer template<typename T> T NDArray<T>::getScalar(const Nd4jLong i) const { return (*this)(i); } ////////////////////////////////////////////////////////////////////////// template<typename T> T NDArray<T>::getIndexedScalar(const Nd4jLong i) const { return (*this)(i); } ////////////////////////////////////////////////////////////////////////// // Returns value from 2D matrix by coordinates/indexes template<typename T> T NDArray<T>::getScalar(const Nd4jLong i, const Nd4jLong j) const { return (*this)(i, j); } ////////////////////////////////////////////////////////////////////////// // returns value from 3D tensor by coordinates template<typename T> T NDArray<T>::getScalar(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) const { return (*this)(i, j, k); } ////////////////////////////////////////////////////////////////////////// template<typename T> void NDArray<T>::putIndexedScalar(const Nd4jLong i, const T value) { (*this)(i) = value; } ////////////////////////////////////////////////////////////////////////// // This method sets value in linear buffer to position i template<typename T> void NDArray<T>::putScalar(const Nd4jLong i, const T value) { (*this)(i) = value; } ////////////////////////////////////////////////////////////////////////// // This method sets value in 2D matrix to position i, j template<typename T> void NDArray<T>::putScalar(const Nd4jLong i, const Nd4jLong j, const T value) { (*this)(i,j) = value; } ////////////////////////////////////////////////////////////////////////// // This method sets value in 3D matrix to position i,j,k template<typename T> void NDArray<T>::putScalar(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k, const T value) { (*this)(i,j,k) = value; } ////////////////////////////////////////////////////////////////////////// template<typename T> Nd4jLong NDArray<T>::memoryFootprint() { Nd4jLong size = this->lengthOf() * this->sizeOfT(); size += shape::shapeInfoByteLength(this->rankOf()); return size; } ////////////////////////////////////////////////////////////////////////// // still the definition of inline function must be in header file template<typename T> bool NDArray<T>::isSameShape(const std::vector<Nd4jLong>& shape) const{ if (this->isScalar() && shape.size() == 1 && shape[0] == 0) return true; if (this->rankOf() != (int) shape.size()) return false; for (int e = 0; e < this->rankOf(); e++) { if (this->shapeOf()[e] != shape.at(e) && shape.at(e) != -1) return false; } return true; } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isSameShape(const NDArray<T> *other) const { if (this->isEmpty() != other->isEmpty()) return false; return isSameShape(std::vector<Nd4jLong>(other->_shapeInfo+1, other->_shapeInfo+1+other->_shapeInfo[0])); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isSameShape(NDArray<T> &other) const { return isSameShape(&other); } ////////////////////////////////////////////////////////////////////////// template<typename T> bool NDArray<T>::isSameShape(const std::initializer_list<Nd4jLong>& other) const { return isSameShape(std::vector<Nd4jLong>(other)); } ////////////////////////////////////////////////////////////////////////// // returns true if these two NDArrays have same _shapeInfo // still the definition of inline function must be in header file template<typename T> bool NDArray<T>::isSameShapeStrict(const NDArray<T> *other) const { return shape::equalsStrict(_shapeInfo, other->_shapeInfo); } template<typename T> bool NDArray<T>::isEmpty() const { return ArrayOptions::arrayType(this->getShapeInfo()) == ArrayType::EMPTY; } template <typename T> bool NDArray<T>::operator ==(const NDArray<T> &other) const { if (!this->isSameShape(&other)) return false; return this->equalsTo(&other); } } #endif
GB_unaryop__minv_uint8_uint64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_uint8_uint64 // op(A') function: GB_tran__minv_uint8_uint64 // C type: uint8_t // A type: uint64_t // cast: uint8_t cij = (uint8_t) aij // unaryop: cij = GB_IMINV_UNSIGNED (aij, 8) #define GB_ATYPE \ uint64_t #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_UNSIGNED (x, 8) ; // casting #define GB_CASTING(z, x) \ uint8_t z = (uint8_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_UINT8 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_uint8_uint64 ( uint8_t *restrict Cx, const uint64_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_uint8_uint64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
firstlastprivate-clause.c
#include <stdio.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num()0 #endif main(){ int i,n=7; int a[n], suma=0; for(i=0;i<n;i++) a[i]=i; #pragma omp parallel for firstprivate(suma) lastprivate(suma) for(i=0; i<n; i++){ suma=suma+a[i]; printf ("thread %d suma a[%d] suma=%d\n ",omp_get_thread_num(),i,suma); } printf("\nFuera de la construccion parallel suma=%d\n",suma); }
3d7pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 16; tile_size[1] = 16; tile_size[2] = 32; tile_size[3] = 64; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,8);t1++) { lbp=max(ceild(t1,2),ceild(16*t1-Nt+3,16)); ubp=min(floord(Nt+Nz-4,16),floord(8*t1+Nz+5,16)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-3,4)),ceild(16*t2-Nz-28,32));t3<=min(min(min(floord(Nt+Ny-4,32),floord(8*t1+Ny+13,32)),floord(16*t2+Ny+12,32)),floord(16*t1-16*t2+Nz+Ny+11,32));t3++) { for (t4=max(max(max(0,ceild(t1-7,8)),ceild(16*t2-Nz-60,64)),ceild(32*t3-Ny-60,64));t4<=min(min(min(min(floord(Nt+Nx-4,64),floord(8*t1+Nx+13,64)),floord(16*t2+Nx+12,64)),floord(32*t3+Nx+28,64)),floord(16*t1-16*t2+Nz+Nx+11,64));t4++) { for (t5=max(max(max(max(max(0,8*t1),16*t1-16*t2+1),16*t2-Nz+2),32*t3-Ny+2),64*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,8*t1+15),16*t2+14),32*t3+30),64*t4+62),16*t1-16*t2+Nz+13);t5++) { for (t6=max(max(16*t2,t5+1),-16*t1+16*t2+2*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(32*t3,t5+1);t7<=min(32*t3+31,t5+Ny-2);t7++) { lbv=max(64*t4,t5+1); ubv=min(64*t4+63,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = (((((((coef[0][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (coef[1][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)])) + (coef[2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)])) + (coef[3][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1])) + (coef[4][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)])) + (coef[5][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)])) + (coef[6][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1]));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
omp_for_schedule_static.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include "omp_testsuite.h" #include "omp_my_sleep.h" #define CFSMAX_SIZE 1000 #define MAX_TIME 0.01 #ifdef SLEEPTIME #undef SLEEPTIME #define SLEEPTIME 0.0005 #endif int test_omp_for_schedule_static() { int threads; int i,lasttid; int * tids; int notout; int maxiter; int chunk_size; int counter = 0; int tmp_count=1; int lastthreadsstarttid = -1; int result = 1; chunk_size = 7; tids = (int *) malloc (sizeof (int) * (CFSMAX_SIZE + 1)); notout = 1; maxiter = 0; #pragma omp parallel shared(tids,counter) { /* begin of parallel*/ #pragma omp single { threads = omp_get_num_threads (); } /* end of single */ } /* end of parallel */ if (threads < 2) { omp_set_num_threads(2); threads = 2; } fprintf (stderr,"Using an internal count of %d\nUsing a specified" " chunksize of %d\n", CFSMAX_SIZE, chunk_size); tids[CFSMAX_SIZE] = -1; /* setting endflag */ #pragma omp parallel shared(tids) { /* begin of parallel */ double count; int tid; int j; tid = omp_get_thread_num (); #pragma omp for nowait schedule(static,chunk_size) for(j = 0; j < CFSMAX_SIZE; ++j) { count = 0.; #pragma omp flush(maxiter) if (j > maxiter) { #pragma omp critical { maxiter = j; } } /*printf ("thread %d sleeping\n", tid);*/ while (notout && (count < MAX_TIME) && (maxiter == j)) { #pragma omp flush(maxiter,notout) my_sleep (SLEEPTIME); count += SLEEPTIME; printf("."); } #ifdef VERBOSE if (count > 0.) printf(" waited %lf s\n", count); #endif /*printf ("thread %d awake\n", tid);*/ tids[j] = tid; #ifdef VERBOSE printf("%d finished by %d\n",j,tid); #endif } /* end of for */ notout = 0; #pragma omp flush(maxiter,notout) } /* end of parallel */ /**** analysing the data in array tids ****/ lasttid = tids[0]; tmp_count = 0; for (i = 0; i < CFSMAX_SIZE + 1; ++i) { /* If the work was done by the same thread increase tmp_count by one. */ if (tids[i] == lasttid) { tmp_count++; #ifdef VERBOSE fprintf (stderr, "%d: %d \n", i, tids[i]); #endif continue; } /* Check if the next thread had has the right thread number. When finding * threadnumber -1 the end should be reached. */ if (tids[i] == (lasttid + 1) % threads || tids[i] == -1) { /* checking for the right chunk size */ if (tmp_count == chunk_size) { tmp_count = 1; lasttid = tids[i]; #ifdef VERBOSE fprintf (stderr, "OK\n"); #endif } else { /* If the chunk size was wrong, check if the end was reached */ if (tids[i] == -1) { if (i == CFSMAX_SIZE) { fprintf (stderr, "Last thread had chunk size %d\n", tmp_count); break; } else { fprintf (stderr, "ERROR: Last thread (thread with" " number -1) was found before the end.\n"); result = 0; } } else { fprintf (stderr, "ERROR: chunk size was %d. (assigned" " was %d)\n", tmp_count, chunk_size); result = 0; } } } else { fprintf(stderr, "ERROR: Found thread with number %d (should be" " inbetween 0 and %d).", tids[i], threads - 1); result = 0; } #ifdef VERBOSE fprintf (stderr, "%d: %d \n", i, tids[i]); #endif } return result; } int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_for_schedule_static()) { num_failed++; } } return num_failed; }
stencil_opt2.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> #include "malloc2D.h" #include "timer.h" #define SWAP_PTR(xnew,xold,xtmp) (xtmp=xnew, xnew=xold, xold=xtmp) int main(int argc, char *argv[]) { #pragma omp parallel if (omp_get_thread_num() == 0) printf("Running with %d thread(s)\n",omp_get_num_threads()); struct timespec tstart_init, tstart_flush, tstart_stencil, tstart_total; double init_time, flush_time, stencil_time, total_time; int imax=2002, jmax = 2002; double** xtmp; double** x = malloc2D(jmax, imax); double** xnew = malloc2D(jmax, imax); int *flush = (int *)malloc(jmax*imax*sizeof(int)*4); cpu_timer_start(&tstart_total); cpu_timer_start(&tstart_init); #pragma omp parallel for for (int j = 0; j < jmax; j++){ for (int i = 0; i < imax; i++){ xnew[j][i] = 0.0; x[j][i] = 5.0; } } #pragma omp parallel for for (int j = jmax/2 - 5; j < jmax/2 + 5; j++){ for (int i = imax/2 - 5; i < imax/2 -1; i++){ x[j][i] = 400.0; } } init_time += cpu_timer_stop(tstart_init); for (int iter = 0; iter < 10000; iter++){ cpu_timer_start(&tstart_flush); #pragma omp parallel for for (int l = 1; l < jmax*imax*4; l++){ flush[l] = 1.0; } flush_time += cpu_timer_stop(tstart_flush); cpu_timer_start(&tstart_stencil); #pragma omp parallel for for (int j = 1; j < jmax-1; j++){ for (int i = 1; i < imax-1; i++){ xnew[j][i] = ( x[j][i] + x[j][i-1] + x[j][i+1] + x[j-1][i] + x[j+1][i] )/5.0; } } stencil_time += cpu_timer_stop(tstart_stencil); SWAP_PTR(xnew, x, xtmp); if (iter%1000 == 0) printf("Iter %d\n",iter); } total_time += cpu_timer_stop(tstart_total); printf("Timing is init %f flush %f stencil %f total %f\n", init_time,flush_time,stencil_time,total_time); free(x); free(xnew); free(flush); }
distribute.c
#pragma omp distribute [clauses] for-loops
rhs.c
//-------------------------------------------------------------------------// // // // This benchmark is an OpenMP C version of the NPB BT code. This OpenMP // // C version is developed by the Center for Manycore Programming at Seoul // // National University and derived from the OpenMP Fortran versions in // // "NPB3.3-OMP" developed by NAS. // // // // Permission to use, copy, distribute and modify this software for any // // purpose with or without fee is hereby granted. This software is // // provided "as is" without express or implied warranty. // // // // Information on NPB 3.3, including the technical report, the original // // specifications, source code, results and information on how to submit // // new results, is available at: // // // // http://www.nas.nasa.gov/Software/NPB/ // // // // Send comments or suggestions for this OpenMP C version to // // cmp@aces.snu.ac.kr // // // // Center for Manycore Programming // // School of Computer Science and Engineering // // Seoul National University // // Seoul 151-744, Korea // // // // E-mail: cmp@aces.snu.ac.kr // // // //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// // Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, // // and Jaejin Lee // //-------------------------------------------------------------------------// #include "header.h" #include "timers.h" void compute_rhs() { int i, j, k, m; double rho_inv, uijk, up1, um1, vijk, vp1, vm1, wijk, wp1, wm1; if (timeron) timer_start(t_rhs); #pragma scop #pragma omp parallel default(shared) private(i,j,k,m,rho_inv,uijk,up1,um1,\ vijk,vp1,vm1,wijk,wp1,wm1) { //--------------------------------------------------------------------- // compute the reciprocal of density, and the kinetic energy, // and the speed of sound. //--------------------------------------------------------------------- #pragma omp for schedule(static) nowait for (k = 0; k <= grid_points[2]-1; k++) { for (j = 0; j <= grid_points[1]-1; j++) { for (i = 0; i <= grid_points[0]-1; i++) { rho_inv = 1.0/u[k][j][i][0]; rho_i[k][j][i] = rho_inv; us[k][j][i] = u[k][j][i][1] * rho_inv; vs[k][j][i] = u[k][j][i][2] * rho_inv; ws[k][j][i] = u[k][j][i][3] * rho_inv; square[k][j][i] = 0.5* ( u[k][j][i][1]*u[k][j][i][1] + u[k][j][i][2]*u[k][j][i][2] + u[k][j][i][3]*u[k][j][i][3] ) * rho_inv; qs[k][j][i] = square[k][j][i] * rho_inv; } } } //--------------------------------------------------------------------- // copy the exact forcing term to the right hand side; because // this forcing term is known, we can store it on the whole grid // including the boundary //--------------------------------------------------------------------- #pragma omp for schedule(static) for (k = 0; k <= grid_points[2]-1; k++) { for (j = 0; j <= grid_points[1]-1; j++) { for (i = 0; i <= grid_points[0]-1; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = forcing[k][j][i][m]; } } } } //--------------------------------------------------------------------- // compute xi-direction fluxes //--------------------------------------------------------------------- #pragma omp for schedule(static) nowait for (k = 1; k <= grid_points[2]-2; k++) { for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { uijk = us[k][j][i]; up1 = us[k][j][i+1]; um1 = us[k][j][i-1]; rhs[k][j][i][0] = rhs[k][j][i][0] + dx1tx1 * (u[k][j][i+1][0] - 2.0*u[k][j][i][0] + u[k][j][i-1][0]) - tx2 * (u[k][j][i+1][1] - u[k][j][i-1][1]); rhs[k][j][i][1] = rhs[k][j][i][1] + dx2tx1 * (u[k][j][i+1][1] - 2.0*u[k][j][i][1] + u[k][j][i-1][1]) + xxcon2*con43 * (up1 - 2.0*uijk + um1) - tx2 * (u[k][j][i+1][1]*up1 - u[k][j][i-1][1]*um1 + (u[k][j][i+1][4]- square[k][j][i+1]- u[k][j][i-1][4]+ square[k][j][i-1])* c2); rhs[k][j][i][2] = rhs[k][j][i][2] + dx3tx1 * (u[k][j][i+1][2] - 2.0*u[k][j][i][2] + u[k][j][i-1][2]) + xxcon2 * (vs[k][j][i+1] - 2.0*vs[k][j][i] + vs[k][j][i-1]) - tx2 * (u[k][j][i+1][2]*up1 - u[k][j][i-1][2]*um1); rhs[k][j][i][3] = rhs[k][j][i][3] + dx4tx1 * (u[k][j][i+1][3] - 2.0*u[k][j][i][3] + u[k][j][i-1][3]) + xxcon2 * (ws[k][j][i+1] - 2.0*ws[k][j][i] + ws[k][j][i-1]) - tx2 * (u[k][j][i+1][3]*up1 - u[k][j][i-1][3]*um1); rhs[k][j][i][4] = rhs[k][j][i][4] + dx5tx1 * (u[k][j][i+1][4] - 2.0*u[k][j][i][4] + u[k][j][i-1][4]) + xxcon3 * (qs[k][j][i+1] - 2.0*qs[k][j][i] + qs[k][j][i-1]) + xxcon4 * (up1*up1 - 2.0*uijk*uijk + um1*um1) + xxcon5 * (u[k][j][i+1][4]*rho_i[k][j][i+1] - 2.0*u[k][j][i][4]*rho_i[k][j][i] + u[k][j][i-1][4]*rho_i[k][j][i-1]) - tx2 * ( (c1*u[k][j][i+1][4] - c2*square[k][j][i+1])*up1 - (c1*u[k][j][i-1][4] - c2*square[k][j][i-1])*um1 ); } } //--------------------------------------------------------------------- // add fourth order xi-direction dissipation //--------------------------------------------------------------------- for (j = 1; j <= grid_points[1]-2; j++) { i = 1; for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m]- dssp * ( 5.0*u[k][j][i][m] - 4.0*u[k][j][i+1][m] + u[k][j][i+2][m]); } i = 2; for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (-4.0*u[k][j][i-1][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j][i+1][m] + u[k][j][i+2][m]); } } for (j = 1; j <= grid_points[1]-2; j++) { for (i = 3; i <= grid_points[0]-4; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j][i-2][m] - 4.0*u[k][j][i-1][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j][i+1][m] + u[k][j][i+2][m] ); } } } for (j = 1; j <= grid_points[1]-2; j++) { i = grid_points[0]-3; for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j][i-2][m] - 4.0*u[k][j][i-1][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j][i+1][m] ); } i = grid_points[0]-2; for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j][i-2][m] - 4.*u[k][j][i-1][m] + 5.*u[k][j][i][m] ); } } } //--------------------------------------------------------------------- // compute eta-direction fluxes //--------------------------------------------------------------------- #pragma omp for schedule(static) for (k = 1; k <= grid_points[2]-2; k++) { for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { vijk = vs[k][j][i]; vp1 = vs[k][j+1][i]; vm1 = vs[k][j-1][i]; rhs[k][j][i][0] = rhs[k][j][i][0] + dy1ty1 * (u[k][j+1][i][0] - 2.0*u[k][j][i][0] + u[k][j-1][i][0]) - ty2 * (u[k][j+1][i][2] - u[k][j-1][i][2]); rhs[k][j][i][1] = rhs[k][j][i][1] + dy2ty1 * (u[k][j+1][i][1] - 2.0*u[k][j][i][1] + u[k][j-1][i][1]) + yycon2 * (us[k][j+1][i] - 2.0*us[k][j][i] + us[k][j-1][i]) - ty2 * (u[k][j+1][i][1]*vp1 - u[k][j-1][i][1]*vm1); rhs[k][j][i][2] = rhs[k][j][i][2] + dy3ty1 * (u[k][j+1][i][2] - 2.0*u[k][j][i][2] + u[k][j-1][i][2]) + yycon2*con43 * (vp1 - 2.0*vijk + vm1) - ty2 * (u[k][j+1][i][2]*vp1 - u[k][j-1][i][2]*vm1 + (u[k][j+1][i][4] - square[k][j+1][i] - u[k][j-1][i][4] + square[k][j-1][i]) *c2); rhs[k][j][i][3] = rhs[k][j][i][3] + dy4ty1 * (u[k][j+1][i][3] - 2.0*u[k][j][i][3] + u[k][j-1][i][3]) + yycon2 * (ws[k][j+1][i] - 2.0*ws[k][j][i] + ws[k][j-1][i]) - ty2 * (u[k][j+1][i][3]*vp1 - u[k][j-1][i][3]*vm1); rhs[k][j][i][4] = rhs[k][j][i][4] + dy5ty1 * (u[k][j+1][i][4] - 2.0*u[k][j][i][4] + u[k][j-1][i][4]) + yycon3 * (qs[k][j+1][i] - 2.0*qs[k][j][i] + qs[k][j-1][i]) + yycon4 * (vp1*vp1 - 2.0*vijk*vijk + vm1*vm1) + yycon5 * (u[k][j+1][i][4]*rho_i[k][j+1][i] - 2.0*u[k][j][i][4]*rho_i[k][j][i] + u[k][j-1][i][4]*rho_i[k][j-1][i]) - ty2 * ((c1*u[k][j+1][i][4] - c2*square[k][j+1][i]) * vp1 - (c1*u[k][j-1][i][4] - c2*square[k][j-1][i]) * vm1); } } //--------------------------------------------------------------------- // add fourth order eta-direction dissipation //--------------------------------------------------------------------- j = 1; for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m]- dssp * ( 5.0*u[k][j][i][m] - 4.0*u[k][j+1][i][m] + u[k][j+2][i][m]); } } j = 2; for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (-4.0*u[k][j-1][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j+1][i][m] + u[k][j+2][i][m]); } } for (j = 3; j <= grid_points[1]-4; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j-2][i][m] - 4.0*u[k][j-1][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j+1][i][m] + u[k][j+2][i][m] ); } } } j = grid_points[1]-3; for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j-2][i][m] - 4.0*u[k][j-1][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j+1][i][m] ); } } j = grid_points[1]-2; for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j-2][i][m] - 4.*u[k][j-1][i][m] + 5.*u[k][j][i][m] ); } } } //--------------------------------------------------------------------- // compute zeta-direction fluxes //--------------------------------------------------------------------- #pragma omp for schedule(static) for (k = 1; k <= grid_points[2]-2; k++) { for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { wijk = ws[k][j][i]; wp1 = ws[k+1][j][i]; wm1 = ws[k-1][j][i]; rhs[k][j][i][0] = rhs[k][j][i][0] + dz1tz1 * (u[k+1][j][i][0] - 2.0*u[k][j][i][0] + u[k-1][j][i][0]) - tz2 * (u[k+1][j][i][3] - u[k-1][j][i][3]); rhs[k][j][i][1] = rhs[k][j][i][1] + dz2tz1 * (u[k+1][j][i][1] - 2.0*u[k][j][i][1] + u[k-1][j][i][1]) + zzcon2 * (us[k+1][j][i] - 2.0*us[k][j][i] + us[k-1][j][i]) - tz2 * (u[k+1][j][i][1]*wp1 - u[k-1][j][i][1]*wm1); rhs[k][j][i][2] = rhs[k][j][i][2] + dz3tz1 * (u[k+1][j][i][2] - 2.0*u[k][j][i][2] + u[k-1][j][i][2]) + zzcon2 * (vs[k+1][j][i] - 2.0*vs[k][j][i] + vs[k-1][j][i]) - tz2 * (u[k+1][j][i][2]*wp1 - u[k-1][j][i][2]*wm1); rhs[k][j][i][3] = rhs[k][j][i][3] + dz4tz1 * (u[k+1][j][i][3] - 2.0*u[k][j][i][3] + u[k-1][j][i][3]) + zzcon2*con43 * (wp1 - 2.0*wijk + wm1) - tz2 * (u[k+1][j][i][3]*wp1 - u[k-1][j][i][3]*wm1 + (u[k+1][j][i][4] - square[k+1][j][i] - u[k-1][j][i][4] + square[k-1][j][i]) *c2); rhs[k][j][i][4] = rhs[k][j][i][4] + dz5tz1 * (u[k+1][j][i][4] - 2.0*u[k][j][i][4] + u[k-1][j][i][4]) + zzcon3 * (qs[k+1][j][i] - 2.0*qs[k][j][i] + qs[k-1][j][i]) + zzcon4 * (wp1*wp1 - 2.0*wijk*wijk + wm1*wm1) + zzcon5 * (u[k+1][j][i][4]*rho_i[k+1][j][i] - 2.0*u[k][j][i][4]*rho_i[k][j][i] + u[k-1][j][i][4]*rho_i[k-1][j][i]) - tz2 * ( (c1*u[k+1][j][i][4] - c2*square[k+1][j][i])*wp1 - (c1*u[k-1][j][i][4] - c2*square[k-1][j][i])*wm1); } } } //--------------------------------------------------------------------- // add fourth order zeta-direction dissipation //--------------------------------------------------------------------- k = 1; #pragma omp for schedule(static) nowait for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m]- dssp * ( 5.0*u[k][j][i][m] - 4.0*u[k+1][j][i][m] + u[k+2][j][i][m]); } } } k = 2; #pragma omp for schedule(static) nowait for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (-4.0*u[k-1][j][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k+1][j][i][m] + u[k+2][j][i][m]); } } } #pragma omp for schedule(static) nowait for (k = 3; k <= grid_points[2]-4; k++) { for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k-2][j][i][m] - 4.0*u[k-1][j][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k+1][j][i][m] + u[k+2][j][i][m] ); } } } } k = grid_points[2]-3; #pragma omp for schedule(static) nowait for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k-2][j][i][m] - 4.0*u[k-1][j][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k+1][j][i][m] ); } } } k = grid_points[2]-2; #pragma omp for schedule(static) for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k-2][j][i][m] - 4.*u[k-1][j][i][m] + 5.*u[k][j][i][m] ); } } } #pragma omp for schedule(static) nowait for (k = 1; k <= grid_points[2]-2; k++) { for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] * dt; } } } } } //end parallel #pragma endscop if (timeron) timer_stop(t_rhs); }
effect.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % EEEEE FFFFF FFFFF EEEEE CCCC TTTTT % % E F F E C T % % EEE FFF FFF EEE C T % % E F F E C T % % EEEEE F F EEEEE CCCC T % % % % % % MagickCore Image Effects Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/blob.h" #include "MagickCore/cache-view.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/constitute.h" #include "MagickCore/decorate.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/effect.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/matrix.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/montage.h" #include "MagickCore/morphology.h" #include "MagickCore/morphology-private.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/shear.h" #include "MagickCore/signature-private.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/transform.h" #include "MagickCore/threshold.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveBlurImage() adaptively blurs the image by blurring less % intensely near image edges and more intensely far from edges. We blur the % image with a Gaussian operator of the given radius and standard deviation % (sigma). For reasonable results, radius should be larger than sigma. Use a % radius of 0 and AdaptiveBlurImage() selects a suitable radius for you. % % The format of the AdaptiveBlurImage method is: % % Image *AdaptiveBlurImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Laplacian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveBlurImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { #define AdaptiveBlurImageTag "Convolve/Image" #define MagickSigma (fabs(sigma) < MagickEpsilon ? MagickEpsilon : sigma) CacheView *blur_view, *edge_view, *image_view; double normalize, **kernel; Image *blur_image, *edge_image, *gaussian_image; MagickBooleanType status; MagickOffsetType progress; ssize_t i; size_t width; ssize_t j, k, u, v, y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); blur_image=CloneImage(image,0,0,MagickTrue,exception); if (blur_image == (Image *) NULL) return((Image *) NULL); if (fabs(sigma) < MagickEpsilon) return(blur_image); if (SetImageStorageClass(blur_image,DirectClass,exception) == MagickFalse) { blur_image=DestroyImage(blur_image); return((Image *) NULL); } /* Edge detect the image brightness channel, level, blur, and level again. */ edge_image=EdgeImage(image,radius,exception); if (edge_image == (Image *) NULL) { blur_image=DestroyImage(blur_image); return((Image *) NULL); } (void) AutoLevelImage(edge_image,exception); gaussian_image=BlurImage(edge_image,radius,sigma,exception); if (gaussian_image != (Image *) NULL) { edge_image=DestroyImage(edge_image); edge_image=gaussian_image; } (void) AutoLevelImage(edge_image,exception); /* Create a set of kernels from maximum (radius,sigma) to minimum. */ width=GetOptimalKernelWidth2D(radius,sigma); kernel=(double **) MagickAssumeAligned(AcquireAlignedMemory((size_t) width, sizeof(*kernel))); if (kernel == (double **) NULL) { edge_image=DestroyImage(edge_image); blur_image=DestroyImage(blur_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memset(kernel,0,(size_t) width*sizeof(*kernel)); for (i=0; i < (ssize_t) width; i+=2) { kernel[i]=(double *) MagickAssumeAligned(AcquireAlignedMemory( (size_t) (width-i),(width-i)*sizeof(**kernel))); if (kernel[i] == (double *) NULL) break; normalize=0.0; j=(ssize_t) (width-i-1)/2; k=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel[i][k]=(double) (exp(-((double) u*u+v*v)/(2.0*MagickSigma* MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); normalize+=kernel[i][k]; k++; } } kernel[i][(k-1)/2]+=(double) (1.0-normalize); if (sigma < MagickEpsilon) kernel[i][(k-1)/2]=1.0; } if (i < (ssize_t) width) { for (i-=2; i >= 0; i-=2) kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]); kernel=(double **) RelinquishAlignedMemory(kernel); edge_image=DestroyImage(edge_image); blur_image=DestroyImage(blur_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Adaptively blur image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); edge_view=AcquireVirtualCacheView(edge_image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,blur_image,blur_image->rows,1) #endif for (y=0; y < (ssize_t) blur_image->rows; y++) { const Quantum *magick_restrict r; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; r=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if ((r == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) blur_image->columns; x++) { const Quantum *magick_restrict p; ssize_t i; ssize_t center, j; j=CastDoubleToLong(ceil((double) width*(1.0-QuantumScale* GetPixelIntensity(edge_image,r))-0.5)); if (j < 0) j=0; else if (j > (ssize_t) width) j=(ssize_t) width; if ((j & 0x01) != 0) j--; p=GetCacheViewVirtualPixels(image_view,x-((ssize_t) (width-j)/2L),y- (ssize_t) ((width-j)/2L),width-j,width-j,exception); if (p == (const Quantum *) NULL) break; center=(ssize_t) GetPixelChannels(image)*(width-j)*((width-j)/2L)+ GetPixelChannels(image)*((width-j)/2); for (i=0; i < (ssize_t) GetPixelChannels(blur_image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait blur_traits, traits; const double *magick_restrict k; const Quantum *magick_restrict pixels; ssize_t u; ssize_t v; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); blur_traits=GetPixelChannelTraits(blur_image,channel); if ((traits == UndefinedPixelTrait) || (blur_traits == UndefinedPixelTrait)) continue; if ((blur_traits & CopyPixelTrait) != 0) { SetPixelChannel(blur_image,channel,p[center+i],q); continue; } k=kernel[j]; pixels=p; pixel=0.0; gamma=0.0; if ((blur_traits & BlendPixelTrait) == 0) { /* No alpha blending. */ for (v=0; v < (ssize_t) (width-j); v++) { for (u=0; u < (ssize_t) (width-j); u++) { pixel+=(*k)*pixels[i]; gamma+=(*k); k++; pixels+=GetPixelChannels(image); } } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); continue; } /* Alpha blending. */ for (v=0; v < (ssize_t) (width-j); v++) { for (u=0; u < (ssize_t) (width-j); u++) { alpha=(double) (QuantumScale*GetPixelAlpha(image,pixels)); pixel+=(*k)*alpha*pixels[i]; gamma+=(*k)*alpha; k++; pixels+=GetPixelChannels(image); } } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); } q+=GetPixelChannels(blur_image); r+=GetPixelChannels(edge_image); } if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveBlurImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_image->type=image->type; blur_view=DestroyCacheView(blur_view); edge_view=DestroyCacheView(edge_view); image_view=DestroyCacheView(image_view); edge_image=DestroyImage(edge_image); for (i=0; i < (ssize_t) width; i+=2) kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]); kernel=(double **) RelinquishAlignedMemory(kernel); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e S h a r p e n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveSharpenImage() adaptively sharpens the image by sharpening more % intensely near image edges and less intensely far from edges. We sharpen the % image with a Gaussian operator of the given radius and standard deviation % (sigma). For reasonable results, radius should be larger than sigma. Use a % radius of 0 and AdaptiveSharpenImage() selects a suitable radius for you. % % The format of the AdaptiveSharpenImage method is: % % Image *AdaptiveSharpenImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Laplacian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveSharpenImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { #define AdaptiveSharpenImageTag "Convolve/Image" #define MagickSigma (fabs(sigma) < MagickEpsilon ? MagickEpsilon : sigma) CacheView *sharp_view, *edge_view, *image_view; double normalize, **kernel; Image *sharp_image, *edge_image, *gaussian_image; MagickBooleanType status; MagickOffsetType progress; ssize_t i; size_t width; ssize_t j, k, u, v, y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); sharp_image=CloneImage(image,0,0,MagickTrue,exception); if (sharp_image == (Image *) NULL) return((Image *) NULL); if (fabs(sigma) < MagickEpsilon) return(sharp_image); if (SetImageStorageClass(sharp_image,DirectClass,exception) == MagickFalse) { sharp_image=DestroyImage(sharp_image); return((Image *) NULL); } /* Edge detect the image brightness channel, level, sharp, and level again. */ edge_image=EdgeImage(image,radius,exception); if (edge_image == (Image *) NULL) { sharp_image=DestroyImage(sharp_image); return((Image *) NULL); } (void) AutoLevelImage(edge_image,exception); gaussian_image=BlurImage(edge_image,radius,sigma,exception); if (gaussian_image != (Image *) NULL) { edge_image=DestroyImage(edge_image); edge_image=gaussian_image; } (void) AutoLevelImage(edge_image,exception); /* Create a set of kernels from maximum (radius,sigma) to minimum. */ width=GetOptimalKernelWidth2D(radius,sigma); kernel=(double **) MagickAssumeAligned(AcquireAlignedMemory((size_t) width,sizeof(*kernel))); if (kernel == (double **) NULL) { edge_image=DestroyImage(edge_image); sharp_image=DestroyImage(sharp_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memset(kernel,0,(size_t) width*sizeof(*kernel)); for (i=0; i < (ssize_t) width; i+=2) { kernel[i]=(double *) MagickAssumeAligned(AcquireAlignedMemory((size_t) (width-i),(width-i)*sizeof(**kernel))); if (kernel[i] == (double *) NULL) break; normalize=0.0; j=(ssize_t) (width-i-1)/2; k=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel[i][k]=(double) (-exp(-((double) u*u+v*v)/(2.0*MagickSigma* MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); normalize+=kernel[i][k]; k++; } } kernel[i][(k-1)/2]=(double) ((-2.0)*normalize); if (sigma < MagickEpsilon) kernel[i][(k-1)/2]=1.0; } if (i < (ssize_t) width) { for (i-=2; i >= 0; i-=2) kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]); kernel=(double **) RelinquishAlignedMemory(kernel); edge_image=DestroyImage(edge_image); sharp_image=DestroyImage(sharp_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Adaptively sharpen image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); edge_view=AcquireVirtualCacheView(edge_image,exception); sharp_view=AcquireAuthenticCacheView(sharp_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,sharp_image,sharp_image->rows,1) #endif for (y=0; y < (ssize_t) sharp_image->rows; y++) { const Quantum *magick_restrict r; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; r=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(sharp_view,0,y,sharp_image->columns,1, exception); if ((r == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) sharp_image->columns; x++) { const Quantum *magick_restrict p; ssize_t i; ssize_t center, j; j=CastDoubleToLong(ceil((double) width*(1.0-QuantumScale* GetPixelIntensity(edge_image,r))-0.5)); if (j < 0) j=0; else if (j > (ssize_t) width) j=(ssize_t) width; if ((j & 0x01) != 0) j--; p=GetCacheViewVirtualPixels(image_view,x-((ssize_t) (width-j)/2L),y- (ssize_t) ((width-j)/2L),width-j,width-j,exception); if (p == (const Quantum *) NULL) break; center=(ssize_t) GetPixelChannels(image)*(width-j)*((width-j)/2L)+ GetPixelChannels(image)*((width-j)/2); for (i=0; i < (ssize_t) GetPixelChannels(sharp_image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait sharp_traits, traits; const double *magick_restrict k; const Quantum *magick_restrict pixels; ssize_t u; ssize_t v; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); sharp_traits=GetPixelChannelTraits(sharp_image,channel); if ((traits == UndefinedPixelTrait) || (sharp_traits == UndefinedPixelTrait)) continue; if ((sharp_traits & CopyPixelTrait) != 0) { SetPixelChannel(sharp_image,channel,p[center+i],q); continue; } k=kernel[j]; pixels=p; pixel=0.0; gamma=0.0; if ((sharp_traits & BlendPixelTrait) == 0) { /* No alpha blending. */ for (v=0; v < (ssize_t) (width-j); v++) { for (u=0; u < (ssize_t) (width-j); u++) { pixel+=(*k)*pixels[i]; gamma+=(*k); k++; pixels+=GetPixelChannels(image); } } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(sharp_image,channel,ClampToQuantum(gamma*pixel),q); continue; } /* Alpha blending. */ for (v=0; v < (ssize_t) (width-j); v++) { for (u=0; u < (ssize_t) (width-j); u++) { alpha=(double) (QuantumScale*GetPixelAlpha(image,pixels)); pixel+=(*k)*alpha*pixels[i]; gamma+=(*k)*alpha; k++; pixels+=GetPixelChannels(image); } } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(sharp_image,channel,ClampToQuantum(gamma*pixel),q); } q+=GetPixelChannels(sharp_image); r+=GetPixelChannels(edge_image); } if (SyncCacheViewAuthenticPixels(sharp_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveSharpenImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } sharp_image->type=image->type; sharp_view=DestroyCacheView(sharp_view); edge_view=DestroyCacheView(edge_view); image_view=DestroyCacheView(image_view); edge_image=DestroyImage(edge_image); for (i=0; i < (ssize_t) width; i+=2) kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]); kernel=(double **) RelinquishAlignedMemory(kernel); if (status == MagickFalse) sharp_image=DestroyImage(sharp_image); return(sharp_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlurImage() blurs an image. We convolve the image with a Gaussian operator % of the given radius and standard deviation (sigma). For reasonable results, % the radius should be larger than sigma. Use a radius of 0 and BlurImage() % selects a suitable radius for you. % % The format of the BlurImage method is: % % Image *BlurImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *BlurImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { char geometry[MagickPathExtent]; KernelInfo *kernel_info; Image *blur_image; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) blur_image=AccelerateBlurImage(image,radius,sigma,exception); if (blur_image != (Image *) NULL) return(blur_image); #endif (void) FormatLocaleString(geometry,MagickPathExtent, "blur:%.20gx%.20g;blur:%.20gx%.20g+90",radius,sigma,radius,sigma); kernel_info=AcquireKernelInfo(geometry,exception); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); blur_image=ConvolveImage(image,kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B i l a t e r a l B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BilateralBlurImage() is a non-linear, edge-preserving, and noise-reducing % smoothing filter for images. It replaces the intensity of each pixel with % a weighted average of intensity values from nearby pixels. This weight is % based on a Gaussian distribution. The weights depend not only on Euclidean % distance of pixels, but also on the radiometric differences (e.g., range % differences, such as color intensity, depth distance, etc.). This preserves % sharp edges. % % The format of the BilateralBlurImage method is: % % Image *BilateralBlurImage(const Image *image,const size_t width, % const size_t height,const double intensity_sigma, % const double spatial_sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the neighborhood in pixels. % % o height: the height of the neighborhood in pixels. % % o intensity_sigma: sigma in the intensity space. A larger value means % that farther colors within the pixel neighborhood (see spatial_sigma) % will be mixed together, resulting in larger areas of semi-equal color. % % o spatial_sigma: sigma in the coordinate space. A larger value means that % farther pixels influence each other as long as their colors are close % enough (see intensity_sigma ). When the neigborhood diameter is greater % than zero, it specifies the neighborhood size regardless of % spatial_sigma. Otherwise, the neigborhood diameter is proportional to % spatial_sigma. % % o exception: return any errors or warnings in this structure. % */ static inline double BlurDistance(const ssize_t x,const ssize_t y, const ssize_t u,const ssize_t v) { return(sqrt(((double) x-u)*((double) x-u)+((double) y-v)*((double) y-v))); } static inline double BlurGaussian(const double x,const double sigma) { return(exp(-((double) x*x)*PerceptibleReciprocal(2.0*sigma*sigma))* PerceptibleReciprocal(Magick2PI*sigma*sigma)); } static double **DestroyBilateralThreadSet(const ssize_t number_threads, double **weights) { ssize_t i; assert(weights != (double **) NULL); for (i=0; i <= (ssize_t) number_threads; i++) if (weights[i] != (double *) NULL) weights[i]=(double *) RelinquishMagickMemory(weights[i]); weights=(double **) RelinquishMagickMemory(weights); return(weights); } static double **AcquireBilateralThreadSet(const size_t number_threads, const size_t width,const size_t height) { double **weights; ssize_t i; weights=(double **) AcquireQuantumMemory(number_threads+1,sizeof(*weights)); if (weights == (double **) NULL) return((double **) NULL); (void) memset(weights,0,number_threads*sizeof(*weights)); for (i=0; i <= (ssize_t) number_threads; i++) { weights[i]=(double *) AcquireQuantumMemory(width,height*sizeof(**weights)); if (weights[i] == (double *) NULL) return(DestroyBilateralThreadSet(number_threads,weights)); } return(weights); } MagickExport Image *BilateralBlurImage(const Image *image,const size_t width, const size_t height,const double intensity_sigma,const double spatial_sigma, ExceptionInfo *exception) { #define MaxIntensity (255) #define BilateralBlurImageTag "Blur/Image" CacheView *blur_view, *image_view; double intensity_gaussian[2*(MaxIntensity+1)], *spatial_gaussian, **weights; Image *blur_image; MagickBooleanType status; MagickOffsetType progress; OffsetInfo mid; ssize_t u; ssize_t n, number_threads, v; ssize_t i, y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); blur_image=CloneImage(image,0,0,MagickTrue,exception); if (blur_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(blur_image,DirectClass,exception) == MagickFalse) { blur_image=DestroyImage(blur_image); return((Image *) NULL); } number_threads=(size_t) GetMagickResourceLimit(ThreadResource); weights=AcquireBilateralThreadSet(number_threads,width,height); if (weights == (double **) NULL) { blur_image=DestroyImage(blur_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=(-MaxIntensity); i < MaxIntensity; i++) intensity_gaussian[i+MaxIntensity]=BlurGaussian((double) i,intensity_sigma); spatial_gaussian=weights[number_threads]; n=0; mid.x=(ssize_t) (width/2L); mid.y=(ssize_t) (height/2L); for (v=0; v < (ssize_t) height; v++) for (u=0; u < (ssize_t) width; u++) spatial_gaussian[n++]=BlurGaussian(BlurDistance(0,0,u-mid.x,v-mid.y), spatial_sigma); /* Bilateral blur image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,blur_image,blur_image->rows,1) #endif for (y=0; y < (ssize_t) blur_image->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) blur_image->columns; x++) { double gamma, pixel; const Quantum *magick_restrict p, *magick_restrict r; ssize_t i, u; ssize_t n, v; /* Tonal weighting preserves edges while smoothing in the flat regions. */ p=GetCacheViewVirtualPixels(image_view,x-mid.x,y-mid.y,width,height, exception); if (p == (const Quantum *) NULL) break; p+=(ssize_t) GetPixelChannels(image)*width*mid.y+GetPixelChannels(image)* mid.x; n=0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { double intensity; r=p+(ssize_t) GetPixelChannels(image)*(ssize_t) width*(mid.y-v)+ GetPixelChannels(image)*(mid.x-u); intensity=ScaleQuantumToChar(GetPixelIntensity(image,r))- (double) ScaleQuantumToChar(GetPixelIntensity(image,p)); if ((intensity >= -MaxIntensity) && (intensity <= MaxIntensity)) weights[id][n]=intensity_gaussian[(ssize_t) intensity+MaxIntensity]* spatial_gaussian[n]; else weights[id][n]=BlurGaussian(intensity,intensity_sigma)* BlurGaussian(BlurDistance(x,y,x+u-mid.x,y+v-mid.y),spatial_sigma); n++; } } for (i=0; i < (ssize_t) GetPixelChannels(blur_image); i++) { PixelChannel channel; PixelTrait blur_traits, traits; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); blur_traits=GetPixelChannelTraits(blur_image,channel); if ((traits == UndefinedPixelTrait) || (blur_traits == UndefinedPixelTrait)) continue; if ((blur_traits & CopyPixelTrait) != 0) { SetPixelChannel(blur_image,channel,p[i],q); continue; } pixel=0.0; gamma=0.0; n=0; if ((blur_traits & BlendPixelTrait) == 0) { /* No alpha blending. */ for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { r=p+(ssize_t) GetPixelChannels(image)*width*(mid.y-v)+ GetPixelChannels(image)*(mid.x-u); pixel+=weights[id][n]*r[i]; gamma+=weights[id][n]; n++; } } SetPixelChannel(blur_image,channel,ClampToQuantum( PerceptibleReciprocal(gamma)*pixel),q); continue; } /* Alpha blending. */ for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { double alpha, beta; r=p+(ssize_t) GetPixelChannels(image)*width*(mid.y-v)+ GetPixelChannels(image)*(mid.x-u); alpha=(double) (QuantumScale*GetPixelAlpha(image,p)); beta=(double) (QuantumScale*GetPixelAlpha(image,r)); pixel+=weights[id][n]*r[i]; gamma+=weights[id][n]*alpha*beta; n++; } } SetPixelChannel(blur_image,channel,ClampToQuantum( PerceptibleReciprocal(gamma)*pixel),q); } q+=GetPixelChannels(blur_image); } if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,BilateralBlurImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_image->type=image->type; blur_view=DestroyCacheView(blur_view); image_view=DestroyCacheView(image_view); weights=DestroyBilateralThreadSet(number_threads,weights); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n v o l v e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvolveImage() applies a custom convolution kernel to the image. % % The format of the ConvolveImage method is: % % Image *ConvolveImage(const Image *image,const KernelInfo *kernel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o kernel: the filtering kernel. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ConvolveImage(const Image *image, const KernelInfo *kernel_info,ExceptionInfo *exception) { Image *convolve_image; #if defined(MAGICKCORE_OPENCL_SUPPORT) convolve_image=AccelerateConvolveImage(image,kernel_info,exception); if (convolve_image != (Image *) NULL) return(convolve_image); #endif convolve_image=MorphologyImage(image,ConvolveMorphology,1,kernel_info, exception); return(convolve_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s p e c k l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DespeckleImage() reduces the speckle noise in an image while perserving the % edges of the original image. A speckle removing filter uses a complementary % hulling technique (raising pixels that are darker than their surrounding % neighbors, then complementarily lowering pixels that are brighter than their % surrounding neighbors) to reduce the speckle index of that image (reference % Crimmins speckle removal). % % The format of the DespeckleImage method is: % % Image *DespeckleImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static void Hull(const Image *image,const ssize_t x_offset, const ssize_t y_offset,const size_t columns,const size_t rows, const int polarity,Quantum *magick_restrict f,Quantum *magick_restrict g) { Quantum *p, *q, *r, *s; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(f != (Quantum *) NULL); assert(g != (Quantum *) NULL); p=f+(columns+2); q=g+(columns+2); r=p+(y_offset*((ssize_t) columns+2)+x_offset); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) \ magick_number_threads(image,image,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { MagickRealType v; ssize_t i, x; i=(2*y+1)+y*columns; if (polarity > 0) for (x=0; x < (ssize_t) columns; x++) { v=(MagickRealType) p[i]; if ((MagickRealType) r[i] >= (v+ScaleCharToQuantum(2))) v+=ScaleCharToQuantum(1); q[i]=(Quantum) v; i++; } else for (x=0; x < (ssize_t) columns; x++) { v=(MagickRealType) p[i]; if ((MagickRealType) r[i] <= (v-ScaleCharToQuantum(2))) v-=ScaleCharToQuantum(1); q[i]=(Quantum) v; i++; } } p=f+(columns+2); q=g+(columns+2); r=q+(y_offset*((ssize_t) columns+2)+x_offset); s=q-(y_offset*((ssize_t) columns+2)+x_offset); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) \ magick_number_threads(image,image,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { ssize_t i, x; MagickRealType v; i=(2*y+1)+y*columns; if (polarity > 0) for (x=0; x < (ssize_t) columns; x++) { v=(MagickRealType) q[i]; if (((MagickRealType) s[i] >= (v+ScaleCharToQuantum(2))) && ((MagickRealType) r[i] > v)) v+=ScaleCharToQuantum(1); p[i]=(Quantum) v; i++; } else for (x=0; x < (ssize_t) columns; x++) { v=(MagickRealType) q[i]; if (((MagickRealType) s[i] <= (v-ScaleCharToQuantum(2))) && ((MagickRealType) r[i] < v)) v-=ScaleCharToQuantum(1); p[i]=(Quantum) v; i++; } } } MagickExport Image *DespeckleImage(const Image *image,ExceptionInfo *exception) { #define DespeckleImageTag "Despeckle/Image" CacheView *despeckle_view, *image_view; Image *despeckle_image; MagickBooleanType status; MemoryInfo *buffer_info, *pixel_info; Quantum *magick_restrict buffer, *magick_restrict pixels; ssize_t i; size_t length; static const ssize_t X[4] = {0, 1, 1,-1}, Y[4] = {1, 0, 1, 1}; /* Allocate despeckled image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) despeckle_image=AccelerateDespeckleImage(image,exception); if (despeckle_image != (Image *) NULL) return(despeckle_image); #endif despeckle_image=CloneImage(image,0,0,MagickTrue,exception); if (despeckle_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(despeckle_image,DirectClass,exception); if (status == MagickFalse) { despeckle_image=DestroyImage(despeckle_image); return((Image *) NULL); } /* Allocate image buffer. */ length=(size_t) ((image->columns+2)*(image->rows+2)); pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); buffer_info=AcquireVirtualMemory(length,sizeof(*buffer)); if ((pixel_info == (MemoryInfo *) NULL) || (buffer_info == (MemoryInfo *) NULL)) { if (buffer_info != (MemoryInfo *) NULL) buffer_info=RelinquishVirtualMemory(buffer_info); if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); despeckle_image=DestroyImage(despeckle_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(Quantum *) GetVirtualMemoryBlob(pixel_info); buffer=(Quantum *) GetVirtualMemoryBlob(buffer_info); /* Reduce speckle in the image. */ status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); despeckle_view=AcquireAuthenticCacheView(despeckle_image,exception); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel; PixelTrait despeckle_traits, traits; ssize_t k, x; ssize_t j, y; if (status == MagickFalse) continue; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); despeckle_traits=GetPixelChannelTraits(despeckle_image,channel); if ((traits == UndefinedPixelTrait) || (despeckle_traits == UndefinedPixelTrait)) continue; if ((despeckle_traits & CopyPixelTrait) != 0) continue; (void) memset(pixels,0,length*sizeof(*pixels)); j=(ssize_t) image->columns+2; for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } j++; for (x=0; x < (ssize_t) image->columns; x++) { pixels[j++]=p[i]; p+=GetPixelChannels(image); } j++; } (void) memset(buffer,0,length*sizeof(*buffer)); for (k=0; k < 4; k++) { Hull(image,X[k],Y[k],image->columns,image->rows,1,pixels,buffer); Hull(image,-X[k],-Y[k],image->columns,image->rows,1,pixels,buffer); Hull(image,-X[k],-Y[k],image->columns,image->rows,-1,pixels,buffer); Hull(image,X[k],Y[k],image->columns,image->rows,-1,pixels,buffer); } j=(ssize_t) image->columns+2; for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(despeckle_view,0,y,despeckle_image->columns, 1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } j++; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelChannel(despeckle_image,channel,pixels[j++],q); q+=GetPixelChannels(despeckle_image); } sync=SyncCacheViewAuthenticPixels(despeckle_view,exception); if (sync == MagickFalse) status=MagickFalse; j++; } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,DespeckleImageTag,(MagickOffsetType) i, GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } despeckle_view=DestroyCacheView(despeckle_view); image_view=DestroyCacheView(image_view); buffer_info=RelinquishVirtualMemory(buffer_info); pixel_info=RelinquishVirtualMemory(pixel_info); despeckle_image->type=image->type; if (status == MagickFalse) despeckle_image=DestroyImage(despeckle_image); return(despeckle_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E d g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EdgeImage() finds edges in an image. Radius defines the radius of the % convolution filter. Use a radius of 0 and EdgeImage() selects a suitable % radius for you. % % The format of the EdgeImage method is: % % Image *EdgeImage(const Image *image,const double radius, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *EdgeImage(const Image *image,const double radius, ExceptionInfo *exception) { Image *edge_image; KernelInfo *kernel_info; ssize_t i; size_t width; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=GetOptimalKernelWidth1D(radius,0.5); kernel_info=AcquireKernelInfo((const char *) NULL,exception); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(kernel_info,0,sizeof(*kernel_info)); kernel_info->width=width; kernel_info->height=width; kernel_info->x=(ssize_t) (kernel_info->width-1)/2; kernel_info->y=(ssize_t) (kernel_info->height-1)/2; kernel_info->signature=MagickCoreSignature; kernel_info->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel_info->width,kernel_info->height* sizeof(*kernel_info->values))); if (kernel_info->values == (MagickRealType *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) kernel_info->values[i]=(-1.0); kernel_info->values[i/2]=(double) kernel_info->width*kernel_info->height-1.0; edge_image=ConvolveImage(image,kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); return(edge_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E m b o s s I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EmbossImage() returns a grayscale image with a three-dimensional effect. % We convolve the image with a Gaussian operator of the given radius and % standard deviation (sigma). For reasonable results, radius should be % larger than sigma. Use a radius of 0 and Emboss() selects a suitable % radius for you. % % The format of the EmbossImage method is: % % Image *EmbossImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *EmbossImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { double gamma, normalize; Image *emboss_image; KernelInfo *kernel_info; ssize_t i; size_t width; ssize_t j, k, u, v; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=GetOptimalKernelWidth1D(radius,sigma); kernel_info=AcquireKernelInfo((const char *) NULL,exception); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); kernel_info->width=width; kernel_info->height=width; kernel_info->x=(ssize_t) (width-1)/2; kernel_info->y=(ssize_t) (width-1)/2; kernel_info->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel_info->width,kernel_info->width* sizeof(*kernel_info->values))); if (kernel_info->values == (MagickRealType *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } j=(ssize_t) (kernel_info->width-1)/2; k=j; i=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel_info->values[i]=(MagickRealType) (((u < 0) || (v < 0) ? -8.0 : 8.0)*exp(-((double) u*u+v*v)/(2.0*MagickSigma*MagickSigma))/ (2.0*MagickPI*MagickSigma*MagickSigma)); if (u != k) kernel_info->values[i]=0.0; i++; } k--; } normalize=0.0; for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) normalize+=kernel_info->values[i]; gamma=PerceptibleReciprocal(normalize); for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) kernel_info->values[i]*=gamma; emboss_image=ConvolveImage(image,kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); if (emboss_image != (Image *) NULL) (void) EqualizeImage(emboss_image,exception); return(emboss_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G a u s s i a n B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GaussianBlurImage() blurs an image. We convolve the image with a % Gaussian operator of the given radius and standard deviation (sigma). % For reasonable results, the radius should be larger than sigma. Use a % radius of 0 and GaussianBlurImage() selects a suitable radius for you. % % The format of the GaussianBlurImage method is: % % Image *GaussianBlurImage(const Image *image,onst double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *GaussianBlurImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { char geometry[MagickPathExtent]; KernelInfo *kernel_info; Image *blur_image; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); (void) FormatLocaleString(geometry,MagickPathExtent,"gaussian:%.20gx%.20g", radius,sigma); kernel_info=AcquireKernelInfo(geometry,exception); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); blur_image=ConvolveImage(image,kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % K u w a h a r a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % KuwaharaImage() is an edge preserving noise reduction filter. % % The format of the KuwaharaImage method is: % % Image *KuwaharaImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the square window radius. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ static inline MagickRealType GetMeanLuma(const Image *magick_restrict image, const double *magick_restrict pixel) { return(0.212656f*pixel[image->channel_map[RedPixelChannel].offset]+ 0.715158f*pixel[image->channel_map[GreenPixelChannel].offset]+ 0.072186f*pixel[image->channel_map[BluePixelChannel].offset]); /* Rec709 */ } MagickExport Image *KuwaharaImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { #define KuwaharaImageTag "Kuwahara/Image" CacheView *image_view, *kuwahara_view; Image *gaussian_image, *kuwahara_image; MagickBooleanType status; MagickOffsetType progress; size_t width; ssize_t y; /* Initialize Kuwahara image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=(size_t) radius+1; gaussian_image=BlurImage(image,radius,sigma,exception); if (gaussian_image == (Image *) NULL) return((Image *) NULL); kuwahara_image=CloneImage(image,0,0,MagickTrue,exception); if (kuwahara_image == (Image *) NULL) { gaussian_image=DestroyImage(gaussian_image); return((Image *) NULL); } if (SetImageStorageClass(kuwahara_image,DirectClass,exception) == MagickFalse) { gaussian_image=DestroyImage(gaussian_image); kuwahara_image=DestroyImage(kuwahara_image); return((Image *) NULL); } /* Edge preserving noise reduction filter. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(gaussian_image,exception); kuwahara_view=AcquireAuthenticCacheView(kuwahara_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,kuwahara_image,gaussian_image->rows,1) #endif for (y=0; y < (ssize_t) gaussian_image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(kuwahara_view,0,y,kuwahara_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) gaussian_image->columns; x++) { const Quantum *magick_restrict p; double min_variance; RectangleInfo quadrant, target; size_t i; min_variance=MagickMaximumValue; SetGeometry(gaussian_image,&target); quadrant.width=width; quadrant.height=width; for (i=0; i < 4; i++) { const Quantum *magick_restrict k; double mean[MaxPixelChannels], variance; ssize_t n; ssize_t j; quadrant.x=x; quadrant.y=y; switch (i) { case 0: { quadrant.x=x-(ssize_t) (width-1); quadrant.y=y-(ssize_t) (width-1); break; } case 1: { quadrant.y=y-(ssize_t) (width-1); break; } case 2: { quadrant.x=x-(ssize_t) (width-1); break; } case 3: default: break; } p=GetCacheViewVirtualPixels(image_view,quadrant.x,quadrant.y, quadrant.width,quadrant.height,exception); if (p == (const Quantum *) NULL) break; for (j=0; j < (ssize_t) GetPixelChannels(gaussian_image); j++) mean[j]=0.0; k=p; for (n=0; n < (ssize_t) (width*width); n++) { for (j=0; j < (ssize_t) GetPixelChannels(gaussian_image); j++) mean[j]+=(double) k[j]; k+=GetPixelChannels(gaussian_image); } for (j=0; j < (ssize_t) GetPixelChannels(gaussian_image); j++) mean[j]/=(double) (width*width); k=p; variance=0.0; for (n=0; n < (ssize_t) (width*width); n++) { double luma; luma=GetPixelLuma(gaussian_image,k); variance+=(luma-GetMeanLuma(gaussian_image,mean))* (luma-GetMeanLuma(gaussian_image,mean)); k+=GetPixelChannels(gaussian_image); } if (variance < min_variance) { min_variance=variance; target=quadrant; } } if (i < 4) { status=MagickFalse; break; } status=InterpolatePixelChannels(gaussian_image,image_view,kuwahara_image, UndefinedInterpolatePixel,(double) target.x+target.width/2.0,(double) target.y+target.height/2.0,q,exception); if (status == MagickFalse) break; q+=GetPixelChannels(kuwahara_image); } if (SyncCacheViewAuthenticPixels(kuwahara_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,KuwaharaImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } kuwahara_view=DestroyCacheView(kuwahara_view); image_view=DestroyCacheView(image_view); gaussian_image=DestroyImage(gaussian_image); if (status == MagickFalse) kuwahara_image=DestroyImage(kuwahara_image); return(kuwahara_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocalContrastImage() attempts to increase the appearance of large-scale % light-dark transitions. Local contrast enhancement works similarly to % sharpening with an unsharp mask, however the mask is instead created using % an image with a greater blur distance. % % The format of the LocalContrastImage method is: % % Image *LocalContrastImage(const Image *image, const double radius, % const double strength,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian blur, in percentage with 100% % resulting in a blur radius of 20% of largest dimension. % % o strength: the strength of the blur mask in percentage. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *LocalContrastImage(const Image *image,const double radius, const double strength,ExceptionInfo *exception) { #define LocalContrastImageTag "LocalContrast/Image" CacheView *image_view, *contrast_view; float *interImage, *scanline, totalWeight; Image *contrast_image; MagickBooleanType status; MemoryInfo *scanline_info, *interImage_info; ssize_t scanLineSize, width; /* Initialize contrast image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) contrast_image=AccelerateLocalContrastImage(image,radius,strength,exception); if (contrast_image != (Image *) NULL) return(contrast_image); #endif contrast_image=CloneImage(image,0,0,MagickTrue,exception); if (contrast_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(contrast_image,DirectClass,exception) == MagickFalse) { contrast_image=DestroyImage(contrast_image); return((Image *) NULL); } image_view=AcquireVirtualCacheView(image,exception); contrast_view=AcquireAuthenticCacheView(contrast_image,exception); scanLineSize=(ssize_t) MagickMax(image->columns,image->rows); width=(ssize_t) scanLineSize*0.002f*fabs(radius); scanLineSize+=(2*width); scanline_info=AcquireVirtualMemory((size_t) GetOpenMPMaximumThreads()* scanLineSize,sizeof(*scanline)); if (scanline_info == (MemoryInfo *) NULL) { contrast_view=DestroyCacheView(contrast_view); image_view=DestroyCacheView(image_view); contrast_image=DestroyImage(contrast_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } scanline=(float *) GetVirtualMemoryBlob(scanline_info); /* Create intermediate buffer. */ interImage_info=AcquireVirtualMemory(image->rows*(image->columns+(2*width)), sizeof(*interImage)); if (interImage_info == (MemoryInfo *) NULL) { scanline_info=RelinquishVirtualMemory(scanline_info); contrast_view=DestroyCacheView(contrast_view); image_view=DestroyCacheView(image_view); contrast_image=DestroyImage(contrast_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } interImage=(float *) GetVirtualMemoryBlob(interImage_info); totalWeight=(float) ((width+1)*(width+1)); /* Vertical pass. */ status=MagickTrue; { ssize_t x; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) \ magick_number_threads(image,image,image->columns,1) #endif for (x=0; x < (ssize_t) image->columns; x++) { const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; float *out, *pix, *pixels; ssize_t y; ssize_t i; if (status == MagickFalse) continue; pixels=scanline; pixels+=id*scanLineSize; pix=pixels; p=GetCacheViewVirtualPixels(image_view,x,-width,1,image->rows+(2*width), exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (y=0; y < (ssize_t) image->rows+(2*width); y++) { *pix++=(float)GetPixelLuma(image,p); p+=image->number_channels; } out=interImage+x+width; for (y=0; y < (ssize_t) image->rows; y++) { float sum, weight; weight=1.0f; sum=0; pix=pixels+y; for (i=0; i < width; i++) { sum+=weight*(*pix++); weight+=1.0f; } for (i=width+1; i < (2*width); i++) { sum+=weight*(*pix++); weight-=1.0f; } /* write to output */ *out=sum/totalWeight; /* mirror into padding */ if (x <= width && x != 0) *(out-(x*2))=*out; if ((x > (ssize_t) image->columns-width-2) && (x != (ssize_t) image->columns-1)) *(out+((image->columns-x-1)*2))=*out; out+=image->columns+(width*2); } } } /* Horizontal pass. */ { ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; float *pix, *pixels; Quantum *magick_restrict q; ssize_t x; ssize_t i; if (status == MagickFalse) continue; pixels=scanline; pixels+=id*scanLineSize; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(contrast_view,0,y,image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } memcpy(pixels,interImage+(y*(image->columns+(2*width))),(image->columns+ (2*width))*sizeof(float)); for (x=0; x < (ssize_t) image->columns; x++) { float mult, srcVal, sum, weight; PixelTrait traits; weight=1.0f; sum=0; pix=pixels+x; for (i=0; i < width; i++) { sum+=weight*(*pix++); weight+=1.0f; } for (i=width+1; i < (2*width); i++) { sum+=weight*(*pix++); weight-=1.0f; } /* Apply and write */ srcVal=(float) GetPixelLuma(image,p); mult=(srcVal-(sum/totalWeight))*(strength/100.0f); mult=(srcVal+mult)/srcVal; traits=GetPixelChannelTraits(image,RedPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelRed(contrast_image,ClampToQuantum((MagickRealType) GetPixelRed(image,p)*mult),q); traits=GetPixelChannelTraits(image,GreenPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelGreen(contrast_image,ClampToQuantum((MagickRealType) GetPixelGreen(image,p)*mult),q); traits=GetPixelChannelTraits(image,BluePixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelBlue(contrast_image,ClampToQuantum((MagickRealType) GetPixelBlue(image,p)*mult),q); p+=image->number_channels; q+=contrast_image->number_channels; } if (SyncCacheViewAuthenticPixels(contrast_view,exception) == MagickFalse) status=MagickFalse; } } scanline_info=RelinquishVirtualMemory(scanline_info); interImage_info=RelinquishVirtualMemory(interImage_info); contrast_view=DestroyCacheView(contrast_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) contrast_image=DestroyImage(contrast_image); return(contrast_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o t i o n B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MotionBlurImage() simulates motion blur. We convolve the image with a % Gaussian operator of the given radius and standard deviation (sigma). % For reasonable results, radius should be larger than sigma. Use a % radius of 0 and MotionBlurImage() selects a suitable radius for you. % Angle gives the angle of the blurring motion. % % Andrew Protano contributed this effect. % % The format of the MotionBlurImage method is: % % Image *MotionBlurImage(const Image *image,const double radius, % const double sigma,const double angle,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting % the center pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o angle: Apply the effect along this angle. % % o exception: return any errors or warnings in this structure. % */ static MagickRealType *GetMotionBlurKernel(const size_t width, const double sigma) { MagickRealType *kernel, normalize; ssize_t i; /* Generate a 1-D convolution kernel. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); kernel=(MagickRealType *) MagickAssumeAligned(AcquireAlignedMemory((size_t) width,sizeof(*kernel))); if (kernel == (MagickRealType *) NULL) return(kernel); normalize=0.0; for (i=0; i < (ssize_t) width; i++) { kernel[i]=(MagickRealType) (exp((-((double) i*i)/(double) (2.0*MagickSigma* MagickSigma)))/(MagickSQ2PI*MagickSigma)); normalize+=kernel[i]; } for (i=0; i < (ssize_t) width; i++) kernel[i]/=normalize; return(kernel); } MagickExport Image *MotionBlurImage(const Image *image,const double radius, const double sigma,const double angle,ExceptionInfo *exception) { #define BlurImageTag "Blur/Image" CacheView *blur_view, *image_view, *motion_view; Image *blur_image; MagickBooleanType status; MagickOffsetType progress; MagickRealType *kernel; OffsetInfo *offset; PointInfo point; ssize_t i; size_t width; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); width=GetOptimalKernelWidth1D(radius,sigma); kernel=GetMotionBlurKernel(width,sigma); if (kernel == (MagickRealType *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); offset=(OffsetInfo *) AcquireQuantumMemory(width,sizeof(*offset)); if (offset == (OffsetInfo *) NULL) { kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } point.x=(double) width*sin(DegreesToRadians(angle)); point.y=(double) width*cos(DegreesToRadians(angle)); for (i=0; i < (ssize_t) width; i++) { offset[i].x=CastDoubleToLong(ceil((double) (i*point.y)/ hypot(point.x,point.y)-0.5)); offset[i].y=CastDoubleToLong(ceil((double) (i*point.x)/ hypot(point.x,point.y)-0.5)); } /* Motion blur image. */ #if defined(MAGICKCORE_OPENCL_SUPPORT) blur_image=AccelerateMotionBlurImage(image,kernel,width,offset,exception); if (blur_image != (Image *) NULL) { kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); offset=(OffsetInfo *) RelinquishMagickMemory(offset); return(blur_image); } #endif blur_image=CloneImage(image,0,0,MagickTrue,exception); if (blur_image == (Image *) NULL) { kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); offset=(OffsetInfo *) RelinquishMagickMemory(offset); return((Image *) NULL); } if (SetImageStorageClass(blur_image,DirectClass,exception) == MagickFalse) { kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); offset=(OffsetInfo *) RelinquishMagickMemory(offset); blur_image=DestroyImage(blur_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); motion_view=AcquireVirtualCacheView(image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,blur_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait blur_traits, traits; const Quantum *magick_restrict r; MagickRealType *magick_restrict k; ssize_t j; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); blur_traits=GetPixelChannelTraits(blur_image,channel); if ((traits == UndefinedPixelTrait) || (blur_traits == UndefinedPixelTrait)) continue; if ((blur_traits & CopyPixelTrait) != 0) { SetPixelChannel(blur_image,channel,p[i],q); continue; } k=kernel; pixel=0.0; if ((blur_traits & BlendPixelTrait) == 0) { for (j=0; j < (ssize_t) width; j++) { r=GetCacheViewVirtualPixels(motion_view,x+offset[j].x,y+ offset[j].y,1,1,exception); if (r == (const Quantum *) NULL) { status=MagickFalse; continue; } pixel+=(*k)*r[i]; k++; } SetPixelChannel(blur_image,channel,ClampToQuantum(pixel),q); continue; } alpha=0.0; gamma=0.0; for (j=0; j < (ssize_t) width; j++) { r=GetCacheViewVirtualPixels(motion_view,x+offset[j].x,y+offset[j].y,1, 1,exception); if (r == (const Quantum *) NULL) { status=MagickFalse; continue; } alpha=(double) (QuantumScale*GetPixelAlpha(image,r)); pixel+=(*k)*alpha*r[i]; gamma+=(*k)*alpha; k++; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(blur_image); } if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,BlurImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_view=DestroyCacheView(blur_view); motion_view=DestroyCacheView(motion_view); image_view=DestroyCacheView(image_view); kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); offset=(OffsetInfo *) RelinquishMagickMemory(offset); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P r e v i e w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PreviewImage() tiles 9 thumbnails of the specified image with an image % processing operation applied with varying parameters. This may be helpful % pin-pointing an appropriate parameter for a particular image processing % operation. % % The format of the PreviewImages method is: % % Image *PreviewImages(const Image *image,const PreviewType preview, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o preview: the image processing operation. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PreviewImage(const Image *image,const PreviewType preview, ExceptionInfo *exception) { #define NumberTiles 9 #define PreviewImageTag "Preview/Image" #define DefaultPreviewGeometry "204x204+10+10" char factor[MagickPathExtent], label[MagickPathExtent]; double degrees, gamma, percentage, radius, sigma, threshold; Image *images, *montage_image, *preview_image, *thumbnail; ImageInfo *preview_info; MagickBooleanType proceed; MontageInfo *montage_info; QuantizeInfo quantize_info; RectangleInfo geometry; ssize_t i, x; size_t colors; ssize_t y; /* Open output image file. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); colors=2; degrees=0.0; gamma=(-0.2f); preview_info=AcquireImageInfo(); SetGeometry(image,&geometry); (void) ParseMetaGeometry(DefaultPreviewGeometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); images=NewImageList(); percentage=12.5; GetQuantizeInfo(&quantize_info); radius=0.0; sigma=1.0; threshold=0.0; x=0; y=0; for (i=0; i < NumberTiles; i++) { thumbnail=ThumbnailImage(image,geometry.width,geometry.height,exception); if (thumbnail == (Image *) NULL) break; (void) SetImageProgressMonitor(thumbnail,(MagickProgressMonitor) NULL, (void *) NULL); (void) SetImageProperty(thumbnail,"label",DefaultTileLabel,exception); if (i == (NumberTiles/2)) { (void) QueryColorCompliance("#dfdfdf",AllCompliance, &thumbnail->matte_color,exception); AppendImageToList(&images,thumbnail); continue; } switch (preview) { case RotatePreview: { degrees+=45.0; preview_image=RotateImage(thumbnail,degrees,exception); (void) FormatLocaleString(label,MagickPathExtent,"rotate %g",degrees); break; } case ShearPreview: { degrees+=5.0; preview_image=ShearImage(thumbnail,degrees,degrees,exception); (void) FormatLocaleString(label,MagickPathExtent,"shear %gx%g",degrees, 2.0*degrees); break; } case RollPreview: { x=(ssize_t) ((i+1)*thumbnail->columns)/NumberTiles; y=(ssize_t) ((i+1)*thumbnail->rows)/NumberTiles; preview_image=RollImage(thumbnail,x,y,exception); (void) FormatLocaleString(label,MagickPathExtent,"roll %+.20gx%+.20g", (double) x,(double) y); break; } case HuePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(factor,MagickPathExtent,"100,100,%g",2.0* percentage); (void) ModulateImage(preview_image,factor,exception); (void) FormatLocaleString(label,MagickPathExtent,"modulate %s",factor); break; } case SaturationPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(factor,MagickPathExtent,"100,%g",2.0* percentage); (void) ModulateImage(preview_image,factor,exception); (void) FormatLocaleString(label,MagickPathExtent,"modulate %s",factor); break; } case BrightnessPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(factor,MagickPathExtent,"%g",2.0*percentage); (void) ModulateImage(preview_image,factor,exception); (void) FormatLocaleString(label,MagickPathExtent,"modulate %s",factor); break; } case GammaPreview: default: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; gamma+=0.4f; (void) GammaImage(preview_image,gamma,exception); (void) FormatLocaleString(label,MagickPathExtent,"gamma %g",gamma); break; } case SpiffPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image != (Image *) NULL) for (x=0; x < i; x++) (void) ContrastImage(preview_image,MagickTrue,exception); (void) FormatLocaleString(label,MagickPathExtent,"contrast (%.20g)", (double) i+1); break; } case DullPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; for (x=0; x < i; x++) (void) ContrastImage(preview_image,MagickFalse,exception); (void) FormatLocaleString(label,MagickPathExtent,"+contrast (%.20g)", (double) i+1); break; } case GrayscalePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; colors<<=1; quantize_info.number_colors=colors; quantize_info.colorspace=GRAYColorspace; (void) QuantizeImage(&quantize_info,preview_image,exception); (void) FormatLocaleString(label,MagickPathExtent, "-colorspace gray -colors %.20g",(double) colors); break; } case QuantizePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; colors<<=1; quantize_info.number_colors=colors; (void) QuantizeImage(&quantize_info,preview_image,exception); (void) FormatLocaleString(label,MagickPathExtent,"colors %.20g", (double) colors); break; } case DespecklePreview: { for (x=0; x < (i-1); x++) { preview_image=DespeckleImage(thumbnail,exception); if (preview_image == (Image *) NULL) break; thumbnail=DestroyImage(thumbnail); thumbnail=preview_image; } preview_image=DespeckleImage(thumbnail,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(label,MagickPathExtent,"despeckle (%.20g)", (double) i+1); break; } case ReduceNoisePreview: { preview_image=StatisticImage(thumbnail,NonpeakStatistic,(size_t) radius,(size_t) radius,exception); (void) FormatLocaleString(label,MagickPathExtent,"noise %g",radius); break; } case AddNoisePreview: { switch ((int) i) { case 0: { (void) CopyMagickString(factor,"uniform",MagickPathExtent); break; } case 1: { (void) CopyMagickString(factor,"gaussian",MagickPathExtent); break; } case 2: { (void) CopyMagickString(factor,"multiplicative",MagickPathExtent); break; } case 3: { (void) CopyMagickString(factor,"impulse",MagickPathExtent); break; } case 5: { (void) CopyMagickString(factor,"laplacian",MagickPathExtent); break; } case 6: { (void) CopyMagickString(factor,"Poisson",MagickPathExtent); break; } default: { (void) CopyMagickString(thumbnail->magick,"NULL",MagickPathExtent); break; } } preview_image=StatisticImage(thumbnail,NonpeakStatistic,(size_t) i, (size_t) i,exception); (void) FormatLocaleString(label,MagickPathExtent,"+noise %s",factor); break; } case SharpenPreview: { preview_image=SharpenImage(thumbnail,radius,sigma,exception); (void) FormatLocaleString(label,MagickPathExtent,"sharpen %gx%g", radius,sigma); break; } case BlurPreview: { preview_image=BlurImage(thumbnail,radius,sigma,exception); (void) FormatLocaleString(label,MagickPathExtent,"blur %gx%g",radius, sigma); break; } case ThresholdPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) BilevelImage(thumbnail,(double) (percentage*((double) QuantumRange+1.0))/100.0,exception); (void) FormatLocaleString(label,MagickPathExtent,"threshold %g", (double) (percentage*((double) QuantumRange+1.0))/100.0); break; } case EdgeDetectPreview: { preview_image=EdgeImage(thumbnail,radius,exception); (void) FormatLocaleString(label,MagickPathExtent,"edge %g",radius); break; } case SpreadPreview: { preview_image=SpreadImage(thumbnail,image->interpolate,radius, exception); (void) FormatLocaleString(label,MagickPathExtent,"spread %g", radius+0.5); break; } case SolarizePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) SolarizeImage(preview_image,(double) QuantumRange*percentage/ 100.0,exception); (void) FormatLocaleString(label,MagickPathExtent,"solarize %g", (QuantumRange*percentage)/100.0); break; } case ShadePreview: { degrees+=10.0; preview_image=ShadeImage(thumbnail,MagickTrue,degrees,degrees, exception); (void) FormatLocaleString(label,MagickPathExtent,"shade %gx%g",degrees, degrees); break; } case RaisePreview: { RectangleInfo raise; preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; raise.width=(size_t) (2*i+2); raise.height=(size_t) (2*i+2); raise.x=(i-1)/2; raise.y=(i-1)/2; (void) RaiseImage(preview_image,&raise,MagickTrue,exception); (void) FormatLocaleString(label,MagickPathExtent, "raise %.20gx%.20g%+.20g%+.20g",(double) raise.width,(double) raise.height,(double) raise.x,(double) raise.y); break; } case SegmentPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; threshold+=0.4f; (void) SegmentImage(preview_image,sRGBColorspace,MagickFalse,threshold, threshold,exception); (void) FormatLocaleString(label,MagickPathExtent,"segment %gx%g", threshold,threshold); break; } case SwirlPreview: { preview_image=SwirlImage(thumbnail,degrees,image->interpolate, exception); (void) FormatLocaleString(label,MagickPathExtent,"swirl %g",degrees); degrees+=45.0; break; } case ImplodePreview: { degrees+=0.1f; preview_image=ImplodeImage(thumbnail,degrees,image->interpolate, exception); (void) FormatLocaleString(label,MagickPathExtent,"implode %g",degrees); break; } case WavePreview: { degrees+=5.0f; preview_image=WaveImage(thumbnail,0.5*degrees,2.0*degrees, image->interpolate,exception); (void) FormatLocaleString(label,MagickPathExtent,"wave %gx%g",0.5* degrees,2.0*degrees); break; } case OilPaintPreview: { preview_image=OilPaintImage(thumbnail,(double) radius,(double) sigma, exception); (void) FormatLocaleString(label,MagickPathExtent,"charcoal %gx%g", radius,sigma); break; } case CharcoalDrawingPreview: { preview_image=CharcoalImage(thumbnail,(double) radius,(double) sigma, exception); (void) FormatLocaleString(label,MagickPathExtent,"charcoal %gx%g", radius,sigma); break; } case JPEGPreview: { char filename[MagickPathExtent]; int file; MagickBooleanType status; preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; preview_info->quality=(size_t) percentage; (void) FormatLocaleString(factor,MagickPathExtent,"%.20g",(double) preview_info->quality); file=AcquireUniqueFileResource(filename); if (file != -1) file=close(file)-1; (void) FormatLocaleString(preview_image->filename,MagickPathExtent, "jpeg:%s",filename); status=WriteImage(preview_info,preview_image,exception); if (status != MagickFalse) { Image *quality_image; (void) CopyMagickString(preview_info->filename, preview_image->filename,MagickPathExtent); quality_image=ReadImage(preview_info,exception); if (quality_image != (Image *) NULL) { preview_image=DestroyImage(preview_image); preview_image=quality_image; } } (void) RelinquishUniqueFileResource(preview_image->filename); if ((GetBlobSize(preview_image)/1024) >= 1024) (void) FormatLocaleString(label,MagickPathExtent,"quality %s\n%gmb ", factor,(double) ((MagickOffsetType) GetBlobSize(preview_image))/ 1024.0/1024.0); else if (GetBlobSize(preview_image) >= 1024) (void) FormatLocaleString(label,MagickPathExtent, "quality %s\n%gkb ",factor,(double) ((MagickOffsetType) GetBlobSize(preview_image))/1024.0); else (void) FormatLocaleString(label,MagickPathExtent, "quality %s\n%.20gb ",factor,(double) ((MagickOffsetType) GetBlobSize(thumbnail))); break; } } thumbnail=DestroyImage(thumbnail); percentage+=12.5; radius+=0.5; sigma+=0.25; if (preview_image == (Image *) NULL) break; preview_image->alpha_trait=UndefinedPixelTrait; (void) DeleteImageProperty(preview_image,"label"); (void) SetImageProperty(preview_image,"label",label,exception); AppendImageToList(&images,preview_image); proceed=SetImageProgress(image,PreviewImageTag,(MagickOffsetType) i, NumberTiles); if (proceed == MagickFalse) break; } if (images == (Image *) NULL) { preview_info=DestroyImageInfo(preview_info); return((Image *) NULL); } /* Create the montage. */ montage_info=CloneMontageInfo(preview_info,(MontageInfo *) NULL); (void) CopyMagickString(montage_info->filename,image->filename, MagickPathExtent); montage_info->shadow=MagickTrue; (void) CloneString(&montage_info->tile,"3x3"); (void) CloneString(&montage_info->geometry,DefaultPreviewGeometry); (void) CloneString(&montage_info->frame,DefaultTileFrame); montage_image=MontageImages(images,montage_info,exception); montage_info=DestroyMontageInfo(montage_info); images=DestroyImageList(images); if (montage_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); if (montage_image->montage != (char *) NULL) { /* Free image directory. */ montage_image->montage=(char *) RelinquishMagickMemory( montage_image->montage); if (image->directory != (char *) NULL) montage_image->directory=(char *) RelinquishMagickMemory( montage_image->directory); } preview_info=DestroyImageInfo(preview_info); return(montage_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R o t a t i o n a l B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RotationalBlurImage() applies a radial blur to the image. % % Andrew Protano contributed this effect. % % The format of the RotationalBlurImage method is: % % Image *RotationalBlurImage(const Image *image,const double angle, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o angle: the angle of the radial blur. % % o blur: the blur. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *RotationalBlurImage(const Image *image,const double angle, ExceptionInfo *exception) { CacheView *blur_view, *image_view, *radial_view; double blur_radius, *cos_theta, offset, *sin_theta, theta; Image *blur_image; MagickBooleanType status; MagickOffsetType progress; PointInfo blur_center; ssize_t i; size_t n; ssize_t y; /* Allocate blur image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) blur_image=AccelerateRotationalBlurImage(image,angle,exception); if (blur_image != (Image *) NULL) return(blur_image); #endif blur_image=CloneImage(image,0,0,MagickTrue,exception); if (blur_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(blur_image,DirectClass,exception) == MagickFalse) { blur_image=DestroyImage(blur_image); return((Image *) NULL); } blur_center.x=(double) (image->columns-1)/2.0; blur_center.y=(double) (image->rows-1)/2.0; blur_radius=hypot(blur_center.x,blur_center.y); n=(size_t) fabs(4.0*DegreesToRadians(angle)*sqrt((double) blur_radius)+2UL); theta=DegreesToRadians(angle)/(double) (n-1); cos_theta=(double *) AcquireQuantumMemory((size_t) n,sizeof(*cos_theta)); sin_theta=(double *) AcquireQuantumMemory((size_t) n,sizeof(*sin_theta)); if ((cos_theta == (double *) NULL) || (sin_theta == (double *) NULL)) { if (cos_theta != (double *) NULL) cos_theta=(double *) RelinquishMagickMemory(cos_theta); if (sin_theta != (double *) NULL) sin_theta=(double *) RelinquishMagickMemory(sin_theta); blur_image=DestroyImage(blur_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } offset=theta*(double) (n-1)/2.0; for (i=0; i < (ssize_t) n; i++) { cos_theta[i]=cos((double) (theta*i-offset)); sin_theta[i]=sin((double) (theta*i-offset)); } /* Radial blur image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); radial_view=AcquireVirtualCacheView(image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,blur_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double radius; PointInfo center; ssize_t i; size_t step; center.x=(double) x-blur_center.x; center.y=(double) y-blur_center.y; radius=hypot((double) center.x,center.y); if (radius == 0) step=1; else { step=(size_t) (blur_radius/radius); if (step == 0) step=1; else if (step >= n) step=n-1; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double gamma, pixel; PixelChannel channel; PixelTrait blur_traits, traits; const Quantum *magick_restrict r; ssize_t j; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); blur_traits=GetPixelChannelTraits(blur_image,channel); if ((traits == UndefinedPixelTrait) || (blur_traits == UndefinedPixelTrait)) continue; if ((blur_traits & CopyPixelTrait) != 0) { SetPixelChannel(blur_image,channel,p[i],q); continue; } gamma=0.0; pixel=0.0; if ((GetPixelChannelTraits(image,AlphaPixelChannel) == UndefinedPixelTrait) || (channel == AlphaPixelChannel)) { for (j=0; j < (ssize_t) n; j+=(ssize_t) step) { r=GetCacheViewVirtualPixels(radial_view, (ssize_t) (blur_center.x+ center.x*cos_theta[j]-center.y*sin_theta[j]+0.5),(ssize_t) (blur_center.y+center.x*sin_theta[j]+center.y*cos_theta[j]+0.5), 1,1,exception); if (r == (const Quantum *) NULL) { status=MagickFalse; continue; } pixel+=r[i]; gamma++; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); continue; } for (j=0; j < (ssize_t) n; j+=(ssize_t) step) { double alpha; r=GetCacheViewVirtualPixels(radial_view, (ssize_t) (blur_center.x+ center.x*cos_theta[j]-center.y*sin_theta[j]+0.5),(ssize_t) (blur_center.y+center.x*sin_theta[j]+center.y*cos_theta[j]+0.5), 1,1,exception); if (r == (const Quantum *) NULL) { status=MagickFalse; continue; } alpha=(double) QuantumScale*GetPixelAlpha(image,r); pixel+=alpha*r[i]; gamma+=alpha; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(blur_image); } if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,BlurImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_view=DestroyCacheView(blur_view); radial_view=DestroyCacheView(radial_view); image_view=DestroyCacheView(image_view); cos_theta=(double *) RelinquishMagickMemory(cos_theta); sin_theta=(double *) RelinquishMagickMemory(sin_theta); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e l e c t i v e B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SelectiveBlurImage() selectively blur pixels within a contrast threshold. % It is similar to the unsharpen mask that sharpens everything with contrast % above a certain threshold. % % The format of the SelectiveBlurImage method is: % % Image *SelectiveBlurImage(const Image *image,const double radius, % const double sigma,const double threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o threshold: only pixels within this contrast threshold are included % in the blur operation. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SelectiveBlurImage(const Image *image,const double radius, const double sigma,const double threshold,ExceptionInfo *exception) { #define SelectiveBlurImageTag "SelectiveBlur/Image" CacheView *blur_view, *image_view, *luminance_view; Image *blur_image, *luminance_image; MagickBooleanType status; MagickOffsetType progress; MagickRealType *kernel; ssize_t i; size_t width; ssize_t center, j, u, v, y; /* Initialize blur image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=GetOptimalKernelWidth1D(radius,sigma); kernel=(MagickRealType *) MagickAssumeAligned(AcquireAlignedMemory((size_t) width,width*sizeof(*kernel))); if (kernel == (MagickRealType *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); j=(ssize_t) (width-1)/2; i=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) kernel[i++]=(MagickRealType) (exp(-((double) u*u+v*v)/(2.0*MagickSigma* MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); } if (image->debug != MagickFalse) { char format[MagickPathExtent], *message; const MagickRealType *k; ssize_t u, v; (void) LogMagickEvent(TransformEvent,GetMagickModule(), " SelectiveBlurImage with %.20gx%.20g kernel:",(double) width,(double) width); message=AcquireString(""); k=kernel; for (v=0; v < (ssize_t) width; v++) { *message='\0'; (void) FormatLocaleString(format,MagickPathExtent,"%.20g: ",(double) v); (void) ConcatenateString(&message,format); for (u=0; u < (ssize_t) width; u++) { (void) FormatLocaleString(format,MagickPathExtent,"%+f ",(double) *k++); (void) ConcatenateString(&message,format); } (void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message); } message=DestroyString(message); } blur_image=CloneImage(image,0,0,MagickTrue,exception); if (blur_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(blur_image,DirectClass,exception) == MagickFalse) { blur_image=DestroyImage(blur_image); kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); return((Image *) NULL); } luminance_image=CloneImage(image,0,0,MagickTrue,exception); if (luminance_image == (Image *) NULL) { blur_image=DestroyImage(blur_image); kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); return((Image *) NULL); } status=TransformImageColorspace(luminance_image,GRAYColorspace,exception); if (status == MagickFalse) { luminance_image=DestroyImage(luminance_image); blur_image=DestroyImage(blur_image); kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); return((Image *) NULL); } /* Threshold blur image. */ status=MagickTrue; progress=0; center=(ssize_t) (GetPixelChannels(image)*(image->columns+width)* ((width-1)/2L)+GetPixelChannels(image)*((width-1)/2L)); image_view=AcquireVirtualCacheView(image,exception); luminance_view=AcquireVirtualCacheView(luminance_image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,blur_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double contrast; MagickBooleanType sync; const Quantum *magick_restrict l, *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) (width-1)/2L),y-(ssize_t) ((width-1)/2L),image->columns+width,width,exception); l=GetCacheViewVirtualPixels(luminance_view,-((ssize_t) (width-1)/2L),y- (ssize_t) ((width-1)/2L),luminance_image->columns+width,width,exception); q=QueueCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (l == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double intensity; ssize_t i; intensity=GetPixelIntensity(image,p+center); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait blur_traits, traits; const MagickRealType *magick_restrict k; const Quantum *magick_restrict luminance_pixels, *magick_restrict pixels; ssize_t u; ssize_t v; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); blur_traits=GetPixelChannelTraits(blur_image,channel); if ((traits == UndefinedPixelTrait) || (blur_traits == UndefinedPixelTrait)) continue; if ((blur_traits & CopyPixelTrait) != 0) { SetPixelChannel(blur_image,channel,p[center+i],q); continue; } k=kernel; pixel=0.0; pixels=p; luminance_pixels=l; gamma=0.0; if ((blur_traits & BlendPixelTrait) == 0) { for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,luminance_pixels)- intensity; if (fabs(contrast) < threshold) { pixel+=(*k)*pixels[i]; gamma+=(*k); } k++; pixels+=GetPixelChannels(image); luminance_pixels+=GetPixelChannels(luminance_image); } pixels+=GetPixelChannels(image)*image->columns; luminance_pixels+=GetPixelChannels(luminance_image)* luminance_image->columns; } if (fabs((double) gamma) < MagickEpsilon) { SetPixelChannel(blur_image,channel,p[center+i],q); continue; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); continue; } for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(image,pixels)-intensity; if (fabs(contrast) < threshold) { alpha=(double) (QuantumScale*GetPixelAlpha(image,pixels)); pixel+=(*k)*alpha*pixels[i]; gamma+=(*k)*alpha; } k++; pixels+=GetPixelChannels(image); luminance_pixels+=GetPixelChannels(luminance_image); } pixels+=GetPixelChannels(image)*image->columns; luminance_pixels+=GetPixelChannels(luminance_image)* luminance_image->columns; } if (fabs((double) gamma) < MagickEpsilon) { SetPixelChannel(blur_image,channel,p[center+i],q); continue; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(blur_image,channel,ClampToQuantum(gamma*pixel),q); } p+=GetPixelChannels(image); l+=GetPixelChannels(luminance_image); q+=GetPixelChannels(blur_image); } sync=SyncCacheViewAuthenticPixels(blur_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SelectiveBlurImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_image->type=image->type; blur_view=DestroyCacheView(blur_view); luminance_view=DestroyCacheView(luminance_view); image_view=DestroyCacheView(image_view); luminance_image=DestroyImage(luminance_image); kernel=(MagickRealType *) RelinquishAlignedMemory(kernel); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShadeImage() shines a distant light on an image to create a % three-dimensional effect. You control the positioning of the light with % azimuth and elevation; azimuth is measured in degrees off the x axis % and elevation is measured in pixels above the Z axis. % % The format of the ShadeImage method is: % % Image *ShadeImage(const Image *image,const MagickBooleanType gray, % const double azimuth,const double elevation,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o gray: A value other than zero shades the intensity of each pixel. % % o azimuth, elevation: Define the light source direction. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShadeImage(const Image *image,const MagickBooleanType gray, const double azimuth,const double elevation,ExceptionInfo *exception) { #define GetShadeIntensity(image,pixel) \ ClampPixel(GetPixelIntensity((image),(pixel))) #define ShadeImageTag "Shade/Image" CacheView *image_view, *shade_view; Image *linear_image, *shade_image; MagickBooleanType status; MagickOffsetType progress; PrimaryInfo light; ssize_t y; /* Initialize shaded image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); linear_image=CloneImage(image,0,0,MagickTrue,exception); shade_image=CloneImage(image,0,0,MagickTrue,exception); if ((linear_image == (Image *) NULL) || (shade_image == (Image *) NULL)) { if (linear_image != (Image *) NULL) linear_image=DestroyImage(linear_image); if (shade_image != (Image *) NULL) shade_image=DestroyImage(shade_image); return((Image *) NULL); } if (SetImageStorageClass(shade_image,DirectClass,exception) == MagickFalse) { linear_image=DestroyImage(linear_image); shade_image=DestroyImage(shade_image); return((Image *) NULL); } /* Compute the light vector. */ light.x=(double) QuantumRange*cos(DegreesToRadians(azimuth))* cos(DegreesToRadians(elevation)); light.y=(double) QuantumRange*sin(DegreesToRadians(azimuth))* cos(DegreesToRadians(elevation)); light.z=(double) QuantumRange*sin(DegreesToRadians(elevation)); /* Shade image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(linear_image,exception); shade_view=AcquireAuthenticCacheView(shade_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(linear_image,shade_image,linear_image->rows,1) #endif for (y=0; y < (ssize_t) linear_image->rows; y++) { double distance, normal_distance, shade; PrimaryInfo normal; const Quantum *magick_restrict center, *magick_restrict p, *magick_restrict post, *magick_restrict pre; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-1,y-1,linear_image->columns+2,3, exception); q=QueueCacheViewAuthenticPixels(shade_view,0,y,shade_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } /* Shade this row of pixels. */ normal.z=2.0*(double) QuantumRange; /* constant Z of surface normal */ for (x=0; x < (ssize_t) linear_image->columns; x++) { ssize_t i; /* Determine the surface normal and compute shading. */ pre=p+GetPixelChannels(linear_image); center=pre+(linear_image->columns+2)*GetPixelChannels(linear_image); post=center+(linear_image->columns+2)*GetPixelChannels(linear_image); normal.x=(double) ( GetShadeIntensity(linear_image,pre-GetPixelChannels(linear_image))+ GetShadeIntensity(linear_image,center-GetPixelChannels(linear_image))+ GetShadeIntensity(linear_image,post-GetPixelChannels(linear_image))- GetShadeIntensity(linear_image,pre+GetPixelChannels(linear_image))- GetShadeIntensity(linear_image,center+GetPixelChannels(linear_image))- GetShadeIntensity(linear_image,post+GetPixelChannels(linear_image))); normal.y=(double) ( GetShadeIntensity(linear_image,post-GetPixelChannels(linear_image))+ GetShadeIntensity(linear_image,post)+ GetShadeIntensity(linear_image,post+GetPixelChannels(linear_image))- GetShadeIntensity(linear_image,pre-GetPixelChannels(linear_image))- GetShadeIntensity(linear_image,pre)- GetShadeIntensity(linear_image,pre+GetPixelChannels(linear_image))); if ((fabs(normal.x) <= MagickEpsilon) && (fabs(normal.y) <= MagickEpsilon)) shade=light.z; else { shade=0.0; distance=normal.x*light.x+normal.y*light.y+normal.z*light.z; if (distance > MagickEpsilon) { normal_distance=normal.x*normal.x+normal.y*normal.y+ normal.z*normal.z; if (normal_distance > (MagickEpsilon*MagickEpsilon)) shade=distance/sqrt((double) normal_distance); } } for (i=0; i < (ssize_t) GetPixelChannels(linear_image); i++) { PixelChannel channel; PixelTrait shade_traits, traits; channel=GetPixelChannelChannel(linear_image,i); traits=GetPixelChannelTraits(linear_image,channel); shade_traits=GetPixelChannelTraits(shade_image,channel); if ((traits == UndefinedPixelTrait) || (shade_traits == UndefinedPixelTrait)) continue; if ((shade_traits & CopyPixelTrait) != 0) { SetPixelChannel(shade_image,channel,center[i],q); continue; } if ((traits & UpdatePixelTrait) == 0) { SetPixelChannel(shade_image,channel,center[i],q); continue; } if (gray != MagickFalse) { SetPixelChannel(shade_image,channel,ClampToQuantum(shade),q); continue; } SetPixelChannel(shade_image,channel,ClampToQuantum(QuantumScale*shade* center[i]),q); } p+=GetPixelChannels(linear_image); q+=GetPixelChannels(shade_image); } if (SyncCacheViewAuthenticPixels(shade_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ShadeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } shade_view=DestroyCacheView(shade_view); image_view=DestroyCacheView(image_view); linear_image=DestroyImage(linear_image); if (status == MagickFalse) shade_image=DestroyImage(shade_image); return(shade_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a r p e n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SharpenImage() sharpens the image. We convolve the image with a Gaussian % operator of the given radius and standard deviation (sigma). For % reasonable results, radius should be larger than sigma. Use a radius of 0 % and SharpenImage() selects a suitable radius for you. % % Using a separable kernel would be faster, but the negative weights cancel % out on the corners of the kernel producing often undesirable ringing in the % filtered result; this can be avoided by using a 2D gaussian shaped image % sharpening kernel instead. % % The format of the SharpenImage method is: % % Image *SharpenImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Laplacian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SharpenImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { double gamma, normalize; Image *sharp_image; KernelInfo *kernel_info; ssize_t i; size_t width; ssize_t j, u, v; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=GetOptimalKernelWidth2D(radius,sigma); kernel_info=AcquireKernelInfo((const char *) NULL,exception); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(kernel_info,0,sizeof(*kernel_info)); kernel_info->width=width; kernel_info->height=width; kernel_info->x=(ssize_t) (width-1)/2; kernel_info->y=(ssize_t) (width-1)/2; kernel_info->signature=MagickCoreSignature; kernel_info->values=(MagickRealType *) MagickAssumeAligned( AcquireAlignedMemory(kernel_info->width,kernel_info->height* sizeof(*kernel_info->values))); if (kernel_info->values == (MagickRealType *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } normalize=0.0; j=(ssize_t) (kernel_info->width-1)/2; i=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel_info->values[i]=(MagickRealType) (-exp(-((double) u*u+v*v)/(2.0* MagickSigma*MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); normalize+=kernel_info->values[i]; i++; } } kernel_info->values[i/2]=(double) ((-2.0)*normalize); normalize=0.0; for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) normalize+=kernel_info->values[i]; gamma=PerceptibleReciprocal(normalize); for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) kernel_info->values[i]*=gamma; sharp_image=ConvolveImage(image,kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); return(sharp_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S p r e a d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SpreadImage() is a special effects method that randomly displaces each % pixel in a square area defined by the radius parameter. % % The format of the SpreadImage method is: % % Image *SpreadImage(const Image *image, % const PixelInterpolateMethod method,const double radius, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: intepolation method. % % o radius: choose a random pixel in a neighborhood of this extent. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SpreadImage(const Image *image, const PixelInterpolateMethod method,const double radius, ExceptionInfo *exception) { #define SpreadImageTag "Spread/Image" CacheView *image_view, *spread_view; Image *spread_image; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; size_t width; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Initialize spread image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); spread_image=CloneImage(image,0,0,MagickTrue,exception); if (spread_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(spread_image,DirectClass,exception) == MagickFalse) { spread_image=DestroyImage(spread_image); return((Image *) NULL); } /* Spread image. */ status=MagickTrue; progress=0; width=GetOptimalKernelWidth1D(radius,0.5); random_info=AcquireRandomInfoThreadSet(); image_view=AcquireVirtualCacheView(image,exception); spread_view=AcquireAuthenticCacheView(spread_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,spread_image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(spread_view,0,y,spread_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { PointInfo point; point.x=GetPseudoRandomValue(random_info[id]); point.y=GetPseudoRandomValue(random_info[id]); status=InterpolatePixelChannels(image,image_view,spread_image,method, (double) x+width*(point.x-0.5),(double) y+width*(point.y-0.5),q, exception); if (status == MagickFalse) break; q+=GetPixelChannels(spread_image); } if (SyncCacheViewAuthenticPixels(spread_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SpreadImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } spread_view=DestroyCacheView(spread_view); image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) spread_image=DestroyImage(spread_image); return(spread_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n s h a r p M a s k I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnsharpMaskImage() sharpens one or more image channels. We convolve the % image with a Gaussian operator of the given radius and standard deviation % (sigma). For reasonable results, radius should be larger than sigma. Use a % radius of 0 and UnsharpMaskImage() selects a suitable radius for you. % % The format of the UnsharpMaskImage method is: % % Image *UnsharpMaskImage(const Image *image,const double radius, % const double sigma,const double amount,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o gain: the percentage of the difference between the original and the % blur image that is added back into the original. % % o threshold: the threshold in pixels needed to apply the diffence gain. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *UnsharpMaskImage(const Image *image,const double radius, const double sigma,const double gain,const double threshold, ExceptionInfo *exception) { #define SharpenImageTag "Sharpen/Image" CacheView *image_view, *unsharp_view; Image *unsharp_image; MagickBooleanType status; MagickOffsetType progress; double quantum_threshold; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); /* This kernel appears to be broken. #if defined(MAGICKCORE_OPENCL_SUPPORT) unsharp_image=AccelerateUnsharpMaskImage(image,radius,sigma,gain,threshold, exception); if (unsharp_image != (Image *) NULL) return(unsharp_image); #endif */ unsharp_image=BlurImage(image,radius,sigma,exception); if (unsharp_image == (Image *) NULL) return((Image *) NULL); quantum_threshold=(double) QuantumRange*threshold; /* Unsharp-mask image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); unsharp_view=AcquireAuthenticCacheView(unsharp_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,unsharp_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(unsharp_view,0,y,unsharp_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double pixel; PixelChannel channel; PixelTrait traits, unsharp_traits; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); unsharp_traits=GetPixelChannelTraits(unsharp_image,channel); if ((traits == UndefinedPixelTrait) || (unsharp_traits == UndefinedPixelTrait)) continue; if ((unsharp_traits & CopyPixelTrait) != 0) { SetPixelChannel(unsharp_image,channel,p[i],q); continue; } pixel=p[i]-(double) GetPixelChannel(unsharp_image,channel,q); if (fabs(2.0*pixel) < quantum_threshold) pixel=(double) p[i]; else pixel=(double) p[i]+gain*pixel; SetPixelChannel(unsharp_image,channel,ClampToQuantum(pixel),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(unsharp_image); } if (SyncCacheViewAuthenticPixels(unsharp_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SharpenImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } unsharp_image->type=image->type; unsharp_view=DestroyCacheView(unsharp_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) unsharp_image=DestroyImage(unsharp_image); return(unsharp_image); }
parallel-left-looking.h
#ifndef __PARALLEL_LEFT_LOOKING_H__ #define __PARALLEL_LEFT_LOOKING_H__ #include <omp.h> #include "../matrix-formats/matrix-formats.h" #include "elimitate-variables.h" #include "eliminate-branches.h" #include "super-nodes.h" namespace __core__ { namespace __linear_algebra__ { namespace __cholesky__ { template <typename T=void,typename IT=void,typename Allocator=void> void choleskyLeftLookingP(MatrixCXSHandler<T,IT> L,MatrixCXSHandler<T,IT> A,MatrixCXSHandler<IT,IT> RP,LRTree<IT,IT,Allocator,int>& tree,LRTree<IT,SuperNode,Allocator,int>& supernodetree, ArrayHandler<IT,IT> p,std::vector<ArrayHandler<T,IT>>& c,int threadnum=4){ std::vector<int> __dummy__(supernodetree.size()+10,0); int *ptr=__dummy__.data(); #pragma omp parallel num_threads(threadnum) shared(L,A,RP,tree,supernodetree,p,c) { #pragma omp single { int node=(*supernodetree).left_child; bool down=true; size_t i=0; while((i++)<supernodetree.size()) { if(down) while(supernodetree[node].left_child!=supernodetree.invalidPos) node=supernodetree[node].left_child; down=false; #pragma omp task depend(out:ptr[supernodetree[node].key]) depend(in:ptr[supernodetree[node].value.parent]) { for(auto j=supernodetree[node].value.nodes.begin();j!=supernodetree[node].value.nodes.end();++j) eliminateBranch(L,A,RP,tree,tree[*j],p,c); } if(supernodetree[node].right_sibling!=supernodetree.invalidPos) { node=supernodetree[node].right_sibling; down=true; } else node=supernodetree[node].parent; if(node==0||node==supernodetree.invalidPos) break; } } } } template <typename T=void,typename IT=void,typename Allocator=void> void choleskyLeftLookingPT(MatrixCXSHandler<T,IT> L,MatrixCXSHandler<T,IT> A,MatrixCXSHandler<IT,IT> RP,LRTree<IT,IT,Allocator,int>& tree,LRTree<IT,SuperNode,Allocator,int>& supernodetree, ArrayHandler<IT,IT> p,std::vector<ArrayHandler<T,IT>>& c,int threadnum=4){ std::vector<int> __dummy__(supernodetree.size()+10,0); int *ptr=__dummy__.data(); #pragma omp parallel num_threads(threadnum) shared(L,A,RP,tree,supernodetree,p,c) { #pragma omp single { int node=(*supernodetree).left_child; bool down=true; size_t i=0; while((i++)<supernodetree.size()) { if(down) while(supernodetree[node].left_child!=supernodetree.invalidPos) node=supernodetree[node].left_child; down=false; #pragma omp task depend(out:ptr[supernodetree[node].key]) depend(in:ptr[supernodetree[node].value.parent]) { supernodetree[node].value.time=0; supernodetree[node].value.processor=omp_get_thread_num(); cpu_timer timer; timer.start(); for(auto j=supernodetree[node].value.nodes.begin();j!=supernodetree[node].value.nodes.end();++j) eliminateBranch(L,A,RP,tree,tree[*j],p,c,supernodetree[node].value.processor); timer.stop(); supernodetree[node].value.time=timer.elapsed_time(); } if(supernodetree[node].right_sibling!=supernodetree.invalidPos) { node=supernodetree[node].right_sibling; down=true; } else node=supernodetree[node].parent; if(node==0||node==supernodetree.invalidPos) break; } } } } //template <int threadnum=4,typename T=void,typename IT=void,typename Allocator=void> //void choleskyLeftLookingP(MatrixCXSHandler<T,IT> L,MatrixCXSHandler<T,IT> A,MatrixCXSHandler<IT,IT> RP,LRTree<IT,IT,Allocator,int>& tree,LRTree<IT,SuperNode,Allocator,int>& supernodetree, // ArrayHandler<IT,IT> p,ArrayHandler<T,IT> c){ // int node=(*supernodetree).left_child; // bool down=true; // size_t i=0; // while((i++)<supernodetree.size()) { // if(down) // while(supernodetree[node].left_child!=supernodetree.invalidPos) // node=supernodetree[node].left_child; // down=false; // for(auto j=supernodetree[node].value.nodes.begin();j!=supernodetree[node].value.nodes.end();++j) { // eliminateBranch(L,A,RP,tree,tree[*j],p,c); // } // if(supernodetree[node].right_sibling!=supernodetree.invalidPos) { // node=supernodetree[node].right_sibling; // down=true; // } // else // node=supernodetree[node].parent; // if(node==0||node==supernodetree.invalidPos) // break; // } //} } } } #endif
block_vector.h
/* Copyright (c) 2020, VSB - Technical University of Ostrava and Graz University of Technology All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of VSB - Technical University of Ostrava and Graz University of Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VSB - TECHNICAL UNIVERSITY OF OSTRAVA AND GRAZ UNIVERSITY OF TECHNOLOGY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** @file vector.h * @brief Contains a class representing a block vector, i.e. a vector of scalars * partitioned into blocks. * @note updated documentation */ #ifndef INCLUDE_BESTHEA_BLOCK_VECTOR_H_ #define INCLUDE_BESTHEA_BLOCK_VECTOR_H_ #include "besthea/settings.h" #include "besthea/vector.h" #include <cmath> #include <iostream> #include <vector> namespace besthea { namespace linear_algebra { class block_vector; } } /** * Class representing a block vector, i.e. a vector of scalars partitioned into * blocks. */ class besthea::linear_algebra::block_vector { public: using vector_type = besthea::linear_algebra::vector; //!< Vector type. /** * Constructor. */ block_vector( ); /** * Copy constructor. * @param[in] that Vector to be copied. */ block_vector( const block_vector & that ); /** * Constructs a block vector with an initializer list. All @p n_blocks have * the same size and elements as the provided list. * @param[in] n_blocks Number of blocks. * @param[in] list Initializer list for vector. */ block_vector( lo n_blocks, std::initializer_list< sc > list ); /** * Constructs a vector with a given number of blocks of given size. * @param[in] n_blocks Number of blocks. * @param[in] size Size of each block. * @param[in] zero Initialize to 0 if true. */ block_vector( lo n_blocks, lo size, bool zero = true ); ~block_vector( ); /** * Returns a reference to a single block. * @param[in] d Index of the block. */ vector_type & get_block( lo d ) { return _data[ d ]; } /** * Returns a reference to a single block. * @param[in] d Index of the block. */ const vector_type & get_block( lo d ) const { return _data[ d ]; } /** * @brief Returns the i-th element of the d-th block. * @param[in] d Block index. * @param[in] i Element index. */ sc get( lo d, lo i ) const { return _data[ d ][ i ]; } /** * Returns the number of blocks. */ lo get_n_blocks( ) const { return _n_blocks; } /** * Returns the size of a single block. */ lo get_size_of_block( ) const { return _size; } /** * Returns the size of the whole vector, i.e. the total number of elements. */ lo size( ) const { return _n_blocks * _size; } /** * Resizes the block vector by changing the number of blocks. * @param[in] n_blocks New number of blocks. */ void resize( lo n_blocks ) { _data.resize( n_blocks ); _data.shrink_to_fit( ); _n_blocks = n_blocks; } /** * Resizes all blocks of the block vector. * @param[in] size New size of each block. * @param[in] zero If true, all blocks are filled with zeros. */ void resize_blocks( lo size, bool zero = true ) { for ( vector_type & v : _data ) { v.resize( size, zero ); } _size = size; } /*! * @brief Sets the i-th element of the d-th block. * @param[in] d Block index. * @param[in] i Element index. * @param[in] value Value to be set. */ void set( lo d, lo i, sc value ) { _data[ d ][ i ] = value; } /*! * @brief Adds a value atomically(!) to a single element of a single block. * @param[in] d Block index. * @param[in] i Element index. * @param[in] value Value to be added. */ void add_atomic( lo d, lo i, sc value ) { #pragma omp atomic update _data[ d ][ i ] += value; } /*! * @brief Adds a value to a single element of a single block. * @param[in] d Block index. * @param[in] i Element index. * @param[in] value Value to be added. */ void add( lo d, lo i, sc value ) { _data[ d ][ i ] += value; } /** * Copies data from another block vector. * @param[in] that Vector to be copied. */ void copy( const block_vector & that ); /*! * @brief Copies data from a raw array. * @param[in] n_blocks Number of blocks. * @param[in] size Size of each block. * @param[in] data Array to copy from. Contains all elements, block by block. * @note If @p n_blocks and @p size are different from the member variables * @p _n_blocks and @p _size, respectively, the block vector is resized * appropriately. * @warning The source array has to contain at least @p n_blocks * @p size * elements. */ void copy_from_raw( lo n_blocks, lo size, const sc * data ); /*! * @brief Copies data to a raw array. * @param[in,out] data Array to copy to. Is filled with all elements, block by * block. * @warning The array's size has to be at least @p _n_blocks * @p _size. */ void copy_to_raw( sc * data ) const; /*! * @brief Copies data from a raw vector. * @param[in] n_blocks Number of blocks. * @param[in] size Size of each block. * @param[in] data Vector to copy from. Contains all elements, block by block. * @note If @p n_blocks and @p size are different from the member variables * @p _n_blocks and @p _size, respectively, the block vector is resized * appropriately. * @warning The source vector has to contain at least @p n_blocks * @p size * elements. */ void copy_from_vector( lo n_blocks, lo size, const vector_type & data ); /*! * @brief Copies data to a raw vector. * @param[in,out] data Vector to copy to. Is filled with all elements, block * by block. * @warning The target vector has to contain at least * @p _n_blocks * @p _size elements. */ void copy_to_vector( vector_type & data ) const; /*! * @brief Vector addition: this += alpha * v. * @param[in] v Block vector with the same number and size of blocks. * @param[in] alpha Scaling factor. */ void add( block_vector const & v, sc alpha = 1.0 ) { for ( lo i = 0; i < _n_blocks; ++i ) { _data[ i ].add( v._data[ i ], alpha ); } } /*! * @brief Fills the block vector with the given value. * @param[in] value Value to fill the blocks with. */ void fill( sc value ) { for ( lo i = 0; i < _n_blocks; ++i ) { _data[ i ].fill( value ); } } /*! * @brief Returns the euclidean dot product. * @param[in] v Second block vector for dot product. * @warning Dimension of the second block vector have to agree! */ sc dot( block_vector const & v ) const { sc val = 0.0; for ( lo i = 0; i < _n_blocks; ++i ) { val += _data[ i ].dot( v.get_block( i ) ); } return val; } /*! * @brief Returns the Euclidean norm of the vector. * @return Euclidean norm of the vector. */ sc norm( ) const { return std::sqrt( this->dot( *this ) ); } /*! * @brief Scales the vector by a given scalar. * @param[in] alpha Scaling factor. */ void scale( sc alpha ) { for ( auto & it : _data ) { it.scale( alpha ); } } /*! * @brief Prints the vector. * @param[in] stream Stream into which the vector is printed. */ void print( std::ostream & stream = std::cout ) const; /** * Prints info on the object. */ void print_info( ) const { std::cout << "besthea::linear_algebra::block_vector" << std::endl; std::cout << " number of blocks: " << _data.size( ) << std::endl; std::cout << " dimension of each block: " << _data[ 0 ].size( ) << std::endl; } protected: lo _n_blocks; //!< number of blocks lo _size; //!< size of each block. std::vector< vector_type > _data; //!< raw data }; #endif /* INCLUDE_BESTHEA_BLOCK_VECTOR_H_ */
SuperRayGenerator.h
/* * Copyright(c) 2016, Youngsun Kwon, Donghyuk Kim, and Sung-eui Yoon, KAIST * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met : * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and / or other materials provided with the distribution. * * Neither the name of SuperRay nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef OCTOMAP_SUPERRAY_SUPERRAY_GENERATOR_H #define OCTOMAP_SUPERRAY_SUPERRAY_GENERATOR_H #include <octomap/octomap_types.h> #include <octomap/OcTreeKey.h> #include <octomap/Pointcloud.h> #include <octomap_superray/SuperRayCloud.h> #ifdef _OPENMP #include <omp.h> #pragma omp declare reduction (merge : std::vector<octomap::SuperRay> : omp_out.insert(omp_out.end(), omp_in.begin(), omp_in.end())) #endif namespace octomap{ class SuperRayGenerator{ public: SuperRayGenerator(const double _resolution, const unsigned int _tree_max_val, const int _threshold = 0); ~SuperRayGenerator() {}; void GenerateSuperRay(const octomap::Pointcloud& _pc, const octomap::point3d& _origin, SuperRayCloud& _srcloud); protected: struct VoxelInfo; struct Axis3D; octomap::point3d originW; // origin point in World Space octomap::OcTreeKey originKey; // origin key // constants for generating super rays double RESOLUTION; // resolution double RESOLUTION_FACTOR; // 1.0 / resolution unsigned int TREE_MAX_VAL; // offset unsigned int THRESHOLD; // threshold for limiting to generate super rays for each voxel // Functions for generating super rays void GenerateSuperRay(const point3d_collection& _pointlist, std::vector<SuperRay>& _srcloud); void GenerateSuperRay2D(const point3d_collection& _pointlist, Axis3D& _axis, VoxelInfo& _voxelinfo, std::vector<SuperRay>& _srcloud); void GenerateSuperRay3D(const point3d_collection& _pointlist, Axis3D& _axis, VoxelInfo& _voxelinfo, std::vector<SuperRay>& _srcloud); // Function for generating mapping line in 2-D double GenerateMappingLine(VoxelInfo& _voxelinfo, const unsigned int& _axisX, const unsigned int& _axisY, std::vector<double>& _mappingPlane); // Utility functions typedef unordered_ns::unordered_map<octomap::OcTreeKey, std::vector<octomap::point3d>, octomap::OcTreeKey::KeyHash> Voxelized_Pointclouds; void ComputeAxis(const octomap::point3d& _min, const octomap::point3d& _max, Axis3D& _axis); // Re-implmentation for Key / coordinate conversion functions inline octomap::OcTreeKey coordToKey(const octomap::point3d& coord) const { return octomap::OcTreeKey(coordToKey(coord(0)), coordToKey(coord(1)), coordToKey(coord(2))); } inline octomap::key_type coordToKey(double coordinate) const { return ((int)floor(RESOLUTION_FACTOR * coordinate)) + TREE_MAX_VAL; } // Structures that represents the traversal information struct VoxelInfo{ VoxelInfo(void) {}; // Voxel Info. octomap::point3d minW; // min position of voxel octomap::point3d maxW; // max position of voxel octomap::OcTreeKey voxelKey; // key of voxel }; struct Axis3D{ Axis3D(void) : axisU(0), axisV(1), axisK(2) {}; unsigned int axisU; // Nearest Axis unsigned int axisV; // unsigned int axisK; // Farthest Axis }; }; } #endif
integral_parallel1.c
#include<stdio.h> #include<omp.h> #define NUM_THREADS 4 static long num_steps = 100000; double step; int main(){ int i, nthreads; double pi, sum[NUM_THREADS], init_time, finish_time; step = 1.0 / (double)num_steps; init_time = omp_get_wtime(); omp_set_num_threads(NUM_THREADS); #pragma omp parallel { int i, id, nthrds; double x; id = omp_get_thread_num(); nthrds = omp_get_num_threads(); if (id == 0) nthreads = nthrds; for (i=id, sum[id]=0.0 ; i<num_steps ; i=i+nthrds){ x = (i+0.5)*step; sum[id] += 4.0/(1.0+x*x); } } finish_time = omp_get_wtime()-init_time; for (i=0, pi=0.0 ; i < nthreads; i++) pi += sum[i]*step; printf("PI = %f\n", pi); printf("Time = %f\n", finish_time); }
GB_unop__erf_fp64_fp64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__erf_fp64_fp64) // op(A') function: GB (_unop_tran__erf_fp64_fp64) // C type: double // A type: double // cast: double cij = aij // unaryop: cij = erf (aij) #define GB_ATYPE \ double #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = erf (x) ; // casting #define GB_CAST(z, aij) \ double z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ double aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = aij ; \ Cx [pC] = erf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ERF || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__erf_fp64_fp64) ( double *Cx, // Cx and Ax may be aliased const double *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; double z = aij ; Cx [p] = erf (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; double aij = Ax [p] ; double z = aij ; Cx [p] = erf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__erf_fp64_fp64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
Microemulsion.h
// // Created by tommaso on 08/08/18. // #ifndef ACTIVE_MICROEMULSION_MICROEMULSION_H #define ACTIVE_MICROEMULSION_MICROEMULSION_H #include "../Grid/Grid.h" #include "../Logger/Logger.h" #include <cmath> #include <functional> #include <random> #include "../Utils/RandomGenerator.h" class Microemulsion { public: static const int colourStride = 5; private: Grid &grid; Logger &logger; double omega, deltaEmin; static std::mt19937 randomGenerator; #pragma omp threadprivate(randomGenerator) static std::mt19937_64 randomGenerator_64; //#pragma omp threadprivate(randomGenerator_64) std::uniform_real_distribution<double> uniformProbabilityDistribution; std::uniform_int_distribution<int> coloursDistribution; double dtChem, kOn, kOff, kChromPlus, kChromMinus, kRnaPlus, kRnaMinusRbp, kRnaMinusTxn, kRnaTransfer; bool isBoundarySticky; public: Microemulsion(Grid &grid, double omega, Logger &logger, double deltaTChem, double kOn, double kOff, double kChromPlus, double kChromMinus, double kRnaPlus, double kRnaMinus, double kRnaTransfer, bool isBoundarySticky); void setDtChem(double dtChem); void setKOn(double kOn); void setKOff(double kOff); void setKChromPlus(double kChromPlus); void setKChromMinus(double kChromMinus); void setKRnaPlus(double kRnaPlus); void setKRnaMinusRbp(double kRnaMinusRbp); void setKRnaMinusTxn(double kRnaMinusTxn); void setKRnaTransfer(double kRnaTransfer); /** * Attempts a random swap between two neighbouring cells on the grid. * @return True if the swap was performed. */ bool performRandomSwap(); /** * Attempts the given amount of swaps and returns how many actually done. * @param rounds The number of swaps to attempt. * @return The number of swaps successfully performed. */ unsigned int performRandomSwaps(unsigned int rounds); /** * Perform the chemical reactions on the entire grid. * @return The total number of chemical changes. */ unsigned int performChemicalReactions(); /** * Switch the given chain to the transcribable state. * @param targetChains */ void enablePermissivityOnChains(std::set<ChainId> targetChains); void disablePermissivityOnChains(std::set<ChainId> targetChains); void setTranscriptionInhibitionOnChains(const std::set<ChainId> &targetChains, const TranscriptionInhibition &inhibition) const; void enableTranscribabilityOnChains(std::set<ChainId> targetChains); void disableTranscribabilityOnChains(std::set<ChainId> targetChains); void setTranscribabilityOnChains(const std::set<ChainId> &targetChains, const Transcribability &transcribability) const; private: double computePartialDifferentialEnergy(int x, int y, int nx, int ny); double computeSwappedPartialDifferentialEnergy(int x, int y, int nx, int ny); inline double computePairEnergy(int x, int y, int nx, int ny) { // If the species is different, return omega return omega * doesPairRequireEnergyCost(x, y, nx, ny); } bool doesPairRequireEnergyCost(int x, int y, int nx, int ny) const; inline double computeSwapProbability(double deltaEnergy) { return std::exp(deltaEmin - deltaEnergy); // The below is here just as a reminder for possible future tests // double prob = std::exp(-deltaEnergy); // return fmin(prob, 1); } inline bool randomChoiceWithProbability(double probability) { return (uniformProbabilityDistribution(randomGenerator) < probability); } bool isSwapBlockedByStickyBoundary(int x, int y, int nx, int ny); bool isSwapAllowedByChainsAndMeaningful(int x, int y, int nx, int ny); bool isDiagonalSwapAllowedByChains(int x, int y, int nx, int ny, std::vector<std::reference_wrapper<ChainProperties>> &chains, std::vector<std::reference_wrapper<ChainProperties>> &nChains, int dx, int dy); bool isHorizontalSwapAllowedByChains(int x, int y, int nx, int ny, std::vector<std::reference_wrapper<ChainProperties>> &chains, std::vector<std::reference_wrapper<ChainProperties>> &nChains, int dx); bool isVerticalSwapAllowedByChains(int x, int y, int nx, int ny, std::vector<std::reference_wrapper<ChainProperties>> &chains, std::vector<std::reference_wrapper<ChainProperties>> &nChains, int dy); bool isSwapAllowedByChainNeighboursInDiagonalCase(int x, int y, int dx, int dy, ChainProperties &chainProperties); bool isSwapAllowedByChainNeighboursInHorizontalCase(int x, int y, int dx, ChainProperties &chainProperties); bool isSwapAllowedByChainNeighboursInVerticalCase(int x, int y, int dy, ChainProperties &chainProperties); // If reaction causes a change in chemical properties, return True. bool performChemicalReactionsProductionTransfer(int column, int row); bool performChemicalReactionsDecay(int column, int row); bool performActivitySwitchingReaction(CellData &cellData, double reactionRatePlus, double reactionRateMinus); bool performRnaAccumulationReaction(CellData &cellData, double reactionRatePlus); bool performRnaDecayReaction(CellData &cellData, double reactionRateMinus); RnaCounter performRnaTransferReaction(int column, int row, double transferRate); bool performTranscribabilitySwitchingReaction(CellData &cellData, double reactionRatePlus, double reactionRateMinus); bool performRandomSwap(int x, int y); }; #endif //ACTIVE_MICROEMULSION_MICROEMULSION_H
VoxelBlockGridImpl.h
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ---------------------------------------------------------------------------- #include <atomic> #include <cmath> #include "open3d/core/Dispatch.h" #include "open3d/core/Dtype.h" #include "open3d/core/MemoryManager.h" #include "open3d/core/SizeVector.h" #include "open3d/core/Tensor.h" #include "open3d/core/hashmap/Dispatch.h" #include "open3d/t/geometry/Utility.h" #include "open3d/t/geometry/kernel/GeometryIndexer.h" #include "open3d/t/geometry/kernel/GeometryMacros.h" #include "open3d/t/geometry/kernel/VoxelBlockGrid.h" #include "open3d/utility/Logging.h" #include "open3d/utility/Timer.h" namespace open3d { namespace t { namespace geometry { namespace kernel { namespace voxel_grid { using index_t = int; using ArrayIndexer = TArrayIndexer<index_t>; #if defined(__CUDACC__) void GetVoxelCoordinatesAndFlattenedIndicesCUDA #else void GetVoxelCoordinatesAndFlattenedIndicesCPU #endif (const core::Tensor& buf_indices, const core::Tensor& block_keys, core::Tensor& voxel_coords, core::Tensor& flattened_indices, index_t resolution, float voxel_size) { core::Device device = buf_indices.GetDevice(); const index_t* buf_indices_ptr = buf_indices.GetDataPtr<index_t>(); const index_t* block_key_ptr = block_keys.GetDataPtr<index_t>(); float* voxel_coords_ptr = voxel_coords.GetDataPtr<float>(); int64_t* flattened_indices_ptr = flattened_indices.GetDataPtr<int64_t>(); index_t n = flattened_indices.GetLength(); ArrayIndexer voxel_indexer({resolution, resolution, resolution}); index_t resolution3 = resolution * resolution * resolution; core::ParallelFor(device, n, [=] OPEN3D_DEVICE(index_t workload_idx) { index_t block_idx = buf_indices_ptr[workload_idx / resolution3]; index_t voxel_idx = workload_idx % resolution3; index_t block_key_offset = block_idx * 3; index_t xb = block_key_ptr[block_key_offset + 0]; index_t yb = block_key_ptr[block_key_offset + 1]; index_t zb = block_key_ptr[block_key_offset + 2]; index_t xv, yv, zv; voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv); float x = (xb * resolution + xv) * voxel_size; float y = (yb * resolution + yv) * voxel_size; float z = (zb * resolution + zv) * voxel_size; flattened_indices_ptr[workload_idx] = block_idx * resolution3 + voxel_idx; index_t voxel_coords_offset = workload_idx * 3; voxel_coords_ptr[voxel_coords_offset + 0] = x; voxel_coords_ptr[voxel_coords_offset + 1] = y; voxel_coords_ptr[voxel_coords_offset + 2] = z; }); } inline OPEN3D_DEVICE index_t DeviceGetLinearIdx(index_t xo, index_t yo, index_t zo, index_t curr_block_idx, index_t resolution, const ArrayIndexer& nb_block_masks_indexer, const ArrayIndexer& nb_block_indices_indexer) { index_t xn = (xo + resolution) % resolution; index_t yn = (yo + resolution) % resolution; index_t zn = (zo + resolution) % resolution; index_t dxb = Sign(xo - xn); index_t dyb = Sign(yo - yn); index_t dzb = Sign(zo - zn); index_t nb_idx = (dxb + 1) + (dyb + 1) * 3 + (dzb + 1) * 9; bool block_mask_i = *nb_block_masks_indexer.GetDataPtr<bool>(curr_block_idx, nb_idx); if (!block_mask_i) return -1; index_t block_idx_i = *nb_block_indices_indexer.GetDataPtr<index_t>( curr_block_idx, nb_idx); return (((block_idx_i * resolution) + zn) * resolution + yn) * resolution + xn; } template <typename tsdf_t> inline OPEN3D_DEVICE void DeviceGetNormal( const tsdf_t* tsdf_base_ptr, index_t xo, index_t yo, index_t zo, index_t curr_block_idx, float* n, index_t resolution, const ArrayIndexer& nb_block_masks_indexer, const ArrayIndexer& nb_block_indices_indexer) { auto GetLinearIdx = [&] OPEN3D_DEVICE(index_t xo, index_t yo, index_t zo) -> index_t { return DeviceGetLinearIdx(xo, yo, zo, curr_block_idx, resolution, nb_block_masks_indexer, nb_block_indices_indexer); }; index_t vxp = GetLinearIdx(xo + 1, yo, zo); index_t vxn = GetLinearIdx(xo - 1, yo, zo); index_t vyp = GetLinearIdx(xo, yo + 1, zo); index_t vyn = GetLinearIdx(xo, yo - 1, zo); index_t vzp = GetLinearIdx(xo, yo, zo + 1); index_t vzn = GetLinearIdx(xo, yo, zo - 1); if (vxp >= 0 && vxn >= 0) n[0] = tsdf_base_ptr[vxp] - tsdf_base_ptr[vxn]; if (vyp >= 0 && vyn >= 0) n[1] = tsdf_base_ptr[vyp] - tsdf_base_ptr[vyn]; if (vzp >= 0 && vzn >= 0) n[2] = tsdf_base_ptr[vzp] - tsdf_base_ptr[vzn]; }; template <typename input_depth_t, typename input_color_t, typename tsdf_t, typename weight_t, typename color_t> #if defined(__CUDACC__) void IntegrateCUDA #else void IntegrateCPU #endif (const core::Tensor& depth, const core::Tensor& color, const core::Tensor& indices, const core::Tensor& block_keys, TensorMap& block_value_map, const core::Tensor& depth_intrinsic, const core::Tensor& color_intrinsic, const core::Tensor& extrinsics, index_t resolution, float voxel_size, float sdf_trunc, float depth_scale, float depth_max) { // Parameters index_t resolution2 = resolution * resolution; index_t resolution3 = resolution2 * resolution; TransformIndexer transform_indexer(depth_intrinsic, extrinsics, voxel_size); TransformIndexer colormap_indexer( color_intrinsic, core::Tensor::Eye(4, core::Dtype::Float64, core::Device("CPU:0"))); ArrayIndexer voxel_indexer({resolution, resolution, resolution}); ArrayIndexer block_keys_indexer(block_keys, 1); ArrayIndexer depth_indexer(depth, 2); core::Device device = block_keys.GetDevice(); const index_t* indices_ptr = indices.GetDataPtr<index_t>(); if (!block_value_map.Contains("tsdf") || !block_value_map.Contains("weight")) { utility::LogError( "TSDF and/or weight not allocated in blocks, please implement " "customized integration."); } tsdf_t* tsdf_base_ptr = block_value_map.at("tsdf").GetDataPtr<tsdf_t>(); weight_t* weight_base_ptr = block_value_map.at("weight").GetDataPtr<weight_t>(); bool integrate_color = block_value_map.Contains("color") && color.NumElements() > 0; color_t* color_base_ptr = nullptr; ArrayIndexer color_indexer; float color_multiplier = 1.0; if (integrate_color) { color_base_ptr = block_value_map.at("color").GetDataPtr<color_t>(); color_indexer = ArrayIndexer(color, 2); // Float32: [0, 1] -> [0, 255] if (color.GetDtype() == core::Float32) { color_multiplier = 255.0; } } index_t n = indices.GetLength() * resolution3; core::ParallelFor(device, n, [=] OPEN3D_DEVICE(index_t workload_idx) { // Natural index (0, N) -> (block_idx, voxel_idx) index_t block_idx = indices_ptr[workload_idx / resolution3]; index_t voxel_idx = workload_idx % resolution3; /// Coordinate transform // block_idx -> (x_block, y_block, z_block) index_t* block_key_ptr = block_keys_indexer.GetDataPtr<index_t>(block_idx); index_t xb = block_key_ptr[0]; index_t yb = block_key_ptr[1]; index_t zb = block_key_ptr[2]; // voxel_idx -> (x_voxel, y_voxel, z_voxel) index_t xv, yv, zv; voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv); // coordinate in world (in voxel) index_t x = xb * resolution + xv; index_t y = yb * resolution + yv; index_t z = zb * resolution + zv; // coordinate in camera (in voxel -> in meter) float xc, yc, zc, u, v; transform_indexer.RigidTransform(static_cast<float>(x), static_cast<float>(y), static_cast<float>(z), &xc, &yc, &zc); // coordinate in image (in pixel) transform_indexer.Project(xc, yc, zc, &u, &v); if (!depth_indexer.InBoundary(u, v)) { return; } index_t ui = static_cast<index_t>(u); index_t vi = static_cast<index_t>(v); // Associate image workload and compute SDF and // TSDF. float depth = *depth_indexer.GetDataPtr<input_depth_t>(ui, vi) / depth_scale; float sdf = depth - zc; if (depth <= 0 || depth > depth_max || zc <= 0 || sdf < -sdf_trunc) { return; } sdf = sdf < sdf_trunc ? sdf : sdf_trunc; sdf /= sdf_trunc; index_t linear_idx = block_idx * resolution3 + voxel_idx; tsdf_t* tsdf_ptr = tsdf_base_ptr + linear_idx; weight_t* weight_ptr = weight_base_ptr + linear_idx; float inv_wsum = 1.0f / (*weight_ptr + 1); float weight = *weight_ptr; *tsdf_ptr = (weight * (*tsdf_ptr) + sdf) * inv_wsum; if (integrate_color) { color_t* color_ptr = color_base_ptr + 3 * linear_idx; // Unproject ui, vi with depth_intrinsic, then project back with // color_intrinsic float x, y, z; transform_indexer.Unproject(ui, vi, 1.0, &x, &y, &z); float uf, vf; colormap_indexer.Project(x, y, z, &uf, &vf); if (color_indexer.InBoundary(uf, vf)) { ui = round(uf); vi = round(vf); input_color_t* input_color_ptr = color_indexer.GetDataPtr<input_color_t>(ui, vi); for (index_t i = 0; i < 3; ++i) { color_ptr[i] = (weight * color_ptr[i] + input_color_ptr[i] * color_multiplier) * inv_wsum; } } } *weight_ptr = weight + 1; }); #if defined(__CUDACC__) core::cuda::Synchronize(); #endif } #if defined(__CUDACC__) void EstimateRangeCUDA #else void EstimateRangeCPU #endif (const core::Tensor& block_keys, core::Tensor& range_minmax_map, const core::Tensor& intrinsics, const core::Tensor& extrinsics, int h, int w, int down_factor, int64_t block_resolution, float voxel_size, float depth_min, float depth_max) { // TODO(wei): reserve it in a reusable buffer // Every 2 channels: (min, max) int h_down = h / down_factor; int w_down = w / down_factor; range_minmax_map = core::Tensor({h_down, w_down, 2}, core::Float32, block_keys.GetDevice()); NDArrayIndexer range_map_indexer(range_minmax_map, 2); // Every 6 channels: (v_min, u_min, v_max, u_max, z_min, z_max) const int fragment_size = 16; const int frag_buffer_size = 65535; // TODO(wei): explicit buffer core::Tensor fragment_buffer = core::Tensor( {frag_buffer_size, 6}, core::Float32, block_keys.GetDevice()); NDArrayIndexer frag_buffer_indexer(fragment_buffer, 1); NDArrayIndexer block_keys_indexer(block_keys, 1); TransformIndexer w2c_transform_indexer(intrinsics, extrinsics); #if defined(__CUDACC__) core::Tensor count(std::vector<int>{0}, {1}, core::Int32, block_keys.GetDevice()); int* count_ptr = count.GetDataPtr<int>(); #else std::atomic<int> count_atomic(0); std::atomic<int>* count_ptr = &count_atomic; #endif #ifndef __CUDACC__ using std::max; using std::min; #endif // Pass 0: iterate over blocks, fill-in an rendering fragment array core::ParallelFor( block_keys.GetDevice(), block_keys.GetLength(), [=] OPEN3D_DEVICE(int64_t workload_idx) { int* key = block_keys_indexer.GetDataPtr<int>(workload_idx); int u_min = w_down - 1, v_min = h_down - 1, u_max = 0, v_max = 0; float z_min = depth_max, z_max = depth_min; float xc, yc, zc, u, v; // Project 8 corners to low-res image and form a rectangle for (int i = 0; i < 8; ++i) { float xw = (key[0] + ((i & 1) > 0)) * block_resolution * voxel_size; float yw = (key[1] + ((i & 2) > 0)) * block_resolution * voxel_size; float zw = (key[2] + ((i & 4) > 0)) * block_resolution * voxel_size; w2c_transform_indexer.RigidTransform(xw, yw, zw, &xc, &yc, &zc); if (zc <= 0) continue; // Project to the down sampled image buffer w2c_transform_indexer.Project(xc, yc, zc, &u, &v); u /= down_factor; v /= down_factor; v_min = min(static_cast<int>(floorf(v)), v_min); v_max = max(static_cast<int>(ceilf(v)), v_max); u_min = min(static_cast<int>(floorf(u)), u_min); u_max = max(static_cast<int>(ceilf(u)), u_max); z_min = min(z_min, zc); z_max = max(z_max, zc); } v_min = max(0, v_min); v_max = min(h_down - 1, v_max); u_min = max(0, u_min); u_max = min(w_down - 1, u_max); if (v_min >= v_max || u_min >= u_max || z_min >= z_max) return; // Divide the rectangle into small 16x16 fragments int frag_v_count = ceilf(float(v_max - v_min + 1) / float(fragment_size)); int frag_u_count = ceilf(float(u_max - u_min + 1) / float(fragment_size)); int frag_count = frag_v_count * frag_u_count; int frag_count_start = OPEN3D_ATOMIC_ADD(count_ptr, 1); int frag_count_end = frag_count_start + frag_count; if (frag_count_end >= frag_buffer_size) { printf("Fragment count exceeding buffer size, abort!\n"); } int offset = 0; for (int frag_v = 0; frag_v < frag_v_count; ++frag_v) { for (int frag_u = 0; frag_u < frag_u_count; ++frag_u, ++offset) { float* frag_ptr = frag_buffer_indexer.GetDataPtr<float>( frag_count_start + offset); // zmin, zmax frag_ptr[0] = z_min; frag_ptr[1] = z_max; // vmin, umin frag_ptr[2] = v_min + frag_v * fragment_size; frag_ptr[3] = u_min + frag_u * fragment_size; // vmax, umax frag_ptr[4] = min(frag_ptr[2] + fragment_size - 1, static_cast<float>(v_max)); frag_ptr[5] = min(frag_ptr[3] + fragment_size - 1, static_cast<float>(u_max)); } } }); #if defined(__CUDACC__) int frag_count = count[0].Item<int>(); #else int frag_count = (*count_ptr).load(); #endif // Pass 0.5: Fill in range map to prepare for atomic min/max core::ParallelFor(block_keys.GetDevice(), h_down * w_down, [=] OPEN3D_DEVICE(int64_t workload_idx) { int v = workload_idx / w_down; int u = workload_idx % w_down; float* range_ptr = range_map_indexer.GetDataPtr<float>(u, v); range_ptr[0] = depth_max; range_ptr[1] = depth_min; }); // Pass 1: iterate over rendering fragment array, fill-in range core::ParallelFor( block_keys.GetDevice(), frag_count * fragment_size * fragment_size, [=] OPEN3D_DEVICE(int64_t workload_idx) { int frag_idx = workload_idx / (fragment_size * fragment_size); int local_idx = workload_idx % (fragment_size * fragment_size); int dv = local_idx / fragment_size; int du = local_idx % fragment_size; float* frag_ptr = frag_buffer_indexer.GetDataPtr<float>(frag_idx); int v_min = static_cast<int>(frag_ptr[2]); int u_min = static_cast<int>(frag_ptr[3]); int v_max = static_cast<int>(frag_ptr[4]); int u_max = static_cast<int>(frag_ptr[5]); int v = v_min + dv; int u = u_min + du; if (v > v_max || u > u_max) return; float z_min = frag_ptr[0]; float z_max = frag_ptr[1]; float* range_ptr = range_map_indexer.GetDataPtr<float>(u, v); #ifdef __CUDACC__ atomicMinf(&(range_ptr[0]), z_min); atomicMaxf(&(range_ptr[1]), z_max); #else #pragma omp critical(EstimateRangeCPU) { range_ptr[0] = min(z_min, range_ptr[0]); range_ptr[1] = max(z_max, range_ptr[1]); } #endif }); #if defined(__CUDACC__) core::cuda::Synchronize(); #endif } struct MiniVecCache { index_t x; index_t y; index_t z; index_t block_idx; inline index_t OPEN3D_DEVICE Check(index_t xin, index_t yin, index_t zin) { return (xin == x && yin == y && zin == z) ? block_idx : -1; } inline void OPEN3D_DEVICE Update(index_t xin, index_t yin, index_t zin, index_t block_idx_in) { x = xin; y = yin; z = zin; block_idx = block_idx_in; } }; template <typename tsdf_t, typename weight_t, typename color_t> #if defined(__CUDACC__) void RayCastCUDA #else void RayCastCPU #endif (std::shared_ptr<core::HashMap>& hashmap, const TensorMap& block_value_map, const core::Tensor& range, TensorMap& renderings_map, const core::Tensor& intrinsic, const core::Tensor& extrinsics, index_t h, index_t w, index_t block_resolution, float voxel_size, float depth_scale, float depth_min, float depth_max, float weight_threshold, float trunc_voxel_multiplier, int range_map_down_factor) { using Key = utility::MiniVec<index_t, 3>; using Hash = utility::MiniVecHash<index_t, 3>; using Eq = utility::MiniVecEq<index_t, 3>; auto device_hashmap = hashmap->GetDeviceHashBackend(); #if defined(__CUDACC__) auto cuda_hashmap = std::dynamic_pointer_cast<core::StdGPUHashBackend<Key, Hash, Eq>>( device_hashmap); if (cuda_hashmap == nullptr) { utility::LogError( "Unsupported backend: CUDA raycasting only supports STDGPU."); } auto hashmap_impl = cuda_hashmap->GetImpl(); #else auto cpu_hashmap = std::dynamic_pointer_cast<core::TBBHashBackend<Key, Hash, Eq>>( device_hashmap); if (cpu_hashmap == nullptr) { utility::LogError( "Unsupported backend: CPU raycasting only supports TBB."); } auto hashmap_impl = *cpu_hashmap->GetImpl(); #endif core::Device device = hashmap->GetDevice(); ArrayIndexer range_indexer(range, 2); // Geometry ArrayIndexer depth_indexer; ArrayIndexer vertex_indexer; ArrayIndexer normal_indexer; // Diff rendering ArrayIndexer index_indexer; ArrayIndexer mask_indexer; ArrayIndexer interp_ratio_indexer; ArrayIndexer interp_ratio_dx_indexer; ArrayIndexer interp_ratio_dy_indexer; ArrayIndexer interp_ratio_dz_indexer; // Color ArrayIndexer color_indexer; if (!block_value_map.Contains("tsdf") || !block_value_map.Contains("weight")) { utility::LogError( "TSDF and/or weight not allocated in blocks, please implement " "customized integration."); } const tsdf_t* tsdf_base_ptr = block_value_map.at("tsdf").GetDataPtr<tsdf_t>(); const weight_t* weight_base_ptr = block_value_map.at("weight").GetDataPtr<weight_t>(); // Geometry if (renderings_map.Contains("depth")) { depth_indexer = ArrayIndexer(renderings_map.at("depth"), 2); } if (renderings_map.Contains("vertex")) { vertex_indexer = ArrayIndexer(renderings_map.at("vertex"), 2); } if (renderings_map.Contains("normal")) { normal_indexer = ArrayIndexer(renderings_map.at("normal"), 2); } // Diff rendering if (renderings_map.Contains("index")) { index_indexer = ArrayIndexer(renderings_map.at("index"), 2); } if (renderings_map.Contains("mask")) { mask_indexer = ArrayIndexer(renderings_map.at("mask"), 2); } if (renderings_map.Contains("interp_ratio")) { interp_ratio_indexer = ArrayIndexer(renderings_map.at("interp_ratio"), 2); } if (renderings_map.Contains("interp_ratio_dx")) { interp_ratio_dx_indexer = ArrayIndexer(renderings_map.at("interp_ratio_dx"), 2); } if (renderings_map.Contains("interp_ratio_dy")) { interp_ratio_dy_indexer = ArrayIndexer(renderings_map.at("interp_ratio_dy"), 2); } if (renderings_map.Contains("interp_ratio_dz")) { interp_ratio_dz_indexer = ArrayIndexer(renderings_map.at("interp_ratio_dz"), 2); } // Color bool render_color = false; if (block_value_map.Contains("color") && renderings_map.Contains("color")) { render_color = true; color_indexer = ArrayIndexer(renderings_map.at("color"), 2); } const color_t* color_base_ptr = render_color ? block_value_map.at("color").GetDataPtr<color_t>() : nullptr; bool visit_neighbors = render_color || normal_indexer.GetDataPtr() || mask_indexer.GetDataPtr() || index_indexer.GetDataPtr() || interp_ratio_indexer.GetDataPtr() || interp_ratio_dx_indexer.GetDataPtr() || interp_ratio_dy_indexer.GetDataPtr() || interp_ratio_dz_indexer.GetDataPtr(); TransformIndexer c2w_transform_indexer( intrinsic, t::geometry::InverseTransformation(extrinsics)); TransformIndexer w2c_transform_indexer(intrinsic, extrinsics); index_t rows = h; index_t cols = w; index_t n = rows * cols; float block_size = voxel_size * block_resolution; index_t resolution2 = block_resolution * block_resolution; index_t resolution3 = resolution2 * block_resolution; #ifndef __CUDACC__ using std::max; using std::sqrt; #endif core::ParallelFor(device, n, [=] OPEN3D_DEVICE(index_t workload_idx) { auto GetLinearIdxAtP = [&] OPEN3D_DEVICE( index_t x_b, index_t y_b, index_t z_b, index_t x_v, index_t y_v, index_t z_v, core::buf_index_t block_buf_idx, MiniVecCache & cache) -> index_t { index_t x_vn = (x_v + block_resolution) % block_resolution; index_t y_vn = (y_v + block_resolution) % block_resolution; index_t z_vn = (z_v + block_resolution) % block_resolution; index_t dx_b = Sign(x_v - x_vn); index_t dy_b = Sign(y_v - y_vn); index_t dz_b = Sign(z_v - z_vn); if (dx_b == 0 && dy_b == 0 && dz_b == 0) { return block_buf_idx * resolution3 + z_v * resolution2 + y_v * block_resolution + x_v; } else { Key key(x_b + dx_b, y_b + dy_b, z_b + dz_b); index_t block_buf_idx = cache.Check(key[0], key[1], key[2]); if (block_buf_idx < 0) { auto iter = hashmap_impl.find(key); if (iter == hashmap_impl.end()) return -1; block_buf_idx = iter->second; cache.Update(key[0], key[1], key[2], block_buf_idx); } return block_buf_idx * resolution3 + z_vn * resolution2 + y_vn * block_resolution + x_vn; } }; auto GetLinearIdxAtT = [&] OPEN3D_DEVICE( float x_o, float y_o, float z_o, float x_d, float y_d, float z_d, float t, MiniVecCache& cache) -> index_t { float x_g = x_o + t * x_d; float y_g = y_o + t * y_d; float z_g = z_o + t * z_d; // MiniVec coordinate and look up index_t x_b = static_cast<index_t>(floorf(x_g / block_size)); index_t y_b = static_cast<index_t>(floorf(y_g / block_size)); index_t z_b = static_cast<index_t>(floorf(z_g / block_size)); Key key(x_b, y_b, z_b); index_t block_buf_idx = cache.Check(x_b, y_b, z_b); if (block_buf_idx < 0) { auto iter = hashmap_impl.find(key); if (iter == hashmap_impl.end()) return -1; block_buf_idx = iter->second; cache.Update(x_b, y_b, z_b, block_buf_idx); } // Voxel coordinate and look up index_t x_v = index_t((x_g - x_b * block_size) / voxel_size); index_t y_v = index_t((y_g - y_b * block_size) / voxel_size); index_t z_v = index_t((z_g - z_b * block_size) / voxel_size); return block_buf_idx * resolution3 + z_v * resolution2 + y_v * block_resolution + x_v; }; index_t y = workload_idx / cols; index_t x = workload_idx % cols; const float* range = range_indexer.GetDataPtr<float>( x / range_map_down_factor, y / range_map_down_factor); float* depth_ptr = nullptr; float* vertex_ptr = nullptr; float* color_ptr = nullptr; float* normal_ptr = nullptr; int64_t* index_ptr = nullptr; bool* mask_ptr = nullptr; float* interp_ratio_ptr = nullptr; float* interp_ratio_dx_ptr = nullptr; float* interp_ratio_dy_ptr = nullptr; float* interp_ratio_dz_ptr = nullptr; if (vertex_indexer.GetDataPtr()) { vertex_ptr = vertex_indexer.GetDataPtr<float>(x, y); vertex_ptr[0] = 0; vertex_ptr[1] = 0; vertex_ptr[2] = 0; } if (depth_indexer.GetDataPtr()) { depth_ptr = depth_indexer.GetDataPtr<float>(x, y); depth_ptr[0] = 0; } if (normal_indexer.GetDataPtr()) { normal_ptr = normal_indexer.GetDataPtr<float>(x, y); normal_ptr[0] = 0; normal_ptr[1] = 0; normal_ptr[2] = 0; } if (mask_indexer.GetDataPtr()) { mask_ptr = mask_indexer.GetDataPtr<bool>(x, y); #ifdef __CUDACC__ #pragma unroll #endif for (int i = 0; i < 8; ++i) { mask_ptr[i] = false; } } if (index_indexer.GetDataPtr()) { index_ptr = index_indexer.GetDataPtr<int64_t>(x, y); #ifdef __CUDACC__ #pragma unroll #endif for (int i = 0; i < 8; ++i) { index_ptr[i] = 0; } } if (interp_ratio_indexer.GetDataPtr()) { interp_ratio_ptr = interp_ratio_indexer.GetDataPtr<float>(x, y); #ifdef __CUDACC__ #pragma unroll #endif for (int i = 0; i < 8; ++i) { interp_ratio_ptr[i] = 0; } } if (interp_ratio_dx_indexer.GetDataPtr()) { interp_ratio_dx_ptr = interp_ratio_dx_indexer.GetDataPtr<float>(x, y); #ifdef __CUDACC__ #pragma unroll #endif for (int i = 0; i < 8; ++i) { interp_ratio_dx_ptr[i] = 0; } } if (interp_ratio_dy_indexer.GetDataPtr()) { interp_ratio_dy_ptr = interp_ratio_dy_indexer.GetDataPtr<float>(x, y); #ifdef __CUDACC__ #pragma unroll #endif for (int i = 0; i < 8; ++i) { interp_ratio_dy_ptr[i] = 0; } } if (interp_ratio_dz_indexer.GetDataPtr()) { interp_ratio_dz_ptr = interp_ratio_dz_indexer.GetDataPtr<float>(x, y); #ifdef __CUDACC__ #pragma unroll #endif for (int i = 0; i < 8; ++i) { interp_ratio_dz_ptr[i] = 0; } } if (color_indexer.GetDataPtr()) { color_ptr = color_indexer.GetDataPtr<float>(x, y); color_ptr[0] = 0; color_ptr[1] = 0; color_ptr[2] = 0; } float t = range[0]; const float t_max = range[1]; if (t >= t_max) return; // Coordinates in camera and global float x_c = 0, y_c = 0, z_c = 0; float x_g = 0, y_g = 0, z_g = 0; float x_o = 0, y_o = 0, z_o = 0; // Iterative ray intersection check float t_prev = t; float tsdf_prev = -1.0f; float tsdf = 1.0; float sdf_trunc = voxel_size * trunc_voxel_multiplier; float w = 0.0; // Camera origin c2w_transform_indexer.RigidTransform(0, 0, 0, &x_o, &y_o, &z_o); // Direction c2w_transform_indexer.Unproject(static_cast<float>(x), static_cast<float>(y), 1.0f, &x_c, &y_c, &z_c); c2w_transform_indexer.RigidTransform(x_c, y_c, z_c, &x_g, &y_g, &z_g); float x_d = (x_g - x_o); float y_d = (y_g - y_o); float z_d = (z_g - z_o); MiniVecCache cache{0, 0, 0, -1}; bool surface_found = false; while (t < t_max) { index_t linear_idx = GetLinearIdxAtT(x_o, y_o, z_o, x_d, y_d, z_d, t, cache); if (linear_idx < 0) { t_prev = t; t += block_size; } else { tsdf_prev = tsdf; tsdf = tsdf_base_ptr[linear_idx]; w = weight_base_ptr[linear_idx]; if (tsdf_prev > 0 && w >= weight_threshold && tsdf <= 0) { surface_found = true; break; } t_prev = t; float delta = tsdf * sdf_trunc; t += delta < voxel_size ? voxel_size : delta; } } if (surface_found) { float t_intersect = (t * tsdf_prev - t_prev * tsdf) / (tsdf_prev - tsdf); x_g = x_o + t_intersect * x_d; y_g = y_o + t_intersect * y_d; z_g = z_o + t_intersect * z_d; // Trivial vertex assignment if (depth_ptr) { *depth_ptr = t_intersect * depth_scale; } if (vertex_ptr) { w2c_transform_indexer.RigidTransform( x_g, y_g, z_g, vertex_ptr + 0, vertex_ptr + 1, vertex_ptr + 2); } if (!visit_neighbors) return; // Trilinear interpolation // TODO(wei): simplify the flow by splitting the // functions given what is enabled index_t x_b = static_cast<index_t>(floorf(x_g / block_size)); index_t y_b = static_cast<index_t>(floorf(y_g / block_size)); index_t z_b = static_cast<index_t>(floorf(z_g / block_size)); float x_v = (x_g - float(x_b) * block_size) / voxel_size; float y_v = (y_g - float(y_b) * block_size) / voxel_size; float z_v = (z_g - float(z_b) * block_size) / voxel_size; Key key(x_b, y_b, z_b); index_t block_buf_idx = cache.Check(x_b, y_b, z_b); if (block_buf_idx < 0) { auto iter = hashmap_impl.find(key); if (iter == hashmap_impl.end()) return; block_buf_idx = iter->second; cache.Update(x_b, y_b, z_b, block_buf_idx); } index_t x_v_floor = static_cast<index_t>(floorf(x_v)); index_t y_v_floor = static_cast<index_t>(floorf(y_v)); index_t z_v_floor = static_cast<index_t>(floorf(z_v)); float ratio_x = x_v - float(x_v_floor); float ratio_y = y_v - float(y_v_floor); float ratio_z = z_v - float(z_v_floor); float sum_r = 0.0; for (index_t k = 0; k < 8; ++k) { index_t dx_v = (k & 1) > 0 ? 1 : 0; index_t dy_v = (k & 2) > 0 ? 1 : 0; index_t dz_v = (k & 4) > 0 ? 1 : 0; index_t linear_idx_k = GetLinearIdxAtP( x_b, y_b, z_b, x_v_floor + dx_v, y_v_floor + dy_v, z_v_floor + dz_v, block_buf_idx, cache); if (linear_idx_k >= 0 && weight_base_ptr[linear_idx_k] > 0) { float rx = dx_v * (ratio_x) + (1 - dx_v) * (1 - ratio_x); float ry = dy_v * (ratio_y) + (1 - dy_v) * (1 - ratio_y); float rz = dz_v * (ratio_z) + (1 - dz_v) * (1 - ratio_z); float r = rx * ry * rz; if (interp_ratio_ptr) { interp_ratio_ptr[k] = r; } if (mask_ptr) { mask_ptr[k] = true; } if (index_ptr) { index_ptr[k] = linear_idx_k; } float tsdf_k = tsdf_base_ptr[linear_idx_k]; float interp_ratio_dx = ry * rz * (2 * dx_v - 1); float interp_ratio_dy = rx * rz * (2 * dy_v - 1); float interp_ratio_dz = rx * ry * (2 * dz_v - 1); if (interp_ratio_dx_ptr) { interp_ratio_dx_ptr[k] = interp_ratio_dx; } if (interp_ratio_dy_ptr) { interp_ratio_dy_ptr[k] = interp_ratio_dy; } if (interp_ratio_dz_ptr) { interp_ratio_dz_ptr[k] = interp_ratio_dz; } if (normal_ptr) { normal_ptr[0] += interp_ratio_dx * tsdf_k; normal_ptr[1] += interp_ratio_dy * tsdf_k; normal_ptr[2] += interp_ratio_dz * tsdf_k; } if (color_ptr) { index_t color_linear_idx = linear_idx_k * 3; color_ptr[0] += r * color_base_ptr[color_linear_idx + 0]; color_ptr[1] += r * color_base_ptr[color_linear_idx + 1]; color_ptr[2] += r * color_base_ptr[color_linear_idx + 2]; } sum_r += r; } } // loop over 8 neighbors if (sum_r > 0) { sum_r *= 255.0; if (color_ptr) { color_ptr[0] /= sum_r; color_ptr[1] /= sum_r; color_ptr[2] /= sum_r; } if (normal_ptr) { constexpr float EPSILON = 1e-5f; float norm = sqrt(normal_ptr[0] * normal_ptr[0] + normal_ptr[1] * normal_ptr[1] + normal_ptr[2] * normal_ptr[2]); norm = std::max(norm, EPSILON); w2c_transform_indexer.Rotate( -normal_ptr[0] / norm, -normal_ptr[1] / norm, -normal_ptr[2] / norm, normal_ptr + 0, normal_ptr + 1, normal_ptr + 2); } } } // surface-found }); #if defined(__CUDACC__) core::cuda::Synchronize(); #endif } template <typename tsdf_t, typename weight_t, typename color_t> #if defined(__CUDACC__) void ExtractPointCloudCUDA #else void ExtractPointCloudCPU #endif (const core::Tensor& indices, const core::Tensor& nb_indices, const core::Tensor& nb_masks, const core::Tensor& block_keys, const TensorMap& block_value_map, core::Tensor& points, core::Tensor& normals, core::Tensor& colors, index_t resolution, float voxel_size, float weight_threshold, int& valid_size) { core::Device device = block_keys.GetDevice(); // Parameters index_t resolution2 = resolution * resolution; index_t resolution3 = resolution2 * resolution; // Shape / transform indexers, no data involved ArrayIndexer voxel_indexer({resolution, resolution, resolution}); // Real data indexer ArrayIndexer block_keys_indexer(block_keys, 1); ArrayIndexer nb_block_masks_indexer(nb_masks, 2); ArrayIndexer nb_block_indices_indexer(nb_indices, 2); // Plain arrays that does not require indexers const index_t* indices_ptr = indices.GetDataPtr<index_t>(); if (!block_value_map.Contains("tsdf") || !block_value_map.Contains("weight")) { utility::LogError( "TSDF and/or weight not allocated in blocks, please implement " "customized integration."); } const tsdf_t* tsdf_base_ptr = block_value_map.at("tsdf").GetDataPtr<tsdf_t>(); const weight_t* weight_base_ptr = block_value_map.at("weight").GetDataPtr<weight_t>(); const color_t* color_base_ptr = nullptr; if (block_value_map.Contains("color")) { color_base_ptr = block_value_map.at("color").GetDataPtr<color_t>(); } index_t n_blocks = indices.GetLength(); index_t n = n_blocks * resolution3; // Output #if defined(__CUDACC__) core::Tensor count(std::vector<index_t>{0}, {1}, core::Int32, block_keys.GetDevice()); index_t* count_ptr = count.GetDataPtr<index_t>(); #else std::atomic<index_t> count_atomic(0); std::atomic<index_t>* count_ptr = &count_atomic; #endif if (valid_size < 0) { utility::LogDebug( "No estimated max point cloud size provided, using a 2-pass " "estimation. Surface extraction could be slow."); // This pass determines valid number of points. core::ParallelFor(device, n, [=] OPEN3D_DEVICE(index_t workload_idx) { auto GetLinearIdx = [&] OPEN3D_DEVICE( index_t xo, index_t yo, index_t zo, index_t curr_block_idx) -> index_t { return DeviceGetLinearIdx(xo, yo, zo, curr_block_idx, resolution, nb_block_masks_indexer, nb_block_indices_indexer); }; // Natural index (0, N) -> (block_idx, // voxel_idx) index_t workload_block_idx = workload_idx / resolution3; index_t block_idx = indices_ptr[workload_block_idx]; index_t voxel_idx = workload_idx % resolution3; // voxel_idx -> (x_voxel, y_voxel, z_voxel) index_t xv, yv, zv; voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv); index_t linear_idx = block_idx * resolution3 + voxel_idx; float tsdf_o = tsdf_base_ptr[linear_idx]; float weight_o = weight_base_ptr[linear_idx]; if (weight_o <= weight_threshold) return; // Enumerate x-y-z directions for (index_t i = 0; i < 3; ++i) { index_t linear_idx_i = GetLinearIdx(xv + (i == 0), yv + (i == 1), zv + (i == 2), workload_block_idx); if (linear_idx_i < 0) continue; float tsdf_i = tsdf_base_ptr[linear_idx_i]; float weight_i = weight_base_ptr[linear_idx_i]; if (weight_i > weight_threshold && tsdf_i * tsdf_o < 0) { OPEN3D_ATOMIC_ADD(count_ptr, 1); } } }); #if defined(__CUDACC__) valid_size = count[0].Item<index_t>(); count[0] = 0; #else valid_size = (*count_ptr).load(); (*count_ptr) = 0; #endif } if (points.GetLength() == 0) { points = core::Tensor({valid_size, 3}, core::Float32, device); } ArrayIndexer point_indexer(points, 1); // Normals ArrayIndexer normal_indexer; normals = core::Tensor({valid_size, 3}, core::Float32, device); normal_indexer = ArrayIndexer(normals, 1); // This pass extracts exact surface points. // Colors ArrayIndexer color_indexer; if (color_base_ptr) { colors = core::Tensor({valid_size, 3}, core::Float32, device); color_indexer = ArrayIndexer(colors, 1); } core::ParallelFor(device, n, [=] OPEN3D_DEVICE(index_t workload_idx) { auto GetLinearIdx = [&] OPEN3D_DEVICE( index_t xo, index_t yo, index_t zo, index_t curr_block_idx) -> index_t { return DeviceGetLinearIdx(xo, yo, zo, curr_block_idx, resolution, nb_block_masks_indexer, nb_block_indices_indexer); }; auto GetNormal = [&] OPEN3D_DEVICE(index_t xo, index_t yo, index_t zo, index_t curr_block_idx, float* n) { return DeviceGetNormal<tsdf_t>( tsdf_base_ptr, xo, yo, zo, curr_block_idx, n, resolution, nb_block_masks_indexer, nb_block_indices_indexer); }; // Natural index (0, N) -> (block_idx, voxel_idx) index_t workload_block_idx = workload_idx / resolution3; index_t block_idx = indices_ptr[workload_block_idx]; index_t voxel_idx = workload_idx % resolution3; /// Coordinate transform // block_idx -> (x_block, y_block, z_block) index_t* block_key_ptr = block_keys_indexer.GetDataPtr<index_t>(block_idx); index_t xb = block_key_ptr[0]; index_t yb = block_key_ptr[1]; index_t zb = block_key_ptr[2]; // voxel_idx -> (x_voxel, y_voxel, z_voxel) index_t xv, yv, zv; voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv); index_t linear_idx = block_idx * resolution3 + voxel_idx; float tsdf_o = tsdf_base_ptr[linear_idx]; float weight_o = weight_base_ptr[linear_idx]; if (weight_o <= weight_threshold) return; float no[3] = {0}, ne[3] = {0}; // Get normal at origin GetNormal(xv, yv, zv, workload_block_idx, no); index_t x = xb * resolution + xv; index_t y = yb * resolution + yv; index_t z = zb * resolution + zv; // Enumerate x-y-z axis for (index_t i = 0; i < 3; ++i) { index_t linear_idx_i = GetLinearIdx(xv + (i == 0), yv + (i == 1), zv + (i == 2), workload_block_idx); if (linear_idx_i < 0) continue; float tsdf_i = tsdf_base_ptr[linear_idx_i]; float weight_i = weight_base_ptr[linear_idx_i]; if (weight_i > weight_threshold && tsdf_i * tsdf_o < 0) { float ratio = (0 - tsdf_o) / (tsdf_i - tsdf_o); index_t idx = OPEN3D_ATOMIC_ADD(count_ptr, 1); if (idx >= valid_size) { printf("Point cloud size larger than " "estimated, please increase the " "estimation!\n"); return; } float* point_ptr = point_indexer.GetDataPtr<float>(idx); point_ptr[0] = voxel_size * (x + ratio * int(i == 0)); point_ptr[1] = voxel_size * (y + ratio * int(i == 1)); point_ptr[2] = voxel_size * (z + ratio * int(i == 2)); // Get normal at edge and interpolate float* normal_ptr = normal_indexer.GetDataPtr<float>(idx); GetNormal(xv + (i == 0), yv + (i == 1), zv + (i == 2), workload_block_idx, ne); float nx = (1 - ratio) * no[0] + ratio * ne[0]; float ny = (1 - ratio) * no[1] + ratio * ne[1]; float nz = (1 - ratio) * no[2] + ratio * ne[2]; float norm = static_cast<float>( sqrt(nx * nx + ny * ny + nz * nz) + 1e-5); normal_ptr[0] = nx / norm; normal_ptr[1] = ny / norm; normal_ptr[2] = nz / norm; if (color_base_ptr) { float* color_ptr = color_indexer.GetDataPtr<float>(idx); const color_t* color_o_ptr = color_base_ptr + 3 * linear_idx; float r_o = color_o_ptr[0]; float g_o = color_o_ptr[1]; float b_o = color_o_ptr[2]; const color_t* color_i_ptr = color_base_ptr + 3 * linear_idx_i; float r_i = color_i_ptr[0]; float g_i = color_i_ptr[1]; float b_i = color_i_ptr[2]; color_ptr[0] = ((1 - ratio) * r_o + ratio * r_i) / 255.0f; color_ptr[1] = ((1 - ratio) * g_o + ratio * g_i) / 255.0f; color_ptr[2] = ((1 - ratio) * b_o + ratio * b_i) / 255.0f; } } } }); #if defined(__CUDACC__) index_t total_count = count.Item<index_t>(); #else index_t total_count = (*count_ptr).load(); #endif utility::LogDebug("{} vertices extracted", total_count); valid_size = total_count; #if defined(BUILD_CUDA_MODULE) && defined(__CUDACC__) core::cuda::Synchronize(); #endif } template <typename tsdf_t, typename weight_t, typename color_t> #if defined(__CUDACC__) void ExtractTriangleMeshCUDA #else void ExtractTriangleMeshCPU #endif (const core::Tensor& block_indices, const core::Tensor& inv_block_indices, const core::Tensor& nb_block_indices, const core::Tensor& nb_block_masks, const core::Tensor& block_keys, const TensorMap& block_value_map, core::Tensor& vertices, core::Tensor& triangles, core::Tensor& vertex_normals, core::Tensor& vertex_colors, index_t block_resolution, float voxel_size, float weight_threshold, index_t& vertex_count) { core::Device device = block_indices.GetDevice(); index_t resolution = block_resolution; index_t resolution3 = resolution * resolution * resolution; // Shape / transform indexers, no data involved ArrayIndexer voxel_indexer({resolution, resolution, resolution}); index_t n_blocks = static_cast<index_t>(block_indices.GetLength()); // TODO(wei): profile performance by replacing the table to a hashmap. // Voxel-wise mesh info. 4 channels correspond to: // 3 edges' corresponding vertex index + 1 table index. core::Tensor mesh_structure; try { mesh_structure = core::Tensor::Zeros( {n_blocks, resolution, resolution, resolution, 4}, core::Int32, device); } catch (const std::runtime_error&) { utility::LogError( "Unable to allocate assistance mesh structure for Marching " "Cubes with {} active voxel blocks. Please consider using a " "larger voxel size (currently {}) for TSDF integration, or " "using tsdf_volume.cpu() to perform mesh extraction on CPU.", n_blocks, voxel_size); } // Real data indexer ArrayIndexer mesh_structure_indexer(mesh_structure, 4); ArrayIndexer nb_block_masks_indexer(nb_block_masks, 2); ArrayIndexer nb_block_indices_indexer(nb_block_indices, 2); // Plain arrays that does not require indexers const index_t* indices_ptr = block_indices.GetDataPtr<index_t>(); const index_t* inv_indices_ptr = inv_block_indices.GetDataPtr<index_t>(); if (!block_value_map.Contains("tsdf") || !block_value_map.Contains("weight")) { utility::LogError( "TSDF and/or weight not allocated in blocks, please implement " "customized integration."); } const tsdf_t* tsdf_base_ptr = block_value_map.at("tsdf").GetDataPtr<tsdf_t>(); const weight_t* weight_base_ptr = block_value_map.at("weight").GetDataPtr<weight_t>(); const color_t* color_base_ptr = nullptr; if (block_value_map.Contains("color")) { color_base_ptr = block_value_map.at("color").GetDataPtr<color_t>(); } index_t n = n_blocks * resolution3; // Pass 0: analyze mesh structure, set up one-on-one correspondences // from edges to vertices. core::ParallelFor(device, n, [=] OPEN3D_DEVICE(index_t widx) { auto GetLinearIdx = [&] OPEN3D_DEVICE( index_t xo, index_t yo, index_t zo, index_t curr_block_idx) -> index_t { return DeviceGetLinearIdx(xo, yo, zo, curr_block_idx, static_cast<index_t>(resolution), nb_block_masks_indexer, nb_block_indices_indexer); }; // Natural index (0, N) -> (block_idx, voxel_idx) index_t workload_block_idx = widx / resolution3; index_t voxel_idx = widx % resolution3; // voxel_idx -> (x_voxel, y_voxel, z_voxel) index_t xv, yv, zv; voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv); // Check per-vertex sign in the cube to determine cube // type index_t table_idx = 0; for (index_t i = 0; i < 8; ++i) { index_t linear_idx_i = GetLinearIdx(xv + vtx_shifts[i][0], yv + vtx_shifts[i][1], zv + vtx_shifts[i][2], workload_block_idx); if (linear_idx_i < 0) return; float tsdf_i = tsdf_base_ptr[linear_idx_i]; float weight_i = weight_base_ptr[linear_idx_i]; if (weight_i <= weight_threshold) return; table_idx |= ((tsdf_i < 0) ? (1 << i) : 0); } index_t* mesh_struct_ptr = mesh_structure_indexer.GetDataPtr<index_t>( xv, yv, zv, workload_block_idx); mesh_struct_ptr[3] = table_idx; if (table_idx == 0 || table_idx == 255) return; // Check per-edge sign determine the cube type index_t edges_with_vertices = edge_table[table_idx]; for (index_t i = 0; i < 12; ++i) { if (edges_with_vertices & (1 << i)) { index_t xv_i = xv + edge_shifts[i][0]; index_t yv_i = yv + edge_shifts[i][1]; index_t zv_i = zv + edge_shifts[i][2]; index_t edge_i = edge_shifts[i][3]; index_t dxb = xv_i / resolution; index_t dyb = yv_i / resolution; index_t dzb = zv_i / resolution; index_t nb_idx = (dxb + 1) + (dyb + 1) * 3 + (dzb + 1) * 9; index_t block_idx_i = *nb_block_indices_indexer.GetDataPtr<index_t>( workload_block_idx, nb_idx); index_t* mesh_ptr_i = mesh_structure_indexer.GetDataPtr<index_t>( xv_i - dxb * resolution, yv_i - dyb * resolution, zv_i - dzb * resolution, inv_indices_ptr[block_idx_i]); // Non-atomic write, but we are safe mesh_ptr_i[edge_i] = -1; } } }); // Pass 1: determine valid number of vertices (if not preset) #if defined(__CUDACC__) core::Tensor count(std::vector<index_t>{0}, {}, core::Int32, device); index_t* count_ptr = count.GetDataPtr<index_t>(); #else std::atomic<index_t> count_atomic(0); std::atomic<index_t>* count_ptr = &count_atomic; #endif if (vertex_count < 0) { core::ParallelFor(device, n, [=] OPEN3D_DEVICE(index_t widx) { // Natural index (0, N) -> (block_idx, voxel_idx) index_t workload_block_idx = widx / resolution3; index_t voxel_idx = widx % resolution3; // voxel_idx -> (x_voxel, y_voxel, z_voxel) index_t xv, yv, zv; voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv); // Obtain voxel's mesh struct ptr index_t* mesh_struct_ptr = mesh_structure_indexer.GetDataPtr<index_t>( xv, yv, zv, workload_block_idx); // Early quit -- no allocated vertex to compute if (mesh_struct_ptr[0] != -1 && mesh_struct_ptr[1] != -1 && mesh_struct_ptr[2] != -1) { return; } // Enumerate 3 edges in the voxel for (index_t e = 0; e < 3; ++e) { index_t vertex_idx = mesh_struct_ptr[e]; if (vertex_idx != -1) continue; OPEN3D_ATOMIC_ADD(count_ptr, 1); } }); #if defined(__CUDACC__) vertex_count = count.Item<index_t>(); #else vertex_count = (*count_ptr).load(); #endif } utility::LogDebug("Total vertex count = {}", vertex_count); vertices = core::Tensor({vertex_count, 3}, core::Float32, device); vertex_normals = core::Tensor({vertex_count, 3}, core::Float32, device); ArrayIndexer normal_indexer = ArrayIndexer(vertex_normals, 1); ArrayIndexer color_indexer; if (color_base_ptr) { vertex_colors = core::Tensor({vertex_count, 3}, core::Float32, device); color_indexer = ArrayIndexer(vertex_colors, 1); } ArrayIndexer block_keys_indexer(block_keys, 1); ArrayIndexer vertex_indexer(vertices, 1); #if defined(__CUDACC__) count = core::Tensor(std::vector<index_t>{0}, {}, core::Int32, device); count_ptr = count.GetDataPtr<index_t>(); #else (*count_ptr) = 0; #endif // Pass 2: extract vertices. core::ParallelFor(device, n, [=] OPEN3D_DEVICE(index_t widx) { auto GetLinearIdx = [&] OPEN3D_DEVICE( index_t xo, index_t yo, index_t zo, index_t curr_block_idx) -> index_t { return DeviceGetLinearIdx(xo, yo, zo, curr_block_idx, resolution, nb_block_masks_indexer, nb_block_indices_indexer); }; auto GetNormal = [&] OPEN3D_DEVICE(index_t xo, index_t yo, index_t zo, index_t curr_block_idx, float* n) { return DeviceGetNormal<tsdf_t>( tsdf_base_ptr, xo, yo, zo, curr_block_idx, n, resolution, nb_block_masks_indexer, nb_block_indices_indexer); }; // Natural index (0, N) -> (block_idx, voxel_idx) index_t workload_block_idx = widx / resolution3; index_t block_idx = indices_ptr[workload_block_idx]; index_t voxel_idx = widx % resolution3; // block_idx -> (x_block, y_block, z_block) index_t* block_key_ptr = block_keys_indexer.GetDataPtr<index_t>(block_idx); index_t xb = block_key_ptr[0]; index_t yb = block_key_ptr[1]; index_t zb = block_key_ptr[2]; // voxel_idx -> (x_voxel, y_voxel, z_voxel) index_t xv, yv, zv; voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv); // global coordinate (in voxels) index_t x = xb * resolution + xv; index_t y = yb * resolution + yv; index_t z = zb * resolution + zv; // Obtain voxel's mesh struct ptr index_t* mesh_struct_ptr = mesh_structure_indexer.GetDataPtr<index_t>( xv, yv, zv, workload_block_idx); // Early quit -- no allocated vertex to compute if (mesh_struct_ptr[0] != -1 && mesh_struct_ptr[1] != -1 && mesh_struct_ptr[2] != -1) { return; } // Obtain voxel ptr index_t linear_idx = resolution3 * block_idx + voxel_idx; float tsdf_o = tsdf_base_ptr[linear_idx]; float no[3] = {0}, ne[3] = {0}; // Get normal at origin GetNormal(xv, yv, zv, workload_block_idx, no); // Enumerate 3 edges in the voxel for (index_t e = 0; e < 3; ++e) { index_t vertex_idx = mesh_struct_ptr[e]; if (vertex_idx != -1) continue; index_t linear_idx_e = GetLinearIdx(xv + (e == 0), yv + (e == 1), zv + (e == 2), workload_block_idx); OPEN3D_ASSERT(linear_idx_e > 0 && "Internal error: GetVoxelAt returns nullptr."); float tsdf_e = tsdf_base_ptr[linear_idx_e]; float ratio = (0 - tsdf_o) / (tsdf_e - tsdf_o); index_t idx = OPEN3D_ATOMIC_ADD(count_ptr, 1); mesh_struct_ptr[e] = idx; float ratio_x = ratio * index_t(e == 0); float ratio_y = ratio * index_t(e == 1); float ratio_z = ratio * index_t(e == 2); float* vertex_ptr = vertex_indexer.GetDataPtr<float>(idx); vertex_ptr[0] = voxel_size * (x + ratio_x); vertex_ptr[1] = voxel_size * (y + ratio_y); vertex_ptr[2] = voxel_size * (z + ratio_z); // Get normal at edge and interpolate float* normal_ptr = normal_indexer.GetDataPtr<float>(idx); GetNormal(xv + (e == 0), yv + (e == 1), zv + (e == 2), workload_block_idx, ne); float nx = (1 - ratio) * no[0] + ratio * ne[0]; float ny = (1 - ratio) * no[1] + ratio * ne[1]; float nz = (1 - ratio) * no[2] + ratio * ne[2]; float norm = static_cast<float>(sqrt(nx * nx + ny * ny + nz * nz) + 1e-5); normal_ptr[0] = nx / norm; normal_ptr[1] = ny / norm; normal_ptr[2] = nz / norm; if (color_base_ptr) { float* color_ptr = color_indexer.GetDataPtr<float>(idx); float r_o = color_base_ptr[linear_idx * 3 + 0]; float g_o = color_base_ptr[linear_idx * 3 + 1]; float b_o = color_base_ptr[linear_idx * 3 + 2]; float r_e = color_base_ptr[linear_idx_e * 3 + 0]; float g_e = color_base_ptr[linear_idx_e * 3 + 1]; float b_e = color_base_ptr[linear_idx_e * 3 + 2]; color_ptr[0] = ((1 - ratio) * r_o + ratio * r_e) / 255.0f; color_ptr[1] = ((1 - ratio) * g_o + ratio * g_e) / 255.0f; color_ptr[2] = ((1 - ratio) * b_o + ratio * b_e) / 255.0f; } } }); // Pass 3: connect vertices and form triangles. index_t triangle_count = vertex_count * 3; triangles = core::Tensor({triangle_count, 3}, core::Int32, device); ArrayIndexer triangle_indexer(triangles, 1); #if defined(__CUDACC__) count = core::Tensor(std::vector<index_t>{0}, {}, core::Int32, device); count_ptr = count.GetDataPtr<index_t>(); #else (*count_ptr) = 0; #endif core::ParallelFor(device, n, [=] OPEN3D_DEVICE(index_t widx) { // Natural index (0, N) -> (block_idx, voxel_idx) index_t workload_block_idx = widx / resolution3; index_t voxel_idx = widx % resolution3; // voxel_idx -> (x_voxel, y_voxel, z_voxel) index_t xv, yv, zv; voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv); // Obtain voxel's mesh struct ptr index_t* mesh_struct_ptr = mesh_structure_indexer.GetDataPtr<index_t>( xv, yv, zv, workload_block_idx); index_t table_idx = mesh_struct_ptr[3]; if (tri_count[table_idx] == 0) return; for (index_t tri = 0; tri < 16; tri += 3) { if (tri_table[table_idx][tri] == -1) return; index_t tri_idx = OPEN3D_ATOMIC_ADD(count_ptr, 1); for (index_t vertex = 0; vertex < 3; ++vertex) { index_t edge = tri_table[table_idx][tri + vertex]; index_t xv_i = xv + edge_shifts[edge][0]; index_t yv_i = yv + edge_shifts[edge][1]; index_t zv_i = zv + edge_shifts[edge][2]; index_t edge_i = edge_shifts[edge][3]; index_t dxb = xv_i / resolution; index_t dyb = yv_i / resolution; index_t dzb = zv_i / resolution; index_t nb_idx = (dxb + 1) + (dyb + 1) * 3 + (dzb + 1) * 9; index_t block_idx_i = *nb_block_indices_indexer.GetDataPtr<index_t>( workload_block_idx, nb_idx); index_t* mesh_struct_ptr_i = mesh_structure_indexer.GetDataPtr<index_t>( xv_i - dxb * resolution, yv_i - dyb * resolution, zv_i - dzb * resolution, inv_indices_ptr[block_idx_i]); index_t* triangle_ptr = triangle_indexer.GetDataPtr<index_t>(tri_idx); triangle_ptr[2 - vertex] = mesh_struct_ptr_i[edge_i]; } } }); #if defined(__CUDACC__) triangle_count = count.Item<index_t>(); #else triangle_count = (*count_ptr).load(); #endif utility::LogDebug("Total triangle count = {}", triangle_count); triangles = triangles.Slice(0, 0, triangle_count); } } // namespace voxel_grid } // namespace kernel } // namespace geometry } // namespace t } // namespace open3d
dsytrs.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/zhetrs.c, normal z -> d, Fri Sep 28 17:38:07 2018 * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_tuning.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_hetrs * * Solves a system of linear equations A * X = B with LTLt factorization * computed by plasma_dsytrf. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * TODO: only support Lower for now * * @param[in] n * The order of the matrix A. n >= 0. * * @param[in] nrhs * The number of right hand sides, i.e., the number of * columns of the matrix B. nrhs >= 0. * * @param[in,out] A * Details of the LTL factorization of the symmetric matrix A, * as computed by plasma_dsytrf. * * @param[in] lda * The leading dimension of the array A. * * @param[in,out] T * Details of the LU factorization of the band matrix A, as * computed by plasma_dgbtrf. * * @param[in] ldt * The leading dimension of the array T. * * @param[in] ipiv * The pivot indices used for dsytrf; for 1 <= i <= min(m,n), * row i of the matrix was interchanged with row ipiv(i). * * @param[in] ipiv2 * The pivot indices used for dgbtrf; for 1 <= i <= min(m,n), * row i of the matrix was interchanged with row ipiv(i). * * @param[in,out] B * On entry, the n-by-nrhs right hand side matrix B. * On exit, if return value = 0, the n-by-nrhs solution matrix X. * * @param[in] ldb * The leading dimension of the array B. ldb >= max(1,n). * ******************************************************************************* * * @retval PlasmaSuccess successful exit * @retval < 0 if -i, the i-th argument had an illegal value * ******************************************************************************* * * @sa plasma_omp_dsytrs * @sa plasma_chetrs * @sa plasma_dsytrs * @sa plasma_ssytrs * @sa plasma_dsytrf * ******************************************************************************/ int plasma_dsytrs(plasma_enum_t uplo, int n, int nrhs, double *pA, int lda, int *ipiv, double *pT, int ldt, int *ipiv2, double *pB, int ldb) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if (//(uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo (Upper not supported, yet)"); return -1; } if (n < 0) { plasma_error("illegal value of n"); return -2; } if (nrhs < 0) { plasma_error("illegal value of nrhs"); return -5; } if (lda < imax(1, n)) { plasma_error("illegal value of lda"); return -7; } if (ldb < imax(1, n)) { plasma_error("illegal value of ldb"); return -10; } // quick return if (imax(n, nrhs) == 0) return PlasmaSuccess; // Tune parameters. if (plasma->tuning) plasma_tune_trsm(plasma, PlasmaRealDouble, n, n); // Set tiling parameters. int nb = plasma->nb; // Initialize tile matrix descriptors. plasma_desc_t A; plasma_desc_t T; plasma_desc_t B; int tku = (nb+nb+nb-1)/nb; // number of tiles in upper band (not including diagonal) int tkl = (nb+nb-1)/nb; // number of tiles in lower band (not including diagonal) int lm = (tku+tkl+1)*nb; // since we use dgetrf on panel, we pivot back within panel. // this could fill the last tile of the panel, // and we need extra NB space on the bottom int retval; retval = plasma_desc_triangular_create(PlasmaRealDouble, uplo, nb, nb, n, n, 0, 0, n, n, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } retval = plasma_desc_general_band_create(PlasmaRealDouble, PlasmaGeneral, nb, nb, lm, n, 0, 0, n, n, nb, nb, &T); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_band_create() failed"); return retval; } retval = plasma_desc_general_create(PlasmaRealDouble, nb, nb, n, nrhs, 0, 0, n, nrhs, &B); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&A); return retval; } // Initialize sequence. plasma_sequence_t sequence; retval = plasma_sequence_init(&sequence); // Initialize request. plasma_request_t request; retval = plasma_request_init(&request); // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_dtr2desc(pA, lda, A, &sequence, &request); plasma_omp_dpb2desc(pT, ldt, T, &sequence, &request); plasma_omp_dge2desc(pB, ldb, B, &sequence, &request); } #pragma omp parallel #pragma omp master { // Call the tile async function. plasma_omp_dsytrs(uplo, A, ipiv, T, ipiv2, B, &sequence, &request); } #pragma omp parallel #pragma omp master { // Translate back to LAPACK layout. plasma_omp_ddesc2ge(B, pB, ldb, &sequence, &request); } // implicit synchronization // Free matrix A in tile layout. plasma_desc_destroy(&A); plasma_desc_destroy(&T); plasma_desc_destroy(&B); // Return status. int status = sequence.status; return status; } /***************************************************************************//** * * @ingroup plasma_hetrs * * Solves a system of linear equations using previously * computed factorization. * Non-blocking tile version of plasma_dsytrs(). * May return before the computation is finished. * Operates on matrices stored by tiles. * All matrices are passed through descriptors. * All dimensions are taken from the descriptors. * Allows for pipelining of operations at runtime. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * * @param[in] A * The triangular factor U or L from the Cholesky factorization * A = U^T*U or A = L*L^T, computed by plasma_dpotrf. * * @param[in,out] B * On entry, the n-by-nrhs right hand side matrix B. * On exit, if return value = 0, the n-by-nrhs solution matrix X. * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). Check * the sequence->status for errors. * * @param[out] request * Identifies this function call (for exception handling purposes). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_dsytrs * @sa plasma_omp_dsytrs * @sa plasma_omp_chetrs * @sa plasma_omp_dsytrs * @sa plasma_omp_ssytrs * @sa plasma_omp_dsytrf * ******************************************************************************/ void plasma_omp_dsytrs(plasma_enum_t uplo, plasma_desc_t A, int *ipiv, plasma_desc_t T, int *ipiv2, plasma_desc_t B, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if (//(uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo (Upper not supported, yet)"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(B) != PlasmaSuccess) { plasma_error("invalid B"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_fatal_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_fatal_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return if (A.n == 0 || B.n == 0) return; // Call the parallel functions. if (uplo == PlasmaLower) { plasma_desc_t vA; plasma_desc_t vB; // forward-substitution with L if (A.m > A.nb) { vA = plasma_desc_view(A, A.nb, 0, A.m-A.nb, A.n-A.nb); vB = plasma_desc_view(B, B.nb, 0, B.m-B.nb, B.n); plasma_pdgeswp(PlasmaRowwise, B, ipiv, 1, sequence, request); #pragma omp taskwait plasma_pdtrsm(PlasmaLeft, PlasmaLower, PlasmaNoTrans, PlasmaUnit, 1.0, vA, vB, sequence, request); } // solve with band matrix T #pragma omp taskwait plasma_pdtbsm(PlasmaLeft, PlasmaLower, PlasmaNoTrans, PlasmaUnit, 1.0, T, B, ipiv2, sequence, request); plasma_pdtbsm(PlasmaLeft, PlasmaUpper, PlasmaNoTrans, PlasmaNonUnit, 1.0, T, B, ipiv2, sequence, request); // backward-substitution with L^T if (A.m > A.nb) { plasma_pdtrsm(PlasmaLeft, PlasmaLower, PlasmaConjTrans, PlasmaUnit, 1.0, vA, vB, sequence, request); #pragma omp taskwait plasma_pdgeswp(PlasmaRowwise, B, ipiv, -1, sequence, request); } } else { // TODO: upper } }
udr-1.c
/* { dg-do compile } */ /* { dg-options "-fopenmp" } */ struct S {}; void foo (void *, void *); void bar (void *, void *); void baz (void *); #pragma omp declare reduction(+:struct S:foo (&omp_out, &omp_in))initializer(bar(&omp_priv, &omp_orig)) void test (void) { struct S a, b[10]; #pragma omp parallel reduction(+:a) baz (&a); }
jacobi_omp.c
/* * Copyright (c) 2008, BSC (Barcelon Supercomputing Center) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY BSC ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <math.h> #include <time.h> #define NB 256 #define B 32 #define FALSE (0) #define TRUE (1) typedef double fp_type; typedef fp_type *vin; typedef fp_type *vout; typedef fp_type *bin; typedef fp_type *binout; fp_type *A[NB][NB]; fp_type *A_new[NB][NB]; fp_type *tmp[NB][NB]; void alloc_and_genmat() { int init_val, i, j, ii, jj; fp_type *p, *p_new; init_val = 1325; for (ii = 0; ii < NB; ii++) { for (jj = 0; jj < NB; jj++) { A[ii][jj] = (fp_type *)malloc(B * B * sizeof(fp_type)); A_new[ii][jj] = (fp_type *)malloc(B * B * sizeof(fp_type)); tmp[ii][jj] = (fp_type *)malloc(B * B * sizeof(fp_type)); if (A[ii][jj] == NULL || A_new[ii][jj] == NULL || tmp[ii][jj] == NULL) { printf("Out of memory\n"); exit(1); } p = A[ii][jj]; p_new = A_new[ii][jj]; for (i = 0; i < B; i++) { for (j = 0; j < B; j++) { init_val = (3125 * init_val) % 65536; (*p) = (fp_type)((init_val - 32768.0) / 16384.0); (*p_new) = (*p); p++; p_new++; } } } } } long usecs(void) { struct timeval t; gettimeofday(&t, NULL); return t.tv_sec * 1000000 + t.tv_usec; } void clear(vout v) { int i, j, k; for (i = 0; i < B; i++) v[i] = (fp_type)0.0; } void getlastrow(bin A, vout v) { int j; for (j = 0; j < B; j++) v[j] = A[(B - 1) * B + j]; } void getlastcol(bin A, vout v) { int i; for (i = 0; i < B; i++) v[i] = A[i * B + B - 1]; } void getfirstrow(bin A, vout v) { int j; for (j = 0; j < B; j++) v[j] = A[0 * B + j]; } void getfirstcol(bin A, vout v) { int i; for (i = 0; i < B; i++) v[i] = A[i * B + 0]; } void jacobi(vin lefthalo, vin tophalo, vin righthalo, vin bottomhalo, bin A, binout A_new) { int i, j; fp_type tmp; fp_type left, top, right, bottom; for (i = 0; (i < B); i++) { for (j = 0; j < B; j++) { tmp = A[i * B + j]; left = (j == 0 ? lefthalo[j] : A[i * B + j - 1]); top = (i == 0 ? tophalo[i] : A[(i - 1) * B + j]); right = (j == B - 1 ? righthalo[i] : A[i * B + j + 1]); bottom = (i == B - 1 ? bottomhalo[i] : A[(i + 1) * B + j]); A_new[i * B + j] = 0.2 * (A[i * B + j] + left + top + right + bottom); } } } double maxdelta() { double dmax = -__DBL_MAX__; int ii, jj, i, j; #pragma omp parallel for schedule(static) reduction(max: dmax) for (ii = 0; ii < NB; ii++) { for (jj = 0; jj < NB; jj++) { for (i = 0; (i < B); i++) { for (j = 0; j < B; j++) { double diff = fabs(A_new[ii][jj][i * B + j] - A[ii][jj][i * B + j]); if(diff > dmax) dmax = diff; } } } } return dmax; } void compute(int niters) { int iters; int ii, jj; fp_type lefthalo[B], tophalo[B], righthalo[B], bottomhalo[B]; double delta = 2.0; double epsilon = 1e-7; iters = 0; // for (iters = 0; iters < niters; iters++) while(iters < niters) { ++iters; #pragma omp parallel \ private(ii, jj, lefthalo, tophalo, righthalo, bottomhalo) \ shared(A, A_new) { #pragma omp for schedule(static) for (ii = 0; ii < NB; ii++) { for (jj = 0; jj < NB; jj++) { if (ii > 0) getlastrow(A[ii - 1][jj], tophalo); else clear(tophalo); if (jj > 0) getlastcol(A[ii][jj - 1], lefthalo); else clear(lefthalo); if (ii < NB - 1) getfirstrow(A[ii + 1][jj], bottomhalo); else clear(bottomhalo); if (jj < NB - 1) getfirstcol(A[ii][jj + 1], righthalo); else clear(lefthalo); jacobi(lefthalo, tophalo, righthalo, bottomhalo, A[ii][jj], A_new[ii][jj]); } // jj } // ii } // end parallel delta = maxdelta(); printf("iteration %d: delta = %e\n", iters, delta); // yes, this is an inefficient copy // however, the library version requires you to do a copy in this way // on all of the component parts to avoid segmentation fault #pragma omp parallel for schedule(static) shared(A, A_new) for(int i = 0; i < NB; ++i) { for(int j = 0; j < NB; ++j) { for(int k = 0; k < B; ++k) for(int l = 0; l < B; ++l) A[i][j][k * B + l] = A_new[i][j][k * B + l]; } } } // iter } int main(int argc, char *argv[]) { int niters; // pp_time_t tm; // memset( &tm, 0, sizeof(tm) ); struct timespec start, end; if (argc > 1) { niters = atoi(argv[1]); } else niters = 1; alloc_and_genmat(); clock_gettime(CLOCK_MONOTONIC, &start); compute(niters); clock_gettime(CLOCK_MONOTONIC, &end); double time_taken = (end.tv_sec - start.tv_sec) * 1e9; time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9; printf("Running time = %g %s\n", time_taken, "s"); /* FILE *outFile; outFile = fopen("./jacobi_omp_values.txt", "w"); if (outFile == NULL) { fprintf(stderr, "Error writing to file\n"); } else { int ii, jj, i, j; for (ii = 0; ii < NB; ++ii) for (jj = 0; jj < NB; ++jj) for (i = 0; i < B; ++i) for (j = 0; j < B; ++j) fprintf(outFile, "%.15f\n", A[ii][jj][i * B + j]); fclose(outFile); } */ return 0; }
c-tree.h
/* Definitions for C parsing and type checking. Copyright (C) 1987, 1993, 1994, 1995, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef GCC_C_TREE_H #define GCC_C_TREE_H #include "c-common.h" #include "toplev.h" #include "diagnostic.h" /* struct lang_identifier is private to c-decl.c, but langhooks.c needs to know how big it is. This is sanity-checked in c-decl.c. */ #define C_SIZEOF_STRUCT_LANG_IDENTIFIER \ (sizeof (struct c_common_identifier) + 3 * sizeof (void *)) /* Language-specific declaration information. */ struct lang_decl GTY(()) { char dummy; }; /* In a RECORD_TYPE or UNION_TYPE, nonzero if any component is read-only. */ #define C_TYPE_FIELDS_READONLY(TYPE) TREE_LANG_FLAG_1 (TYPE) /* In a RECORD_TYPE or UNION_TYPE, nonzero if any component is volatile. */ #define C_TYPE_FIELDS_VOLATILE(TYPE) TREE_LANG_FLAG_2 (TYPE) /* In a RECORD_TYPE or UNION_TYPE or ENUMERAL_TYPE nonzero if the definition of the type has already started. */ #define C_TYPE_BEING_DEFINED(TYPE) TYPE_LANG_FLAG_0 (TYPE) /* In an incomplete RECORD_TYPE or UNION_TYPE, a list of variable declarations whose type would be completed by completing that type. */ #define C_TYPE_INCOMPLETE_VARS(TYPE) TYPE_VFIELD (TYPE) /* In an IDENTIFIER_NODE, nonzero if this identifier is actually a keyword. C_RID_CODE (node) is then the RID_* value of the keyword, and C_RID_YYCODE is the token number wanted by Yacc. */ #define C_IS_RESERVED_WORD(ID) TREE_LANG_FLAG_0 (ID) struct lang_type GTY(()) { /* In a RECORD_TYPE, a sorted array of the fields of the type. */ struct sorted_fields_type * GTY ((reorder ("resort_sorted_fields"))) s; /* In an ENUMERAL_TYPE, the min and max values. */ tree enum_min; tree enum_max; /* In a RECORD_TYPE, information specific to Objective-C, such as a list of adopted protocols or a pointer to a corresponding @interface. See objc/objc-act.h for details. */ tree objc_info; }; /* Record whether a type or decl was written with nonconstant size. Note that TYPE_SIZE may have simplified to a constant. */ #define C_TYPE_VARIABLE_SIZE(TYPE) TYPE_LANG_FLAG_1 (TYPE) #define C_DECL_VARIABLE_SIZE(TYPE) DECL_LANG_FLAG_0 (TYPE) /* Record whether a typedef for type `int' was actually `signed int'. */ #define C_TYPEDEF_EXPLICITLY_SIGNED(EXP) DECL_LANG_FLAG_1 (EXP) /* For a FUNCTION_DECL, nonzero if it was defined without an explicit return type. */ #define C_FUNCTION_IMPLICIT_INT(EXP) DECL_LANG_FLAG_1 (EXP) /* For a FUNCTION_DECL, nonzero if it was an implicit declaration. */ #define C_DECL_IMPLICIT(EXP) DECL_LANG_FLAG_2 (EXP) /* For FUNCTION_DECLs, evaluates true if the decl is built-in but has been declared. */ #define C_DECL_DECLARED_BUILTIN(EXP) \ DECL_LANG_FLAG_3 (FUNCTION_DECL_CHECK (EXP)) /* For FUNCTION_DECLs, evaluates true if the decl is built-in, has a built-in prototype and does not have a non-built-in prototype. */ #define C_DECL_BUILTIN_PROTOTYPE(EXP) \ DECL_LANG_FLAG_6 (FUNCTION_DECL_CHECK (EXP)) /* Record whether a decl was declared register. This is strictly a front-end flag, whereas DECL_REGISTER is used for code generation; they may differ for structures with volatile fields. */ #define C_DECL_REGISTER(EXP) DECL_LANG_FLAG_4 (EXP) /* Record whether a decl was used in an expression anywhere except an unevaluated operand of sizeof / typeof / alignof. This is only used for functions declared static but not defined, though outside sizeof and typeof it is set for other function decls as well. */ #define C_DECL_USED(EXP) DECL_LANG_FLAG_5 (FUNCTION_DECL_CHECK (EXP)) /* Record whether a label was defined in a statement expression which has finished and so can no longer be jumped to. */ #define C_DECL_UNJUMPABLE_STMT_EXPR(EXP) \ DECL_LANG_FLAG_6 (LABEL_DECL_CHECK (EXP)) /* Record whether a label was the subject of a goto from outside the current level of statement expression nesting and so cannot be defined right now. */ #define C_DECL_UNDEFINABLE_STMT_EXPR(EXP) \ DECL_LANG_FLAG_7 (LABEL_DECL_CHECK (EXP)) /* Record whether a label was defined in the scope of an identifier with variably modified type which has finished and so can no longer be jumped to. */ #define C_DECL_UNJUMPABLE_VM(EXP) \ DECL_LANG_FLAG_3 (LABEL_DECL_CHECK (EXP)) /* Record whether a label was the subject of a goto from outside the current level of scopes of identifiers with variably modified type and so cannot be defined right now. */ #define C_DECL_UNDEFINABLE_VM(EXP) \ DECL_LANG_FLAG_5 (LABEL_DECL_CHECK (EXP)) /* Record whether a variable has been declared threadprivate by #pragma omp threadprivate. */ #define C_DECL_THREADPRIVATE_P(DECL) DECL_LANG_FLAG_3 (VAR_DECL_CHECK (DECL)) /* Nonzero for a decl which either doesn't exist or isn't a prototype. N.B. Could be simplified if all built-in decls had complete prototypes (but this is presently difficult because some of them need FILE*). */ #define C_DECL_ISNT_PROTOTYPE(EXP) \ (EXP == 0 \ || (TYPE_ARG_TYPES (TREE_TYPE (EXP)) == 0 \ && !DECL_BUILT_IN (EXP))) /* For FUNCTION_TYPE, a hidden list of types of arguments. The same as TYPE_ARG_TYPES for functions with prototypes, but created for functions without prototypes. */ #define TYPE_ACTUAL_ARG_TYPES(NODE) TYPE_LANG_SLOT_1 (NODE) /* Record parser information about an expression that is irrelevant for code generation alongside a tree representing its value. */ struct c_expr { /* The value of the expression. */ tree value; /* Record the original binary operator of an expression, which may have been changed by fold, STRING_CST for unparenthesized string constants, or ERROR_MARK for other expressions (including parenthesized expressions). */ enum tree_code original_code; }; /* A kind of type specifier. Note that this information is currently only used to distinguish tag definitions, tag references and typeof uses. */ enum c_typespec_kind { /* A reserved keyword type specifier. */ ctsk_resword, /* A reference to a tag, previously declared, such as "struct foo". This includes where the previous declaration was as a different kind of tag, in which case this is only valid if shadowing that tag in an inner scope. */ ctsk_tagref, /* A reference to a tag, not previously declared in a visible scope. */ ctsk_tagfirstref, /* A definition of a tag such as "struct foo { int a; }". */ ctsk_tagdef, /* A typedef name. */ ctsk_typedef, /* An ObjC-specific kind of type specifier. */ ctsk_objc, /* A typeof specifier. */ ctsk_typeof }; /* A type specifier: this structure is created in the parser and passed to declspecs_add_type only. */ struct c_typespec { /* What kind of type specifier this is. */ enum c_typespec_kind kind; /* The specifier itself. */ tree spec; }; /* A storage class specifier. */ enum c_storage_class { csc_none, csc_auto, csc_extern, csc_register, csc_static, csc_typedef }; /* A type specifier keyword "void", "_Bool", "char", "int", "float", "double", or none of these. */ enum c_typespec_keyword { cts_none, cts_void, cts_bool, cts_char, cts_int, cts_float, cts_double, cts_dfloat32, cts_dfloat64, cts_dfloat128 }; /* A sequence of declaration specifiers in C. */ struct c_declspecs { /* The type specified, if a single type specifier such as a struct, union or enum specifier, typedef name or typeof specifies the whole type, or NULL_TREE if none or a keyword such as "void" or "char" is used. Does not include qualifiers. */ tree type; /* The attributes from a typedef decl. */ tree decl_attr; /* When parsing, the attributes. Outside the parser, this will be NULL; attributes (possibly from multiple lists) will be passed separately. */ tree attrs; /* Any type specifier keyword used such as "int", not reflecting modifiers such as "short", or cts_none if none. */ enum c_typespec_keyword typespec_word; /* The storage class specifier, or csc_none if none. */ enum c_storage_class storage_class; /* Whether any declaration specifiers have been seen at all. */ BOOL_BITFIELD declspecs_seen_p : 1; /* Whether a type specifier has been seen. */ BOOL_BITFIELD type_seen_p : 1; /* Whether something other than a storage class specifier or attribute has been seen. This is used to warn for the obsolescent usage of storage class specifiers other than at the start of the list. (Doing this properly would require function specifiers to be handled separately from storage class specifiers.) */ BOOL_BITFIELD non_sc_seen_p : 1; /* Whether the type is specified by a typedef or typeof name. */ BOOL_BITFIELD typedef_p : 1; /* Whether a struct, union or enum type either had its content defined by a type specifier in the list or was the first visible declaration of its tag. */ BOOL_BITFIELD tag_defined_p : 1; /* Whether the type is explicitly "signed" or specified by a typedef whose type is explicitly "signed". */ BOOL_BITFIELD explicit_signed_p : 1; /* Whether the specifiers include a deprecated typedef. */ BOOL_BITFIELD deprecated_p : 1; /* APPLE LOCAL begin "unavailable" attribute (radar 2809697) */ /* Whether the specifiers include a unavailable typedef. */ BOOL_BITFIELD unavailable_p : 1; /* APPLE LOCAL end "unavailable" attribute (radar 2809697) */ /* Whether the type defaulted to "int" because there were no type specifiers. */ BOOL_BITFIELD default_int_p; /* Whether "long" was specified. */ BOOL_BITFIELD long_p : 1; /* Whether "long" was specified more than once. */ BOOL_BITFIELD long_long_p : 1; /* Whether "short" was specified. */ BOOL_BITFIELD short_p : 1; /* Whether "signed" was specified. */ BOOL_BITFIELD signed_p : 1; /* Whether "unsigned" was specified. */ BOOL_BITFIELD unsigned_p : 1; /* Whether "complex" was specified. */ BOOL_BITFIELD complex_p : 1; /* Whether "inline" was specified. */ BOOL_BITFIELD inline_p : 1; /* Whether "__thread" was specified. */ BOOL_BITFIELD thread_p : 1; /* Whether "const" was specified. */ BOOL_BITFIELD const_p : 1; /* Whether "volatile" was specified. */ BOOL_BITFIELD volatile_p : 1; /* Whether "restrict" was specified. */ BOOL_BITFIELD restrict_p : 1; }; /* The various kinds of declarators in C. */ enum c_declarator_kind { /* An identifier. */ cdk_id, /* A function. */ cdk_function, /* An array. */ cdk_array, /* A pointer. */ cdk_pointer, /* APPLE LOCAL blocks (C++ ch) */ cdk_block_pointer, /* Parenthesized declarator with nested attributes. */ cdk_attrs }; /* Information about the parameters in a function declarator. */ struct c_arg_info { /* A list of parameter decls. */ tree parms; /* A list of structure, union and enum tags defined. */ tree tags; /* A list of argument types to go in the FUNCTION_TYPE. */ tree types; /* A list of non-parameter decls (notably enumeration constants) defined with the parameters. */ tree others; /* A list of VLA sizes from the parameters. In a function definition, these are used to ensure that side-effects in sizes of arrays converted to pointers (such as a parameter int i[n++]) take place; otherwise, they are ignored. */ tree pending_sizes; /* True when these arguments had [*]. */ BOOL_BITFIELD had_vla_unspec : 1; }; /* A declarator. */ struct c_declarator { /* The kind of declarator. */ enum c_declarator_kind kind; /* Except for cdk_id, the contained declarator. For cdk_id, NULL. */ struct c_declarator *declarator; location_t id_loc; /* Currently only set for cdk_id. */ union { /* For identifiers, an IDENTIFIER_NODE or NULL_TREE if an abstract declarator. */ tree id; /* For functions. */ struct c_arg_info *arg_info; /* For arrays. */ struct { /* The array dimension, or NULL for [] and [*]. */ tree dimen; /* The qualifiers inside []. */ int quals; /* The attributes (currently ignored) inside []. */ tree attrs; /* Whether [static] was used. */ BOOL_BITFIELD static_p : 1; /* Whether [*] was used. */ BOOL_BITFIELD vla_unspec_p : 1; } array; /* For pointers, the qualifiers on the pointer type. */ int pointer_quals; /* For attributes. */ tree attrs; } u; }; /* A type name. */ struct c_type_name { /* The declaration specifiers. */ struct c_declspecs *specs; /* The declarator. */ struct c_declarator *declarator; }; /* A parameter. */ struct c_parm { /* The declaration specifiers, minus any prefix attributes. */ struct c_declspecs *specs; /* The attributes. */ tree attrs; /* The declarator. */ struct c_declarator *declarator; }; /* Save and restore the variables in this file and elsewhere that keep track of the progress of compilation of the current function. Used for nested functions. */ struct language_function GTY(()) { struct c_language_function base; tree x_break_label; tree x_cont_label; struct c_switch * GTY((skip)) x_switch_stack; struct c_arg_info * GTY((skip)) arg_info; int returns_value; int returns_null; int returns_abnormally; int warn_about_return_type; }; /* Save lists of labels used or defined in particular contexts. Allocated on the parser obstack. */ struct c_label_list { /* The label at the head of the list. */ tree label; /* The rest of the list. */ struct c_label_list *next; }; /* Statement expression context. */ struct c_label_context_se { /* The labels defined at this level of nesting. */ struct c_label_list *labels_def; /* The labels used at this level of nesting. */ struct c_label_list *labels_used; /* The next outermost context. */ struct c_label_context_se *next; }; /* Context of variably modified declarations. */ struct c_label_context_vm { /* The labels defined at this level of nesting. */ struct c_label_list *labels_def; /* The labels used at this level of nesting. */ struct c_label_list *labels_used; /* The scope of this context. Multiple contexts may be at the same numbered scope, since each variably modified declaration starts a new context. */ unsigned scope; /* The next outermost context. */ struct c_label_context_vm *next; }; /* in c-parser.c */ extern void c_parse_init (void); /* in c-aux-info.c */ extern void gen_aux_info_record (tree, int, int, int); /* in c-decl.c */ extern struct obstack parser_obstack; extern tree c_break_label; extern tree c_cont_label; extern int global_bindings_p (void); extern void push_scope (void); extern tree pop_scope (void); extern void insert_block (tree); extern void c_expand_body (tree); extern void c_init_decl_processing (void); extern void c_dup_lang_specific_decl (tree); extern void c_print_identifier (FILE *, tree, int); extern int quals_from_declspecs (const struct c_declspecs *); extern struct c_declarator *build_array_declarator (tree, struct c_declspecs *, bool, bool); extern tree build_enumerator (tree, tree); extern tree check_for_loop_decls (void); extern void mark_forward_parm_decls (void); extern void declare_parm_level (void); extern void undeclared_variable (tree, location_t); extern tree declare_label (tree); extern tree define_label (location_t, tree); extern void c_maybe_initialize_eh (void); extern void finish_decl (tree, tree, tree); extern tree finish_enum (tree, tree, tree); extern void finish_function (void); extern tree finish_struct (tree, tree, tree); extern struct c_arg_info *get_parm_info (bool); extern tree grokfield (struct c_declarator *, struct c_declspecs *, tree); extern tree groktypename (struct c_type_name *); /* APPLE LOCAL blocks 6339747 */ extern tree grokblockdecl (struct c_declspecs *, struct c_declarator *); extern tree grokparm (const struct c_parm *); extern tree implicitly_declare (tree); extern void keep_next_level (void); extern void pending_xref_error (void); extern void c_push_function_context (struct function *); extern void c_pop_function_context (struct function *); extern void push_parm_decl (const struct c_parm *); extern struct c_declarator *set_array_declarator_inner (struct c_declarator *, struct c_declarator *, bool); extern tree builtin_function (const char *, tree, int, enum built_in_class, const char *, tree); extern void shadow_tag (const struct c_declspecs *); extern void shadow_tag_warned (const struct c_declspecs *, int); extern tree start_enum (tree); extern int start_function (struct c_declspecs *, struct c_declarator *, tree); extern tree start_decl (struct c_declarator *, struct c_declspecs *, bool, tree); extern tree start_struct (enum tree_code, tree); extern void store_parm_decls (void); extern void store_parm_decls_from (struct c_arg_info *); extern tree xref_tag (enum tree_code, tree); extern struct c_typespec parser_xref_tag (enum tree_code, tree); extern int c_expand_decl (tree); extern struct c_parm *build_c_parm (struct c_declspecs *, tree, struct c_declarator *); extern struct c_declarator *build_attrs_declarator (tree, struct c_declarator *); extern struct c_declarator *build_function_declarator (struct c_arg_info *, struct c_declarator *); extern struct c_declarator *build_id_declarator (tree); extern struct c_declarator *make_pointer_declarator (struct c_declspecs *, struct c_declarator *); /* APPLE LOCAL begin radar 5814025 - blocks (C++ cg) */ extern struct c_declarator *make_block_pointer_declarator (struct c_declspecs *, struct c_declarator *); /* APPLE LOCAL end radar 5814025 - blocks (C++ cg) */ extern struct c_declspecs *build_null_declspecs (void); extern struct c_declspecs *declspecs_add_qual (struct c_declspecs *, tree); extern struct c_declspecs *declspecs_add_type (struct c_declspecs *, struct c_typespec); extern struct c_declspecs *declspecs_add_scspec (struct c_declspecs *, tree); extern struct c_declspecs *declspecs_add_attrs (struct c_declspecs *, tree); extern struct c_declspecs *finish_declspecs (struct c_declspecs *); /* in c-objc-common.c */ extern int c_disregard_inline_limits (tree); extern int c_cannot_inline_tree_fn (tree *); extern bool c_objc_common_init (void); extern bool c_missing_noreturn_ok_p (tree); extern tree c_objc_common_truthvalue_conversion (tree expr); extern bool c_warn_unused_global_decl (tree); extern void c_initialize_diagnostics (diagnostic_context *); extern bool c_vla_unspec_p (tree x, tree fn); #define c_build_type_variant(TYPE, CONST_P, VOLATILE_P) \ c_build_qualified_type ((TYPE), \ ((CONST_P) ? TYPE_QUAL_CONST : 0) | \ ((VOLATILE_P) ? TYPE_QUAL_VOLATILE : 0)) /* in c-typeck.c */ extern int in_alignof; extern int in_sizeof; extern int in_typeof; extern struct c_switch *c_switch_stack; extern struct c_label_context_se *label_context_stack_se; extern struct c_label_context_vm *label_context_stack_vm; extern tree require_complete_type (tree); extern int same_translation_unit_p (tree, tree); extern int comptypes (tree, tree); extern bool c_vla_type_p (tree); extern bool c_mark_addressable (tree); extern void c_incomplete_type_error (tree, tree); extern tree c_type_promotes_to (tree); extern struct c_expr default_function_array_conversion (struct c_expr); extern tree composite_type (tree, tree); extern tree build_component_ref (tree, tree); extern tree build_array_ref (tree, tree); extern tree build_external_ref (tree, int, location_t); extern void pop_maybe_used (bool); extern struct c_expr c_expr_sizeof_expr (struct c_expr); extern struct c_expr c_expr_sizeof_type (struct c_type_name *); extern struct c_expr parser_build_unary_op (enum tree_code, struct c_expr); extern struct c_expr parser_build_binary_op (enum tree_code, struct c_expr, struct c_expr); extern tree build_conditional_expr (tree, tree, tree); extern tree build_compound_expr (tree, tree); extern tree c_cast_expr (struct c_type_name *, tree); extern tree build_c_cast (tree, tree); extern void store_init_value (tree, tree); extern void error_init (const char *); extern void pedwarn_init (const char *); extern void maybe_warn_string_init (tree, struct c_expr); extern void start_init (tree, tree, int); extern void finish_init (void); extern void really_start_incremental_init (tree); extern void push_init_level (int); extern struct c_expr pop_init_level (int); extern void set_init_index (tree, tree); extern void set_init_label (tree); extern void process_init_element (struct c_expr); extern tree build_compound_literal (tree, tree); extern tree c_start_case (tree); extern void c_finish_case (tree); extern tree build_asm_expr (tree, tree, tree, tree, bool); extern tree build_asm_stmt (tree, tree); extern tree c_convert_parm_for_inlining (tree, tree, tree, int); extern int c_types_compatible_p (tree, tree); extern tree c_begin_compound_stmt (bool); extern tree c_end_compound_stmt (tree, bool); extern void c_finish_if_stmt (location_t, tree, tree, tree, bool); /* APPLE LOCAL begin for-fsf-4_4 3274130 5295549 */ \ extern void c_finish_loop (location_t, tree, tree, tree, tree, tree, tree, bool); /* APPLE LOCAL end for-fsf-4_4 3274130 5295549 */ \ extern tree c_begin_stmt_expr (void); extern tree c_finish_stmt_expr (tree); extern tree c_process_expr_stmt (tree); extern tree c_finish_expr_stmt (tree); extern tree c_finish_return (tree); extern tree c_finish_bc_stmt (tree *, bool); extern tree c_finish_goto_label (tree); extern tree c_finish_goto_ptr (tree); extern void c_begin_vm_scope (unsigned int); extern void c_end_vm_scope (unsigned int); extern tree c_expr_to_decl (tree, bool *, bool *, bool *); extern tree c_begin_omp_parallel (void); extern tree c_finish_omp_parallel (tree, tree); extern tree c_finish_omp_clauses (tree); /* Set to 0 at beginning of a function definition, set to 1 if a return statement that specifies a return value is seen. */ extern int current_function_returns_value; /* Set to 0 at beginning of a function definition, set to 1 if a return statement with no argument is seen. */ extern int current_function_returns_null; /* Set to 0 at beginning of a function definition, set to 1 if a call to a noreturn function is seen. */ extern int current_function_returns_abnormally; /* Nonzero means we are reading code that came from a system header file. */ extern int system_header_p; /* True means global_bindings_p should return false even if the scope stack says we are in file scope. */ extern bool c_override_global_bindings_to_false; /* True means we've initialized exception handling. */ extern bool c_eh_initialized_p; /* In c-decl.c */ extern void c_finish_incomplete_decl (tree); extern void c_write_global_declarations (void); /* APPLE LOCAL radar 5741070 */ extern tree c_return_interface_record_type (tree); /* In order for the format checking to accept the C frontend diagnostic framework extensions, you must include this file before toplev.h, not after. */ #if GCC_VERSION >= 4001 #define ATTRIBUTE_GCC_CDIAG(m, n) __attribute__ ((__format__ (GCC_DIAG_STYLE, m ,n))) ATTRIBUTE_NONNULL(m) #else #define ATTRIBUTE_GCC_CDIAG(m, n) ATTRIBUTE_NONNULL(m) #endif extern void pedwarn_c90 (const char *, ...) ATTRIBUTE_GCC_CDIAG(1,2); extern void pedwarn_c99 (const char *, ...) ATTRIBUTE_GCC_CDIAG(1,2); #endif /* ! GCC_C_TREE_H */
cg_single.c
/*-------------------------------------------------------------------- NAS Parallel Benchmarks 2.3 OpenMP C versions - CG This benchmark is an OpenMP C version of the NPB CG code. The OpenMP C versions are developed by RWCP and derived from the serial Fortran versions in "NPB 2.3-serial" developed by NAS. Permission to use, copy, distribute and modify this software for any purpose with or without fee is hereby granted. This software is provided "as is" without express or implied warranty. Send comments on the OpenMP C versions to pdp-openmp@rwcp.or.jp Information on OpenMP activities at RWCP is available at: http://pdplab.trc.rwcp.or.jp/pdperf/Omni/ Information on NAS Parallel Benchmarks 2.3 is available at: http://www.nas.nasa.gov/NAS/NPB/ --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- Authors: M. Yarrow C. Kuszmaul OpenMP C version: S. Satoh --------------------------------------------------------------------*/ /* c--------------------------------------------------------------------- c Note: please observe that in the routine conj_grad three c implementations of the sparse matrix-vector multiply have c been supplied. The default matrix-vector multiply is not c loop unrolled. The alternate implementations are unrolled c to a depth of 2 and unrolled to a depth of 8. Please c experiment with these to find the fastest for your particular c architecture. If reporting timing results, any of these three may c be used without penalty. c--------------------------------------------------------------------- */ //#include "npb-C.h" /* NAS Parallel Benchmarks 2.3 OpenMP C Versions */ #include <stdio.h> #include <stdlib.h> #include <math.h> #if defined(_OPENMP) #include <omp.h> #endif /* _OPENMP */ typedef int boolean; typedef struct { double real; double imag; } dcomplex; #define TRUE 1 #define FALSE 0 #define max(a,b) (((a) > (b)) ? (a) : (b)) #define min(a,b) (((a) < (b)) ? (a) : (b)) #define pow2(a) ((a)*(a)) #define get_real(c) c.real #define get_imag(c) c.imag #define cadd(c,a,b) (c.real = a.real + b.real, c.imag = a.imag + b.imag) #define csub(c,a,b) (c.real = a.real - b.real, c.imag = a.imag - b.imag) #define cmul(c,a,b) (c.real = a.real * b.real - a.imag * b.imag, \ c.imag = a.real * b.imag + a.imag * b.real) #define crmul(c,a,b) (c.real = a.real * b, c.imag = a.imag * b) extern double randlc(double *, double); extern void vranlc(int, double *, double, double *); extern void timer_clear(int); extern void timer_start(int); extern void timer_stop(int); extern double timer_read(int); extern void c_print_results(char *name, char cclass, int n1, int n2, int n3, int niter, int nthreads, double t, double mops, char *optype, int passed_verification, char *npbversion, char *compiletime, char *cc, char *clink, char *c_lib, char *c_inc, char *cflags, char *clinkflags, char *rand); //#include "npbparams.h" /******************/ /* default values */ /******************/ #ifndef CLASS #define CLASS 'B' #endif #if CLASS == 'S' /* CLASS = S */ /* c This file is generated automatically by the setparams utility. c It sets the number of processors and the classc of the NPB c in this directory. Do not modify it by hand. */ #define NA 1400 #define NONZER 7 #define NITER 15 #define SHIFT 10.0 #define RCOND 1.0e-1 #define CONVERTDOUBLE FALSE #endif #if CLASS == 'W' /* CLASS = W */ /* c This file is generated automatically by the setparams utility. c It sets the number of processors and the classc of the NPB c in this directory. Do not modify it by hand. */ #define NA 7000 #define NONZER 8 #define NITER 15 #define SHIFT 12.0 #define RCOND 1.0e-1 #define CONVERTDOUBLE FALSE #endif #if CLASS == 'A' /* CLASS = A */ /* c This file is generated automatically by the setparams utility. c It sets the number of processors and the classc of the NPB c in this directory. Do not modify it by hand. */ #define NA 14000 #define NONZER 11 #define NITER 15 #define SHIFT 20.0 #define RCOND 1.0e-1 #define CONVERTDOUBLE FALSE #endif #if CLASS == 'B' /* CLASS = B */ /* c This file is generated automatically by the setparams utility. c It sets the number of processors and the classc of the NPB c in this directory. Do not modify it by hand. */ #define NA 75000 #define NONZER 13 #define NITER 75 #define SHIFT 60.0 #define RCOND 1.0e-1 #define CONVERTDOUBLE FALSE #endif #if CLASS == 'C' /* CLASS = C */ /* c This file is generated automatically by the setparams utility. c It sets the number of processors and the classc of the NPB c in this directory. Do not modify it by hand. */ #define NA 150000 #define NONZER 15 #define NITER 75 #define SHIFT 110.0 #define RCOND 1.0e-1 #define CONVERTDOUBLE FALSE #endif #define COMPILETIME "28 Oct 2014" #define NPBVERSION "2.3" #define CS1 "gcc" #define CS2 "$(CC)" #define CS3 "(none)" #define CS4 "-I../common" #define CS5 "-fopenmp -O2" #define CS6 "-lm -fopenmp" #define CS7 "randdp" #define NZ NA*(NONZER+1)*(NONZER+1)+NA*(NONZER+2) /* global variables */ /* common /partit_size/ */ static int naa; static int nzz; static int firstrow; static int lastrow; static int firstcol; static int lastcol; /* common /main_int_mem/ */ static int colidx[NZ+1]; /* colidx[1:NZ] */ static int rowstr[NA+1+1]; /* rowstr[1:NA+1] */ static int iv[2*NA+1+1]; /* iv[1:2*NA+1] */ static int arow[NZ+1]; /* arow[1:NZ] */ static int acol[NZ+1]; /* acol[1:NZ] */ /* common /main_flt_mem/ */ static double v[NA+1+1]; /* v[1:NA+1] */ static double aelt[NZ+1]; /* aelt[1:NZ] */ static double a[NZ+1]; /* a[1:NZ] */ static double x[NA+2+1]; /* x[1:NA+2] */ static double z[NA+2+1]; /* z[1:NA+2] */ static double p[NA+2+1]; /* p[1:NA+2] */ static double q[NA+2+1]; /* q[1:NA+2] */ static double r[NA+2+1]; /* r[1:NA+2] */ static double w[NA+2+1]; /* w[1:NA+2] */ /* common /urando/ */ static double amult; static double tran; /* function declarations */ static void conj_grad (int colidx[], int rowstr[], double x[], double z[], double a[], double p[], double q[], double r[], double w[], double *rnorm); static void makea(int n, int nz, double a[], int colidx[], int rowstr[], int nonzer, int firstrow, int lastrow, int firstcol, int lastcol, double rcond, int arow[], int acol[], double aelt[], double v[], int iv[], double shift ); static void sparse(double a[], int colidx[], int rowstr[], int n, int arow[], int acol[], double aelt[], int firstrow, int lastrow, double x[], boolean mark[], int nzloc[], int nnza); static void sprnvc(int n, int nz, double v[], int iv[], int nzloc[], int mark[]); static int icnvrt(double x, int ipwr2); static void vecset(int n, double v[], int iv[], int *nzv, int i, double val); /*-------------------------------------------------------------------- program cg --------------------------------------------------------------------*/ int main(int argc, char **argv) { int i, j, k, it; int nthreads = 1; double zeta; double rnorm; double norm_temp11; double norm_temp12; double t, mflops; char cclass; boolean verified; double zeta_verify_value, epsilon; firstrow = 1; lastrow = NA; firstcol = 1; lastcol = NA; if (NA == 1400 && NONZER == 7 && NITER == 15 && SHIFT == 10.0) { cclass = 'S'; zeta_verify_value = 8.5971775078648; } else if (NA == 7000 && NONZER == 8 && NITER == 15 && SHIFT == 12.0) { cclass = 'W'; zeta_verify_value = 10.362595087124; } else if (NA == 14000 && NONZER == 11 && NITER == 15 && SHIFT == 20.0) { cclass = 'A'; zeta_verify_value = 17.130235054029; } else if (NA == 75000 && NONZER == 13 && NITER == 75 && SHIFT == 60.0) { cclass = 'B'; zeta_verify_value = 22.712745482631; } else if (NA == 150000 && NONZER == 15 && NITER == 75 && SHIFT == 110.0) { cclass = 'C'; zeta_verify_value = 28.973605592845; } else { cclass = 'U'; } printf("\n\n NAS Parallel Benchmarks 2.3 OpenMP C version" " - CG Benchmark\n"); printf(" Size: %10d\n", NA); printf(" Iterations: %5d\n", NITER); naa = NA; nzz = NZ; /*-------------------------------------------------------------------- c Initialize random number generator c-------------------------------------------------------------------*/ tran = 314159265.0; amult = 1220703125.0; zeta = randlc( &tran, amult ); /*-------------------------------------------------------------------- c c-------------------------------------------------------------------*/ makea(naa, nzz, a, colidx, rowstr, NONZER, firstrow, lastrow, firstcol, lastcol, RCOND, arow, acol, aelt, v, iv, SHIFT); /*--------------------------------------------------------------------- c Note: as a result of the above call to makea: c values of j used in indexing rowstr go from 1 --> lastrow-firstrow+1 c values of colidx which are col indexes go from firstcol --> lastcol c So: c Shift the col index vals from actual (firstcol --> lastcol ) c to local, i.e., (1 --> lastcol-firstcol+1) c---------------------------------------------------------------------*/ #pragma omp parallel private(it,i,j,k) { #pragma omp for nowait for (j = 1; j <= lastrow - firstrow + 1; j++) { for (k = rowstr[j]; k < rowstr[j+1]; k++) { colidx[k] = colidx[k] - firstcol + 1; } } /*-------------------------------------------------------------------- c set starting vector to (1, 1, .... 1) c-------------------------------------------------------------------*/ #pragma omp for nowait for (i = 1; i <= NA+1; i++) { x[i] = 1.0; } #pragma omp single zeta = 0.0; /*------------------------------------------------------------------- c----> c Do one iteration untimed to init all code and data page tables c----> (then reinit, start timing, to niter its) c-------------------------------------------------------------------*/ for (it = 1; it <= 1; it++) { /*-------------------------------------------------------------------- c The call to the conjugate gradient routine: c-------------------------------------------------------------------*/ conj_grad (colidx, rowstr, x, z, a, p, q, r, w, &rnorm); /*-------------------------------------------------------------------- c zeta = shift + 1/(x.z) c So, first: (x.z) c Also, find norm of z c So, first: (z.z) c-------------------------------------------------------------------*/ #pragma omp single { norm_temp11 = 0.0; norm_temp12 = 0.0; } /* end single */ #pragma omp for reduction(+:norm_temp11,norm_temp12) for (j = 1; j <= lastcol-firstcol+1; j++) { norm_temp11 = norm_temp11 + x[j]*z[j]; norm_temp12 = norm_temp12 + z[j]*z[j]; } #pragma omp single norm_temp12 = 1.0 / sqrt( norm_temp12 ); /*-------------------------------------------------------------------- c Normalize z to obtain x c-------------------------------------------------------------------*/ #pragma omp for for (j = 1; j <= lastcol-firstcol+1; j++) { x[j] = norm_temp12*z[j]; } } /* end of do one iteration untimed */ /*-------------------------------------------------------------------- c set starting vector to (1, 1, .... 1) c-------------------------------------------------------------------*/ #pragma omp for nowait for (i = 1; i <= NA+1; i++) { x[i] = 1.0; } #pragma omp single zeta = 0.0; } /* end parallel */ timer_clear( 1 ); timer_start( 1 ); /*-------------------------------------------------------------------- c----> c Main Iteration for inverse power method c----> c-------------------------------------------------------------------*/ #pragma omp parallel private(it,i,j,k) { for (it = 1; it <= NITER; it++) { /*-------------------------------------------------------------------- c The call to the conjugate gradient routine: c-------------------------------------------------------------------*/ conj_grad(colidx, rowstr, x, z, a, p, q, r, w, &rnorm); /*-------------------------------------------------------------------- c zeta = shift + 1/(x.z) c So, first: (x.z) c Also, find norm of z c So, first: (z.z) c-------------------------------------------------------------------*/ #pragma omp single { norm_temp11 = 0.0; norm_temp12 = 0.0; } /* end single */ #pragma omp for reduction(+:norm_temp11,norm_temp12) for (j = 1; j <= lastcol-firstcol+1; j++) { norm_temp11 = norm_temp11 + x[j]*z[j]; norm_temp12 = norm_temp12 + z[j]*z[j]; } #pragma omp single { norm_temp12 = 1.0 / sqrt( norm_temp12 ); zeta = SHIFT + 1.0 / norm_temp11; } /* end single */ #pragma omp master { if( it == 1 ) { printf(" iteration ||r|| zeta\n"); } printf(" %5d %20.14e%20.13e\n", it, rnorm, zeta); } /* end master */ /*-------------------------------------------------------------------- c Normalize z to obtain x c-------------------------------------------------------------------*/ #pragma omp for for (j = 1; j <= lastcol-firstcol+1; j++) { x[j] = norm_temp12*z[j]; } } /* end of main iter inv pow meth */ #if defined(_OPENMP) #pragma omp master nthreads = omp_get_num_threads(); #endif /* _OPENMP */ } /* end parallel */ timer_stop( 1 ); /*-------------------------------------------------------------------- c End of timed section c-------------------------------------------------------------------*/ t = timer_read( 1 ); printf(" Benchmark completed\n"); epsilon = 1.0e-10; if (cclass != 'U') { if (fabs(zeta - zeta_verify_value) <= epsilon) { verified = TRUE; printf(" VERIFICATION SUCCESSFUL\n"); printf(" Zeta is %20.12e\n", zeta); printf(" Error is %20.12e\n", zeta - zeta_verify_value); } else { verified = FALSE; printf(" VERIFICATION FAILED\n"); printf(" Zeta %20.12e\n", zeta); printf(" The correct zeta is %20.12e\n", zeta_verify_value); } } else { verified = FALSE; printf(" Problem size unknown\n"); printf(" NO VERIFICATION PERFORMED\n"); } if ( t != 0.0 ) { mflops = (2.0*NITER*NA) * (3.0+(NONZER*(NONZER+1)) + 25.0*(5.0+(NONZER*(NONZER+1))) + 3.0 ) / t / 1000000.0; } else { mflops = 0.0; } c_print_results("CG", cclass, NA, 0, 0, NITER, nthreads, t, mflops, " floating point", verified, NPBVERSION, COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, CS7); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void conj_grad ( int colidx[], /* colidx[1:nzz] */ int rowstr[], /* rowstr[1:naa+1] */ double x[], /* x[*] */ double z[], /* z[*] */ double a[], /* a[1:nzz] */ double p[], /* p[*] */ double q[], /* q[*] */ double r[], /* r[*] */ double w[], /* w[*] */ double *rnorm ) /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*--------------------------------------------------------------------- c Floaging point arrays here are named as in NPB1 spec discussion of c CG algorithm c---------------------------------------------------------------------*/ { static double d, sum, rho, rho0, alpha, beta; int i, j, k; int cgit, cgitmax = 25; #pragma omp single nowait rho = 0.0; /*-------------------------------------------------------------------- c Initialize the CG algorithm: c-------------------------------------------------------------------*/ #pragma omp for nowait for (j = 1; j <= naa+1; j++) { q[j] = 0.0; z[j] = 0.0; r[j] = x[j]; p[j] = r[j]; w[j] = 0.0; } /*-------------------------------------------------------------------- c rho = r.r c Now, obtain the norm of r: First, sum squares of r elements locally... c-------------------------------------------------------------------*/ #pragma omp for reduction(+:rho) for (j = 1; j <= lastcol-firstcol+1; j++) { rho = rho + x[j]*x[j]; } /*-------------------------------------------------------------------- c----> c The conj grad iteration loop c----> c-------------------------------------------------------------------*/ for (cgit = 1; cgit <= cgitmax; cgit++) { #pragma omp single nowait { rho0 = rho; d = 0.0; rho = 0.0; } /* end single */ /*-------------------------------------------------------------------- c q = A.p c The partition submatrix-vector multiply: use workspace w c--------------------------------------------------------------------- C C NOTE: this version of the multiply is actually (slightly: maybe %5) C faster on the sp2 on 16 nodes than is the unrolled-by-2 version C below. On the Cray t3d, the reverse is true, i.e., the C unrolled-by-two version is some 10% faster. C The unrolled-by-8 version below is significantly faster C on the Cray t3d - overall speed of code is 1.5 times faster. */ /* rolled version */ #pragma omp for private(sum,k) for (j = 1; j <= lastrow-firstrow+1; j++) { sum = 0.0; for (k = rowstr[j]; k < rowstr[j+1]; k++) { sum = sum + a[k]*p[colidx[k]]; } w[j] = sum; } /* unrolled-by-two version #pragma omp for private(i,k) for (j = 1; j <= lastrow-firstrow+1; j++) { int iresidue; double sum1, sum2; i = rowstr[j]; iresidue = (rowstr[j+1]-i) % 2; sum1 = 0.0; sum2 = 0.0; if (iresidue == 1) sum1 = sum1 + a[i]*p[colidx[i]]; for (k = i+iresidue; k <= rowstr[j+1]-2; k += 2) { sum1 = sum1 + a[k] * p[colidx[k]]; sum2 = sum2 + a[k+1] * p[colidx[k+1]]; } w[j] = sum1 + sum2; } */ /* unrolled-by-8 version #pragma omp for private(i,k,sum) for (j = 1; j <= lastrow-firstrow+1; j++) { int iresidue; i = rowstr[j]; iresidue = (rowstr[j+1]-i) % 8; sum = 0.0; for (k = i; k <= i+iresidue-1; k++) { sum = sum + a[k] * p[colidx[k]]; } for (k = i+iresidue; k <= rowstr[j+1]-8; k += 8) { sum = sum + a[k ] * p[colidx[k ]] + a[k+1] * p[colidx[k+1]] + a[k+2] * p[colidx[k+2]] + a[k+3] * p[colidx[k+3]] + a[k+4] * p[colidx[k+4]] + a[k+5] * p[colidx[k+5]] + a[k+6] * p[colidx[k+6]] + a[k+7] * p[colidx[k+7]]; } w[j] = sum; } */ #pragma omp for for (j = 1; j <= lastcol-firstcol+1; j++) { q[j] = w[j]; } /*-------------------------------------------------------------------- c Clear w for reuse... c-------------------------------------------------------------------*/ #pragma omp for nowait for (j = 1; j <= lastcol-firstcol+1; j++) { w[j] = 0.0; } /*-------------------------------------------------------------------- c Obtain p.q c-------------------------------------------------------------------*/ #pragma omp for reduction(+:d) for (j = 1; j <= lastcol-firstcol+1; j++) { d = d + p[j]*q[j]; } /*-------------------------------------------------------------------- c Obtain alpha = rho / (p.q) c-------------------------------------------------------------------*/ #pragma omp single alpha = rho0 / d; /*-------------------------------------------------------------------- c Save a temporary of rho c-------------------------------------------------------------------*/ /* rho0 = rho;*/ /*--------------------------------------------------------------------- c Obtain z = z + alpha*p c and r = r - alpha*q c---------------------------------------------------------------------*/ #pragma omp for for (j = 1; j <= lastcol-firstcol+1; j++) { z[j] = z[j] + alpha*p[j]; r[j] = r[j] - alpha*q[j]; } /*--------------------------------------------------------------------- c rho = r.r c Now, obtain the norm of r: First, sum squares of r elements locally... c---------------------------------------------------------------------*/ #pragma omp for reduction(+:rho) for (j = 1; j <= lastcol-firstcol+1; j++) { rho = rho + r[j]*r[j]; } /*-------------------------------------------------------------------- c Obtain beta: c-------------------------------------------------------------------*/ #pragma omp single beta = rho / rho0; /*-------------------------------------------------------------------- c p = r + beta*p c-------------------------------------------------------------------*/ #pragma omp for for (j = 1; j <= lastcol-firstcol+1; j++) { p[j] = r[j] + beta*p[j]; } } /* end of do cgit=1,cgitmax */ /*--------------------------------------------------------------------- c Compute residual norm explicitly: ||r|| = ||x - A.z|| c First, form A.z c The partition submatrix-vector multiply c---------------------------------------------------------------------*/ #pragma omp single nowait sum = 0.0; #pragma omp for private(d, k) for (j = 1; j <= lastrow-firstrow+1; j++) { d = 0.0; for (k = rowstr[j]; k <= rowstr[j+1]-1; k++) { d = d + a[k]*z[colidx[k]]; } w[j] = d; } #pragma omp for for (j = 1; j <= lastcol-firstcol+1; j++) { r[j] = w[j]; } /*-------------------------------------------------------------------- c At this point, r contains A.z c-------------------------------------------------------------------*/ #pragma omp for reduction(+:sum) private(d) for (j = 1; j <= lastcol-firstcol+1; j++) { d = x[j] - r[j]; sum = sum + d*d; } #pragma omp single { (*rnorm) = sqrt(sum); } /* end single */ } /*--------------------------------------------------------------------- c generate the test problem for benchmark 6 c makea generates a sparse matrix with a c prescribed sparsity distribution c c parameter type usage c c input c c n i number of cols/rows of matrix c nz i nonzeros as declared array size c rcond r*8 condition number c shift r*8 main diagonal shift c c output c c a r*8 array for nonzeros c colidx i col indices c rowstr i row pointers c c workspace c c iv, arow, acol i c v, aelt r*8 c---------------------------------------------------------------------*/ static void makea( int n, int nz, double a[], /* a[1:nz] */ int colidx[], /* colidx[1:nz] */ int rowstr[], /* rowstr[1:n+1] */ int nonzer, int firstrow, int lastrow, int firstcol, int lastcol, double rcond, int arow[], /* arow[1:nz] */ int acol[], /* acol[1:nz] */ double aelt[], /* aelt[1:nz] */ double v[], /* v[1:n+1] */ int iv[], /* iv[1:2*n+1] */ double shift ) { int i, nnza, iouter, ivelt, ivelt1, irow, nzv; /*-------------------------------------------------------------------- c nonzer is approximately (int(sqrt(nnza /n))); c-------------------------------------------------------------------*/ double size, ratio, scale; int jcol; size = 1.0; ratio = pow(rcond, (1.0 / (double)n)); nnza = 0; /*--------------------------------------------------------------------- c Initialize colidx(n+1 .. 2n) to zero. c Used by sprnvc to mark nonzero positions c---------------------------------------------------------------------*/ #pragma omp parallel for for (i = 1; i <= n; i++) { colidx[n+i] = 0; } for (iouter = 1; iouter <= n; iouter++) { nzv = nonzer; sprnvc(n, nzv, v, iv, &(colidx[0]), &(colidx[n])); vecset(n, v, iv, &nzv, iouter, 0.5); for (ivelt = 1; ivelt <= nzv; ivelt++) { jcol = iv[ivelt]; if (jcol >= firstcol && jcol <= lastcol) { scale = size * v[ivelt]; for (ivelt1 = 1; ivelt1 <= nzv; ivelt1++) { irow = iv[ivelt1]; if (irow >= firstrow && irow <= lastrow) { nnza = nnza + 1; if (nnza > nz) { printf("Space for matrix elements exceeded in" " makea\n"); printf("nnza, nzmax = %d, %d\n", nnza, nz); printf("iouter = %d\n", iouter); exit(1); } acol[nnza] = jcol; arow[nnza] = irow; aelt[nnza] = v[ivelt1] * scale; } } } } size = size * ratio; } /*--------------------------------------------------------------------- c ... add the identity * rcond to the generated matrix to bound c the smallest eigenvalue from below by rcond c---------------------------------------------------------------------*/ for (i = firstrow; i <= lastrow; i++) { if (i >= firstcol && i <= lastcol) { iouter = n + i; nnza = nnza + 1; if (nnza > nz) { printf("Space for matrix elements exceeded in makea\n"); printf("nnza, nzmax = %d, %d\n", nnza, nz); printf("iouter = %d\n", iouter); exit(1); } acol[nnza] = i; arow[nnza] = i; aelt[nnza] = rcond - shift; } } /*--------------------------------------------------------------------- c ... make the sparse matrix from list of elements with duplicates c (v and iv are used as workspace) c---------------------------------------------------------------------*/ sparse(a, colidx, rowstr, n, arow, acol, aelt, firstrow, lastrow, v, &(iv[0]), &(iv[n]), nnza); } /*--------------------------------------------------- c generate a sparse matrix from a list of c [col, row, element] tri c---------------------------------------------------*/ static void sparse( double a[], /* a[1:*] */ int colidx[], /* colidx[1:*] */ int rowstr[], /* rowstr[1:*] */ int n, int arow[], /* arow[1:*] */ int acol[], /* acol[1:*] */ double aelt[], /* aelt[1:*] */ int firstrow, int lastrow, double x[], /* x[1:n] */ boolean mark[], /* mark[1:n] */ int nzloc[], /* nzloc[1:n] */ int nnza) /*--------------------------------------------------------------------- c rows range from firstrow to lastrow c the rowstr pointers are defined for nrows = lastrow-firstrow+1 values c---------------------------------------------------------------------*/ { int nrows; int i, j, jajp1, nza, k, nzrow; double xi; /*-------------------------------------------------------------------- c how many rows of result c-------------------------------------------------------------------*/ nrows = lastrow - firstrow + 1; /*-------------------------------------------------------------------- c ...count the number of triples in each row c-------------------------------------------------------------------*/ #pragma omp parallel for for (j = 1; j <= n; j++) { rowstr[j] = 0; mark[j] = FALSE; } rowstr[n+1] = 0; for (nza = 1; nza <= nnza; nza++) { j = (arow[nza] - firstrow + 1) + 1; rowstr[j] = rowstr[j] + 1; } rowstr[1] = 1; for (j = 2; j <= nrows+1; j++) { rowstr[j] = rowstr[j] + rowstr[j-1]; } /*--------------------------------------------------------------------- c ... rowstr(j) now is the location of the first nonzero c of row j of a c---------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c ... do a bucket sort of the triples on the row index c-------------------------------------------------------------------*/ for (nza = 1; nza <= nnza; nza++) { j = arow[nza] - firstrow + 1; k = rowstr[j]; a[k] = aelt[nza]; colidx[k] = acol[nza]; rowstr[j] = rowstr[j] + 1; } /*-------------------------------------------------------------------- c ... rowstr(j) now points to the first element of row j+1 c-------------------------------------------------------------------*/ for (j = nrows; j >= 1; j--) { rowstr[j+1] = rowstr[j]; } rowstr[1] = 1; /*-------------------------------------------------------------------- c ... generate the actual output rows by adding elements c-------------------------------------------------------------------*/ nza = 0; #pragma omp parallel for for (i = 1; i <= n; i++) { x[i] = 0.0; mark[i] = FALSE; } jajp1 = rowstr[1]; for (j = 1; j <= nrows; j++) { nzrow = 0; /*-------------------------------------------------------------------- c ...loop over the jth row of a c-------------------------------------------------------------------*/ for (k = jajp1; k < rowstr[j+1]; k++) { i = colidx[k]; x[i] = x[i] + a[k]; if ( mark[i] == FALSE && x[i] != 0.0) { mark[i] = TRUE; nzrow = nzrow + 1; nzloc[nzrow] = i; } } /*-------------------------------------------------------------------- c ... extract the nonzeros of this row c-------------------------------------------------------------------*/ for (k = 1; k <= nzrow; k++) { i = nzloc[k]; mark[i] = FALSE; xi = x[i]; x[i] = 0.0; if (xi != 0.0) { nza = nza + 1; a[nza] = xi; colidx[nza] = i; } } jajp1 = rowstr[j+1]; rowstr[j+1] = nza + rowstr[1]; } } /*--------------------------------------------------------------------- c generate a sparse n-vector (v, iv) c having nzv nonzeros c c mark(i) is set to 1 if position i is nonzero. c mark is all zero on entry and is reset to all zero before exit c this corrects a performance bug found by John G. Lewis, caused by c reinitialization of mark on every one of the n calls to sprnvc ---------------------------------------------------------------------*/ static void sprnvc( int n, int nz, double v[], /* v[1:*] */ int iv[], /* iv[1:*] */ int nzloc[], /* nzloc[1:n] */ int mark[] ) /* mark[1:n] */ { int nn1; int nzrow, nzv, ii, i; double vecelt, vecloc; nzv = 0; nzrow = 0; nn1 = 1; do { nn1 = 2 * nn1; } while (nn1 < n); /*-------------------------------------------------------------------- c nn1 is the smallest power of two not less than n c-------------------------------------------------------------------*/ while (nzv < nz) { vecelt = randlc(&tran, amult); /*-------------------------------------------------------------------- c generate an integer between 1 and n in a portable manner c-------------------------------------------------------------------*/ vecloc = randlc(&tran, amult); i = icnvrt(vecloc, nn1) + 1; if (i > n) continue; /*-------------------------------------------------------------------- c was this integer generated already? c-------------------------------------------------------------------*/ if (mark[i] == 0) { mark[i] = 1; nzrow = nzrow + 1; nzloc[nzrow] = i; nzv = nzv + 1; v[nzv] = vecelt; iv[nzv] = i; } } for (ii = 1; ii <= nzrow; ii++) { i = nzloc[ii]; mark[i] = 0; } } /*--------------------------------------------------------------------- * scale a double precision number x in (0,1) by a power of 2 and chop it *---------------------------------------------------------------------*/ static int icnvrt(double x, int ipwr2) { return ((int)(ipwr2 * x)); } /*-------------------------------------------------------------------- c set ith element of sparse vector (v, iv) with c nzv nonzeros to val c-------------------------------------------------------------------*/ static void vecset( int n, double v[], /* v[1:*] */ int iv[], /* iv[1:*] */ int *nzv, int i, double val) { int k; boolean set; set = FALSE; for (k = 1; k <= *nzv; k++) { if (iv[k] == i) { v[k] = val; set = TRUE; } } if (set == FALSE) { *nzv = *nzv + 1; v[*nzv] = val; iv[*nzv] = i; } } /* cat ./common/c_print_results.c */ /*****************************************************************/ /****** C _ P R I N T _ R E S U L T S ******/ /*****************************************************************/ void c_print_results( char *name, char cclass, int n1, int n2, int n3, int niter, int nthreads, double t, double mops, char *optype, int passed_verification, char *npbversion, char *compiletime, char *cc, char *clink, char *c_lib, char *c_inc, char *cflags, char *clinkflags, char *rand) { char *evalue="1000"; printf( "\n\n %s Benchmark Completed\n", name ); printf( " Class = %c\n", cclass ); if( n2 == 0 && n3 == 0 ) printf( " Size = %12d\n", n1 ); /* as in IS */ else printf( " Size = %3dx%3dx%3d\n", n1,n2,n3 ); printf( " Iterations = %12d\n", niter ); printf( " Threads = %12d\n", nthreads ); printf( " Time in seconds = %12.2f\n", t ); printf( " Mop/s total = %12.2f\n", mops ); printf( " Operation type = %24s\n", optype); if( passed_verification ) printf( " Verification = SUCCESSFUL\n" ); else printf( " Verification = UNSUCCESSFUL\n" ); printf( " Version = %12s\n", npbversion ); printf( " Compile date = %12s\n", compiletime ); printf( "\n Compile options:\n" ); printf( " CC = %s\n", cc ); printf( " CLINK = %s\n", clink ); printf( " C_LIB = %s\n", c_lib ); printf( " C_INC = %s\n", c_inc ); printf( " CFLAGS = %s\n", cflags ); printf( " CLINKFLAGS = %s\n", clinkflags ); printf( " RAND = %s\n", rand ); #ifdef SMP evalue = getenv("MP_SET_NUMTHREADS"); printf( " MULTICPUS = %s\n", evalue ); #endif /* printf( "\n\n" ); printf( " Please send the results of this run to:\n\n" ); printf( " NPB Development Team\n" ); printf( " Internet: npb@nas.nasa.gov\n \n" ); printf( " If email is not available, send this to:\n\n" ); printf( " MS T27A-1\n" ); printf( " NASA Ames Research Center\n" ); printf( " Moffett Field, CA 94035-1000\n\n" ); printf( " Fax: 415-604-3957\n\n" );*/ } /* cat ./common/c_timers.c */ /* #include "wtime.h" #if defined(IBM) #define wtime wtime #elif defined(CRAY) #define wtime WTIME #else #define wtime wtime_ #endif */ /* Prototype */ void wtime( double * ); /*****************************************************************/ /****** E L A P S E D _ T I M E ******/ /*****************************************************************/ double elapsed_time( void ) { double t; wtime( &t ); return( t ); } double start[64], elapsed[64]; /*****************************************************************/ /****** T I M E R _ C L E A R ******/ /*****************************************************************/ void timer_clear( int n ) { elapsed[n] = 0.0; } /*****************************************************************/ /****** T I M E R _ S T A R T ******/ /*****************************************************************/ void timer_start( int n ) { start[n] = elapsed_time(); } /*****************************************************************/ /****** T I M E R _ S T O P ******/ /*****************************************************************/ void timer_stop( int n ) { double t, now; now = elapsed_time(); t = now - start[n]; elapsed[n] += t; } /*****************************************************************/ /****** T I M E R _ R E A D ******/ /*****************************************************************/ double timer_read( int n ) { return( elapsed[n] ); } void wtime(double *t) { static int sec = -1; struct timeval tv; // gettimeofday(&tv, (void *)0); gettimeofday(&tv, (struct timezone *)0); if (sec < 0) sec = tv.tv_sec; *t = (tv.tv_sec - sec) + 1.0e-6*tv.tv_usec; } // common/c_randdp.c /* */ #if defined(USE_POW) #define r23 pow(0.5, 23.0) #define r46 (r23*r23) #define t23 pow(2.0, 23.0) #define t46 (t23*t23) #else #define r23 (0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5) #define r46 (r23*r23) #define t23 (2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0) #define t46 (t23*t23) #endif /*c--------------------------------------------------------------------- c---------------------------------------------------------------------*/ double randlc (double *x, double a) { /*c--------------------------------------------------------------------- c---------------------------------------------------------------------*/ /*c--------------------------------------------------------------------- c c This routine returns a uniform pseudorandom double precision number in the c range (0, 1) by using the linear congruential generator c c x_{k+1} = a x_k (mod 2^46) c c where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers c before repeating. The argument A is the same as 'a' in the above formula, c and X is the same as x_0. A and X must be odd double precision integers c in the range (1, 2^46). The returned value RANDLC is normalized to be c between 0 and 1, i.e. RANDLC = 2^(-46) * x_1. X is updated to contain c the new seed x_1, so that subsequent calls to RANDLC using the same c arguments will generate a continuous sequence. c c This routine should produce the same results on any computer with at least c 48 mantissa bits in double precision floating point data. On 64 bit c systems, double precision should be disabled. c c David H. Bailey October 26, 1990 c c---------------------------------------------------------------------*/ double t1,t2,t3,t4,a1,a2,x1,x2,z; /*c--------------------------------------------------------------------- c Break A into two parts such that A = 2^23 * A1 + A2. c---------------------------------------------------------------------*/ t1 = r23 * a; a1 = (int)t1; a2 = a - t23 * a1; /*c--------------------------------------------------------------------- c Break X into two parts such that X = 2^23 * X1 + X2, compute c Z = A1 * X2 + A2 * X1 (mod 2^23), and then c X = 2^23 * Z + A2 * X2 (mod 2^46). c---------------------------------------------------------------------*/ t1 = r23 * (*x); x1 = (int)t1; x2 = (*x) - t23 * x1; t1 = a1 * x2 + a2 * x1; t2 = (int)(r23 * t1); z = t1 - t23 * t2; t3 = t23 * z + a2 * x2; t4 = (int)(r46 * t3); (*x) = t3 - t46 * t4; return (r46 * (*x)); }
union_find.h
/***************************************************************************** * * ALPS/looper: multi-cluster quantum Monte Carlo algorithms for spin systems * * Copyright (C) 1997-2011 by Synge Todo <wistaria@comp-phys.org> * * This software is published under the ALPS Application License; you * can use, redistribute it and/or modify it under the terms of the * license, either version 1 or (at your option) any later version. * * You should have received a copy of the ALPS Application License * along with this software; see the file LICENSE. If not, the license * is also available from http://alps.comp-phys.org/. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ // Weighted Union-Find Algorithm // Reference: // D. Knuth, // `The Art of Computer Programming, Vol. 1, Fundamental Algorithms' // 3rd edition (Addison Wesley, Reading, 1997) Sec 2.3.3. #ifndef LOOPER_UNION_FIND_H #define LOOPER_UNION_FIND_H #ifndef ALPS_INDEP_SOURCE # include <alps/config.h> # if defined(LOOPER_ENABLE_OPENMP) && defined(ALPS_ENABLE_OPENMP_WORKER) && !defined(LOOPER_OPENMP) # define LOOPER_OPENMP # endif #else # if defined(LOOPER_ENABLE_OPENMP) && defined(_OPENMP) && !defined(LOOPER_OPENMP) # define LOOPER_OPENMP # endif #endif #include <algorithm> // for std::swap #include <vector> #include <iostream> #ifdef LOOPER_OPENMP # include <omp.h> # include "atomic.h" #endif namespace looper { namespace union_find { class node { public: node() : parent_(-1) {} // root node with weight = 1 ~node() {} bool is_root() const { return parent_ <= 0; } void set_parent(int parent) { parent_ = parent + 1; } int parent() const { return parent_ - 1; } void set_weight(int w) { parent_ = -w; } int weight() const { return -parent_; } void set_id(int id) { id_ = id; } int id() const { return id_; } #ifdef LOOPER_OPENMP int lock_root() { int p = parent_; if (p < 0 && compare_and_swap(parent_, p, 0)) { return -p; } else { return 0; } } // unlock can be done by set_parent or set_weight #endif private: int parent_; // negative for root fragment int id_; }; class node_c { public: node_c() : parent_(1 ^ id_mask) {} // root node with weight = 1 ~node_c() {} int is_root() const { return (int) parent_ <= 0; } void set_parent(int parent) { parent_ = parent + 1; } int parent() const { return parent_ - 1; } void set_weight(int w) { parent_ = w ^ id_mask; } int weight() const { return parent_ ^ id_mask; } void set_id(int id) { parent_ = id ^ id_mask; } int id() const { return parent_ ^ id_mask; } #ifdef LOOPER_OPENMP int lock_root() { int p = parent_; if (p < 0 && compare_and_swap(parent_, p, 0)) { return -p; } else { return 0; } } // unlock can be done by set_parent or set_weight #endif private: static const int id_mask = -1; int parent_; // non-positive for root fragment }; class node_noweight { public: node_noweight() : parent_(id_mask) {} // root note with id = 0 ~node_noweight() {} int is_root() const { return (int) parent_ <= 0; } void set_parent(int parent) { parent_ = parent + 1; } int parent() const { return parent_ - 1; } void set_weight(int) { set_id(0); } // dummy routine for unlock int weight() const { return 0; } // dummy void set_id(int id) { parent_ = id ^ id_mask; } int id() const { return parent_ ^ id_mask; } #ifdef LOOPER_OPENMP int lock_root() { int p = parent_; if (p < 0 && compare_and_swap(parent_, p, 0)) { return 1; } else { return 0; } } // unlock can be done by set_parent, set_weight or set_id #endif private: static const int id_mask = -1; int parent_; // negative for root fragment }; // thread-unsafe template<class T> inline int add(std::vector<T>& v) { v.push_back(T()); return v.size() - 1; // return index of new node } template<class T> inline int root_index(std::vector<T> const& v, int g) { #ifdef LOOPER_OPENMP T c = v[g]; while (!c.is_root()) { g = c.parent(); c = v[g]; } #else while (!v[g].is_root()) { g = v[g].parent(); } #endif return g; } // root_index with path-halving // Note: this is not thread-safe, but is really safe as long as called from unify_* template<class T> inline int root_index_ph(std::vector<T>& v, int g) { if (v[g].is_root()) return g; while (true) { int p = v[g].parent(); if (v[p].is_root()) return p; v[g].set_parent(v[p].parent()); g = p; } } template<class T> inline T const& root(std::vector<T> const& v, int g) { return v[root_index(v, g)]; } template<class T> inline T const& root(std::vector<T> const& v, T const& n) { return n.is_root() ? n : root(v, n.parent()); } template<class T> inline int cluster_id(std::vector<T> const& v, int g) { return root(v, g).id(); } template<class T> inline int cluster_id(std::vector<T> const& v, T const& n) { return root(v, n).id(); } template<class T> void set_root(std::vector<T>& v, int g) { #ifdef LOOPER_OPENMP while(true) { int r = root_index(v, g); if (r == g) { return; } else { int w = v[r].lock_root(); if (w != 0) { v[g].set_weight(w); v[r].set_parent(g); // release lock return; } } } #else int r = root_index(v, g); if (r != g) { v[g] = v[r]; v[r].set_parent(g); } #endif } template<class T> inline void update_link(std::vector<T>& v, int g, int r) { while (g != r) { int p = v[g].parent(); v[g].set_parent(r); g = p; } } // WARNING: this is not thread-safe template<class T> inline int unify_compress(std::vector<T>& v, int g0, int g1) { using std::swap; int r0 = root_index(v, g0); int r1 = root_index(v, g1); if (r0 != r1) { #if !defined(LOOPER_USE_DETERMINISTIC_UNIFY) if (v[r0].weight() < v[r1].weight()) swap(r0, r1); #else if (r0 > r1) swap(r0, r1); #endif v[r0].set_weight(v[r0].weight() + v[r1].weight()); v[r1].set_parent(r0); } update_link(v, g0, r0); update_link(v, g1, r0); return r0; // return (new) root node } template<class T> inline int unify_pathhalving(std::vector<T>& v, int g0, int g1) { using std::swap; int r0 = root_index_ph(v, g0); int r1 = root_index_ph(v, g1); #ifdef LOOPER_OPENMP int w0 = 0; int w1 = 0; while (true) { if (r1 == r0) return r0; // g0 and g1 belong to the same cluster w0 = v[r0].lock_root(); w1 = v[r1].lock_root(); if (w0 != 0 && w1 != 0) break; if (w0 != 0) v[r0].set_weight(w0); // release lock if (w1 != 0) v[r1].set_weight(w1); // release lock r0 = root_index_ph(v, r0); r1 = root_index_ph(v, r1); } # if !defined(LOOPER_USE_DETERMINISTIC_UNIFY) if (w0 < w1) swap(r0, r1); # else if (r0 > r1) swap(r0, r1); # endif v[r0].set_weight(w0 + w1); // release lock v[r1].set_parent(r0); // release lock #else if (r0 != r1) { # if !defined(LOOPER_USE_DETERMINISTIC_UNIFY) if (v[r0].weight() < v[r1].weight()) swap(r0, r1); # else if (r0 > r1) swap(r0, r1); # endif v[r0].set_weight(v[r0].weight() + v[r1].weight()); v[r1].set_parent(r0); } #endif return r0; // return (new) root node } template<class T> inline int unify(std::vector<T>& v, int g0, int g1) { return unify_pathhalving(v, g0, g1); } template<class T> inline void output(std::vector<T> const& v, std::ostream& os = std::cout) { for (int i = 0; i < v.size(); ++i) { os << "node " << i << ": "; int g = i; if (v[g].is_root()) { os << "root (id = " << v[g].id() << ")" << std::endl; } else { while (true) { if (v[g].is_root()) { os << g << std::endl; break; } else { os << g << " -> "; g = v[g].parent(); } } } } } template<typename T> int count_root(std::vector<T>& v, int start, int n) { int nc = 0; for (int i = start; i < start + n; ++i) if (v[i].is_root()) ++nc; return nc; } template<typename T> int count_root_p(std::vector<T>& v, int start, int n) { int nc = 0; #pragma omp for schedule(static) nowait for (int i = start; i < start + n; ++i) if (v[i].is_root()) ++nc; return nc; } template<typename T> int set_id(std::vector<T>& v, int start, int n, int nc) { for (int i = start; i < start + n; ++i) if (v[i].is_root()) v[i].set_id(nc++); return nc; } template<typename T> int set_id_p(std::vector<T>& v, int start, int n, int nc) { #pragma omp for schedule(static) nowait for (int i = start; i < start + n; ++i) if (v[i].is_root()) v[i].set_id(nc++); return nc; } template<typename T> void copy_id(std::vector<T>& v, int start, int n) { for (int i = start; i < start + n; ++i) v[i].set_id(cluster_id(v, i)); } template<typename T> void copy_id_p(std::vector<T>& v, int start, int n) { #pragma omp for schedule(static) nowait for (int i = start; i < start + n; ++i) v[i].set_id(cluster_id(v, i)); } template<typename T> inline void pack_tree(std::vector<T>& v, int n) { #ifdef LOOPER_OPENMP int g, w; // workaround for FCC OpenMP bug? -- ST 2010-11-22 #pragma omp parallel for schedule(static) private(g, w) for (int i = 0; i < n; ++i) { if (!v[i].is_root()) { g = v[i].parent(); while (true) { if (g < n) { // encounter node with index < n v[i].set_parent(g); break; } else if (v[g].is_root()) { // found root with index >= n w = v[g].lock_root(); if (w != 0) { v[i].set_weight(w); v[g].set_parent(i); // release lock break; } } else { g = v[g].parent(); } } } } #else for (int i = 0; i < n; ++i) { if (!v[i].is_root()) { int g = v[i].parent(); while (true) { if (g < n) { // encounter node with index < n v[i].set_parent(g); break; } else if (v[g].is_root()) { // found root with index >= n v[i] = v[g]; v[g].set_parent(i); break; } else { g = v[g].parent(); } } } } #endif } // pack tree so that nodes with id [0...n) and [m...) come upper template<typename T> inline void pack_tree(std::vector<T>& v, int n, int m) { #ifdef LOOPER_OPENMP int g, w; // workaround for FCC OpenMP bug? -- ST 2010-11-22 #pragma omp parallel for schedule(static) private(g, w) for (int i = 0; i < n; ++i) { if (!v[i].is_root()) { g = v[i].parent(); while (true) { if (g < n || g >= m) { // encounter node with index < n or >= m v[i].set_parent(g); break; } else if (v[g].is_root()) { // found root with index >= n and < m w = v[g].lock_root(); if (w != 0) { v[i].set_weight(w); v[g].set_parent(i); // release lock break; } } else { g = v[g].parent(); } } } } #pragma omp parallel for schedule(static) private(g, w) for (int i = m; i < m + n; ++i) { if (!v[i].is_root()) { g = v[i].parent(); while (true) { if (g < n || g >= m) { // encounter node with index < n or >= m v[i].set_parent(g); break; } else if (v[g].is_root()) { // found root with index >= n and < m w = v[g].lock_root(); if (w != 0) { v[i].set_weight(w); v[g].set_parent(i); // release lock break; } } else { g = v[g].parent(); } } } } #else for (int i = 0; i < n; ++i) { if (!v[i].is_root()) { int g = v[i].parent(); while (true) { if (g < n || g >= m) { // encounter node with index < n or >= m v[i].set_parent(g); break; } else if (v[g].is_root()) { // found root with index >= n and < m v[i] = v[g]; v[g].set_parent(i); break; } else { g = v[g].parent(); } } } } for (int i = m; i < m + n; ++i) { if (!v[i].is_root()) { int g = v[i].parent(); while (true) { if (g < n || g >= m) { // encounter node with index < n or >= m v[i].set_parent(g); break; } else if (v[g].is_root()) { // found root with index >= n and < m v[i] = v[g]; v[g].set_parent(i); break; } else { g = v[g].parent(); } } } } #endif } } // end namespace union_find } // end namespace looper #endif
GB_binop__land_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__land_uint32 // A.*B function (eWiseMult): GB_AemultB__land_uint32 // A*D function (colscale): GB_AxD__land_uint32 // D*A function (rowscale): GB_DxB__land_uint32 // C+=B function (dense accum): GB_Cdense_accumB__land_uint32 // C+=b function (dense accum): GB_Cdense_accumb__land_uint32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__land_uint32 // C=scalar+B GB_bind1st__land_uint32 // C=scalar+B' GB_bind1st_tran__land_uint32 // C=A+scalar GB_bind2nd__land_uint32 // C=A'+scalar GB_bind2nd_tran__land_uint32 // C type: uint32_t // A type: uint32_t // B,b type: uint32_t // BinaryOp: cij = ((aij != 0) && (bij != 0)) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = ((x != 0) && (y != 0)) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LAND || GxB_NO_UINT32 || GxB_NO_LAND_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__land_uint32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__land_uint32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__land_uint32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__land_uint32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *GB_RESTRICT Cx = (uint32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__land_uint32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *GB_RESTRICT Cx = (uint32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__land_uint32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__land_uint32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__land_uint32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint32_t bij = Bx [p] ; Cx [p] = ((x != 0) && (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__land_uint32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint32_t aij = Ax [p] ; Cx [p] = ((aij != 0) && (y != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = ((x != 0) && (aij != 0)) ; \ } GrB_Info GB_bind1st_tran__land_uint32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = ((aij != 0) && (y != 0)) ; \ } GrB_Info GB_bind2nd_tran__land_uint32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t y = (*((const uint32_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
psd.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Photoshop spec @ https://www.adobe.com/devnet-apps/photoshop/fileformatashtml % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/registry.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[257], visible; unsigned short channels; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(Image *image) { switch (image->compose) { case ColorBurnCompositeOp: return(image->endian == LSBEndian ? "vidi" : "idiv"); case ColorDodgeCompositeOp: return(image->endian == LSBEndian ? " vid" : "div "); case ColorizeCompositeOp: return(image->endian == LSBEndian ? "rloc" : "colr"); case DarkenCompositeOp: return(image->endian == LSBEndian ? "krad" : "dark"); case DifferenceCompositeOp: return(image->endian == LSBEndian ? "ffid" : "diff"); case DissolveCompositeOp: return(image->endian == LSBEndian ? "ssid" : "diss"); case ExclusionCompositeOp: return(image->endian == LSBEndian ? "dums" : "smud"); case HardLightCompositeOp: return(image->endian == LSBEndian ? "tiLh" : "hLit"); case HardMixCompositeOp: return(image->endian == LSBEndian ? "xiMh" : "hMix"); case HueCompositeOp: return(image->endian == LSBEndian ? " euh" : "hue "); case LightenCompositeOp: return(image->endian == LSBEndian ? "etil" : "lite"); case LinearBurnCompositeOp: return(image->endian == LSBEndian ? "nrbl" : "lbrn"); case LinearDodgeCompositeOp: return(image->endian == LSBEndian ? "gddl" : "lddg"); case LinearLightCompositeOp: return(image->endian == LSBEndian ? "tiLl" : "lLit"); case LuminizeCompositeOp: return(image->endian == LSBEndian ? " mul" : "lum "); case MultiplyCompositeOp: return(image->endian == LSBEndian ? " lum" : "mul "); case OverlayCompositeOp: return(image->endian == LSBEndian ? "revo" : "over"); case PinLightCompositeOp: return(image->endian == LSBEndian ? "tiLp" : "pLit"); case SaturateCompositeOp: return(image->endian == LSBEndian ? " tas" : "sat "); case ScreenCompositeOp: return(image->endian == LSBEndian ? "nrcs" : "scrn"); case SoftLightCompositeOp: return(image->endian == LSBEndian ? "tiLs" : "sLit"); case VividLightCompositeOp: return(image->endian == LSBEndian ? "tiLv" : "vLit"); case OverCompositeOp: default: return(image->endian == LSBEndian ? "mron" : "norm"); } } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if ((image->alpha_trait != BlendPixelTrait) || (image->colorspace != sRGBColorspace)) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; register ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == OpaqueAlpha) return(MagickTrue); if (image->alpha_trait != BlendPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))* opacity),q); else if (opacity > 0) SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/ (MagickRealType) opacity)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; PixelInfo color; ssize_t y; if (image->alpha_trait == UndefinedPixelTrait) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,0,0,MagickTrue,exception); if (complete_mask == (Image *) NULL) return(MagickFalse); complete_mask->alpha_trait=BlendPixelTrait; GetPixelInfo(complete_mask,&color); color.red=(MagickRealType) background; (void) SetImageColor(complete_mask,&color,exception); status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue, mask->page.x-image->page.x,mask->page.y-image->page.y,exception); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register Quantum *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=(MagickRealType) GetPixelAlpha(image,q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q); else if (intensity > 0) SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q); q+=GetPixelChannels(image); p+=GetPixelChannels(complete_mask); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=(char) layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(const Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); } if (image->depth > 16) return(4); if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static StringInfo *ParseImageResourceBlocks(PSDInfo *psd_info,Image *image, const unsigned char *blocks,size_t length) { const unsigned char *p; ssize_t offset; StringInfo *profile; unsigned char name_length; unsigned int count; unsigned short id, short_sans; if (length < 16) return((StringInfo *) NULL); profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); SetStringInfoName(profile,"8bim"); for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p+=4; p=PushShortPixel(MSBEndian,p,&id); p=PushCharPixel(p,&name_length); if ((name_length % 2) == 0) name_length++; p+=name_length; if (p > (blocks+length-4)) break; p=PushLongPixel(MSBEndian,p,&count); offset=(ssize_t) count; if (((p+offset) < blocks) || ((p+offset) > (blocks+length))) break; switch (id) { case 0x03ed: { unsigned short resolution; /* Resolution info. */ if (offset < 16) break; p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatImageProperty(image,"tiff:XResolution","%*g", GetMagickPrecision(),image->resolution.x); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatImageProperty(image,"tiff:YResolution","%*g", GetMagickPrecision(),image->resolution.y); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if ((offset > 4) && (*(p+4) == 0)) psd_info->has_merged_image=MagickFalse; p+=offset; break; } default: { p+=offset; break; } } if ((offset & 0x01) != 0) p++; } return(profile); } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q, ExceptionInfo *exception) { if (image->storage_class == PseudoClass) { PixelInfo *color; Quantum index; index=pixel; if (packet_size == 1) index=(Quantum) ScaleQuantumToChar(index); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) index, exception); if (type == 0) SetPixelIndex(image,index,q); if ((type == 0) && (channels > 1)) return; color=image->colormap+(ssize_t) GetPixelIndex(image,q); if (type != 0) color->alpha=(MagickRealType) pixel; SetPixelViaPixelInfo(image,color,q); return; } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); break; } case -3: case 1: { SetPixelGreen(image,pixel,q); break; } case -4: case 2: { SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const ssize_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else if (packet_size == 2) { unsigned short nibble; p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } else { MagickFloatType nibble; p=PushFloatPixel(MSBEndian,p,&nibble); pixel=ClampToQuantum((MagickRealType) (QuantumRange*nibble)); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); q+=GetPixelChannels(image); } else { ssize_t bit, number_bits; number_bits=(ssize_t) image->columns-x; if (number_bits > 8) number_bits=8; for (bit = 0; bit < (ssize_t) number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception); q+=GetPixelChannels(image); x++; } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t row_size; ssize_t count, y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(pixels,0,row_size*sizeof(*pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != (ssize_t) row_size) { status=MagickFalse; break; } status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; if (length > (row_size+2048)) /* arbitrary number */ { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength",image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); if ((MagickSizeType) compact_size > GetBlobSize(image)) ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) count; if (inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream,Z_SYNC_FLUSH); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { (void) inflateEnd(&stream); compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } if (ret == Z_STREAM_END) break; } (void) inflateEnd(&stream); } if (compression == ZipWithPrediction) { p=pixels; while (count > 0) { length=image->columns; while (--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } /* else if (packet_size == 4) { TODO: Figure out what to do there. } */ else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { (void) SeekBlob(image,(MagickOffsetType) layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { (void) ResetImagePixels(mask,exception); (void) SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, (ssize_t) layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, (ssize_t) layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, (ssize_t) layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } (void) SeekBlob(image,offset+layer_info->channel_info[channel].size-2, SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) (void) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (layer_info->mask.image != (Image *) NULL) layer_info->mask.image=DestroyImage(layer_info->mask.image); layer_info->mask.image=mask; } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); /* TODO: Remove this when we figure out how to support this */ if ((compression == ZipWithPrediction) && (image->depth == 32)) { (void) ThrowMagickException(exception,GetMagickModule(), TypeError,"CompressionNotSupported","ZipWithPrediction(32 bit)"); return(MagickFalse); } layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info, (size_t) j,compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } static MagickBooleanType CheckPSDChannels(const PSDInfo *psd_info, LayerInfo *layer_info) { int channel_type; register ssize_t i; if (layer_info->channels < psd_info->min_channels) return(MagickFalse); channel_type=RedChannel; if (psd_info->min_channels >= 3) channel_type|=(GreenChannel | BlueChannel); if (psd_info->min_channels >= 4) channel_type|=BlackChannel; for (i=0; i < (ssize_t) layer_info->channels; i++) { short type; type=layer_info->channel_info[i].type; if ((i == 0) && (psd_info->mode == IndexedMode) && (type != 0)) return(MagickFalse); if (type == -1) { channel_type|=AlphaChannel; continue; } if (type < -1) continue; if (type == 0) channel_type&=~RedChannel; else if (type == 1) channel_type&=~GreenChannel; else if (type == 2) channel_type&=~BlueChannel; else if (type == 3) channel_type&=~BlackChannel; } if (channel_type == 0) return(MagickTrue); if ((channel_type == AlphaChannel) && (layer_info->channels >= psd_info->min_channels + 1)) return(MagickTrue); return(MagickFalse); } static void AttachPSDLayers(Image *image,LayerInfo *layer_info, ssize_t number_layers) { register ssize_t i; ssize_t j; for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers == 0) { layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); return; } for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } static inline MagickBooleanType PSDSkipImage(const PSDInfo *psd_info, const ImageInfo *image_info,const size_t index) { if (psd_info->has_merged_image == MagickFalse) return(MagickFalse); if (image_info->number_scenes == 0) return(MagickFalse); if (index < image_info->scene) return(MagickTrue); if (index > image_info->scene+image_info->number_scenes-1) return(MagickTrue); return(MagickFalse); } static void CheckMergedImageAlpha(const PSDInfo *psd_info,Image *image) { /* The number of layers cannot be used to determine if the merged image contains an alpha channel. So we enable it when we think we should. */ if (((psd_info->mode == GrayscaleMode) && (psd_info->channels > 2)) || ((psd_info->mode == RGBMode) && (psd_info->channels > 3)) || ((psd_info->mode == CMYKMode) && (psd_info->channels > 4))) image->alpha_trait=BlendPixelTrait; } static void ParseAdditionalInfo(LayerInfo *layer_info) { char key[5]; MagickBooleanType found; register size_t i; size_t remaining_length; unsigned char *p; unsigned int size; p=GetStringInfoDatum(layer_info->info); remaining_length=GetStringInfoLength(layer_info->info); while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(char) (*p++); key[1]=(char) (*p++); key[2]=(char) (*p++); key[3]=(char) (*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) break; if (LocaleNCompare(key,"luni",sizeof(key)) == 0) { unsigned char *name; unsigned int length; p+=4; length=(size-4)/2; if (sizeof(layer_info->name) <= length) break; name=layer_info->name; while (length > 0) { /* Only ASCII strings are supported */ if (*p++ != '\0') break; *name++=*p++; length--; } if (length == 0) *name='\0'; break; } else p+=size; remaining_length-=(size_t) size; } } static MagickBooleanType ReadPSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, index, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); if (count == 4) ReversePSDString(image,type,(size_t) count); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) { CheckMergedImageAlpha(psd_info,image); return(MagickTrue); } else { count=ReadBlob(image,4,(unsigned char *) type); if (count == 4) ReversePSDString(image,type,4); if ((count == 4) && ((LocaleNCompare(type,"Lr16",4) == 0) || (LocaleNCompare(type,"Lr32",4) == 0))) size=GetPSDSize(psd_info,image); else { CheckMergedImageAlpha(psd_info,image); return(MagickTrue); } } } if (size == 0) return(MagickTrue); layer_info=(LayerInfo *) NULL; number_layers=(ssize_t) ReadBlobSignedShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(layer_info,0,(size_t) number_layers*sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t top, left, bottom, right; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); top=(ssize_t) ReadBlobSignedLong(image); left=(ssize_t) ReadBlobSignedLong(image); bottom=(ssize_t) ReadBlobSignedLong(image); right=(ssize_t) ReadBlobSignedLong(image); if ((right < left) || (bottom < top)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } layer_info[i].page.y=top; layer_info[i].page.x=left; layer_info[i].page.width=(size_t) (right-left); layer_info[i].page.height=(size_t) (bottom-top); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); if ((layer_info[i].channel_info[j].type < -4) || (layer_info[i].channel_info[j].type > 4)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"NoSuchImageChannel", image->filename); } layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } if (CheckPSDChannels(psd_info,&layer_info[i]) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) type); if (count == 4) ReversePSDString(image,type,4); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); if (count != 4) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(ssize_t) ReadBlobSignedLong(image); layer_info[i].mask.page.x=(ssize_t) ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)-layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) ( ReadBlobSignedLong(image)-layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,(double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; if (length > GetBlobSize(image)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); ParseAdditionalInfo(&layer_info[i]); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info,exception); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping != MagickFalse) { AttachPSDLayers(image,layer_info,number_layers); return(MagickTrue); } status=MagickTrue; index=0; for (i=0; i < number_layers; i++) { if ((layer_info[i].image == (Image *) NULL) || (PSDSkipImage(psd_info, image_info,++index) != MagickFalse)) { for (j=0; j < (ssize_t) layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i, (MagickSizeType) number_layers); if (status == MagickFalse) break; } if (status != MagickFalse) AttachPSDLayers(image,layer_info,number_layers); else layer_info=DestroyLayerInfo(layer_info,number_layers); return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception) { PolicyDomain domain; PolicyRights rights; domain=CoderPolicyDomain; rights=ReadPolicyRights; if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse) return(MagickTrue); return(ReadPSDLayersInternal(image,image_info,psd_info,MagickFalse, exception)); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *sizes; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; if ((image_info->number_scenes != 0) && (image_info->scene != 0)) return(MagickTrue); compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { ssize_t type; type=i; if ((type == 1) && (psd_info->channels == 2)) type=-1; if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,type,sizes+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,type,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i, psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t imageListLength; ssize_t count; StringInfo *profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count != 4) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels < 1) ThrowReaderException(CorruptImageError,"MissingImageChannel"); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16) && (psd_info.depth != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if ((psd_info.mode == IndexedMode) && (psd_info.channels > 3)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); status=ResetImagePixels(image,exception); if (status == MagickFalse) return(DestroyImageList(image)); psd_info.min_channels=3; if (psd_info.mode == LabMode) (void) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { psd_info.min_channels=4; (void) SetImageColorspace(image,CMYKColorspace,exception); } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { if (psd_info.depth != 32) { status=AcquireImageColormap(image,MagickMin((size_t) (psd_info.depth < 16 ? 256 : 65536), MaxColormapSize),exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); } psd_info.min_channels=1; (void) SetImageColorspace(image,GRAYColorspace,exception); } else if (psd_info.mode == IndexedMode) psd_info.min_channels=1; if (psd_info.channels < psd_info.min_channels) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if ((psd_info.mode == IndexedMode) && (length < 3)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if ((psd_info.mode == DuotoneMode) || (psd_info.depth == 32)) { /* Duotone image data; the format of this data is undocumented. 32 bits per pixel; the colormap is ignored. */ (void) SeekBlob(image,(const MagickOffsetType) length,SEEK_CUR); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=(size_t) length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); psd_info.has_merged_image=MagickTrue; profile=(StringInfo *) NULL; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } profile=ParseImageResourceBlocks(&psd_info,image,blocks,(size_t) length); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (psd_info.has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers, exception) != MagickTrue) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ (void) SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (EOFBlob(image) != MagickFalse) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } if (image_info->ping != MagickFalse) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); imageListLength=GetImageListLength(image); if ((psd_info.has_merged_image != MagickFalse) || (imageListLength == 1)) psd_info.has_merged_image=(MagickBooleanType) ReadPSDMergedImage( image_info,image,&psd_info,exception); if ((psd_info.has_merged_image == MagickFalse) && (imageListLength == 1) && (length != 0)) { (void) SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse, exception); if (status != MagickTrue) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if (psd_info.has_merged_image == MagickFalse) { Image *merged; if (imageListLength == 1) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); } image->background_color.alpha=(MagickRealType) TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(image,exception); merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } if (profile != (StringInfo *) NULL) { Image *next; i=0; next=image; while (next != (Image *) NULL) { if (PSDSkipImage(&psd_info,image_info,i++) == MagickFalse) (void) SetImageProfile(next,GetStringInfoName(profile),profile, exception); next=next->next; } profile=DestroyStringInfo(profile); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned int) offset)); } static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickOffsetType offset) { MagickOffsetType current_offset; ssize_t result; current_offset=TellBlob(image); (void) SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=WriteBlobMSBLong(image,(unsigned int) size); (void) SeekBlob(image,current_offset,SEEK_SET); return(result); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobLong(image,(unsigned int) size)); return(WriteBlobLongLong(image,size)); } static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickOffsetType offset) { MagickOffsetType current_offset; ssize_t result; current_offset=TellBlob(image); (void) SeekBlob(image,offset,SEEK_SET); result=SetPSDSize(psd_info,image,size); (void) SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const CompressionType compression, const ssize_t channels) { size_t length; ssize_t i, y; if (compression == RLECompression) { length=(size_t) WriteBlobShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (compression == ZipCompression) length=(size_t) WriteBlobShort(image,ZipWithoutPrediction); #endif else length=(size_t) WriteBlobShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, const CompressionType compression,ExceptionInfo *exception) { MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t count, length; ssize_t y; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,compression,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory( MagickMinBufferExtent,sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) MagickMinBufferExtent; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) MagickMinBufferExtent-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(const Image *image, ExceptionInfo *exception) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); } return(compact_pixels); } static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { CompressionType compression; Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; compression=next_image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; if (compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if ((next_image->storage_class != PseudoClass) || (IsImageGray(next_image) != MagickFalse)) { if (IsImageGray(next_image) == MagickFalse) channels=(size_t) (next_image->colorspace == CMYKColorspace ? 4 : 3); if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,compression, (ssize_t) channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if ((next_image->storage_class == PseudoClass) && (IsImageGray(next_image) == MagickFalse)) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,compression, exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=(size_t) WriteBlobShort(image,(const unsigned short) channel); count+=SetPSDSize(psd_info,image,0); return(count); } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) memmove(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)) && ((ssize_t) length-(cnt+12)-(q-datum)) > 0) { (void) memmove(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(char) (*p++); key[1]=(char) (*p++); key[2]=(char) (*p++); key[3]=(char) (*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) memmove(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); (void) SetImageProfile(image,"psd:additional-info",info,exception); return(profile); } static MagickBooleanType WritePSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,size_t *layers_size, ExceptionInfo *exception) { char layer_name[MagickPathExtent]; const char *property; const StringInfo *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; register ssize_t i; size_t layer_count, layer_index, length, name_length, rounded_size, size; status=MagickTrue; base_image=GetNextImageInList(image); if (base_image == (Image *) NULL) base_image=image; size=0; size_offset=TellBlob(image); (void) SetPSDSize(psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->alpha_trait != UndefinedPixelTrait) size+=WriteBlobShort(image,-(unsigned short) layer_count); else size+=WriteBlobShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception); default_color=(unsigned char) (strlen(property) == 9 ? 255 : 0); } size+=WriteBlobSignedLong(image,(signed int) next_image->page.y); size+=WriteBlobSignedLong(image,(signed int) next_image->page.x); size+=WriteBlobSignedLong(image,(signed int) (next_image->page.y+ next_image->rows)); size+=WriteBlobSignedLong(image,(signed int) (next_image->page.x+ next_image->columns)); channels=1; if ((next_image->storage_class != PseudoClass) && (IsImageGray(next_image) == MagickFalse)) channels=(unsigned short) (next_image->colorspace == CMYKColorspace ? 4 : 3); total_channels=channels; if (next_image->alpha_trait != UndefinedPixelTrait) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(psd_info,image,(signed short) i); if (next_image->alpha_trait != UndefinedPixelTrait) size+=WriteChannelSize(psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(psd_info,image,-2); size+=WriteBlobString(image,image->endian == LSBEndian ? "MIB8" :"8BIM"); size+=WriteBlobString(image,CompositeOperatorToPSDBlendMode(next_image)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,(const unsigned char) (next_image->compose == NoCompositeOp ? 1 << 0x02 : 1)); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image,exception); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MagickPathExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobLong(image,20); size+=WriteBlobSignedLong(image,(const signed int) mask->page.y); size+=WriteBlobSignedLong(image,(const signed int) mask->page.x); size+=WriteBlobSignedLong(image,(const signed int) (mask->rows+ mask->page.y)); size+=WriteBlobSignedLong(image,(const signed int) (mask->columns+ mask->page.x)); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,(const unsigned char) (mask->compose == NoCompositeOp ? 2 : 0)); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue,exception); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } /* Write the total size */ if (layers_size != (size_t*) NULL) *layers_size=size; if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) (void) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } return(status); } ModuleExport MagickBooleanType WritePSDLayers(Image * image, const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception) { PolicyDomain domain; PolicyRights rights; domain=CoderPolicyDomain; rights=WritePolicyRights; if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse) return(MagickTrue); return WritePSDLayersInternal(image,image_info,psd_info,(size_t*) NULL, exception); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const StringInfo *icc_profile; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t length, num_channels, packet_size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ /* When the image has a color profile it won't be converted to gray scale */ if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) && (SetImageGray(image,exception) != MagickFalse)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((ssize_t) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } if (status != MagickFalse) { MagickOffsetType size_offset; size_t size; size_offset=TellBlob(image); (void) SetPSDSize(&psd_info,image,0); status=WritePSDLayersInternal(image,image_info,&psd_info,&size, exception); size_offset+=WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 12),size_offset); } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image_info->compression != UndefinedCompression) image->compression=image_info->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse, exception) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
draw.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD RRRR AAA W W % % D D R R A A W W % % D D RRRR AAAAA W W W % % D D R RN A A WW WW % % DDDD R R A A W W % % % % % % MagickCore Image Drawing Methods % % % % % % Software Design % % Cristy % % July 1998 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon % rendering code based on Paul Heckbert's "Concave Polygon Scan Conversion", % Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent % (www.appligent.com) contributed the dash pattern, linecap stroking % algorithm, and minor rendering improvements. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/annotate.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/draw-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/transform-private.h" #include "MagickCore/utility.h" /* Define declarations. */ #define BezierQuantum 200 #define DrawEpsilon (1.0e-10) /* Typedef declarations. */ typedef struct _EdgeInfo { SegmentInfo bounds; double scanline; PointInfo *points; size_t number_points; ssize_t direction; MagickBooleanType ghostline; size_t highwater; } EdgeInfo; typedef struct _ElementInfo { double cx, cy, major, minor, angle; } ElementInfo; typedef struct _PolygonInfo { EdgeInfo *edges; size_t number_edges; } PolygonInfo; typedef enum { MoveToCode, OpenCode, GhostlineCode, LineToCode, EndCode } PathInfoCode; typedef struct _PathInfo { PointInfo point; PathInfoCode code; } PathInfo; /* Forward declarations. */ static MagickBooleanType DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *, ExceptionInfo *); static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *); static size_t TracePath(PrimitiveInfo *,const char *); static void TraceArc(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo), TraceArcPath(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo, const double,const MagickBooleanType,const MagickBooleanType), TraceBezier(PrimitiveInfo *,const size_t), TraceCircle(PrimitiveInfo *,const PointInfo,const PointInfo), TraceEllipse(PrimitiveInfo *,const PointInfo,const PointInfo, const PointInfo), TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRoundRectangle(PrimitiveInfo *,const PointInfo,const PointInfo, PointInfo), TraceSquareLinecap(PrimitiveInfo *,const size_t,const double); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireDrawInfo() returns a DrawInfo structure properly initialized. % % The format of the AcquireDrawInfo method is: % % DrawInfo *AcquireDrawInfo(void) % */ MagickExport DrawInfo *AcquireDrawInfo(void) { DrawInfo *draw_info; draw_info=(DrawInfo *) AcquireMagickMemory(sizeof(*draw_info)); if (draw_info == (DrawInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); GetDrawInfo((ImageInfo *) NULL,draw_info); return(draw_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneDrawInfo() makes a copy of the given draw_info structure. If NULL % is specified, a new DrawInfo structure is created initialized to default % values. % % The format of the CloneDrawInfo method is: % % DrawInfo *CloneDrawInfo(const ImageInfo *image_info, % const DrawInfo *draw_info) % % A description of each parameter follows: % % o image_info: the image info. % % o draw_info: the draw info. % */ MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info, const DrawInfo *draw_info) { DrawInfo *clone_info; ExceptionInfo *exception; clone_info=(DrawInfo *) AcquireMagickMemory(sizeof(*clone_info)); if (clone_info == (DrawInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); GetDrawInfo(image_info,clone_info); if (draw_info == (DrawInfo *) NULL) return(clone_info); exception=AcquireExceptionInfo(); if (clone_info->primitive != (char *) NULL) (void) CloneString(&clone_info->primitive,draw_info->primitive); if (draw_info->geometry != (char *) NULL) (void) CloneString(&clone_info->geometry,draw_info->geometry); clone_info->viewbox=draw_info->viewbox; clone_info->affine=draw_info->affine; clone_info->gravity=draw_info->gravity; clone_info->fill=draw_info->fill; clone_info->stroke=draw_info->stroke; clone_info->stroke_width=draw_info->stroke_width; if (draw_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue, exception); if (draw_info->stroke_pattern != (Image *) NULL) clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0, MagickTrue,exception); clone_info->stroke_antialias=draw_info->stroke_antialias; clone_info->text_antialias=draw_info->text_antialias; clone_info->fill_rule=draw_info->fill_rule; clone_info->linecap=draw_info->linecap; clone_info->linejoin=draw_info->linejoin; clone_info->miterlimit=draw_info->miterlimit; clone_info->dash_offset=draw_info->dash_offset; clone_info->decorate=draw_info->decorate; clone_info->compose=draw_info->compose; if (draw_info->text != (char *) NULL) (void) CloneString(&clone_info->text,draw_info->text); if (draw_info->font != (char *) NULL) (void) CloneString(&clone_info->font,draw_info->font); if (draw_info->metrics != (char *) NULL) (void) CloneString(&clone_info->metrics,draw_info->metrics); if (draw_info->family != (char *) NULL) (void) CloneString(&clone_info->family,draw_info->family); clone_info->style=draw_info->style; clone_info->stretch=draw_info->stretch; clone_info->weight=draw_info->weight; if (draw_info->encoding != (char *) NULL) (void) CloneString(&clone_info->encoding,draw_info->encoding); clone_info->pointsize=draw_info->pointsize; clone_info->kerning=draw_info->kerning; clone_info->interline_spacing=draw_info->interline_spacing; clone_info->interword_spacing=draw_info->interword_spacing; clone_info->direction=draw_info->direction; if (draw_info->density != (char *) NULL) (void) CloneString(&clone_info->density,draw_info->density); clone_info->align=draw_info->align; clone_info->undercolor=draw_info->undercolor; clone_info->border_color=draw_info->border_color; if (draw_info->server_name != (char *) NULL) (void) CloneString(&clone_info->server_name,draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) { register ssize_t x; for (x=0; fabs(draw_info->dash_pattern[x]) >= DrawEpsilon; x++) ; clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) x+1UL, sizeof(*clone_info->dash_pattern)); if (clone_info->dash_pattern == (double *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) CopyMagickMemory(clone_info->dash_pattern,draw_info->dash_pattern, (size_t) (x+1)*sizeof(*clone_info->dash_pattern)); } clone_info->gradient=draw_info->gradient; if (draw_info->gradient.stops != (StopInfo *) NULL) { size_t number_stops; number_stops=clone_info->gradient.number_stops; clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t) number_stops,sizeof(*clone_info->gradient.stops)); if (clone_info->gradient.stops == (StopInfo *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) CopyMagickMemory(clone_info->gradient.stops, draw_info->gradient.stops,(size_t) number_stops* sizeof(*clone_info->gradient.stops)); } if (draw_info->clip_mask != (char *) NULL) (void) CloneString(&clone_info->clip_mask,draw_info->clip_mask); clone_info->bounds=draw_info->bounds; clone_info->clip_units=draw_info->clip_units; clone_info->render=draw_info->render; clone_info->fill_alpha=draw_info->fill_alpha; clone_info->stroke_alpha=draw_info->stroke_alpha; clone_info->element_reference=draw_info->element_reference; clone_info->debug=IsEventLogging(); exception=DestroyExceptionInfo(exception); return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n v e r t P a t h T o P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvertPathToPolygon() converts a path to the more efficient sorted % rendering form. % % The format of the ConvertPathToPolygon method is: % % PolygonInfo *ConvertPathToPolygon(const DrawInfo *draw_info, % const PathInfo *path_info) % % A description of each parameter follows: % % o Method ConvertPathToPolygon returns the path in a more efficient sorted % rendering form of type PolygonInfo. % % o draw_info: Specifies a pointer to an DrawInfo structure. % % o path_info: Specifies a pointer to an PathInfo structure. % % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int CompareEdges(const void *x,const void *y) { register const EdgeInfo *p, *q; /* Compare two edges. */ p=(const EdgeInfo *) x; q=(const EdgeInfo *) y; if ((p->points[0].y-DrawEpsilon) > q->points[0].y) return(1); if ((p->points[0].y+DrawEpsilon) < q->points[0].y) return(-1); if ((p->points[0].x-DrawEpsilon) > q->points[0].x) return(1); if ((p->points[0].x+DrawEpsilon) < q->points[0].x) return(-1); if (((p->points[1].x-p->points[0].x)*(q->points[1].y-q->points[0].y)- (p->points[1].y-p->points[0].y)*(q->points[1].x-q->points[0].x)) > 0.0) return(1); return(-1); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static void LogPolygonInfo(const PolygonInfo *polygon_info) { register EdgeInfo *p; register ssize_t i, j; (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin active-edge"); p=polygon_info->edges; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { (void) LogMagickEvent(DrawEvent,GetMagickModule()," edge %.20g:", (double) i); (void) LogMagickEvent(DrawEvent,GetMagickModule()," direction: %s", p->direction != MagickFalse ? "down" : "up"); (void) LogMagickEvent(DrawEvent,GetMagickModule()," ghostline: %s", p->ghostline != MagickFalse ? "transparent" : "opaque"); (void) LogMagickEvent(DrawEvent,GetMagickModule(), " bounds: %g,%g - %g,%g",p->bounds.x1,p->bounds.y1, p->bounds.x2,p->bounds.y2); for (j=0; j < (ssize_t) p->number_points; j++) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %g,%g", p->points[j].x,p->points[j].y); p++; } (void) LogMagickEvent(DrawEvent,GetMagickModule()," end active-edge"); } static void ReversePoints(PointInfo *points,const size_t number_points) { PointInfo point; register ssize_t i; for (i=0; i < (ssize_t) (number_points >> 1); i++) { point=points[i]; points[i]=points[number_points-(i+1)]; points[number_points-(i+1)]=point; } } static PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info) { long direction, next_direction; PointInfo point, *points; PolygonInfo *polygon_info; SegmentInfo bounds; register ssize_t i, n; MagickBooleanType ghostline; size_t edge, number_edges, number_points; /* Convert a path to the more efficient sorted rendering form. */ polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info)); if (polygon_info == (PolygonInfo *) NULL) return((PolygonInfo *) NULL); number_edges=16; polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory(number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); (void) ResetMagickMemory(polygon_info->edges,0,number_edges* sizeof(*polygon_info->edges)); direction=0; edge=0; ghostline=MagickFalse; n=0; number_points=0; points=(PointInfo *) NULL; (void) ResetMagickMemory(&point,0,sizeof(point)); (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); for (i=0; path_info[i].code != EndCode; i++) { if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) || (path_info[i].code == GhostlineCode)) { /* Move to. */ if ((points != (PointInfo *) NULL) && (n >= 2)) { if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; points=(PointInfo *) NULL; ghostline=MagickFalse; edge++; } if (points == (PointInfo *) NULL) { number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); } ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse; point=path_info[i].point; points[0]=point; bounds.x1=point.x; bounds.x2=point.x; direction=0; n=1; continue; } /* Line to. */ next_direction=((path_info[i].point.y > point.y) || ((fabs(path_info[i].point.y-point.y) < DrawEpsilon) && (path_info[i].point.x > point.x))) ? 1 : -1; if ((points != (PointInfo *) NULL) && (direction != 0) && (direction != next_direction)) { /* New edge. */ point=points[n-1]; if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); n=1; ghostline=MagickFalse; points[0]=point; bounds.x1=point.x; bounds.x2=point.x; edge++; } direction=next_direction; if (points == (PointInfo *) NULL) continue; if (n == (ssize_t) number_points) { number_points<<=1; points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); } point=path_info[i].point; points[n]=point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.x > bounds.x2) bounds.x2=point.x; n++; } if (points != (PointInfo *) NULL) { if (n < 2) points=(PointInfo *) RelinquishMagickMemory(points); else { if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; ghostline=MagickFalse; edge++; } } polygon_info->number_edges=edge; qsort(polygon_info->edges,(size_t) polygon_info->number_edges, sizeof(*polygon_info->edges),CompareEdges); if (IsEventLogging() != MagickFalse) LogPolygonInfo(polygon_info); return(polygon_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n v e r t P r i m i t i v e T o P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector % path structure. % % The format of the ConvertPrimitiveToPath method is: % % PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info, % const PrimitiveInfo *primitive_info) % % A description of each parameter follows: % % o Method ConvertPrimitiveToPath returns a vector path structure of type % PathInfo. % % o draw_info: a structure of type DrawInfo. % % o primitive_info: Specifies a pointer to an PrimitiveInfo structure. % % */ static void LogPathInfo(const PathInfo *path_info) { register const PathInfo *p; (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin vector-path"); for (p=path_info; p->code != EndCode; p++) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %g,%g %s",p->point.x,p->point.y,p->code == GhostlineCode ? "moveto ghostline" : p->code == OpenCode ? "moveto open" : p->code == MoveToCode ? "moveto" : p->code == LineToCode ? "lineto" : "?"); (void) LogMagickEvent(DrawEvent,GetMagickModule()," end vector-path"); } static PathInfo *ConvertPrimitiveToPath(const PrimitiveInfo *primitive_info) { PathInfo *path_info; PathInfoCode code; PointInfo p, q; register ssize_t i, n; ssize_t coordinates, start; /* Converts a PrimitiveInfo structure into a vector path structure. */ switch (primitive_info->primitive) { case AlphaPrimitive: case ColorPrimitive: case ImagePrimitive: case PointPrimitive: case TextPrimitive: return((PathInfo *) NULL); default: break; } for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; path_info=(PathInfo *) AcquireQuantumMemory((size_t) (2UL*i+3UL), sizeof(*path_info)); if (path_info == (PathInfo *) NULL) return((PathInfo *) NULL); coordinates=0; n=0; p.x=(-1.0); p.y=(-1.0); q.x=(-1.0); q.y=(-1.0); start=0; for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { code=LineToCode; if (coordinates <= 0) { coordinates=(ssize_t) primitive_info[i].coordinates; p=primitive_info[i].point; start=n; code=MoveToCode; } coordinates--; /* Eliminate duplicate points. */ if ((i == 0) || (fabs(q.x-primitive_info[i].point.x) >= DrawEpsilon) || (fabs(q.y-primitive_info[i].point.y) >= DrawEpsilon)) { path_info[n].code=code; path_info[n].point=primitive_info[i].point; q=primitive_info[i].point; n++; } if (coordinates > 0) continue; if ((fabs(p.x-primitive_info[i].point.x) < DrawEpsilon) && (fabs(p.y-primitive_info[i].point.y) < DrawEpsilon)) continue; /* Mark the p point as open if it does not match the q. */ path_info[start].code=OpenCode; path_info[n].code=GhostlineCode; path_info[n].point=primitive_info[i].point; n++; path_info[n].code=LineToCode; path_info[n].point=p; n++; } path_info[n].code=EndCode; path_info[n].point.x=0.0; path_info[n].point.y=0.0; if (IsEventLogging() != MagickFalse) LogPathInfo(path_info); return(path_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyDrawInfo() deallocates memory associated with an DrawInfo % structure. % % The format of the DestroyDrawInfo method is: % % DrawInfo *DestroyDrawInfo(DrawInfo *draw_info) % % A description of each parameter follows: % % o draw_info: the draw info. % */ MagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info) { if (draw_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (draw_info->primitive != (char *) NULL) draw_info->primitive=DestroyString(draw_info->primitive); if (draw_info->text != (char *) NULL) draw_info->text=DestroyString(draw_info->text); if (draw_info->geometry != (char *) NULL) draw_info->geometry=DestroyString(draw_info->geometry); if (draw_info->fill_pattern != (Image *) NULL) draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern); if (draw_info->stroke_pattern != (Image *) NULL) draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern); if (draw_info->font != (char *) NULL) draw_info->font=DestroyString(draw_info->font); if (draw_info->metrics != (char *) NULL) draw_info->metrics=DestroyString(draw_info->metrics); if (draw_info->family != (char *) NULL) draw_info->family=DestroyString(draw_info->family); if (draw_info->encoding != (char *) NULL) draw_info->encoding=DestroyString(draw_info->encoding); if (draw_info->density != (char *) NULL) draw_info->density=DestroyString(draw_info->density); if (draw_info->server_name != (char *) NULL) draw_info->server_name=(char *) RelinquishMagickMemory(draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) draw_info->dash_pattern=(double *) RelinquishMagickMemory( draw_info->dash_pattern); if (draw_info->gradient.stops != (StopInfo *) NULL) draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory( draw_info->gradient.stops); if (draw_info->clip_mask != (char *) NULL) draw_info->clip_mask=DestroyString(draw_info->clip_mask); draw_info->signature=(~MagickCoreSignature); draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info); return(draw_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y E d g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyEdge() destroys the specified polygon edge. % % The format of the DestroyEdge method is: % % ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge) % % A description of each parameter follows: % % o polygon_info: Specifies a pointer to an PolygonInfo structure. % % o edge: the polygon edge number to destroy. % */ static size_t DestroyEdge(PolygonInfo *polygon_info, const size_t edge) { assert(edge < polygon_info->number_edges); polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory( polygon_info->edges[edge].points); polygon_info->number_edges--; if (edge < polygon_info->number_edges) (void) CopyMagickMemory(polygon_info->edges+edge,polygon_info->edges+edge+1, (size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges)); return(polygon_info->number_edges); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P o l y g o n I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPolygonInfo() destroys the PolygonInfo data structure. % % The format of the DestroyPolygonInfo method is: % % PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info) % % A description of each parameter follows: % % o polygon_info: Specifies a pointer to an PolygonInfo structure. % */ static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info) { register ssize_t i; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) polygon_info->edges[i].points=(PointInfo *) RelinquishMagickMemory(polygon_info->edges[i].points); polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory(polygon_info->edges); return((PolygonInfo *) RelinquishMagickMemory(polygon_info)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w A f f i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawAffineImage() composites the source over the destination image as % dictated by the affine transform. % % The format of the DrawAffineImage method is: % % MagickBooleanType DrawAffineImage(Image *image,const Image *source, % const AffineMatrix *affine,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o source: the source image. % % o affine: the affine transform. % % o exception: return any errors or warnings in this structure. % */ static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine, const double y,const SegmentInfo *edge) { double intercept, z; register double x; SegmentInfo inverse_edge; /* Determine left and right edges. */ inverse_edge.x1=edge->x1; inverse_edge.y1=edge->y1; inverse_edge.x2=edge->x2; inverse_edge.y2=edge->y2; z=affine->ry*y+affine->tx; if (affine->sx >= DrawEpsilon) { intercept=(-z/affine->sx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->sx < -DrawEpsilon) { intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->sx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns)) { inverse_edge.x2=edge->x1; return(inverse_edge); } /* Determine top and bottom edges. */ z=affine->sy*y+affine->ty; if (affine->rx >= DrawEpsilon) { intercept=(-z/affine->rx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->rx < -DrawEpsilon) { intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->rx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows)) { inverse_edge.x2=edge->x2; return(inverse_edge); } return(inverse_edge); } static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine) { AffineMatrix inverse_affine; double determinant; determinant=PerceptibleReciprocal(affine->sx*affine->sy-affine->rx* affine->ry); inverse_affine.sx=determinant*affine->sy; inverse_affine.rx=determinant*(-affine->rx); inverse_affine.ry=determinant*(-affine->ry); inverse_affine.sy=determinant*affine->sx; inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty* inverse_affine.ry; inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty* inverse_affine.sy; return(inverse_affine); } MagickExport MagickBooleanType DrawAffineImage(Image *image, const Image *source,const AffineMatrix *affine,ExceptionInfo *exception) { AffineMatrix inverse_affine; CacheView *image_view, *source_view; MagickBooleanType status; PixelInfo zero; PointInfo extent[4], min, max; register ssize_t i; SegmentInfo edge; ssize_t start, stop, y; /* Determine bounding box. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(source != (const Image *) NULL); assert(source->signature == MagickCoreSignature); assert(affine != (AffineMatrix *) NULL); extent[0].x=0.0; extent[0].y=0.0; extent[1].x=(double) source->columns-1.0; extent[1].y=0.0; extent[2].x=(double) source->columns-1.0; extent[2].y=(double) source->rows-1.0; extent[3].x=0.0; extent[3].y=(double) source->rows-1.0; for (i=0; i < 4; i++) { PointInfo point; point=extent[i]; extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx; extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty; } min=extent[0]; max=extent[0]; for (i=1; i < 4; i++) { if (min.x > extent[i].x) min.x=extent[i].x; if (min.y > extent[i].y) min.y=extent[i].y; if (max.x < extent[i].x) max.x=extent[i].x; if (max.y < extent[i].y) max.y=extent[i].y; } /* Affine transform image. */ if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; edge.x1=MagickMax(min.x,0.0); edge.y1=MagickMax(min.y,0.0); edge.x2=MagickMin(max.x,(double) image->columns-1.0); edge.y2=MagickMin(max.y,(double) image->rows-1.0); inverse_affine=InverseAffineMatrix(affine); GetPixelInfo(image,&zero); start=(ssize_t) ceil(edge.y1-0.5); stop=(ssize_t) floor(edge.y2+0.5); source_view=AcquireVirtualCacheView(source,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(source,image,1,1) #endif for (y=start; y <= stop; y++) { PixelInfo composite, pixel; PointInfo point; register ssize_t x; register Quantum *magick_restrict q; SegmentInfo inverse_edge; ssize_t x_offset; inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge); if (inverse_edge.x2 < inverse_edge.x1) continue; q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1- 0.5),y,(size_t) (floor(inverse_edge.x2+0.5)-ceil(inverse_edge.x1-0.5)+1), 1,exception); if (q == (Quantum *) NULL) continue; pixel=zero; composite=zero; x_offset=0; for (x=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) floor(inverse_edge.x2+0.5); x++) { point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+ inverse_affine.tx; point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+ inverse_affine.ty; (void) InterpolatePixelInfo(source,source_view,UndefinedInterpolatePixel, point.x,point.y,&pixel,exception); GetPixelInfoPixel(image,q,&composite); CompositePixelInfoOver(&pixel,pixel.alpha,&composite,composite.alpha, &composite); SetPixelViaPixelInfo(image,&composite,q); x_offset++; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w B o u n d i n g R e c t a n g l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawBoundingRectangles() draws the bounding rectangles on the image. This % is only useful for developers debugging the rendering algorithm. % % The format of the DrawBoundingRectangles method is: % % void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info, % PolygonInfo *polygon_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o polygon_info: Specifies a pointer to a PolygonInfo structure. % % o exception: return any errors or warnings in this structure. % */ static void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info, const PolygonInfo *polygon_info,ExceptionInfo *exception) { DrawInfo *clone_info; double mid; PointInfo end, resolution, start; PrimitiveInfo primitive_info[6]; register ssize_t i; SegmentInfo bounds; ssize_t coordinates; clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) QueryColorCompliance("#000F",AllCompliance,&clone_info->fill, exception); resolution.x=DefaultResolution; resolution.y=DefaultResolution; if (clone_info->density != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(clone_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == MagickFalse) resolution.y=resolution.x; } mid=(resolution.x/72.0)*ExpandAffine(&clone_info->affine)* clone_info->stroke_width/2.0; bounds.x1=0.0; bounds.y1=0.0; bounds.x2=0.0; bounds.y2=0.0; if (polygon_info != (PolygonInfo *) NULL) { bounds=polygon_info->edges[0].bounds; for (i=1; i < (ssize_t) polygon_info->number_edges; i++) { if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1) bounds.x1=polygon_info->edges[i].bounds.x1; if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1) bounds.y1=polygon_info->edges[i].bounds.y1; if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2) bounds.x2=polygon_info->edges[i].bounds.x2; if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2) bounds.y2=polygon_info->edges[i].bounds.y2; } bounds.x1-=mid; bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double) image->columns ? (double) image->columns-1 : bounds.x1; bounds.y1-=mid; bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double) image->rows ? (double) image->rows-1 : bounds.y1; bounds.x2+=mid; bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double) image->columns ? (double) image->columns-1 : bounds.x2; bounds.y2+=mid; bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double) image->rows ? (double) image->rows-1 : bounds.y2; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { if (polygon_info->edges[i].direction != 0) (void) QueryColorCompliance("red",AllCompliance,&clone_info->stroke, exception); else (void) QueryColorCompliance("green",AllCompliance,&clone_info->stroke, exception); start.x=(double) (polygon_info->edges[i].bounds.x1-mid); start.y=(double) (polygon_info->edges[i].bounds.y1-mid); end.x=(double) (polygon_info->edges[i].bounds.x2+mid); end.y=(double) (polygon_info->edges[i].bounds.y2+mid); primitive_info[0].primitive=RectanglePrimitive; TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; (void) DrawPrimitive(image,clone_info,primitive_info,exception); } } (void) QueryColorCompliance("blue",AllCompliance,&clone_info->stroke, exception); start.x=(double) (bounds.x1-mid); start.y=(double) (bounds.y1-mid); end.x=(double) (bounds.x2+mid); end.y=(double) (bounds.y2+mid); primitive_info[0].primitive=RectanglePrimitive; TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; (void) DrawPrimitive(image,clone_info,primitive_info,exception); clone_info=DestroyDrawInfo(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C l i p P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawClipPath() draws the clip path on the image mask. % % The format of the DrawClipPath method is: % % MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info, % const char *name,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o name: the name of the clip path. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DrawClipPath(Image *image, const DrawInfo *draw_info,const char *name,ExceptionInfo *exception) { char filename[MagickPathExtent]; Image *clip_mask; const char *value; DrawInfo *clone_info; MagickStatusType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); (void) FormatLocaleString(filename,MagickPathExtent,"%s",name); value=GetImageArtifact(image,filename); if (value == (const char *) NULL) return(MagickFalse); clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (clip_mask == (Image *) NULL) return(MagickFalse); (void) QueryColorCompliance("#0000",AllCompliance, &clip_mask->background_color,exception); clip_mask->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(clip_mask,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s", draw_info->clip_mask); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,value); (void) QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); clone_info->clip_mask=(char *) NULL; status=NegateImage(clip_mask,MagickFalse,exception); (void) SetImageMask(image,ReadPixelMask,clip_mask,exception); clip_mask=DestroyImage(clip_mask); status&=DrawImage(image,clone_info,exception); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w D a s h P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the % image while respecting the dash offset and dash pattern attributes. % % The format of the DrawDashPolygon method is: % % MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, % const PrimitiveInfo *primitive_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception) { DrawInfo *clone_info; double length, maximum_length, offset, scale, total_length; MagickStatusType status; PrimitiveInfo *dash_polygon; register ssize_t i; register double dx, dy; size_t number_vertices; ssize_t j, n; assert(draw_info != (const DrawInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash"); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; number_vertices=(size_t) i; dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (2UL*number_vertices+1UL),sizeof(*dash_polygon)); if (dash_polygon == (PrimitiveInfo *) NULL) return(MagickFalse); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->miterlimit=0; dash_polygon[0]=primitive_info[0]; scale=ExpandAffine(&draw_info->affine); length=scale*(draw_info->dash_pattern[0]-0.5); offset=fabs(draw_info->dash_offset) >= DrawEpsilon ? scale*draw_info->dash_offset : 0.0; j=1; for (n=0; offset > 0.0; j=0) { if (draw_info->dash_pattern[n] <= 0.0) break; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); if (offset > length) { offset-=length; n++; length=scale*(draw_info->dash_pattern[n]+0.5); continue; } if (offset < length) { length-=offset; offset=0.0; break; } offset=0.0; n++; } status=MagickTrue; maximum_length=0.0; total_length=0.0; for (i=1; (i < (ssize_t) number_vertices) && (length >= 0.0); i++) { dx=primitive_info[i].point.x-primitive_info[i-1].point.x; dy=primitive_info[i].point.y-primitive_info[i-1].point.y; maximum_length=hypot((double) dx,dy); if (fabs(length) < DrawEpsilon) { n++; if (fabs(draw_info->dash_pattern[n]) < DrawEpsilon) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); ) { total_length+=length; if ((n & 0x01) != 0) { dash_polygon[0]=primitive_info[0]; dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx* total_length/maximum_length); dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy* total_length/maximum_length); j=1; } else { if ((j+1) > (ssize_t) (2*number_vertices)) break; dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx* total_length/maximum_length); dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy* total_length/maximum_length); dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); } n++; if (fabs(draw_info->dash_pattern[n]) < DrawEpsilon) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } length-=(maximum_length-total_length); if ((n & 0x01) != 0) continue; dash_polygon[j]=primitive_info[i]; dash_polygon[j].coordinates=1; j++; } if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1)) { dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x+=DrawEpsilon; dash_polygon[j].point.y+=DrawEpsilon; dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); } dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawImage() draws a graphic primitive on your image. The primitive % may be represented as a string or filename. Precede the filename with an % "at" sign (@) and the contents of the file are drawn on the image. You % can affect how text is drawn by setting one or more members of the draw % info structure. % % The format of the DrawImage method is: % % MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType IsPoint(const char *point) { char *p; double value; value=StringToDouble(point,&p); return((fabs(value) < DrawEpsilon) && (p == point) ? MagickFalse : MagickTrue); } static inline void TracePoint(PrimitiveInfo *primitive_info, const PointInfo point) { primitive_info->coordinates=1; primitive_info->point=point; } MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, ExceptionInfo *exception) { #define RenderImageTag "Render/Image" AffineMatrix affine, current; char keyword[MagickPathExtent], geometry[MagickPathExtent], *next_token, pattern[MagickPathExtent], *primitive, *token; const char *q; double angle, factor, primitive_extent; DrawInfo **graphic_context; MagickBooleanType proceed; MagickSizeType length, number_points; MagickStatusType status; PointInfo point; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; register const char *p; register ssize_t i, x; SegmentInfo bounds; size_t extent, number_stops; ssize_t j, k, n; StopInfo *stops; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if ((draw_info->primitive == (char *) NULL) || (*draw_info->primitive == '\0')) return(MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image"); if (*draw_info->primitive != '@') primitive=AcquireString(draw_info->primitive); else primitive=FileToString(draw_info->primitive+1,~0UL,exception); if (primitive == (char *) NULL) return(MagickFalse); primitive_extent=(double) strlen(primitive); (void) SetImageArtifact(image,"MVG",primitive); n=0; number_stops=0; stops=(StopInfo *) NULL; /* Allocate primitive info memory. */ graphic_context=(DrawInfo **) AcquireMagickMemory(sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { primitive=DestroyString(primitive); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } number_points=6553; primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { primitive=DestroyString(primitive); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info); graphic_context[n]->viewbox=image->page; if ((image->page.width == 0) || (image->page.height == 0)) { graphic_context[n]->viewbox.width=image->columns; graphic_context[n]->viewbox.height=image->rows; } token=AcquireString(primitive); extent=strlen(token)+MagickPathExtent; if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; for (q=primitive; *q != '\0'; ) { /* Interpret graphic primitive. */ GetNextToken(q,&q,MagickPathExtent,keyword); if (*keyword == '\0') break; if (*keyword == '#') { /* Comment. */ while ((*q != '\n') && (*q != '\0')) q++; continue; } p=q-strlen(keyword)-1; primitive_type=UndefinedPrimitive; current=graphic_context[n]->affine; GetAffineMatrix(&affine); switch (*keyword) { case ';': break; case 'a': case 'A': { if (LocaleCompare("affine",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.rx=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ry=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("alpha",keyword) == 0) { primitive_type=AlphaPrimitive; break; } if (LocaleCompare("arc",keyword) == 0) { primitive_type=ArcPrimitive; break; } status=MagickFalse; break; } case 'b': case 'B': { if (LocaleCompare("bezier",keyword) == 0) { primitive_type=BezierPrimitive; break; } if (LocaleCompare("border-color",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) QueryColorCompliance(token,AllCompliance, &graphic_context[n]->border_color,exception); break; } status=MagickFalse; break; } case 'c': case 'C': { if (LocaleCompare("clip-path",keyword) == 0) { /* Create clip mask. */ GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->clip_mask,token); (void) DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); break; } if (LocaleCompare("clip-rule",keyword) == 0) { ssize_t fill_rule; GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) status=MagickFalse; else graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("clip-units",keyword) == 0) { ssize_t clip_units; GetNextToken(q,&q,extent,token); clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse, token); if (clip_units == -1) { status=MagickFalse; break; } graphic_context[n]->clip_units=(ClipPathUnits) clip_units; if (clip_units == ObjectBoundingBox) { GetAffineMatrix(&current); affine.sx=draw_info->bounds.x2; affine.sy=draw_info->bounds.y2; affine.tx=draw_info->bounds.x1; affine.ty=draw_info->bounds.y1; break; } break; } if (LocaleCompare("circle",keyword) == 0) { primitive_type=CirclePrimitive; break; } if (LocaleCompare("color",keyword) == 0) { primitive_type=ColorPrimitive; break; } status=MagickFalse; break; } case 'd': case 'D': { if (LocaleCompare("decorate",keyword) == 0) { ssize_t decorate; GetNextToken(q,&q,extent,token); decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse, token); if (decorate == -1) status=MagickFalse; else graphic_context[n]->decorate=(DecorationType) decorate; break; } if (LocaleCompare("density",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->density,token); break; } if (LocaleCompare("direction",keyword) == 0) { ssize_t direction; GetNextToken(q,&q,extent,token); direction=ParseCommandOption(MagickDirectionOptions,MagickFalse, token); if (direction == -1) status=MagickFalse; else graphic_context[n]->direction=(DirectionType) direction; break; } status=MagickFalse; break; } case 'e': case 'E': { if (LocaleCompare("ellipse",keyword) == 0) { primitive_type=EllipsePrimitive; break; } if (LocaleCompare("encoding",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->encoding,token); break; } status=MagickFalse; break; } case 'f': case 'F': { if (LocaleCompare("fill",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->fill_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->fill,exception); if (graphic_context[n]->fill_alpha != OpaqueAlpha) graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha; if (status == MagickFalse) { ImageInfo *pattern_info; pattern_info=AcquireImageInfo(); (void) CopyMagickString(pattern_info->filename,token, MagickPathExtent); graphic_context[n]->fill_pattern=ReadImage(pattern_info, exception); CatchException(exception); pattern_info=DestroyImageInfo(pattern_info); } } break; } if (LocaleCompare("fill-opacity",keyword) == 0) { GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->fill.alpha=QuantumRange-ClampToQuantum( (MagickRealType) QuantumRange*(1.0-factor*StringToDouble(token, &next_token))); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("fill-rule",keyword) == 0) { ssize_t fill_rule; GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) status=MagickFalse; else graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("font",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->font,token); if (LocaleCompare("none",token) == 0) graphic_context[n]->font=(char *) RelinquishMagickMemory( graphic_context[n]->font); break; } if (LocaleCompare("font-family",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->family,token); break; } if (LocaleCompare("font-size",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->pointsize=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("font-stretch",keyword) == 0) { ssize_t stretch; GetNextToken(q,&q,extent,token); stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token); if (stretch == -1) status=MagickFalse; else graphic_context[n]->stretch=(StretchType) stretch; break; } if (LocaleCompare("font-style",keyword) == 0) { ssize_t style; GetNextToken(q,&q,extent,token); style=ParseCommandOption(MagickStyleOptions,MagickFalse,token); if (style == -1) status=MagickFalse; else graphic_context[n]->style=(StyleType) style; break; } if (LocaleCompare("font-weight",keyword) == 0) { ssize_t weight; GetNextToken(q,&q,extent,token); weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(token); graphic_context[n]->weight=(size_t) weight; break; } status=MagickFalse; break; } case 'g': case 'G': { if (LocaleCompare("gradient-units",keyword) == 0) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gravity",keyword) == 0) { ssize_t gravity; GetNextToken(q,&q,extent,token); gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token); if (gravity == -1) status=MagickFalse; else graphic_context[n]->gravity=(GravityType) gravity; break; } status=MagickFalse; break; } case 'i': case 'I': { if (LocaleCompare("image",keyword) == 0) { ssize_t compose; primitive_type=ImagePrimitive; GetNextToken(q,&q,extent,token); compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token); if (compose == -1) status=MagickFalse; else graphic_context[n]->compose=(CompositeOperator) compose; break; } if (LocaleCompare("interline-spacing",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->interline_spacing=StringToDouble(token, &next_token); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("interword-spacing",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=StringToDouble(token, &next_token); if (token == next_token) status=MagickFalse; break; } status=MagickFalse; break; } case 'k': case 'K': { if (LocaleCompare("kerning",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->kerning=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } status=MagickFalse; break; } case 'l': case 'L': { if (LocaleCompare("line",keyword) == 0) primitive_type=LinePrimitive; else status=MagickFalse; break; } case 'o': case 'O': { if (LocaleCompare("offset",keyword) == 0) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("opacity",keyword) == 0) { GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->alpha=QuantumRange*(1.0-(QuantumScale* graphic_context[n]->alpha*(1.0-factor*StringToDouble(token, &next_token)))); graphic_context[n]->fill_alpha=QuantumRange*(1.0-(QuantumScale* graphic_context[n]->fill_alpha*(1.0-factor*StringToDouble(token, &next_token)))); graphic_context[n]->stroke_alpha=QuantumRange*(1.0-(QuantumScale* graphic_context[n]->stroke_alpha*(1.0-factor*StringToDouble(token, &next_token)))); if (token == next_token) status=MagickFalse; break; } status=MagickFalse; break; } case 'p': case 'P': { if (LocaleCompare("path",keyword) == 0) { primitive_type=PathPrimitive; break; } if (LocaleCompare("point",keyword) == 0) { primitive_type=PointPrimitive; break; } if (LocaleCompare("polyline",keyword) == 0) { primitive_type=PolylinePrimitive; break; } if (LocaleCompare("polygon",keyword) == 0) { primitive_type=PolygonPrimitive; break; } if (LocaleCompare("pop",keyword) == 0) { GetNextToken(q,&q,extent,token); if (LocaleCompare("clip-path",token) == 0) break; if (LocaleCompare("defs",token) == 0) break; if (LocaleCompare("gradient",token) == 0) break; if (LocaleCompare("graphic-context",token) == 0) { if (n <= 0) { (void) ThrowMagickException(exception,GetMagickModule(), DrawError,"UnbalancedGraphicContextPushPop","`%s'",token); status=MagickFalse; n=0; break; } if (graphic_context[n]->clip_mask != (char *) NULL) if (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0) (void) SetImageMask(image,ReadPixelMask,(Image *) NULL, exception); graphic_context[n]=DestroyDrawInfo(graphic_context[n]); n--; break; } if (LocaleCompare("pattern",token) == 0) break; status=MagickFalse; break; } if (LocaleCompare("push",keyword) == 0) { GetNextToken(q,&q,extent,token); if (LocaleCompare("clip-path",token) == 0) { char name[MagickPathExtent]; GetNextToken(q,&q,extent,token); (void) FormatLocaleString(name,MagickPathExtent,"%s",token); for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"clip-path") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) SetImageArtifact(image,name,token); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gradient",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent], type[MagickPathExtent]; SegmentInfo segment; GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); GetNextToken(q,&q,extent,token); (void) CopyMagickString(type,token,MagickPathExtent); GetNextToken(q,&q,extent,token); segment.x1=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.y1=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.x2=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.y2=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; if (LocaleCompare(type,"radial") == 0) { GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); } for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"gradient") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); bounds.x1=graphic_context[n]->affine.sx*segment.x1+ graphic_context[n]->affine.ry*segment.y1+ graphic_context[n]->affine.tx; bounds.y1=graphic_context[n]->affine.rx*segment.x1+ graphic_context[n]->affine.sy*segment.y1+ graphic_context[n]->affine.ty; bounds.x2=graphic_context[n]->affine.sx*segment.x2+ graphic_context[n]->affine.ry*segment.y2+ graphic_context[n]->affine.tx; bounds.y2=graphic_context[n]->affine.rx*segment.x2+ graphic_context[n]->affine.sy*segment.y2+ graphic_context[n]->affine.ty; (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-type",name); (void) SetImageArtifact(image,key,type); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry", name); (void) FormatLocaleString(geometry,MagickPathExtent, "%gx%g%+.15g%+.15g", MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0), MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0), bounds.x1,bounds.y1); (void) SetImageArtifact(image,key,geometry); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("pattern",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent]; RectangleInfo pattern_bounds; GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); GetNextToken(q,&q,extent,token); pattern_bounds.x=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); pattern_bounds.y=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); pattern_bounds.width=(size_t) floor(StringToDouble(token, &next_token)+0.5); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); pattern_bounds.height=(size_t) floor(StringToDouble(token, &next_token)+0.5); if (token == next_token) status=MagickFalse; for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"pattern") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry", name); (void) FormatLocaleString(geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double)pattern_bounds.width, (double)pattern_bounds.height,(double)pattern_bounds.x, (double)pattern_bounds.y); (void) SetImageArtifact(image,key,geometry); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("graphic-context",token) == 0) { n++; graphic_context=(DrawInfo **) ResizeQuantumMemory( graphic_context,(size_t) (n+1),sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL, graphic_context[n-1]); break; } if (LocaleCompare("defs",token) == 0) break; status=MagickFalse; break; } status=MagickFalse; break; } case 'r': case 'R': { if (LocaleCompare("rectangle",keyword) == 0) { primitive_type=RectanglePrimitive; break; } if (LocaleCompare("rotate",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0))); affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0))); break; } if (LocaleCompare("roundRectangle",keyword) == 0) { primitive_type=RoundRectanglePrimitive; break; } status=MagickFalse; break; } case 's': case 'S': { if (LocaleCompare("scale",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("skewX",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; affine.ry=sin(DegreesToRadians(angle)); break; } if (LocaleCompare("skewY",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; affine.rx=(-tan(DegreesToRadians(angle)/2.0)); break; } if (LocaleCompare("stop-color",keyword) == 0) { PixelInfo stop_color; number_stops++; if (number_stops == 1) stops=(StopInfo *) AcquireQuantumMemory(2,sizeof(*stops)); else if (number_stops > 2) stops=(StopInfo *) ResizeQuantumMemory(stops,number_stops, sizeof(*stops)); if (stops == (StopInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } GetNextToken(q,&q,extent,token); (void) QueryColorCompliance(token,AllCompliance,&stop_color, exception); stops[number_stops-1].color=stop_color; GetNextToken(q,&q,extent,token); stops[number_stops-1].offset=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("stroke",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->stroke_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->stroke,exception); if (graphic_context[n]->stroke_alpha != OpaqueAlpha) graphic_context[n]->stroke.alpha= graphic_context[n]->stroke_alpha; if (status == MagickFalse) { ImageInfo *pattern_info; pattern_info=AcquireImageInfo(); (void) CopyMagickString(pattern_info->filename,token, MagickPathExtent); graphic_context[n]->stroke_pattern=ReadImage(pattern_info, exception); CatchException(exception); pattern_info=DestroyImageInfo(pattern_info); } } break; } if (LocaleCompare("stroke-antialias",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->stroke_antialias= StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("stroke-dasharray",keyword) == 0) { if (graphic_context[n]->dash_pattern != (double *) NULL) graphic_context[n]->dash_pattern=(double *) RelinquishMagickMemory(graphic_context[n]->dash_pattern); if (IsPoint(q) != MagickFalse) { const char *r; r=q; GetNextToken(r,&r,extent,token); if (*token == ',') GetNextToken(r,&r,extent,token); for (x=0; IsPoint(token) != MagickFalse; x++) { GetNextToken(r,&r,extent,token); if (*token == ',') GetNextToken(r,&r,extent,token); } graphic_context[n]->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2UL*x+1UL), sizeof(*graphic_context[n]->dash_pattern)); if (graphic_context[n]->dash_pattern == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); status=MagickFalse; break; } for (j=0; j < x; j++) { GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->dash_pattern[j]=StringToDouble(token, &next_token); if (token == next_token) status=MagickFalse; if (graphic_context[n]->dash_pattern[j] < 0.0) status=MagickFalse; } if ((x & 0x01) != 0) for ( ; j < (2*x); j++) graphic_context[n]->dash_pattern[j]= graphic_context[n]->dash_pattern[j-x]; graphic_context[n]->dash_pattern[j]=0.0; break; } GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("stroke-dashoffset",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->dash_offset=StringToDouble(token, &next_token); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("stroke-linecap",keyword) == 0) { ssize_t linecap; GetNextToken(q,&q,extent,token); linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token); if (linecap == -1) status=MagickFalse; else graphic_context[n]->linecap=(LineCap) linecap; break; } if (LocaleCompare("stroke-linejoin",keyword) == 0) { ssize_t linejoin; GetNextToken(q,&q,extent,token); linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse, token); if (linejoin == -1) status=MagickFalse; else graphic_context[n]->linejoin=(LineJoin) linejoin; break; } if (LocaleCompare("stroke-miterlimit",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->miterlimit=StringToUnsignedLong(token); break; } if (LocaleCompare("stroke-opacity",keyword) == 0) { GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->stroke.alpha=QuantumRange-ClampToQuantum( (MagickRealType) QuantumRange*(1.0-factor*StringToDouble(token, &next_token))); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("stroke-width",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->stroke_width=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } status=MagickFalse; break; } case 't': case 'T': { if (LocaleCompare("text",keyword) == 0) { primitive_type=TextPrimitive; break; } if (LocaleCompare("text-align",keyword) == 0) { ssize_t align; GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) status=MagickFalse; else graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-anchor",keyword) == 0) { ssize_t align; GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) status=MagickFalse; else graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-antialias",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->text_antialias=StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("text-undercolor",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) QueryColorCompliance(token,AllCompliance, &graphic_context[n]->undercolor,exception); break; } if (LocaleCompare("translate",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } status=MagickFalse; break; } case 'v': case 'V': { if (LocaleCompare("viewbox",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble( token,&next_token)+0.5); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble( token,&next_token)+0.5); if (token == next_token) status=MagickFalse; break; } status=MagickFalse; break; } default: { status=MagickFalse; break; } } if (status == MagickFalse) break; if ((fabs(affine.sx-1.0) >= DrawEpsilon) || (fabs(affine.rx) >= DrawEpsilon) || (fabs(affine.ry) >= DrawEpsilon) || (fabs(affine.sy-1.0) >= DrawEpsilon) || (fabs(affine.tx) >= DrawEpsilon) || (fabs(affine.ty) >= DrawEpsilon)) { graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx; graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx; graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy; graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy; graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+ current.tx; graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+ current.ty; } if (primitive_type == UndefinedPrimitive) { if (*q == '\0') { if (number_stops > 1) { GradientType type; type=LinearGradient; if (draw_info->gradient.type == RadialGradient) type=RadialGradient; (void) GradientImage(image,type,PadSpread,stops,number_stops, exception); } if (number_stops > 0) stops=(StopInfo *) RelinquishMagickMemory(stops); } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p); continue; } /* Parse the primitive attributes. */ i=0; j=0; primitive_info[0].point.x=0.0; primitive_info[0].point.y=0.0; for (x=0; *q != '\0'; x++) { /* Define points. */ if (IsPoint(q) == MagickFalse) break; GetNextToken(q,&q,extent,token); point.x=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); point.y=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,(const char **) NULL,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); primitive_info[i].primitive=primitive_type; primitive_info[i].point=point; primitive_info[i].coordinates=0; primitive_info[i].method=FloodfillMethod; i++; if (i < (ssize_t) number_points) continue; number_points<<=1; primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info, (size_t) number_points,sizeof(*primitive_info)); if ((primitive_info == (PrimitiveInfo *) NULL) || (number_points != (MagickSizeType) ((size_t) number_points))) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } primitive_info[j].primitive=primitive_type; primitive_info[j].coordinates=(size_t) x; primitive_info[j].method=FloodfillMethod; primitive_info[j].text=(char *) NULL; /* Circumscribe primitive within a circle. */ bounds.x1=primitive_info[j].point.x; bounds.y1=primitive_info[j].point.y; bounds.x2=primitive_info[j].point.x; bounds.y2=primitive_info[j].point.y; for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++) { point=primitive_info[j+k].point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.y < bounds.y1) bounds.y1=point.y; if (point.x > bounds.x2) bounds.x2=point.x; if (point.y > bounds.y2) bounds.y2=point.y; } /* Speculate how many points our primitive might consume. */ length=primitive_info[j].coordinates; switch (primitive_type) { case RectanglePrimitive: { length*=5; break; } case RoundRectanglePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot((double) alpha,(double) beta); length*=5; length+=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360; break; } case BezierPrimitive: { if (primitive_info[j].coordinates > 107) (void) ThrowMagickException(exception,GetMagickModule(),DrawError, "TooManyBezierCoordinates","`%s'",token); length=BezierQuantum*primitive_info[j].coordinates; break; } case PathPrimitive: { char *s, *t; GetNextToken(q,&q,extent,token); length=1; t=token; for (s=token; *s != '\0'; s=t) { double value; value=StringToDouble(s,&t); (void) value; if (s == t) { t++; continue; } length++; } length=length*BezierQuantum; break; } case CirclePrimitive: case ArcPrimitive: case EllipsePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot((double) alpha,(double) beta); length=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360; break; } default: break; } if ((i+length) >= number_points) { /* Resize based on speculative points required by primitive. */ number_points+=length+1; primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info, (size_t) number_points,sizeof(*primitive_info)); if ((primitive_info == (PrimitiveInfo *) NULL) || (number_points != (MagickSizeType) ((size_t) number_points))) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } } switch (primitive_type) { case PointPrimitive: default: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } TracePoint(primitive_info+j,primitive_info[j].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case LinePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceLine(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RectanglePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceRectangle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RoundRectanglePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } TraceRoundRectangle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case ArcPrimitive: { if (primitive_info[j].coordinates != 3) { primitive_type=UndefinedPrimitive; break; } TraceArc(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case EllipsePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } TraceEllipse(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case CirclePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceCircle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PolylinePrimitive: break; case PolygonPrimitive: { primitive_info[i]=primitive_info[j]; primitive_info[i].coordinates=0; primitive_info[j].coordinates++; i++; break; } case BezierPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } TraceBezier(primitive_info+j,primitive_info[j].coordinates); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PathPrimitive: { i=(ssize_t) (j+TracePath(primitive_info+j,token)); break; } case AlphaPrimitive: case ColorPrimitive: { ssize_t method; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } GetNextToken(q,&q,extent,token); method=ParseCommandOption(MagickMethodOptions,MagickFalse,token); if (method == -1) status=MagickFalse; else primitive_info[j].method=(PaintMethod) method; break; } case TextPrimitive: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } if (*token != ',') GetNextToken(q,&q,extent,token); primitive_info[j].text=AcquireString(token); break; } case ImagePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } GetNextToken(q,&q,extent,token); primitive_info[j].text=AcquireString(token); break; } } if (primitive_info == (PrimitiveInfo *) NULL) break; if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p); if (status == MagickFalse) break; primitive_info[i].primitive=UndefinedPrimitive; if (i == 0) continue; /* Transform points. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+ graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx; primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+ graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty; point=primitive_info[i].point; if (point.x < graphic_context[n]->bounds.x1) graphic_context[n]->bounds.x1=point.x; if (point.y < graphic_context[n]->bounds.y1) graphic_context[n]->bounds.y1=point.y; if (point.x > graphic_context[n]->bounds.x2) graphic_context[n]->bounds.x2=point.x; if (point.y > graphic_context[n]->bounds.y2) graphic_context[n]->bounds.y2=point.y; if (primitive_info[i].primitive == ImagePrimitive) break; if (i >= (ssize_t) number_points) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); } if (graphic_context[n]->render != MagickFalse) { if ((n != 0) && (graphic_context[n]->clip_mask != (char *) NULL) && (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0)) status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); status&=DrawPrimitive(image,graphic_context[n],primitive_info, exception); } if (primitive_info->text != (char *) NULL) primitive_info->text=(char *) RelinquishMagickMemory( primitive_info->text); proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType) primitive_extent); if (proceed == MagickFalse) break; if (status == 0) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image"); /* Relinquish resources. */ token=DestroyString(token); if (primitive_info != (PrimitiveInfo *) NULL) primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info); primitive=DestroyString(primitive); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); if (status == MagickFalse) ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition", keyword); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w G r a d i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawGradientImage() draws a linear gradient on the image. % % The format of the DrawGradientImage method is: % % MagickBooleanType DrawGradientImage(Image *image, % const DrawInfo *draw_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o exception: return any errors or warnings in this structure. % */ static inline double GetStopColorOffset(const GradientInfo *gradient, const ssize_t x,const ssize_t y) { switch (gradient->type) { case UndefinedGradient: case LinearGradient: { double gamma, length, offset, scale; PointInfo p, q; const SegmentInfo *gradient_vector; gradient_vector=(&gradient->gradient_vector); p.x=gradient_vector->x2-gradient_vector->x1; p.y=gradient_vector->y2-gradient_vector->y1; q.x=(double) x-gradient_vector->x1; q.y=(double) y-gradient_vector->y1; length=sqrt(q.x*q.x+q.y*q.y); gamma=sqrt(p.x*p.x+p.y*p.y)*length; gamma=PerceptibleReciprocal(gamma); scale=p.x*q.x+p.y*q.y; offset=gamma*scale*length; return(offset); } case RadialGradient: { PointInfo v; if (gradient->spread == RepeatSpread) { v.x=(double) x-gradient->center.x; v.y=(double) y-gradient->center.y; return(sqrt(v.x*v.x+v.y*v.y)); } v.x=(double) (((x-gradient->center.x)*cos(DegreesToRadians( gradient->angle)))+((y-gradient->center.y)*sin(DegreesToRadians( gradient->angle))))/gradient->radii.x; v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians( gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians( gradient->angle))))/gradient->radii.y; return(sqrt(v.x*v.x+v.y*v.y)); } } return(0.0); } static int StopInfoCompare(const void *x,const void *y) { StopInfo *stop_1, *stop_2; stop_1=(StopInfo *) x; stop_2=(StopInfo *) y; if (stop_1->offset > stop_2->offset) return(1); if (fabs(stop_1->offset-stop_2->offset) <= DrawEpsilon) return(0); return(-1); } MagickExport MagickBooleanType DrawGradientImage(Image *image, const DrawInfo *draw_info,ExceptionInfo *exception) { CacheView *image_view; const GradientInfo *gradient; const SegmentInfo *gradient_vector; double length; MagickBooleanType status; PixelInfo zero; PointInfo point; RectangleInfo bounding_box; ssize_t y; /* Draw linear or radial gradient on image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); gradient=(&draw_info->gradient); qsort(gradient->stops,gradient->number_stops,sizeof(StopInfo), StopInfoCompare); gradient_vector=(&gradient->gradient_vector); point.x=gradient_vector->x2-gradient_vector->x1; point.y=gradient_vector->y2-gradient_vector->y1; length=sqrt(point.x*point.x+point.y*point.y); bounding_box=gradient->bounding_box; status=MagickTrue; GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++) { PixelInfo composite, pixel; double alpha, offset; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t j; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; composite=zero; offset=GetStopColorOffset(gradient,0,y); if (gradient->type != RadialGradient) offset/=length; for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++) { GetPixelInfoPixel(image,q,&pixel); switch (gradient->spread) { case UndefinedSpread: case PadSpread: { if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) ceil(gradient_vector->y1-0.5))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset/=length; } for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if ((offset < 0.0) || (i == 0)) composite=gradient->stops[0].color; else if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops)) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } case ReflectSpread: { if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) ceil(gradient_vector->y1-0.5))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset/=length; } if (offset < 0.0) offset=(-offset); if ((ssize_t) fmod(offset,2.0) == 0) offset=fmod(offset,1.0); else offset=1.0-fmod(offset,1.0); for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if (i == 0) composite=gradient->stops[0].color; else if (i == (ssize_t) gradient->number_stops) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } case RepeatSpread: { MagickBooleanType antialias; double repeat; antialias=MagickFalse; repeat=0.0; if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) ceil(gradient_vector->y1-0.5))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type == LinearGradient) { repeat=fmod(offset,length); if (repeat < 0.0) repeat=length-fmod(-repeat,length); else repeat=fmod(offset,length); antialias=(repeat < length) && ((repeat+1.0) > length) ? MagickTrue : MagickFalse; offset=repeat/length; } else { repeat=fmod(offset,gradient->radius); if (repeat < 0.0) repeat=gradient->radius-fmod(-repeat,gradient->radius); else repeat=fmod(offset,gradient->radius); antialias=repeat+1.0 > gradient->radius ? MagickTrue : MagickFalse; offset=repeat/gradient->radius; } } for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if (i == 0) composite=gradient->stops[0].color; else if (i == (ssize_t) gradient->number_stops) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); if (antialias != MagickFalse) { if (gradient->type == LinearGradient) alpha=length-repeat; else alpha=gradient->radius-repeat; i=0; j=(ssize_t) gradient->number_stops-1L; } CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } } CompositePixelInfoOver(&composite,composite.alpha,&pixel,pixel.alpha, &pixel); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P a t t e r n P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPatternPath() draws a pattern. % % The format of the DrawPatternPath method is: % % MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info, % const char *name,Image **pattern,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o name: the pattern name. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DrawPatternPath(Image *image, const DrawInfo *draw_info,const char *name,Image **pattern, ExceptionInfo *exception) { char property[MagickPathExtent]; const char *geometry, *path, *type; DrawInfo *clone_info; ImageInfo *image_info; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); assert(name != (const char *) NULL); (void) FormatLocaleString(property,MagickPathExtent,"%s",name); path=GetImageArtifact(image,property); if (path == (const char *) NULL) return(MagickFalse); (void) FormatLocaleString(property,MagickPathExtent,"%s-geometry",name); geometry=GetImageArtifact(image,property); if (geometry == (const char *) NULL) return(MagickFalse); if ((*pattern) != (Image *) NULL) *pattern=DestroyImage(*pattern); image_info=AcquireImageInfo(); image_info->size=AcquireString(geometry); *pattern=AcquireImage(image_info,exception); image_info=DestroyImageInfo(image_info); (void) QueryColorCompliance("#000000ff",AllCompliance, &(*pattern)->background_color,exception); (void) SetImageBackgroundColor(*pattern,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), "begin pattern-path %s %s",name,geometry); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->fill_pattern=NewImageList(); clone_info->stroke_pattern=NewImageList(); (void) FormatLocaleString(property,MagickPathExtent,"%s-type",name); type=GetImageArtifact(image,property); if (type != (const char *) NULL) clone_info->gradient.type=(GradientType) ParseCommandOption( MagickGradientOptions,MagickFalse,type); (void) CloneString(&clone_info->primitive,path); status=DrawImage(*pattern,clone_info,exception); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end pattern-path"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w P o l y g o n P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPolygonPrimitive() draws a polygon on the image. % % The format of the DrawPolygonPrimitive method is: % % MagickBooleanType DrawPolygonPrimitive(Image *image, % const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o exception: return any errors or warnings in this structure. % */ static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info) { register ssize_t i; assert(polygon_info != (PolygonInfo **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (polygon_info[i] != (PolygonInfo *) NULL) polygon_info[i]=DestroyPolygonInfo(polygon_info[i]); polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info); return(polygon_info); } static PolygonInfo **AcquirePolygonThreadSet( const PrimitiveInfo *primitive_info) { PathInfo *magick_restrict path_info; PolygonInfo **polygon_info; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads, sizeof(*polygon_info)); if (polygon_info == (PolygonInfo **) NULL) return((PolygonInfo **) NULL); (void) ResetMagickMemory(polygon_info,0,number_threads*sizeof(*polygon_info)); path_info=ConvertPrimitiveToPath(primitive_info); if (path_info == (PathInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); for (i=0; i < (ssize_t) number_threads; i++) { polygon_info[i]=ConvertPathToPolygon(path_info); if (polygon_info[i] == (PolygonInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); } path_info=(PathInfo *) RelinquishMagickMemory(path_info); return(polygon_info); } static double GetFillAlpha(PolygonInfo *polygon_info,const double mid, const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x, const ssize_t y,double *stroke_alpha) { double alpha, beta, distance, subpath_alpha; PointInfo delta; register const PointInfo *q; register EdgeInfo *p; register ssize_t i; ssize_t j, winding_number; /* Compute fill & stroke opacity for this (x,y) point. */ *stroke_alpha=0.0; subpath_alpha=0.0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= (p->bounds.y1-mid-0.5)) break; if ((double) y > (p->bounds.y2+mid+0.5)) { (void) DestroyEdge(polygon_info,(size_t) j); continue; } if (((double) x <= (p->bounds.x1-mid-0.5)) || ((double) x > (p->bounds.x2+mid+0.5))) continue; i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) p->number_points; i++) { if ((double) y <= (p->points[i-1].y-mid-0.5)) break; if ((double) y > (p->points[i].y+mid+0.5)) continue; if (p->scanline != (double) y) { p->scanline=(double) y; p->highwater=(size_t) i; } /* Compute distance between a point and an edge. */ q=p->points+i-1; delta.x=(q+1)->x-q->x; delta.y=(q+1)->y-q->y; beta=delta.x*(x-q->x)+delta.y*(y-q->y); if (beta < 0.0) { delta.x=(double) x-q->x; delta.y=(double) y-q->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=delta.x*delta.x+delta.y*delta.y; if (beta > alpha) { delta.x=(double) x-(q+1)->x; delta.y=(double) y-(q+1)->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=1.0/alpha; beta=delta.x*(y-q->y)-delta.y*(x-q->x); distance=alpha*beta*beta; } } /* Compute stroke & subpath opacity. */ beta=0.0; if (p->ghostline == MagickFalse) { alpha=mid+0.5; if ((*stroke_alpha < 1.0) && (distance <= ((alpha+0.25)*(alpha+0.25)))) { alpha=mid-0.5; if (distance <= ((alpha+0.25)*(alpha+0.25))) *stroke_alpha=1.0; else { beta=1.0; if (fabs(distance-1.0) >= DrawEpsilon) beta=sqrt((double) distance); alpha=beta-mid-0.5; if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25))) *stroke_alpha=(alpha-0.25)*(alpha-0.25); } } } if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0)) continue; if (distance <= 0.0) { subpath_alpha=1.0; continue; } if (distance > 1.0) continue; if (fabs(beta) < DrawEpsilon) { beta=1.0; if (fabs(distance-1.0) >= DrawEpsilon) beta=sqrt(distance); } alpha=beta-1.0; if (subpath_alpha < (alpha*alpha)) subpath_alpha=alpha*alpha; } } /* Compute fill opacity. */ if (fill == MagickFalse) return(0.0); if (subpath_alpha >= 1.0) return(1.0); /* Determine winding number. */ winding_number=0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= p->bounds.y1) break; if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1)) continue; if ((double) x > p->bounds.x2) { winding_number+=p->direction ? 1 : -1; continue; } i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) p->number_points; i++) if ((double) y <= p->points[i].y) break; q=p->points+i-1; if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x))) winding_number+=p->direction ? 1 : -1; } if (fill_rule != NonZeroRule) { if ((MagickAbsoluteValue(winding_number) & 0x01) != 0) return(1.0); } else if (MagickAbsoluteValue(winding_number) != 0) return(1.0); return(subpath_alpha); } static MagickBooleanType DrawPolygonPrimitive(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType fill, status; double mid; PolygonInfo **magick_restrict polygon_info; register EdgeInfo *p; register ssize_t i; SegmentInfo bounds; ssize_t start_y, stop_y, y; /* Compute bounding box. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); assert(primitive_info != (PrimitiveInfo *) NULL); if (primitive_info->coordinates == 0) return(MagickTrue); polygon_info=AcquirePolygonThreadSet(primitive_info); if (polygon_info == (PolygonInfo **) NULL) return(MagickFalse); DisableMSCWarning(4127) if (0) DrawBoundingRectangles(image,draw_info,polygon_info[0],exception); RestoreMSCWarning if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-polygon"); fill=(primitive_info->method == FillToBorderMethod) || (primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse; mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; bounds=polygon_info[0]->edges[0].bounds; for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++) { p=polygon_info[0]->edges+i; if (p->bounds.x1 < bounds.x1) bounds.x1=p->bounds.x1; if (p->bounds.y1 < bounds.y1) bounds.y1=p->bounds.y1; if (p->bounds.x2 > bounds.x2) bounds.x2=p->bounds.x2; if (p->bounds.y2 > bounds.y2) bounds.y2=p->bounds.y2; } bounds.x1-=(mid+1.0); bounds.x1=bounds.x1 < 0.0 ? 0.0 : (size_t) ceil(bounds.x1-0.5) >= image->columns ? (double) image->columns-1 : bounds.x1; bounds.y1-=(mid+1.0); bounds.y1=bounds.y1 < 0.0 ? 0.0 : (size_t) ceil(bounds.y1-0.5) >= image->rows ? (double) image->rows-1 : bounds.y1; bounds.x2+=(mid+1.0); bounds.x2=bounds.x2 < 0.0 ? 0.0 : (size_t) floor(bounds.x2+0.5) >= image->columns ? (double) image->columns-1 : bounds.x2; bounds.y2+=(mid+1.0); bounds.y2=bounds.y2 < 0.0 ? 0.0 : (size_t) floor(bounds.y2+0.5) >= image->rows ? (double) image->rows-1 : bounds.y2; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); if ((primitive_info->coordinates == 1) || (polygon_info[0]->number_edges == 0)) { /* Draw point. */ start_y=(ssize_t) ceil(bounds.y1-0.5); stop_y=(ssize_t) floor(bounds.y2+0.5); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=start_y; y <= stop_y; y++) { MagickBooleanType sync; PixelInfo pixel; register ssize_t x; register Quantum *magick_restrict q; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=(ssize_t) ceil(bounds.x1-0.5); stop_x=(ssize_t) floor(bounds.x2+0.5); x=start_x; q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop_x-x+1),1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for ( ; x <= stop_x; x++) { if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) && (y == (ssize_t) ceil(primitive_info->point.y-0.5))) { GetFillColor(draw_info,x-start_x,y-start_y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); } q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); polygon_info=DestroyPolygonThreadSet(polygon_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-polygon"); return(status); } /* Draw polygon or line. */ if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); start_y=(ssize_t) ceil(bounds.y1-0.5); stop_y=(ssize_t) floor(bounds.y2+0.5); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=start_y; y <= stop_y; y++) { const int id = GetOpenMPThreadId(); double fill_alpha, stroke_alpha; PixelInfo fill_color, stroke_color; register Quantum *magick_restrict q; register ssize_t x; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=(ssize_t) ceil(bounds.x1-0.5); stop_x=(ssize_t) floor(bounds.x2+0.5); q=GetCacheViewAuthenticPixels(image_view,start_x,y,(size_t) (stop_x-start_x+ 1),1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=start_x; x <= stop_x; x++) { /* Fill and/or stroke. */ fill_alpha=GetFillAlpha(polygon_info[id],mid,fill,draw_info->fill_rule, x,y,&stroke_alpha); if (draw_info->stroke_antialias == MagickFalse) { fill_alpha=fill_alpha > 0.25 ? 1.0 : 0.0; stroke_alpha=stroke_alpha > 0.25 ? 1.0 : 0.0; } GetFillColor(draw_info,x-start_x,y-start_y,&fill_color,exception); fill_alpha=fill_alpha*fill_color.alpha; CompositePixelOver(image,&fill_color,fill_alpha,q,(double) GetPixelAlpha(image,q),q); GetStrokeColor(draw_info,x-start_x,y-start_y,&stroke_color,exception); stroke_alpha=stroke_alpha*stroke_color.alpha; CompositePixelOver(image,&stroke_color,stroke_alpha,q,(double) GetPixelAlpha(image,q),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); polygon_info=DestroyPolygonThreadSet(polygon_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-polygon"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image. % % The format of the DrawPrimitive method is: % % MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info, % PrimitiveInfo *primitive_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o exception: return any errors or warnings in this structure. % */ static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info) { const char *methods[] = { "point", "replace", "floodfill", "filltoborder", "reset", "?" }; PointInfo p, q, point; register ssize_t i, x; ssize_t coordinates, y; x=(ssize_t) ceil(primitive_info->point.x-0.5); y=(ssize_t) ceil(primitive_info->point.y-0.5); switch (primitive_info->primitive) { case AlphaPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "AlphaPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case ColorPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ColorPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case ImagePrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ImagePrimitive %.20g,%.20g",(double) x,(double) y); return; } case PointPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "PointPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case TextPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "TextPrimitive %.20g,%.20g",(double) x,(double) y); return; } default: break; } coordinates=0; p=primitive_info[0].point; q.x=(-1.0); q.y=(-1.0); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; if (coordinates <= 0) { coordinates=(ssize_t) primitive_info[i].coordinates; (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin open (%.20g)",(double) coordinates); p=point; } point=primitive_info[i].point; if ((fabs(q.x-point.x) >= DrawEpsilon) || (fabs(q.y-point.y) >= DrawEpsilon)) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %.20g: %.18g,%.18g",(double) coordinates,point.x,point.y); else (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %.20g: %g %g (duplicate)",(double) coordinates,point.x,point.y); q=point; coordinates--; if (coordinates > 0) continue; if ((fabs(p.x-point.x) >= DrawEpsilon) || (fabs(p.y-point.y) >= DrawEpsilon)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end last (%.20g)", (double) coordinates); else (void) LogMagickEvent(DrawEvent,GetMagickModule()," end open (%.20g)", (double) coordinates); } } MagickExport MagickBooleanType DrawPrimitive(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { CacheView *image_view; MagickStatusType status; register ssize_t i, x; ssize_t y; if (image->debug != MagickFalse) { (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin draw-primitive"); (void) LogMagickEvent(DrawEvent,GetMagickModule(), " affine: %g,%g,%g,%g,%g,%g",draw_info->affine.sx, draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy, draw_info->affine.tx,draw_info->affine.ty); } if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsPixelInfoGray(&draw_info->fill) == MagickFalse) || (IsPixelInfoGray(&draw_info->stroke) == MagickFalse))) (void) SetImageColorspace(image,sRGBColorspace,exception); status=MagickTrue; x=(ssize_t) ceil(primitive_info->point.x-0.5); y=(ssize_t) ceil(primitive_info->point.y-0.5); image_view=AcquireAuthenticCacheView(image,exception); switch (primitive_info->primitive) { case AlphaPrimitive: { if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; register Quantum *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { MagickBooleanType sync; PixelInfo pixel, target; (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) { q+=GetPixelChannels(image); continue; } GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { ChannelType channel_mask; PixelInfo target; (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, &target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(double) draw_info->border_color.red; target.green=(double) draw_info->border_color.green; target.blue=(double) draw_info->border_color.blue; } channel_mask=SetImageChannelMask(image,AlphaChannel); status&=FloodfillPaintImage(image,draw_info,&target,x,y, primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue,exception); (void) SetImageChannelMask(image,channel_mask); break; } case ResetMethod: { MagickBooleanType sync; PixelInfo pixel; for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } } break; } case ColorPrimitive: { switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; register Quantum *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetPixelInfo(image,&pixel); GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { MagickBooleanType sync; PixelInfo pixel, target; (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) { q+=GetPixelChannels(image); continue; } GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { PixelInfo target; (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, &target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(double) draw_info->border_color.red; target.green=(double) draw_info->border_color.green; target.blue=(double) draw_info->border_color.blue; } status&=FloodfillPaintImage(image,draw_info,&target,x,y, primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue,exception); break; } case ResetMethod: { MagickBooleanType sync; PixelInfo pixel; GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } } break; } case ImagePrimitive: { AffineMatrix affine; char composite_geometry[MagickPathExtent]; Image *composite_image; ImageInfo *clone_info; RectangleInfo geometry; ssize_t x1, y1; if (primitive_info->text == (char *) NULL) break; clone_info=AcquireImageInfo(); if (LocaleNCompare(primitive_info->text,"data:",5) == 0) composite_image=ReadInlineImage(clone_info,primitive_info->text, exception); else { (void) CopyMagickString(clone_info->filename,primitive_info->text, MagickPathExtent); composite_image=ReadImage(clone_info,exception); } clone_info=DestroyImageInfo(clone_info); if (composite_image == (Image *) NULL) break; (void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor) NULL,(void *) NULL); x1=(ssize_t) ceil(primitive_info[1].point.x-0.5); y1=(ssize_t) ceil(primitive_info[1].point.y-0.5); if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) || ((y1 != 0L) && (y1 != (ssize_t) composite_image->rows))) { /* Resize image. */ (void) FormatLocaleString(composite_geometry,MagickPathExtent, "%gx%g!",primitive_info[1].point.x,primitive_info[1].point.y); composite_image->filter=image->filter; (void) TransformImage(&composite_image,(char *) NULL, composite_geometry,exception); } if (composite_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel, exception); if (draw_info->alpha != OpaqueAlpha) (void) SetImageAlpha(composite_image,draw_info->alpha,exception); SetGeometry(image,&geometry); image->gravity=draw_info->gravity; geometry.x=x; geometry.y=y; (void) FormatLocaleString(composite_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double) composite_image->rows,(double) geometry.x,(double) geometry.y); (void) ParseGravityGeometry(image,composite_geometry,&geometry,exception); affine=draw_info->affine; affine.tx=(double) geometry.x; affine.ty=(double) geometry.y; composite_image->interpolate=image->interpolate; if (draw_info->compose == OverCompositeOp) (void) DrawAffineImage(image,composite_image,&affine,exception); else (void) CompositeImage(image,composite_image,draw_info->compose, MagickTrue,geometry.x,geometry.y,exception); composite_image=DestroyImage(composite_image); break; } case PointPrimitive: { PixelInfo fill_color; register Quantum *q; if ((y < 0) || (y >= (ssize_t) image->rows)) break; if ((x < 0) || (x >= (ssize_t) image->columns)) break; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetFillColor(draw_info,x,y,&fill_color,exception); CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q, (double) GetPixelAlpha(image,q),q); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case TextPrimitive: { char geometry[MagickPathExtent]; DrawInfo *clone_info; if (primitive_info->text == (char *) NULL) break; clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->text,primitive_info->text); (void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f", primitive_info->point.x,primitive_info->point.y); (void) CloneString(&clone_info->geometry,geometry); status&=AnnotateImage(image,clone_info,exception); clone_info=DestroyDrawInfo(clone_info); break; } default: { double mid, scale; DrawInfo *clone_info; if (IsEventLogging() != MagickFalse) LogPrimitiveInfo(primitive_info); scale=ExpandAffine(&draw_info->affine); if ((draw_info->dash_pattern != (double *) NULL) && (fabs(draw_info->dash_pattern[0]) >= DrawEpsilon) && (fabs(scale*draw_info->stroke_width) >= DrawEpsilon) && (draw_info->stroke.alpha != (Quantum) TransparentAlpha)) { /* Draw dash polygon. */ clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; status&=DrawPolygonPrimitive(image,clone_info,primitive_info, exception); clone_info=DestroyDrawInfo(clone_info); (void) DrawDashPolygon(draw_info,primitive_info,image,exception); break; } mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; if ((mid > 1.0) && ((draw_info->stroke.alpha != (Quantum) TransparentAlpha) || (draw_info->stroke_pattern != (Image *) NULL))) { MagickBooleanType closed_path; /* Draw strokes while respecting line cap/join attributes. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; closed_path= (fabs(primitive_info[i-1].point.x-primitive_info[0].point.x) < DrawEpsilon) && (fabs(primitive_info[i-1].point.y-primitive_info[0].point.y) < DrawEpsilon) ? MagickTrue : MagickFalse; i=(ssize_t) primitive_info[0].coordinates; if (((closed_path != MagickFalse) && (draw_info->linejoin == RoundJoin)) || (primitive_info[i].primitive != UndefinedPrimitive)) { (void) DrawPolygonPrimitive(image,draw_info,primitive_info, exception); break; } if (draw_info->linecap == RoundCap) { (void) DrawPolygonPrimitive(image,draw_info,primitive_info, exception); break; } clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; status&=DrawPolygonPrimitive(image,clone_info,primitive_info, exception); clone_info=DestroyDrawInfo(clone_info); status&=DrawStrokePolygon(image,draw_info,primitive_info,exception); break; } status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception); break; } } image_view=DestroyCacheView(image_view); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w S t r o k e P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on % the image while respecting the line cap and join attributes. % % The format of the DrawStrokePolygon method is: % % MagickBooleanType DrawStrokePolygon(Image *image, % const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % */ static void DrawRoundLinecap(Image *image,const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,ExceptionInfo *exception) { PrimitiveInfo linecap[5]; register ssize_t i; for (i=0; i < 4; i++) linecap[i]=(*primitive_info); linecap[0].coordinates=4; linecap[1].point.x+=2.0*DrawEpsilon; linecap[2].point.x+=2.0*DrawEpsilon; linecap[2].point.y+=2.0*DrawEpsilon; linecap[3].point.y+=2.0*DrawEpsilon; linecap[4].primitive=UndefinedPrimitive; (void) DrawPolygonPrimitive(image,draw_info,linecap,exception); } static MagickBooleanType DrawStrokePolygon(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { DrawInfo *clone_info; MagickBooleanType closed_path; MagickStatusType status; PrimitiveInfo *stroke_polygon; register const PrimitiveInfo *p, *q; /* Draw stroked polygon. */ if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin draw-stroke-polygon"); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->fill=draw_info->stroke; if (clone_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern); if (clone_info->stroke_pattern != (Image *) NULL) clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0, MagickTrue,exception); clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; clone_info->stroke_width=0.0; clone_info->fill_rule=NonZeroRule; status=MagickTrue; for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates) { stroke_polygon=TraceStrokePolygon(draw_info,p); status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception); if (status == 0) break; stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon); q=p+p->coordinates-1; closed_path=(fabs(q->point.x-p->point.x) < DrawEpsilon) && (fabs(q->point.y-p->point.y) < DrawEpsilon) ? MagickTrue : MagickFalse; if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse)) { DrawRoundLinecap(image,draw_info,p,exception); DrawRoundLinecap(image,draw_info,q,exception); } } clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-stroke-polygon"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A f f i n e M a t r i x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAffineMatrix() returns an AffineMatrix initialized to the identity % matrix. % % The format of the GetAffineMatrix method is: % % void GetAffineMatrix(AffineMatrix *affine_matrix) % % A description of each parameter follows: % % o affine_matrix: the affine matrix. % */ MagickExport void GetAffineMatrix(AffineMatrix *affine_matrix) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(affine_matrix != (AffineMatrix *) NULL); (void) ResetMagickMemory(affine_matrix,0,sizeof(*affine_matrix)); affine_matrix->sx=1.0; affine_matrix->sy=1.0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetDrawInfo() initializes draw_info to default values from image_info. % % The format of the GetDrawInfo method is: % % void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) % % A description of each parameter follows: % % o image_info: the image info.. % % o draw_info: the draw info. % */ MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) { char *next_token; const char *option; ExceptionInfo *exception; ImageInfo *clone_info; /* Initialize draw attributes. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); (void) ResetMagickMemory(draw_info,0,sizeof(*draw_info)); clone_info=CloneImageInfo(image_info); GetAffineMatrix(&draw_info->affine); exception=AcquireExceptionInfo(); (void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill, exception); (void) QueryColorCompliance("#0000",AllCompliance,&draw_info->stroke, exception); draw_info->stroke_width=1.0; draw_info->fill_rule=EvenOddRule; draw_info->alpha=OpaqueAlpha; draw_info->fill_alpha=OpaqueAlpha; draw_info->stroke_alpha=OpaqueAlpha; draw_info->linecap=ButtCap; draw_info->linejoin=MiterJoin; draw_info->miterlimit=10; draw_info->decorate=NoDecoration; draw_info->pointsize=12.0; draw_info->undercolor.alpha=(MagickRealType) TransparentAlpha; draw_info->compose=OverCompositeOp; draw_info->render=MagickTrue; draw_info->debug=IsEventLogging(); draw_info->stroke_antialias=clone_info->antialias; if (clone_info->font != (char *) NULL) draw_info->font=AcquireString(clone_info->font); if (clone_info->density != (char *) NULL) draw_info->density=AcquireString(clone_info->density); draw_info->text_antialias=clone_info->antialias; if (fabs(clone_info->pointsize) >= DrawEpsilon) draw_info->pointsize=clone_info->pointsize; draw_info->border_color=clone_info->border_color; if (clone_info->server_name != (char *) NULL) draw_info->server_name=AcquireString(clone_info->server_name); option=GetImageOption(clone_info,"direction"); if (option != (const char *) NULL) draw_info->direction=(DirectionType) ParseCommandOption( MagickDirectionOptions,MagickFalse,option); else draw_info->direction=UndefinedDirection; option=GetImageOption(clone_info,"encoding"); if (option != (const char *) NULL) (void) CloneString(&draw_info->encoding,option); option=GetImageOption(clone_info,"family"); if (option != (const char *) NULL) (void) CloneString(&draw_info->family,option); option=GetImageOption(clone_info,"fill"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->fill, exception); option=GetImageOption(clone_info,"gravity"); if (option != (const char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(clone_info,"interline-spacing"); if (option != (const char *) NULL) draw_info->interline_spacing=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"interword-spacing"); if (option != (const char *) NULL) draw_info->interword_spacing=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"kerning"); if (option != (const char *) NULL) draw_info->kerning=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"stroke"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke, exception); option=GetImageOption(clone_info,"strokewidth"); if (option != (const char *) NULL) draw_info->stroke_width=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"style"); if (option != (const char *) NULL) draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions, MagickFalse,option); option=GetImageOption(clone_info,"undercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor, exception); option=GetImageOption(clone_info,"weight"); if (option != (const char *) NULL) { ssize_t weight; weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(option); draw_info->weight=(size_t) weight; } exception=DestroyExceptionInfo(exception); draw_info->signature=MagickCoreSignature; clone_info=DestroyImageInfo(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r m u t a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Permutate() returns the permuation of the (n,k). % % The format of the Permutate method is: % % void Permutate(ssize_t n,ssize_t k) % % A description of each parameter follows: % % o n: % % o k: % % */ static inline double Permutate(const ssize_t n,const ssize_t k) { double r; register ssize_t i; r=1.0; for (i=k+1; i <= n; i++) r*=i; for (i=1; i <= (n-k); i++) r/=i; return(r); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + T r a c e P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TracePrimitive is a collection of methods for generating graphic % primitives such as arcs, ellipses, paths, etc. % */ static void TraceArc(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end,const PointInfo degrees) { PointInfo center, radii; center.x=0.5*(end.x+start.x); center.y=0.5*(end.y+start.y); radii.x=fabs(center.x-start.x); radii.y=fabs(center.y-start.y); TraceEllipse(primitive_info,center,radii,degrees); } static void TraceArcPath(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end,const PointInfo arc,const double angle, const MagickBooleanType large_arc,const MagickBooleanType sweep) { double alpha, beta, delta, factor, gamma, theta; PointInfo center, points[3], radii; register double cosine, sine; register PrimitiveInfo *p; register ssize_t i; size_t arc_segments; if ((fabs(start.x-end.x) < DrawEpsilon) && (fabs(start.y-end.y) < DrawEpsilon)) { TracePoint(primitive_info,end); return; } radii.x=fabs(arc.x); radii.y=fabs(arc.y); if ((fabs(radii.x) < DrawEpsilon) || (fabs(radii.y) < DrawEpsilon)) { TraceLine(primitive_info,start,end); return; } cosine=cos(DegreesToRadians(fmod((double) angle,360.0))); sine=sin(DegreesToRadians(fmod((double) angle,360.0))); center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2); center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2); delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/ (radii.y*radii.y); if (delta < DrawEpsilon) { TraceLine(primitive_info,start,end); return; } if (delta > 1.0) { radii.x*=sqrt((double) delta); radii.y*=sqrt((double) delta); } points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x); points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y); points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x); points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y); alpha=points[1].x-points[0].x; beta=points[1].y-points[0].y; factor=PerceptibleReciprocal(alpha*alpha+beta*beta)-0.25; if (factor <= 0.0) factor=0.0; else { factor=sqrt((double) factor); if (sweep == large_arc) factor=(-factor); } center.x=(double) ((points[0].x+points[1].x)/2-factor*beta); center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha); alpha=atan2(points[0].y-center.y,points[0].x-center.x); theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha; if ((theta < 0.0) && (sweep != MagickFalse)) theta+=2.0*MagickPI; else if ((theta > 0.0) && (sweep == MagickFalse)) theta-=2.0*MagickPI; arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+DrawEpsilon)))); p=primitive_info; for (i=0; i < (ssize_t) arc_segments; i++) { beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments)); gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))* sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/ sin(fmod((double) beta,DegreesToRadians(360.0))); points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/ arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+ (double) i*theta/arc_segments),DegreesToRadians(360.0)))); points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/ arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+ (double) i*theta/arc_segments),DegreesToRadians(360.0)))); points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)* theta/arc_segments),DegreesToRadians(360.0)))); points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)* theta/arc_segments),DegreesToRadians(360.0)))); points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double) (i+1)*theta/arc_segments),DegreesToRadians(360.0)))); points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double) (i+1)*theta/arc_segments),DegreesToRadians(360.0)))); p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x; p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y; (p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y* points[0].y); (p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y* points[0].y); (p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y* points[1].y); (p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y* points[1].y); (p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y* points[2].y); (p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y* points[2].y); if (i == (ssize_t) (arc_segments-1)) (p+3)->point=end; TraceBezier(p,4); p+=p->coordinates; } primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceBezier(PrimitiveInfo *primitive_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coeficients. */ quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) quantum) quantum=(size_t) alpha; } } quantum=(size_t) MagickMin((double) quantum/number_coordinates, (double) BezierQuantum); control_points=quantum*number_coordinates; coefficients=(double *) AcquireQuantumMemory((size_t) number_coordinates,sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory((size_t) control_points, sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { TracePoint(p,points[i]); p+=p->coordinates; } TracePoint(p,end); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); } static void TraceCircle(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end) { double alpha, beta, radius; PointInfo offset, degrees; alpha=end.x-start.x; beta=end.y-start.y; radius=hypot((double) alpha,(double) beta); offset.x=(double) radius; offset.y=(double) radius; degrees.x=0.0; degrees.y=360.0; TraceEllipse(primitive_info,start,offset,degrees); } static void TraceEllipse(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo stop,const PointInfo degrees) { double delta, step, y; PointInfo angle, point; register PrimitiveInfo *p; register ssize_t i; /* Ellipses are just short segmented polys. */ if ((fabs(stop.x) < DrawEpsilon) && (fabs(stop.y) < DrawEpsilon)) { TracePoint(primitive_info,start); return; } delta=2.0/MagickMax(stop.x,stop.y); step=MagickPI/8.0; if ((delta >= 0.0) && (delta < (MagickPI/8.0))) step=MagickPI/(4*(MagickPI/delta/2+0.5)); angle.x=DegreesToRadians(degrees.x); y=degrees.y; while (y < degrees.x) y+=360.0; angle.y=DegreesToRadians(y); for (p=primitive_info; angle.x < angle.y; angle.x+=step) { point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*stop.x+start.x; point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*stop.y+start.y; TracePoint(p,point); p+=p->coordinates; } point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*stop.x+start.x; point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*stop.y+start.y; TracePoint(p,point); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceLine(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end) { TracePoint(primitive_info,start); if ((fabs(start.x-end.x) < DrawEpsilon) && (fabs(start.y-end.y) < DrawEpsilon)) { primitive_info->primitive=PointPrimitive; primitive_info->coordinates=1; return; } TracePoint(primitive_info+1,end); (primitive_info+1)->primitive=primitive_info->primitive; primitive_info->coordinates=2; } static size_t TracePath(PrimitiveInfo *primitive_info,const char *path) { char *next_token, token[MagickPathExtent]; const char *p; double x, y; int attribute, last_attribute; PointInfo end = {0.0, 0.0}, points[4] = { {0.0,0.0}, {0.0,0.0}, {0.0,0.0}, {0.0,0.0} }, point = {0.0, 0.0}, start = {0.0, 0.0}; PrimitiveType primitive_type; register PrimitiveInfo *q; register ssize_t i; size_t number_coordinates, z_count; attribute=0; number_coordinates=0; z_count=0; primitive_type=primitive_info->primitive; q=primitive_info; for (p=path; *p != '\0'; ) { while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == '\0') break; last_attribute=attribute; attribute=(int) (*p++); switch (attribute) { case 'a': case 'A': { double angle; MagickBooleanType large_arc, sweep; PointInfo arc; /* Compute arc points. */ do { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arc.x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arc.y=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); angle=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse; GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse; GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); end.x=(double) (attribute == (int) 'A' ? x : point.x+x); end.y=(double) (attribute == (int) 'A' ? y : point.y+y); TraceArcPath(q,point,end,arc,angle,large_arc,sweep); q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'c': case 'C': { /* Compute bezier points. */ do { points[0]=point; for (i=1; i < 4; i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); end.x=(double) (attribute == (int) 'C' ? x : point.x+x); end.y=(double) (attribute == (int) 'C' ? y : point.y+y); points[i]=end; } for (i=0; i < 4; i++) (q+i)->point=points[i]; TraceBezier(q,4); q+=q->coordinates; point=end; } while (IsPoint(p) != MagickFalse); break; } case 'H': case 'h': { do { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); point.x=(double) (attribute == (int) 'H' ? x: point.x+x); TracePoint(q,point); q+=q->coordinates; } while (IsPoint(p) != MagickFalse); break; } case 'l': case 'L': { do { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); point.x=(double) (attribute == (int) 'L' ? x : point.x+x); point.y=(double) (attribute == (int) 'L' ? y : point.y+y); TracePoint(q,point); q+=q->coordinates; } while (IsPoint(p) != MagickFalse); break; } case 'M': case 'm': { if (q != primitive_info) { primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; primitive_info=q; } i=0; do { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); point.x=(double) (attribute == (int) 'M' ? x : point.x+x); point.y=(double) (attribute == (int) 'M' ? y : point.y+y); if (i == 0) start=point; i++; TracePoint(q,point); q+=q->coordinates; if ((i != 0) && (attribute == (int) 'M')) { TracePoint(q,point); q+=q->coordinates; } } while (IsPoint(p) != MagickFalse); break; } case 'q': case 'Q': { /* Compute bezier points. */ do { points[0]=point; for (i=1; i < 3; i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); if (*p == ',') p++; end.x=(double) (attribute == (int) 'Q' ? x : point.x+x); end.y=(double) (attribute == (int) 'Q' ? y : point.y+y); points[i]=end; } for (i=0; i < 3; i++) (q+i)->point=points[i]; TraceBezier(q,3); q+=q->coordinates; point=end; } while (IsPoint(p) != MagickFalse); break; } case 's': case 'S': { /* Compute bezier points. */ do { points[0]=points[3]; points[1].x=2.0*points[3].x-points[2].x; points[1].y=2.0*points[3].y-points[2].y; for (i=2; i < 4; i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); if (*p == ',') p++; end.x=(double) (attribute == (int) 'S' ? x : point.x+x); end.y=(double) (attribute == (int) 'S' ? y : point.y+y); points[i]=end; } if (strchr("CcSs",last_attribute) == (char *) NULL) { points[0]=point; points[1]=point; } for (i=0; i < 4; i++) (q+i)->point=points[i]; TraceBezier(q,4); q+=q->coordinates; point=end; } while (IsPoint(p) != MagickFalse); break; } case 't': case 'T': { /* Compute bezier points. */ do { points[0]=points[2]; points[1].x=2.0*points[2].x-points[1].x; points[1].y=2.0*points[2].y-points[1].y; for (i=2; i < 3; i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); end.x=(double) (attribute == (int) 'T' ? x : point.x+x); end.y=(double) (attribute == (int) 'T' ? y : point.y+y); points[i]=end; } if (strchr("QqTt",last_attribute) == (char *) NULL) { points[0]=point; points[1]=point; } for (i=0; i < 3; i++) (q+i)->point=points[i]; TraceBezier(q,3); q+=q->coordinates; point=end; } while (IsPoint(p) != MagickFalse); break; } case 'v': case 'V': { do { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); point.y=(double) (attribute == (int) 'V' ? y : point.y+y); TracePoint(q,point); q+=q->coordinates; } while (IsPoint(p) != MagickFalse); break; } case 'z': case 'Z': { point=start; TracePoint(q,point); q+=q->coordinates; primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; primitive_info=q; z_count++; break; } default: { if (isalpha((int) ((unsigned char) attribute)) != 0) (void) FormatLocaleFile(stderr,"attribute not recognized: %c\n", attribute); break; } } } primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { q--; q->primitive=primitive_type; if (z_count > 1) q->method=FillToBorderMethod; } q=primitive_info; return(number_coordinates); } static void TraceRectangle(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end) { PointInfo point; register PrimitiveInfo *p; register ssize_t i; p=primitive_info; TracePoint(p,start); p+=p->coordinates; point.x=start.x; point.y=end.y; TracePoint(p,point); p+=p->coordinates; TracePoint(p,end); p+=p->coordinates; point.x=end.x; point.y=start.y; TracePoint(p,point); p+=p->coordinates; TracePoint(p,start); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceRoundRectangle(PrimitiveInfo *primitive_info, const PointInfo start,const PointInfo end,PointInfo arc) { PointInfo degrees, offset, point; register PrimitiveInfo *p; register ssize_t i; p=primitive_info; offset.x=fabs(end.x-start.x); offset.y=fabs(end.y-start.y); if (arc.x > (0.5*offset.x)) arc.x=0.5*offset.x; if (arc.y > (0.5*offset.y)) arc.y=0.5*offset.y; point.x=start.x+offset.x-arc.x; point.y=start.y+arc.y; degrees.x=270.0; degrees.y=360.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; point.x=start.x+offset.x-arc.x; point.y=start.y+offset.y-arc.y; degrees.x=0.0; degrees.y=90.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+offset.y-arc.y; degrees.x=90.0; degrees.y=180.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+arc.y; degrees.x=180.0; degrees.y=270.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; TracePoint(p,primitive_info->point); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceSquareLinecap(PrimitiveInfo *primitive_info, const size_t number_vertices,const double offset) { double distance; register double dx, dy; register ssize_t i; ssize_t j; dx=0.0; dy=0.0; for (i=1; i < (ssize_t) number_vertices; i++) { dx=primitive_info[0].point.x-primitive_info[i].point.x; dy=primitive_info[0].point.y-primitive_info[i].point.y; if ((fabs((double) dx) >= DrawEpsilon) || (fabs((double) dy) >= DrawEpsilon)) break; } if (i == (ssize_t) number_vertices) i=(ssize_t) number_vertices-1L; distance=hypot((double) dx,(double) dy); primitive_info[0].point.x=(double) (primitive_info[i].point.x+ dx*(distance+offset)/distance); primitive_info[0].point.y=(double) (primitive_info[i].point.y+ dy*(distance+offset)/distance); for (j=(ssize_t) number_vertices-2; j >= 0; j--) { dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x; dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y; if ((fabs((double) dx) >= DrawEpsilon) || (fabs((double) dy) >= DrawEpsilon)) break; } distance=hypot((double) dx,(double) dy); primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+ dx*(distance+offset)/distance); primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+ dy*(distance+offset)/distance); } static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info) { typedef struct _LineSegment { double p, q; } LineSegment; double delta_theta, dot_product, mid, miterlimit; LineSegment dx, dy, inverse_slope, slope, theta; MagickBooleanType closed_path; PointInfo box_p[5], box_q[5], center, offset, *path_p, *path_q; PrimitiveInfo *polygon_primitive, *stroke_polygon; register ssize_t i; size_t arc_segments, max_strokes, number_vertices; ssize_t j, n, p, q; /* Allocate paths. */ number_vertices=primitive_info->coordinates; max_strokes=2*number_vertices+6*BezierQuantum+360; path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_p)); path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_q)); polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_vertices+2UL,sizeof(*polygon_primitive)); if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) || (polygon_primitive == (PrimitiveInfo *) NULL)) return((PrimitiveInfo *) NULL); (void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t) number_vertices*sizeof(*polygon_primitive)); closed_path= (fabs(primitive_info[number_vertices-1].point.x-primitive_info[0].point.x) < DrawEpsilon) && (fabs(primitive_info[number_vertices-1].point.y-primitive_info[0].point.y) < DrawEpsilon) ? MagickTrue : MagickFalse; if (((draw_info->linejoin == RoundJoin) || (draw_info->linejoin == MiterJoin)) && (closed_path != MagickFalse)) { polygon_primitive[number_vertices]=primitive_info[1]; number_vertices++; } polygon_primitive[number_vertices].primitive=UndefinedPrimitive; /* Compute the slope for the first line segment, p. */ dx.p=0.0; dy.p=0.0; for (n=1; n < (ssize_t) number_vertices; n++) { dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x; dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y; if ((fabs(dx.p) >= DrawEpsilon) || (fabs(dy.p) >= DrawEpsilon)) break; } if (n == (ssize_t) number_vertices) n=(ssize_t) number_vertices-1L; slope.p=0.0; inverse_slope.p=0.0; if (fabs(dx.p) < DrawEpsilon) { if (dx.p >= 0.0) slope.p=dy.p < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon; else slope.p=dy.p < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon; } else if (fabs(dy.p) < DrawEpsilon) { if (dy.p >= 0.0) inverse_slope.p=dx.p < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon; else inverse_slope.p=dx.p < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon; } else { slope.p=dy.p/dx.p; inverse_slope.p=(-1.0/slope.p); } mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*mid*mid); if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse)) TraceSquareLinecap(polygon_primitive,number_vertices,mid); offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0))); offset.y=(double) (offset.x*inverse_slope.p); if ((dy.p*offset.x-dx.p*offset.y) > 0.0) { box_p[0].x=polygon_primitive[0].point.x-offset.x; box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p; box_p[1].x=polygon_primitive[n].point.x-offset.x; box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p; box_q[0].x=polygon_primitive[0].point.x+offset.x; box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p; box_q[1].x=polygon_primitive[n].point.x+offset.x; box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p; } else { box_p[0].x=polygon_primitive[0].point.x+offset.x; box_p[0].y=polygon_primitive[0].point.y+offset.y; box_p[1].x=polygon_primitive[n].point.x+offset.x; box_p[1].y=polygon_primitive[n].point.y+offset.y; box_q[0].x=polygon_primitive[0].point.x-offset.x; box_q[0].y=polygon_primitive[0].point.y-offset.y; box_q[1].x=polygon_primitive[n].point.x-offset.x; box_q[1].y=polygon_primitive[n].point.y-offset.y; } /* Create strokes for the line join attribute: bevel, miter, round. */ p=0; q=0; path_q[p++]=box_q[0]; path_p[q++]=box_p[0]; for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++) { /* Compute the slope for this line segment, q. */ dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x; dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y; dot_product=dx.q*dx.q+dy.q*dy.q; if (dot_product < 0.25) continue; slope.q=0.0; inverse_slope.q=0.0; if (fabs(dx.q) < DrawEpsilon) { if (dx.q >= 0.0) slope.q=dy.q < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon; else slope.q=dy.q < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon; } else if (fabs(dy.q) < DrawEpsilon) { if (dy.q >= 0.0) inverse_slope.q=dx.q < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon; else inverse_slope.q=dx.q < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon; } else { slope.q=dy.q/dx.q; inverse_slope.q=(-1.0/slope.q); } offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0))); offset.y=(double) (offset.x*inverse_slope.q); dot_product=dy.q*offset.x-dx.q*offset.y; if (dot_product > 0.0) { box_p[2].x=polygon_primitive[n].point.x-offset.x; box_p[2].y=polygon_primitive[n].point.y-offset.y; box_p[3].x=polygon_primitive[i].point.x-offset.x; box_p[3].y=polygon_primitive[i].point.y-offset.y; box_q[2].x=polygon_primitive[n].point.x+offset.x; box_q[2].y=polygon_primitive[n].point.y+offset.y; box_q[3].x=polygon_primitive[i].point.x+offset.x; box_q[3].y=polygon_primitive[i].point.y+offset.y; } else { box_p[2].x=polygon_primitive[n].point.x+offset.x; box_p[2].y=polygon_primitive[n].point.y+offset.y; box_p[3].x=polygon_primitive[i].point.x+offset.x; box_p[3].y=polygon_primitive[i].point.y+offset.y; box_q[2].x=polygon_primitive[n].point.x-offset.x; box_q[2].y=polygon_primitive[n].point.y-offset.y; box_q[3].x=polygon_primitive[i].point.x-offset.x; box_q[3].y=polygon_primitive[i].point.y-offset.y; } if (fabs((double) (slope.p-slope.q)) < DrawEpsilon) { box_p[4]=box_p[1]; box_q[4]=box_q[1]; } else { box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+ box_p[3].y)/(slope.p-slope.q)); box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y); box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+ box_q[3].y)/(slope.p-slope.q)); box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y); } if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360)) { if (~max_strokes < (6*BezierQuantum+360)) { path_p=(PointInfo *) RelinquishMagickMemory(path_p); path_q=(PointInfo *) RelinquishMagickMemory(path_q); } else { max_strokes+=6*BezierQuantum+360; path_p=(PointInfo *) ResizeQuantumMemory(path_p,max_strokes, sizeof(*path_p)); path_q=(PointInfo *) ResizeQuantumMemory(path_q,max_strokes, sizeof(*path_q)); } if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL)) { if (path_p != (PointInfo *) NULL) path_p=(PointInfo *) RelinquishMagickMemory(path_p); if (path_q != (PointInfo *) NULL) path_q=(PointInfo *) RelinquishMagickMemory(path_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return((PrimitiveInfo *) NULL); } } dot_product=dx.q*dy.p-dx.p*dy.q; if (dot_product <= 0.0) switch (draw_info->linejoin) { case BevelJoin: { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x); theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x); if (theta.q < theta.p) theta.q+=2.0*MagickPI; arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/ (2.0*sqrt((double) (1.0/mid))))); path_q[q].x=box_q[1].x; path_q[q].y=box_q[1].y; q++; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); path_q[q].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_q[q].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); q++; } path_q[q++]=box_q[2]; break; } default: break; } else switch (draw_info->linejoin) { case BevelJoin: { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x); theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x); if (theta.p < theta.q) theta.p+=2.0*MagickPI; arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/ (2.0*sqrt((double) (1.0/mid))))); path_p[p++]=box_p[1]; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); path_p[p].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_p[p].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); p++; } path_p[p++]=box_p[2]; break; } default: break; } slope.p=slope.q; inverse_slope.p=inverse_slope.q; box_p[0]=box_p[2]; box_p[1]=box_p[3]; box_q[0]=box_q[2]; box_q[1]=box_q[3]; dx.p=dx.q; dy.p=dy.q; n=i; } path_p[p++]=box_p[1]; path_q[q++]=box_q[1]; /* Trace stroked polygon. */ stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon)); if (stroke_polygon != (PrimitiveInfo *) NULL) { for (i=0; i < (ssize_t) p; i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=path_p[i]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; } for ( ; i < (ssize_t) (p+q+closed_path); i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[p+closed_path].point; i++; } stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; stroke_polygon[i].primitive=UndefinedPrimitive; stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1); } path_p=(PointInfo *) RelinquishMagickMemory(path_p); path_q=(PointInfo *) RelinquishMagickMemory(path_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return(stroke_polygon); }
CBasedTraversal.h
/** * @file CBasedTraversal.h * @author C. Menges * @date 26.04.2019 */ #pragma once #include "autopas/containers/cellPairTraversals/CellPairTraversal.h" #include "autopas/utils/ArrayMath.h" #include "autopas/utils/DataLayoutConverter.h" #include "autopas/utils/ThreeDimensionalMapping.h" namespace autopas { /** * This class provides the base for traversals using base steps based on cell coloring. * * @tparam ParticleCell the type of cells * @tparam PairwiseFunctor The functor that defines the interaction of two particles. * @tparam dataLayout * @tparam useNewton3 * @tparam collapseDepth Set the depth of loop collapsion for OpenMP. Loop variables from outer to inner loop: z,y,x */ template <class ParticleCell, class PairwiseFunctor, DataLayoutOption dataLayout, bool useNewton3, int collapseDepth = 3> class CBasedTraversal : public CellPairTraversal<ParticleCell> { protected: /** * Constructor of the CBasedTraversal. * @param dims The dimensions of the cellblock, i.e. the number of cells in x, * y and z direction. * @param pairwiseFunctor The functor that defines the interaction of two particles. * @param interactionLength Interaction length (cutoff + skin). * @param cellLength cell length. */ explicit CBasedTraversal(const std::array<unsigned long, 3> &dims, PairwiseFunctor *pairwiseFunctor, const double interactionLength, const std::array<double, 3> &cellLength) : CellPairTraversal<ParticleCell>(dims), _interactionLength(interactionLength), _cellLength(cellLength), _dataLayoutConverter(pairwiseFunctor) { for (unsigned int d = 0; d < 3; d++) { _overlap[d] = std::ceil(_interactionLength / _cellLength[d]); } } /** * Destructor of CBasedTraversal. */ ~CBasedTraversal() override = default; public: /** * load Data Layouts required for this Traversal if cells have been set through setCellsToTraverse(). */ void initTraversal() override { if (this->_cells) { auto &cells = *(this->_cells); #ifdef AUTOPAS_OPENMP // @todo find a condition on when to use omp or when it is just overhead #pragma omp parallel for #endif for (size_t i = 0; i < cells.size(); ++i) { _dataLayoutConverter.loadDataLayout(cells[i]); } } } /** * write Data to AoS if cells have been set through setCellsToTraverse(). */ void endTraversal() override { if (this->_cells) { auto &cells = *(this->_cells); #ifdef AUTOPAS_OPENMP // @todo find a condition on when to use omp or when it is just overhead #pragma omp parallel for #endif for (size_t i = 0; i < cells.size(); ++i) { _dataLayoutConverter.storeDataLayout(cells[i]); } } } protected: /** * The main traversal of the CTraversal. * @tparam LoopBody type of the loop body * @param loopBody The body of the loop as a function. Normally a lambda function, that takes as as parameters * (x,y,z). If you need additional input from outside, please use captures (by reference). * @param end 3D index until interactions are processed (exclusive) * @param stride dimension of stride (depends on coloring) * @param offset initial offset */ template <typename LoopBody> inline void cTraversal(LoopBody &&loopBody, const std::array<unsigned long, 3> &end, const std::array<unsigned long, 3> &stride, const std::array<unsigned long, 3> &offset = {0ul, 0ul, 0ul}); /** * This method is called when the color during the traversal has changed. * * @param newColor The new current color. */ virtual void notifyColorChange(unsigned long newColor){}; /** * Interaction length (cutoff + skin). */ const double _interactionLength; /** * cell length in CellBlock3D. */ const std::array<double, 3> _cellLength; /** * overlap of interacting cells. Array allows asymmetric cell sizes. */ std::array<unsigned long, 3> _overlap; private: /** * Data Layout Converter to be used with this traversal */ utils::DataLayoutConverter<PairwiseFunctor, dataLayout> _dataLayoutConverter; }; template <class ParticleCell, class PairwiseFunctor, DataLayoutOption dataLayout, bool useNewton3, int collapseDepth> template <typename LoopBody> inline void CBasedTraversal<ParticleCell, PairwiseFunctor, dataLayout, useNewton3, collapseDepth>::cTraversal( LoopBody &&loopBody, const std::array<unsigned long, 3> &end, const std::array<unsigned long, 3> &stride, const std::array<unsigned long, 3> &offset) { #if defined(AUTOPAS_OPENMP) #pragma omp parallel #endif { const unsigned long numColors = stride[0] * stride[1] * stride[2]; for (unsigned long col = 0; col < numColors; ++col) { notifyColorChange(col); std::array<unsigned long, 3> startWithoutOffset(utils::ThreeDimensionalMapping::oneToThreeD(col, stride)); std::array<unsigned long, 3> start(ArrayMath::add(startWithoutOffset, offset)); // intel compiler demands following: const unsigned long start_x = start[0], start_y = start[1], start_z = start[2]; const unsigned long end_x = end[0], end_y = end[1], end_z = end[2]; const unsigned long stride_x = stride[0], stride_y = stride[1], stride_z = stride[2]; if (collapseDepth == 2) { #if defined(AUTOPAS_OPENMP) #pragma omp for schedule(dynamic, 1) collapse(2) #endif for (unsigned long z = start_z; z < end_z; z += stride_z) { for (unsigned long y = start_y; y < end_y; y += stride_y) { for (unsigned long x = start_x; x < end_x; x += stride_x) { // Don't exchange order of execution (x must be last!), it would break other code loopBody(x, y, z); } } } } else { #if defined(AUTOPAS_OPENMP) #pragma omp for schedule(dynamic, 1) collapse(3) #endif for (unsigned long z = start_z; z < end_z; z += stride_z) { for (unsigned long y = start_y; y < end_y; y += stride_y) { for (unsigned long x = start_x; x < end_x; x += stride_x) { // Don't exchange order of execution (x must be last!), it would break other code loopBody(x, y, z); } } } } } } } } // namespace autopas
generator_gemm_common.c
/****************************************************************************** * Copyright (c) Intel Corporation - All rights reserved. * * This file is part of the LIBXSMM library. * * * * For information on the license, see the LICENSE file. * * Further information: https://github.com/hfp/libxsmm/ * * SPDX-License-Identifier: BSD-3-Clause * ******************************************************************************/ /* Alexander Heinecke (Intel Corp.) ******************************************************************************/ #include "generator_gemm_common.h" #include "generator_common.h" #include "generator_x86_instructions.h" #include "libxsmm_main.h" LIBXSMM_API_INTERN int libxsmm_generator_gemm_get_rbp_relative_offset( libxsmm_gemm_stack_var stack_var ) { /* The stack at exit of setup looks like this: * * 10th param (if applicable) <-- RBP+40 * 9th param (if applicable) <-- RBP+32 * 8th param (if applicable) <-- RBP+24 * 7th param (if applicable) <-- RBP+16 * Return address <-- RBP+8 * Entry/saved RBP <-- RBP * prefetch A ptr <-- RBP-8 * prefetch B ptr <-- RBP-16 * Offset A array ptr <-- RBP-24 * Offset B array ptr <-- RBP-32 * Int8 scaling factor <-- RBP-40 * GEMM_scratch ptr in stack (to be filled) <-- RBP-48 * Eltwise bias ptr <-- RBP-56 * Eltwise output_ptr <-- RBP-64 * Eltwise buf1_ptr <-- RBP-72 * Eltwise buf2_ptr <-- RBP-80 * * */ switch ( stack_var ) { case LIBXSMM_GEMM_STACK_VAR_NONE: return 0; case LIBXSMM_GEMM_STACK_VAR_PFA_PTR: return -8; case LIBXSMM_GEMM_STACK_VAR_PFB_PTR: return -16; case LIBXSMM_GEMM_STACK_VAR_A_OFFS_BRGEMM_PTR: return -24; case LIBXSMM_GEMM_STACK_VAR_B_OFFS_BRGEMM_PTR: return -32; case LIBXSMM_GEMM_STACK_VAR_INT8_SCF: return -40; case LIBXSMM_GEMM_STACK_VAR_GEMM_SCRATCH_PTR: return -48; case LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR: return -56; case LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR: return -64; case LIBXSMM_GEMM_STACK_VAR_ELT_RELU_BITMASK_PTR: return -72; case LIBXSMM_GEMM_STACK_VAR_ELT_BUF1: return -72; case LIBXSMM_GEMM_STACK_VAR_ELT_BUF2: return -80; case LIBXSMM_GEMM_STACK_VAR_TRANS_EXT_BUF_B: return -72; case LIBXSMM_GEMM_STACK_VAR_TRANS_EXT_BUF_C: return -80; case LIBXSMM_GEMM_STACK_VAR_ELT_BITMAP_PTR: return -72; case LIBXSMM_GEMM_STACK_VAR_ELT_DECOMPRESS_BUF: return -80; case LIBXSMM_GEMM_STACK_VAR_ARG_7: return 16; case LIBXSMM_GEMM_STACK_VAR_ARG_8: return 24; case LIBXSMM_GEMM_STACK_VAR_ARG_9: return 32; case LIBXSMM_GEMM_STACK_VAR_ARG_10: return 40; default: return 0; } } LIBXSMM_API_INTERN void libxsmm_generator_gemm_getval_stack_var( libxsmm_generated_code* io_generated_code, const libxsmm_micro_kernel_config* i_micro_kernel_config, libxsmm_gemm_stack_var stack_var, unsigned int i_gp_reg ) { int offset = libxsmm_generator_gemm_get_rbp_relative_offset(stack_var); /* make sure we requested a legal stack var */ if (offset == 0) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_GENERAL ); return; } libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, LIBXSMM_X86_GP_REG_RBP, LIBXSMM_X86_GP_REG_UNDEF, 0, offset, i_gp_reg, 0 ); } LIBXSMM_API_INTERN void libxsmm_generator_gemm_setval_stack_var( libxsmm_generated_code* io_generated_code, const libxsmm_micro_kernel_config* i_micro_kernel_config, libxsmm_gemm_stack_var stack_var, unsigned int i_gp_reg ) { int offset = libxsmm_generator_gemm_get_rbp_relative_offset(stack_var); /* make sure we requested to set a legal stack var */ if (offset >= 0) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_GENERAL ); return; } libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, LIBXSMM_X86_GP_REG_RBP, LIBXSMM_X86_GP_REG_UNDEF, 0, offset, i_gp_reg, 1 ); } LIBXSMM_API_INTERN void libxsmm_generator_gemm_init_micro_kernel_config_fullvector( libxsmm_micro_kernel_config* io_micro_kernel_config, const unsigned int i_arch, const libxsmm_gemm_descriptor* i_xgemm_desc, const unsigned int i_use_masking_a_c ) { memset(io_micro_kernel_config, 0, sizeof(*io_micro_kernel_config)); /* avoid warning "maybe used uninitialized" */ if ( (i_arch < LIBXSMM_X86_SSE3) || (i_arch > LIBXSMM_X86_ALLFEAT) ) { io_micro_kernel_config->instruction_set = LIBXSMM_X86_GENERIC; io_micro_kernel_config->vector_reg_count = 0; io_micro_kernel_config->use_masking_a_c = 0; io_micro_kernel_config->vector_name = 'a'; io_micro_kernel_config->vector_length = 0; io_micro_kernel_config->datatype_size = 0; io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF; } else if ( i_arch <= LIBXSMM_X86_SSE4 ) { io_micro_kernel_config->instruction_set = LIBXSMM_X86_SSE3; io_micro_kernel_config->vector_reg_count = 16; io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c; io_micro_kernel_config->vector_name = 'x'; if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { io_micro_kernel_config->vector_length = 2; io_micro_kernel_config->datatype_size = 8; if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVAPD; } else { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVUPD; } io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_MOVDDUP; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVAPD; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVAPD; } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVUPD; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVUPD; } io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_XORPD; io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_MULPD; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_ADDPD; } else { io_micro_kernel_config->vector_length = 4; io_micro_kernel_config->datatype_size = 4; if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVAPS; } else { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVUPS; } io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_MOVSS; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_SHUFPS; if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVAPS; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVAPS; } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVUPS; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVUPS; } io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_XORPS; io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_MULPS; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_ADDPS; } } else if ( i_arch <= LIBXSMM_X86_AVX2 ) { io_micro_kernel_config->instruction_set = i_arch; io_micro_kernel_config->vector_reg_count = 16; io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c; io_micro_kernel_config->vector_name = 'y'; if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { io_micro_kernel_config->vector_length = 4; io_micro_kernel_config->datatype_size = 8; if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD; } else { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD; } io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSD; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPD; } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPD; } io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPD; if ( i_arch == LIBXSMM_X86_AVX ) { io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULPD; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPD; } else { io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PD; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPD; } } else { io_micro_kernel_config->vector_length = 8; io_micro_kernel_config->datatype_size = 4; if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; } else { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS; } io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSS; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS; } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS; } io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPS; if ( i_arch == LIBXSMM_X86_AVX ) { io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULPS; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS; } else { io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PS; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS; } } } else if ( i_arch <= LIBXSMM_X86_ALLFEAT ) { io_micro_kernel_config->instruction_set = i_arch; io_micro_kernel_config->vector_reg_count = 32; io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c; io_micro_kernel_config->vector_name = 'z'; if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { io_micro_kernel_config->vector_length = 8; io_micro_kernel_config->datatype_size = 8; if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD; } else { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD; } io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSD; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD; if ( (i_use_masking_a_c == 0) ) { io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPD; } else { io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVAPD; } } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPD; } io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD; io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PD; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPD; } else if ( LIBXSMM_GEMM_PRECISION_F32 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { io_micro_kernel_config->vector_length = 16; io_micro_kernel_config->datatype_size = 4; if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; } else { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS; } io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSS; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; if ( (i_use_masking_a_c == 0) ) { io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS; } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; } } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS; } io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD; io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PS; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS; } else if ( LIBXSMM_GEMM_PRECISION_I16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { /* C is 32bit, so we treat all 3 matrices as 32bit element arrays */ io_micro_kernel_config->vector_length = 16; io_micro_kernel_config->datatype_size = 4; if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; } else { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS; } io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTD; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; if ( (i_use_masking_a_c == 0) ) { io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS; } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; } } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS; } io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD; io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VPDPWSSD; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VPADDD; } else if ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { /* C is 32bit, so we treat all 3 matrices as 32bit element arrays */ io_micro_kernel_config->vector_length = 16; io_micro_kernel_config->datatype_size = 4; if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; } else { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS; } io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTD; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; if ( (i_use_masking_a_c == 0) ) { io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS; } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; } } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS; } io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD; io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VPDPBUSD; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VPADDD; } else if ( LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { /* C is 32bit, so we treat all 3 matrices as 32bit element arrays */ io_micro_kernel_config->vector_length = 16; io_micro_kernel_config->datatype_size = 4; if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; } else { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS; } io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTD; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; if ( (i_use_masking_a_c == 0) ) { io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS; } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; } } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS; } io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD; io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VDPBF16PS; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS; } else { /* shouldn't happen as we caught this case earlier */ io_micro_kernel_config->instruction_set = LIBXSMM_X86_GENERIC; io_micro_kernel_config->vector_reg_count = 0; io_micro_kernel_config->use_masking_a_c = 0; io_micro_kernel_config->vector_name = 'a'; io_micro_kernel_config->vector_length = 0; io_micro_kernel_config->datatype_size = 0; io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF; } } else { /* that should no happen */ } io_micro_kernel_config->prefetch_instruction = LIBXSMM_X86_INSTR_PREFETCHT1; io_micro_kernel_config->alu_add_instruction = LIBXSMM_X86_INSTR_ADDQ; io_micro_kernel_config->alu_sub_instruction = LIBXSMM_X86_INSTR_SUBQ; io_micro_kernel_config->alu_cmp_instruction = LIBXSMM_X86_INSTR_CMPQ; io_micro_kernel_config->alu_jmp_instruction = LIBXSMM_X86_INSTR_JL; io_micro_kernel_config->alu_mov_instruction = LIBXSMM_X86_INSTR_MOVQ; } LIBXSMM_API_INTERN void libxsmm_generator_gemm_init_micro_kernel_config_halfvector( libxsmm_micro_kernel_config* io_micro_kernel_config, const unsigned int i_arch, const libxsmm_gemm_descriptor* i_xgemm_desc, const unsigned int i_use_masking_a_c ) { if ( (i_arch < LIBXSMM_X86_SSE3) || (i_arch > LIBXSMM_X86_ALLFEAT) ) { io_micro_kernel_config->instruction_set = LIBXSMM_X86_GENERIC; io_micro_kernel_config->vector_reg_count = 0; io_micro_kernel_config->use_masking_a_c = 0; io_micro_kernel_config->vector_name = 'a'; io_micro_kernel_config->vector_length = 0; io_micro_kernel_config->datatype_size = 0; io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF; } else if ( i_arch <= LIBXSMM_X86_SSE4 ) { #if !defined(NDEBUG) fprintf(stderr, "LIBXSMM WARNING, libxsmm_generator_gemm_init_micro_kernel_config_halfvector, redirecting to scalar, please fix the generation code!!!\n"); #endif libxsmm_generator_gemm_init_micro_kernel_config_scalar( io_micro_kernel_config, i_arch, i_xgemm_desc, i_use_masking_a_c ); } else if ( i_arch <= LIBXSMM_X86_AVX2 ) { io_micro_kernel_config->instruction_set = LIBXSMM_X86_AVX; io_micro_kernel_config->vector_reg_count = 16; io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c; io_micro_kernel_config->vector_name = 'x'; if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { io_micro_kernel_config->vector_length = 2; io_micro_kernel_config->datatype_size = 8; if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD; } else { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD; } io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VMOVDDUP; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPD; } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPD; } io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPD; if ( i_arch == LIBXSMM_X86_AVX ) { io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULPD; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPD; } else { io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PD; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF; } } else { io_micro_kernel_config->vector_length = 4; io_micro_kernel_config->datatype_size = 4; if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; } else { io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS; } io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSS; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS; } else { io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS; } io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPS; if ( i_arch == LIBXSMM_X86_AVX ) { io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULPS; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS; } else { io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PS; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF; } } } else if ( i_arch <= LIBXSMM_X86_ALLFEAT ) { #if !defined(NDEBUG) fprintf(stderr, "LIBXSMM WARNING, libxsmm_generator_gemm_init_micro_kernel_config_halfvector, AVX512 redirecting to fullvector!\n"); #endif libxsmm_generator_gemm_init_micro_kernel_config_fullvector( io_micro_kernel_config, i_arch, i_xgemm_desc, i_use_masking_a_c ); } else { /* should not happen */ } io_micro_kernel_config->prefetch_instruction = LIBXSMM_X86_INSTR_PREFETCHT1; io_micro_kernel_config->alu_add_instruction = LIBXSMM_X86_INSTR_ADDQ; io_micro_kernel_config->alu_sub_instruction = LIBXSMM_X86_INSTR_SUBQ; io_micro_kernel_config->alu_cmp_instruction = LIBXSMM_X86_INSTR_CMPQ; io_micro_kernel_config->alu_jmp_instruction = LIBXSMM_X86_INSTR_JL; io_micro_kernel_config->alu_mov_instruction = LIBXSMM_X86_INSTR_MOVQ; } LIBXSMM_API_INTERN void libxsmm_generator_gemm_init_micro_kernel_config_scalar( libxsmm_micro_kernel_config* io_micro_kernel_config, const unsigned int i_arch, const libxsmm_gemm_descriptor* i_xgemm_desc, const unsigned int i_use_masking_a_c ) { if ( ( i_arch < LIBXSMM_X86_SSE3 ) || ( i_arch > LIBXSMM_X86_ALLFEAT ) ) { io_micro_kernel_config->instruction_set = LIBXSMM_X86_GENERIC; io_micro_kernel_config->vector_reg_count = 0; io_micro_kernel_config->use_masking_a_c = 0; io_micro_kernel_config->vector_name = 'a'; io_micro_kernel_config->vector_length = 0; io_micro_kernel_config->datatype_size = 0; io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF; } else if ( i_arch <= LIBXSMM_X86_SSE4 ) { io_micro_kernel_config->instruction_set = LIBXSMM_X86_SSE3; io_micro_kernel_config->vector_reg_count = 16; io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c; io_micro_kernel_config->vector_name = 'x'; if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { io_micro_kernel_config->vector_length = 1; io_micro_kernel_config->datatype_size = 8; io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVSD; io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_MOVSD; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVSD; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVSD; io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_XORPD; io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_MULSD; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_ADDSD; } else { io_micro_kernel_config->vector_length = 1; io_micro_kernel_config->datatype_size = 4; io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVSS; io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_MOVSS; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVSS; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVSS; io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_XORPS; io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_MULSS; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_ADDSS; } } else if ( i_arch <= LIBXSMM_X86_ALLFEAT ) { io_micro_kernel_config->instruction_set = i_arch; io_micro_kernel_config->vector_reg_count = 16; io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c; io_micro_kernel_config->vector_name = 'x'; if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { io_micro_kernel_config->vector_length = 1; io_micro_kernel_config->datatype_size = 8; io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSD; io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSD; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSD; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVSD; io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPD; if ( i_arch == LIBXSMM_X86_AVX ) { io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULSD; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDSD; } else { io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231SD; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF; } } else { io_micro_kernel_config->vector_length = 1; io_micro_kernel_config->datatype_size = 4; io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSS; io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSS; io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF; io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSS; io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVSS; io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPS; if ( i_arch == LIBXSMM_X86_AVX ) { io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULSS; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDSS; } else { io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231SS; io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF; } } } else { /* should not happen */ } io_micro_kernel_config->prefetch_instruction = LIBXSMM_X86_INSTR_PREFETCHT1; io_micro_kernel_config->alu_add_instruction = LIBXSMM_X86_INSTR_ADDQ; io_micro_kernel_config->alu_sub_instruction = LIBXSMM_X86_INSTR_SUBQ; io_micro_kernel_config->alu_cmp_instruction = LIBXSMM_X86_INSTR_CMPQ; io_micro_kernel_config->alu_jmp_instruction = LIBXSMM_X86_INSTR_JL; io_micro_kernel_config->alu_mov_instruction = LIBXSMM_X86_INSTR_MOVQ; } LIBXSMM_API_INTERN void libxsmm_generator_gemm_add_flop_counter( libxsmm_generated_code* io_generated_code, const libxsmm_gemm_descriptor* i_xgemm_desc ) { if ( io_generated_code->code_type == 0 ) { char l_new_code[512]; const unsigned int l_max_code_length = sizeof(l_new_code) - 1; int l_code_length = 0; l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#ifndef NDEBUG\n" ); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#ifdef _OPENMP\n" ); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#pragma omp atomic\n" ); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#endif\n" ); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "libxsmm_num_total_flops += %u;\n", 2u * i_xgemm_desc->m * i_xgemm_desc->n * i_xgemm_desc->k); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#endif\n" ); libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length ); } } LIBXSMM_API_INTERN void libxsmm_generator_gemm_header_kloop( libxsmm_generated_code* io_generated_code, libxsmm_loop_label_tracker* io_loop_label_tracker, const libxsmm_gp_reg_mapping* i_gp_reg_mapping, const libxsmm_micro_kernel_config* i_micro_kernel_config, const unsigned int i_m_blocking, const unsigned int i_k_blocking ) { LIBXSMM_UNUSED(i_m_blocking); libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_kloop, 0); libxsmm_x86_instruction_register_jump_back_label( io_generated_code, io_loop_label_tracker ); libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_kloop, i_k_blocking); } LIBXSMM_API_INTERN void libxsmm_generator_gemm_footer_kloop( libxsmm_generated_code* io_generated_code, libxsmm_loop_label_tracker* io_loop_label_tracker, const libxsmm_gp_reg_mapping* i_gp_reg_mapping, const libxsmm_micro_kernel_config* i_micro_kernel_config, const libxsmm_gemm_descriptor* i_xgemm_desc, const unsigned int i_m_blocking, const unsigned int i_max_blocked_k, const unsigned int i_kloop_complete ) { LIBXSMM_UNUSED(i_m_blocking); libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_cmp_instruction, i_gp_reg_mapping->gp_reg_kloop, i_max_blocked_k ); libxsmm_x86_instruction_jump_back_to_label( io_generated_code, i_micro_kernel_config->alu_jmp_instruction, io_loop_label_tracker ); if ( i_kloop_complete != 0 ) { int l_b_offset = 0; if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) > 0 ) { l_b_offset = i_xgemm_desc->ldb * i_xgemm_desc->k * i_micro_kernel_config->datatype_size; } else { l_b_offset = i_xgemm_desc->k * i_micro_kernel_config->datatype_size; } libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_b, l_b_offset ); } } LIBXSMM_API_INTERN void libxsmm_generator_gemm_header_reduceloop( libxsmm_generated_code* io_generated_code, libxsmm_loop_label_tracker* io_loop_label_tracker, const libxsmm_gp_reg_mapping* i_gp_reg_mapping, const libxsmm_micro_kernel_config* i_micro_kernel_config ) { libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_reduce_loop, 0); libxsmm_x86_instruction_register_jump_back_label( io_generated_code, io_loop_label_tracker ); } LIBXSMM_API_INTERN void libxsmm_generator_gemm_footer_reduceloop( libxsmm_generated_code* io_generated_code, libxsmm_loop_label_tracker* io_loop_label_tracker, const libxsmm_gp_reg_mapping* i_gp_reg_mapping, const libxsmm_micro_kernel_config* i_micro_kernel_config, const libxsmm_gemm_descriptor* i_xgemm_desc) { LIBXSMM_UNUSED(i_xgemm_desc); libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_reduce_loop, 1); libxsmm_x86_instruction_alu_reg( io_generated_code, i_micro_kernel_config->alu_cmp_instruction, i_gp_reg_mapping->gp_reg_reduce_count, i_gp_reg_mapping->gp_reg_reduce_loop); libxsmm_x86_instruction_jump_back_to_label( io_generated_code, i_micro_kernel_config->alu_jmp_instruction, io_loop_label_tracker ); } LIBXSMM_API_INTERN void libxsmm_generator_gemm_header_nloop( libxsmm_generated_code* io_generated_code, libxsmm_loop_label_tracker* io_loop_label_tracker, const libxsmm_gp_reg_mapping* i_gp_reg_mapping, const libxsmm_micro_kernel_config* i_micro_kernel_config, const unsigned int i_n_blocking) { libxsmm_x86_instruction_register_jump_back_label( io_generated_code, io_loop_label_tracker ); libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_nloop, i_n_blocking ); libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_mloop, 0 ); } LIBXSMM_API_INTERN void libxsmm_generator_gemm_footer_nloop( libxsmm_generated_code* io_generated_code, libxsmm_loop_label_tracker* io_loop_label_tracker, const libxsmm_gp_reg_mapping* i_gp_reg_mapping, const libxsmm_micro_kernel_config* i_micro_kernel_config, const libxsmm_gemm_descriptor* i_xgemm_desc, const unsigned int i_n_blocking, const unsigned int i_n_done ) { if ( LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) { libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c, (i_n_blocking*(i_xgemm_desc->ldc)*(i_micro_kernel_config->datatype_size/2)) - ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size/2)) ); } else if ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) { libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c, (i_n_blocking*(i_xgemm_desc->ldc)*(i_micro_kernel_config->datatype_size/4)) - ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size/4)) ); } else { libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c, (i_n_blocking*(i_xgemm_desc->ldc)*(i_micro_kernel_config->datatype_size)) - ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size)) ); } /* B prefetch */ if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_BL2_VIA_C || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C_AHEAD ) { if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) == 0 ) { unsigned int l_type_scaling; if ( (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype )) || (LIBXSMM_GEMM_PRECISION_I16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype )) ) { l_type_scaling = 2; } else if ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { l_type_scaling = 4; } else { l_type_scaling = 1; } libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_b_prefetch, (i_n_blocking*(i_xgemm_desc->ldc)*(i_micro_kernel_config->datatype_size/l_type_scaling)) - ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size/l_type_scaling)) ); } } #if 0 if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_CL2 || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2CL2BL2_VIA_C ) { libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c_prefetch, (i_n_blocking*(i_xgemm_desc->ldc)*(i_micro_kernel_config->datatype_size)) - ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size)) ); } #endif if (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_ADDRESS) { /* handle trans B */ int l_b_offset = 0; if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) > 0 ) { l_b_offset = i_n_blocking * i_micro_kernel_config->datatype_size; } else { l_b_offset = i_n_blocking * i_xgemm_desc->ldb * i_micro_kernel_config->datatype_size; } libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 ); libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop ); libxsmm_generator_gemm_header_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config ); libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_a, i_gp_reg_mapping->gp_reg_reduce_loop, 8, 0, i_gp_reg_mapping->gp_reg_help_0, 0 ); libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_help_0, ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size)) ); libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_a, i_gp_reg_mapping->gp_reg_reduce_loop, 8, 0, i_gp_reg_mapping->gp_reg_help_0, 1 ); libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_b, i_gp_reg_mapping->gp_reg_reduce_loop, 8, 0, i_gp_reg_mapping->gp_reg_help_0, 0 ); libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_help_0, l_b_offset ); libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_b, i_gp_reg_mapping->gp_reg_reduce_loop, 8, 0, i_gp_reg_mapping->gp_reg_help_0, 1 ); if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2 || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C ) { libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_a_prefetch, i_gp_reg_mapping->gp_reg_reduce_loop, 8, 0, i_gp_reg_mapping->gp_reg_help_0, 0 ); libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_help_0, ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size)) ); libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_a_prefetch, i_gp_reg_mapping->gp_reg_reduce_loop, 8, 0, i_gp_reg_mapping->gp_reg_help_0, 1 ); } libxsmm_generator_gemm_footer_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config, i_xgemm_desc); libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop ); libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 ); } else { /* handle trans B */ int l_b_offset = 0; if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) > 0 ) { l_b_offset = i_n_blocking * i_micro_kernel_config->datatype_size; } else { l_b_offset = i_n_blocking * i_xgemm_desc->ldb * i_micro_kernel_config->datatype_size; } libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_b, l_b_offset ); libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_a, ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size)) ); if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2 || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C ) { libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_a_prefetch, ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size)) ); } } libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_cmp_instruction, i_gp_reg_mapping->gp_reg_nloop, i_n_done ); libxsmm_x86_instruction_jump_back_to_label( io_generated_code, i_micro_kernel_config->alu_jmp_instruction, io_loop_label_tracker ); } LIBXSMM_API_INTERN void libxsmm_generator_gemm_header_mloop( libxsmm_generated_code* io_generated_code, libxsmm_loop_label_tracker* io_loop_label_tracker, const libxsmm_gp_reg_mapping* i_gp_reg_mapping, const libxsmm_micro_kernel_config* i_micro_kernel_config, const unsigned int i_m_blocking ) { libxsmm_x86_instruction_register_jump_back_label( io_generated_code, io_loop_label_tracker ); libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_mloop, i_m_blocking ); } LIBXSMM_API_INTERN void libxsmm_generator_gemm_footer_mloop( libxsmm_generated_code* io_generated_code, libxsmm_loop_label_tracker* io_loop_label_tracker, const libxsmm_gp_reg_mapping* i_gp_reg_mapping, const libxsmm_micro_kernel_config* i_micro_kernel_config, const libxsmm_gemm_descriptor* i_xgemm_desc, const unsigned int i_m_blocking, const unsigned int i_m_done ) { /* advance C pointer */ if ( LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) { libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c, i_m_blocking*(i_micro_kernel_config->datatype_size/2) ); } else if ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) { libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c, i_m_blocking*(i_micro_kernel_config->datatype_size/4) ); } else { libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c, i_m_blocking*(i_micro_kernel_config->datatype_size) ); } /* C prefetch */ #if 0 if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_CL2 || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2CL2BL2_VIA_C ) { libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c_prefetch, i_m_blocking*(i_micro_kernel_config->datatype_size) ); } #endif /* B prefetch */ if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_BL2_VIA_C || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C_AHEAD ) { if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) == 0 ) { unsigned int l_type_scaling; if ( (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype )) || (LIBXSMM_GEMM_PRECISION_I16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype )) ) { l_type_scaling = 2; } else if ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { l_type_scaling = 4; } else { l_type_scaling = 1; } libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_b_prefetch, i_m_blocking*(i_micro_kernel_config->datatype_size/l_type_scaling) ); } } /* A prefetch */ if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2 || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C) { if (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_ADDRESS) { if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2 ) { libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 ); libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop ); libxsmm_generator_gemm_header_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config ); libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_a_prefetch, i_gp_reg_mapping->gp_reg_reduce_loop, 8, 0, i_gp_reg_mapping->gp_reg_help_0, 0 ); libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_help_0, ((i_xgemm_desc->k) * (i_micro_kernel_config->datatype_size) * (i_xgemm_desc->lda) ) - (i_m_blocking * (i_micro_kernel_config->datatype_size)) ); libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_a_prefetch, i_gp_reg_mapping->gp_reg_reduce_loop, 8, 0, i_gp_reg_mapping->gp_reg_help_0, 1 ); libxsmm_generator_gemm_footer_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config, i_xgemm_desc); libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop ); libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 ); } } else { libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_a_prefetch, ((i_xgemm_desc->k) * (i_micro_kernel_config->datatype_size) * (i_xgemm_desc->lda) ) - (i_m_blocking * (i_micro_kernel_config->datatype_size)) ); } } /* advance A pointer */ if (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_ADDRESS) { libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 ); libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop ); libxsmm_generator_gemm_header_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config ); libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_a, i_gp_reg_mapping->gp_reg_reduce_loop, 8, 0, i_gp_reg_mapping->gp_reg_help_0, 0 ); libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_help_0, ((i_xgemm_desc->k) * (i_micro_kernel_config->datatype_size) * (i_xgemm_desc->lda) ) - (i_m_blocking * (i_micro_kernel_config->datatype_size)) ); libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_a, i_gp_reg_mapping->gp_reg_reduce_loop, 8, 0, i_gp_reg_mapping->gp_reg_help_0, 1 ); libxsmm_generator_gemm_footer_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config, i_xgemm_desc); libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop ); libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 ); } else { libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_a, ((i_xgemm_desc->k) * (i_micro_kernel_config->datatype_size) * (i_xgemm_desc->lda) ) - (i_m_blocking * (i_micro_kernel_config->datatype_size)) ); } /* loop handling */ libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_cmp_instruction, i_gp_reg_mapping->gp_reg_mloop, i_m_done ); libxsmm_x86_instruction_jump_back_to_label( io_generated_code, i_micro_kernel_config->alu_jmp_instruction, io_loop_label_tracker ); } LIBXSMM_API_INTERN void libxsmm_generator_gemm_load_C( libxsmm_generated_code* io_generated_code, const libxsmm_gp_reg_mapping* i_gp_reg_mapping, const libxsmm_micro_kernel_config* i_micro_kernel_config, const libxsmm_gemm_descriptor* i_xgemm_desc, const unsigned int i_m_blocking, const unsigned int i_n_blocking ) { unsigned int l_m_blocking, l_vec_reg_acc_start; /* register blocking counter in n */ unsigned int l_n = 0; /* register blocking counter in m */ unsigned int l_m = 0; assert(0 < i_micro_kernel_config->vector_length); /* deriving register blocking from kernel config */ l_m_blocking = ( i_m_blocking % i_micro_kernel_config->vector_length == 0 ) ? i_m_blocking/i_micro_kernel_config->vector_length : (i_m_blocking/i_micro_kernel_config->vector_length)+1; /* start register of accumulator */ l_vec_reg_acc_start = i_micro_kernel_config->vector_reg_count - (i_n_blocking * l_m_blocking); #if !defined(NDEBUG) /* Do some test if it is possible to generate the requested code. This is not done in release mode and therefore bad things might happen.... HUAAH */ if (i_micro_kernel_config->instruction_set == LIBXSMM_X86_SSE3 || i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX || i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX2 ) { if ( (i_n_blocking > 3) || (i_n_blocking < 1) || (i_m_blocking < 1) ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK ); return; } } else if ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512_CORE ) { if ( (i_n_blocking > 30) || (i_n_blocking < 1) || (l_m_blocking != 1) ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK ); return; } } else if ( i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CORE ) { if ( (i_n_blocking > 30) || (i_n_blocking < 1) || (l_m_blocking < 1) || (l_m_blocking > 6) ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK ); return; } } else {} #if 0 if ( i_m_blocking % i_micro_kernel_config->vector_length != 0 ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_M_BLOCK ); return; } #endif #endif /*!defined(NDEBUG)*/ /* load C accumulator */ if (0 == (LIBXSMM_GEMM_FLAG_BETA_0 & i_xgemm_desc->flags)) { /* Beta=1 */ /* pure BF16 kernel */ if ( ( (i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CORE) && (i_micro_kernel_config->instruction_set <= LIBXSMM_X86_ALLFEAT) ) && ( (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) { /* we add when scaling during conversion to FP32 */ for ( l_n = 0; l_n < i_n_blocking; l_n++ ) { for ( l_m = 0; l_m < l_m_blocking; l_m++ ) { /* load 16 bit values into ymm portion of the register */ if ( (i_micro_kernel_config->use_masking_a_c != 0) && ( l_m == (l_m_blocking - 1) ) ) { libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VMOVDQU16, i_gp_reg_mapping->gp_reg_c, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2), 'z', 0, 2, 1, 0 ); } else { libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, i_micro_kernel_config->c_vmove_instruction, i_gp_reg_mapping->gp_reg_c, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2), 'y', 0, 0, 1, 0 ); } /* convert 16 bit values into 32 bit (integer convert) */ libxsmm_x86_instruction_vec_compute_convert( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VPMOVSXWD, i_micro_kernel_config->vector_name, 0, LIBXSMM_X86_VEC_REG_UNDEF, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), LIBXSMM_X86_VEC_REG_UNDEF); /* shift 16 bits to the left to generate valid FP32 numbers */ libxsmm_x86_instruction_vec_shuffle_reg(io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VPSLLD, i_micro_kernel_config->vector_name, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), LIBXSMM_X86_VEC_REG_UNDEF, 16); } } /* pure int8 kernel */ } else if ( ( (i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CORE) && (i_micro_kernel_config->instruction_set <= LIBXSMM_X86_ALLFEAT) ) && ( (LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) { /* we need to up convert int8 to int32 */ for ( l_n = 0; l_n < i_n_blocking; l_n++ ) { for ( l_m = 0; l_m < l_m_blocking; l_m++ ) { /* load 16 bit values into xmm portion of the register */ if ( (i_micro_kernel_config->use_masking_a_c != 0) && ( l_m == (l_m_blocking - 1) ) ) { libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VMOVDQU8, i_gp_reg_mapping->gp_reg_c, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/4), 'z', 0, 2, 1, 0 ); } else { libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, i_micro_kernel_config->c_vmove_instruction, i_gp_reg_mapping->gp_reg_c, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/4), 'x', 0, 0, 1, 0 ); } /* convert 8 bit values into 32 bit (integer convert) */ if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_C_UNSIGNED) != 0 ) { libxsmm_x86_instruction_vec_compute_convert( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VPMOVZXBD, i_micro_kernel_config->vector_name, 0, LIBXSMM_X86_VEC_REG_UNDEF, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), LIBXSMM_X86_VEC_REG_UNDEF); } else { libxsmm_x86_instruction_vec_compute_convert( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VPMOVSXBD, i_micro_kernel_config->vector_name, 0, LIBXSMM_X86_VEC_REG_UNDEF, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), LIBXSMM_X86_VEC_REG_UNDEF); } } } } else { /* adding to C, so let's load C */ for ( l_n = 0; l_n < i_n_blocking; l_n++ ) { for ( l_m = 0; l_m < l_m_blocking; l_m++ ) { /* we only mask the last m-blocked load */ libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, i_micro_kernel_config->c_vmove_instruction, i_gp_reg_mapping->gp_reg_c, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size), i_micro_kernel_config->vector_name, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), ( l_m == (l_m_blocking - 1) ) ? i_micro_kernel_config->use_masking_a_c : 0, 1, 0 ); } #if 0 if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_CL2 || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2CL2BL2_VIA_C ) { for (l_m = 0; l_m < l_m_blocking; l_m += l_m++ ) { libxsmm_x86_instruction_prefetch( io_generated_code, i_micro_kernel_config->prefetch_instruction, i_gp_reg_mapping->gp_reg_c_prefetch, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size)); } } #endif } } } else { /* overwriting C, so let's xout accumulator */ for ( l_n = 0; l_n < i_n_blocking; l_n++ ) { for ( l_m = 0; l_m < l_m_blocking; l_m++ ) { libxsmm_x86_instruction_vec_compute_reg( io_generated_code, i_micro_kernel_config->instruction_set, i_micro_kernel_config->vxor_instruction, i_micro_kernel_config->vector_name, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), l_vec_reg_acc_start + l_m + (l_m_blocking * l_n) ); } #if 0 if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_CL2 || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2CL2BL2_VIA_C ) { for (l_m = 0; l_m < l_m_blocking; l_m += l_m++ ) { libxsmm_x86_instruction_prefetch( io_generated_code, i_micro_kernel_config->prefetch_instruction, i_gp_reg_mapping->gp_reg_c_prefetch, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size)); } } #endif } } } LIBXSMM_API_INTERN void libxsmm_generator_gemm_store_C( libxsmm_generated_code* io_generated_code, const libxsmm_gp_reg_mapping* i_gp_reg_mapping, const libxsmm_micro_kernel_config* i_micro_kernel_config, const libxsmm_gemm_descriptor* i_xgemm_desc, const unsigned int i_m_blocking, const unsigned int i_n_blocking ) { /* deriving register blocking from kernel config */ unsigned int l_m_blocking = ( i_m_blocking % i_micro_kernel_config->vector_length == 0 ) ? i_m_blocking/i_micro_kernel_config->vector_length : (i_m_blocking/i_micro_kernel_config->vector_length)+1; /* register blocking counter in n */ unsigned int l_n = 0; /* register blocking counter in m */ unsigned int l_m = 0; /* start register of accumulator */ unsigned int l_vec_reg_acc_start = i_micro_kernel_config->vector_reg_count - (i_n_blocking * l_m_blocking); /* select store instruction */ unsigned int l_vstore = (LIBXSMM_GEMM_FLAG_ALIGN_C_NTS_HINT == (LIBXSMM_GEMM_FLAG_ALIGN_C_NTS_HINT & i_xgemm_desc->flags)) ? i_micro_kernel_config->c_vmove_nts_instruction : i_micro_kernel_config->c_vmove_instruction; /* @TODO fix this test */ #if !defined(NDEBUG) if (i_micro_kernel_config->instruction_set == LIBXSMM_X86_SSE3 || i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX || i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX2 ) { if ( (i_n_blocking > 3) || (i_n_blocking < 1) || (i_m_blocking < 1) ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK ); return; } } else if ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512_CORE ) { if ( (i_n_blocking > 30) || (i_n_blocking < 1) || (i_m_blocking != i_micro_kernel_config->vector_length) ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK ); return; } } else if ( i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CORE ) { if ( (i_n_blocking > 30) || (i_n_blocking < 1) || (l_m_blocking < 1) || (l_m_blocking > 6) ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK ); return; } } else {} #if 0 if ( i_m_blocking % i_micro_kernel_config->vector_length != 0 ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_M_BLOCK ); return; } #endif #endif if ( ( (i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_CORE) || (i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_CLX) ) && ( (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) { /* init stack with helper variables for SW-based RNE rounding */ /* push 0x7f800000 on the stack, naninf masking */ libxsmm_x86_instruction_alu_imm( io_generated_code, LIBXSMM_X86_INSTR_MOVQ, i_gp_reg_mapping->gp_reg_help_2, 0x7f800000); libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 ); /* push 0x00010000 on the stack, fixup masking */ libxsmm_x86_instruction_alu_imm( io_generated_code, LIBXSMM_X86_INSTR_MOVQ, i_gp_reg_mapping->gp_reg_help_2, 0x00010000); libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 ); /* push 0x00007fff on the stack, rneadd */ libxsmm_x86_instruction_alu_imm( io_generated_code, LIBXSMM_X86_INSTR_MOVQ, i_gp_reg_mapping->gp_reg_help_2, 0x00007fff); libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 ); /* push 0x00000001 on the stack, fixup */ libxsmm_x86_instruction_alu_imm( io_generated_code, LIBXSMM_X86_INSTR_MOVQ, i_gp_reg_mapping->gp_reg_help_2, 0x00000001); libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 ); /* storing downconverted and rounded C accumulator */ for ( l_n = 0; l_n < i_n_blocking; l_n++ ) { for ( l_m = 0; l_m < l_m_blocking; l_m++ ) { unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n); /* and with naninf */ libxsmm_x86_instruction_vec_compute_mem( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VPANDD, 1, LIBXSMM_X86_GP_REG_RSP, LIBXSMM_X86_GP_REG_UNDEF, 0, 24, i_micro_kernel_config->vector_name, reg_X, 0 ); /* and with fixup */ libxsmm_x86_instruction_vec_compute_mem( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VPANDD, 1, LIBXSMM_X86_GP_REG_RSP, LIBXSMM_X86_GP_REG_UNDEF, 0, 16, i_micro_kernel_config->vector_name, reg_X, 1 ); /* compute naninf mask k7 */ libxsmm_x86_instruction_vec_compute_mem_mask( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VPCMPD, 1, LIBXSMM_X86_GP_REG_RSP, LIBXSMM_X86_GP_REG_UNDEF, 0, 24, i_micro_kernel_config->vector_name, 0, LIBXSMM_X86_VEC_REG_UNDEF, 4, 7, 0 ); /* compute fixup mask k6 */ libxsmm_x86_instruction_vec_compute_mem_mask( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VPCMPD, 1, LIBXSMM_X86_GP_REG_RSP, LIBXSMM_X86_GP_REG_UNDEF, 0, 16, i_micro_kernel_config->vector_name, 1, LIBXSMM_X86_VEC_REG_UNDEF, 0, 6, 0 ); /* load rneadd */ libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, LIBXSMM_X86_GP_REG_RSP, LIBXSMM_X86_GP_REG_UNDEF, 0, 8, i_micro_kernel_config->vector_name, 0, 0, 1, 0 ); /* load fixup */ libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, LIBXSMM_X86_GP_REG_RSP, LIBXSMM_X86_GP_REG_UNDEF, 0, 0, i_micro_kernel_config->vector_name, 1, 0, 1, 0 ); /* compute fixup */ libxsmm_x86_instruction_vec_compute_reg_mask( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VPADDD, i_micro_kernel_config->vector_name, 1, 0, 0, LIBXSMM_X86_IMM_UNDEF, 6, 0 ); /* compute fixup */ libxsmm_x86_instruction_vec_compute_reg_mask( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VPADDD, i_micro_kernel_config->vector_name, 0, reg_X, reg_X, LIBXSMM_X86_IMM_UNDEF, 7, 0 ); /* shift FP32 by 16bit to right */ libxsmm_x86_instruction_vec_shuffle_reg(io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VPSRAD, i_micro_kernel_config->vector_name, reg_X, reg_X, LIBXSMM_X86_VEC_REG_UNDEF, 16); /* shift FP32 by 16bit to right */ libxsmm_x86_instruction_vec_compute_convert( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VPMOVDW, i_micro_kernel_config->vector_name, reg_X, LIBXSMM_X86_VEC_REG_UNDEF, 0, LIBXSMM_X86_VEC_REG_UNDEF); /* store 16 bit values into ymm portion of the register */ if ( (i_micro_kernel_config->use_masking_a_c != 0) && ( l_m == (l_m_blocking - 1) ) ) { libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VMOVDQU16, i_gp_reg_mapping->gp_reg_c, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2), 'z', 0, 2, 0, 1 ); } else { libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, l_vstore, i_gp_reg_mapping->gp_reg_c, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2), 'y', 0, 0, 0, 1 ); } } } /* clean stack and restore help5 */ libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 ); libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 ); libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 ); libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 ); } else if ( ( (i_micro_kernel_config->instruction_set <= LIBXSMM_X86_ALLFEAT) && (i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CPX) ) && ( (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) { /* storing downconverted and rounded C accumulator */ for ( l_n = 0; l_n < i_n_blocking; l_n++ ) { unsigned int l_m_2_blocking = (l_m_blocking/2)*2; l_m = 0; if ( i_micro_kernel_config->use_masking_a_c != 0 ) { for ( l_m = 0 ; l_m < l_m_blocking; l_m++ ) { unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n); libxsmm_x86_instruction_vec_compute_convert( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VCVTNEPS2BF16, i_micro_kernel_config->vector_name, reg_X, LIBXSMM_X86_VEC_REG_UNDEF, 0, 0); /* store 16 bit values into ymm portion of the register */ if ( l_m == (l_m_blocking - 1) ) { libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VMOVDQU16, i_gp_reg_mapping->gp_reg_c, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2), 'z', 0, 2, 0, 1 ); } else { libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, l_vstore, i_gp_reg_mapping->gp_reg_c, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2), 'y', 0, 0, 0, 1 ); } } } else { for (; l_m < l_m_2_blocking; l_m+=2 ) { unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n); unsigned int reg_X2 = l_vec_reg_acc_start + l_m+1 + (l_m_blocking * l_n); libxsmm_x86_instruction_vec_compute_convert( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VCVTNE2PS2BF16, i_micro_kernel_config->vector_name, reg_X, reg_X2, 0, 0); libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, l_vstore, i_gp_reg_mapping->gp_reg_c, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2), 'z', 0, 0, 0, 1 ); } for (; l_m < l_m_blocking; l_m++ ) { unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n); libxsmm_x86_instruction_vec_compute_convert( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VCVTNEPS2BF16, i_micro_kernel_config->vector_name, reg_X, LIBXSMM_X86_VEC_REG_UNDEF, 0, 0); libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, l_vstore, i_gp_reg_mapping->gp_reg_c, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2), 'y', 0, 0, 0, 1 ); } } } } else if ( ( (i_micro_kernel_config->instruction_set <= LIBXSMM_X86_ALLFEAT) || (i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CORE) ) && ( (LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) { /* pick the right instrucitons */ unsigned int inst_f32_i32 = ( ( i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_C_UNSIGNED ) != 0 ) ? LIBXSMM_X86_INSTR_VCVTPS2UDQ : LIBXSMM_X86_INSTR_VCVTPS2DQ; unsigned int inst_i32_i8 = ( ( i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_C_UNSIGNED ) != 0 ) ? LIBXSMM_X86_INSTR_VPMOVUSDB : LIBXSMM_X86_INSTR_VPMOVSDB; /* there are case where we need to load the scaling factor's address from the stack argument list */ if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_OFFSET) != 0 ) { libxsmm_x86_instruction_load_arg_to_reg( io_generated_code, 0, i_gp_reg_mapping->gp_reg_scf ); } /* loading scf into register 3 */ libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, i_gp_reg_mapping->gp_reg_scf, LIBXSMM_X86_GP_REG_UNDEF, 0, 0, i_micro_kernel_config->vector_name, 3, 0, 1, 0 ); /* Zero out register 0 to perform relu */ libxsmm_x86_instruction_vec_compute_reg( io_generated_code, i_micro_kernel_config->instruction_set, i_micro_kernel_config->vxor_instruction, i_micro_kernel_config->vector_name, 0, 0, 0); /* storing downconverted and rounded C accumulator */ for ( l_n = 0; l_n < i_n_blocking; l_n++ ) { for ( l_m = 0; l_m < l_m_blocking; l_m++ ) { unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n); /* Convert result to F32 */ libxsmm_x86_instruction_vec_compute_reg( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VCVTDQ2PS, i_micro_kernel_config->vector_name, reg_X, reg_X, LIBXSMM_X86_VEC_REG_UNDEF); /* Multiply with scaling factor */ libxsmm_x86_instruction_vec_compute_reg( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VMULPS, i_micro_kernel_config->vector_name, reg_X, 3, reg_X ); /* Perform RELU */ libxsmm_x86_instruction_vec_compute_reg( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VMAXPS, i_micro_kernel_config->vector_name, reg_X, 0, reg_X); /* Round result to int32 */ libxsmm_x86_instruction_vec_compute_convert( io_generated_code, i_micro_kernel_config->instruction_set, inst_f32_i32, i_micro_kernel_config->vector_name, reg_X, LIBXSMM_X86_VEC_REG_UNDEF, reg_X, 0); /* down-convert to int8 */ libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, inst_i32_i8, i_gp_reg_mapping->gp_reg_c, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/4), i_micro_kernel_config->vector_name, reg_X, ( ( l_m == (l_m_blocking - 1)) && ( i_micro_kernel_config->use_masking_a_c != 0 ) ) ? 2 : 0, 0, 1 ); } } } else { /* storing C accumulator */ for ( l_n = 0; l_n < i_n_blocking; l_n++ ) { for ( l_m = 0; l_m < l_m_blocking; l_m++ ) { libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, l_vstore, i_gp_reg_mapping->gp_reg_c, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size), i_micro_kernel_config->vector_name, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), ( l_m == (l_m_blocking - 1) ) ? i_micro_kernel_config->use_masking_a_c : 0, 0, 1 ); } if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_BL2_VIA_C || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C_AHEAD ) { if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) == 0 ) { /* determining how many prefetches we need in M direction as we just need one prefetch per cache line */ unsigned int l_m_advance = 64 / ((i_micro_kernel_config->vector_length) * (i_micro_kernel_config->datatype_size)); /* 64: hardcoded cache line length */ for (l_m = 0; l_m < l_m_blocking; l_m += l_m_advance ) { libxsmm_x86_instruction_prefetch( io_generated_code, i_micro_kernel_config->prefetch_instruction, i_gp_reg_mapping->gp_reg_b_prefetch, LIBXSMM_X86_GP_REG_UNDEF, 0, ((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size)); } } } } } } LIBXSMM_API_INTERN void libxsmm_generator_gemm_initialize_avx512_mask( libxsmm_generated_code* io_generated_code, const unsigned int i_gp_reg_tmp, const libxsmm_gemm_descriptor* i_xgemm_desc, const unsigned int i_mask_count ) { unsigned int l_mask; /* init full mask */ if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) { l_mask = 0xff; } else { l_mask = 0xffff; } /* shift right by "inverse" remainder */ l_mask = l_mask >> i_mask_count; /* move mask to GP register */ libxsmm_x86_instruction_alu_imm( io_generated_code, LIBXSMM_X86_INSTR_MOVQ, i_gp_reg_tmp, l_mask ); if ( ( io_generated_code->arch >= LIBXSMM_X86_AVX512 ) && ( io_generated_code->arch <= LIBXSMM_X86_ALLFEAT ) ) { libxsmm_x86_instruction_mask_move( io_generated_code, LIBXSMM_X86_INSTR_KMOVW, i_gp_reg_tmp, LIBXSMM_X86_AVX512_MASK, 0 ); if ( ( LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && ( LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) { libxsmm_x86_instruction_mask_move( io_generated_code, LIBXSMM_X86_INSTR_KMOVD, i_gp_reg_tmp, 2, 0 ); } else if ( ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) { libxsmm_x86_instruction_mask_move( io_generated_code, LIBXSMM_X86_INSTR_KMOVQ, i_gp_reg_tmp, 2, 0 ); } else { /* no addtional mask is needed */ } } else { /* shouldn't happen */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_ARCH ); return; } }
camera.h
/* * Copyright (C) 2019, unclearness * All rights reserved. */ /* * right-handed coordinate system * z:forward, y:down, x:right * same to OpenCV */ #pragma once #include <string> #include <utility> #include <vector> #include "ugu/common.h" namespace ugu { // interface (pure abstract base class with no state or defined methods) for // camera class Camera { public: virtual ~Camera() {} virtual int width() const = 0; virtual int height() const = 0; virtual const Eigen::Affine3d& c2w() const = 0; virtual const Eigen::Affine3d& w2c() const = 0; virtual void set_size(int width, int height) = 0; virtual void set_c2w(const Eigen::Affine3d& c2w) = 0; // camera -> image conversion virtual void Project(const Eigen::Vector3f& camera_p, Eigen::Vector3f* image_p) const = 0; virtual void Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p) const = 0; virtual void Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p, float* d) const = 0; // image -> camera conversion // need depth value as input virtual void Unproject(const Eigen::Vector3f& image_p, Eigen::Vector3f* camera_p) const = 0; virtual void Unproject(const Eigen::Vector2f& image_p, float d, Eigen::Vector3f* camera_p) const = 0; // position emmiting ray virtual void org_ray_c(float x, float y, Eigen::Vector3f* org) const = 0; virtual void org_ray_w(float x, float y, Eigen::Vector3f* org) const = 0; virtual void org_ray_c(int x, int y, Eigen::Vector3f* org) const = 0; virtual void org_ray_w(int x, int y, Eigen::Vector3f* org) const = 0; // ray direction virtual void ray_c( float x, float y, Eigen::Vector3f* dir) const = 0; // ray in camera coordinate virtual void ray_w( float x, float y, Eigen::Vector3f* dir) const = 0; // ray in world coordinate virtual void ray_c(int x, int y, Eigen::Vector3f* dir) const = 0; virtual void ray_w(int x, int y, Eigen::Vector3f* dir) const = 0; }; // Pinhole camera model with pixel-scale principal point and focal length // Widely used in computer vision community as perspective camera model // Valid only if FoV is much less than 180 deg. class PinholeCamera : public Camera { protected: int width_; int height_; Eigen::Affine3d c2w_; // camera -> world, sometimes called as "pose" Eigen::Affine3d w2c_; Eigen::Matrix3f c2w_R_f_; Eigen::Vector3f c2w_t_f_; Eigen::Vector3f x_direc_, y_direc_, z_direc_; Eigen::Matrix3f w2c_R_f_; Eigen::Vector3f w2c_t_f_; Eigen::Vector2f principal_point_; Eigen::Vector2f focal_length_; mutable std::vector<Eigen::Vector3f> org_ray_c_table_; mutable std::vector<Eigen::Vector3f> org_ray_w_table_; mutable std::vector<Eigen::Vector3f> ray_c_table_; mutable std::vector<Eigen::Vector3f> ray_w_table_; mutable bool need_init_ray_table_ = true; void InitRayTable() const; public: PinholeCamera(); ~PinholeCamera(); PinholeCamera(int width, int height, float fov_y_deg); PinholeCamera(int width, int height, const Eigen::Affine3d& c2w, float fov_y_deg); PinholeCamera(int width, int height, const Eigen::Affine3d& c2w, const Eigen::Vector2f& principal_point, const Eigen::Vector2f& focal_length); int width() const override; int height() const override; const Eigen::Affine3d& c2w() const override; const Eigen::Affine3d& w2c() const override; void set_size(int width, int height) override; void set_c2w(const Eigen::Affine3d& c2w) override; // FoV (Field of View) in degree interface is provided for convenience float fov_x() const; float fov_y() const; void set_fov_x(float fov_x_deg); void set_fov_y(float fov_y_deg); // pixel-scale principal point and focal length const Eigen::Vector2f& principal_point() const; const Eigen::Vector2f& focal_length() const; void set_principal_point(const Eigen::Vector2f& principal_point); void set_focal_length(const Eigen::Vector2f& focal_length); void Project(const Eigen::Vector3f& camera_p, Eigen::Vector3f* image_p) const override; void Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p) const override; void Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p, float* d) const override; void Unproject(const Eigen::Vector3f& image_p, Eigen::Vector3f* camera_p) const override; void Unproject(const Eigen::Vector2f& image_p, float d, Eigen::Vector3f* camera_p) const override; void org_ray_c(float x, float y, Eigen::Vector3f* org) const override; void org_ray_w(float x, float y, Eigen::Vector3f* org) const override; void org_ray_c(int x, int y, Eigen::Vector3f* org) const override; void org_ray_w(int x, int y, Eigen::Vector3f* org) const override; void ray_c(float x, float y, Eigen::Vector3f* dir) const override; void ray_w(float x, float y, Eigen::Vector3f* dir) const override; void ray_c(int x, int y, Eigen::Vector3f* dir) const override; void ray_w(int x, int y, Eigen::Vector3f* dir) const override; }; // PinholeCamera with support of OpenCV style distortion/undistortion class OpenCvCamera : public PinholeCamera { private: float k1_, k2_, p1_, p2_, k3_, k4_, k5_, k6_; public: void distortion_coeffs(float* k1, float* k2, float* p1, float* p2, float* k3 = nullptr, float* k4 = nullptr, float* k5 = nullptr, float* k6 = nullptr) const; void set_distortion_coeffs(float k1, float k2, float p1, float p2, float k3 = 0.0f, float k4 = 0.0f, float k5 = 0.0f, float k6 = 0.0f); // To project 3D points to distorted image coordinate void Project(const Eigen::Vector3f& camera_p, Eigen::Vector3f* image_p) const override; void Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p) const override; void Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p, float* d) const override; // To recover 3D points in camera coordinate from distorted depth image void Unproject(const Eigen::Vector3f& image_p, Eigen::Vector3f* camera_p) const override; void Unproject(const Eigen::Vector2f& image_p, float d, Eigen::Vector3f* camera_p) const override; }; // Orthographic/orthogonal projection camera with no perspective // Image coordinate is translated camera coordinate // Different from pinhole camera in particular x and y coordinate in image class OrthoCamera : public Camera { int width_; int height_; Eigen::Affine3d c2w_; // camera -> world, sometimes called as "pose" Eigen::Affine3d w2c_; Eigen::Matrix3f c2w_R_f_; Eigen::Vector3f c2w_t_f_; Eigen::Vector3f x_direc_, y_direc_, z_direc_; Eigen::Matrix3f w2c_R_f_; Eigen::Vector3f w2c_t_f_; std::vector<Eigen::Vector3f> org_ray_c_table_; std::vector<Eigen::Vector3f> org_ray_w_table_; std::vector<Eigen::Vector3f> ray_c_table_; std::vector<Eigen::Vector3f> ray_w_table_; void InitRayTable(); void set_size_no_raytable_update(int width, int height); void set_c2w_no_raytable_update(const Eigen::Affine3d& c2w); public: OrthoCamera(); ~OrthoCamera(); OrthoCamera(int width, int height); OrthoCamera(int width, int height, const Eigen::Affine3d& c2w); int width() const override; int height() const override; const Eigen::Affine3d& c2w() const override; const Eigen::Affine3d& w2c() const override; void set_size(int width, int height) override; void set_c2w(const Eigen::Affine3d& c2w) override; void Project(const Eigen::Vector3f& camera_p, Eigen::Vector3f* image_p) const override; void Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p) const override; void Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p, float* d) const override; void Unproject(const Eigen::Vector3f& image_p, Eigen::Vector3f* camera_p) const override; void Unproject(const Eigen::Vector2f& image_p, float d, Eigen::Vector3f* camera_p) const override; void org_ray_c(float x, float y, Eigen::Vector3f* org) const override; void org_ray_w(float x, float y, Eigen::Vector3f* org) const override; void org_ray_c(int x, int y, Eigen::Vector3f* org) const override; void org_ray_w(int x, int y, Eigen::Vector3f* org) const override; void ray_c(float x, float y, Eigen::Vector3f* dir) const override; void ray_w(float x, float y, Eigen::Vector3f* dir) const override; void ray_c(int x, int y, Eigen::Vector3f* dir) const override; void ray_w(int x, int y, Eigen::Vector3f* dir) const override; }; void WriteTumFormat(const std::vector<Eigen::Affine3d>& poses, const std::string& path); bool LoadTumFormat(const std::string& path, std::vector<Eigen::Affine3d>* poses); bool LoadTumFormat(const std::string& path, std::vector<std::pair<int, Eigen::Affine3d>>* poses); inline PinholeCamera::PinholeCamera() : principal_point_(-1, -1), focal_length_(-1, -1) { set_size(-1, -1); set_c2w(Eigen::Affine3d::Identity()); } inline PinholeCamera::~PinholeCamera() {} inline int PinholeCamera::width() const { return width_; } inline int PinholeCamera::height() const { return height_; } inline const Eigen::Affine3d& PinholeCamera::c2w() const { return c2w_; } inline const Eigen::Affine3d& PinholeCamera::w2c() const { return w2c_; } inline PinholeCamera::PinholeCamera(int width, int height, float fov_y_deg) { set_size(width, height); principal_point_[0] = width_ * 0.5f - 0.5f; principal_point_[1] = height_ * 0.5f - 0.5f; set_fov_y(fov_y_deg); set_c2w(Eigen::Affine3d::Identity()); need_init_ray_table_ = true; } inline PinholeCamera::PinholeCamera(int width, int height, const Eigen::Affine3d& c2w, float fov_y_deg) { set_size(width, height); set_c2w(c2w); principal_point_[0] = width_ * 0.5f - 0.5f; principal_point_[1] = height_ * 0.5f - 0.5f; set_fov_y(fov_y_deg); need_init_ray_table_ = true; } inline PinholeCamera::PinholeCamera(int width, int height, const Eigen::Affine3d& c2w, const Eigen::Vector2f& principal_point, const Eigen::Vector2f& focal_length) : principal_point_(principal_point), focal_length_(focal_length) { set_size(width, height); set_c2w(c2w); need_init_ray_table_ = true; } inline void PinholeCamera::set_size(int width, int height) { width_ = width; height_ = height; need_init_ray_table_ = true; } inline void PinholeCamera::set_c2w(const Eigen::Affine3d& c2w) { c2w_ = c2w; w2c_ = c2w_.inverse(); c2w_R_f_ = c2w_.matrix().block<3, 3>(0, 0).cast<float>(); c2w_t_f_ = c2w_.matrix().block<3, 1>(0, 3).cast<float>(); x_direc_ = c2w_.matrix().block<3, 3>(0, 0).col(0).cast<float>(); y_direc_ = c2w_.matrix().block<3, 3>(0, 0).col(1).cast<float>(); z_direc_ = c2w_.matrix().block<3, 3>(0, 0).col(2).cast<float>(); w2c_R_f_ = w2c_.matrix().block<3, 3>(0, 0).cast<float>(); w2c_t_f_ = w2c_.matrix().block<3, 1>(0, 3).cast<float>(); need_init_ray_table_ = true; } inline float PinholeCamera::fov_x() const { return degrees<float>(2 * std::atan(width_ * 0.5f / focal_length_[0])); } inline float PinholeCamera::fov_y() const { return degrees<float>(2 * std::atan(height_ * 0.5f / focal_length_[1])); } inline const Eigen::Vector2f& PinholeCamera::principal_point() const { return principal_point_; } inline const Eigen::Vector2f& PinholeCamera::focal_length() const { return focal_length_; } inline void PinholeCamera::set_principal_point( const Eigen::Vector2f& principal_point) { principal_point_ = principal_point; need_init_ray_table_ = true; } inline void PinholeCamera::set_focal_length( const Eigen::Vector2f& focal_length) { focal_length_ = focal_length; need_init_ray_table_ = true; } inline void PinholeCamera::set_fov_x(float fov_x_deg) { // same focal length per pixel for x and y focal_length_[0] = width_ * 0.5f / static_cast<float>(std::tan(radians<float>(fov_x_deg) * 0.5)); focal_length_[1] = focal_length_[0]; need_init_ray_table_ = true; } inline void PinholeCamera::set_fov_y(float fov_y_deg) { // same focal length per pixel for x and y focal_length_[1] = height_ * 0.5f / static_cast<float>(std::tan(radians<float>(fov_y_deg) * 0.5)); focal_length_[0] = focal_length_[1]; need_init_ray_table_ = true; } inline void PinholeCamera::Project(const Eigen::Vector3f& camera_p, Eigen::Vector3f* image_p) const { (*image_p)[0] = focal_length_[0] / camera_p[2] * camera_p[0] + principal_point_[0]; (*image_p)[1] = focal_length_[1] / camera_p[2] * camera_p[1] + principal_point_[1]; (*image_p)[2] = camera_p[2]; } inline void PinholeCamera::Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p) const { (*image_p)[0] = focal_length_[0] / camera_p[2] * camera_p[0] + principal_point_[0]; (*image_p)[1] = focal_length_[1] / camera_p[2] * camera_p[1] + principal_point_[1]; } inline void PinholeCamera::Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p, float* d) const { (*image_p)[0] = focal_length_[0] / camera_p[2] * camera_p[0] + principal_point_[0]; (*image_p)[1] = focal_length_[1] / camera_p[2] * camera_p[1] + principal_point_[1]; *d = camera_p[2]; } inline void PinholeCamera::Unproject(const Eigen::Vector3f& image_p, Eigen::Vector3f* camera_p) const { (*camera_p)[0] = (image_p[0] - principal_point_[0]) * image_p[2] / focal_length_[0]; (*camera_p)[1] = (image_p[1] - principal_point_[1]) * image_p[2] / focal_length_[1]; (*camera_p)[2] = image_p[2]; } inline void PinholeCamera::Unproject(const Eigen::Vector2f& image_p, float d, Eigen::Vector3f* camera_p) const { (*camera_p)[0] = (image_p[0] - principal_point_[0]) * d / focal_length_[0]; (*camera_p)[1] = (image_p[1] - principal_point_[1]) * d / focal_length_[1]; (*camera_p)[2] = d; } inline void PinholeCamera::org_ray_c(float x, float y, Eigen::Vector3f* org) const { (void)x; (void)y; (*org)[0] = 0.0f; (*org)[1] = 0.0f; (*org)[2] = 0.0f; } inline void PinholeCamera::org_ray_w(float x, float y, Eigen::Vector3f* org) const { (void)x; (void)y; *org = c2w_t_f_; } inline void PinholeCamera::ray_c(float x, float y, Eigen::Vector3f* dir) const { (*dir)[0] = (x - principal_point_[0]) / focal_length_[0]; (*dir)[1] = (y - principal_point_[1]) / focal_length_[1]; (*dir)[2] = 1.0f; dir->normalize(); } inline void PinholeCamera::ray_w(float x, float y, Eigen::Vector3f* dir) const { ray_c(x, y, dir); *dir = c2w_R_f_ * *dir; } inline void PinholeCamera::org_ray_c(int x, int y, Eigen::Vector3f* org) const { if (need_init_ray_table_) { InitRayTable(); need_init_ray_table_ = false; } *org = org_ray_c_table_[y * width_ + x]; } inline void PinholeCamera::org_ray_w(int x, int y, Eigen::Vector3f* org) const { if (need_init_ray_table_) { InitRayTable(); need_init_ray_table_ = false; } *org = org_ray_w_table_[y * width_ + x]; } inline void PinholeCamera::ray_c(int x, int y, Eigen::Vector3f* dir) const { if (need_init_ray_table_) { InitRayTable(); need_init_ray_table_ = false; } *dir = ray_c_table_[y * width_ + x]; } inline void PinholeCamera::ray_w(int x, int y, Eigen::Vector3f* dir) const { if (need_init_ray_table_) { InitRayTable(); need_init_ray_table_ = false; } *dir = ray_w_table_[y * width_ + x]; } inline void PinholeCamera::InitRayTable() const { org_ray_c_table_.resize(width_ * height_); org_ray_w_table_.resize(width_ * height_); ray_c_table_.resize(width_ * height_); ray_w_table_.resize(width_ * height_); #if defined(_OPENMP) && defined(UGU_USE_OPENMP) #pragma omp parallel for schedule(dynamic, 1) #endif for (int y = 0; y < height_; y++) { for (int x = 0; x < width_; x++) { org_ray_c(static_cast<float>(x), static_cast<float>(y), &org_ray_c_table_[y * width_ + x]); org_ray_w(static_cast<float>(x), static_cast<float>(y), &org_ray_w_table_[y * width_ + x]); ray_c(static_cast<float>(x), static_cast<float>(y), &ray_c_table_[y * width_ + x]); ray_w(static_cast<float>(x), static_cast<float>(y), &ray_w_table_[y * width_ + x]); } } } inline void OpenCvCamera::distortion_coeffs(float* k1, float* k2, float* p1, float* p2, float* k3, float* k4, float* k5, float* k6) const { *k1 = k1_; *k2 = k2_; *p1 = p1_; *p2 = p2_; if (k3 != nullptr) { *k3 = k3_; } if (k4 != nullptr) { *k4 = k4_; } if (k5 != nullptr) { *k5 = k5_; } if (k6 != nullptr) { *k6 = k6_; } } inline void OpenCvCamera::set_distortion_coeffs(float k1, float k2, float p1, float p2, float k3, float k4, float k5, float k6) { k1_ = k1; k2_ = k2; p1_ = p1; p2_ = p2; k3_ = k3; k4_ = k4; k5_ = k5; k6_ = k6; } inline void OpenCvCamera::Project(const Eigen::Vector3f& camera_p, Eigen::Vector3f* image_p) const { (void)camera_p; (void)image_p; LOGE("HAVE NOT IMPLEMENTED\n"); } inline void OpenCvCamera::Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p) const { (void)camera_p; (void)image_p; LOGE("HAVE NOT IMPLEMENTED\n"); } inline void OpenCvCamera::Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p, float* d) const { (void)camera_p; (void)image_p; (void)d; LOGE("HAVE NOT IMPLEMENTED\n"); } // To recover 3D points in camera coordinate from distorted depth image inline void OpenCvCamera::Unproject(const Eigen::Vector3f& image_p, Eigen::Vector3f* camera_p) const { Eigen::Vector3f undistorted_image_p = image_p; UndistortPixelOpencv(&undistorted_image_p.x(), &undistorted_image_p.y(), focal_length_.x(), focal_length_.y(), principal_point_.x(), principal_point_.y(), k1_, k2_, p1_, p2_, k3_, k4_, k5_, k6_); PinholeCamera::Unproject(undistorted_image_p, camera_p); } inline void OpenCvCamera::Unproject(const Eigen::Vector2f& image_p, float d, Eigen::Vector3f* camera_p) const { Eigen::Vector2f undistorted_image_p = image_p; UndistortPixelOpencv(&undistorted_image_p.x(), &undistorted_image_p.y(), focal_length_.x(), focal_length_.y(), principal_point_.x(), principal_point_.y(), k1_, k2_, p1_, p2_, k3_, k4_, k5_, k6_); PinholeCamera::Unproject(undistorted_image_p, d, camera_p); } inline OrthoCamera::OrthoCamera() { set_size_no_raytable_update(-1, -1); set_c2w_no_raytable_update(Eigen::Affine3d::Identity()); } inline OrthoCamera::~OrthoCamera() {} inline OrthoCamera::OrthoCamera(int width, int height) { set_size_no_raytable_update(width, height); set_c2w_no_raytable_update(Eigen::Affine3d::Identity()); InitRayTable(); } inline OrthoCamera::OrthoCamera(int width, int height, const Eigen::Affine3d& c2w) { set_size_no_raytable_update(width, height); set_c2w_no_raytable_update(c2w); InitRayTable(); } inline void OrthoCamera::set_size_no_raytable_update(int width, int height) { width_ = width; height_ = height; } inline void OrthoCamera::set_c2w_no_raytable_update( const Eigen::Affine3d& c2w) { c2w_ = c2w; w2c_ = c2w_.inverse(); c2w_R_f_ = c2w_.matrix().block<3, 3>(0, 0).cast<float>(); c2w_t_f_ = c2w_.matrix().block<3, 1>(0, 3).cast<float>(); x_direc_ = c2w_.matrix().block<3, 3>(0, 0).col(0).cast<float>(); y_direc_ = c2w_.matrix().block<3, 3>(0, 0).col(1).cast<float>(); z_direc_ = c2w_.matrix().block<3, 3>(0, 0).col(2).cast<float>(); w2c_R_f_ = w2c_.matrix().block<3, 3>(0, 0).cast<float>(); w2c_t_f_ = w2c_.matrix().block<3, 1>(0, 3).cast<float>(); } inline int OrthoCamera::width() const { return width_; } inline int OrthoCamera::height() const { return height_; } inline const Eigen::Affine3d& OrthoCamera::c2w() const { return c2w_; } inline const Eigen::Affine3d& OrthoCamera::w2c() const { return w2c_; } inline void OrthoCamera::set_size(int width, int height) { set_size_no_raytable_update(width, height); InitRayTable(); } inline void OrthoCamera::set_c2w(const Eigen::Affine3d& c2w) { set_c2w_no_raytable_update(c2w); InitRayTable(); } inline void OrthoCamera::Project(const Eigen::Vector3f& camera_p, Eigen::Vector3f* image_p) const { *image_p = camera_p; } inline void OrthoCamera::Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p) const { (*image_p)[0] = camera_p[0]; (*image_p)[1] = camera_p[1]; } inline void OrthoCamera::Project(const Eigen::Vector3f& camera_p, Eigen::Vector2f* image_p, float* d) const { (*image_p)[0] = camera_p[0]; (*image_p)[1] = camera_p[1]; *d = camera_p[2]; } inline void OrthoCamera::Unproject(const Eigen::Vector3f& image_p, Eigen::Vector3f* camera_p) const { *camera_p = image_p; } inline void OrthoCamera::Unproject(const Eigen::Vector2f& image_p, float d, Eigen::Vector3f* camera_p) const { (*camera_p)[0] = image_p[0]; (*camera_p)[1] = image_p[1]; (*camera_p)[2] = d; } inline void OrthoCamera::org_ray_c(float x, float y, Eigen::Vector3f* org) const { (*org)[0] = x - width_ / 2; (*org)[1] = y - height_ / 2; (*org)[2] = 0.0f; } inline void OrthoCamera::org_ray_w(float x, float y, Eigen::Vector3f* org) const { *org = c2w_t_f_; Eigen::Vector3f offset_x = (x - width_ * 0.5f) * x_direc_; Eigen::Vector3f offset_y = (y - height_ * 0.5f) * y_direc_; *org += offset_x; *org += offset_y; } inline void OrthoCamera::ray_c(float x, float y, Eigen::Vector3f* dir) const { (void)x; (void)y; // parallell ray along with z axis (*dir)[0] = 0.0f; (*dir)[1] = 0.0f; (*dir)[2] = 1.0f; } inline void OrthoCamera::ray_w(float x, float y, Eigen::Vector3f* dir) const { (void)x; (void)y; // extract z direction of camera pose *dir = z_direc_; } inline void OrthoCamera::org_ray_c(int x, int y, Eigen::Vector3f* org) const { *org = org_ray_c_table_[y * width_ + x]; } inline void OrthoCamera::org_ray_w(int x, int y, Eigen::Vector3f* org) const { *org = org_ray_w_table_[y * width_ + x]; } inline void OrthoCamera::ray_c(int x, int y, Eigen::Vector3f* dir) const { *dir = ray_c_table_[y * width_ + x]; } inline void OrthoCamera::ray_w(int x, int y, Eigen::Vector3f* dir) const { *dir = ray_w_table_[y * width_ + x]; } inline void OrthoCamera::InitRayTable() { org_ray_c_table_.resize(width_ * height_); org_ray_w_table_.resize(width_ * height_); ray_c_table_.resize(width_ * height_); ray_w_table_.resize(width_ * height_); #if defined(_OPENMP) && defined(UGU_USE_OPENMP) #pragma omp parallel for schedule(dynamic, 1) #endif for (int y = 0; y < height_; y++) { for (int x = 0; x < width_; x++) { org_ray_c(static_cast<float>(x), static_cast<float>(y), &org_ray_c_table_[y * width_ + x]); org_ray_w(static_cast<float>(x), static_cast<float>(y), &org_ray_w_table_[y * width_ + x]); ray_c(static_cast<float>(x), static_cast<float>(y), &ray_c_table_[y * width_ + x]); ray_w(static_cast<float>(x), static_cast<float>(y), &ray_w_table_[y * width_ + x]); } } } } // namespace ugu
KMeans.h
#pragma once #include "headers/Matrix.h" #include "ClosestCentroids.h" template<typename T> class KMeans{ public: KMeans(const Matrix<T>& dataset, int n_clusters, bool stop_criterion=true, int n_threads=1); Matrix<T> getCentroid(); Matrix<int> getDataToCentroid(); int getNIters(); void mapSampleToCentroid(); void updateCentroids(); void run(int max_iter, float threashold=-1); void print(); private: bool _stop_crit; int _n_threads; int _n_iters = 0; /** * number of features of the dataset (x0, x1, ..., xn) */ int _dims; /** * number of training samples */ int _samples; /** * desired number of clusters */ int _n_clusters; /** * K cluster centroids µ1, ..., µK. NxK matrix * where: * N: number of dimensions * K: number of classes/clusters */ std::unique_ptr<Matrix<T>> _centroids; /** * By convention, _training_set is a NxM matrix * where: * N: number of dimensions * M: number of training samples */ Matrix<T> _training_set; /** * M centroids indices mapping each training sample to a * corresponding cluster. 1xM matrix * where: * M: number of samples * element: index of cluster mapping * taining_index -> cluster_index * note: M may increase as we add new samples * The class doesn't support that yet * * stopping criterion idea: * keep _dataset_cluster from step t-1 * and check for changes. * If almost no change -> stop algorithm */ std::unique_ptr<ClosestCentroids<T>> _dataset_to_centroids; }; template<typename T> KMeans<T>::KMeans(const Matrix<T>& dataset, int n_clusters, bool stop_criterion, int n_threads) : _training_set{ dataset }, _n_clusters{ n_clusters }, _stop_crit{ stop_criterion }, _n_threads{ n_threads } { _training_set = dataset; _dims = dataset.getRows(); _samples = dataset.getCols(); _training_set.setThreads(_n_threads); Matrix<T> vMinValues = _training_set.vMin(); Matrix<T> vMaxValues = _training_set.vMax(); _centroids = std::make_unique<Matrix<T>>(_dims, n_clusters, UNIFORM, vMinValues, vMaxValues); _centroids->setThreads(_n_threads); _dataset_to_centroids = std::make_unique<ClosestCentroids<T>>(_samples, 0, stop_criterion, _n_threads); } template<typename T> inline Matrix<T> KMeans<T>::getCentroid(){ return *_centroids; } template<typename T> inline Matrix<int> KMeans<T>::getDataToCentroid(){ return *static_cast<Matrix<int>* >(_dataset_to_centroids.get()); } template<typename T> inline int KMeans<T>::getNIters(){ return _n_iters; } template<typename T> void KMeans<T>::mapSampleToCentroid(){ _dataset_to_centroids->getClosest(_training_set, *_centroids); } template<typename T> void KMeans<T>::updateCentroids(){ // number of points assigned to a cluster int occurences[_n_clusters] = {0}; // accumulates the samples to compute new cluster positions T sample_buff[_n_clusters*_dims] = {0}; //#pragma omp parallel for num_threads(_n_threads) for(int i = 0; i < _samples; ++i){ const int& k_index = (*_dataset_to_centroids)(i); for(int d = 0; d < _dims; ++d){ //#pragma atomic read write sample_buff[k_index+d*_n_clusters] += _training_set(d, i); } //#pragma atomic write ++occurences[k_index]; } //#pragma omp parallel for num_threads(_n_threads) for(int c = 0; c < _n_clusters; ++c){ if(!occurences[c]) continue; for(int d = 0; d < _dims; ++d){ (*_centroids)(d, c) = sample_buff[c+d*_n_clusters] / occurences[c]; } } } template<typename T> void KMeans<T>::run(int max_iter, float threashold){ mapSampleToCentroid(); updateCentroids(); _n_iters = 1; if(max_iter == 1) return; int epoch = 1; float modif_rate_prev = 0; float modif_rate_curr; float inertia; do { mapSampleToCentroid(); updateCentroids(); modif_rate_curr = _dataset_to_centroids->getModifRate(); inertia = modif_rate_curr - modif_rate_prev; modif_rate_prev = modif_rate_curr; //printf("%.3f %.3f\n", modif_rate_curr, inertia); ++epoch; } while(epoch < max_iter && modif_rate_curr >= threashold && std::abs(inertia) >= 1e-2); //} while(epoch < max_iter && modif_rate_curr > threashold); //} while(epoch < max_iter); _n_iters = epoch; //printf("iter number: %d\n", epoch); } template<typename T> void KMeans<T>::print() { for(int d = 0; d < _dims; ++d){ std::cout << "["; std::cout << _centroids->row(d) << "]," << std::endl; } }
convolution_3x3_pack1to4.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv3x3s1_pack1to4_msa(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out0 = top_blob.channel(p); v4f32 _bias0 = bias ? (v4f32)__msa_ld_w(bias + p * 4, 0) : (v4f32)__msa_fill_w(0); out0.fill(_bias0); const float* k0 = kernel.channel(p); int q = 0; for (; q < inch; q++) { float* outptr0 = out0; const Mat img0 = bottom_blob.channel(q); const float* r0 = img0.row(0); const float* r1 = img0.row(1); const float* r2 = img0.row(2); v4f32 _k00 = (v4f32)__msa_ld_w(k0, 0); v4f32 _k01 = (v4f32)__msa_ld_w(k0 + 4, 0); v4f32 _k02 = (v4f32)__msa_ld_w(k0 + 4 * 2, 0); v4f32 _k10 = (v4f32)__msa_ld_w(k0 + 4 * 3, 0); v4f32 _k11 = (v4f32)__msa_ld_w(k0 + 4 * 4, 0); v4f32 _k12 = (v4f32)__msa_ld_w(k0 + 4 * 5, 0); v4f32 _k20 = (v4f32)__msa_ld_w(k0 + 4 * 6, 0); v4f32 _k21 = (v4f32)__msa_ld_w(k0 + 4 * 7, 0); v4f32 _k22 = (v4f32)__msa_ld_w(k0 + 4 * 8, 0); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 7 < outw; j += 8) { v4f32 _sum0 = (v4f32)__msa_ld_w(outptr0, 0); v4f32 _sum1 = (v4f32)__msa_ld_w(outptr0 + 4, 0); v4f32 _sum2 = (v4f32)__msa_ld_w(outptr0 + 4 * 2, 0); v4f32 _sum3 = (v4f32)__msa_ld_w(outptr0 + 4 * 3, 0); v4f32 _sum4 = (v4f32)__msa_ld_w(outptr0 + 4 * 4, 0); v4f32 _sum5 = (v4f32)__msa_ld_w(outptr0 + 4 * 5, 0); v4f32 _sum6 = (v4f32)__msa_ld_w(outptr0 + 4 * 6, 0); v4f32 _sum7 = (v4f32)__msa_ld_w(outptr0 + 4 * 7, 0); v4i32 _r0 = __msa_ld_w(r0, 0); v4i32 _r0n = __msa_ld_w(r0 + 4, 0); v4i32 _r0nn = __msa_ld_w(r0 + 8, 0); v4f32 _r00 = (v4f32)__msa_splati_w(_r0, 0); v4f32 _r01 = (v4f32)__msa_splati_w(_r0, 1); v4f32 _r02 = (v4f32)__msa_splati_w(_r0, 2); v4f32 _r03 = (v4f32)__msa_splati_w(_r0, 3); v4f32 _r04 = (v4f32)__msa_splati_w(_r0n, 0); v4f32 _r05 = (v4f32)__msa_splati_w(_r0n, 1); v4f32 _r06 = (v4f32)__msa_splati_w(_r0n, 2); v4f32 _r07 = (v4f32)__msa_splati_w(_r0n, 3); v4f32 _r08 = (v4f32)__msa_splati_w(_r0nn, 0); v4f32 _r09 = (v4f32)__msa_splati_w(_r0nn, 1); _sum0 = __msa_fmadd_w(_sum0, _r00, _k00); _sum1 = __msa_fmadd_w(_sum1, _r01, _k00); _sum2 = __msa_fmadd_w(_sum2, _r02, _k00); _sum3 = __msa_fmadd_w(_sum3, _r03, _k00); _sum4 = __msa_fmadd_w(_sum4, _r04, _k00); _sum5 = __msa_fmadd_w(_sum5, _r05, _k00); _sum6 = __msa_fmadd_w(_sum6, _r06, _k00); _sum7 = __msa_fmadd_w(_sum7, _r07, _k00); _sum0 = __msa_fmadd_w(_sum0, _r01, _k01); _sum1 = __msa_fmadd_w(_sum1, _r02, _k01); _sum2 = __msa_fmadd_w(_sum2, _r03, _k01); _sum3 = __msa_fmadd_w(_sum3, _r04, _k01); _sum4 = __msa_fmadd_w(_sum4, _r05, _k01); _sum5 = __msa_fmadd_w(_sum5, _r06, _k01); _sum6 = __msa_fmadd_w(_sum6, _r07, _k01); _sum7 = __msa_fmadd_w(_sum7, _r08, _k01); _sum0 = __msa_fmadd_w(_sum0, _r02, _k02); _sum1 = __msa_fmadd_w(_sum1, _r03, _k02); _sum2 = __msa_fmadd_w(_sum2, _r04, _k02); _sum3 = __msa_fmadd_w(_sum3, _r05, _k02); _sum4 = __msa_fmadd_w(_sum4, _r06, _k02); _sum5 = __msa_fmadd_w(_sum5, _r07, _k02); _sum6 = __msa_fmadd_w(_sum6, _r08, _k02); _sum7 = __msa_fmadd_w(_sum7, _r09, _k02); v4i32 _r1 = __msa_ld_w(r1, 0); v4i32 _r1n = __msa_ld_w(r1 + 4, 0); v4i32 _r1nn = __msa_ld_w(r1 + 8, 0); v4f32 _r10 = (v4f32)__msa_splati_w(_r1, 0); v4f32 _r11 = (v4f32)__msa_splati_w(_r1, 1); v4f32 _r12 = (v4f32)__msa_splati_w(_r1, 2); v4f32 _r13 = (v4f32)__msa_splati_w(_r1, 3); v4f32 _r14 = (v4f32)__msa_splati_w(_r1n, 0); v4f32 _r15 = (v4f32)__msa_splati_w(_r1n, 1); v4f32 _r16 = (v4f32)__msa_splati_w(_r1n, 2); v4f32 _r17 = (v4f32)__msa_splati_w(_r1n, 3); v4f32 _r18 = (v4f32)__msa_splati_w(_r1nn, 0); v4f32 _r19 = (v4f32)__msa_splati_w(_r1nn, 1); _sum0 = __msa_fmadd_w(_sum0, _r10, _k10); _sum1 = __msa_fmadd_w(_sum1, _r11, _k10); _sum2 = __msa_fmadd_w(_sum2, _r12, _k10); _sum3 = __msa_fmadd_w(_sum3, _r13, _k10); _sum4 = __msa_fmadd_w(_sum4, _r14, _k10); _sum5 = __msa_fmadd_w(_sum5, _r15, _k10); _sum6 = __msa_fmadd_w(_sum6, _r16, _k10); _sum7 = __msa_fmadd_w(_sum7, _r17, _k10); _sum0 = __msa_fmadd_w(_sum0, _r11, _k11); _sum1 = __msa_fmadd_w(_sum1, _r12, _k11); _sum2 = __msa_fmadd_w(_sum2, _r13, _k11); _sum3 = __msa_fmadd_w(_sum3, _r14, _k11); _sum4 = __msa_fmadd_w(_sum4, _r15, _k11); _sum5 = __msa_fmadd_w(_sum5, _r16, _k11); _sum6 = __msa_fmadd_w(_sum6, _r17, _k11); _sum7 = __msa_fmadd_w(_sum7, _r18, _k11); _sum0 = __msa_fmadd_w(_sum0, _r12, _k12); _sum1 = __msa_fmadd_w(_sum1, _r13, _k12); _sum2 = __msa_fmadd_w(_sum2, _r14, _k12); _sum3 = __msa_fmadd_w(_sum3, _r15, _k12); _sum4 = __msa_fmadd_w(_sum4, _r16, _k12); _sum5 = __msa_fmadd_w(_sum5, _r17, _k12); _sum6 = __msa_fmadd_w(_sum6, _r18, _k12); _sum7 = __msa_fmadd_w(_sum7, _r19, _k12); v4i32 _r2 = __msa_ld_w(r2, 0); v4i32 _r2n = __msa_ld_w(r2 + 4, 0); v4i32 _r2nn = __msa_ld_w(r2 + 8, 0); v4f32 _r20 = (v4f32)__msa_splati_w(_r2, 0); v4f32 _r21 = (v4f32)__msa_splati_w(_r2, 1); v4f32 _r22 = (v4f32)__msa_splati_w(_r2, 2); v4f32 _r23 = (v4f32)__msa_splati_w(_r2, 3); v4f32 _r24 = (v4f32)__msa_splati_w(_r2n, 0); v4f32 _r25 = (v4f32)__msa_splati_w(_r2n, 1); v4f32 _r26 = (v4f32)__msa_splati_w(_r2n, 2); v4f32 _r27 = (v4f32)__msa_splati_w(_r2n, 3); v4f32 _r28 = (v4f32)__msa_splati_w(_r2nn, 0); v4f32 _r29 = (v4f32)__msa_splati_w(_r2nn, 1); _sum0 = __msa_fmadd_w(_sum0, _r20, _k20); _sum1 = __msa_fmadd_w(_sum1, _r21, _k20); _sum2 = __msa_fmadd_w(_sum2, _r22, _k20); _sum3 = __msa_fmadd_w(_sum3, _r23, _k20); _sum4 = __msa_fmadd_w(_sum4, _r24, _k20); _sum5 = __msa_fmadd_w(_sum5, _r25, _k20); _sum6 = __msa_fmadd_w(_sum6, _r26, _k20); _sum7 = __msa_fmadd_w(_sum7, _r27, _k20); _sum0 = __msa_fmadd_w(_sum0, _r21, _k21); _sum1 = __msa_fmadd_w(_sum1, _r22, _k21); _sum2 = __msa_fmadd_w(_sum2, _r23, _k21); _sum3 = __msa_fmadd_w(_sum3, _r24, _k21); _sum4 = __msa_fmadd_w(_sum4, _r25, _k21); _sum5 = __msa_fmadd_w(_sum5, _r26, _k21); _sum6 = __msa_fmadd_w(_sum6, _r27, _k21); _sum7 = __msa_fmadd_w(_sum7, _r28, _k21); _sum0 = __msa_fmadd_w(_sum0, _r22, _k22); _sum1 = __msa_fmadd_w(_sum1, _r23, _k22); _sum2 = __msa_fmadd_w(_sum2, _r24, _k22); _sum3 = __msa_fmadd_w(_sum3, _r25, _k22); _sum4 = __msa_fmadd_w(_sum4, _r26, _k22); _sum5 = __msa_fmadd_w(_sum5, _r27, _k22); _sum6 = __msa_fmadd_w(_sum6, _r28, _k22); _sum7 = __msa_fmadd_w(_sum7, _r29, _k22); __msa_st_w((v4i32)_sum0, outptr0, 0); __msa_st_w((v4i32)_sum1, outptr0 + 4, 0); __msa_st_w((v4i32)_sum2, outptr0 + 4 * 2, 0); __msa_st_w((v4i32)_sum3, outptr0 + 4 * 3, 0); __msa_st_w((v4i32)_sum4, outptr0 + 4 * 4, 0); __msa_st_w((v4i32)_sum5, outptr0 + 4 * 5, 0); __msa_st_w((v4i32)_sum6, outptr0 + 4 * 6, 0); __msa_st_w((v4i32)_sum7, outptr0 + 4 * 7, 0); outptr0 += 4 * 8; r0 += 8; r1 += 8; r2 += 8; } for (; j + 3 < outw; j += 4) { v4f32 _sum0 = (v4f32)__msa_ld_w(outptr0, 0); v4f32 _sum1 = (v4f32)__msa_ld_w(outptr0 + 4, 0); v4f32 _sum2 = (v4f32)__msa_ld_w(outptr0 + 4 * 2, 0); v4f32 _sum3 = (v4f32)__msa_ld_w(outptr0 + 4 * 3, 0); v4i32 _r0 = __msa_ld_w(r0, 0); v4i32 _r0n = __msa_ld_w(r0 + 4, 0); v4f32 _r00 = (v4f32)__msa_splati_w(_r0, 0); v4f32 _r01 = (v4f32)__msa_splati_w(_r0, 1); v4f32 _r02 = (v4f32)__msa_splati_w(_r0, 2); v4f32 _r03 = (v4f32)__msa_splati_w(_r0, 3); v4f32 _r04 = (v4f32)__msa_splati_w(_r0n, 0); v4f32 _r05 = (v4f32)__msa_splati_w(_r0n, 1); _sum0 = __msa_fmadd_w(_sum0, _r00, _k00); _sum1 = __msa_fmadd_w(_sum1, _r01, _k00); _sum2 = __msa_fmadd_w(_sum2, _r02, _k00); _sum3 = __msa_fmadd_w(_sum3, _r03, _k00); _sum0 = __msa_fmadd_w(_sum0, _r01, _k01); _sum1 = __msa_fmadd_w(_sum1, _r02, _k01); _sum2 = __msa_fmadd_w(_sum2, _r03, _k01); _sum3 = __msa_fmadd_w(_sum3, _r04, _k01); _sum0 = __msa_fmadd_w(_sum0, _r02, _k02); _sum1 = __msa_fmadd_w(_sum1, _r03, _k02); _sum2 = __msa_fmadd_w(_sum2, _r04, _k02); _sum3 = __msa_fmadd_w(_sum3, _r05, _k02); v4i32 _r1 = __msa_ld_w(r1, 0); v4i32 _r1n = __msa_ld_w(r1 + 4, 0); v4f32 _r10 = (v4f32)__msa_splati_w(_r1, 0); v4f32 _r11 = (v4f32)__msa_splati_w(_r1, 1); v4f32 _r12 = (v4f32)__msa_splati_w(_r1, 2); v4f32 _r13 = (v4f32)__msa_splati_w(_r1, 3); v4f32 _r14 = (v4f32)__msa_splati_w(_r1n, 0); v4f32 _r15 = (v4f32)__msa_splati_w(_r1n, 1); _sum0 = __msa_fmadd_w(_sum0, _r10, _k10); _sum1 = __msa_fmadd_w(_sum1, _r11, _k10); _sum2 = __msa_fmadd_w(_sum2, _r12, _k10); _sum3 = __msa_fmadd_w(_sum3, _r13, _k10); _sum0 = __msa_fmadd_w(_sum0, _r11, _k11); _sum1 = __msa_fmadd_w(_sum1, _r12, _k11); _sum2 = __msa_fmadd_w(_sum2, _r13, _k11); _sum3 = __msa_fmadd_w(_sum3, _r14, _k11); _sum0 = __msa_fmadd_w(_sum0, _r12, _k12); _sum1 = __msa_fmadd_w(_sum1, _r13, _k12); _sum2 = __msa_fmadd_w(_sum2, _r14, _k12); _sum3 = __msa_fmadd_w(_sum3, _r15, _k12); v4i32 _r2 = __msa_ld_w(r2, 0); v4i32 _r2n = __msa_ld_w(r2 + 4, 0); v4f32 _r20 = (v4f32)__msa_splati_w(_r2, 0); v4f32 _r21 = (v4f32)__msa_splati_w(_r2, 1); v4f32 _r22 = (v4f32)__msa_splati_w(_r2, 2); v4f32 _r23 = (v4f32)__msa_splati_w(_r2, 3); v4f32 _r24 = (v4f32)__msa_splati_w(_r2n, 0); v4f32 _r25 = (v4f32)__msa_splati_w(_r2n, 1); _sum0 = __msa_fmadd_w(_sum0, _r20, _k20); _sum1 = __msa_fmadd_w(_sum1, _r21, _k20); _sum2 = __msa_fmadd_w(_sum2, _r22, _k20); _sum3 = __msa_fmadd_w(_sum3, _r23, _k20); _sum0 = __msa_fmadd_w(_sum0, _r21, _k21); _sum1 = __msa_fmadd_w(_sum1, _r22, _k21); _sum2 = __msa_fmadd_w(_sum2, _r23, _k21); _sum3 = __msa_fmadd_w(_sum3, _r24, _k21); _sum0 = __msa_fmadd_w(_sum0, _r22, _k22); _sum1 = __msa_fmadd_w(_sum1, _r23, _k22); _sum2 = __msa_fmadd_w(_sum2, _r24, _k22); _sum3 = __msa_fmadd_w(_sum3, _r25, _k22); __msa_st_w((v4i32)_sum0, outptr0, 0); __msa_st_w((v4i32)_sum1, outptr0 + 4, 0); __msa_st_w((v4i32)_sum2, outptr0 + 4 * 2, 0); __msa_st_w((v4i32)_sum3, outptr0 + 4 * 3, 0); outptr0 += 4 * 4; r0 += 4; r1 += 4; r2 += 4; } for (; j + 1 < outw; j += 2) { v4f32 _sum0 = (v4f32)__msa_ld_w(outptr0, 0); v4f32 _sum1 = (v4f32)__msa_ld_w(outptr0 + 4, 0); v4i32 _r0 = __msa_ld_w(r0, 0); v4f32 _r00 = (v4f32)__msa_splati_w(_r0, 0); v4f32 _r01 = (v4f32)__msa_splati_w(_r0, 1); v4f32 _r02 = (v4f32)__msa_splati_w(_r0, 2); v4f32 _r03 = (v4f32)__msa_splati_w(_r0, 3); _sum0 = __msa_fmadd_w(_sum0, _r00, _k00); _sum1 = __msa_fmadd_w(_sum1, _r01, _k00); _sum0 = __msa_fmadd_w(_sum0, _r01, _k01); _sum1 = __msa_fmadd_w(_sum1, _r02, _k01); _sum0 = __msa_fmadd_w(_sum0, _r02, _k02); _sum1 = __msa_fmadd_w(_sum1, _r03, _k02); v4i32 _r1 = __msa_ld_w(r1, 0); v4f32 _r10 = (v4f32)__msa_splati_w(_r1, 0); v4f32 _r11 = (v4f32)__msa_splati_w(_r1, 1); v4f32 _r12 = (v4f32)__msa_splati_w(_r1, 2); v4f32 _r13 = (v4f32)__msa_splati_w(_r1, 3); _sum0 = __msa_fmadd_w(_sum0, _r10, _k10); _sum1 = __msa_fmadd_w(_sum1, _r11, _k10); _sum0 = __msa_fmadd_w(_sum0, _r11, _k11); _sum1 = __msa_fmadd_w(_sum1, _r12, _k11); _sum0 = __msa_fmadd_w(_sum0, _r12, _k12); _sum1 = __msa_fmadd_w(_sum1, _r13, _k12); v4i32 _r2 = __msa_ld_w(r2, 0); v4f32 _r20 = (v4f32)__msa_splati_w(_r2, 0); v4f32 _r21 = (v4f32)__msa_splati_w(_r2, 1); v4f32 _r22 = (v4f32)__msa_splati_w(_r2, 2); v4f32 _r23 = (v4f32)__msa_splati_w(_r2, 3); _sum0 = __msa_fmadd_w(_sum0, _r20, _k20); _sum1 = __msa_fmadd_w(_sum1, _r21, _k20); _sum0 = __msa_fmadd_w(_sum0, _r21, _k21); _sum1 = __msa_fmadd_w(_sum1, _r22, _k21); _sum0 = __msa_fmadd_w(_sum0, _r22, _k22); _sum1 = __msa_fmadd_w(_sum1, _r23, _k22); __msa_st_w((v4i32)_sum0, outptr0, 0); __msa_st_w((v4i32)_sum1, outptr0 + 4, 0); outptr0 += 4 * 2; r0 += 2; r1 += 2; r2 += 2; } for (; j < outw; j++) { v4f32 _sum0 = (v4f32)__msa_ld_w(outptr0, 0); v4i32 _r0 = __msa_ld_w(r0, 0); v4f32 _r00 = (v4f32)__msa_splati_w(_r0, 0); v4f32 _r01 = (v4f32)__msa_splati_w(_r0, 1); v4f32 _r02 = (v4f32)__msa_splati_w(_r0, 2); _sum0 = __msa_fmadd_w(_sum0, _r00, _k00); _sum0 = __msa_fmadd_w(_sum0, _r01, _k01); _sum0 = __msa_fmadd_w(_sum0, _r02, _k02); v4i32 _r1 = __msa_ld_w(r1, 0); v4f32 _r10 = (v4f32)__msa_splati_w(_r1, 0); v4f32 _r11 = (v4f32)__msa_splati_w(_r1, 1); v4f32 _r12 = (v4f32)__msa_splati_w(_r1, 2); _sum0 = __msa_fmadd_w(_sum0, _r10, _k10); _sum0 = __msa_fmadd_w(_sum0, _r11, _k11); _sum0 = __msa_fmadd_w(_sum0, _r12, _k12); v4i32 _r2 = __msa_ld_w(r2, 0); v4f32 _r20 = (v4f32)__msa_splati_w(_r2, 0); v4f32 _r21 = (v4f32)__msa_splati_w(_r2, 1); v4f32 _r22 = (v4f32)__msa_splati_w(_r2, 2); _sum0 = __msa_fmadd_w(_sum0, _r20, _k20); _sum0 = __msa_fmadd_w(_sum0, _r21, _k21); _sum0 = __msa_fmadd_w(_sum0, _r22, _k22); __msa_st_w((v4i32)_sum0, outptr0, 0); outptr0 += 4; r0 += 1; r1 += 1; r2 += 1; } r0 += 2; r1 += 2; r2 += 2; } k0 += 9 * 4; } } } static void conv3x3s2_pack1to4_msa(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out0 = top_blob.channel(p); v4f32 _bias0 = bias ? (v4f32)__msa_ld_w(bias + p * 4, 0) : (v4f32)__msa_fill_w(0); out0.fill(_bias0); const float* k0 = kernel.channel(p); int q = 0; for (; q < inch; q++) { float* outptr0 = out0; const Mat img0 = bottom_blob.channel(q); const float* r0 = img0.row(0); const float* r1 = img0.row(1); const float* r2 = img0.row(2); v4f32 _k00 = (v4f32)__msa_ld_w(k0, 0); v4f32 _k01 = (v4f32)__msa_ld_w(k0 + 4, 0); v4f32 _k02 = (v4f32)__msa_ld_w(k0 + 4 * 2, 0); v4f32 _k10 = (v4f32)__msa_ld_w(k0 + 4 * 3, 0); v4f32 _k11 = (v4f32)__msa_ld_w(k0 + 4 * 4, 0); v4f32 _k12 = (v4f32)__msa_ld_w(k0 + 4 * 5, 0); v4f32 _k20 = (v4f32)__msa_ld_w(k0 + 4 * 6, 0); v4f32 _k21 = (v4f32)__msa_ld_w(k0 + 4 * 7, 0); v4f32 _k22 = (v4f32)__msa_ld_w(k0 + 4 * 8, 0); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 7 < outw; j += 8) { v4f32 _sum0 = (v4f32)__msa_ld_w(outptr0, 0); v4f32 _sum1 = (v4f32)__msa_ld_w(outptr0 + 4, 0); v4f32 _sum2 = (v4f32)__msa_ld_w(outptr0 + 4 * 2, 0); v4f32 _sum3 = (v4f32)__msa_ld_w(outptr0 + 4 * 3, 0); v4f32 _sum4 = (v4f32)__msa_ld_w(outptr0 + 4 * 4, 0); v4f32 _sum5 = (v4f32)__msa_ld_w(outptr0 + 4 * 5, 0); v4f32 _sum6 = (v4f32)__msa_ld_w(outptr0 + 4 * 6, 0); v4f32 _sum7 = (v4f32)__msa_ld_w(outptr0 + 4 * 7, 0); v4i32 _r0 = __msa_ld_w(r0, 0); v4i32 _r0n = __msa_ld_w(r0 + 4, 0); v4i32 _r0nn = __msa_ld_w(r0 + 8, 0); v4i32 _r0nnn = __msa_ld_w(r0 + 12, 0); v4f32 _r00 = (v4f32)__msa_splati_w(_r0, 0); v4f32 _r01 = (v4f32)__msa_splati_w(_r0, 1); v4f32 _r02 = (v4f32)__msa_splati_w(_r0, 2); v4f32 _r03 = (v4f32)__msa_splati_w(_r0, 3); v4f32 _r04 = (v4f32)__msa_splati_w(_r0n, 0); v4f32 _r05 = (v4f32)__msa_splati_w(_r0n, 1); v4f32 _r06 = (v4f32)__msa_splati_w(_r0n, 2); v4f32 _r07 = (v4f32)__msa_splati_w(_r0n, 3); v4f32 _r08 = (v4f32)__msa_splati_w(_r0nn, 0); v4f32 _r09 = (v4f32)__msa_splati_w(_r0nn, 1); v4f32 _r0a = (v4f32)__msa_splati_w(_r0nn, 2); v4f32 _r0b = (v4f32)__msa_splati_w(_r0nn, 3); v4f32 _r0c = (v4f32)__msa_splati_w(_r0nnn, 0); v4f32 _r0d = (v4f32)__msa_splati_w(_r0nnn, 1); v4f32 _r0e = (v4f32)__msa_splati_w(_r0nnn, 2); v4f32 _r0f = (v4f32)__msa_splati_w(_r0nnn, 3); v4f32 _r0g = __msa_fill_w_f32(r0[16]); _sum0 = __msa_fmadd_w(_sum0, _r00, _k00); _sum1 = __msa_fmadd_w(_sum1, _r02, _k00); _sum2 = __msa_fmadd_w(_sum2, _r04, _k00); _sum3 = __msa_fmadd_w(_sum3, _r06, _k00); _sum4 = __msa_fmadd_w(_sum4, _r08, _k00); _sum5 = __msa_fmadd_w(_sum5, _r0a, _k00); _sum6 = __msa_fmadd_w(_sum6, _r0c, _k00); _sum7 = __msa_fmadd_w(_sum7, _r0e, _k00); _sum0 = __msa_fmadd_w(_sum0, _r01, _k01); _sum1 = __msa_fmadd_w(_sum1, _r03, _k01); _sum2 = __msa_fmadd_w(_sum2, _r05, _k01); _sum3 = __msa_fmadd_w(_sum3, _r07, _k01); _sum4 = __msa_fmadd_w(_sum4, _r09, _k01); _sum5 = __msa_fmadd_w(_sum5, _r0b, _k01); _sum6 = __msa_fmadd_w(_sum6, _r0d, _k01); _sum7 = __msa_fmadd_w(_sum7, _r0f, _k01); _sum0 = __msa_fmadd_w(_sum0, _r02, _k02); _sum1 = __msa_fmadd_w(_sum1, _r04, _k02); _sum2 = __msa_fmadd_w(_sum2, _r06, _k02); _sum3 = __msa_fmadd_w(_sum3, _r08, _k02); _sum4 = __msa_fmadd_w(_sum4, _r0a, _k02); _sum5 = __msa_fmadd_w(_sum5, _r0c, _k02); _sum6 = __msa_fmadd_w(_sum6, _r0e, _k02); _sum7 = __msa_fmadd_w(_sum7, _r0g, _k02); v4i32 _r1 = __msa_ld_w(r1, 0); v4i32 _r1n = __msa_ld_w(r1 + 4, 0); v4i32 _r1nn = __msa_ld_w(r1 + 8, 0); v4i32 _r1nnn = __msa_ld_w(r1 + 12, 0); v4f32 _r10 = (v4f32)__msa_splati_w(_r1, 0); v4f32 _r11 = (v4f32)__msa_splati_w(_r1, 1); v4f32 _r12 = (v4f32)__msa_splati_w(_r1, 2); v4f32 _r13 = (v4f32)__msa_splati_w(_r1, 3); v4f32 _r14 = (v4f32)__msa_splati_w(_r1n, 0); v4f32 _r15 = (v4f32)__msa_splati_w(_r1n, 1); v4f32 _r16 = (v4f32)__msa_splati_w(_r1n, 2); v4f32 _r17 = (v4f32)__msa_splati_w(_r1n, 3); v4f32 _r18 = (v4f32)__msa_splati_w(_r1nn, 0); v4f32 _r19 = (v4f32)__msa_splati_w(_r1nn, 1); v4f32 _r1a = (v4f32)__msa_splati_w(_r1nn, 2); v4f32 _r1b = (v4f32)__msa_splati_w(_r1nn, 3); v4f32 _r1c = (v4f32)__msa_splati_w(_r1nnn, 0); v4f32 _r1d = (v4f32)__msa_splati_w(_r1nnn, 1); v4f32 _r1e = (v4f32)__msa_splati_w(_r1nnn, 2); v4f32 _r1f = (v4f32)__msa_splati_w(_r1nnn, 3); v4f32 _r1g = __msa_fill_w_f32(r1[16]); _sum0 = __msa_fmadd_w(_sum0, _r10, _k10); _sum1 = __msa_fmadd_w(_sum1, _r12, _k10); _sum2 = __msa_fmadd_w(_sum2, _r14, _k10); _sum3 = __msa_fmadd_w(_sum3, _r16, _k10); _sum4 = __msa_fmadd_w(_sum4, _r18, _k10); _sum5 = __msa_fmadd_w(_sum5, _r1a, _k10); _sum6 = __msa_fmadd_w(_sum6, _r1c, _k10); _sum7 = __msa_fmadd_w(_sum7, _r1e, _k10); _sum0 = __msa_fmadd_w(_sum0, _r11, _k11); _sum1 = __msa_fmadd_w(_sum1, _r13, _k11); _sum2 = __msa_fmadd_w(_sum2, _r15, _k11); _sum3 = __msa_fmadd_w(_sum3, _r17, _k11); _sum4 = __msa_fmadd_w(_sum4, _r19, _k11); _sum5 = __msa_fmadd_w(_sum5, _r1b, _k11); _sum6 = __msa_fmadd_w(_sum6, _r1d, _k11); _sum7 = __msa_fmadd_w(_sum7, _r1f, _k11); _sum0 = __msa_fmadd_w(_sum0, _r12, _k12); _sum1 = __msa_fmadd_w(_sum1, _r14, _k12); _sum2 = __msa_fmadd_w(_sum2, _r16, _k12); _sum3 = __msa_fmadd_w(_sum3, _r18, _k12); _sum4 = __msa_fmadd_w(_sum4, _r1a, _k12); _sum5 = __msa_fmadd_w(_sum5, _r1c, _k12); _sum6 = __msa_fmadd_w(_sum6, _r1e, _k12); _sum7 = __msa_fmadd_w(_sum7, _r1g, _k12); v4i32 _r2 = __msa_ld_w(r2, 0); v4i32 _r2n = __msa_ld_w(r2 + 4, 0); v4i32 _r2nn = __msa_ld_w(r2 + 8, 0); v4i32 _r2nnn = __msa_ld_w(r2 + 12, 0); v4f32 _r20 = (v4f32)__msa_splati_w(_r2, 0); v4f32 _r21 = (v4f32)__msa_splati_w(_r2, 1); v4f32 _r22 = (v4f32)__msa_splati_w(_r2, 2); v4f32 _r23 = (v4f32)__msa_splati_w(_r2, 3); v4f32 _r24 = (v4f32)__msa_splati_w(_r2n, 0); v4f32 _r25 = (v4f32)__msa_splati_w(_r2n, 1); v4f32 _r26 = (v4f32)__msa_splati_w(_r2n, 2); v4f32 _r27 = (v4f32)__msa_splati_w(_r2n, 3); v4f32 _r28 = (v4f32)__msa_splati_w(_r2nn, 0); v4f32 _r29 = (v4f32)__msa_splati_w(_r2nn, 1); v4f32 _r2a = (v4f32)__msa_splati_w(_r2nn, 2); v4f32 _r2b = (v4f32)__msa_splati_w(_r2nn, 3); v4f32 _r2c = (v4f32)__msa_splati_w(_r2nnn, 0); v4f32 _r2d = (v4f32)__msa_splati_w(_r2nnn, 1); v4f32 _r2e = (v4f32)__msa_splati_w(_r2nnn, 2); v4f32 _r2f = (v4f32)__msa_splati_w(_r2nnn, 3); v4f32 _r2g = __msa_fill_w_f32(r2[16]); _sum0 = __msa_fmadd_w(_sum0, _r20, _k20); _sum1 = __msa_fmadd_w(_sum1, _r22, _k20); _sum2 = __msa_fmadd_w(_sum2, _r24, _k20); _sum3 = __msa_fmadd_w(_sum3, _r26, _k20); _sum4 = __msa_fmadd_w(_sum4, _r28, _k20); _sum5 = __msa_fmadd_w(_sum5, _r2a, _k20); _sum6 = __msa_fmadd_w(_sum6, _r2c, _k20); _sum7 = __msa_fmadd_w(_sum7, _r2e, _k20); _sum0 = __msa_fmadd_w(_sum0, _r21, _k21); _sum1 = __msa_fmadd_w(_sum1, _r23, _k21); _sum2 = __msa_fmadd_w(_sum2, _r25, _k21); _sum3 = __msa_fmadd_w(_sum3, _r27, _k21); _sum4 = __msa_fmadd_w(_sum4, _r29, _k21); _sum5 = __msa_fmadd_w(_sum5, _r2b, _k21); _sum6 = __msa_fmadd_w(_sum6, _r2d, _k21); _sum7 = __msa_fmadd_w(_sum7, _r2f, _k21); _sum0 = __msa_fmadd_w(_sum0, _r22, _k22); _sum1 = __msa_fmadd_w(_sum1, _r24, _k22); _sum2 = __msa_fmadd_w(_sum2, _r26, _k22); _sum3 = __msa_fmadd_w(_sum3, _r28, _k22); _sum4 = __msa_fmadd_w(_sum4, _r2a, _k22); _sum5 = __msa_fmadd_w(_sum5, _r2c, _k22); _sum6 = __msa_fmadd_w(_sum6, _r2e, _k22); _sum7 = __msa_fmadd_w(_sum7, _r2g, _k22); __msa_st_w((v4i32)_sum0, outptr0, 0); __msa_st_w((v4i32)_sum1, outptr0 + 4, 0); __msa_st_w((v4i32)_sum2, outptr0 + 4 * 2, 0); __msa_st_w((v4i32)_sum3, outptr0 + 4 * 3, 0); __msa_st_w((v4i32)_sum4, outptr0 + 4 * 4, 0); __msa_st_w((v4i32)_sum5, outptr0 + 4 * 5, 0); __msa_st_w((v4i32)_sum6, outptr0 + 4 * 6, 0); __msa_st_w((v4i32)_sum7, outptr0 + 4 * 7, 0); outptr0 += 4 * 8; r0 += 16; r1 += 16; r2 += 16; } for (; j + 3 < outw; j += 4) { v4f32 _sum0 = (v4f32)__msa_ld_w(outptr0, 0); v4f32 _sum1 = (v4f32)__msa_ld_w(outptr0 + 4, 0); v4f32 _sum2 = (v4f32)__msa_ld_w(outptr0 + 4 * 2, 0); v4f32 _sum3 = (v4f32)__msa_ld_w(outptr0 + 4 * 3, 0); v4i32 _r0 = __msa_ld_w(r0, 0); v4i32 _r0n = __msa_ld_w(r0 + 4, 0); v4f32 _r00 = (v4f32)__msa_splati_w(_r0, 0); v4f32 _r01 = (v4f32)__msa_splati_w(_r0, 1); v4f32 _r02 = (v4f32)__msa_splati_w(_r0, 2); v4f32 _r03 = (v4f32)__msa_splati_w(_r0, 3); v4f32 _r04 = (v4f32)__msa_splati_w(_r0n, 0); v4f32 _r05 = (v4f32)__msa_splati_w(_r0n, 1); v4f32 _r06 = (v4f32)__msa_splati_w(_r0n, 2); v4f32 _r07 = (v4f32)__msa_splati_w(_r0n, 3); v4f32 _r08 = __msa_fill_w_f32(r0[8]); _sum0 = __msa_fmadd_w(_sum0, _r00, _k00); _sum1 = __msa_fmadd_w(_sum1, _r02, _k00); _sum2 = __msa_fmadd_w(_sum2, _r04, _k00); _sum3 = __msa_fmadd_w(_sum3, _r06, _k00); _sum0 = __msa_fmadd_w(_sum0, _r01, _k01); _sum1 = __msa_fmadd_w(_sum1, _r03, _k01); _sum2 = __msa_fmadd_w(_sum2, _r05, _k01); _sum3 = __msa_fmadd_w(_sum3, _r07, _k01); _sum0 = __msa_fmadd_w(_sum0, _r02, _k02); _sum1 = __msa_fmadd_w(_sum1, _r04, _k02); _sum2 = __msa_fmadd_w(_sum2, _r06, _k02); _sum3 = __msa_fmadd_w(_sum3, _r08, _k02); v4i32 _r1 = __msa_ld_w(r1, 0); v4i32 _r1n = __msa_ld_w(r1 + 4, 0); v4f32 _r10 = (v4f32)__msa_splati_w(_r1, 0); v4f32 _r11 = (v4f32)__msa_splati_w(_r1, 1); v4f32 _r12 = (v4f32)__msa_splati_w(_r1, 2); v4f32 _r13 = (v4f32)__msa_splati_w(_r1, 3); v4f32 _r14 = (v4f32)__msa_splati_w(_r1n, 0); v4f32 _r15 = (v4f32)__msa_splati_w(_r1n, 1); v4f32 _r16 = (v4f32)__msa_splati_w(_r1n, 2); v4f32 _r17 = (v4f32)__msa_splati_w(_r1n, 3); v4f32 _r18 = __msa_fill_w_f32(r1[8]); _sum0 = __msa_fmadd_w(_sum0, _r10, _k10); _sum1 = __msa_fmadd_w(_sum1, _r12, _k10); _sum2 = __msa_fmadd_w(_sum2, _r14, _k10); _sum3 = __msa_fmadd_w(_sum3, _r16, _k10); _sum0 = __msa_fmadd_w(_sum0, _r11, _k11); _sum1 = __msa_fmadd_w(_sum1, _r13, _k11); _sum2 = __msa_fmadd_w(_sum2, _r15, _k11); _sum3 = __msa_fmadd_w(_sum3, _r17, _k11); _sum0 = __msa_fmadd_w(_sum0, _r12, _k12); _sum1 = __msa_fmadd_w(_sum1, _r14, _k12); _sum2 = __msa_fmadd_w(_sum2, _r16, _k12); _sum3 = __msa_fmadd_w(_sum3, _r18, _k12); v4i32 _r2 = __msa_ld_w(r2, 0); v4i32 _r2n = __msa_ld_w(r2 + 4, 0); v4f32 _r20 = (v4f32)__msa_splati_w(_r2, 0); v4f32 _r21 = (v4f32)__msa_splati_w(_r2, 1); v4f32 _r22 = (v4f32)__msa_splati_w(_r2, 2); v4f32 _r23 = (v4f32)__msa_splati_w(_r2, 3); v4f32 _r24 = (v4f32)__msa_splati_w(_r2n, 0); v4f32 _r25 = (v4f32)__msa_splati_w(_r2n, 1); v4f32 _r26 = (v4f32)__msa_splati_w(_r2n, 2); v4f32 _r27 = (v4f32)__msa_splati_w(_r2n, 3); v4f32 _r28 = __msa_fill_w_f32(r2[8]); _sum0 = __msa_fmadd_w(_sum0, _r20, _k20); _sum1 = __msa_fmadd_w(_sum1, _r22, _k20); _sum2 = __msa_fmadd_w(_sum2, _r24, _k20); _sum3 = __msa_fmadd_w(_sum3, _r26, _k20); _sum0 = __msa_fmadd_w(_sum0, _r21, _k21); _sum1 = __msa_fmadd_w(_sum1, _r23, _k21); _sum2 = __msa_fmadd_w(_sum2, _r25, _k21); _sum3 = __msa_fmadd_w(_sum3, _r27, _k21); _sum0 = __msa_fmadd_w(_sum0, _r22, _k22); _sum1 = __msa_fmadd_w(_sum1, _r24, _k22); _sum2 = __msa_fmadd_w(_sum2, _r26, _k22); _sum3 = __msa_fmadd_w(_sum3, _r28, _k22); __msa_st_w((v4i32)_sum0, outptr0, 0); __msa_st_w((v4i32)_sum1, outptr0 + 4, 0); __msa_st_w((v4i32)_sum2, outptr0 + 4 * 2, 0); __msa_st_w((v4i32)_sum3, outptr0 + 4 * 3, 0); outptr0 += 4 * 4; r0 += 8; r1 += 8; r2 += 8; } for (; j + 1 < outw; j += 2) { v4f32 _sum0 = (v4f32)__msa_ld_w(outptr0, 0); v4f32 _sum1 = (v4f32)__msa_ld_w(outptr0 + 4, 0); v4i32 _r0 = __msa_ld_w(r0, 0); v4f32 _r00 = (v4f32)__msa_splati_w(_r0, 0); v4f32 _r01 = (v4f32)__msa_splati_w(_r0, 1); v4f32 _r02 = (v4f32)__msa_splati_w(_r0, 2); v4f32 _r03 = (v4f32)__msa_splati_w(_r0, 3); v4f32 _r04 = __msa_fill_w_f32(r0[4]); _sum0 = __msa_fmadd_w(_sum0, _r00, _k00); _sum1 = __msa_fmadd_w(_sum1, _r02, _k00); _sum0 = __msa_fmadd_w(_sum0, _r01, _k01); _sum1 = __msa_fmadd_w(_sum1, _r03, _k01); _sum0 = __msa_fmadd_w(_sum0, _r02, _k02); _sum1 = __msa_fmadd_w(_sum1, _r04, _k02); v4i32 _r1 = __msa_ld_w(r1, 0); v4f32 _r10 = (v4f32)__msa_splati_w(_r1, 0); v4f32 _r11 = (v4f32)__msa_splati_w(_r1, 1); v4f32 _r12 = (v4f32)__msa_splati_w(_r1, 2); v4f32 _r13 = (v4f32)__msa_splati_w(_r1, 3); v4f32 _r14 = __msa_fill_w_f32(r1[4]); _sum0 = __msa_fmadd_w(_sum0, _r10, _k10); _sum1 = __msa_fmadd_w(_sum1, _r12, _k10); _sum0 = __msa_fmadd_w(_sum0, _r11, _k11); _sum1 = __msa_fmadd_w(_sum1, _r13, _k11); _sum0 = __msa_fmadd_w(_sum0, _r12, _k12); _sum1 = __msa_fmadd_w(_sum1, _r14, _k12); v4i32 _r2 = __msa_ld_w(r2, 0); v4f32 _r20 = (v4f32)__msa_splati_w(_r2, 0); v4f32 _r21 = (v4f32)__msa_splati_w(_r2, 1); v4f32 _r22 = (v4f32)__msa_splati_w(_r2, 2); v4f32 _r23 = (v4f32)__msa_splati_w(_r2, 3); v4f32 _r24 = __msa_fill_w_f32(r2[4]); _sum0 = __msa_fmadd_w(_sum0, _r20, _k20); _sum1 = __msa_fmadd_w(_sum1, _r22, _k20); _sum0 = __msa_fmadd_w(_sum0, _r21, _k21); _sum1 = __msa_fmadd_w(_sum1, _r23, _k21); _sum0 = __msa_fmadd_w(_sum0, _r22, _k22); _sum1 = __msa_fmadd_w(_sum1, _r24, _k22); __msa_st_w((v4i32)_sum0, outptr0, 0); __msa_st_w((v4i32)_sum1, outptr0 + 4, 0); outptr0 += 4 * 2; r0 += 4; r1 += 4; r2 += 4; } for (; j < outw; j++) { v4f32 _sum0 = (v4f32)__msa_ld_w(outptr0, 0); v4i32 _r0 = __msa_ld_w(r0, 0); v4f32 _r00 = (v4f32)__msa_splati_w(_r0, 0); v4f32 _r01 = (v4f32)__msa_splati_w(_r0, 1); v4f32 _r02 = (v4f32)__msa_splati_w(_r0, 2); _sum0 = __msa_fmadd_w(_sum0, _r00, _k00); _sum0 = __msa_fmadd_w(_sum0, _r01, _k01); _sum0 = __msa_fmadd_w(_sum0, _r02, _k02); v4i32 _r1 = __msa_ld_w(r1, 0); v4f32 _r10 = (v4f32)__msa_splati_w(_r1, 0); v4f32 _r11 = (v4f32)__msa_splati_w(_r1, 1); v4f32 _r12 = (v4f32)__msa_splati_w(_r1, 2); _sum0 = __msa_fmadd_w(_sum0, _r10, _k10); _sum0 = __msa_fmadd_w(_sum0, _r11, _k11); _sum0 = __msa_fmadd_w(_sum0, _r12, _k12); v4i32 _r2 = __msa_ld_w(r2, 0); v4f32 _r20 = (v4f32)__msa_splati_w(_r2, 0); v4f32 _r21 = (v4f32)__msa_splati_w(_r2, 1); v4f32 _r22 = (v4f32)__msa_splati_w(_r2, 2); _sum0 = __msa_fmadd_w(_sum0, _r20, _k20); _sum0 = __msa_fmadd_w(_sum0, _r21, _k21); _sum0 = __msa_fmadd_w(_sum0, _r22, _k22); __msa_st_w((v4i32)_sum0, outptr0, 0); outptr0 += 4; r0 += 2; r1 += 2; r2 += 2; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } k0 += 9 * 4; } } }
GI.h
#include <parse.h> #define SELF_GRAVITY #define FLAG_GI #ifdef PARTICLE_SIMULATOR_TWO_DIMENSION #error #endif template <class Ptcl> class GI : public Problem<Ptcl>{ public: static const double END_TIME; static void setupIC(PS::ParticleSystem<Ptcl>& sph_system, system_t& sysinfo, PS::DomainInfo& dinfo){ const bool createTarget = true;//set false if you make an impactor. const double Corr = .98;//Correction Term ///////// //place ptcls ///////// std::vector<Ptcl> ptcl; std::vector<Ptcl> tar;//Target std::vector<Ptcl> imp;//Impactor ///////// // Use parameters from input file, or defaults if none provided // TODO: Currently the input file has to be in the same directory as the executable // Change this into a command-line parameter. ParameterFile parameter_file("input.txt"); PS::F64 UnitMass = parameter_file.getValueOf("UnitMass", 6.0e+24); PS::F64 UnitRadi = parameter_file.getValueOf("UnitRadi", 6400e+3); PS::F64 coreFracRadi = parameter_file.getValueOf("coreFracRadi", 3500.0e+3 / 6400.0e+3); PS::F64 coreFracMass = parameter_file.getValueOf("coreFracMass", 0.3); PS::F64 imptarMassRatio = parameter_file.getValueOf("imptarMassRatio", 0.1); ///////// const PS::F64 Expand = 1.1; const PS::F64 tarMass = UnitMass; const PS::F64 tarRadi = UnitRadi; const PS::F64 tarCoreMass = tarMass * coreFracMass; const PS::F64 tarCoreRadi = tarRadi * coreFracRadi; const PS::F64 impMass = imptarMassRatio * tarMass; const PS::F64 impRadi = Expand * cbrt(impMass / tarMass) * UnitRadi; const PS::F64 impCoreMass = impMass * coreFracMass; const PS::F64 impCoreRadi = impRadi * coreFracRadi; const double offset = 5.0 * UnitRadi; const PS::F64 dx = 1.0 / 39; const PS::F64 Grav = 6.67e-11; std::cout << impRadi / tarRadi << std::endl; std::cout << impCoreRadi / impRadi << std::endl; /////////////////// //Dummy put to determine # of ptcls /////////////////// //target int tarNmntl = 0; for(PS::F64 x = -1.0 ; x <= 1.0 ; x += dx){ for(PS::F64 y = -1.0 ; y <= 1.0 ; y += dx){ for(PS::F64 z = -1.0 ; z <= 1.0 ; z += dx){ const PS::F64 r = sqrt(x*x + y*y + z*z) * UnitRadi; if(r >= tarRadi || r <= tarCoreRadi) continue; ++ tarNmntl; } } } int tarNcore; double tarCoreShrinkFactor = 1.0; while(tarCoreShrinkFactor *= 0.99){ tarNcore = 0; for(PS::F64 x = -1.0 ; x <= 1.0 ; x += dx){ for(PS::F64 y = -1.0 ; y <= 1.0 ; y += dx){ for(PS::F64 z = -1.0 ; z <= 1.0 ; z += dx){ const PS::F64 r = tarCoreShrinkFactor * sqrt(x*x + y*y + z*z) * UnitRadi; if(r >= Corr * tarCoreRadi) continue; ++ tarNcore; } } } if((double)(tarNcore) / (double)(tarNcore + tarNmntl) > coreFracMass) break; } //imp int impNmntl = 0; for(PS::F64 x = -1.0 ; x <= 1.0 ; x += dx){ for(PS::F64 y = -1.0 ; y <= 1.0 ; y += dx){ for(PS::F64 z = -1.0 ; z <= 1.0 ; z += dx){ const PS::F64 r = Expand * sqrt(x*x + y*y + z*z) * UnitRadi; if(r >= impRadi || r <= impCoreRadi) continue; ++ impNmntl; } } } double impCoreShrinkFactor = 1.0; int impNcore; while(impCoreShrinkFactor *= 0.99){ impNcore = 0; for(PS::F64 x = -1.0 ; x <= 1.0 ; x += dx){ for(PS::F64 y = -1.0 ; y <= 1.0 ; y += dx){ for(PS::F64 z = -1.0 ; z <= 1.0 ; z += dx){ const PS::F64 r = Expand * impCoreShrinkFactor * sqrt(x*x + y*y + z*z) * UnitRadi; if(r >= Corr * impCoreRadi) continue; ++ impNcore; } } } if((double)(impNcore) / (double)(impNcore + impNmntl) > coreFracMass) break; } /////////////////// //Dummy end /////////////////// const int tarNptcl = tarNcore + tarNmntl; const int impNptcl = impNcore + impNmntl; const int Nptcl = tarNptcl + impNptcl; std::cout << "Target :" << tarNptcl << std::endl; std::cout << " radius : " << tarRadi << std::endl; std::cout << " total-to-core : " << (double)(tarNcore) / (double)(tarNptcl) << std::endl; std::cout << " # of core ptcls : " << tarNcore << std::endl; std::cout << " # of mantle ptcls: " << tarNmntl << std::endl; std::cout << " core density : " << tarCoreMass / (4.0 * math::pi / 3.0 * tarCoreRadi * tarCoreRadi * tarCoreRadi * Corr * Corr * Corr) << std::endl; std::cout << " mantle density : " << (tarMass - tarCoreMass) / (4.0 * math::pi / 3.0 * (tarRadi * tarRadi * tarRadi - tarCoreRadi * tarCoreRadi * tarCoreRadi)) << std::endl; std::cout << " mean density : " << tarMass / (4.0 * math::pi / 3.0 * tarRadi * tarRadi * tarRadi) << std::endl; std::cout << "Impactor:" << impNptcl << std::endl; std::cout << " radius : " << impRadi << std::endl; std::cout << " total-to-core : " << (double)(impNcore) / (double)(impNptcl) << std::endl; std::cout << " # of core ptcls : " << impNcore << std::endl; std::cout << " # of mantle ptcls: " << impNmntl << std::endl; std::cout << " core density : " << impCoreMass / (4.0 * math::pi / 3.0 * impCoreRadi * impCoreRadi * impCoreRadi * Corr * Corr * Corr) << std::endl; std::cout << " mantle density : " << (impMass - impCoreMass) / (4.0 * math::pi / 3.0 * (impRadi * impRadi * impRadi - impCoreRadi * impCoreRadi * impCoreRadi)) << std::endl; std::cout << " mean density : " << impMass / (4.0 * math::pi / 3.0 * impRadi * impRadi * impRadi) << std::endl; std::cout << "Total:" << Nptcl << std::endl; std::cout << "Tar-to-Imp mass ratio: " << (double)(impNmntl) / (double)(tarNmntl) << std::endl; const int NptclIn1Node = Nptcl / PS::Comm::getNumberOfProc(); /////////////////// //Real put /////////////////// PS::S32 id = 0; //Put Tar. for(PS::F64 x = -1.0 ; x <= 1.0 ; x += dx){ for(PS::F64 y = -1.0 ; y <= 1.0 ; y += dx){ for(PS::F64 z = -1.0 ; z <= 1.0 ; z += dx){ const PS::F64 r = sqrt(x*x + y*y + z*z) * UnitRadi; if(r >= tarRadi || r <= tarCoreRadi) continue; Ptcl ith; ith.pos.x = UnitRadi * x; ith.pos.y = UnitRadi * y; ith.pos.z = UnitRadi * z; ith.dens = (tarMass - tarCoreMass) / (4.0 / 3.0 * math::pi * (tarRadi * tarRadi * tarRadi - tarCoreRadi * tarCoreRadi * tarCoreRadi)); ith.mass = tarMass + impMass; ith.eng = 0.1 * Grav * tarMass / tarRadi; ith.id = id++; ith.setPressure(&Granite); ith.tag = 0; if(ith.id / NptclIn1Node == PS::Comm::getRank()) tar.push_back(ith); } } } for(PS::F64 x = -1.0 ; x <= 1.0 ; x += dx){ for(PS::F64 y = -1.0 ; y <= 1.0 ; y += dx){ for(PS::F64 z = -1.0 ; z <= 1.0 ; z += dx){ const PS::F64 r = tarCoreShrinkFactor * sqrt(x*x + y*y + z*z) * UnitRadi; if(r >= Corr * tarCoreRadi) continue; Ptcl ith; ith.pos.x = tarCoreShrinkFactor * UnitRadi * x; ith.pos.y = tarCoreShrinkFactor * UnitRadi * y; ith.pos.z = tarCoreShrinkFactor * UnitRadi * z; ith.dens = tarCoreMass / (4.0 / 3.0 * math::pi * tarCoreRadi * tarCoreRadi * tarCoreRadi * Corr * Corr * Corr); ith.mass = tarMass + impMass; ith.eng = 0.1 * Grav * tarMass / tarRadi; ith.id = id++; ith.setPressure(&Iron); ith.tag = 1; if(ith.id / NptclIn1Node == PS::Comm::getRank()) tar.push_back(ith); } } } //imp for(PS::F64 x = -1.0 ; x <= 1.0 ; x += dx){ for(PS::F64 y = -1.0 ; y <= 1.0 ; y += dx){ for(PS::F64 z = -1.0 ; z <= 1.0 ; z += dx){ const PS::F64 r = Expand * sqrt(x*x + y*y + z*z) * UnitRadi; if(r >= impRadi || r <= impCoreRadi) continue; Ptcl ith; ith.pos.x = Expand * UnitRadi * x + offset; ith.pos.y = Expand * UnitRadi * y; ith.pos.z = Expand * UnitRadi * z; ith.dens = (impMass - impCoreMass) / (4.0 / 3.0 * math::pi * (impRadi * impRadi * impRadi - impCoreRadi * impCoreRadi * impCoreRadi)); ith.mass = tarMass + impMass; ith.eng = 0.1 * Grav * tarMass / tarRadi; ith.id = id++; ith.setPressure(&Granite); ith.tag = 2; if(ith.id / NptclIn1Node == PS::Comm::getRank()) imp.push_back(ith); } } } for(PS::F64 x = -1.0 ; x <= 1.0 ; x += dx){ for(PS::F64 y = -1.0 ; y <= 1.0 ; y += dx){ for(PS::F64 z = -1.0 ; z <= 1.0 ; z += dx){ const PS::F64 r = Expand * impCoreShrinkFactor * sqrt(x*x + y*y + z*z) * UnitRadi; if(r >= impCoreRadi) continue; Ptcl ith; ith.pos.x = Expand * impCoreShrinkFactor * UnitRadi * x + offset; ith.pos.y = Expand * impCoreShrinkFactor * UnitRadi * y; ith.pos.z = Expand * impCoreShrinkFactor * UnitRadi * z; ith.dens = impCoreMass / (4.0 / 3.0 * math::pi * impCoreRadi * impCoreRadi * impCoreRadi * Corr * Corr * Corr); ith.mass = tarMass + impMass; ith.eng = 0.1 * Grav * tarMass / tarRadi; ith.id = id++; ith.setPressure(&Iron); ith.tag = 3; if(ith.id / NptclIn1Node == PS::Comm::getRank()) imp.push_back(ith); } } } for(PS::U32 i = 0 ; i < tar.size() ; ++ i){ tar[i].mass /= (PS::F64)(Nptcl); } for(PS::U32 i = 0 ; i < imp.size() ; ++ i){ imp[i].mass /= (PS::F64)(Nptcl); } if(createTarget == true){ for(PS::U32 i = 0 ; i < tar.size() ; ++ i){ ptcl.push_back(tar[i]); } }else{ for(PS::U32 i = 0 ; i < imp.size() ; ++ i){ ptcl.push_back(imp[i]); } } const PS::S32 numPtclLocal = ptcl.size(); sph_system.setNumberOfParticleLocal(numPtclLocal); for(PS::U32 i = 0 ; i < ptcl.size() ; ++ i){ sph_system[i] = ptcl[i]; } //Fin. std::cout << "# of ptcls = " << ptcl.size() << std::endl; std::cout << "setup..." << std::endl; } static void setEoS(PS::ParticleSystem<Ptcl>& sph_system){ for(PS::U64 i = 0 ; i < sph_system.getNumberOfParticleLocal() ; ++ i){ if(sph_system[i].tag % 2 == 0){ sph_system[i].setPressure(&Granite); }else{ sph_system[i].setPressure(&Iron); } } } static void addExternalForce(PS::ParticleSystem<Ptcl>& sph_system, system_t& sysinfo){ if(sysinfo.time >= 5000) return; std::cout << "Add Ext. Force!!!" << std::endl; #pragma omp parallel for for(PS::S32 i = 0 ; i < sph_system.getNumberOfParticleLocal() ; ++ i){ sph_system[i].acc += - sph_system[i].vel * 0.05 / sph_system[i].dt; } } }; template <class Ptcl> const double GI<Ptcl>::END_TIME = 1.0e+4;
sum_int.c
//sum.c #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/timeb.h> #include <malloc.h> #define N_RUNS 1000 #define N 120000 // read timer in second double read_timer() { struct timeb tm; ftime(&tm); return (double) tm.time + (double) tm.millitm / 1000.0; } //Create a matrix and a vector and fill with random numbers void init(int *X) { for (int i = 0; i<N; i++) { X[i] = (int)rand()/(int)(RAND_MAX/10.0); } } //Our sum function- what it does is pretty straight-forward. int sum(int *X) { int result = 0; #pragma omp simd reduction(+:result) for (int i = 0; i<N; i++) { result += X[i]; } return result; } // Debug functions int sum_serial(int *X) { int result = 0; for (int i = 0; i<N; i++) { result += X[i]; } return result; } void print_vector(int *vector) { printf("["); for (int i = 0; i<8; i++) { printf("%d ", vector[i]); } puts("]"); } int main(int argc, char **argv) { //Set everything up int *X = malloc(sizeof(int)*N); int result, result_serial; srand(time(NULL)); init(X); double start = read_timer(); for (int i = 0; i<N_RUNS; i++) result = sum(X); double t = (read_timer() - start); double start_serial = read_timer(); for (int i = 0; i<N_RUNS; i++) result_serial = sum_serial(X); double t_serial = (read_timer() - start_serial); print_vector(X); puts("=\n"); printf("SIMD: %d\n", result); puts("---------------------------------"); printf("Serial: %d\n", result_serial); double gflops = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t); double gflops_serial = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t_serial); printf("==================================================================\n"); printf("Performance:\t\t\tRuntime (s)\t GFLOPS\n"); printf("------------------------------------------------------------------\n"); printf("Sum (SIMD):\t\t%4f\t%4f\n", t, gflops); printf("Sum (Serial):\t\t%4f\t%4f\n", t_serial, gflops_serial); printf("Correctness check: %d\n", result_serial - result); free(X); return 0; }
opencl_strip_fmt_plug.c
/* STRIP Password Manager cracker patch for JtR. Hacked together during * September of 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>. * * This software is Copyright (c) 2012 Lukas Odzioba <ukasz@openwall.net> * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com> */ #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_strip; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_strip); #else #include <string.h> #include "aes.h" #ifdef _OPENMP #include <omp.h> #endif #include "arch.h" #include "formats.h" #include "options.h" #include "common.h" #include "stdint.h" #include "misc.h" #include "common-opencl.h" #define FORMAT_LABEL "strip-opencl" #define FORMAT_NAME "STRIP Password Manager" #define ALGORITHM_NAME "PBKDF2-SHA1 OpenCL" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define BINARY_SIZE 0 #define PLAINTEXT_LENGTH 64 #define SALT_SIZE sizeof(struct custom_salt) #define BINARY_ALIGN 1 #define SALT_ALIGN 4 #define ITERATIONS 4000 #define FILE_HEADER_SZ 16 #define SQLITE_FILE_HEADER "SQLite format 3" #define HMAC_SALT_MASK 0x3a #define FAST_PBKDF2_ITER 2 #define SQLITE_MAX_PAGE_SIZE 65536 static struct fmt_tests strip_tests[] = { /* test vector created by STRIP for Windows */ {"$strip$*66cd7a4ff7716f7b86cf587ce18eb39518e096eb152615ada8d007d9f035c20c711e62cbde96d8c3aad2a4658497a6119addc97ed3c970580cd666f301c63ce041a1748ee5c3861ada3cd6ee75b5d68891f731b3c2e3294b08e10ce3c23c2bfac158f8c45d0332791f64d1e3ad55e936d17a42fef5228e713b8188050c9a61c7f026af6203172cf2fc54c8b439e2260d7a00a4156713f92f8466de5c05cd8701e0d3d9cb3f392ae918e6900d5363886d4e1ed7e90da76b180ef9555c1cd358f6d1ee3755a208fee4d5aa1c776a0888200b21a3da6614d5fe2303e78c09563d862d19deecdc9f0ec7fbc015689a74f4eb477d9f22298b1b3f866ca4cb772d74821a1f8d03fd5fd0d020ffd41dd449b431ddf3bbfba3399311d9827be428202ee56e2c2a4e91f3415b4282c691f16cd447cf877b576ab963ea4ea3dc7d8c433febdc36607fd2372c4165abb59e3e75c28142f1f2575ecca6d97a9f782c3410151f8bbcbc65a42fdc59fdc4ecd8214a2bbd3a4562fac21c48f7fc69a4ecbcf664b4e435d7734fde5494e4d80019a0302e22565ed6a49b29cecf81077fd92f0105d18a421e04ee0deaca6389214abc7182db7003da7e267816531010b236eadfea20509718ff743ed5ad2828b6501dd84a371feed26f0514bbda69118a69048ebb71e3e2c54fb918422f1320724a353fe8d81a562197454d2c67443be8a4008a756aec0998386a5fd48e379befe966b42dfa6684ff049a61b51de5f874a12ab7d9ab33dc84738e036e294c22a07bebcc95be9999ab988a1fa1c944ab95be970045accb661249be8cc34fcc0680cb1aff8dfee21f586c571b1d09bf370c6fc131418201e0414acb2e4005b0b6fda1f3d73b7865823a008d1d3f45492a960dbdd6331d78d9e2e6a368f08ee3456b6d78df1d5630f825c536fff60bad23fb164d151d80a03b0c78edbfdee5c7183d7527e289428cf554ad05c9d75011f6b233744f12cd85fbb62f5d1ae22f43946f24a483a64377bf3fa16bf32cea1ab4363ef36206a5989e97ff847e5d645791571b9ecd1db194119b7663897b9175dd9cc123bcc7192eaf56d4a2779c502700e88c5c20b962943084bcdf024dc4f19ca649a860bdbd8f8f9b4a9d03027ae80f4a3168fc030859acb08a871950b024d27306cdc1a408b2b3799bb8c1f4b6ac3593aab42c962c979cd9e6f59d029f8d392315830cfcf4066bf03e0fc5c0f3630e9c796ddb38f51a2992b0a61d6ef115cb34d36c7d94b6c9d49dfe8d064d92b483f12c14fa10bf1170a575e4571836cef0a1fbf9f8b6968abda5e964bb16fd62fde1d1df0f5ee9c68ce568014f46f1717b6cd948b0da9a6f4128da338960dbbcbc9c9c3b486859c06e5e2338db3458646054ccd59bb940c7fc60cda34f633c26dde83bb717b75fefcbd09163f147d59a6524752a47cd94", "openwall"}, /* test vector created by STRIP Password Manager (for Android) */ {"$strip$*78adb0052203efa1bd1b02cac098cc9af1bf7e84ee2eaebaaba156bdcfe729ab12ee7ba8a84e79d11dbd67eee82bcb24be99dbd5db7f4c3a62f188ce4b48edf4ebf6cbf5a5869a61f83fbdb3cb4bf79b3c2c898f422d71eab31afdf3a8d4e97204dedbe7bd8b5e4c891f4880ca917c8b2f67ca06035e7f8db1fae91c45db6a08adf96ec5ddcb9e60b648acf883a7550ea5b67e2d27623e8de315f29cba48b8b1d1bde62283615ab88293b29ad73ae404a42b13e35a95770a504d81e335c00328a6290e411fa2708a697fab7c2d17ff5d0a3fe508118bb43c3d5e72ef563e0ffd337f559085a1373651ca2b8444f4437d8ac0c19aa0a24b248d1d283062afbc3b4ccc9b1861f59518eba771f1d9707affe0222ff946da7c014265ab4ba1f6417dd22d92e4adf5b7e462588f0a42e061a3dad041cbb312d8862aed3cf490df50b710a695517b0c8771a01f82db09231d392d825f5667012e349d2ed787edf8448bbb1ff548bee3a33392cd209e8b6c1de8202f6527d354c3858b5e93790c4807a8967b4c0321ed3a1d09280921650ac33308bd04f35fb72d12ff64a05300053358c5d018a62841290f600f7df0a7371b6fac9b41133e2509cb90f774d02e7202185b9641d063ed38535afb81590bfd5ad9a90107e4ff6d097ac8f35435f307a727f5021f190fc157956414bfce4818a1e5c6af187485683498dcc1d56c074c534a99125c6cfbf5242087c6b0ae10971b0ff6114a93616e1a346a22fcac4c8f6e5c4a19f049bbc7a02d2a31d39548f12440c36dbb253299a11b630e8fd88e7bfe58545d60dce5e8566a0a190d816cb775bd859b8623a7b076bce82c52e9cff6a2d221f9d3fd888ac30c7e3000ba8ed326881ffe911e27bb8982b56caa9a12065721269976517d2862e4a486b7ed143ee42c6566bba04c41c3371220f4843f26e328c33a5fb8450dadc466202ffc5c49cc95827916771e49e0602c3f8468537a81cf2fa1db34c090fccab6254436c05657cf29c3c415bb22a42adeac7870858bf96039b81c42c3d772509fdbe9a94eaf99ee9c59bac3ea97da31e9feac14ed53a0af5c5ebd2e81e40a5140da4f8a44048d5f414b0ba9bfb8024c7abaf5346fde6368162a045d1196f81d55ed746cc6cbd7a7c9cdbfa392279169626437da15a62730c2990772e106a5b84a60edaa6c5b8030e1840aa6361f39a12121a1e33b9e63fb2867d6241de1fb6e2cd1bd9a78c7122258d052ea53a4bff4e097ed49fc17b9ec196780f4c6506e74a5abb10c2545e6f7608d2eefad179d54ad31034576be517affeb3964c65562538dd6ea7566a52c75e4df593895539609a44097cb6d31f438e8f7717ce2bf777c76c22d60b15affeb89f08084e8f316be3f4aefa4fba8ec2cc1dc845c7affbc0ce5ebccdbfde5ebab080a285f02bdfb76c6dbd243e5ee1e5d", "p@$$w0rD"}, {NULL} }; typedef struct { uint32_t length; uint8_t v[PLAINTEXT_LENGTH]; } strip_password; typedef struct { uint32_t v[32/4]; } strip_hash; typedef struct { uint32_t iterations; uint32_t outlen; uint32_t skip_bytes; uint8_t length; uint8_t salt[64]; } strip_salt; static int *cracked; static int any_cracked; static struct custom_salt { unsigned char salt[16]; unsigned char data[1024]; } *cur_salt; static cl_int cl_error; static strip_password *inbuffer; static strip_hash *outbuffer; static strip_salt currentsalt; static cl_mem mem_in, mem_out, mem_setting; static struct fmt_main *self; static size_t insize, outsize, settingsize, cracked_size; #define STEP 0 #define SEED 256 // This file contains auto-tuning routine(s). Has to be included after formats definitions. #include "opencl-autotune.h" #include "memdbg.h" static const char * warn[] = { "xfer: ", ", crypt: ", ", xfer: " }; /* ------- Helper functions ------- */ static size_t get_task_max_work_group_size() { return autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel); } static void create_clobj(size_t gws, struct fmt_main *self) { insize = sizeof(strip_password) * gws; outsize = sizeof(strip_hash) * gws; settingsize = sizeof(strip_salt); cracked_size = sizeof(*cracked) * gws; inbuffer = mem_calloc(1, insize); outbuffer = mem_alloc(outsize); cracked = mem_calloc(1, cracked_size); /// Allocate memory mem_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem in"); mem_setting = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, settingsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem setting"); mem_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem out"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 1, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 2, sizeof(mem_setting), &mem_setting), "Error while setting mem_salt kernel argument"); } static void release_clobj(void) { if (inbuffer) { HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in"); HANDLE_CLERROR(clReleaseMemObject(mem_setting), "Release mem setting"); HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out"); MEM_FREE(inbuffer); MEM_FREE(outbuffer); MEM_FREE(cracked); } } static void done(void) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } static void init(struct fmt_main *_self) { self = _self; opencl_prepare_dev(gpu_id); } static void reset(struct db_main *db) { if (!autotuned) { char build_opts[64]; snprintf(build_opts, sizeof(build_opts), "-DKEYLEN=%d -DSALTLEN=%d -DOUTLEN=%d", PLAINTEXT_LENGTH, (int)sizeof(currentsalt.salt), (int)sizeof(outbuffer->v)); opencl_init("$JOHN/kernels/pbkdf2_hmac_sha1_unsplit_kernel.cl", gpu_id, build_opts); crypt_kernel = clCreateKernel(program[gpu_id], "derive_key", &cl_error); HANDLE_CLERROR(cl_error, "Error creating kernel"); // Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, 0, NULL, warn, 1, self, create_clobj, release_clobj, sizeof(strip_password), 0, db); // Auto tune execution from shared/included code. autotune_run(self, 1, 0, 1000); } } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy; char *keeptr; char *p; if (strncmp(ciphertext, "$strip$*", 8)) return 0; /* handle 'chopped' .pot lines */ if (ldr_isa_pot_source(ciphertext)) return 1; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += 7+1; /* skip over "$strip$" and first '*' */ if ((p = strtokm(ctcopy, "*")) == NULL) /* salt + data */ goto err; if (hexlenl(p) != 2048) goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; char *p; int i; static struct custom_salt *cs; if (!cs) cs = mem_alloc_tiny(sizeof(struct custom_salt), 4); memset(cs, 0, sizeof(struct custom_salt)); ctcopy += 7+1; /* skip over "$strip$" and first '*' */ p = strtokm(ctcopy, "*"); for (i = 0; i < 16; i++) cs->salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; for (; i < 1024; i++) cs->data[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)cs; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; memcpy((char*)currentsalt.salt, cur_salt->salt, 16); currentsalt.length = 16; currentsalt.iterations = ITERATIONS; currentsalt.outlen = 32; currentsalt.skip_bytes = 0; HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_setting, CL_FALSE, 0, settingsize, &currentsalt, 0, NULL, NULL), "Copy salt to gpu"); } #undef set_key static void set_key(char *key, int index) { uint8_t length = strlen(key); if (length > PLAINTEXT_LENGTH) length = PLAINTEXT_LENGTH; inbuffer[index].length = length; memcpy(inbuffer[index].v, key, length); } static char *get_key(int index) { static char ret[PLAINTEXT_LENGTH + 1]; uint8_t length = inbuffer[index].length; memcpy(ret, inbuffer[index].v, length); ret[length] = '\0'; return ret; } /* verify validity of page */ static int verify_page(unsigned char *page1) { uint32_t pageSize; uint32_t usableSize; if (memcmp(page1, SQLITE_FILE_HEADER, 16) != 0) { return -1; } if (page1[19] > 2) { return -1; } if (memcmp(&page1[21], "\100\040\040", 3) != 0) { return -1; } pageSize = (page1[16] << 8) | (page1[17] << 16); if (((pageSize - 1) & pageSize) != 0 || pageSize > SQLITE_MAX_PAGE_SIZE || pageSize <= 256) { return -1; } if ((pageSize & 7) != 0) { return -1; } usableSize = pageSize - page1[20]; if (usableSize < 480) { return -1; } return 0; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; size_t *lws = local_work_size ? &local_work_size : NULL; global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size); if (any_cracked) { memset(cracked, 0, cracked_size); any_cracked = 0; } /// Copy data to gpu BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0, insize, inbuffer, 0, NULL, multi_profilingEvent[0]), "Copy data to gpu"); /// Run kernel BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[1]), "Run kernel"); /// Read the result back BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0, outsize, outbuffer, 0, NULL, multi_profilingEvent[2]), "Copy result back"); if (ocl_autotune_running) return count; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { unsigned char master[32]; unsigned char output[1024]; unsigned char *iv_in; unsigned char iv_out[16]; int size; int page_sz = 1008; /* 1024 - strlen(SQLITE_FILE_HEADER) */ int reserve_sz = 16; /* for HMAC off case */ AES_KEY akey; memcpy(master, outbuffer[index].v, 32); memcpy(output, SQLITE_FILE_HEADER, FILE_HEADER_SZ); size = page_sz - reserve_sz; iv_in = cur_salt->data + size + 16; memcpy(iv_out, iv_in, 16); if (AES_set_decrypt_key(master, 256, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed!\n"); } /* decrypting 24 bytes is enough */ AES_cbc_encrypt(cur_salt->data + 16, output + 16, 24, &akey, iv_out, AES_DECRYPT); if (verify_page(output) == 0) { cracked[index] = 1; #ifdef _OPENMP #pragma omp atomic #endif any_cracked |= 1; } } return count; } static int cmp_all(void *binary, int count) { return any_cracked; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return 1; } struct fmt_main fmt_opencl_strip = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_NOT_EXACT, { NULL }, strip_tests }, { init, done, reset, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
HardTanh.h
// -------------------------------------------------------------------------- // Binary Brain -- binary neural net framework // // Copyright (C) 2018-2019 by Ryuji Fuchikami // https://github.com/ryuz // ryuji.fuchikami@nifty.com // -------------------------------------------------------------------------- #pragma once #include "bb/Manager.h" #include "bb/Binarize.h" namespace bb { // Hard-Tanh template <typename BinType = float, typename RealType = float> class HardTanh : public Binarize<BinType, RealType> { using _super = Binarize<BinType, RealType>; public: static inline std::string ModelName(void) { return "HardTanh"; } static inline std::string ObjectName(void){ return ModelName() + "_" + DataType<BinType>::Name() + "_" + DataType<RealType>::Name(); } std::string GetModelName(void) const override { return ModelName(); } std::string GetObjectName(void) const override { return ObjectName(); } protected: using _super::m_host_only; using _super::m_binary_th; using _super::m_hardtanh_min; using _super::m_hardtanh_max; bool m_binary_mode = false; public: // 生成情報 struct create_t { RealType hardtanh_min = (RealType)-1.0; RealType hardtanh_max = (RealType)+1.0; }; protected: HardTanh(create_t const &create) { m_hardtanh_min = create.hardtanh_min; m_hardtanh_max = create.hardtanh_max; m_binary_th = (m_hardtanh_min + m_hardtanh_max) / (RealType)2; } /** * @brief コマンド処理 * @detail コマンド処理 * @param args コマンド */ void CommandProc(std::vector<std::string> args) override { // バイナリモード設定 if ( args.size() == 2 && args[0] == "binary" ) { m_binary_mode = EvalBool(args[1]); } // HostOnlyモード設定 if (args.size() == 2 && args[0] == "host_only") { m_host_only = EvalBool(args[1]); } } public: ~HardTanh() {} static std::shared_ptr<HardTanh> Create(create_t const &create) { return std::shared_ptr<HardTanh>(new HardTanh(create)); } static std::shared_ptr<HardTanh> Create(RealType hardtanh_min = (RealType)-1, RealType hardtanh_max = (RealType)+1) { create_t create; create.hardtanh_min = hardtanh_min; create.hardtanh_max = hardtanh_max; return Create(create); } #ifdef BB_PYBIND11 static std::shared_ptr<HardTanh> CreatePy(double hardtanh_min = -1.0, double hardtanh_max = +1.0) { create_t create; create.hardtanh_min = (RealType)hardtanh_min; create.hardtanh_max = (RealType)hardtanh_max; return Create(create); } #endif // 1ノードのみForward計算 std::vector<double> ForwardNode(index_t node, std::vector<double> x_vec) const override { if ( m_binary_mode ) { return _super::ForwardNode(node, x_vec); } for ( auto& x : x_vec ) { if ( x <= m_hardtanh_min ) { x = (double)m_hardtanh_min; } if ( x >= m_hardtanh_max ) { x = (double)m_hardtanh_max; } } return x_vec; } /** * @brief forward演算 * @detail forward演算を行う * @param x 入力データ * @param train 学習時にtrueを指定 * @return forward演算結果 */ inline FrameBuffer Forward(FrameBuffer x_buf, bool train = true) override { // binaryモード if ( DataType<BinType>::type == BB_TYPE_BIT || m_binary_mode ) { return _super::Forward(x_buf, train); } BB_ASSERT(x_buf.GetType() == DataType<RealType>::type); // backward用に保存 if ( train ) { this->PushFrameBuffer(x_buf); } // 戻り値の設定 FrameBuffer y_buf(x_buf.GetFrameSize(), x_buf.GetShape(), x_buf.GetType()); #ifdef BB_WITH_CUDA if ( DataType<RealType>::type == BB_TYPE_FP32 && !m_host_only && x_buf.IsDeviceAvailable() && y_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable() ) { // CUDA版 auto ptr_x = x_buf.LockDeviceMemoryConst(); auto ptr_y = y_buf.LockDeviceMemory(); bbcu_fp32_HardTanh_Forward( (float const *)ptr_x.GetAddr(), (float *)ptr_y.GetAddr(), (float )m_hardtanh_min, (float )m_hardtanh_max, (int )y_buf.GetNodeSize(), (int )y_buf.GetFrameSize(), (int )(y_buf.GetFrameStride() / sizeof(float)) ); return y_buf; } #endif { // 汎用版 index_t frame_size = x_buf.GetFrameSize(); index_t node_size = x_buf.GetNodeSize(); auto x_ptr = x_buf.template LockConst<RealType>(); auto y_ptr = y_buf.template Lock<BinType>(); // Hard-Tanh #pragma omp parallel for for (index_t node = 0; node < node_size; ++node) { for (index_t frame = 0; frame < frame_size; ++frame) { auto x = x_ptr.Get(frame, node); if ( x <= m_hardtanh_min ) { x = m_hardtanh_min; } if ( x >= m_hardtanh_max ) { x = m_hardtanh_max; } y_ptr.Set(frame, node, x); } } return y_buf; } } /** * @brief backward演算 * @detail backward演算を行う * * @return backward演算結果 */ inline FrameBuffer Backward(FrameBuffer dy_buf) override { if (dy_buf.Empty()) { return dy_buf; } // binaryモード if ( DataType<BinType>::type == BB_TYPE_BIT || m_binary_mode) { return _super::Backward(dy_buf); } BB_ASSERT(dy_buf.GetType() == DataType<RealType>::type); // 戻り値のサイズ設定 FrameBuffer dx_buf(dy_buf.GetFrameSize(), dy_buf.GetShape(), dy_buf.GetType()); FrameBuffer x_buf = this->PopFrameBuffer(); #ifdef BB_WITH_CUDA if ( DataType<RealType>::type == BB_TYPE_FP32 && !m_host_only && x_buf.IsDeviceAvailable() && dx_buf.IsDeviceAvailable() && dy_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable() ) { // GPU版 auto ptr_x = x_buf.LockDeviceMemoryConst(); auto ptr_dy = dy_buf.LockDeviceMemoryConst(); auto ptr_dx = dx_buf.LockDeviceMemory(true); bbcu_fp32_HardTanh_Backward( (float const *)ptr_x.GetAddr(), (float const *)ptr_dy.GetAddr(), (float *)ptr_dx.GetAddr(), (float )m_hardtanh_min, (float )m_hardtanh_max, (int )dx_buf.GetNodeSize(), (int )dx_buf.GetFrameSize(), (int )(dx_buf.GetFrameStride() / sizeof(float)) ); return dx_buf; } #endif { // 汎用版 index_t frame_size = dx_buf.GetFrameSize(); index_t node_size = dx_buf.GetNodeSize(); auto x_ptr = x_buf.template LockConst<RealType>(); auto dy_ptr = dy_buf.template LockConst<RealType>(); auto dx_ptr = dx_buf.template Lock<RealType>(); // Hard-Tanh #pragma omp parallel for for (index_t node = 0; node < node_size; ++node) { for (index_t frame = 0; frame < frame_size; ++frame) { auto x = x_ptr.Get(frame, node); auto dy = dy_ptr.Get(frame, node); if ( x <= m_hardtanh_min ) { dy = (RealType)0; } if ( x >= m_hardtanh_max ) { dy = (RealType)0; } dx_ptr.Set(frame, node, dy); } } return dx_buf; } } // シリアライズ protected: void DumpObjectData(std::ostream &os) const override { // バージョン std::int64_t ver = 1; bb::SaveValue(os, ver); // 親クラス _super::DumpObjectData(os); // メンバ bb::SaveValue(os, m_binary_mode); } void LoadObjectData(std::istream &is) override { // バージョン std::int64_t ver; bb::LoadValue(is, ver); BB_ASSERT(ver == 1); // 親クラス _super::LoadObjectData(is); // メンバ bb::LoadValue(is, m_binary_mode); } }; } // end of file
image_handler.h
#include "parameters.h" class ImageHandler { public: ros::NodeHandle nh; ros::Publisher pub_image; cv::Mat image_range; cv::Mat image_noise; cv::Mat image_intensity; pcl::PointCloud<PointType>::Ptr cloud_track; ImageHandler() { cloud_track.reset(new pcl::PointCloud<PointType>()); cloud_track->resize(IMAGE_HEIGHT * IMAGE_WIDTH); pub_image = nh.advertise<sensor_msgs::Image>("loop_detector/image_stack", 1); } void cloud_handler(const sensor_msgs::PointCloud2ConstPtr &cloud_msg) { // convert cloud pcl::PointCloud<PointOuster>::Ptr laser_cloud(new pcl::PointCloud<PointOuster>()); pcl::fromROSMsg(*cloud_msg, *laser_cloud); assert((int)laser_cloud->size() % IMAGE_HEIGHT * IMAGE_WIDTH == 0); // reset images image_range = cv::Mat(IMAGE_HEIGHT, IMAGE_WIDTH, CV_8UC1, cv::Scalar(0)); image_noise = cv::Mat(IMAGE_HEIGHT, IMAGE_WIDTH, CV_8UC1, cv::Scalar(0)); image_intensity = cv::Mat(IMAGE_HEIGHT, IMAGE_WIDTH, CV_8UC1, cv::Scalar(0)); #pragma omp parallel for num_threads(NUM_THREADS) for (int u = 0; u < IMAGE_HEIGHT; u++) { for (int v = 0; v < IMAGE_WIDTH; v++) { const auto& pt = laser_cloud->points[u * IMAGE_WIDTH + v]; // extract sensor data float range = std::sqrt(pt.x*pt.x + pt.y*pt.y + pt.z*pt.z); float noise = pt.noise; float intensity = pt.intensity; // limit to (0~255) noise = std::min(noise, 255.0f); intensity = std::min(intensity, 255.0f); // update all images image_range.at<uint8_t>(u, v) = std::min(range * 20, 255.0f); image_noise.at<uint8_t>(u, v) = noise; image_intensity.at<uint8_t>(u, v) = intensity; // update cloud PointType* p = &cloud_track->points[u * IMAGE_WIDTH + v]; if (range >= 0.1) { p->x = pt.x; p->y = pt.y; p->z = pt.z; p->intensity = intensity; } else { p->x = p->y = p->z = p->intensity = 0; } } } if (pub_image.getNumSubscribers() != 0) { // option 1: display intensity image // cv::Mat image_visualization = image_intensity.clone(); // cv::cvtColor(image_visualization, image_visualization, CV_GRAY2RGB); // pubImage(&pub_image, image_visualization, cloud_msg->header, "bgr8"); // option 2: display all images from available lidar channels cv::Mat image_visualization; cv::vconcat(image_noise, image_intensity, image_visualization); cv::vconcat(image_visualization, image_range, image_visualization); cv::cvtColor(image_visualization, image_visualization, CV_GRAY2RGB); cv::putText(image_visualization, "Ambient", cv::Point2f(5, 20 + IMAGE_HEIGHT*0), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(255,0,255), 2); cv::putText(image_visualization, "Intensity", cv::Point2f(5, 20 + IMAGE_HEIGHT*1), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(255,0,255), 2); cv::putText(image_visualization, "Range", cv::Point2f(5, 20 + IMAGE_HEIGHT*2), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(255,0,255), 2); pubImage(&pub_image, image_visualization, cloud_msg->header, "bgr8"); } // static tf in case tf between base_link and lidar is missing static tf::TransformBroadcaster tf_base_to_lidar; static tf::Transform base_to_lidar = tf::Transform(tf::createQuaternionFromRPY(0, 0, 0), tf::Vector3(0, 0, 0)); tf_base_to_lidar.sendTransform(tf::StampedTransform(base_to_lidar, cloud_msg->header.stamp, "base_link", "velodyne")); } void pubImage(ros::Publisher *this_pub, const cv::Mat& this_image, std_msgs::Header this_header, string image_format) { static cv_bridge::CvImage bridge; bridge.header = this_header; bridge.encoding = image_format; bridge.image = this_image; this_pub->publish(bridge.toImageMsg()); } };
parallel.h
#ifndef PARALLEL #define PARALLEL #include "omp.h" void none(long long n, int p) { //vector<bool> numbers(n-1, true); bool * numbers = new bool[n-1]; memset(numbers, true, n-1); long long k = 2; while (k*k <= n) { #pragma omp parallel for num_threads(p) // Mark all multiples of k between k*k and n for (long long i = k*k; i <= n; i += k) { numbers[i-2] = false; } // Set k as the smallest urmarked number > k for(long long i = k+1; i <= n; i++) { if (numbers[i-2] == true) { k = i; break; } } } cout << Utils::countPrimes(numbers, n-1) << ","; delete [] numbers; } void parallel(int improvment, long long n, int p) { struct timespec start, finish; double elapsed; clock_gettime(CLOCK_MONOTONIC, &start); switch (improvment) { case 0: none(n, p); break; } clock_gettime(CLOCK_MONOTONIC, &finish); elapsed = (finish.tv_sec - start.tv_sec); elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0; cout << elapsed << endl; } #endif
transpose.c
/* * */ #include <stdlib.h> #include <complex.h> #include "np_helper.h" /* * matrix a[n,m] */ void NPdtranspose(int n, int m, double *a, double *at) { size_t i, j, j0, j1; for (j0 = 0; j0 < n; j0+=BLOCK_DIM) { j1 = MIN(j0+BLOCK_DIM, n); for (i = 0; i < m; i++) { for (j = j0; j < j1; j++) { at[i*n+j] = a[j*m+i]; } } } } void NPztranspose(int n, int m, double complex *a, double complex *at) { size_t i, j, j0, j1; for (j0 = 0; j0 < n; j0+=BLOCK_DIM) { j1 = MIN(j0+BLOCK_DIM, n); for (i = 0; i < m; i++) { for (j = j0; j < j1; j++) { at[i*n+j] = a[j*m+i]; } } } } void NPdtranspose_021(int *shape, double *a, double *at) { #pragma omp parallel default(none) \ shared(shape, a, at) { int ic; size_t nm = shape[1] * shape[2]; #pragma omp for schedule (static) for (ic = 0; ic < shape[0]; ic++) { NPdtranspose(shape[1], shape[2], a+ic*nm, at+ic*nm); } } } void NPztranspose_021(int *shape, double complex *a, double complex *at) { #pragma omp parallel default(none) \ shared(shape, a, at) { int ic; size_t nm = shape[1] * shape[2]; #pragma omp for schedule (static) for (ic = 0; ic < shape[0]; ic++) { NPztranspose(shape[1], shape[2], a+ic*nm, at+ic*nm); } } } void NPdsymm_sum(int n, double *a, double *out, int hermi) { size_t i, j, j0, j1; double tmp; if (hermi == HERMITIAN || hermi == SYMMETRIC) { TRIU_LOOP(i, j) { tmp = a[i*n+j] + a[j*n+i]; out[i*n+j] = tmp; out[j*n+i] = tmp; } } else { TRIU_LOOP(i, j) { tmp = a[i*n+j] - a[j*n+i]; out[i*n+j] = tmp; out[j*n+i] =-tmp; } } } void NPzhermi_sum(int n, double complex *a, double complex *out, int hermi) { size_t i, j, j0, j1; double complex tmp; if (hermi == HERMITIAN) { TRIU_LOOP(i, j) { tmp = a[i*n+j] + conj(a[j*n+i]); out[i*n+j] = tmp; out[j*n+i] = conj(tmp); } } else if (hermi == SYMMETRIC) { TRIU_LOOP(i, j) { tmp = a[i*n+j] + a[j*n+i]; out[i*n+j] = tmp; out[j*n+i] = tmp; } } else { TRIU_LOOP(i, j) { tmp = a[i*n+j] - conj(a[j*n+i]); out[i*n+j] = tmp; out[j*n+i] =-conj(tmp); } } } void NPdsymm_021_sum(int *shape, double *a, double *out, int hermi) { #pragma omp parallel default(none) \ shared(shape, a, out, hermi) { int ic; size_t nn = shape[1] * shape[1]; #pragma omp for schedule (static) for (ic = 0; ic < shape[0]; ic++) { NPdsymm_sum(shape[1], a+ic*nn, out+ic*nn, hermi); } } } void NPzhermi_021_sum(int *shape, double complex *a, double complex *out, int hermi) { #pragma omp parallel default(none) \ shared(shape, a, out, hermi) { int ic; size_t nn = shape[1] * shape[1]; #pragma omp for schedule (static) for (ic = 0; ic < shape[0]; ic++) { NPzhermi_sum(shape[1], a+ic*nn, out+ic*nn, hermi); } } }
sunmd5_fmt_plug.c
/* * First cut, which was oSSL only, and done in 2 source files, by * Bartavelle (please change to proper cite). * Corrections, and re-write into SSE2, JimF. * * This software was written by Bartavelle <cite> and JimF * jfoug AT cox dot net, in 2012 for CMIYC-12. No copyright is claimed, * and the software is hereby placed in the public domain. In case this * attempt to disclaim copyright and place the software in the public * domain is deemed null and void, then the software is: * Copyright (c) 2012 Bartavelle and JimF and it is hereby released to * the general public under the following terms: * * This software may be modified, redistributed, and used for any * purpose, in source and binary forms, with or without modification. * */ #if FMT_EXTERNS_H extern struct fmt_main fmt_sunmd5; #elif FMT_REGISTERS_H john_register_one(&fmt_sunmd5); #else #include <string.h> #include "os.h" #if (!AC_BUILT || HAVE_UNISTD_H) && !_MSC_VER #include <unistd.h> #endif #include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 2 #endif #endif #include "arch.h" #include "misc.h" #include "options.h" #include "misc.h" #include "params.h" #include "memory.h" #include "common.h" #include "formats.h" #include "loader.h" #include "memory.h" #include "md5.h" #include "simd-intrinsics.h" #include "memdbg.h" /* * these 2 are for testing non-MMX mode. if we * undefine these 2, then we force build oSSL model. */ //#undef SIMD_PARA_MD5 //#undef SIMD_COEF_32 #ifndef MD5_CBLOCK #define MD5_CBLOCK 64 #endif #ifndef MD5_DIGEST_LENGTH #define MD5_DIGEST_LENGTH 16 #endif #define STRINGIZE2(s) #s #define STRINGIZE(s) STRINGIZE2(s) #define PLAINTEXT_LENGTH 120 /* JtR actually only 'uses' 4 byte binaries from this format, but for cmp_exact we need full binary */ #define FULL_BINARY_SIZE 16 #define BINARY_SIZE 4 #define BINARY_ALIGN 4 /* salt==48 allows $md5$ (5) rounds=999999$ (14) salt (16) null(1) (40 allows for 19 byte salt) */ #define SALT_SIZE 40 #define SALT_ALIGN 1 #if SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT SIMD_COEF_32 #define MAX_KEYS_PER_CRYPT (16 * SIMD_COEF_32 * SIMD_PARA_MD5) #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #define FORMAT_LABEL "SunMD5" #define FORMAT_NAME "" #define FORMAT_TAG "$md5$" #define FORMAT_TAG2 "$md5," #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "MD5 " MD5_ALGORITHM_NAME #define BENCHMARK_COMMENT "" // it is salted, but very slow, AND there is no difference between 1 and multi salts, so simply turn off salt benchmarks #define BENCHMARK_LENGTH -1 /* THIS one IS a depricated sun string, but for real: $md5$3UqYqndY$$6P.aaWOoucxxq.l00SS9k0: Sun MD5 "password" */ /* $md5,rounds=5000$GUBv0xjJ$$mSwgIswdjlTY0YxV7HBVm0 passwd This one was the python code from http://packages.python.org/passlib/lib/passlib.hash.sun_md5_crypt.html, but the rounds are busted. */ static struct fmt_tests tests[] = { {"$md5$rounds=904$Vc3VgyFx44iS8.Yu$Scf90iLWN6O6mT9TA06NK/", "test"}, /* from CMIYC-12 */ {"$md5$rounds=904$ZZZig8GS.S0pRNhc$dw5NMYJoxLlnFq4E.phLy.", "Don41dL33"}, {"$md5$rounds=904$zSuVTn567UJLv14u$q2n2ZBFwKg2tElFBIzUq/0", "J4ck!3Wood"}, {"$md5$rounds=904$zuZVga3IOSfOshxU$gkUlHjR6apc6cr.7Bu5tt/", "K!m!M4rt!n"}, {"$md5$rounds=904$/KP7bVaKYTOcplkx$i74NBQdysLaDTUSEu5FtQ.", "people"}, {"$md5$rounds=904$/p4qqfWbTQcUqjNc$leW.8/vzyDpFQxSZrV0x.0", "me"}, {"$md5$rounds=904$wOyGLc0NMRiXJTvI$v69lVSnLif78hZbZWhuEG1", "private"}, // from pass_gen.pl 120 bytes long. {"$md5$rounds=904$Vc3VgyFx44iS8.Yu$mEyEet31IlEkO4HTeobmq0", "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"}, {NULL} }; #ifdef SIMD_PARA_MD5 #define PARA SIMD_PARA_MD5 #else #define PARA 1 #endif #ifdef SIMD_COEF_32 #define COEF SIMD_COEF_32 #define BLK_CNT (PARA*COEF) #if PARA > 1 /* * for para-3 32 bit at MAX_KEYS=1k, 0==281 1==292 2==284 3==284 4==283 5==282 * for para-3 32 bit at MAX_KEYS=512, 0==286 1==287 2==279 3==279 4==278 5==278 * for para-3 32 bit at MAX_KEYS=256, 0==278 1==282 2==276 3==274 4==274 5==274 Above these, the same speed * for para-3 32 bit at MAX_KEYS=128, 0==272 1==277 2==271 3==270 4==271 5==270 * for para-3 32 bit at MAX_KEYS=64, 0==259 1==264 2==264 3==263 4==259 5==270 */ #define MIN_DROP_BACK 1 #else #define MIN_DROP_BACK 1 #endif //#define GETPOS(i, index) ( ((index)&(SIMD_COEF_32-1))*4 + ((i)&(0xffffffff-3))*SIMD_COEF_32 + ((i)&3) ) //#define PARAGETPOS(i, index) ( ((index)&(SIMD_COEF_32-1))*4 + ((i)&(0xffffffff-3))*SIMD_COEF_32 + ((i)&3) + ((index)/SIMD_COEF_32)*SIMD_COEF_32*64 ) // these next 2 defines are same as above, but faster (on my gcc). Speed went fro 282 to 292, about 3.5% improvement. Shifts vs mults. #define GETPOS(i, index) ( (((index)&(SIMD_COEF_32-1))<<2) + (((i)&(0xffffffff-3))*SIMD_COEF_32) + ((i)&3) ) #define PARAGETPOS(i, index) ( (((index)&(SIMD_COEF_32-1))<<2) + (((i)&(0xffffffff-3))*SIMD_COEF_32) + ((i)&3) + (((unsigned int)index/SIMD_COEF_32*SIMD_COEF_32)<<6) ) /* GETPOS0 can be 'faster' if we already have a pointer to the first DWORD in this block. Thus we can do a GETPOS(0,idx), and then multiple GETPOS0(x) and sometimes be faster */ #define GETPOS0(i) ( (((i)&(0xffffffff-3))*SIMD_COEF_32) + ((i)&3) ) /* output buffer for para is only 16 bytes per COEF, vs 64, so it's fewer bytes to jumbo to the next PARA start */ #define PARAGETOUTPOS(i, index) ( (((index)&(SIMD_COEF_32-1))<<2) + (((i)&(0xffffffff-3))*SIMD_COEF_32) + ((i)&3) + (((unsigned int)index/SIMD_COEF_32*SIMD_COEF_32)<<4) ) static unsigned char (*input_buf)[BLK_CNT*MD5_CBLOCK]; static unsigned char (*out_buf)[BLK_CNT*MD5_DIGEST_LENGTH]; static unsigned char (*input_buf_big)[25][BLK_CNT*MD5_CBLOCK]; #else #define COEF 1 #endif /* allocated in init() */ static char (*crypt_out)[FULL_BINARY_SIZE]; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static char *saved_salt; /* minimum number of rounds we do, not including the per-user ones */ #define BASIC_ROUND_COUNT 4096 /* enough to make things interesting */ #define DIGEST_LEN 16 #define ROUND_BUFFER_LEN 64 /* ------------------------------------------------------------------ */ typedef struct { MD5_CTX context; /* working buffer for MD5 algorithm */ unsigned char digest[DIGEST_LEN]; /* where the MD5 digest is stored */ } JTR_ALIGN(MEM_ALIGN_CACHE) Contx, *pConx; static Contx *data; /* * Public domain quotation courtesy of Project Gutenberg. * ftp://metalab.unc.edu/pub/docs/books/gutenberg/etext98/2ws2610.txt * Hamlet III.ii - 1517 bytes, including trailing NUL * ANSI-C string constant concatenation is a requirement here. */ #define constant_phrase_size 1517 static const char constant_phrase[] = "To be, or not to be,--that is the question:--\n" "Whether 'tis nobler in the mind to suffer\n" "The slings and arrows of outrageous fortune\n" "Or to take arms against a sea of troubles,\n" "And by opposing end them?--To die,--to sleep,--\n" "No more; and by a sleep to say we end\n" "The heartache, and the thousand natural shocks\n" "That flesh is heir to,--'tis a consummation\n" "Devoutly to be wish'd. To die,--to sleep;--\n" "To sleep! perchance to dream:--ay, there's the rub;\n" "For in that sleep of death what dreams may come,\n" "When we have shuffled off this mortal coil,\n" "Must give us pause: there's the respect\n" "That makes calamity of so long life;\n" "For who would bear the whips and scorns of time,\n" "The oppressor's wrong, the proud man's contumely,\n" "The pangs of despis'd love, the law's delay,\n" "The insolence of office, and the spurns\n" "That patient merit of the unworthy takes,\n" "When he himself might his quietus make\n" "With a bare bodkin? who would these fardels bear,\n" "To grunt and sweat under a weary life,\n" "But that the dread of something after death,--\n" "The undiscover'd country, from whose bourn\n" "No traveller returns,--puzzles the will,\n" "And makes us rather bear those ills we have\n" "Than fly to others that we know not of?\n" "Thus conscience does make cowards of us all;\n" "And thus the native hue of resolution\n" "Is sicklied o'er with the pale cast of thought;\n" "And enterprises of great pith and moment,\n" "With this regard, their currents turn awry,\n" "And lose the name of action.--Soft you now!\n" "The fair Ophelia!--Nymph, in thy orisons\n" "Be all my sins remember'd.\n"; static unsigned char mod5[0x100]; static void init(struct fmt_main *self) { int i; #ifdef SIMD_COEF_32 int j, k, ngroups = 1; #endif #ifdef _OPENMP int omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #ifdef SIMD_COEF_32 ngroups = omp_t; #endif #endif #ifdef SIMD_COEF_32 /* * allocate SSE2 input and output buffer space. For input's we have * 2 buffers. One does the 'short' 1 block crypts. The other does the * long 25 block crypts. All MUST be aligned to SIMD. */ input_buf = mem_calloc_align(ngroups, sizeof(*input_buf), MEM_ALIGN_CACHE); input_buf_big = mem_calloc_align(ngroups, sizeof(*input_buf_big), MEM_ALIGN_CACHE); out_buf = mem_calloc_align(ngroups, sizeof(*out_buf), MEM_ALIGN_CACHE); /* not super optimal, but only done one time, at program startup, so speed is not important */ for (k = 0; k < ngroups; ++k) { for (i = 0; i < constant_phrase_size; ++i) { for (j = 0; j < BLK_CNT; ++j) input_buf_big[k][(i+16)/64][PARAGETPOS((16+i)%64,j)] = constant_phrase[i]; } } #endif saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); saved_salt = mem_calloc(1, SALT_SIZE + 1); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); data = mem_calloc_align(self->params.max_keys_per_crypt, sizeof(*data), MEM_ALIGN_CACHE); for (i = 0; i < 0x100; i++) mod5[i] = i % 5; } static void done(void) { MEM_FREE(data); MEM_FREE(crypt_out); MEM_FREE(saved_salt); MEM_FREE(saved_key); #ifdef SIMD_COEF_32 MEM_FREE(input_buf); MEM_FREE(input_buf_big); MEM_FREE(out_buf); #endif } static int valid(char *ciphertext, struct fmt_main *self) { char *pos; /* Common prefix. */ if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) && strncmp(ciphertext, FORMAT_TAG2, FORMAT_TAG_LEN)) return 0; ciphertext += FORMAT_TAG_LEN-1; /* Optional rounds. */ if (!strncmp(ciphertext, ",rounds=", 8) || !strncmp(ciphertext, "$rounds=", 8)) { pos = ciphertext += 8; while (*ciphertext >= '0' && *ciphertext <= '9') ciphertext++; /* Accept only numbers from 0 to 999999? */ /* Zero-padding is ok */ if (ciphertext - pos < 1 || ciphertext - pos > 6) return 0; } if (*ciphertext++ != '$') return 0; /* Salt per se. */ pos = ciphertext; while (atoi64[ARCH_INDEX(*ciphertext)] != 0x7F) ciphertext++; /* Upto 16 salt chars? */ if (ciphertext - pos > 16) return 0; /* One or two $ */ if (*ciphertext++ != '$') return 0; if (*ciphertext == '$') ciphertext++; /* Hash per se. */ pos = ciphertext; while (atoi64[ARCH_INDEX(*ciphertext)] != 0x7F) ciphertext++; /* Samples from CMIYC-12 have garbage in padding bits. Hence the check is disabled for now. */ if (ciphertext - pos != 22 /* || atoi64[ARCH_INDEX(*(ciphertext - 1))] & 0x0F */) return 0; /* No garbage at the end */ if (*ciphertext) return 0; return 1; } static long from64 (unsigned char *s, int n) { long l = 0; while (--n >= 0) { l <<= 6; l += atoi64[s[n]]; } return l; } static void *get_binary(char *ciphertext) { static union { char c[FULL_BINARY_SIZE]; uint32_t w[FULL_BINARY_SIZE / sizeof(uint32_t)]; } out; unsigned l; unsigned char *cp; cp = (unsigned char*)strrchr(ciphertext, '$'); ++cp; l = from64(cp, 4); out.c[0] = l>>16; out.c[6] = (l>>8)&0xFF; out.c[12] = l&0xFF; l = from64(&cp[4], 4); out.c[1] = l>>16; out.c[7] = (l>>8)&0xFF; out.c[13] = l&0xFF; l = from64(&cp[8], 4); out.c[2] = l>>16; out.c[8] = (l>>8)&0xFF; out.c[14] = l&0xFF; l = from64(&cp[12], 4); out.c[3] = l>>16; out.c[9] = (l>>8)&0xFF; out.c[15] = l&0xFF; l = from64(&cp[16], 4); out.c[4] = l>>16; out.c[10] = (l>>8)&0xFF; out.c[5] = l&0xFF; l = from64(&cp[20], 2); out.c[11] = l; return out.c; } static void *get_salt(char *ciphertext) { static char out[SALT_SIZE]; char *p = strrchr(ciphertext, '$'); memset(out, 0, sizeof(out)); memcpy(out, ciphertext, p - ciphertext); return out; } static int get_hash_0(int index) { return *((uint32_t*)(crypt_out[index])) & PH_MASK_0; } static int get_hash_1(int index) { return *((uint32_t*)(crypt_out[index])) & PH_MASK_1; } static int get_hash_2(int index) { return *((uint32_t*)(crypt_out[index])) & PH_MASK_2; } static int get_hash_3(int index) { return *((uint32_t*)(crypt_out[index])) & PH_MASK_3; } static int get_hash_4(int index) { return *((uint32_t*)(crypt_out[index])) & PH_MASK_4; } static int get_hash_5(int index) { return *((uint32_t*)(crypt_out[index])) & PH_MASK_5; } static int get_hash_6(int index) { return *((uint32_t*)(crypt_out[index])) & PH_MASK_6; } static int salt_hash(void *salt) { int h; char *sp = (char *)salt; char *cp = strrchr(sp, '$'); if (cp) --cp; else cp = &sp[strlen(sp)-1]; h = atoi64[ARCH_INDEX(*cp--)]; h ^= (unsigned char)*cp--; h <<= 5; h ^= atoi64[ARCH_INDEX(*cp--)]; h ^= (unsigned char)*cp++; return h & (SALT_HASH_SIZE - 1); } static void set_salt(void *salt) { memcpy(saved_salt, salt, SALT_SIZE); } static void set_key(char *key, int index) { strnzcpy(saved_key[index], key, PLAINTEXT_LENGTH + 1); } static char *get_key(int index) { return saved_key[index]; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) if (*((uint32_t*)binary) == *((uint32_t*)crypt_out[index])) return 1; return 0; } static int cmp_one(void *binary, int index) { return *((uint32_t*)binary) == *((uint32_t*)crypt_out[index]); } static int cmp_exact(char *source, int index) { return !memcmp(get_binary(source), crypt_out[index], FULL_BINARY_SIZE); } // inline function, as a macro. #define md5bit_1(d,b) ((d[((b)>>3)&0xF]&(1<<((b)&7))) ? 1 : 0) // md5bit with no conditional logic. #define md5bit_2(d,b) (((d[((b)>>3)&0xF]>>((b)&7)))&1) inline static int md5bit(unsigned char *digest, int bit_num) { return (((digest[((bit_num)>>3)&0xF]>>((bit_num)&7)))&1); #if 0 /* original function from sun code */ int byte_off; int bit_off; bit_num %= 128; /* keep this bounded for convenience */ byte_off = bit_num / 8; bit_off = bit_num % 8; /* return the value of bit N from the digest */ return ((digest[byte_off] & (0x01 << bit_off)) ? 1 : 0); #endif } inline static int coin_step(unsigned char *digest, int i, int j, int shift) { return md5bit(digest, digest[(digest[i] >> mod5[digest[j]]) & 0x0F] >> ((digest[j] >> (digest[i] & 0x07)) & 0x01)) << shift; } #define ROUNDS "rounds=" #define ROUNDSLEN 7 /* * get the integer value after rounds= where ever it occurs in the string. * if the last char after the int is a , or $ that is fine anything else is an * error. */ static unsigned int getrounds(const char *s) { char *r, *p, *e; long val; if (s == NULL) return (0); if ((r = strstr(s, ROUNDS)) == NULL) { return (0); } if (strncmp(r, ROUNDS, ROUNDSLEN) != 0) { return (0); } p = r + ROUNDSLEN; val = strtol(p, &e, 10); /* * An error occurred or there is non-numeric stuff at the end * which isn't one of the crypt(3c) special chars ',' or '$' */ if (val < 0 || !(*e == '\0' || *e == ',' || *e == '$')) { fprintf(stderr, "crypt_sunmd5: invalid rounds specification \"%s\"", s); return (0); } return ((unsigned int)val); } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int idx, group_idx; #ifdef _OPENMP int ngroups = OMP_SCALE * omp_get_max_threads(); #else int ngroups = 1; #endif int group_sz = (count + ngroups - 1) / ngroups; for (idx = 0; idx < count; ++idx) { /* initialise the context */ MD5_Init(&data[idx].context); /* update with the (hopefully entropic) plaintext */ MD5_Update(&data[idx].context, (unsigned char *)saved_key[idx], strlen(saved_key[idx])); /* update with the (publicly known) salt */ MD5_Update(&data[idx].context, (unsigned char *)saved_salt, strlen(saved_salt)); /* compute the digest */ MD5_Final(data[idx].digest, &data[idx].context); } #ifdef _OPENMP #ifdef __INTEL_COMPILER #ifdef SIMD_COEF_32 #pragma omp parallel for default(none) private(idx) shared(ngroups, group_sz, saved_salt, data, input_buf, input_buf_big, out_buf, constant_phrase) #else #pragma omp parallel for default(none) private(idx) shared(ngroups, group_sz, saved_salt, data, constant_phrase) #endif // SIMD_COEF_32 #else #ifdef SIMD_COEF_32 #pragma omp parallel for default(none) private(idx) shared(ngroups, group_sz, saved_salt, data, input_buf, input_buf_big, out_buf) #else #pragma omp parallel for default(none) private(idx) shared(ngroups, group_sz, saved_salt, data) #endif // SIMD_COEF_32 #endif // __INTEL_COMPILER #endif // _OPENMP for (group_idx = 0; group_idx < ngroups; ++group_idx) { int roundasciilen; int round, maxrounds = BASIC_ROUND_COUNT + getrounds(saved_salt); char roundascii[8]; int idx_begin = group_idx * group_sz; int idx_end = idx_begin + group_sz > count ? count : idx_begin + group_sz; #ifdef SIMD_COEF_32 int i, j, zs, zb, zs0, zb0; int bigs[MAX_KEYS_PER_CRYPT], smalls[MAX_KEYS_PER_CRYPT]; int nbig, nsmall; // int zb2; // used in debugging memset(input_buf[group_idx], 0, BLK_CNT*MD5_CBLOCK); #endif /* * now to delay high-speed md5 implementations that have stuff * like code inlining, loops unrolled and table lookup */ /* this is the 'first' sprintf(roundascii,"%d",round); The rest are at the bottom of the loop */ /* some compilers dont allow strcpy inside OMP block with default(none) used */ //strcpy(roundascii, "0"); roundascii[0] = '0'; roundascii[1] = 0; roundasciilen=1; for (round = 0; round < maxrounds; round++) { #ifdef SIMD_COEF_32 nbig = nsmall = 0; #endif /* * now this is computed at bottom of loop (we start properly set at "0", len==1) * ** code replaced** * roundasciilen = sprintf(roundascii, "%d", round); */ for (idx = idx_begin; idx < idx_end; ++idx) { pConx px = &data[idx]; int indirect_a = md5bit(px->digest, round) ? coin_step(px->digest, 1, 4, 0) | coin_step(px->digest, 2, 5, 1) | coin_step(px->digest, 3, 6, 2) | coin_step(px->digest, 4, 7, 3) | coin_step(px->digest, 5, 8, 4) | coin_step(px->digest, 6, 9, 5) | coin_step(px->digest, 7, 10, 6) : coin_step(px->digest, 0, 3, 0) | coin_step(px->digest, 1, 4, 1) | coin_step(px->digest, 2, 5, 2) | coin_step(px->digest, 3, 6, 3) | coin_step(px->digest, 4, 7, 4) | coin_step(px->digest, 5, 8, 5) | coin_step(px->digest, 6, 9, 6); int indirect_b = md5bit(px->digest, round + 64) ? coin_step(px->digest, 9, 12, 0) | coin_step(px->digest, 10, 13, 1) | coin_step(px->digest, 11, 14, 2) | coin_step(px->digest, 12, 15, 3) | coin_step(px->digest, 13, 0, 4) | coin_step(px->digest, 14, 1, 5) | coin_step(px->digest, 15, 2, 6) : coin_step(px->digest, 8, 11, 0) | coin_step(px->digest, 9, 12, 1) | coin_step(px->digest, 10, 13, 2) | coin_step(px->digest, 11, 14, 3) | coin_step(px->digest, 12, 15, 4) | coin_step(px->digest, 13, 0, 5) | coin_step(px->digest, 14, 1, 6); int bit = md5bit(px->digest, indirect_a) ^ md5bit(px->digest, indirect_b); /* xor a coin-toss; if true, mix-in the constant phrase */ #ifndef SIMD_COEF_32 /* * This is the real 'crypt'. Pretty trival, but there are 2 possible sizes * there is a 1 block crypte, and a 25 block crypt. They are chosen based * upon the 'long' coin flip algorithm above. */ /* re-initialise the context */ MD5_Init(&px->context); /* update with the previous digest */ MD5_Update(&px->context, px->digest, sizeof (px->digest)); /* optional, add a constant string. This is what makes the 'long' crypt loops */ if (bit) MD5_Update(&px->context, (unsigned char *) constant_phrase, constant_phrase_size); /* Add a decimal current roundcount */ MD5_Update(&px->context, (unsigned char *) roundascii, roundasciilen); MD5_Final(px->digest, &px->context); #else /* * we do not actually perform the work here. We run through all of the * keys we are working on, and figure out which ones need 'small' buffers * and which ones need large buffers. Then we can group them SIMD_COEF_32*SIMD_PARA_MD5 * at a time, later in the process. */ if (bit) bigs[nbig++] = idx; else smalls[nsmall++] = idx; #endif } #ifdef SIMD_COEF_32 /* * ok, at this time we know what group each element is in. Either a large * crypt, or small one. Now group our crypts up based upon the crypt size * doing COEF*PARA at a time, until we have 2 'partial' buffers left. We * 'waste' some CPU in them, but that is what happens. If there is only 1 or * or 2, we may even drop back and use oSSL, it may be faster than an entire * SSE crypt. We will have to time test, and find where the cut over point is * but likely it will NOT be 0. The cuttover appears to be 1, meaning that 0, * only a 1 limb PARA buffer will not be done (and will fall back to oSSL). This * was for PARA==3 on 32 bit. A much BIGGER difference was in the MAX_KEYS_PER_CRYPT * increasing this does make for more speed, HOWEVER, it also makes for more lost time * if the run is stopped, since ALL of the words in the keys buffer would have to be * redone again (hopefully only redone over the candidates left to test in the input file). * The choice to use 512 MAX_KEYS seems about right. */ /********************************************/ /* get the little ones out of the way first */ /********************************************/ /* first, put the length text, 0x80, and buffer length into the buffer 1 time, not in the loop */ for (j = 0; j < BLK_CNT; ++j) { unsigned char *cpo = &input_buf[group_idx][PARAGETPOS(0, j)]; int k; for (k = 0; k < roundasciilen; ++k) { cpo[GETPOS0(k+16)] = roundascii[k]; } cpo[GETPOS0(k+16)] = 0x80; ((uint32_t*)cpo)[14 * SIMD_COEF_32]=((16+roundasciilen)<<3); } /* now do the 'loop' for the small 1-limb blocks. */ zs = zs0 = zb = zb0 = 0; // zb2 = 0; /* for debugging */ for (i = 0; i < nsmall-MIN_DROP_BACK; i += BLK_CNT) { for (j = 0; j < BLK_CNT && zs < nsmall; ++j) { pConx px = &data[smalls[zs++]]; uint32_t *pi = (uint32_t*)px->digest; uint32_t *po = (uint32_t*)&input_buf[group_idx][PARAGETPOS(0, j)]; /* * digest is flat, input buf is SSE_COEF. * input_buf is po (output) here, we are writing to it. */ po[0] = pi[0]; po[COEF] = pi[1]; po[COEF+COEF] = pi[2]; po[COEF+COEF+COEF] = pi[3]; } SIMDmd5body(input_buf[group_idx], (unsigned int *)out_buf[group_idx], NULL, SSEi_MIXED_IN); /* * we convert from COEF back to flat. since this data will later be used * in non linear order, there is no gain trying to keep it in COEF order */ for (j = 0; j < BLK_CNT && zs0 < nsmall; ++j) { uint32_t *pi, *po; pConx px = &data[smalls[zs0++]]; pi = (uint32_t*)&out_buf[group_idx][PARAGETOUTPOS(0, j)]; po = (uint32_t*)px->digest; po[0] = pi[0]; po[1] = pi[COEF]; po[2] = pi[COEF+COEF]; po[3] = pi[COEF+COEF+COEF]; } } /* this catches any left over small's, and simply uses oSSL */ while (zs < nsmall) { pConx px = &data[smalls[zs++]]; MD5_Init(&px->context); MD5_Update(&px->context, px->digest, sizeof (px->digest)); MD5_Update(&px->context, (unsigned char *) roundascii, roundasciilen); MD5_Final(px->digest, &px->context); } /***************************************************************************** * Now do the big ones. These are more complex that the little ones * (much more complex actually). Here, we have to insert the prior crypt * into the first 16 bytes (just like in the little ones, but then we have * our buffer 'pre-loaded' with a 1517 byte string. we append the text number * after the null byte of that 1517 byte string, then put on the 0x80, and * then put the bit length. NOTE, that this actually is an array of 25 * SSE_PARA buffer blocks, so there is quite a bit more manipluation of where * in the buffer to write this. This is most noted in the text number, where * it spills over from buffer 24 to 25. *****************************************************************************/ /* first, put the length text, 0x80, and buffer length into the buffer 1 time, not in the loop */ for (j = 0; j < BLK_CNT; ++j) { unsigned char *cpo23 = &(input_buf_big[group_idx][23][PARAGETPOS(0, j)]); unsigned char *cpo24 = &(input_buf_big[group_idx][24][PARAGETPOS(0, j)]); *((uint32_t*)cpo24) = 0; /* key clean */ cpo23[GETPOS0(61)] = roundascii[0]; switch(roundasciilen) { case 1: cpo23[GETPOS0(62)] = 0x80; cpo23[GETPOS0(63)] = 0; /* key clean. */ break; case 2: cpo23[GETPOS0(62)] = roundascii[1]; cpo23[GETPOS0(63)] = 0x80; break; case 3: cpo23[GETPOS0(62)] = roundascii[1]; cpo23[GETPOS0(63)] = roundascii[2]; cpo24[0] = 0x80; break; case 4: cpo23[GETPOS0(62)] = roundascii[1]; cpo23[GETPOS0(63)] = roundascii[2]; cpo24[0] = roundascii[3]; cpo24[1] = 0x80; break; case 5: cpo23[GETPOS0(62)] = roundascii[1]; cpo23[GETPOS0(63)] = roundascii[2]; cpo24[0] = roundascii[3]; cpo24[1] = roundascii[4]; cpo24[2] = 0x80; break; case 6: cpo23[GETPOS0(62)] = roundascii[1]; cpo23[GETPOS0(63)] = roundascii[2]; cpo24[0] = roundascii[3]; cpo24[1] = roundascii[4]; cpo24[2] = roundascii[5]; cpo24[3] = 0x80; break; } ((uint32_t*)cpo24)[14*SIMD_COEF_32]=((16+constant_phrase_size+roundasciilen)<<3); } for (i = 0; i < nbig-MIN_DROP_BACK; i += BLK_CNT) { for (j = 0; j < BLK_CNT && zb < nbig; ++j) { pConx px = &data[bigs[zb++]]; uint32_t *pi = (uint32_t *)px->digest; uint32_t *po = (uint32_t*)&input_buf_big[group_idx][0][PARAGETPOS(0, j)]; /* * digest is flat, input buf is SSE_COEF. * input_buf is po (output) here, we are writing to it. */ po[0] = pi[0]; po[COEF] = pi[1]; po[COEF+COEF] = pi[2]; po[COEF+COEF+COEF] = pi[3]; } SIMDmd5body(input_buf_big[group_idx][0], (unsigned int *)out_buf[group_idx], NULL, SSEi_MIXED_IN); for (j = 1; j < 25; ++j) SIMDmd5body(input_buf_big[group_idx][j], (unsigned int *)out_buf[group_idx], (unsigned int *)out_buf[group_idx], SSEi_RELOAD|SSEi_MIXED_IN); for (j = 0; j < BLK_CNT && zb0 < nbig; ++j) { uint32_t *pi, *po; pConx px = &data[bigs[zb0++]]; pi = (uint32_t*)&out_buf[group_idx][PARAGETOUTPOS(0, j)]; po = (uint32_t*)px->digest; po[0] = pi[0]; po[1] = pi[COEF]; po[2] = pi[COEF+COEF]; po[3] = pi[COEF+COEF+COEF]; } } /* this catches any left overs, and simply uses oSSL */ while (zb < nbig) { pConx px = &data[bigs[zb++]]; MD5_Init(&px->context); MD5_Update(&px->context, px->digest, sizeof (px->digest)); MD5_Update(&px->context, (unsigned char *) constant_phrase, constant_phrase_size); MD5_Update(&px->context, (unsigned char *) roundascii, roundasciilen); MD5_Final(px->digest, &px->context); } #endif /* * this is the equivalent of the original code: * roundasciilen = sprintf(roundascii, "%d", round); * that was at the top of this rounds loop. We have moved * it to the bottom. It does compute one 'extra' value that * is never used (5001), but it is faster, and that one * extra value causes no harm. * we do call the sprintf a few times (at 10, 100, 1000, etc) * but we only call it there. */ if (++roundascii[roundasciilen-1] == '9'+1) { int j = roundasciilen-1; if (j > 0) { do { roundascii[j] = '0'; ++roundascii[--j]; } while (j > 0 && roundascii[j] == '9'+1); } if (!j && roundascii[0] == '9'+1) { /* some compilers dont allow sprintf inside OMP block */ //roundasciilen = sprintf(roundascii, "%d", round+1); roundascii[0] = '1'; roundascii[roundasciilen++] = '0'; roundascii[roundasciilen] = 0; } } } } for (idx = 0; idx < count; ++idx) { pConx px = &data[idx]; memcpy(crypt_out[idx], px->digest, FULL_BINARY_SIZE); } return count; } /* * the number of iterations is the sum of a "basic round count" (4096) and * a configurable "per-user round count"; we report the sum as cost */ unsigned int sunmd5_cost(void *salt) { return (unsigned int) (BASIC_ROUND_COUNT + getrounds(salt)); } struct fmt_main fmt_sunmd5 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { /* * sum of a "basic round count" (4096) and * a configurable "per-user round count" */ "iteration count", }, { FORMAT_TAG, FORMAT_TAG2 }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { sunmd5_cost, }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
ic.c
/* * ============================ ic ===================== * IC sets the initial condition * ATMS 502 / CSE 566, Spring 2016 * * Arguments: * * q1 real array IC data. Set 1..nx here; * [0],[nx+1] = ghost zones * if 1 ghost point on each side * dx real grid spacing * i1,i2 integers indices bounding array data * nx integer number of grid points * */ #include <stdio.h> #include <stdlib.h> #include <math.h> void ic(rho,theta_d,u,v,w,p,dx,dy,dz,i1,i2,j1,j2,k1,k2,nx,ny,nz,x0,y0,z0,BC_WIDTH) int i1,i2,j1,j2,k1,k2,nx,ny,nz,BC_WIDTH; float dx,dy,dz,rho[],u[][ny][nz],v[][j2+2][nz],w[][ny][k2+2],p[][ny][nz],theta_d[][ny][nz],x0,y0,z0; { #ifndef M_PI #define M_PI 3.14159265358979323846 #endif int i,j,k,m; float x[nx],y[ny],z[nz],d[nx][ny][nz]; float theta_0 = 300; float g = 9.81; float cp = 1004; float Rd = 287; float P0 = 100000; float T,P,rm; int delta_theta[2],delta_v[2],xstart[2],ystart[2],zstart[2],xradius[2],yradius[2],zradius[2]; float upertur = 2.0; srand(0.0); /*printf(" Enter the first temperature perturbation value \n"); scanf("%d",&delta_theta[0]); printf(" Enter the first temperature perturbation x coordinate \n"); scanf("%d",&xstart[0]); printf(" Enter the first temperature perturbation z coordinate \n"); scanf("%d",&zstart[0]); printf(" Enter the first temperature perturbation x radius \n"); scanf("%d",&xradius[0]); printf(" Enter the first temperature perturbation z radius \n"); scanf("%d",&zradius[0]); printf(" Enter the second temperature perturbation value \n"); scanf("%d",&delta_theta[1]); printf(" Enter the second temperature perturbation x coordinate \n"); scanf("%d",&xstart[1]); printf(" Enter the second temperature perturbation z coordinate \n"); scanf("%d",&zstart[1]); printf(" Enter the second temperature perturbation x radius \n"); scanf("%d",&xradius[1]); printf(" Enter the second temperature perturbation z radius \n"); scanf("%d",&zradius[1]);*/ delta_theta[0] = -25; delta_theta[1] = -25; delta_v[0] = -40; delta_v[1] = 40; xstart[0] = 25; xstart[1] = 14975; ystart[0] = 7525; ystart[1] = 7525; zstart[0] = 1525; zstart[1] = 1525; xradius[0] = 3500; xradius[1] = 3500; yradius[0] = 999999; yradius[1] = 999999; zradius[0] = 1750; zradius[1] = 1750; #pragma omp parallel for shared(u) private(i,j,k) for (i=i1;i<=i2+1;i++) /*u*/ for (j=j1;j<=j2;j++) for (k=k1;k<=k2;k++) { u[i][j][k] = 0; } for (i=i1+2;i<=i2-1;i++) /*u*/ for (j=j1+1;j<=j2-1;j++) for (k=k1+1;k<=k2-1;k++) { u[i][j][k] = u[i][j][k] + upertur * ( rand() / (RAND_MAX + 1.0) ) - upertur/2.0; } #pragma omp parallel for shared(v) private(i,j,k) for (i=i1;i<=i2;i++) /*v*/ for (j=j1-1;j<=j2+1;j++) for (k=k1;k<=k2;k++) { v[i][j][k] = 0; } #pragma omp parallel for shared(w) private(i,j,k) for (i=i1;i<=i2;i++) /*w*/ for (j=j1;j<=j2;j++) for (k=k1;k<=k2+1;k++) { w[i][j][k] = 0; } #pragma omp parallel for shared(p) private(i,j,k) for (i=i1;i<=i2;i++) /*p*/ for (j=j1;j<=j2;j++) for (k=k1;k<=k2;k++) { p[i][j][k] = 0; } for (i=i1;i<=i2;i++) for (j=j1;j<=j2;j++) for (k=k1;k<=k2;k++) { x[i] = dx/2+dx*(i-i1); y[j] = dy/2+dy*(j-j1); z[k] = dz/2+dz*(k-k1); theta_d[i][j][k] = 0; for (m=0;m<2;m++) { rm = sqrt(pow((x[i]-xstart[m])/xradius[m],2.0)+pow((y[j]-ystart[m])/yradius[m],2.0)+pow((z[k]-zstart[m])/zradius[m],2.0)); if (rm <= 1.0) { theta_d[i][j][k] = theta_d[i][j][k] + delta_theta[m]/2.0*(cos(rm*M_PI)+1); } } } for (i=i1;i<=i2;i++) for (j=j1;j<=j2+1;j++) for (k=k1;k<=k2;k++) { x[i] = dx/2+dx*(i-i1); y[j] = dy/2+dy*(j-j1); z[k] = dz/2+dz*(k-k1); for (m=0;m<2;m++) { rm = sqrt(pow((x[i]-xstart[m])/xradius[m],2.0)+pow((y[j]-ystart[m])/yradius[m],2.0)+pow((z[k]-zstart[m])/zradius[m],2.0)); if (rm <= 1.0) { v[i][j][k] = v[i][j][k] + delta_v[m]/2.0*(cos(rm*M_PI)+1); } } } for (k=k1-1;k<=k2+1;k++ ) /*rho*/ { z[k] = dz/2+dz*(k-k1); T = 300.0-g/cp*z[k]; P = P0*pow(T/theta_0,cp/Rd); rho[k] = P/Rd/T; } return; }
phostone.c
// Normal compile // Intel: // mpiicc -fopenmp phostone.c -o phostone // gcc: // mpicc -fopenmp phostone.c -o phostone // // To compile without openmp // Intel: // mpiicc -fopenmp-stubs phostone.c -o purempi // gcc: // mpicc -DSTUBS phostone.c -o purempi // // #ifdef FORCEIT #define _GNU_SOURCE #endif #include <unistd.h> #include <string.h> #include <omp.h> #ifdef NOMPI #define MPI_MAX_LIBRARY_VERSION_STRING 32 #define MPI_MAX_PROCESSOR_NAME 32 #define MPI_Comm int #define MPI_COMM_WORLD 0 #define MPI_INT 0 #define MPI_CHAR 0 #define MPI_DOUBLE 0 #define MPI_Status int void MPI_Get_library_version(char *version, int *vlan) {strcpy(version,"NONE");*vlan=4;}; void MPI_Comm_size(int c, int *numprocs) {*numprocs=1;}; void MPI_Comm_rank(int c, int *numprocs) {*numprocs=0;}; void MPI_Get_processor_name(char *lname, int *resultlen) { gethostname(lname,MPI_MAX_PROCESSOR_NAME); } void MPI_Barrier(int c){} void MPI_Finalize(){} void MPI_Send(void *s ,int c, int t, int f, int tg, int com ){} void MPI_Recv(void *s ,int c, int t, int f, int tg, int com ,void *stat){} void MPI_Bcast(void *r, int c, int t, int f, int com){} void MPI_Comm_split(int oc, int mycolor, int myid, int *node_comm){*node_comm=0;} void MPI_Init(int *argc, char ***argv){} double MPI_Wtime() { return omp_get_wtime();} #else #include <mpi.h> #endif #include <ctype.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <time.h> #include <utmpx.h> // which processor on a node will // print env if requested #ifndef PID #define PID 0 #endif void forceit(int new_id,int new_nodes) ; void dothreads(int full, char *myname, int myid, int mycolor, int new_id); char *trim(char *s); void slowit(int nints, int val); int node_color(); int sched_getcpu(); void ptime() { time_t rawtime; struct tm *timeinfo; char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, 80, "%c", timeinfo); // puts (buffer); printf("%s\n", buffer); } int findcore() { int cpu; #ifdef __APPLE__ cpu = -1; #else cpu = sched_getcpu(); #endif return cpu; } int str_upr(char *cstr) { char *str = cstr; for (; *str; str++) { if (isalpha(*str)) if (*str >= 'a') { *str += 'A' - 'a'; } } return 0; } int str_low(char *cstr) { char *str = cstr; for (; *str; str++) { if (isalpha(*str)) if (*str < 'a') { *str += 'a' - 'A'; } } return 0; } void dohelp(); void dohelp() { /************************************************************ * This is a glorified hello world program. Each processor * prints name, rank, and other information as described below. * ************************************************************/ printf("phostname arguments:\n"); printf(" -h : Print this help message\n"); printf("\n"); printf("no arguments : Print a list of the nodes on which the command is " "run.\n"); printf("\n"); printf(" -f or -1 : Same as no argument but print MPI task id and Thread " "id\n"); printf(" If run with OpenMP threading enabled OMP_NUM_THREADS " "> 1\n"); printf(" there will be a line per MPI task and Thread.\n"); printf("\n"); printf(" -F or -2 : Add columns to tell first MPI task on a node and and " "the\n"); printf(" numbering of tasks on a node. (Hint: pipe this output " "in\n"); printf(" to sort -r\n"); printf("\n"); printf(" -E or -B : Print thread info at 'E'nd of the run or 'B'oth the " "start and end\n"); printf("\n"); printf(" -a : Print a listing of the environmental variables passed " "to\n"); printf(" MPI task. (Hint: use the -l option with SLURM to " "prepend MPI\n"); printf(" task #.)\n"); printf("\n"); printf(" -s ######## : Where ######## is an integer. Sum a bunch on " "integers to slow\n"); printf(" down the program. Should run faster with multiple " "threads.\n"); printf("\n"); printf(" -t ######## : Where is a time in seconds. Sum a bunch on integers " "to slow\n"); printf(" down the program and run for at least the given " "seconds.\n"); printf("\n"); printf(" -T : Print time/date at the beginning/end of the run.\n"); printf("\n"); } /* valid is used to get around an issue in some versions of * MPI that screw up the environmnet passed to programs. Its * usage is not recommended. See: * https://wiki.sei.cmu.edu/confluence/display/c/MEM10-C.+Define+and+use+a+pointer+validation+function * * "The valid() function does not guarantee validity; it only * identifies null pointers and pointers to functions as invalid. * However, it can be used to catch a substantial number of * problems that might otherwise go undetected." */ int valid(void *p) { extern char _etext; return (p != NULL) && ((char *)p > &_etext); } char f1234[128], f1235[128], f1236[128]; int main(int argc, char **argv, char *envp[]) { char *eql; int myid, numprocs, resultlen; int mycolor, new_id, new_nodes; int i, k; MPI_Comm node_comm; char lname[MPI_MAX_PROCESSOR_NAME]; //#ifdef MPI_MAX_LIBRARY_VERSION_STRING char version[MPI_MAX_LIBRARY_VERSION_STRING]; //#else // char version[40]; //#endif char *myname, *cutit; int full, envs, iarg, tn, nt, help, slow, vlan, wait, dotime, when; int nints; double t1, t2, dt; /* Format statements */ // char *f1234="%4.4d %4.4d %18s %4.4d %4.4d // %4.4d\n"; char *f1235="%s %4.4d %4.4d\n"; char *f1236="%s\n"; strcpy(f1234, "%4.4d %4.4d %18s %4.4d %4.4d %4.4d\n"); strcpy(f1235, "%s %4.4d %4.4d\n"); strcpy(f1236, "%s\n"); MPI_Init(&argc, &argv); //#ifdef MPI_MAX_LIBRARY_VERSION_STRING MPI_Get_library_version(version, &vlan); //#else // sprintf(version,"%s","UNDEFINED - consider upgrading"); //#endif MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); MPI_Get_processor_name(lname, &resultlen); /* Get rid of "stuff" from the processor name. */ myname = trim(lname); /* The next line is required for BGQ because the MPI task ID is encoded in the processor name and we don't want it. */ if (strrchr(myname, 32)) myname = strrchr(myname, 32); /* Here we cut off the tail of node name, Summit in this case */ cutit = strstr(myname, ".rc.int.colorado.edu"); if (cutit) cutit[0] = (char)0; slow = 0; wait = 0; /* read in command line args from task 0 */ if (myid == 0) { full = 0; envs = 0; help = 0; dotime = 0; when = 1; if (argc > 1) { for (iarg = 1; iarg < argc; iarg++) { if ((strcmp(argv[iarg], "-h") == 0) || (strcmp(argv[iarg], "--h") == 0) || (strcmp(argv[iarg], "-help") == 0)) help = 1; /**/ if ((strcmp(argv[iarg], "-f") == 0) || (strcmp(argv[iarg], "-1") == 0)) full = 1; /**/ if ((strcmp(argv[iarg], "-F") == 0) || (strcmp(argv[iarg], "-2") == 0)) full = 2; /**/ if (strcmp(argv[iarg], "-s") == 0) slow = 1; /**/ if (strcmp(argv[iarg], "-t") == 0) wait = 1; /**/ if (strcmp(argv[iarg], "-a") == 0) envs = 1; /**/ if (strcmp(argv[iarg], "-T") == 0) dotime = 1; if (strcmp(argv[iarg], "-B") == 0) when = 3; if (strcmp(argv[iarg], "-E") == 0) when = 2; } } } /* send info to all tasks, if doing help doit and quit */ MPI_Bcast(&help, 1, MPI_INT, 0, MPI_COMM_WORLD); if (help == 1) { if (myid == 0) dohelp(); MPI_Finalize(); exit(0); } MPI_Bcast(&full, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&envs, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&when, 1, MPI_INT, 0, MPI_COMM_WORLD); if (myid == 0 && dotime == 1) ptime(); if (myid == 0 && full == 2) { printf("MPI VERSION %s\n", version); printf("task thread node name first task # on node " "core\n"); } /*********/ /* The routine NODE_COLOR will return the same value for all mpi tasks that are running on the same node. We use this to create a new communicator from which we get the numbering of tasks on a node. */ // NODE_COLOR(&mycolor); mycolor = node_color(); MPI_Comm_split(MPI_COMM_WORLD, mycolor, myid, &node_comm); MPI_Comm_rank(node_comm, &new_id); MPI_Comm_size(node_comm, &new_nodes); tn = -1; nt = -1; forceit(new_id,new_nodes); /* Here we print out the information with the format and verbosity determined by the value of full. We do this a task at a time to "hopefully" get a bit better formatting. */ for (i = 0; i < numprocs; i++) { MPI_Barrier(MPI_COMM_WORLD); if (i != myid) continue; if (when == 3) str_low(myname); if (when != 2) dothreads(full, myname, myid, mycolor, new_id); /* here we print out the environment in which a MPI task is running */ /* We try to determine if the passed environment is valid but sometimes * it just does not work and this can crash. Try taking out myid==0 * and setting PID to a nonzero value. */ // if (envs == 1 && new_id==1) { if (envs == 1 && (myid == PID || myid == 0)) { k = 0; if (valid(envp) == 1) { // while(envp[k]) { while (valid(envp[k]) == 1) { if (strlen(envp[k]) > 3) { eql = strchr(envp[k], '='); if (eql == NULL) break; printf("? %d %s\n", myid, envp[k]); } else { break; } // printf("? %d %d\n",myid,k); k++; } } else { printf("? %d %s\n", myid, "Environmnet not set"); } } } if (myid == 0) { dt = 0; if (wait) { slow = 0; for (iarg = 1; iarg < argc; iarg++) { // printf("%s\n",argv[iarg]); if (atof(argv[iarg]) > 0) dt = atof(argv[iarg]); } } } MPI_Bcast(&dt, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); if (dt > 0) { nints = 100000; t1 = MPI_Wtime(); t2 = t1; while (dt > t2 - t1) { for (i = 1; i <= 1000; i++) { slowit(nints, i); } t2 = MPI_Wtime(); } if (myid == 0) printf("total time %10.3f\n", t2 - t1); nints = 0; } if (myid == 0) { nints = 0; if (slow == 1) { for (iarg = 1; iarg < argc; iarg++) { if (atol(argv[iarg]) > 0) nints = atoi(argv[iarg]); } } } MPI_Bcast(&nints, 1, MPI_INT, 0, MPI_COMM_WORLD); if (nints > 0) { t1 = MPI_Wtime(); for (i = 1; i <= 1000; i++) { slowit(nints, i); } t2 = MPI_Wtime(); if (myid == 0) printf("total time %10.3f\n", t2 - t1); } if (myid == 0 && dotime == 1) ptime(); if (when > 1) { for (i = 0; i < numprocs; i++) { MPI_Barrier(MPI_COMM_WORLD); if (i != myid) continue; if (when == 3) str_upr(myname); dothreads(full, myname, myid, mycolor, new_id); } } MPI_Finalize(); return 0; } char *trim(char *s) { int i = 0; int j = strlen(s) - 1; int k = 0; while (isspace(s[i]) && s[i] != '\0') i++; while (isspace(s[j]) && j >= 0) j--; while (i <= j) s[k++] = s[i++]; s[k] = '\0'; return s; } /* ! return a integer which is unique to all mpi ! tasks running on a particular node. It is ! equal to the id of the first MPI task running ! on a node. This can be used to create ! MPI communicators which only contain tasks on ! a node. */ int node_color() { int mycol; MPI_Status status; int xchng, i, n2, myid, numprocs; int nlen; int ie; char *pch; char name[MPI_MAX_PROCESSOR_NAME + 1]; char nlist[MPI_MAX_PROCESSOR_NAME + 1]; MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); MPI_Get_processor_name(name, &nlen); pch = strrchr(name, ' '); if (pch) { ie = strlen(pch + 1); memmove(&name[0], pch + 1, ie + 1); memmove(&nlist[0], pch + 1, ie + 1); } else { strcpy(nlist, name); } mycol = myid; n2 = 1; while (n2 < numprocs) { n2 = n2 * 2; } for (i = 1; i <= n2 - 1; i++) { xchng = i ^ myid; if (xchng <= (numprocs - 1)) { if (myid < xchng) { MPI_Send(name, MPI_MAX_PROCESSOR_NAME, MPI_CHAR, xchng, 12345, MPI_COMM_WORLD); MPI_Recv(nlist, MPI_MAX_PROCESSOR_NAME, MPI_CHAR, xchng, 12345, MPI_COMM_WORLD, &status); } else { MPI_Recv(nlist, MPI_MAX_PROCESSOR_NAME, MPI_CHAR, xchng, 12345, MPI_COMM_WORLD, &status); MPI_Send(name, MPI_MAX_PROCESSOR_NAME, MPI_CHAR, xchng, 12345, MPI_COMM_WORLD); } if (strcmp(nlist, name) == 0 && xchng < mycol) mycol = xchng; } else { /* skip this stage */ } } return mycol; } void slowit(int nints, int val) { int *block; long i, sum; #ifdef VERBOSET double t2, t1; t1 = MPI_Wtime(); #endif block = (int *)malloc(nints * sizeof(int)); #pragma omp parallel for for (i = 0; i < nints; i++) { block[i] = val; } sum = 0; #pragma omp parallel for reduction(+ : sum) for (i = 0; i < nints; i++) { sum = sum + block[i]; } #ifdef VERBOSET t2 = MPI_Wtime(); printf("sum of integers %ld %10.3f\n", sum, t2 - t1); #endif free(block); } #ifdef STUBS int omp_get_thread_num(void) { return 0; } int omp_get_num_threads(void) { return 1; } #endif #ifndef FORCEIT void forceit(int new_id,int new_nodes) {} #endif void dothreads(int full, char *myname, int myid, int mycolor, int new_id) { int nt, tn; #pragma omp parallel { nt = omp_get_num_threads(); if (nt == 0) nt = 1; #pragma omp critical { if (nt < 2) { nt = 1; tn = 0; } else { tn = omp_get_thread_num(); } if (full == 0) { if (tn == 0) printf(f1236, trim(myname)); } if (full == 1) { printf(f1235, trim(myname), myid, tn); } if (full == 2) { printf(f1234, myid, tn, trim(myname), mycolor, new_id, findcore()); } } } } #ifdef FORCEIT #include <pthread.h> #include <errno.h> #define handle_error_en(en, msg) \ do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) void forceit(int new_id,int new_nodes) { int FORCEPROC(int i); int FORCETHREAD(int i); int nt,tn,pcore,tcore,i; #pragma omp parallel { nt = omp_get_num_threads(); } pcore=new_id*nt; i=pcore; // put process on pcore FORCEPROC(i); if (nt == 0) return; #pragma omp parallel { #pragma omp critical { // put threads on cores starting with pcore; tn = omp_get_thread_num(); tcore=tn+pcore; FORCETHREAD(tcore); } } } int FORCETHREAD(int ijk) { int s,j; cpu_set_t cpuset; pthread_t thread; thread = pthread_self(); /* Original set affinity mask to include CPUs 0 to 7. */ CPU_ZERO(&cpuset); printf("ijk=%d\n",ijk); j=ijk; //for (int j = 0; j < 8; j++) CPU_SET(j, &cpuset); // Thread might be a structure not an int so // printing it might not be useful. //printf("%d %d\n",ijk,thread); s = pthread_setaffinity_np(thread, sizeof(cpuset), &cpuset); if (s != 0) handle_error_en(s, "pthread_setaffinity_np"); /* Check the actual affinity mask assigned to the thread. */ s = pthread_getaffinity_np(thread, sizeof(cpuset), &cpuset); if (s != 0) handle_error_en(s, "pthread_getaffinity_np"); //printf("Set returned by pthread_getaffinity_np() contained:\n"); for (int j = 0; j < CPU_SETSIZE; j++) if (CPU_ISSET(j, &cpuset)) { //printf(" CPU %d\n", j); } return(EXIT_SUCCESS); } int FORCEPROC (int core) { int s,bonk; cpu_set_t set; bonk=core; CPU_ZERO(&set); // clear cpu mask CPU_SET(bonk, &set); // set cpu 0 printf("core=%d\n",bonk); s=sched_setaffinity(0, sizeof(cpu_set_t), &set); if (s != 0) handle_error_en(s, "sched_setaffinity"); return(EXIT_SUCCESS); } #endif
enhance.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % EEEEE N N H H AAA N N CCCC EEEEE % % E NN N H H A A NN N C E % % EEE N N N HHHHH AAAAA N N N C EEE % % E N NN H H A A N NN C E % % EEEEE N N H H A A N N CCCC EEEEE % % % % % % MagickCore Image Enhancement Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/accelerate-private.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/cache.h" #include "magick/cache-view.h" #include "magick/channel.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite-private.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/fx.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/histogram.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/opencl.h" #include "magick/opencl-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resample.h" #include "magick/resample-private.h" #include "magick/resource_.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/threshold.h" #include "magick/token.h" #include "magick/xml-tree.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoGammaImage() extract the 'mean' from the image and adjust the image % to try make set its gamma appropriatally. % % The format of the AutoGammaImage method is: % % MagickBooleanType AutoGammaImage(Image *image) % MagickBooleanType AutoGammaImageChannel(Image *image, % const ChannelType channel) % % A description of each parameter follows: % % o image: The image to auto-level % % o channel: The channels to auto-level. If the special 'SyncChannels' % flag is set all given channels is adjusted in the same way using the % mean average of those channels. % */ MagickExport MagickBooleanType AutoGammaImage(Image *image) { return(AutoGammaImageChannel(image,DefaultChannels)); } MagickExport MagickBooleanType AutoGammaImageChannel(Image *image, const ChannelType channel) { double gamma, mean, logmean, sans; MagickStatusType status; logmean=log(0.5); if ((channel & SyncChannels) != 0) { /* Apply gamma correction equally accross all given channels */ (void) GetImageChannelMean(image,channel,&mean,&sans,&image->exception); gamma=log(mean*QuantumScale)/logmean; return(LevelImageChannel(image,channel,0.0,(double) QuantumRange,gamma)); } /* Auto-gamma each channel separateally */ status = MagickTrue; if ((channel & RedChannel) != 0) { (void) GetImageChannelMean(image,RedChannel,&mean,&sans, &image->exception); gamma=log(mean*QuantumScale)/logmean; status&=LevelImageChannel(image,RedChannel,0.0,(double) QuantumRange, gamma); } if ((channel & GreenChannel) != 0) { (void) GetImageChannelMean(image,GreenChannel,&mean,&sans, &image->exception); gamma=log(mean*QuantumScale)/logmean; status&=LevelImageChannel(image,GreenChannel,0.0,(double) QuantumRange, gamma); } if ((channel & BlueChannel) != 0) { (void) GetImageChannelMean(image,BlueChannel,&mean,&sans, &image->exception); gamma=log(mean*QuantumScale)/logmean; status&=LevelImageChannel(image,BlueChannel,0.0,(double) QuantumRange, gamma); } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { (void) GetImageChannelMean(image,OpacityChannel,&mean,&sans, &image->exception); gamma=log(mean*QuantumScale)/logmean; status&=LevelImageChannel(image,OpacityChannel,0.0,(double) QuantumRange, gamma); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { (void) GetImageChannelMean(image,IndexChannel,&mean,&sans, &image->exception); gamma=log(mean*QuantumScale)/logmean; status&=LevelImageChannel(image,IndexChannel,0.0,(double) QuantumRange, gamma); } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoLevelImage() adjusts the levels of a particular image channel by % scaling the minimum and maximum values to the full quantum range. % % The format of the LevelImage method is: % % MagickBooleanType AutoLevelImage(Image *image) % MagickBooleanType AutoLevelImageChannel(Image *image, % const ChannelType channel) % % A description of each parameter follows: % % o image: The image to auto-level % % o channel: The channels to auto-level. If the special 'SyncChannels' % flag is set the min/max/mean value of all given channels is used for % all given channels, to all channels in the same way. % */ MagickExport MagickBooleanType AutoLevelImage(Image *image) { return(AutoLevelImageChannel(image,DefaultChannels)); } MagickExport MagickBooleanType AutoLevelImageChannel(Image *image, const ChannelType channel) { /* Convenience method for a min/max histogram stretch. */ return(MinMaxStretchImage(image,channel,0.0,0.0)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B r i g h t n e s s C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BrightnessContrastImage() changes the brightness and/or contrast of an % image. It converts the brightness and contrast parameters into slope and % intercept and calls a polynomical function to apply to the image. % % The format of the BrightnessContrastImage method is: % % MagickBooleanType BrightnessContrastImage(Image *image, % const double brightness,const double contrast) % MagickBooleanType BrightnessContrastImageChannel(Image *image, % const ChannelType channel,const double brightness, % const double contrast) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o brightness: the brightness percent (-100 .. 100). % % o contrast: the contrast percent (-100 .. 100). % */ MagickExport MagickBooleanType BrightnessContrastImage(Image *image, const double brightness,const double contrast) { MagickBooleanType status; status=BrightnessContrastImageChannel(image,DefaultChannels,brightness, contrast); return(status); } MagickExport MagickBooleanType BrightnessContrastImageChannel(Image *image, const ChannelType channel,const double brightness,const double contrast) { #define BrightnessContastImageTag "BrightnessContast/Image" double alpha, intercept, coefficients[2], slope; MagickBooleanType status; /* Compute slope and intercept. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); alpha=contrast; slope=tan((double) (MagickPI*(alpha/100.0+1.0)/4.0)); if (slope < 0.0) slope=0.0; intercept=brightness/100.0+((100-brightness)/200.0)*(1.0-slope); coefficients[0]=slope; coefficients[1]=intercept; status=FunctionImageChannel(image,channel,PolynomialFunction,2,coefficients, &image->exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r D e c i s i o n L i s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorDecisionListImage() accepts a lightweight Color Correction Collection % (CCC) file which solely contains one or more color corrections and applies % the correction to the image. Here is a sample CCC file: % % <ColorCorrectionCollection xmlns="urn:ASC:CDL:v1.2"> % <ColorCorrection id="cc03345"> % <SOPNode> % <Slope> 0.9 1.2 0.5 </Slope> % <Offset> 0.4 -0.5 0.6 </Offset> % <Power> 1.0 0.8 1.5 </Power> % </SOPNode> % <SATNode> % <Saturation> 0.85 </Saturation> % </SATNode> % </ColorCorrection> % </ColorCorrectionCollection> % % which includes the slop, offset, and power for each of the RGB channels % as well as the saturation. % % The format of the ColorDecisionListImage method is: % % MagickBooleanType ColorDecisionListImage(Image *image, % const char *color_correction_collection) % % A description of each parameter follows: % % o image: the image. % % o color_correction_collection: the color correction collection in XML. % */ MagickExport MagickBooleanType ColorDecisionListImage(Image *image, const char *color_correction_collection) { #define ColorDecisionListCorrectImageTag "ColorDecisionList/Image" typedef struct _Correction { double slope, offset, power; } Correction; typedef struct _ColorCorrection { Correction red, green, blue; double saturation; } ColorCorrection; CacheView *image_view; char token[MaxTextExtent]; ColorCorrection color_correction; const char *content, *p; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; PixelPacket *cdl_map; register ssize_t i; ssize_t y; XMLTreeInfo *cc, *ccc, *sat, *sop; /* Allocate and initialize cdl maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (color_correction_collection == (const char *) NULL) return(MagickFalse); ccc=NewXMLTree((const char *) color_correction_collection,&image->exception); if (ccc == (XMLTreeInfo *) NULL) return(MagickFalse); cc=GetXMLTreeChild(ccc,"ColorCorrection"); if (cc == (XMLTreeInfo *) NULL) { ccc=DestroyXMLTree(ccc); return(MagickFalse); } color_correction.red.slope=1.0; color_correction.red.offset=0.0; color_correction.red.power=1.0; color_correction.green.slope=1.0; color_correction.green.offset=0.0; color_correction.green.power=1.0; color_correction.blue.slope=1.0; color_correction.blue.offset=0.0; color_correction.blue.power=1.0; color_correction.saturation=0.0; sop=GetXMLTreeChild(cc,"SOPNode"); if (sop != (XMLTreeInfo *) NULL) { XMLTreeInfo *offset, *power, *slope; slope=GetXMLTreeChild(sop,"Slope"); if (slope != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(slope); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); switch (i) { case 0: { color_correction.red.slope=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.slope=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.slope=StringToDouble(token, (char **) NULL); break; } } } } offset=GetXMLTreeChild(sop,"Offset"); if (offset != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(offset); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); switch (i) { case 0: { color_correction.red.offset=StringToDouble(token, (char **) NULL); break; } case 1: { color_correction.green.offset=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.offset=StringToDouble(token, (char **) NULL); break; } } } } power=GetXMLTreeChild(sop,"Power"); if (power != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(power); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); switch (i) { case 0: { color_correction.red.power=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.power=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.power=StringToDouble(token, (char **) NULL); break; } } } } } sat=GetXMLTreeChild(cc,"SATNode"); if (sat != (XMLTreeInfo *) NULL) { XMLTreeInfo *saturation; saturation=GetXMLTreeChild(sat,"Saturation"); if (saturation != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(saturation); p=(const char *) content; GetNextToken(p,&p,MaxTextExtent,token); color_correction.saturation=StringToDouble(token,(char **) NULL); } } ccc=DestroyXMLTree(ccc); if (image->debug != MagickFalse) { (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Color Correction Collection:"); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.slope: %g",color_correction.red.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.offset: %g",color_correction.red.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.power: %g",color_correction.red.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.slope: %g",color_correction.green.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.offset: %g",color_correction.green.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.power: %g",color_correction.green.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.slope: %g",color_correction.blue.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.offset: %g",color_correction.blue.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.power: %g",color_correction.blue.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.saturation: %g",color_correction.saturation); } cdl_map=(PixelPacket *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*cdl_map)); if (cdl_map == (PixelPacket *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); for (i=0; i <= (ssize_t) MaxMap; i++) { cdl_map[i].red=ClampToQuantum((MagickRealType) ScaleMapToQuantum(( MagickRealType) (MaxMap*(pow(color_correction.red.slope*i/MaxMap+ color_correction.red.offset,color_correction.red.power))))); cdl_map[i].green=ClampToQuantum((MagickRealType) ScaleMapToQuantum(( MagickRealType) (MaxMap*(pow(color_correction.green.slope*i/MaxMap+ color_correction.green.offset,color_correction.green.power))))); cdl_map[i].blue=ClampToQuantum((MagickRealType) ScaleMapToQuantum(( MagickRealType) (MaxMap*(pow(color_correction.blue.slope*i/MaxMap+ color_correction.blue.offset,color_correction.blue.power))))); } if (image->storage_class == PseudoClass) { /* Apply transfer function to colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { double luma; luma=0.212656*image->colormap[i].red+0.715158*image->colormap[i].green+ 0.072186*image->colormap[i].blue; image->colormap[i].red=ClampToQuantum(luma+color_correction.saturation* cdl_map[ScaleQuantumToMap(image->colormap[i].red)].red-luma); image->colormap[i].green=ClampToQuantum(luma+ color_correction.saturation*cdl_map[ScaleQuantumToMap( image->colormap[i].green)].green-luma); image->colormap[i].blue=ClampToQuantum(luma+color_correction.saturation* cdl_map[ScaleQuantumToMap(image->colormap[i].blue)].blue-luma); } } /* Apply transfer function to image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double luma; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { luma=0.212656*GetPixelRed(q)+0.715158*GetPixelGreen(q)+ 0.072186*GetPixelBlue(q); SetPixelRed(q,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelRed(q))].red-luma))); SetPixelGreen(q,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelGreen(q))].green-luma))); SetPixelBlue(q,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelBlue(q))].blue-luma))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ColorDecisionListImageChannel) #endif proceed=SetImageProgress(image,ColorDecisionListCorrectImageTag, progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); cdl_map=(PixelPacket *) RelinquishMagickMemory(cdl_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClutImage() replaces each color value in the given image, by using it as an % index to lookup a replacement color value in a Color Look UP Table in the % form of an image. The values are extracted along a diagonal of the CLUT % image so either a horizontal or vertial gradient image can be used. % % Typically this is used to either re-color a gray-scale image according to a % color gradient in the CLUT image, or to perform a freeform histogram % (level) adjustment according to the (typically gray-scale) gradient in the % CLUT image. % % When the 'channel' mask includes the matte/alpha transparency channel but % one image has no such channel it is assumed that that image is a simple % gray-scale image that will effect the alpha channel values, either for % gray-scale coloring (with transparent or semi-transparent colors), or % a histogram adjustment of existing alpha channel values. If both images % have matte channels, direct and normal indexing is applied, which is rarely % used. % % The format of the ClutImage method is: % % MagickBooleanType ClutImage(Image *image,Image *clut_image) % MagickBooleanType ClutImageChannel(Image *image, % const ChannelType channel,Image *clut_image) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o clut_image: the color lookup table image for replacement color values. % % o channel: the channel. % */ MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image) { return(ClutImageChannel(image,DefaultChannels,clut_image)); } MagickExport MagickBooleanType ClutImageChannel(Image *image, const ChannelType channel,const Image *clut_image) { #define ClutImageTag "Clut/Image" CacheView *clut_view, *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket *clut_map; register ssize_t i; ssize_t adjust, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clut_image != (Image *) NULL); assert(clut_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsGrayColorspace(clut_image->colorspace) == MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace); clut_map=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1UL, sizeof(*clut_map)); if (clut_map == (MagickPixelPacket *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Clut image. */ status=MagickTrue; progress=0; adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1); exception=(&image->exception); clut_view=AcquireAuthenticCacheView(clut_image,exception); for (i=0; i <= (ssize_t) MaxMap; i++) { GetMagickPixelPacket(clut_image,clut_map+i); status=InterpolateMagickPixelPacket(clut_image,clut_view, UndefinedInterpolatePixel,(double) i*(clut_image->columns-adjust)/MaxMap, (double) i*(clut_image->rows-adjust)/MaxMap,clut_map+i,exception); if (status == MagickFalse) break; } clut_view=DestroyCacheView(clut_view); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickPixelPacket pixel; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); GetMagickPixelPacket(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,q,indexes+x,&pixel); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampPixelRed(clut_map+ ScaleQuantumToMap(GetPixelRed(q)))); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampPixelGreen(clut_map+ ScaleQuantumToMap(GetPixelGreen(q)))); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampPixelBlue(clut_map+ ScaleQuantumToMap(GetPixelBlue(q)))); if ((channel & OpacityChannel) != 0) { if (clut_image->matte == MagickFalse) SetPixelAlpha(q,MagickPixelIntensityToQuantum(clut_map+ ScaleQuantumToMap((Quantum) GetPixelAlpha(q)))); else if (image->matte == MagickFalse) SetPixelOpacity(q,ClampPixelOpacity(clut_map+ ScaleQuantumToMap((Quantum) MagickPixelIntensity(&pixel)))); else SetPixelOpacity(q,ClampPixelOpacity( clut_map+ScaleQuantumToMap(GetPixelOpacity(q)))); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampToQuantum((clut_map+(ssize_t) GetPixelIndex(indexes+x))->index)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ClutImageChannel) #endif proceed=SetImageProgress(image,ClutImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); clut_map=(MagickPixelPacket *) RelinquishMagickMemory(clut_map); if ((clut_image->matte != MagickFalse) && ((channel & OpacityChannel) != 0)) (void) SetImageAlphaChannel(image,ActivateAlphaChannel); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastImage() enhances the intensity differences between the lighter and % darker elements of the image. Set sharpen to a MagickTrue to increase the % image contrast otherwise the contrast is reduced. % % The format of the ContrastImage method is: % % MagickBooleanType ContrastImage(Image *image, % const MagickBooleanType sharpen) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % */ static void Contrast(const int sign,Quantum *red,Quantum *green,Quantum *blue) { double brightness, hue, saturation; /* Enhance contrast: dark color become darker, light color become lighter. */ assert(red != (Quantum *) NULL); assert(green != (Quantum *) NULL); assert(blue != (Quantum *) NULL); hue=0.0; saturation=0.0; brightness=0.0; ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); brightness+=0.5*sign*(0.5*(sin((double) (MagickPI*(brightness-0.5)))+1.0)- brightness); if (brightness > 1.0) brightness=1.0; else if (brightness < 0.0) brightness=0.0; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } MagickExport MagickBooleanType ContrastImage(Image *image, const MagickBooleanType sharpen) { #define ContrastImageTag "Contrast/Image" CacheView *image_view; ExceptionInfo *exception; int sign; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); sign=sharpen != MagickFalse ? 1 : -1; if (image->storage_class == PseudoClass) { /* Contrast enhance colormap. */ for (i=0; i < (ssize_t) image->colors; i++) Contrast(sign,&image->colormap[i].red,&image->colormap[i].green, &image->colormap[i].blue); } /* Contrast enhance image. */ #if defined(MAGICKCORE_OPENCL_SUPPORT) status=AccelerateContrastImage(image,sharpen,&image->exception); if (status != MagickFalse) return status; #endif status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum blue, green, red; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { red=GetPixelRed(q); green=GetPixelGreen(q); blue=GetPixelBlue(q); Contrast(sign,&red,&green,&blue); SetPixelRed(q,red); SetPixelGreen(q,green); SetPixelBlue(q,blue); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ContrastImage) #endif proceed=SetImageProgress(image,ContrastImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastStretchImage() is a simple image enhancement technique that attempts % to improve the contrast in an image by `stretching' the range of intensity % values it contains to span a desired range of values. It differs from the % more sophisticated histogram equalization in that it can only apply a % linear scaling function to the image pixel values. As a result the % `enhancement' is less harsh. % % The format of the ContrastStretchImage method is: % % MagickBooleanType ContrastStretchImage(Image *image, % const char *levels) % MagickBooleanType ContrastStretchImageChannel(Image *image, % const size_t channel,const double black_point, % const double white_point) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o black_point: the black point. % % o white_point: the white point. % % o levels: Specify the levels where the black and white points have the % range of 0 to number-of-pixels (e.g. 1%, 10x90%, etc.). % */ MagickExport MagickBooleanType ContrastStretchImage(Image *image, const char *levels) { double black_point, white_point; GeometryInfo geometry_info; MagickBooleanType status; MagickStatusType flags; /* Parse levels. */ if (levels == (char *) NULL) return(MagickFalse); flags=ParseGeometry(levels,&geometry_info); black_point=geometry_info.rho; white_point=(double) image->columns*image->rows; if ((flags & SigmaValue) != 0) white_point=geometry_info.sigma; if ((flags & PercentValue) != 0) { black_point*=(double) QuantumRange/100.0; white_point*=(double) QuantumRange/100.0; } if ((flags & SigmaValue) == 0) white_point=(double) image->columns*image->rows-black_point; status=ContrastStretchImageChannel(image,DefaultChannels,black_point, white_point); return(status); } MagickExport MagickBooleanType ContrastStretchImageChannel(Image *image, const ChannelType channel,const double black_point,const double white_point) { #define MaxRange(color) ((MagickRealType) ScaleQuantumToMap((Quantum) (color))) #define ContrastStretchImageTag "ContrastStretch/Image" CacheView *image_view; double intensity; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket black, *histogram, white; QuantumPixelPacket *stretch_map; register ssize_t i; ssize_t y; /* Allocate histogram and stretch map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); #if defined(MAGICKCORE_OPENCL_SUPPORT) && 0 /* Call OpenCL version */ status=AccelerateContrastStretchImageChannel(image,channel,black_point, white_point,&image->exception); if (status != MagickFalse) return status; #endif histogram=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1UL, sizeof(*histogram)); stretch_map=(QuantumPixelPacket *) AcquireQuantumMemory(MaxMap+1UL, sizeof(*stretch_map)); if ((histogram == (MagickPixelPacket *) NULL) || (stretch_map == (QuantumPixelPacket *) NULL)) { if (stretch_map != (QuantumPixelPacket *) NULL) stretch_map=(QuantumPixelPacket *) RelinquishMagickMemory(stretch_map); if (histogram != (MagickPixelPacket *) NULL) histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ exception=(&image->exception); if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace); status=MagickTrue; (void) memset(histogram,0,(MaxMap+1)*sizeof(*histogram)); image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict indexes; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); if ((channel & SyncChannels) != 0) for (x=0; x < (ssize_t) image->columns; x++) { Quantum intensity; intensity=ClampToQuantum(GetPixelIntensity(image,p)); histogram[ScaleQuantumToMap(intensity)].red++; histogram[ScaleQuantumToMap(intensity)].green++; histogram[ScaleQuantumToMap(intensity)].blue++; histogram[ScaleQuantumToMap(intensity)].index++; p++; } else for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) histogram[ScaleQuantumToMap(GetPixelRed(p))].red++; if ((channel & GreenChannel) != 0) histogram[ScaleQuantumToMap(GetPixelGreen(p))].green++; if ((channel & BlueChannel) != 0) histogram[ScaleQuantumToMap(GetPixelBlue(p))].blue++; if ((channel & OpacityChannel) != 0) histogram[ScaleQuantumToMap(GetPixelOpacity(p))].opacity++; if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) histogram[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index++; p++; } } /* Find the histogram boundaries by locating the black/white levels. */ black.red=0.0; white.red=MaxRange(QuantumRange); if ((channel & RedChannel) != 0) { intensity=0.0; for (i=0; i <= (ssize_t) MaxMap; i++) { intensity+=histogram[i].red; if (intensity > black_point) break; } black.red=(MagickRealType) i; intensity=0.0; for (i=(ssize_t) MaxMap; i != 0; i--) { intensity+=histogram[i].red; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white.red=(MagickRealType) i; } black.green=0.0; white.green=MaxRange(QuantumRange); if ((channel & GreenChannel) != 0) { intensity=0.0; for (i=0; i <= (ssize_t) MaxMap; i++) { intensity+=histogram[i].green; if (intensity > black_point) break; } black.green=(MagickRealType) i; intensity=0.0; for (i=(ssize_t) MaxMap; i != 0; i--) { intensity+=histogram[i].green; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white.green=(MagickRealType) i; } black.blue=0.0; white.blue=MaxRange(QuantumRange); if ((channel & BlueChannel) != 0) { intensity=0.0; for (i=0; i <= (ssize_t) MaxMap; i++) { intensity+=histogram[i].blue; if (intensity > black_point) break; } black.blue=(MagickRealType) i; intensity=0.0; for (i=(ssize_t) MaxMap; i != 0; i--) { intensity+=histogram[i].blue; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white.blue=(MagickRealType) i; } black.opacity=0.0; white.opacity=MaxRange(QuantumRange); if ((channel & OpacityChannel) != 0) { intensity=0.0; for (i=0; i <= (ssize_t) MaxMap; i++) { intensity+=histogram[i].opacity; if (intensity > black_point) break; } black.opacity=(MagickRealType) i; intensity=0.0; for (i=(ssize_t) MaxMap; i != 0; i--) { intensity+=histogram[i].opacity; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white.opacity=(MagickRealType) i; } black.index=0.0; white.index=MaxRange(QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { intensity=0.0; for (i=0; i <= (ssize_t) MaxMap; i++) { intensity+=histogram[i].index; if (intensity > black_point) break; } black.index=(MagickRealType) i; intensity=0.0; for (i=(ssize_t) MaxMap; i != 0; i--) { intensity+=histogram[i].index; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white.index=(MagickRealType) i; } histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); /* Stretch the histogram to create the stretched image mapping. */ (void) memset(stretch_map,0,(MaxMap+1)*sizeof(*stretch_map)); for (i=0; i <= (ssize_t) MaxMap; i++) { if ((channel & RedChannel) != 0) { if (i < (ssize_t) black.red) stretch_map[i].red=(Quantum) 0; else if (i > (ssize_t) white.red) stretch_map[i].red=QuantumRange; else if (black.red != white.red) stretch_map[i].red=ScaleMapToQuantum((MagickRealType) (MaxMap* (i-black.red)/(white.red-black.red))); } if ((channel & GreenChannel) != 0) { if (i < (ssize_t) black.green) stretch_map[i].green=0; else if (i > (ssize_t) white.green) stretch_map[i].green=QuantumRange; else if (black.green != white.green) stretch_map[i].green=ScaleMapToQuantum((MagickRealType) (MaxMap* (i-black.green)/(white.green-black.green))); } if ((channel & BlueChannel) != 0) { if (i < (ssize_t) black.blue) stretch_map[i].blue=0; else if (i > (ssize_t) white.blue) stretch_map[i].blue= QuantumRange; else if (black.blue != white.blue) stretch_map[i].blue=ScaleMapToQuantum((MagickRealType) (MaxMap* (i-black.blue)/(white.blue-black.blue))); } if ((channel & OpacityChannel) != 0) { if (i < (ssize_t) black.opacity) stretch_map[i].opacity=0; else if (i > (ssize_t) white.opacity) stretch_map[i].opacity=QuantumRange; else if (black.opacity != white.opacity) stretch_map[i].opacity=ScaleMapToQuantum((MagickRealType) (MaxMap* (i-black.opacity)/(white.opacity-black.opacity))); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if (i < (ssize_t) black.index) stretch_map[i].index=0; else if (i > (ssize_t) white.index) stretch_map[i].index=QuantumRange; else if (black.index != white.index) stretch_map[i].index=ScaleMapToQuantum((MagickRealType) (MaxMap* (i-black.index)/(white.index-black.index))); } } /* Stretch the image. */ if (((channel & OpacityChannel) != 0) || (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace))) image->storage_class=DirectClass; if (image->storage_class == PseudoClass) { /* Stretch colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { if ((channel & RedChannel) != 0) { if (black.red != white.red) image->colormap[i].red=stretch_map[ ScaleQuantumToMap(image->colormap[i].red)].red; } if ((channel & GreenChannel) != 0) { if (black.green != white.green) image->colormap[i].green=stretch_map[ ScaleQuantumToMap(image->colormap[i].green)].green; } if ((channel & BlueChannel) != 0) { if (black.blue != white.blue) image->colormap[i].blue=stretch_map[ ScaleQuantumToMap(image->colormap[i].blue)].blue; } if ((channel & OpacityChannel) != 0) { if (black.opacity != white.opacity) image->colormap[i].opacity=stretch_map[ ScaleQuantumToMap(image->colormap[i].opacity)].opacity; } } } /* Stretch image. */ status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { if (black.red != white.red) SetPixelRed(q,stretch_map[ ScaleQuantumToMap(GetPixelRed(q))].red); } if ((channel & GreenChannel) != 0) { if (black.green != white.green) SetPixelGreen(q,stretch_map[ ScaleQuantumToMap(GetPixelGreen(q))].green); } if ((channel & BlueChannel) != 0) { if (black.blue != white.blue) SetPixelBlue(q,stretch_map[ ScaleQuantumToMap(GetPixelBlue(q))].blue); } if ((channel & OpacityChannel) != 0) { if (black.opacity != white.opacity) SetPixelOpacity(q,stretch_map[ ScaleQuantumToMap(GetPixelOpacity(q))].opacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if (black.index != white.index) SetPixelIndex(indexes+x,stretch_map[ ScaleQuantumToMap(GetPixelIndex(indexes+x))].index); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ContrastStretchImageChannel) #endif proceed=SetImageProgress(image,ContrastStretchImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); stretch_map=(QuantumPixelPacket *) RelinquishMagickMemory(stretch_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n h a n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EnhanceImage() applies a digital filter that improves the quality of a % noisy image. % % The format of the EnhanceImage method is: % % Image *EnhanceImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception) { #define EnhancePixel(weight) \ mean=QuantumScale*((double) GetPixelRed(r)+pixel.red)/2.0; \ distance=QuantumScale*((double) GetPixelRed(r)-pixel.red); \ distance_squared=(4.0+mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelGreen(r)+pixel.green)/2.0; \ distance=QuantumScale*((double) GetPixelGreen(r)-pixel.green); \ distance_squared+=(7.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlue(r)+pixel.blue)/2.0; \ distance=QuantumScale*((double) GetPixelBlue(r)-pixel.blue); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelOpacity(r)+pixel.opacity)/2.0; \ distance=QuantumScale*((double) GetPixelOpacity(r)-pixel.opacity); \ distance_squared+=(5.0-mean)*distance*distance; \ if (distance_squared < 0.069) \ { \ aggregate.red+=(weight)*GetPixelRed(r); \ aggregate.green+=(weight)*GetPixelGreen(r); \ aggregate.blue+=(weight)*GetPixelBlue(r); \ aggregate.opacity+=(weight)*GetPixelOpacity(r); \ total_weight+=(weight); \ } \ r++; #define EnhanceImageTag "Enhance/Image" CacheView *enhance_view, *image_view; Image *enhance_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; ssize_t y; /* Initialize enhanced image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((image->columns < 5) || (image->rows < 5)) return((Image *) NULL); enhance_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (enhance_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(enhance_image,DirectClass) == MagickFalse) { InheritException(exception,&enhance_image->exception); enhance_image=DestroyImage(enhance_image); return((Image *) NULL); } /* Enhance image. */ status=MagickTrue; progress=0; (void) memset(&zero,0,sizeof(zero)); image_view=AcquireAuthenticCacheView(image,exception); enhance_view=AcquireAuthenticCacheView(enhance_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,enhance_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; /* Read another scan line. */ if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception); q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double distance, distance_squared, mean, total_weight; MagickPixelPacket aggregate; PixelPacket pixel; register const PixelPacket *magick_restrict r; /* Compute weighted average of target pixel color components. */ aggregate=zero; total_weight=0.0; r=p+2*(image->columns+4)+2; pixel=(*r); r=p; EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); r=p+(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+2*(image->columns+4); EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0); EnhancePixel(40.0); EnhancePixel(10.0); r=p+3*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+4*(image->columns+4); EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); if (total_weight > MagickEpsilon) { SetPixelRed(q,(aggregate.red+(total_weight/2)-1)/total_weight); SetPixelGreen(q,(aggregate.green+(total_weight/2)-1)/total_weight); SetPixelBlue(q,(aggregate.blue+(total_weight/2)-1)/total_weight); SetPixelOpacity(q,(aggregate.opacity+(total_weight/2)-1)/ total_weight); } p++; q++; } if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EnhanceImage) #endif proceed=SetImageProgress(image,EnhanceImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } enhance_view=DestroyCacheView(enhance_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) enhance_image=DestroyImage(enhance_image); return(enhance_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E q u a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EqualizeImage() applies a histogram equalization to the image. % % The format of the EqualizeImage method is: % % MagickBooleanType EqualizeImage(Image *image) % MagickBooleanType EqualizeImageChannel(Image *image, % const ChannelType channel) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % */ MagickExport MagickBooleanType EqualizeImage(Image *image) { return(EqualizeImageChannel(image,DefaultChannels)); } MagickExport MagickBooleanType EqualizeImageChannel(Image *image, const ChannelType channel) { #define EqualizeImageTag "Equalize/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket black, *histogram, intensity, *map, white; QuantumPixelPacket *equalize_map; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); #if defined(MAGICKCORE_OPENCL_SUPPORT) /* Call OpenCL version */ status=AccelerateEqualizeImage(image,channel,&image->exception); if (status != MagickFalse) return status; #endif /* Allocate and initialize histogram arrays. */ equalize_map=(QuantumPixelPacket *) AcquireQuantumMemory(MaxMap+1UL, sizeof(*equalize_map)); histogram=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1UL, sizeof(*histogram)); map=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*map)); if ((equalize_map == (QuantumPixelPacket *) NULL) || (histogram == (MagickPixelPacket *) NULL) || (map == (MagickPixelPacket *) NULL)) { if (map != (MagickPixelPacket *) NULL) map=(MagickPixelPacket *) RelinquishMagickMemory(map); if (histogram != (MagickPixelPacket *) NULL) histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (equalize_map != (QuantumPixelPacket *) NULL) equalize_map=(QuantumPixelPacket *) RelinquishMagickMemory( equalize_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ (void) memset(histogram,0,(MaxMap+1)*sizeof(*histogram)); exception=(&image->exception); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); if ((channel & SyncChannels) != 0) for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType intensity=GetPixelIntensity(image,p); histogram[ScaleQuantumToMap(ClampToQuantum(intensity))].red++; p++; } else for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) histogram[ScaleQuantumToMap(GetPixelRed(p))].red++; if ((channel & GreenChannel) != 0) histogram[ScaleQuantumToMap(GetPixelGreen(p))].green++; if ((channel & BlueChannel) != 0) histogram[ScaleQuantumToMap(GetPixelBlue(p))].blue++; if ((channel & OpacityChannel) != 0) histogram[ScaleQuantumToMap(GetPixelOpacity(p))].opacity++; if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) histogram[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index++; p++; } } image_view=DestroyCacheView(image_view); /* Integrate the histogram to get the equalization map. */ (void) memset(&intensity,0,sizeof(intensity)); for (i=0; i <= (ssize_t) MaxMap; i++) { if ((channel & SyncChannels) != 0) { intensity.red+=histogram[i].red; map[i]=intensity; continue; } if ((channel & RedChannel) != 0) intensity.red+=histogram[i].red; if ((channel & GreenChannel) != 0) intensity.green+=histogram[i].green; if ((channel & BlueChannel) != 0) intensity.blue+=histogram[i].blue; if ((channel & OpacityChannel) != 0) intensity.opacity+=histogram[i].opacity; if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) intensity.index+=histogram[i].index; map[i]=intensity; } black=map[0]; white=map[(int) MaxMap]; (void) memset(equalize_map,0,(MaxMap+1)*sizeof(*equalize_map)); for (i=0; i <= (ssize_t) MaxMap; i++) { if ((channel & SyncChannels) != 0) { if (white.red != black.red) equalize_map[i].red=ScaleMapToQuantum((MagickRealType) ((MaxMap* (map[i].red-black.red))/(white.red-black.red))); continue; } if (((channel & RedChannel) != 0) && (white.red != black.red)) equalize_map[i].red=ScaleMapToQuantum((MagickRealType) ((MaxMap* (map[i].red-black.red))/(white.red-black.red))); if (((channel & GreenChannel) != 0) && (white.green != black.green)) equalize_map[i].green=ScaleMapToQuantum((MagickRealType) ((MaxMap* (map[i].green-black.green))/(white.green-black.green))); if (((channel & BlueChannel) != 0) && (white.blue != black.blue)) equalize_map[i].blue=ScaleMapToQuantum((MagickRealType) ((MaxMap* (map[i].blue-black.blue))/(white.blue-black.blue))); if (((channel & OpacityChannel) != 0) && (white.opacity != black.opacity)) equalize_map[i].opacity=ScaleMapToQuantum((MagickRealType) ((MaxMap* (map[i].opacity-black.opacity))/(white.opacity-black.opacity))); if ((((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) && (white.index != black.index)) equalize_map[i].index=ScaleMapToQuantum((MagickRealType) ((MaxMap* (map[i].index-black.index))/(white.index-black.index))); } histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); map=(MagickPixelPacket *) RelinquishMagickMemory(map); if (image->storage_class == PseudoClass) { /* Equalize colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { if ((channel & SyncChannels) != 0) { if (white.red != black.red) { image->colormap[i].red=equalize_map[ ScaleQuantumToMap(image->colormap[i].red)].red; image->colormap[i].green=equalize_map[ ScaleQuantumToMap(image->colormap[i].green)].red; image->colormap[i].blue=equalize_map[ ScaleQuantumToMap(image->colormap[i].blue)].red; image->colormap[i].opacity=equalize_map[ ScaleQuantumToMap(image->colormap[i].opacity)].red; } continue; } if (((channel & RedChannel) != 0) && (white.red != black.red)) image->colormap[i].red=equalize_map[ ScaleQuantumToMap(image->colormap[i].red)].red; if (((channel & GreenChannel) != 0) && (white.green != black.green)) image->colormap[i].green=equalize_map[ ScaleQuantumToMap(image->colormap[i].green)].green; if (((channel & BlueChannel) != 0) && (white.blue != black.blue)) image->colormap[i].blue=equalize_map[ ScaleQuantumToMap(image->colormap[i].blue)].blue; if (((channel & OpacityChannel) != 0) && (white.opacity != black.opacity)) image->colormap[i].opacity=equalize_map[ ScaleQuantumToMap(image->colormap[i].opacity)].opacity; } } /* Equalize image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & SyncChannels) != 0) { if (white.red != black.red) { SetPixelRed(q,equalize_map[ ScaleQuantumToMap(GetPixelRed(q))].red); SetPixelGreen(q,equalize_map[ ScaleQuantumToMap(GetPixelGreen(q))].red); SetPixelBlue(q,equalize_map[ ScaleQuantumToMap(GetPixelBlue(q))].red); SetPixelOpacity(q,equalize_map[ ScaleQuantumToMap(GetPixelOpacity(q))].red); if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,equalize_map[ ScaleQuantumToMap(GetPixelIndex(indexes+x))].red); } q++; continue; } if (((channel & RedChannel) != 0) && (white.red != black.red)) SetPixelRed(q,equalize_map[ ScaleQuantumToMap(GetPixelRed(q))].red); if (((channel & GreenChannel) != 0) && (white.green != black.green)) SetPixelGreen(q,equalize_map[ ScaleQuantumToMap(GetPixelGreen(q))].green); if (((channel & BlueChannel) != 0) && (white.blue != black.blue)) SetPixelBlue(q,equalize_map[ ScaleQuantumToMap(GetPixelBlue(q))].blue); if (((channel & OpacityChannel) != 0) && (white.opacity != black.opacity)) SetPixelOpacity(q,equalize_map[ ScaleQuantumToMap(GetPixelOpacity(q))].opacity); if ((((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) && (white.index != black.index)) SetPixelIndex(indexes+x,equalize_map[ ScaleQuantumToMap(GetPixelIndex(indexes+x))].index); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EqualizeImageChannel) #endif proceed=SetImageProgress(image,EqualizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); equalize_map=(QuantumPixelPacket *) RelinquishMagickMemory(equalize_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GammaImage() gamma-corrects a particular image channel. The same % image viewed on different devices will have perceptual differences in the % way the image's intensities are represented on the screen. Specify % individual gamma levels for the red, green, and blue channels, or adjust % all three with the gamma parameter. Values typically range from 0.8 to 2.3. % % You can also reduce the influence of a particular channel with a gamma % value of 0. % % The format of the GammaImage method is: % % MagickBooleanType GammaImage(Image *image,const char *level) % MagickBooleanType GammaImageChannel(Image *image, % const ChannelType channel,const double gamma) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o level: the image gamma as a string (e.g. 1.6,1.2,1.0). % % o gamma: the image gamma. % */ static inline double gamma_pow(const double value,const double gamma) { return(value < 0.0 ? value : pow(value,gamma)); } MagickExport MagickBooleanType GammaImage(Image *image,const char *level) { GeometryInfo geometry_info; MagickPixelPacket gamma; MagickStatusType flags, status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (level == (char *) NULL) return(MagickFalse); flags=ParseGeometry(level,&geometry_info); gamma.red=geometry_info.rho; gamma.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) gamma.green=gamma.red; gamma.blue=geometry_info.xi; if ((flags & XiValue) == 0) gamma.blue=gamma.red; if ((gamma.red == 1.0) && (gamma.green == 1.0) && (gamma.blue == 1.0)) return(MagickTrue); if ((gamma.red == gamma.green) && (gamma.green == gamma.blue)) status=GammaImageChannel(image,(ChannelType) (RedChannel | GreenChannel | BlueChannel),(double) gamma.red); else { status=GammaImageChannel(image,RedChannel,(double) gamma.red); status&=GammaImageChannel(image,GreenChannel,(double) gamma.green); status&=GammaImageChannel(image,BlueChannel,(double) gamma.blue); } return(status != 0 ? MagickTrue : MagickFalse); } MagickExport MagickBooleanType GammaImageChannel(Image *image, const ChannelType channel,const double gamma) { #define GammaCorrectImageTag "GammaCorrect/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; Quantum *gamma_map; register ssize_t i; ssize_t y; /* Allocate and initialize gamma maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (gamma == 1.0) return(MagickTrue); gamma_map=(Quantum *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*gamma_map)); if (gamma_map == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(gamma_map,0,(MaxMap+1)*sizeof(*gamma_map)); if (gamma != 0.0) for (i=0; i <= (ssize_t) MaxMap; i++) gamma_map[i]=ClampToQuantum((MagickRealType) ScaleMapToQuantum(( MagickRealType) (MaxMap*pow((double) i/MaxMap,1.0/gamma)))); if (image->storage_class == PseudoClass) { /* Gamma-correct colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { #if !defined(MAGICKCORE_HDRI_SUPPORT) if ((channel & RedChannel) != 0) image->colormap[i].red=gamma_map[ScaleQuantumToMap( image->colormap[i].red)]; if ((channel & GreenChannel) != 0) image->colormap[i].green=gamma_map[ScaleQuantumToMap( image->colormap[i].green)]; if ((channel & BlueChannel) != 0) image->colormap[i].blue=gamma_map[ScaleQuantumToMap( image->colormap[i].blue)]; if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) image->colormap[i].opacity=gamma_map[ScaleQuantumToMap( image->colormap[i].opacity)]; else image->colormap[i].opacity=QuantumRange-gamma_map[ ScaleQuantumToMap((Quantum) (QuantumRange- image->colormap[i].opacity))]; } #else if ((channel & RedChannel) != 0) image->colormap[i].red=QuantumRange*gamma_pow(QuantumScale* image->colormap[i].red,1.0/gamma); if ((channel & GreenChannel) != 0) image->colormap[i].green=QuantumRange*gamma_pow(QuantumScale* image->colormap[i].green,1.0/gamma); if ((channel & BlueChannel) != 0) image->colormap[i].blue=QuantumRange*gamma_pow(QuantumScale* image->colormap[i].blue,1.0/gamma); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) image->colormap[i].opacity=QuantumRange*gamma_pow(QuantumScale* image->colormap[i].opacity,1.0/gamma); else image->colormap[i].opacity=QuantumRange-QuantumRange*gamma_pow( QuantumScale*(QuantumRange-image->colormap[i].opacity),1.0/ gamma); } #endif } } /* Gamma-correct image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { #if !defined(MAGICKCORE_HDRI_SUPPORT) if ((channel & SyncChannels) != 0) { SetPixelRed(q,gamma_map[ScaleQuantumToMap(GetPixelRed(q))]); SetPixelGreen(q,gamma_map[ScaleQuantumToMap(GetPixelGreen(q))]); SetPixelBlue(q,gamma_map[ScaleQuantumToMap(GetPixelBlue(q))]); } else { if ((channel & RedChannel) != 0) SetPixelRed(q,gamma_map[ScaleQuantumToMap(GetPixelRed(q))]); if ((channel & GreenChannel) != 0) SetPixelGreen(q,gamma_map[ScaleQuantumToMap(GetPixelGreen(q))]); if ((channel & BlueChannel) != 0) SetPixelBlue(q,gamma_map[ScaleQuantumToMap(GetPixelBlue(q))]); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,gamma_map[ScaleQuantumToMap( GetPixelOpacity(q))]); else SetPixelAlpha(q,gamma_map[ScaleQuantumToMap((Quantum) GetPixelAlpha(q))]); } } #else if ((channel & SyncChannels) != 0) { SetPixelRed(q,QuantumRange*gamma_pow(QuantumScale*GetPixelRed(q), 1.0/gamma)); SetPixelGreen(q,QuantumRange*gamma_pow(QuantumScale*GetPixelGreen(q), 1.0/gamma)); SetPixelBlue(q,QuantumRange*gamma_pow(QuantumScale*GetPixelBlue(q), 1.0/gamma)); } else { if ((channel & RedChannel) != 0) SetPixelRed(q,QuantumRange*gamma_pow(QuantumScale*GetPixelRed(q), 1.0/gamma)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,QuantumRange*gamma_pow(QuantumScale* GetPixelGreen(q),1.0/gamma)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,QuantumRange*gamma_pow(QuantumScale*GetPixelBlue(q), 1.0/gamma)); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,QuantumRange*gamma_pow(QuantumScale* GetPixelOpacity(q),1.0/gamma)); else SetPixelAlpha(q,QuantumRange*gamma_pow(QuantumScale* GetPixelAlpha(q),1.0/gamma)); } } #endif q++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,gamma_map[ScaleQuantumToMap( GetPixelIndex(indexes+x))]); if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GammaImageChannel) #endif proceed=SetImageProgress(image,GammaCorrectImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); gamma_map=(Quantum *) RelinquishMagickMemory(gamma_map); if (image->gamma != 0.0) image->gamma*=gamma; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G r a y s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GrayscaleImage() converts the colors in the reference image to gray. % % The format of the GrayscaleImageChannel method is: % % MagickBooleanType GrayscaleImage(Image *image, % const PixelIntensityMethod method) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % */ MagickExport MagickBooleanType GrayscaleImage(Image *image, const PixelIntensityMethod method) { #define GrayscaleImageTag "Grayscale/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { if (SyncImage(image) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); } /* Grayscale image. */ /* call opencl version */ #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateGrayscaleImage(image,method,&image->exception) != MagickFalse) { image->intensity=method; image->type=GrayscaleType; if ((method == Rec601LuminancePixelIntensityMethod) || (method == Rec709LuminancePixelIntensityMethod)) return(SetImageColorspace(image,LinearGRAYColorspace)); return(SetImageColorspace(image,GRAYColorspace)); } #endif status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType blue, green, intensity, red; red=(MagickRealType) q->red; green=(MagickRealType) q->green; blue=(MagickRealType) q->blue; intensity=0.0; switch (method) { case AveragePixelIntensityMethod: { intensity=(red+green+blue)/3.0; break; } case BrightnessPixelIntensityMethod: { intensity=MagickMax(MagickMax(red,green),blue); break; } case LightnessPixelIntensityMethod: { intensity=(MagickMin(MagickMin(red,green),blue)+ MagickMax(MagickMax(red,green),blue))/2.0; break; } case MSPixelIntensityMethod: { intensity=(MagickRealType) (((double) red*red+green*green+ blue*blue)/(3.0*QuantumRange)); break; } case Rec601LumaPixelIntensityMethod: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec601LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec709LumaPixelIntensityMethod: default: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case Rec709LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case RMSPixelIntensityMethod: { intensity=(MagickRealType) (sqrt((double) red*red+green*green+ blue*blue)/sqrt(3.0)); break; } } SetPixelGray(q,ClampToQuantum(intensity)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GrayscaleImageChannel) #endif proceed=SetImageProgress(image,GrayscaleImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); image->intensity=method; image->type=GrayscaleType; if ((method == Rec601LuminancePixelIntensityMethod) || (method == Rec709LuminancePixelIntensityMethod)) return(SetImageColorspace(image,LinearGRAYColorspace)); return(SetImageColorspace(image,GRAYColorspace)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H a l d C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % HaldClutImage() applies a Hald color lookup table to the image. A Hald % color lookup table is a 3-dimensional color cube mapped to 2 dimensions. % Create it with the HALD coder. You can apply any color transformation to % the Hald image and then use this method to apply the transform to the % image. % % The format of the HaldClutImage method is: % % MagickBooleanType HaldClutImage(Image *image,Image *hald_image) % MagickBooleanType HaldClutImageChannel(Image *image, % const ChannelType channel,Image *hald_image) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o hald_image: the color lookup table image for replacement color values. % % o channel: the channel. % */ MagickExport MagickBooleanType HaldClutImage(Image *image, const Image *hald_image) { return(HaldClutImageChannel(image,DefaultChannels,hald_image)); } MagickExport MagickBooleanType HaldClutImageChannel(Image *image, const ChannelType channel,const Image *hald_image) { #define HaldClutImageTag "Clut/Image" typedef struct _HaldInfo { MagickRealType x, y, z; } HaldInfo; CacheView *hald_view, *image_view; double width; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; size_t cube_size, length, level; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(hald_image != (Image *) NULL); assert(hald_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); /* Hald clut image. */ status=MagickTrue; progress=0; length=(size_t) MagickMin((MagickRealType) hald_image->columns, (MagickRealType) hald_image->rows); for (level=2; (level*level*level) < length; level++) ; level*=level; cube_size=level*level; width=(double) hald_image->columns; GetMagickPixelPacket(hald_image,&zero); exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); hald_view=AcquireAuthenticCacheView(hald_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,hald_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double offset; HaldInfo point; MagickPixelPacket pixel, pixel1, pixel2, pixel3, pixel4; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(hald_view); pixel=zero; pixel1=zero; pixel2=zero; pixel3=zero; pixel4=zero; for (x=0; x < (ssize_t) image->columns; x++) { point.x=QuantumScale*(level-1.0)*GetPixelRed(q); point.y=QuantumScale*(level-1.0)*GetPixelGreen(q); point.z=QuantumScale*(level-1.0)*GetPixelBlue(q); offset=(double) (point.x+level*floor(point.y)+cube_size*floor(point.z)); point.x-=floor(point.x); point.y-=floor(point.y); point.z-=floor(point.z); status=InterpolateMagickPixelPacket(image,hald_view, UndefinedInterpolatePixel,fmod(offset,width),floor(offset/width), &pixel1,exception); if (status == MagickFalse) break; status=InterpolateMagickPixelPacket(image,hald_view, UndefinedInterpolatePixel,fmod(offset+level,width),floor((offset+level)/ width),&pixel2,exception); if (status == MagickFalse) break; MagickPixelCompositeAreaBlend(&pixel1,pixel1.opacity,&pixel2, pixel2.opacity,point.y,&pixel3); offset+=cube_size; status=InterpolateMagickPixelPacket(image,hald_view, UndefinedInterpolatePixel,fmod(offset,width),floor(offset/width), &pixel1,exception); if (status == MagickFalse) break; status=InterpolateMagickPixelPacket(image,hald_view, UndefinedInterpolatePixel,fmod(offset+level,width),floor((offset+level)/ width),&pixel2,exception); if (status == MagickFalse) break; MagickPixelCompositeAreaBlend(&pixel1,pixel1.opacity,&pixel2, pixel2.opacity,point.y,&pixel4); MagickPixelCompositeAreaBlend(&pixel3,pixel3.opacity,&pixel4, pixel4.opacity,point.z,&pixel); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(pixel.blue)); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampToQuantum(pixel.index)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_HaldClutImageChannel) #endif proceed=SetImageProgress(image,HaldClutImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } hald_view=DestroyCacheView(hald_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImage() adjusts the levels of a particular image channel by % scaling the colors falling between specified white and black points to % the full available quantum range. % % The parameters provided represent the black, and white points. The black % point specifies the darkest color in the image. Colors darker than the % black point are set to zero. White point specifies the lightest color in % the image. Colors brighter than the white point are set to the maximum % quantum value. % % If a '!' flag is given, map black and white colors to the given levels % rather than mapping those levels to black and white. See % LevelizeImageChannel() and LevelizeImageChannel(), below. % % Gamma specifies a gamma correction to apply to the image. % % The format of the LevelImage method is: % % MagickBooleanType LevelImage(Image *image,const char *levels) % % A description of each parameter follows: % % o image: the image. % % o levels: Specify the levels where the black and white points have the % range of 0-QuantumRange, and gamma has the range 0-10 (e.g. 10x90%+2). % A '!' flag inverts the re-mapping. % */ MagickExport MagickBooleanType LevelImage(Image *image,const char *levels) { double black_point, gamma, white_point; GeometryInfo geometry_info; MagickBooleanType status; MagickStatusType flags; /* Parse levels. */ if (levels == (char *) NULL) return(MagickFalse); flags=ParseGeometry(levels,&geometry_info); black_point=geometry_info.rho; white_point=(double) QuantumRange; if ((flags & SigmaValue) != 0) white_point=geometry_info.sigma; gamma=1.0; if ((flags & XiValue) != 0) gamma=geometry_info.xi; if ((flags & PercentValue) != 0) { black_point*=(double) image->columns*image->rows/100.0; white_point*=(double) image->columns*image->rows/100.0; } if ((flags & SigmaValue) == 0) white_point=(double) QuantumRange-black_point; if ((flags & AspectValue ) == 0) status=LevelImageChannel(image,DefaultChannels,black_point,white_point, gamma); else status=LevelizeImage(image,black_point,white_point,gamma); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImage() applies the normal level operation to the image, spreading % out the values between the black and white points over the entire range of % values. Gamma correction is also applied after the values has been mapped. % % It is typically used to improve image contrast, or to provide a controlled % linear threshold for the image. If the black and white points are set to % the minimum and maximum values found in the image, the image can be % normalized. or by swapping black and white values, negate the image. % % The format of the LevelImage method is: % % MagickBooleanType LevelImage(Image *image,const double black_point, % const double white_point,const double gamma) % MagickBooleanType LevelImageChannel(Image *image, % const ChannelType channel,const double black_point, % const double white_point,const double gamma) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o black_point: The level which is to be mapped to zero (black) % % o white_point: The level which is to be mapped to QuantumRange (white) % % o gamma: adjust gamma by this factor before mapping values. % use 1.0 for purely linear stretching of image color values % */ static inline double LevelPixel(const double black_point, const double white_point,const double gamma,const MagickRealType pixel) { double level_pixel, scale; if (fabs(white_point-black_point) < MagickEpsilon) return(pixel); scale=1.0/(white_point-black_point); level_pixel=QuantumRange*gamma_pow(scale*((double) pixel-black_point),1.0/ gamma); return(level_pixel); } MagickExport MagickBooleanType LevelImageChannel(Image *image, const ChannelType channel,const double black_point,const double white_point, const double gamma) { #define LevelImageTag "Level/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((channel & RedChannel) != 0) image->colormap[i].red=(Quantum) ClampToQuantum(LevelPixel(black_point, white_point,gamma,(MagickRealType) image->colormap[i].red)); if ((channel & GreenChannel) != 0) image->colormap[i].green=(Quantum) ClampToQuantum(LevelPixel( black_point,white_point,gamma,(MagickRealType) image->colormap[i].green)); if ((channel & BlueChannel) != 0) image->colormap[i].blue=(Quantum) ClampToQuantum(LevelPixel(black_point, white_point,gamma,(MagickRealType) image->colormap[i].blue)); if ((channel & OpacityChannel) != 0) image->colormap[i].opacity=(Quantum) (QuantumRange-(Quantum) ClampToQuantum(LevelPixel(black_point,white_point,gamma, (MagickRealType) (QuantumRange-image->colormap[i].opacity)))); } /* Level image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(LevelPixel(black_point,white_point,gamma, (MagickRealType) GetPixelRed(q)))); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(LevelPixel(black_point,white_point,gamma, (MagickRealType) GetPixelGreen(q)))); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(LevelPixel(black_point,white_point,gamma, (MagickRealType) GetPixelBlue(q)))); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) SetPixelAlpha(q,ClampToQuantum(LevelPixel(black_point,white_point,gamma, (MagickRealType) GetPixelAlpha(q)))); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampToQuantum(LevelPixel(black_point, white_point,gamma,(MagickRealType) GetPixelIndex(indexes+x)))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_LevelImageChannel) #endif proceed=SetImageProgress(image,LevelImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) ClampImage(image); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l i z e I m a g e C h a n n e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelizeImageChannel() applies the reversed LevelImage() operation to just % the specific channels specified. It compresses the full range of color % values, so that they lie between the given black and white points. Gamma is % applied before the values are mapped. % % LevelizeImageChannel() can be called with by using a +level command line % API option, or using a '!' on a -level or LevelImage() geometry string. % % It can be used for example de-contrast a greyscale image to the exact % levels specified. Or by using specific levels for each channel of an image % you can convert a gray-scale image to any linear color gradient, according % to those levels. % % The format of the LevelizeImageChannel method is: % % MagickBooleanType LevelizeImageChannel(Image *image, % const ChannelType channel,const char *levels) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o gamma: adjust gamma by this factor before mapping values. % */ MagickExport MagickBooleanType LevelizeImage(Image *image, const double black_point,const double white_point,const double gamma) { MagickBooleanType status; status=LevelizeImageChannel(image,DefaultChannels,black_point,white_point, gamma); return(status); } MagickExport MagickBooleanType LevelizeImageChannel(Image *image, const ChannelType channel,const double black_point,const double white_point, const double gamma) { #define LevelizeImageTag "Levelize/Image" #define LevelizeValue(x) ClampToQuantum(((MagickRealType) gamma_pow((double) \ (QuantumScale*(x)),gamma))*(white_point-black_point)+black_point) CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((channel & RedChannel) != 0) image->colormap[i].red=LevelizeValue(image->colormap[i].red); if ((channel & GreenChannel) != 0) image->colormap[i].green=LevelizeValue(image->colormap[i].green); if ((channel & BlueChannel) != 0) image->colormap[i].blue=LevelizeValue(image->colormap[i].blue); if ((channel & OpacityChannel) != 0) image->colormap[i].opacity=(Quantum) (QuantumRange-LevelizeValue( QuantumRange-image->colormap[i].opacity)); } /* Level image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,LevelizeValue(GetPixelRed(q))); if ((channel & GreenChannel) != 0) SetPixelGreen(q,LevelizeValue(GetPixelGreen(q))); if ((channel & BlueChannel) != 0) SetPixelBlue(q,LevelizeValue(GetPixelBlue(q))); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) SetPixelAlpha(q,LevelizeValue(GetPixelAlpha(q))); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,LevelizeValue(GetPixelIndex(indexes+x))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_LevelizeImageChannel) #endif proceed=SetImageProgress(image,LevelizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImageColor() maps the given color to "black" and "white" values, % linearly spreading out the colors, and level values on a channel by channel % bases, as per LevelImage(). The given colors allows you to specify % different level ranges for each of the color channels separately. % % If the boolean 'invert' is set true the image values will modifyed in the % reverse direction. That is any existing "black" and "white" colors in the % image will become the color values given, with all other values compressed % appropriatally. This effectivally maps a greyscale gradient into the given % color gradient. % % The format of the LevelColorsImageChannel method is: % % MagickBooleanType LevelColorsImage(Image *image, % const MagickPixelPacket *black_color, % const MagickPixelPacket *white_color,const MagickBooleanType invert) % MagickBooleanType LevelColorsImageChannel(Image *image, % const ChannelType channel,const MagickPixelPacket *black_color, % const MagickPixelPacket *white_color,const MagickBooleanType invert) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o black_color: The color to map black to/from % % o white_point: The color to map white to/from % % o invert: if true map the colors (levelize), rather than from (level) % */ MagickExport MagickBooleanType LevelColorsImage(Image *image, const MagickPixelPacket *black_color,const MagickPixelPacket *white_color, const MagickBooleanType invert) { MagickBooleanType status; status=LevelColorsImageChannel(image,DefaultChannels,black_color,white_color, invert); return(status); } MagickExport MagickBooleanType LevelColorsImageChannel(Image *image, const ChannelType channel,const MagickPixelPacket *black_color, const MagickPixelPacket *white_color,const MagickBooleanType invert) { MagickStatusType status; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsGrayColorspace(black_color->colorspace) != MagickFalse) || (IsGrayColorspace(white_color->colorspace) != MagickFalse))) (void) SetImageColorspace(image,sRGBColorspace); status=MagickTrue; if (invert == MagickFalse) { if ((channel & RedChannel) != 0) status&=LevelImageChannel(image,RedChannel,black_color->red, white_color->red,(double) 1.0); if ((channel & GreenChannel) != 0) status&=LevelImageChannel(image,GreenChannel,black_color->green, white_color->green,(double) 1.0); if ((channel & BlueChannel) != 0) status&=LevelImageChannel(image,BlueChannel,black_color->blue, white_color->blue,(double) 1.0); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) status&=LevelImageChannel(image,OpacityChannel,black_color->opacity, white_color->opacity,(double) 1.0); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) status&=LevelImageChannel(image,IndexChannel,black_color->index, white_color->index,(double) 1.0); } else { if ((channel & RedChannel) != 0) status&=LevelizeImageChannel(image,RedChannel,black_color->red, white_color->red,(double) 1.0); if ((channel & GreenChannel) != 0) status&=LevelizeImageChannel(image,GreenChannel,black_color->green, white_color->green,(double) 1.0); if ((channel & BlueChannel) != 0) status&=LevelizeImageChannel(image,BlueChannel,black_color->blue, white_color->blue,(double) 1.0); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) status&=LevelizeImageChannel(image,OpacityChannel,black_color->opacity, white_color->opacity,(double) 1.0); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) status&=LevelizeImageChannel(image,IndexChannel,black_color->index, white_color->index,(double) 1.0); } return(status == 0 ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i n e a r S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LinearStretchImage() discards any pixels below the black point and above % the white point and levels the remaining pixels. % % The format of the LinearStretchImage method is: % % MagickBooleanType LinearStretchImage(Image *image, % const double black_point,const double white_point) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % */ MagickExport MagickBooleanType LinearStretchImage(Image *image, const double black_point,const double white_point) { #define LinearStretchImageTag "LinearStretch/Image" ExceptionInfo *exception; MagickBooleanType status; MagickRealType *histogram, intensity; ssize_t black, white, y; /* Allocate histogram and linear map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); histogram=(MagickRealType *) AcquireQuantumMemory(MaxMap+1UL, sizeof(*histogram)); if (histogram == (MagickRealType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Form histogram. */ (void) memset(histogram,0,(MaxMap+1)*sizeof(*histogram)); exception=(&image->exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { histogram[ScaleQuantumToMap(ClampToQuantum(GetPixelIntensity(image,p)))]++; p++; } } /* Find the histogram boundaries by locating the black and white point levels. */ intensity=0.0; for (black=0; black < (ssize_t) MaxMap; black++) { intensity+=histogram[black]; if (intensity >= black_point) break; } intensity=0.0; for (white=(ssize_t) MaxMap; white != 0; white--) { intensity+=histogram[white]; if (intensity >= white_point) break; } histogram=(MagickRealType *) RelinquishMagickMemory(histogram); status=LevelImageChannel(image,DefaultChannels,(double) ScaleMapToQuantum(black),(double) ScaleMapToQuantum(white),1.0); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d u l a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModulateImage() lets you control the brightness, saturation, and hue % of an image. Modulate represents the brightness, saturation, and hue % as one parameter (e.g. 90,150,100). If the image colorspace is HSL, the % modulation is lightness, saturation, and hue. For HWB, use blackness, % whiteness, and hue. And for HCL, use chrome, luma, and hue. % % The format of the ModulateImage method is: % % MagickBooleanType ModulateImage(Image *image,const char *modulate) % % A description of each parameter follows: % % o image: the image. % % o modulate: Define the percent change in brightness, saturation, and % hue. % */ static inline void ModulateHCL(const double percent_hue, const double percent_chroma,const double percent_luma,Quantum *red, Quantum *green,Quantum *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCL(*red,*green,*blue,&hue,&chroma,&luma); hue+=fmod((percent_hue-100.0),200.0)/200.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHCLp(const double percent_hue, const double percent_chroma,const double percent_luma,Quantum *red, Quantum *green,Quantum *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCLp(*red,*green,*blue,&hue,&chroma,&luma); hue+=fmod((percent_hue-100.0),200.0)/200.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLpToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHSB(const double percent_hue, const double percent_saturation,const double percent_brightness,Quantum *red, Quantum *green,Quantum *blue) { double brightness, hue, saturation; /* Increase or decrease color brightness, saturation, or hue. */ ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; brightness*=0.01*percent_brightness; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } static inline void ModulateHSI(const double percent_hue, const double percent_saturation,const double percent_intensity,Quantum *red, Quantum *green,Quantum *blue) { double intensity, hue, saturation; /* Increase or decrease color intensity, saturation, or hue. */ ConvertRGBToHSI(*red,*green,*blue,&hue,&saturation,&intensity); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; intensity*=0.01*percent_intensity; ConvertHSIToRGB(hue,saturation,intensity,red,green,blue); } static inline void ModulateHSL(const double percent_hue, const double percent_saturation,const double percent_lightness,Quantum *red, Quantum *green,Quantum *blue) { double hue, lightness, saturation; /* Increase or decrease color lightness, saturation, or hue. */ ConvertRGBToHSL(*red,*green,*blue,&hue,&saturation,&lightness); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; lightness*=0.01*percent_lightness; ConvertHSLToRGB(hue,saturation,lightness,red,green,blue); } static inline void ModulateHSV(const double percent_hue, const double percent_saturation,const double percent_value,Quantum *red, Quantum *green,Quantum *blue) { double hue, saturation, value; /* Increase or decrease color value, saturation, or hue. */ ConvertRGBToHSV(*red,*green,*blue,&hue,&saturation,&value); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; value*=0.01*percent_value; ConvertHSVToRGB(hue,saturation,value,red,green,blue); } static inline void ModulateHWB(const double percent_hue, const double percent_whiteness,const double percent_blackness,Quantum *red, Quantum *green,Quantum *blue) { double blackness, hue, whiteness; /* Increase or decrease color blackness, whiteness, or hue. */ ConvertRGBToHWB(*red,*green,*blue,&hue,&whiteness,&blackness); hue+=fmod((percent_hue-100.0),200.0)/200.0; blackness*=0.01*percent_blackness; whiteness*=0.01*percent_whiteness; ConvertHWBToRGB(hue,whiteness,blackness,red,green,blue); } static inline void ModulateLCHab(const double percent_luma, const double percent_chroma,const double percent_hue,Quantum *red, Quantum *green,Quantum *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHab(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=fmod((percent_hue-100.0),200.0)/200.0; ConvertLCHabToRGB(luma,chroma,hue,red,green,blue); } static inline void ModulateLCHuv(const double percent_luma, const double percent_chroma,const double percent_hue,Quantum *red, Quantum *green,Quantum *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHuv(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=fmod((percent_hue-100.0),200.0)/200.0; ConvertLCHuvToRGB(luma,chroma,hue,red,green,blue); } MagickExport MagickBooleanType ModulateImage(Image *image,const char *modulate) { #define ModulateImageTag "Modulate/Image" CacheView *image_view; ColorspaceType colorspace; const char *artifact; double percent_brightness, percent_hue, percent_saturation; ExceptionInfo *exception; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickStatusType flags; register ssize_t i; ssize_t y; /* Initialize modulate table. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (modulate == (char *) NULL) return(MagickFalse); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) SetImageColorspace(image,sRGBColorspace); flags=ParseGeometry(modulate,&geometry_info); percent_brightness=geometry_info.rho; percent_saturation=geometry_info.sigma; if ((flags & SigmaValue) == 0) percent_saturation=100.0; percent_hue=geometry_info.xi; if ((flags & XiValue) == 0) percent_hue=100.0; colorspace=UndefinedColorspace; artifact=GetImageArtifact(image,"modulate:colorspace"); if (artifact != (const char *) NULL) colorspace=(ColorspaceType) ParseCommandOption(MagickColorspaceOptions, MagickFalse,artifact); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { Quantum blue, green, red; /* Modulate image colormap. */ red=image->colormap[i].red; green=image->colormap[i].green; blue=image->colormap[i].blue; switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSIColorspace: { ModulateHSI(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHabColorspace: case LCHColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } image->colormap[i].red=red; image->colormap[i].green=green; image->colormap[i].blue=blue; } /* Modulate image. */ /* call opencl version */ #if defined(MAGICKCORE_OPENCL_SUPPORT) status=AccelerateModulateImage(image,percent_brightness,percent_hue, percent_saturation,colorspace,&image->exception); if (status != MagickFalse) return status; #endif status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { Quantum blue, green, red; red=GetPixelRed(q); green=GetPixelGreen(q); blue=GetPixelBlue(q); switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHColorspace: case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } SetPixelRed(q,red); SetPixelGreen(q,green); SetPixelBlue(q,blue); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ModulateImage) #endif proceed=SetImageProgress(image,ModulateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e g a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NegateImage() negates the colors in the reference image. The grayscale % option means that only grayscale values within the image are negated. % % The format of the NegateImageChannel method is: % % MagickBooleanType NegateImage(Image *image, % const MagickBooleanType grayscale) % MagickBooleanType NegateImageChannel(Image *image, % const ChannelType channel,const MagickBooleanType grayscale) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o grayscale: If MagickTrue, only negate grayscale pixels within the image. % */ MagickExport MagickBooleanType NegateImage(Image *image, const MagickBooleanType grayscale) { MagickBooleanType status; status=NegateImageChannel(image,DefaultChannels,grayscale); return(status); } MagickExport MagickBooleanType NegateImageChannel(Image *image, const ChannelType channel,const MagickBooleanType grayscale) { #define NegateImageTag "Negate/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { /* Negate colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { if (grayscale != MagickFalse) if ((image->colormap[i].red != image->colormap[i].green) || (image->colormap[i].green != image->colormap[i].blue)) continue; if ((channel & RedChannel) != 0) image->colormap[i].red=QuantumRange-image->colormap[i].red; if ((channel & GreenChannel) != 0) image->colormap[i].green=QuantumRange-image->colormap[i].green; if ((channel & BlueChannel) != 0) image->colormap[i].blue=QuantumRange-image->colormap[i].blue; } } /* Negate image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); if (grayscale != MagickFalse) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((GetPixelRed(q) != GetPixelGreen(q)) || (GetPixelGreen(q) != GetPixelBlue(q))) { q++; continue; } if ((channel & RedChannel) != 0) SetPixelRed(q,QuantumRange-GetPixelRed(q)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,QuantumRange-GetPixelGreen(q)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,QuantumRange-GetPixelBlue(q)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,QuantumRange-GetPixelOpacity(q)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,QuantumRange-GetPixelIndex(indexes+x)); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_NegateImageChannel) #endif proceed=SetImageProgress(image,NegateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(MagickTrue); } /* Negate image. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); if (channel == DefaultChannels) for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q+x,QuantumRange-GetPixelRed(q+x)); SetPixelGreen(q+x,QuantumRange-GetPixelGreen(q+x)); SetPixelBlue(q+x,QuantumRange-GetPixelBlue(q+x)); } else for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q+x,QuantumRange-GetPixelRed(q+x)); if ((channel & GreenChannel) != 0) SetPixelGreen(q+x,QuantumRange-GetPixelGreen(q+x)); if ((channel & BlueChannel) != 0) SetPixelBlue(q+x,QuantumRange-GetPixelBlue(q+x)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q+x,QuantumRange-GetPixelOpacity(q+x)); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,QuantumRange-GetPixelIndex(indexes+x)); if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_NegateImageChannel) #endif proceed=SetImageProgress(image,NegateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N o r m a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The NormalizeImage() method enhances the contrast of a color image by % mapping the darkest 2 percent of all pixel to black and the brightest % 1 percent to white. % % The format of the NormalizeImage method is: % % MagickBooleanType NormalizeImage(Image *image) % MagickBooleanType NormalizeImageChannel(Image *image, % const ChannelType channel) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % */ MagickExport MagickBooleanType NormalizeImage(Image *image) { MagickBooleanType status; status=NormalizeImageChannel(image,DefaultChannels); return(status); } MagickExport MagickBooleanType NormalizeImageChannel(Image *image, const ChannelType channel) { double black_point, white_point; black_point=(double) image->columns*image->rows*0.0015; white_point=(double) image->columns*image->rows*0.9995; return(ContrastStretchImageChannel(image,channel,black_point,white_point)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S i g m o i d a l C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SigmoidalContrastImage() adjusts the contrast of an image with a non-linear % sigmoidal contrast algorithm. Increase the contrast of the image using a % sigmoidal transfer function without saturating highlights or shadows. % Contrast indicates how much to increase the contrast (0 is none; 3 is % typical; 20 is pushing it); mid-point indicates where midtones fall in the % resultant image (0 is white; 50% is middle-gray; 100% is black). Set % sharpen to MagickTrue to increase the image contrast otherwise the contrast % is reduced. % % The format of the SigmoidalContrastImage method is: % % MagickBooleanType SigmoidalContrastImage(Image *image, % const MagickBooleanType sharpen,const char *levels) % MagickBooleanType SigmoidalContrastImageChannel(Image *image, % const ChannelType channel,const MagickBooleanType sharpen, % const double contrast,const double midpoint) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o sharpen: Increase or decrease image contrast. % % o contrast: strength of the contrast, the larger the number the more % 'threshold-like' it becomes. % % o midpoint: midpoint of the function as a color value 0 to QuantumRange. % */ /* ImageMagick 7 has a version of this function which does not use LUTs. */ /* Sigmoidal function Sigmoidal with inflexion point moved to b and "slope constant" set to a. The first version, based on the hyperbolic tangent tanh, when combined with the scaling step, is an exact arithmetic clone of the the sigmoid function based on the logistic curve. The equivalence is based on the identity 1/(1+exp(-t)) = (1+tanh(t/2))/2 (http://de.wikipedia.org/wiki/Sigmoidfunktion) and the fact that the scaled sigmoidal derivation is invariant under affine transformations of the ordinate. The tanh version is almost certainly more accurate and cheaper. The 0.5 factor in the argument is to clone the legacy ImageMagick behavior. The reason for making the define depend on atanh even though it only uses tanh has to do with the construction of the inverse of the scaled sigmoidal. */ #if defined(MAGICKCORE_HAVE_ATANH) #define Sigmoidal(a,b,x) ( tanh((0.5*(a))*((x)-(b))) ) #else #define Sigmoidal(a,b,x) ( 1.0/(1.0+exp((a)*((b)-(x)))) ) #endif /* Scaled sigmoidal function: ( Sigmoidal(a,b,x) - Sigmoidal(a,b,0) ) / ( Sigmoidal(a,b,1) - Sigmoidal(a,b,0) ) See http://osdir.com/ml/video.image-magick.devel/2005-04/msg00006.html and http://www.cs.dartmouth.edu/farid/downloads/tutorials/fip.pdf. The limit of ScaledSigmoidal as a->0 is the identity, but a=0 gives a division by zero. This is fixed below by exiting immediately when contrast is small, leaving the image (or colormap) unmodified. This appears to be safe because the series expansion of the logistic sigmoidal function around x=b is 1/2-a*(b-x)/4+... so that the key denominator s(1)-s(0) is about a/4 (a/2 with tanh). */ #define ScaledSigmoidal(a,b,x) ( \ (Sigmoidal((a),(b),(x))-Sigmoidal((a),(b),0.0)) / \ (Sigmoidal((a),(b),1.0)-Sigmoidal((a),(b),0.0)) ) /* Inverse of ScaledSigmoidal, used for +sigmoidal-contrast. Because b may be 0 or 1, the argument of the hyperbolic tangent (resp. logistic sigmoidal) may be outside of the interval (-1,1) (resp. (0,1)), even when creating a LUT from in gamut values, hence the branching. In addition, HDRI may have out of gamut values. InverseScaledSigmoidal is not a two-sided inverse of ScaledSigmoidal: It is only a right inverse. This is unavoidable. */ static inline double InverseScaledSigmoidal(const double a,const double b, const double x) { const double sig0=Sigmoidal(a,b,0.0); const double sig1=Sigmoidal(a,b,1.0); const double argument=(sig1-sig0)*x+sig0; const double clamped= ( #if defined(MAGICKCORE_HAVE_ATANH) argument < -1+MagickEpsilon ? -1+MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b+(2.0/a)*atanh(clamped)); #else argument < MagickEpsilon ? MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b-log(1.0/clamped-1.0)/a); #endif } MagickExport MagickBooleanType SigmoidalContrastImage(Image *image, const MagickBooleanType sharpen,const char *levels) { GeometryInfo geometry_info; MagickBooleanType status; MagickStatusType flags; flags=ParseGeometry(levels,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0*QuantumRange/2.0; if ((flags & PercentValue) != 0) geometry_info.sigma=1.0*QuantumRange*geometry_info.sigma/100.0; status=SigmoidalContrastImageChannel(image,DefaultChannels,sharpen, geometry_info.rho,geometry_info.sigma); return(status); } MagickExport MagickBooleanType SigmoidalContrastImageChannel(Image *image, const ChannelType channel,const MagickBooleanType sharpen, const double contrast,const double midpoint) { #define SigmoidalContrastImageTag "SigmoidalContrast/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; MagickRealType *sigmoidal_map; register ssize_t i; ssize_t y; /* Side effect: clamps values unless contrast<MagickEpsilon, in which case nothing is done. */ if (contrast < MagickEpsilon) return(MagickTrue); /* Allocate and initialize sigmoidal maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); sigmoidal_map=(MagickRealType *) AcquireQuantumMemory(MaxMap+1UL, sizeof(*sigmoidal_map)); if (sigmoidal_map == (MagickRealType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(sigmoidal_map,0,(MaxMap+1)*sizeof(*sigmoidal_map)); if (sharpen != MagickFalse) for (i=0; i <= (ssize_t) MaxMap; i++) sigmoidal_map[i]=(MagickRealType) ScaleMapToQuantum((MagickRealType) (MaxMap*ScaledSigmoidal(contrast,QuantumScale*midpoint,(double) i/ MaxMap))); else for (i=0; i <= (ssize_t) MaxMap; i++) sigmoidal_map[i]=(MagickRealType) ScaleMapToQuantum((MagickRealType) ( MaxMap*InverseScaledSigmoidal(contrast,QuantumScale*midpoint,(double) i/ MaxMap))); /* Sigmoidal-contrast enhance colormap. */ if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { if ((channel & RedChannel) != 0) image->colormap[i].red=ClampToQuantum(sigmoidal_map[ ScaleQuantumToMap(image->colormap[i].red)]); if ((channel & GreenChannel) != 0) image->colormap[i].green=ClampToQuantum(sigmoidal_map[ ScaleQuantumToMap(image->colormap[i].green)]); if ((channel & BlueChannel) != 0) image->colormap[i].blue=ClampToQuantum(sigmoidal_map[ ScaleQuantumToMap(image->colormap[i].blue)]); if ((channel & OpacityChannel) != 0) image->colormap[i].opacity=ClampToQuantum(sigmoidal_map[ ScaleQuantumToMap(image->colormap[i].opacity)]); } /* Sigmoidal-contrast enhance image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(sigmoidal_map[ScaleQuantumToMap( GetPixelRed(q))])); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(sigmoidal_map[ScaleQuantumToMap( GetPixelGreen(q))])); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(sigmoidal_map[ScaleQuantumToMap( GetPixelBlue(q))])); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(sigmoidal_map[ScaleQuantumToMap( GetPixelOpacity(q))])); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampToQuantum(sigmoidal_map[ScaleQuantumToMap( GetPixelIndex(indexes+x))])); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SigmoidalContrastImageChannel) #endif proceed=SetImageProgress(image,SigmoidalContrastImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); sigmoidal_map=(MagickRealType *) RelinquishMagickMemory(sigmoidal_map); return(status); }
rakp_fmt_plug.c
/* * This software is Copyright (c) 2013 magnum, and it is hereby released to the * general public under the following terms: Redistribution and use in source * and binary forms, with or without modification, are permitted. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_rakp; #elif FMT_REGISTERS_H john_register_one(&fmt_rakp); #else #include <string.h> #include "arch.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 2048 // tuned for i7 using SSE2 and w/o HT #endif #endif #include "misc.h" #include "common.h" #include "formats.h" #include "sha.h" #include "johnswap.h" #include "simd-intrinsics.h" #include "memdbg.h" #define FORMAT_LABEL "RAKP" #define FORMAT_NAME "IPMI 2.0 RAKP (RMCP+)" #ifdef SIMD_COEF_32 #define SHA1_N (SIMD_PARA_SHA1 * SIMD_COEF_32) #endif #define ALGORITHM_NAME "HMAC-SHA1 " SHA1_ALGORITHM_NAME #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 #define PLAINTEXT_LENGTH 125 #define PAD_SIZE 64 #define BINARY_SIZE 20 #define BINARY_ALIGN sizeof(ARCH_WORD_32) #define SALT_LENGTH (2 * PAD_SIZE) #define SALT_ALIGN MEM_ALIGN_NONE #define SALT_MIN_SIZE (PAD_SIZE - 8) #define SALT_MAX_SIZE (2 * PAD_SIZE - 8 - 1) #define FORMAT_TAG "$rakp$" #define TAG_LENGTH (sizeof(FORMAT_TAG) - 1) #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT SHA1_N #define MAX_KEYS_PER_CRYPT SHA1_N #define GETPOS(i, index) ((index & (SIMD_COEF_32 - 1)) * 4 + ((i) & (0xffffffff - 3)) * SIMD_COEF_32 + (3 - ((i) & 3)) + (unsigned int)index/SIMD_COEF_32 * SHA_BUF_SIZ * 4 * SIMD_COEF_32) #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif static struct fmt_tests tests[] = { {"$rakp$a4a3a2a03f0b000094272eb1ba576450b0d98ad10727a9fb0ab83616e099e8bf5f7366c9c03d36a3000000000000000000000000000000001404726f6f74$0ea27d6d5effaa996e5edc855b944e179a2f2434", "calvin"}, {"$rakp$c358d2a72f0c00001135f9b254c274629208b22f1166d94d2eba47f21093e9734355a33593da16f2000000000000000000000000000000001404726f6f74$41fce60acf2885f87fcafdf658d6f97db12639a9", "calvin"}, {"$rakp$b7c2d6f13a43dce2e44ad120a9cd8a13d0ca23f0414275c0bbe1070d2d1299b1c04da0f1a0f1e4e2537300263a2200000000000000000000140768617368636174$472bdabe2d5d4bffd6add7b3ba79a291d104a9ef", "hashcat"}, /* dummy hash for testing long salts */ {"$rakp$787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878$ba4ecc30a0b36a6ba0db862fc95201a81b9252ee", ""}, {NULL} }; #ifdef SIMD_COEF_32 #define cur_salt rakp_cur_salt static unsigned char *crypt_key; static unsigned char *ipad, *prep_ipad; static unsigned char *opad, *prep_opad; JTR_ALIGN(MEM_ALIGN_SIMD) unsigned char cur_salt[2][SHA_BUF_SIZ * 4 * SHA1_N]; static int bufsize; #else static struct { int length; unsigned char salt[SALT_LENGTH]; } cur_salt; static ARCH_WORD_32 (*crypt_key)[BINARY_SIZE / sizeof(ARCH_WORD_32)]; static unsigned char (*ipad)[PAD_SIZE]; static unsigned char (*opad)[PAD_SIZE]; static SHA_CTX *ipad_ctx; static SHA_CTX *opad_ctx; #endif static char (*saved_plain)[PLAINTEXT_LENGTH + 1]; static int new_keys; #define SALT_SIZE sizeof(cur_salt) #ifdef SIMD_COEF_32 static void clear_keys(void) { memset(ipad, 0x36, bufsize); memset(opad, 0x5C, bufsize); } #endif static void init(struct fmt_main *self) { #ifdef SIMD_COEF_32 int i; #endif #ifdef _OPENMP int omp_t = omp_get_num_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif #ifdef SIMD_COEF_32 bufsize = sizeof(*opad) * self->params.max_keys_per_crypt * SHA_BUF_SIZ * 4; crypt_key = mem_calloc_align(1, bufsize, MEM_ALIGN_SIMD); ipad = mem_calloc_align(1, bufsize, MEM_ALIGN_SIMD); opad = mem_calloc_align(1, bufsize, MEM_ALIGN_SIMD); prep_ipad = mem_calloc_align(self->params.max_keys_per_crypt * BINARY_SIZE, sizeof(*prep_ipad), MEM_ALIGN_SIMD); prep_opad = mem_calloc_align(self->params.max_keys_per_crypt * BINARY_SIZE, sizeof(*prep_opad), MEM_ALIGN_SIMD); for (i = 0; i < self->params.max_keys_per_crypt; ++i) { crypt_key[GETPOS(BINARY_SIZE, i)] = 0x80; ((unsigned int*)crypt_key)[15 * SIMD_COEF_32 + (i&(SIMD_COEF_32-1)) + i/SIMD_COEF_32 * SHA_BUF_SIZ * SIMD_COEF_32] = (BINARY_SIZE + 64) << 3; } clear_keys(); #else crypt_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_key)); ipad = mem_calloc(self->params.max_keys_per_crypt, sizeof(*ipad)); opad = mem_calloc(self->params.max_keys_per_crypt, sizeof(*opad)); ipad_ctx = mem_calloc(self->params.max_keys_per_crypt, sizeof(*ipad_ctx)); opad_ctx = mem_calloc(self->params.max_keys_per_crypt, sizeof(*opad_ctx)); #endif saved_plain = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_plain)); } static void done(void) { MEM_FREE(saved_plain); #ifdef SIMD_COEF_32 MEM_FREE(prep_opad); MEM_FREE(prep_ipad); #else MEM_FREE(opad_ctx); MEM_FREE(ipad_ctx); #endif MEM_FREE(opad); MEM_FREE(ipad); MEM_FREE(crypt_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *q = NULL; int len; p = ciphertext; if (!strncmp(p, FORMAT_TAG, TAG_LENGTH)) p += TAG_LENGTH; q = strrchr(ciphertext, '$'); if (!q) return 0; q = q + 1; if ((q - p - 1) > SALT_MAX_SIZE * 2) return 0; if ((q - p - 1) < SALT_MIN_SIZE * 2) return 0; len = strspn(q, HEXCHARS_lc); if (len != BINARY_SIZE * 2 || len != strlen(q)) return 0; if (strspn(p, HEXCHARS_lc) != q - p - 1) return 0; return 1; } static void set_salt(void *salt) { memcpy(&cur_salt, salt, SALT_SIZE); } static void set_key(char *key, int index) { int len; #ifdef SIMD_COEF_32 ARCH_WORD_32 *ipadp = (ARCH_WORD_32*)&ipad[GETPOS(3, index)]; ARCH_WORD_32 *opadp = (ARCH_WORD_32*)&opad[GETPOS(3, index)]; const ARCH_WORD_32 *keyp = (ARCH_WORD_32*)key; unsigned int temp; len = strlen(key); memcpy(saved_plain[index], key, len); saved_plain[index][len] = 0; if (len > PAD_SIZE) { unsigned char k0[BINARY_SIZE]; SHA_CTX ctx; int i; SHA1_Init(&ctx); SHA1_Update(&ctx, key, len); SHA1_Final(k0, &ctx); keyp = (unsigned int*)k0; for(i = 0; i < BINARY_SIZE / 4; i++, ipadp += SIMD_COEF_32, opadp += SIMD_COEF_32) { temp = JOHNSWAP(*keyp++); *ipadp ^= temp; *opadp ^= temp; } } else while(((temp = JOHNSWAP(*keyp++)) & 0xff000000)) { if (!(temp & 0x00ff0000) || !(temp & 0x0000ff00)) { ((unsigned short*)ipadp)[1] ^= (unsigned short)(temp >> 16); ((unsigned short*)opadp)[1] ^= (unsigned short)(temp >> 16); break; } *ipadp ^= temp; *opadp ^= temp; if (!(temp & 0x000000ff)) break; ipadp += SIMD_COEF_32; opadp += SIMD_COEF_32; } #else int i; len = strlen(key); memcpy(saved_plain[index], key, len); saved_plain[index][len] = 0; memset(ipad[index], 0x36, PAD_SIZE); memset(opad[index], 0x5C, PAD_SIZE); if (len > PAD_SIZE) { SHA_CTX ctx; unsigned char k0[BINARY_SIZE]; SHA1_Init(&ctx); SHA1_Update(&ctx, key, len); SHA1_Final(k0, &ctx); len = BINARY_SIZE; for(i = 0; i < len; i++) { ipad[index][i] ^= k0[i]; opad[index][i] ^= k0[i]; } } else for(i = 0; i < len; i++) { ipad[index][i] ^= key[i]; opad[index][i] ^= key[i]; } #endif new_keys = 1; } static char *get_key(int index) { return saved_plain[index]; } static int cmp_all(void *binary, int count) { #ifdef SIMD_COEF_32 unsigned int x, y = 0; for(;y < (unsigned int)(count + SIMD_COEF_32 - 1) / SIMD_COEF_32; y++) for(x = 0; x < SIMD_COEF_32; x++) { // NOTE crypt_key is in input format (4*SHA_BUF_SIZ*SIMD_COEF_32) if(((ARCH_WORD_32*)binary)[0] == ((ARCH_WORD_32*)crypt_key)[x + y * SIMD_COEF_32 * SHA_BUF_SIZ]) return 1; } return 0; #else int index = 0; #if defined(_OPENMP) || (MAX_KEYS_PER_CRYPT > 1) for (index = 0; index < count; index++) #endif if (((ARCH_WORD_32*)binary)[0] == crypt_key[index][0]) return 1; return 0; #endif } static int cmp_one(void *binary, int index) { #ifdef SIMD_COEF_32 int i; for(i = 0; i < (BINARY_SIZE/4); i++) // NOTE crypt_key is in input format (4 * SHA_BUF_SIZ * SIMD_COEF_32) if (((ARCH_WORD_32*)binary)[i] != ((ARCH_WORD_32*)crypt_key)[i * SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32 * SHA_BUF_SIZ * SIMD_COEF_32]) return 0; return 1; #else return !memcmp(binary, crypt_key[index], BINARY_SIZE); #endif } static int cmp_exact(char *source, int index) { return (1); } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #if _OPENMP #pragma omp parallel for for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) #endif { #ifdef SIMD_COEF_32 if (new_keys) { SIMDSHA1body(&ipad[index * SHA_BUF_SIZ * 4], (unsigned int*)&prep_ipad[index * BINARY_SIZE], NULL, SSEi_MIXED_IN); SIMDSHA1body(&opad[index * SHA_BUF_SIZ * 4], (unsigned int*)&prep_opad[index * BINARY_SIZE], NULL, SSEi_MIXED_IN); } SIMDSHA1body(cur_salt[0], (unsigned int*)&crypt_key[index * SHA_BUF_SIZ * 4], (unsigned int*)&prep_ipad[index * BINARY_SIZE], SSEi_MIXED_IN|SSEi_RELOAD|SSEi_OUTPUT_AS_INP_FMT); SIMDSHA1body(cur_salt[1], (unsigned int*)&crypt_key[index * SHA_BUF_SIZ * 4], (unsigned int*)&crypt_key[index * SHA_BUF_SIZ * 4], SSEi_MIXED_IN|SSEi_RELOAD_INP_FMT|SSEi_OUTPUT_AS_INP_FMT); SIMDSHA1body(&crypt_key[index * SHA_BUF_SIZ * 4], (unsigned int*)&crypt_key[index * SHA_BUF_SIZ * 4], (unsigned int*)&prep_opad[index * BINARY_SIZE], SSEi_MIXED_IN|SSEi_RELOAD|SSEi_OUTPUT_AS_INP_FMT); #else SHA_CTX ctx; if (new_keys) { SHA1_Init(&ipad_ctx[index]); SHA1_Update(&ipad_ctx[index], ipad[index], PAD_SIZE); SHA1_Init(&opad_ctx[index]); SHA1_Update(&opad_ctx[index], opad[index], PAD_SIZE); } memcpy(&ctx, &ipad_ctx[index], sizeof(ctx)); SHA1_Update(&ctx, cur_salt.salt, cur_salt.length); SHA1_Final((unsigned char*) crypt_key[index], &ctx); memcpy(&ctx, &opad_ctx[index], sizeof(ctx)); SHA1_Update(&ctx, crypt_key[index], BINARY_SIZE); SHA1_Final((unsigned char*) crypt_key[index], &ctx); #endif } new_keys = 0; return count; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; p = strrchr(ciphertext, '$') + 1; for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } #ifdef SIMD_COEF_32 alter_endianity(out, BINARY_SIZE); #endif return out; } static void *get_salt(char *ciphertext) { static unsigned char salt[SALT_LENGTH]; unsigned int i, len; #ifdef SIMD_COEF_32 unsigned int j; #endif memset(salt, 0, sizeof(salt)); memset(&cur_salt, 0, sizeof(cur_salt)); if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) ciphertext += TAG_LENGTH; len = (strrchr(ciphertext, '$') - ciphertext) / 2; for (i = 0; i < len; i++) salt[i] = (atoi16[ARCH_INDEX(ciphertext[2 * i])] << 4) | atoi16[ARCH_INDEX(ciphertext[2 * i + 1])]; #ifdef SIMD_COEF_32 for (i = 0; i < len; i++) for (j = 0; j < SHA1_N; ++j) cur_salt[i>>6][GETPOS(i & 63, j)] = ((unsigned char*)salt)[i]; for (i = 0; i < SHA1_N; ++i) cur_salt[len>>6][GETPOS(len & 63, i)] = 0x80; for (j = len + 1; j < SALT_LENGTH; ++j) for (i = 0; i < SHA1_N; ++i) cur_salt[j>>6][GETPOS(j & 63, i)] = 0; for (i = 0; i < SHA1_N; ++i) ((unsigned int*)cur_salt[1])[15 * SIMD_COEF_32 + (i&(SIMD_COEF_32-1)) + i/SIMD_COEF_32 * SHA_BUF_SIZ * SIMD_COEF_32] = (len + 64) << 3; return &cur_salt; #else cur_salt.length = len; memcpy(cur_salt.salt, salt, len); return &cur_salt; #endif } #ifdef SIMD_COEF_32 // NOTE crypt_key is in input format (4*SHA_BUF_SIZ*SIMD_COEF_32) #define HASH_OFFSET (index & (SIMD_COEF_32 - 1)) + ((unsigned int)index / SIMD_COEF_32) * SIMD_COEF_32 * SHA_BUF_SIZ static int get_hash_0(int index) { return ((ARCH_WORD_32*)crypt_key)[HASH_OFFSET] & PH_MASK_0; } static int get_hash_1(int index) { return ((ARCH_WORD_32*)crypt_key)[HASH_OFFSET] & PH_MASK_1; } static int get_hash_2(int index) { return ((ARCH_WORD_32*)crypt_key)[HASH_OFFSET] & PH_MASK_2; } static int get_hash_3(int index) { return ((ARCH_WORD_32*)crypt_key)[HASH_OFFSET] & PH_MASK_3; } static int get_hash_4(int index) { return ((ARCH_WORD_32*)crypt_key)[HASH_OFFSET] & PH_MASK_4; } static int get_hash_5(int index) { return ((ARCH_WORD_32*)crypt_key)[HASH_OFFSET] & PH_MASK_5; } static int get_hash_6(int index) { return ((ARCH_WORD_32*)crypt_key)[HASH_OFFSET] & PH_MASK_6; } #else static int get_hash_0(int index) { return crypt_key[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_key[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_key[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_key[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_key[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_key[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_key[index][0] & PH_MASK_6; } #endif struct fmt_main fmt_rakp = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { NULL }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, #ifdef SIMD_COEF_32 clear_keys, #else fmt_default_clear_keys, #endif crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
poisson.c
# include <stdlib.h> # include <stdio.h> # include <math.h> # include <time.h> # include <string.h> #include <assert.h> #include <unistd.h> #include <sys/time.h> #if defined(_OPENMP) # include <omp.h> #endif # include "poisson.h" # include "main.h" #include "../../common/Utils.h" double r8mat_rms(int nx, int ny, double *a_); void rhs(int nx, int ny, double *f_, int block_size); void timestamp(void); double u_exact(double x, double y); double uxxyy_exact(double x, double y); /* Purpose: MAIN is the main program for POISSON_OPENMP. Discussion: POISSON_OPENMP is a program for solving the Poisson problem. This program uses OpenMP for parallel execution. The Poisson equation - DEL^2 U(X,Y) = F(X,Y) is solved on the unit square [0,1] x [0,1] using a grid of NX by NX evenly spaced points. The first and last points in each direction are boundary points. The boundary conditions and F are set so that the exact solution is U(x,y) = sin ( pi * x * y) so that - DEL^2 U(x,y) = pi^2 * ( x^2 + y^2) * sin ( pi * x * y) The Jacobi iteration is repeatedly applied until convergence is detected. For convenience in writing the discretized equations, we assume that NX = NY. Licensing: This code is distributed under the GNU LGPL license. Modified: 14 December 2011 Author: John Burkardt */ /******************************************************************************/ double run(struct user_parameters* params) { int matrix_size = params->matrix_size; if (matrix_size <= 0) { matrix_size = 512; params->matrix_size = matrix_size; } int block_size = params->blocksize; if (block_size <= 0) { block_size = 128; params->blocksize = block_size; } int niter = params->titer; if (niter <= 0) { niter = 4; params->titer = niter; } int type = params->type; if (type <= 0) { type =1; params->type = type; } double dx; double dy; double error; int ii,i; int jj,j; int nx = matrix_size; int ny = matrix_size; double *f_ = malloc(nx * nx * sizeof(double)); double (*f)[nx][ny] = (double (*)[nx][ny])f_; double *u_ = malloc(nx * nx * sizeof(double)); double *unew_ = malloc(nx * ny * sizeof(double)); double (*unew)[nx][ny] = (double (*)[nx][ny])unew_; /* test if valid */ if ( (nx % block_size) || (ny % block_size) ) { params->succeed = 0; params->string2display = "*****ERROR: blocsize must divide NX and NY"; return 0; } /// INITIALISATION dx = 1.0 / (double) (nx - 1); dy = 1.0 / (double) (ny - 1); // Set the right hand side array F. rhs(nx, ny, f_, block_size); /* Set the initial solution estimate UNEW. We are "allowed" to pick up the boundary conditions exactly. */ #pragma omp parallel #pragma omp master //for collapse(2) for (j = 0; j < ny; j+= block_size) for (i = 0; i < nx; i+= block_size) #pragma omp task firstprivate(i,j) private(ii,jj) for (jj=j; jj<j+block_size; ++jj) for (ii=i; ii<i+block_size; ++ii) { if (ii == 0 || ii == nx - 1 || jj == 0 || jj == ny - 1) { (*unew)[ii][jj] = (*f)[ii][jj]; } else { (*unew)[ii][jj] = 0.0; } } /// KERNEL INTENSIVE COMPUTATION //START_TIMER; double t_start, t_end; t_start = rtclock(); if (type == 1){ sweep_task(nx, ny, dx, dy, f_, 0, niter, u_, unew_, block_size); } else if (type == 2) { sweep_task_dep(nx, ny, dx, dy, f_, 0, niter, u_, unew_, block_size); } else if (type == 3){ sweep_block_for(nx, ny, dx, dy, f_, 0, niter, u_, unew_, block_size); } else if (type == 4){ sweep_block_task(nx, ny, dx, dy, f_, 0, niter, u_, unew_, block_size); } else if (type == 5){ sweep_block_task_dep(nx, ny, dx, dy, f_, 0, niter, u_, unew_, block_size); } else if (type == 6){ sweep_seq(nx, ny, dx, dy, f_, 0, niter, u_, unew_); } if ( type > 6 ) { params->succeed = 0; params->string2display = "*****ERROR: type not known"; return 0; } //END_TIMER; t_end = rtclock(); /* modificar para checar o final do main*/ #ifdef _OPENMP if(params->check) { double x; double y; double *udiff_ = malloc(nx * ny * sizeof(double)); double (*udiff)[nx][ny] = (double (*)[nx][ny])udiff_; /// CHECK OUTPUT // Check for convergence. for (j = 0; j < ny; j++) { y = (double) (j) / (double) (ny - 1); for (i = 0; i < nx; i++) { x = (double) (i) / (double) (nx - 1); (*udiff)[i][j] = (*unew)[i][j] - u_exact(x, y); } } error = r8mat_rms(nx, ny, udiff_); double error1; // Set the right hand side array F. rhs(nx, ny, f_, block_size); /* Set the initial solution estimate UNEW. We are "allowed" to pick up the boundary conditions exactly. */ for (j = 0; j < ny; j++) { for (i = 0; i < nx; i++) { if (i == 0 || i == nx - 1 || j == 0 || j == ny - 1) { (*unew)[i][j] = (*f)[i][j]; } else { (*unew)[i][j] = 0.0; } } } sweep_seq(nx, ny, dx, dy, f_, 0, niter, u_, unew_); // Check for convergence. for (j = 0; j < ny; j++) { y = (double) (j) / (double) (ny - 1); for (i = 0; i < nx; i++) { x = (double) (i) / (double) (nx - 1); (*udiff)[i][j] = (*unew)[i][j] - u_exact(x, y); } } error1 = r8mat_rms(nx, ny, udiff_); params->succeed = fabs(error - error1) < 1.0E-6; free(udiff_); } #else params->succeed = 1; (void)error; #endif free(f_); free(u_); free(unew_); return (t_end - t_start); } /* R8MAT_RMS returns the RMS norm of a vector stored as a matrix. */ double r8mat_rms(int nx, int ny, double *a_) { double (*a)[nx][ny] = (double (*)[nx][ny])a_; int i; int j; double v; v = 0.0; for (j = 0; j < ny; j++) { for (i = 0; i < nx; i++) { v = v + (*a)[i][j] * (*a)[i][j]; } } v = sqrt(v / (double) (nx * ny)); return v; } /* RHS initializes the right hand side "vector". */ void rhs(int nx, int ny, double *f_, int block_size) { double (*f)[nx][ny] = (double (*)[nx][ny])f_; int i,ii; int j,jj; double x; double y; // The "boundary" entries of F store the boundary values of the solution. // The "interior" entries of F store the right hand sides of the Poisson equation. #pragma omp parallel #pragma omp master //for collapse(2) for (j = 0; j < ny; j+=block_size) for (i = 0; i < nx; i+=block_size) #pragma omp task firstprivate(block_size,i,j,nx,ny) private(ii,jj,x,y) for (jj=j; jj<j+block_size; ++jj) { y = (double) (jj) / (double) (ny - 1); for (ii=i; ii<i+block_size; ++ii) { x = (double) (ii) / (double) (nx - 1); if (ii == 0 || ii == nx - 1 || jj == 0 || jj == ny - 1) (*f)[ii][jj] = u_exact(x, y); else (*f)[ii][jj] = - uxxyy_exact(x, y); } } } /* Evaluates the exact solution. */ double u_exact(double x, double y) { double pi = 3.141592653589793; double value; value = sin(pi * x * y); return value; } /* Evaluates (d/dx d/dx + d/dy d/dy) of the exact solution. */ double uxxyy_exact(double x, double y) { double pi = 3.141592653589793; double value; value = - pi * pi * (x * x + y * y) * sin(pi * x * y); return value; }
loop.h
// // Header.h // // // Created by Alex on 08.11.2020. // #ifndef loop_h #define loop_h #include "types.h" #if APPLE #include <dispatch/dispatch.h> #define P_LOOP_START(size, var) dispatch_apply(size, DISPATCH_APPLY_AUTO, ^(size_t var) { #define P_LOOP_END }); #elif _OPENMP #define P_LOOP_START(size var) #pragma omp for \ for (var = 0; var < size; ++var) { \ #define P_LOOP_END } #else #define P_LOOP_START(size, var) for(int var = 0; var < size; ++var){ #define P_LOOP_END } #endif #endif /* Header_h */
GB_unop__acosh_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__acosh_fc64_fc64) // op(A') function: GB (_unop_tran__acosh_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = cacosh (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = cacosh (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = cacosh (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ACOSH || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__acosh_fc64_fc64) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = cacosh (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = cacosh (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__acosh_fc64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
TNV_core.c
/* * This work is part of the Core Imaging Library developed by * Visual Analytics and Imaging System Group of the Science Technology * Facilities Council, STFC * * Copyright 2017 Daniil Kazantsev * Copyright 2017 Srikanth Nagella, Edoardo Pasca * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "TNV_core.h" /* * C-OMP implementation of Total Nuclear Variation regularisation model (2D + channels) [1] * The code is modified from the implementation by Joan Duran <joan.duran@uib.es> see * "denoisingPDHG_ipol.cpp" in Joans Collaborative Total Variation package * * Input Parameters: * 1. Noisy volume of 2D + channel dimension, i.e. 3D volume * 2. lambda - regularisation parameter * 3. Number of iterations [OPTIONAL parameter] * 4. eplsilon - tolerance constant [OPTIONAL parameter] * 5. print information: 0 (off) or 1 (on) [OPTIONAL parameter] * * Output: * 1. Filtered/regularized image * * [1]. Duran, J., Moeller, M., Sbert, C. and Cremers, D., 2016. Collaborative total variation: a general framework for vectorial TV models. SIAM Journal on Imaging Sciences, 9(1), pp.116-151. */ float TNV_CPU_main(float *Input, float *u, float lambda, int maxIter, float tol, int dimX, int dimY, int dimZ) { long k, p, q, r, DimTotal; float taulambda; float *u_upd, *gx, *gy, *gx_upd, *gy_upd, *qx, *qy, *qx_upd, *qy_upd, *v, *vx, *vy, *gradx, *grady, *gradx_upd, *grady_upd, *gradx_ubar, *grady_ubar, *div, *div_upd; p = 1l; q = 1l; r = 0l; lambda = 1.0f/(2.0f*lambda); DimTotal = (long)(dimX*dimY*dimZ); /* PDHG algorithm parameters*/ float tau = 0.5f; float sigma = 0.5f; float theta = 1.0f; // Auxiliar vectors u_upd = calloc(DimTotal, sizeof(float)); gx = calloc(DimTotal, sizeof(float)); gy = calloc(DimTotal, sizeof(float)); gx_upd = calloc(DimTotal, sizeof(float)); gy_upd = calloc(DimTotal, sizeof(float)); qx = calloc(DimTotal, sizeof(float)); qy = calloc(DimTotal, sizeof(float)); qx_upd = calloc(DimTotal, sizeof(float)); qy_upd = calloc(DimTotal, sizeof(float)); v = calloc(DimTotal, sizeof(float)); vx = calloc(DimTotal, sizeof(float)); vy = calloc(DimTotal, sizeof(float)); gradx = calloc(DimTotal, sizeof(float)); grady = calloc(DimTotal, sizeof(float)); gradx_upd = calloc(DimTotal, sizeof(float)); grady_upd = calloc(DimTotal, sizeof(float)); gradx_ubar = calloc(DimTotal, sizeof(float)); grady_ubar = calloc(DimTotal, sizeof(float)); div = calloc(DimTotal, sizeof(float)); div_upd = calloc(DimTotal, sizeof(float)); // Backtracking parameters float s = 1.0f; float gamma = 0.75f; float beta = 0.95f; float alpha0 = 0.2f; float alpha = alpha0; float delta = 1.5f; float eta = 0.95f; // PDHG algorithm parameters taulambda = tau * lambda; float divtau = 1.0f / tau; float divsigma = 1.0f / sigma; float theta1 = 1.0f + theta; /*allocate memory for taulambda */ //taulambda = (float*) calloc(dimZ, sizeof(float)); //for(k=0; k < dimZ; k++) {taulambda[k] = tau*lambda[k];} // Apply Primal-Dual Hybrid Gradient scheme int iter = 0; float residual = fLarge; float ubarx, ubary; for(iter = 0; iter < maxIter; iter++) { // Argument of proximal mapping of fidelity term #pragma omp parallel for shared(v, u) private(k) for(k=0; k<dimX*dimY*dimZ; k++) {v[k] = u[k] + tau*div[k];} // Proximal solution of fidelity term proxG(u_upd, v, Input, taulambda, (long)(dimX), (long)(dimY), (long)(dimZ)); // Gradient of updated primal variable gradient(u_upd, gradx_upd, grady_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); // Argument of proximal mapping of regularization term #pragma omp parallel for shared(gradx_upd, grady_upd, gradx, grady) private(k, ubarx, ubary) for(k=0; k<dimX*dimY*dimZ; k++) { ubarx = theta1 * gradx_upd[k] - theta * gradx[k]; ubary = theta1 * grady_upd[k] - theta * grady[k]; vx[k] = ubarx + divsigma * qx[k]; vy[k] = ubary + divsigma * qy[k]; gradx_ubar[k] = ubarx; grady_ubar[k] = ubary; } proxF(gx_upd, gy_upd, vx, vy, sigma, p, q, r, (long)(dimX), (long)(dimY), (long)(dimZ)); // Update dual variable #pragma omp parallel for shared(qx_upd, qy_upd) private(k) for(k=0; k<dimX*dimY*dimZ; k++) { qx_upd[k] = qx[k] + sigma * (gradx_ubar[k] - gx_upd[k]); qy_upd[k] = qy[k] + sigma * (grady_ubar[k] - gy_upd[k]); } // Divergence of updated dual variable #pragma omp parallel for shared(div_upd) private(k) for(k=0; k<dimX*dimY*dimZ; k++) {div_upd[k] = 0.0f;} divergence(qx_upd, qy_upd, div_upd, dimX, dimY, dimZ); // Compute primal residual, dual residual, and backtracking condition float resprimal = 0.0f; float resdual = 0.0f; float product = 0.0f; float unorm = 0.0f; float qnorm = 0.0f; for(k=0; k<dimX*dimY*dimZ; k++) { float udiff = u[k] - u_upd[k]; float qxdiff = qx[k] - qx_upd[k]; float qydiff = qy[k] - qy_upd[k]; float divdiff = div[k] - div_upd[k]; float gradxdiff = gradx[k] - gradx_upd[k]; float gradydiff = grady[k] - grady_upd[k]; resprimal += fabs(divtau*udiff + divdiff); resdual += fabs(divsigma*qxdiff - gradxdiff); resdual += fabs(divsigma*qydiff - gradydiff); unorm += (udiff * udiff); qnorm += (qxdiff * qxdiff + qydiff * qydiff); product += (gradxdiff * qxdiff + gradydiff * qydiff); } float b = (2.0f * tau * sigma * product) / (gamma * sigma * unorm + gamma * tau * qnorm); // Adapt step-size parameters float dual_dot_delta = resdual * s * delta; float dual_div_delta = (resdual * s) / delta; if(b > 1) { // Decrease step-sizes to fit balancing principle tau = (beta * tau) / b; sigma = (beta * sigma) / b; alpha = alpha0; copyIm(u, u_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(gx, gx_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(gy, gy_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(qx, qx_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(qy, qy_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(gradx, gradx_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(grady, grady_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(div, div_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); } else if(resprimal > dual_dot_delta) { // Increase primal step-size and decrease dual step-size tau = tau / (1.0f - alpha); sigma = sigma * (1.0f - alpha); alpha = alpha * eta; } else if(resprimal < dual_div_delta) { // Decrease primal step-size and increase dual step-size tau = tau * (1.0f - alpha); sigma = sigma / (1.0f - alpha); alpha = alpha * eta; } // Update variables taulambda = tau * lambda; //for(k=0; k < dimZ; k++) taulambda[k] = tau*lambda[k]; divsigma = 1.0f / sigma; divtau = 1.0f / tau; copyIm(u_upd, u, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(gx_upd, gx, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(gy_upd, gy, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(qx_upd, qx, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(qy_upd, qy, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(gradx_upd, gradx, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(grady_upd, grady, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(div_upd, div, (long)(dimX), (long)(dimY), (long)(dimZ)); // Compute residual at current iteration residual = (resprimal + resdual) / ((float) (dimX*dimY*dimZ)); // printf("%f \n", residual); if (residual < tol) { printf("Iterations stopped at %i with the residual %f \n", iter, residual); break; } } printf("Iterations stopped at %i with the residual %f \n", iter, residual); free (u_upd); free(gx); free(gy); free(gx_upd); free(gy_upd); free(qx); free(qy); free(qx_upd); free(qy_upd); free(v); free(vx); free(vy); free(gradx); free(grady); free(gradx_upd); free(grady_upd); free(gradx_ubar); free(grady_ubar); free(div); free(div_upd); return *u; } float proxG(float *u_upd, float *v, float *f, float taulambda, long dimX, long dimY, long dimZ) { float constant; long k; constant = 1.0f + taulambda; #pragma omp parallel for shared(v, f, u_upd) private(k) for(k=0; k<dimZ*dimX*dimY; k++) { u_upd[k] = (v[k] + taulambda * f[k])/constant; //u_upd[(dimX*dimY)*k + l] = (v[(dimX*dimY)*k + l] + taulambda * f[(dimX*dimY)*k + l])/constant; } return *u_upd; } float gradient(float *u_upd, float *gradx_upd, float *grady_upd, long dimX, long dimY, long dimZ) { long i, j, k, l; // Compute discrete gradient using forward differences #pragma omp parallel for shared(gradx_upd,grady_upd,u_upd) private(i, j, k, l) for(k = 0; k < dimZ; k++) { for(j = 0; j < dimY; j++) { l = j * dimX; for(i = 0; i < dimX; i++) { // Derivatives in the x-direction if(i != dimX-1) gradx_upd[(dimX*dimY)*k + i+l] = u_upd[(dimX*dimY)*k + i+1+l] - u_upd[(dimX*dimY)*k + i+l]; else gradx_upd[(dimX*dimY)*k + i+l] = 0.0f; // Derivatives in the y-direction if(j != dimY-1) //grady_upd[(dimX*dimY)*k + i+l] = u_upd[(dimX*dimY)*k + i+dimY+l] -u_upd[(dimX*dimY)*k + i+l]; grady_upd[(dimX*dimY)*k + i+l] = u_upd[(dimX*dimY)*k + i+(j+1)*dimX] -u_upd[(dimX*dimY)*k + i+l]; else grady_upd[(dimX*dimY)*k + i+l] = 0.0f; }}} return 1; } float proxF(float *gx, float *gy, float *vx, float *vy, float sigma, int p, int q, int r, long dimX, long dimY, long dimZ) { // (S^p, \ell^1) norm decouples at each pixel // Spl1(gx, gy, vx, vy, sigma, p, num_channels, dim); float divsigma = 1.0f / sigma; // $\ell^{1,1,1}$-TV regularization // int i,j,k; // #pragma omp parallel for shared (gx,gy,vx,vy) private(i,j,k) // for(k = 0; k < dimZ; k++) { // for(i=0; i<dimX; i++) { // for(j=0; j<dimY; j++) { // gx[(dimX*dimY)*k + (i)*dimY + (j)] = SIGN(vx[(dimX*dimY)*k + (i)*dimY + (j)]) * MAX(fabs(vx[(dimX*dimY)*k + (i)*dimY + (j)]) - divsigma, 0.0f); // gy[(dimX*dimY)*k + (i)*dimY + (j)] = SIGN(vy[(dimX*dimY)*k + (i)*dimY + (j)]) * MAX(fabs(vy[(dimX*dimY)*k + (i)*dimY + (j)]) - divsigma, 0.0f); // }}} // Auxiliar vector float *proj, sum, shrinkfactor ; float M1,M2,M3,valuex,valuey,T,D,det,eig1,eig2,sig1,sig2,V1, V2, V3, V4, v0,v1,v2, mu1,mu2,sig1_upd,sig2_upd,t1,t2,t3; long i,j,k, ii, num; #pragma omp parallel for shared (gx,gy,vx,vy,p) private(i,ii,j,k,proj,num, sum, shrinkfactor, M1,M2,M3,valuex,valuey,T,D,det,eig1,eig2,sig1,sig2,V1, V2, V3, V4,v0,v1,v2,mu1,mu2,sig1_upd,sig2_upd,t1,t2,t3) for(i=0; i<dimX; i++) { for(j=0; j<dimY; j++) { proj = (float*) calloc (2,sizeof(float)); // Compute matrix $M\in\R^{2\times 2}$ M1 = 0.0f; M2 = 0.0f; M3 = 0.0f; for(k = 0; k < dimZ; k++) { valuex = vx[(dimX*dimY)*k + (j)*dimX + (i)]; valuey = vy[(dimX*dimY)*k + (j)*dimX + (i)]; M1 += (valuex * valuex); M2 += (valuex * valuey); M3 += (valuey * valuey); } // Compute eigenvalues of M T = M1 + M3; D = M1 * M3 - M2 * M2; det = sqrt(MAX((T * T / 4.0f) - D, 0.0f)); eig1 = MAX((T / 2.0f) + det, 0.0f); eig2 = MAX((T / 2.0f) - det, 0.0f); sig1 = sqrt(eig1); sig2 = sqrt(eig2); // Compute normalized eigenvectors V1 = V2 = V3 = V4 = 0.0f; if(M2 != 0.0f) { v0 = M2; v1 = eig1 - M3; v2 = eig2 - M3; mu1 = sqrtf(v0 * v0 + v1 * v1); mu2 = sqrtf(v0 * v0 + v2 * v2); if(mu1 > fTiny) { V1 = v1 / mu1; V3 = v0 / mu1; } if(mu2 > fTiny) { V2 = v2 / mu2; V4 = v0 / mu2; } } else { if(M1 > M3) { V1 = V4 = 1.0f; V2 = V3 = 0.0f; } else { V1 = V4 = 0.0f; V2 = V3 = 1.0f; } } // Compute prox_p of the diagonal entries sig1_upd = sig2_upd = 0.0f; if(p == 1) { sig1_upd = MAX(sig1 - divsigma, 0.0f); sig2_upd = MAX(sig2 - divsigma, 0.0f); } else if(p == INFNORM) { proj[0] = sigma * fabs(sig1); proj[1] = sigma * fabs(sig2); /*l1 projection part */ sum = fLarge; num = 0l; shrinkfactor = 0.0f; while(sum > 1.0f) { sum = 0.0f; num = 0; for(ii = 0; ii < 2; ii++) { proj[ii] = MAX(proj[ii] - shrinkfactor, 0.0f); sum += fabs(proj[ii]); if(proj[ii]!= 0.0f) num++; } if(num > 0) shrinkfactor = (sum - 1.0f) / num; else break; } /*l1 proj ends*/ sig1_upd = sig1 - divsigma * proj[0]; sig2_upd = sig2 - divsigma * proj[1]; } // Compute the diagonal entries of $\widehat{\Sigma}\Sigma^{\dagger}_0$ if(sig1 > fTiny) sig1_upd /= sig1; if(sig2 > fTiny) sig2_upd /= sig2; // Compute solution t1 = sig1_upd * V1 * V1 + sig2_upd * V2 * V2; t2 = sig1_upd * V1 * V3 + sig2_upd * V2 * V4; t3 = sig1_upd * V3 * V3 + sig2_upd * V4 * V4; for(k = 0; k < dimZ; k++) { gx[(dimX*dimY)*k + j*dimX + i] = vx[(dimX*dimY)*k + j*dimX + i] * t1 + vy[(dimX*dimY)*k + j*dimX + i] * t2; gy[(dimX*dimY)*k + j*dimX + i] = vx[(dimX*dimY)*k + j*dimX + i] * t2 + vy[(dimX*dimY)*k + j*dimX + i] * t3; } // Delete allocated memory free(proj); }} return 1; } float divergence(float *qx_upd, float *qy_upd, float *div_upd, long dimX, long dimY, long dimZ) { long i, j, k, l; #pragma omp parallel for shared(qx_upd,qy_upd,div_upd) private(i, j, k, l) for(k = 0; k < dimZ; k++) { for(j = 0; j < dimY; j++) { l = j * dimX; for(i = 0; i < dimX; i++) { if(i != dimX-1) { // ux[k][i+l] = u[k][i+1+l] - u[k][i+l] div_upd[(dimX*dimY)*k + i+1+l] -= qx_upd[(dimX*dimY)*k + i+l]; div_upd[(dimX*dimY)*k + i+l] += qx_upd[(dimX*dimY)*k + i+l]; } if(j != dimY-1) { // uy[k][i+l] = u[k][i+width+l] - u[k][i+l] //div_upd[(dimX*dimY)*k + i+dimY+l] -= qy_upd[(dimX*dimY)*k + i+l]; div_upd[(dimX*dimY)*k + i+(j+1)*dimX] -= qy_upd[(dimX*dimY)*k + i+l]; div_upd[(dimX*dimY)*k + i+l] += qy_upd[(dimX*dimY)*k + i+l]; } } } } return *div_upd; }
attribute.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % AAA TTTTT TTTTT RRRR IIIII BBBB U U TTTTT EEEEE % % A A T T R R I B B U U T E % % AAAAA T T RRRR I BBBB U U T EEE % % A A T T R R I B B U U T E % % A A T T R R IIIII BBBB UUU T EEEEE % % % % % % MagickCore Get / Set Image Attributes % % % % Software Design % % John Cristy % % October 2002 % % % % % % Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-view.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/draw.h" #include "magick/draw-private.h" #include "magick/effect.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/histogram.h" #include "magick/identify.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/magick.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/paint.h" #include "magick/pixel.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/segment.h" #include "magick/splay-tree.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/threshold.h" #include "magick/transform.h" #include "magick/utility.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e B o u n d i n g B o x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageBoundingBox() returns the bounding box of an image canvas. % % The format of the GetImageBoundingBox method is: % % RectangleInfo GetImageBoundingBox(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o bounds: Method GetImageBoundingBox returns the bounding box of an % image canvas. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport RectangleInfo GetImageBoundingBox(const Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickPixelPacket target[3], zero; RectangleInfo bounds; register const PixelPacket *p; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); bounds.width=0; bounds.height=0; bounds.x=(ssize_t) image->columns; bounds.y=(ssize_t) image->rows; GetMagickPixelPacket(image,&target[0]); image_view=AcquireCacheView(image); p=GetCacheViewVirtualPixels(image_view,0,0,1,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); return(bounds); } SetMagickPixelPacket(image,p,GetCacheViewAuthenticIndexQueue(image_view), &target[0]); GetMagickPixelPacket(image,&target[1]); p=GetCacheViewVirtualPixels(image_view,(ssize_t) image->columns-1,0,1,1, exception); SetMagickPixelPacket(image,p,GetCacheViewAuthenticIndexQueue(image_view), &target[1]); GetMagickPixelPacket(image,&target[2]); p=GetCacheViewVirtualPixels(image_view,0,(ssize_t) image->rows-1,1,1, exception); SetMagickPixelPacket(image,p,GetCacheViewAuthenticIndexQueue(image_view), &target[2]); status=MagickTrue; GetMagickPixelPacket(image,&zero); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickPixelPacket pixel; RectangleInfo bounding_box; register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register ssize_t x; if (status == MagickFalse) continue; #if defined(MAGICKCORE_OPENMP_SUPPORT) # pragma omp critical (MagickCore_GetImageBoundingBox) #endif bounding_box=bounds; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); if ((x < bounding_box.x) && (IsMagickColorSimilar(&pixel,&target[0]) == MagickFalse)) bounding_box.x=x; if ((x > (ssize_t) bounding_box.width) && (IsMagickColorSimilar(&pixel,&target[1]) == MagickFalse)) bounding_box.width=(size_t) x; if ((y < bounding_box.y) && (IsMagickColorSimilar(&pixel,&target[0]) == MagickFalse)) bounding_box.y=y; if ((y > (ssize_t) bounding_box.height) && (IsMagickColorSimilar(&pixel,&target[2]) == MagickFalse)) bounding_box.height=(size_t) y; p++; } #if defined(MAGICKCORE_OPENMP_SUPPORT) # pragma omp critical (MagickCore_GetImageBoundingBox) #endif { if (bounding_box.x < bounds.x) bounds.x=bounding_box.x; if (bounding_box.y < bounds.y) bounds.y=bounding_box.y; if (bounding_box.width > bounds.width) bounds.width=bounding_box.width; if (bounding_box.height > bounds.height) bounds.height=bounding_box.height; } } image_view=DestroyCacheView(image_view); if ((bounds.width == 0) || (bounds.height == 0)) (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "GeometryDoesNotContainImage","`%s'",image->filename); else { bounds.width-=(bounds.x-1); bounds.height-=(bounds.y-1); } return(bounds); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelDepth() returns the depth of a particular image channel. % % The format of the GetImageChannelDepth method is: % % size_t GetImageDepth(const Image *image,ExceptionInfo *exception) % size_t GetImageChannelDepth(const Image *image, % const ChannelType channel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport size_t GetImageDepth(const Image *image,ExceptionInfo *exception) { return(GetImageChannelDepth(image,CompositeChannels,exception)); } MagickExport size_t GetImageChannelDepth(const Image *image, const ChannelType channel,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; register ssize_t id; size_t *current_depth, depth, number_threads; ssize_t y; /* Compute image depth. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); number_threads=GetOpenMPMaximumThreads(); current_depth=(size_t *) AcquireQuantumMemory(number_threads, sizeof(*current_depth)); if (current_depth == (size_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); status=MagickTrue; for (id=0; id < (ssize_t) number_threads; id++) current_depth[id]=1; if ((image->storage_class == PseudoClass) && (image->matte == MagickFalse)) { register const PixelPacket *restrict p; register ssize_t i; p=image->colormap; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (i=0; i < (ssize_t) image->colors; i++) { const int id = GetOpenMPThreadId(); if (status == MagickFalse) continue; while (current_depth[id] < MAGICKCORE_QUANTUM_DEPTH) { MagickStatusType status; QuantumAny range; status=0; range=GetQuantumRange(current_depth[id]); if ((channel & RedChannel) != 0) status|=GetRedPixelComponent(p) != ScaleAnyToQuantum(ScaleQuantumToAny(GetRedPixelComponent(p), range),range); if ((channel & GreenChannel) != 0) status|=GetGreenPixelComponent(p) != ScaleAnyToQuantum(ScaleQuantumToAny(GetGreenPixelComponent(p), range),range); if ((channel & BlueChannel) != 0) status|=GetBluePixelComponent(p) != ScaleAnyToQuantum(ScaleQuantumToAny(GetBluePixelComponent(p), range),range); if (status == 0) break; current_depth[id]++; } p++; } depth=current_depth[0]; for (id=1; id < (ssize_t) number_threads; id++) if (depth < current_depth[id]) depth=current_depth[id]; current_depth=(size_t *) RelinquishMagickMemory(current_depth); return(depth); } image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) continue; indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { while (current_depth[id] < MAGICKCORE_QUANTUM_DEPTH) { MagickStatusType status; QuantumAny range; status=0; range=GetQuantumRange(current_depth[id]); if ((channel & RedChannel) != 0) status|=GetRedPixelComponent(p) != ScaleAnyToQuantum( ScaleQuantumToAny(GetRedPixelComponent(p),range),range); if ((channel & GreenChannel) != 0) status|=GetGreenPixelComponent(p) != ScaleAnyToQuantum( ScaleQuantumToAny(GetGreenPixelComponent(p),range),range); if ((channel & BlueChannel) != 0) status|=GetBluePixelComponent(p) != ScaleAnyToQuantum( ScaleQuantumToAny(GetBluePixelComponent(p),range),range); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) status|=GetOpacityPixelComponent(p) != ScaleAnyToQuantum( ScaleQuantumToAny(GetOpacityPixelComponent(p),range),range); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) status|=GetIndexPixelComponent(indexes+x) != ScaleAnyToQuantum(ScaleQuantumToAny(GetIndexPixelComponent(indexes+ x),range),range); if (status == 0) break; current_depth[id]++; } p++; } if (current_depth[id] == MAGICKCORE_QUANTUM_DEPTH) status=MagickFalse; } image_view=DestroyCacheView(image_view); depth=current_depth[0]; for (id=1; id < (ssize_t) number_threads; id++) if (depth < current_depth[id]) depth=current_depth[id]; current_depth=(size_t *) RelinquishMagickMemory(current_depth); return(depth); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e Q u a n t u m D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageQuantumDepth() returns the depth of the image rounded to a legal % quantum depth: 8, 16, or 32. % % The format of the GetImageQuantumDepth method is: % % size_t GetImageQuantumDepth(const Image *image, % const MagickBooleanType constrain) % % A description of each parameter follows: % % o image: the image. % % o constrain: A value other than MagickFalse, constrains the depth to % a maximum of MAGICKCORE_QUANTUM_DEPTH. % */ static inline double MagickMin(const double x,const double y) { if (x < y) return(x); return(y); } MagickExport size_t GetImageQuantumDepth(const Image *image, const MagickBooleanType constrain) { size_t depth; depth=image->depth; if (depth <= 8) depth=8; else if (depth <= 16) depth=16; else if (depth <= 32) depth=32; else if (depth <= 64) depth=64; if (constrain != MagickFalse) depth=(size_t) MagickMin((double) depth,(double) MAGICKCORE_QUANTUM_DEPTH); return(depth); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageType() returns the potential type of image: % % Bilevel Grayscale GrayscaleMatte % Palette PaletteMatte TrueColor % TrueColorMatte ColorSeparation ColorSeparationMatte % % To ensure the image type matches its potential, use SetImageType(): % % (void) SetImageType(image,GetImageType(image)); % % The format of the GetImageType method is: % % ImageType GetImageType(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ImageType GetImageType(const Image *image,ExceptionInfo *exception) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->colorspace == CMYKColorspace) { if (image->matte == MagickFalse) return(ColorSeparationType); return(ColorSeparationMatteType); } if (IsMonochromeImage(image,exception) != MagickFalse) return(BilevelType); if (IsGrayImage(image,exception) != MagickFalse) { if (image->matte != MagickFalse) return(GrayscaleMatteType); return(GrayscaleType); } if (IsPaletteImage(image,exception) != MagickFalse) { if (image->matte != MagickFalse) return(PaletteMatteType); return(PaletteType); } if (image->matte != MagickFalse) return(TrueColorMatteType); return(TrueColorType); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s G r a y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsGrayImage() returns MagickTrue if all the pixels in the image have the % same red, green, and blue intensities. % % The format of the IsGrayImage method is: % % MagickBooleanType IsGrayImage(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsGrayImage(const Image *image, ExceptionInfo *exception) { CacheView *image_view; ImageType type; register const PixelPacket *p; register ssize_t x; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->type == BilevelType) || (image->type == GrayscaleType) || (image->type == GrayscaleMatteType)) return(MagickTrue); if (image->colorspace == CMYKColorspace) return(MagickFalse); type=BilevelType; image_view=AcquireCacheView(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) { type=UndefinedType; break; } if ((type == BilevelType) && (IsMonochromePixel(p) == MagickFalse)) type=GrayscaleType; p++; } if (type == UndefinedType) break; } image_view=DestroyCacheView(image_view); if (type == UndefinedType) return(MagickFalse); ((Image *) image)->type=type; if ((type == GrayscaleType) && (image->matte != MagickFalse)) ((Image *) image)->type=GrayscaleMatteType; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M o n o c h r o m e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMonochromeImage() returns MagickTrue if all the pixels in the image have % the same red, green, and blue intensities and the intensity is either % 0 or QuantumRange. % % The format of the IsMonochromeImage method is: % % MagickBooleanType IsMonochromeImage(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsMonochromeImage(const Image *image, ExceptionInfo *exception) { CacheView *image_view; ImageType type; register ssize_t x; register const PixelPacket *p; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->type == BilevelType) return(MagickTrue); if (image->colorspace == CMYKColorspace) return(MagickFalse); type=BilevelType; image_view=AcquireCacheView(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsMonochromePixel(p) == MagickFalse) { type=UndefinedType; break; } p++; } if (type == UndefinedType) break; } image_view=DestroyCacheView(image_view); if (type == UndefinedType) return(MagickFalse); ((Image *) image)->type=type; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s O p a q u e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsOpaqueImage() returns MagickTrue if none of the pixels in the image have % an opacity value other than opaque (0). % % The format of the IsOpaqueImage method is: % % MagickBooleanType IsOpaqueImage(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsOpaqueImage(const Image *image, ExceptionInfo *exception) { CacheView *image_view; register const PixelPacket *p; register ssize_t x; ssize_t y; /* Determine if image is opaque. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->matte == MagickFalse) return(MagickTrue); image_view=AcquireCacheView(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetOpacityPixelComponent(p) != OpaqueOpacity) break; p++; } if (x < (ssize_t) image->columns) break; } image_view=DestroyCacheView(image_view); return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C h a n n e l D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageChannelDepth() sets the depth of the image. % % The format of the SetImageChannelDepth method is: % % MagickBooleanType SetImageDepth(Image *image,const size_t depth) % MagickBooleanType SetImageChannelDepth(Image *image, % const ChannelType channel,const size_t depth) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o depth: the image depth. % */ MagickExport MagickBooleanType SetImageDepth(Image *image, const size_t depth) { return(SetImageChannelDepth(image,CompositeChannels,depth)); } MagickExport MagickBooleanType SetImageChannelDepth(Image *image, const ChannelType channel,const size_t depth) { CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; QuantumAny range; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); if (GetImageDepth(image,&image->exception) <= (size_t) MagickMin((double) depth,(double) MAGICKCORE_QUANTUM_DEPTH)) { image->depth=depth; return(MagickTrue); } /* Scale pixels to desired depth. */ status=MagickTrue; range=GetQuantumRange(depth); exception=(&image->exception); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetRedPixelComponent(q,ScaleAnyToQuantum(ScaleQuantumToAny( GetRedPixelComponent(q),range),range)); if ((channel & GreenChannel) != 0) SetGreenPixelComponent(q,ScaleAnyToQuantum(ScaleQuantumToAny( GetGreenPixelComponent(q),range),range)); if ((channel & BlueChannel) != 0) SetBluePixelComponent(q,ScaleAnyToQuantum(ScaleQuantumToAny( GetBluePixelComponent(q),range),range)); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) SetOpacityPixelComponent(q,ScaleAnyToQuantum(ScaleQuantumToAny( GetOpacityPixelComponent(q),range),range)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetIndexPixelComponent(indexes+x,ScaleAnyToQuantum(ScaleQuantumToAny( GetIndexPixelComponent(indexes+x),range),range)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) { status=MagickFalse; continue; } } image_view=DestroyCacheView(image_view); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelPacket *restrict p; p=image->colormap; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (i=0; i < (ssize_t) image->colors; i++) { if ((channel & RedChannel) != 0) p->red=ScaleAnyToQuantum(ScaleQuantumToAny(p->red,range),range); if ((channel & GreenChannel) != 0) p->green=ScaleAnyToQuantum(ScaleQuantumToAny(p->green,range),range); if ((channel & BlueChannel) != 0) p->blue=ScaleAnyToQuantum(ScaleQuantumToAny(p->blue,range),range); if ((channel & OpacityChannel) != 0) p->opacity=ScaleAnyToQuantum(ScaleQuantumToAny(p->opacity,range), range); p++; } } image->depth=depth; return(status); }
local_parametrization.h
#ifndef LOCAL_PARAMETRIZATION #define LOCAL_PARAMETRIZATION #include "defines.h" ///fitting //#include <vcg/space/fitting3.h> #include <vcg/math/matrix33.h> #include <vcg/space/triangle2.h> #include "texcoord_optimization.h" #include "mesh_operators.h" //#include <vcg/complex/algorithms/point_sampling.h> //#define samples_area 80 template <class MeshType> void ParametrizeExternal(MeshType &to_parametrize) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::CoordType CoordType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::VertexType VertexType; std::vector<VertexType*> vertices; ///find first border vertex VertexType* Start=NULL; typename MeshType::VertexIterator Vi=to_parametrize.vert.begin(); while ((Start==NULL)&&(Vi<to_parametrize.vert.end())) { if (((*Vi).IsB())&&(!(*Vi).IsD())) Start=&(*Vi); Vi++; } if (Vi==to_parametrize.vert.end()) { assert(0); } ///get sorted border vertices FindSortedBorderVertices<MeshType>(to_parametrize,Start,vertices); //assert(vertices.size()>=4); ///find perimeter ScalarType perimeter=0; int size=vertices.size(); for (int i=0;i<size;i++) perimeter+=(vertices[i]->P()-vertices[(i+1)%size]->P()).Norm(); ///find scaling factor /*ScalarType Sperimeter=(2.0*M_PI)/perimeter;*/ ///set default texCoords for (Vi=to_parametrize.vert.begin();Vi!=to_parametrize.vert.end();Vi++) { (*Vi).T().U()=-2; (*Vi).T().V()=-2; } ///set border vertices typename std::vector<VertexType*>::iterator iteV; /*ScalarType curr_perim=0;*/ ScalarType curr_angle=0; vertices[0]->T().U()=cos(curr_angle); vertices[0]->T().V()=sin(curr_angle); //for (int i=1;i<vertices.size();i++) //{ // curr_perim+=(vertices[i]->P()-vertices[(i-1)]->P()).Norm(); // //curr_perim+=perimeter/(ScalarType)size; // curr_angle=curr_perim*Sperimeter; // vertices[i]->T().U()=cos(curr_angle); // vertices[i]->T().V()=sin(curr_angle); // assert((vertices[i]->T().U()>=-1)&&(vertices[i]->T().U()<=1)); // assert((vertices[i]->T().V()>=-1)&&(vertices[i]->T().V()<=1)); //} ScalarType anglediv=(2.0*M_PI)/(ScalarType)(vertices.size()); curr_angle=0; for (unsigned int i=1;i<vertices.size();i++) { curr_angle+=anglediv; vertices[i]->T().U()=cos(curr_angle); vertices[i]->T().V()=sin(curr_angle); assert((vertices[i]->T().U()>=-1)&&(vertices[i]->T().U()<=1)); assert((vertices[i]->T().V()>=-1)&&(vertices[i]->T().V()<=1)); } } template <class MeshType> void ParametrizeInternal(MeshType &to_parametrize) { typedef typename MeshType::ScalarType ScalarType; const ScalarType Eps=(ScalarType)0.0001; ///set internal vertices for (typename MeshType::VertexIterator Vi=to_parametrize.vert.begin();Vi!=to_parametrize.vert.end();Vi++) { //assert(!Vi->IsD()); if ((!Vi->IsB())&&(!Vi->IsD())) { ///find kernel std::vector<typename MeshType::VertexType*> star; getVertexStar<MeshType>(&(*Vi),star); ScalarType kernel=0; for (unsigned int k=0;k<star.size();k++) if (star[k]->IsB()) { ScalarType dist=((*Vi).P()-star[k]->P()).Norm(); if (dist<Eps) dist=Eps; //ScalarType peso=1.0/(dist); ScalarType peso=(dist)/star.size(); kernel+=(peso);//*dist); } assert(kernel>0); ///then find factor kernel=1.0/kernel; (*Vi).T().U()=0; (*Vi).T().V()=0; int num=0; ///find weighted media for (unsigned int k=0;k<star.size();k++) if (star[k]->IsB()) { ScalarType dist=((*Vi).P()-star[k]->P()).Norm(); if (dist<Eps) dist=Eps; //ScalarType peso=1.0/(dist); ScalarType peso=(dist)/star.size(); ScalarType kval=(peso)*kernel; assert(kval>0); (*Vi).T().U()+=kval*star[k]->T().U(); (*Vi).T().V()+=kval*star[k]->T().V(); num++; } ////on border case 2 neighbors ///go next to the center /*if (num==2) { (*Vi).T().U()/=2.0; (*Vi).T().V()/=2.0; }*/ /*ScalarType u=(*Vi).T().U(); ScalarType v=(*Vi).T().V();*/ assert(((*Vi).T().U()>=-1)&&((*Vi).T().U()<=1)); assert(((*Vi).T().V()>=-1)&&((*Vi).T().V()<=1)); } } ///smoothing of txcoords InitDampRestUV(to_parametrize); for (typename MeshType::VertexIterator Vi=to_parametrize.vert.begin();Vi!=to_parametrize.vert.end();Vi++) { if ((!Vi->IsB())&&(!Vi->IsD())) { std::vector<typename MeshType::VertexType*> star; getVertexStar<MeshType>(&(*Vi),star); vcg::Point2<ScalarType> UV=vcg::Point2<ScalarType>(0,0); for (unsigned int k=0;k<star.size();k++) UV+=star[k]->RestUV; UV/=(ScalarType)star.size(); (*Vi).T().P()=UV; } } } template <class FaceType> typename FaceType::CoordType InterpolatePos (FaceType* f, const typename FaceType::CoordType &bary) {return (f->V(0)->P()*bary.X()+f->V(1)->P()*bary.Y()+f->V(2)->P()*bary.Z());} template <class FaceType> typename FaceType::CoordType InterpolateRPos (FaceType* f,const typename FaceType::CoordType &bary) { return (f->V(0)->RPos*bary.X()+f->V(1)->RPos*bary.Y()+f->V(2)->RPos*bary.Z()); } template <class FaceType> typename FaceType::CoordType InterpolateNorm (FaceType* f, const typename FaceType::CoordType &bary) { typedef typename FaceType::CoordType CoordType; CoordType n0=f->V(0)->N(); CoordType n1=f->V(1)->N(); CoordType n2=f->V(2)->N(); return (n0*bary.X()+n1*bary.Y()+n2*bary.Z()); } template <class ScalarType> int Approx(const ScalarType &value) { ScalarType val0=floor(value); ScalarType val1=ceil(value); if (fabs(val0-value)<fabs(val1-value)) return ((int)val0); else return ((int)val1); } template <class FaceType> vcg::Point3i InterpolateColor (FaceType* f,const typename FaceType::CoordType &bary) { typedef typename FaceType::ScalarType ScalarType; vcg::Color4b c0=f->V(0)->C(); vcg::Color4b c1=f->V(1)->C(); vcg::Color4b c2=f->V(2)->C(); double R=(ScalarType)c0.X()*bary.X()+(ScalarType)c1.X()*bary.Y()+(ScalarType)c2.X()*bary.Z(); double G=(ScalarType)c0.Y()*bary.X()+(ScalarType)c1.Y()*bary.Y()+(ScalarType)c2.Y()*bary.Z(); double B=(ScalarType)c0.Z()*bary.X()+(ScalarType)c1.Z()*bary.Y()+(ScalarType)c2.Z()*bary.Z(); vcg::Point3i p=vcg::Point3i(Approx(R),Approx(G),Approx(B)); assert(p.X()<=255); assert(p.Y()<=255); assert(p.Z()<=255); return (p); } template <class VertexType> typename VertexType::CoordType ProjectPos(const VertexType &v) { typedef typename VertexType::FaceType FaceType; typedef typename VertexType::CoordType CoordType; FaceType *f=v.father; CoordType b=v.Bary; return (InterpolatePos<FaceType>(f,b)); } template <class VertexType> typename VertexType::CoordType Warp(const VertexType* v) { typename VertexType::FaceType * father=v->father; typename VertexType::CoordType proj=father->P(0)*v->Bary.X()+father->P(1)*v->Bary.Y()+father->P(2)*v->Bary.Z(); return proj; } template <class VertexType> typename VertexType::CoordType WarpRpos(const VertexType* v) { typename VertexType::FaceType * father=v->father; typename VertexType::CoordType proj=father->V(0)->RPos*v->Bary.X()+father->V(1)->RPos*v->Bary.Y()+father->V(2)->RPos*v->Bary.Z(); return proj; } template <class MeshType> typename MeshType::ScalarType EstimateLenghtByParam (const typename MeshType::VertexType* v0, const typename MeshType::VertexType* v1, typename MeshType::FaceType* on_edge[2]) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::CoordType CoordType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::ScalarType ScalarType; // assert((on_edge.size()==0)||(on_edge.size()==1)); ScalarType estimated[2]={0,0}; int num[2]={0,0}; for (int i=0;i<2;i++) { FaceType *test_face=on_edge[i]; int edge_index=EdgeIndex(test_face,v0,v1); FaceType *Fopp=test_face->FFp(edge_index); if (test_face->vertices_bary.size()<2) { ScalarType dist=Distance(v0->RPos,v1->RPos); //#pragma omp atomic estimated[i]+=dist; num[i]=0; continue; } ///collect vertices std::vector<VertexType*> vertices; vertices.reserve(test_face->vertices_bary.size()); for (unsigned int k=0;k<test_face->vertices_bary.size();k++) vertices.push_back(test_face->vertices_bary[k].first); ///collect faces std::vector<FaceType*> faces; getSharedFace<MeshType>(vertices,faces); ///get border edges std::vector<std::pair<VertexType*,VertexType*> > edges; for (unsigned int j=0;j<faces.size();j++) { FaceType*f=faces[j]; ///find if there is an on-edge edge bool found=false; int k=0; while ((k<3)&&(!found)) { if ((f->V0(k)->father==test_face)&& (f->V1(k)->father==test_face)&& (f->V2(k)->father==Fopp)) { edges.push_back(std::pair<VertexType*,VertexType*>(f->V0(k),f->V1(k))); found=true; } k++; } } ///find if there's ant edge return inital lenght if (edges.size()==0) { estimated[i]+=(Distance(v0->RPos,v1->RPos)); num[i]=0; continue; } else { //get edge direction ///store the two nearest for each vertex /*VertexType *n0=edges[0].first; VertexType *n1=edges[0].second; ScalarType d0=(Warp(n0)-v0->P()).Norm(); ScalarType d1=(Warp(n1)-v1->P()).Norm();*/ //CoordType edgedir=v0->cP()-v1->cP(); CoordType edgedir=v0->RPos-v1->RPos; edgedir.Normalize(); num[i]=edges.size(); for (unsigned int e=0;e<edges.size();e++) { VertexType *vH0=edges[e].first; VertexType *vH1=edges[e].second; ///project points over the plane /*CoordType proj0=Warp(vH0); CoordType proj1=Warp(vH1);*/ CoordType proj0=WarpRpos(vH0); CoordType proj1=WarpRpos(vH1); CoordType dirproj=proj0-proj1; dirproj.Normalize(); //estimated[i]+=fabs(dirproj*edgedir)*((vH0->P()-vH1->P()).Norm()); //#pragma omp atomic estimated[i]+=fabs(dirproj*edgedir)*((vH0->RPos-vH1->RPos).Norm()); } } } ///media of estimated values ScalarType alpha0,alpha1; ScalarType max_num=abstraction_num; if (num[0]>=max_num) alpha0=1; else alpha0=num[0]/max_num; if (num[1]>=max_num) alpha1=1; else alpha1=num[1]/max_num; estimated[0]=alpha0*estimated[0]+(1.0-alpha0)*(Distance(v0->RPos,v1->RPos)); estimated[1]=alpha1*estimated[1]+(1.0-alpha1)*(Distance(v0->RPos,v1->RPos)); return((estimated[0]+estimated[1])/2.0); } template <class MeshType> void MeanVal(const std::vector<vcg::Point2<typename MeshType::ScalarType> > &Points, std::vector<typename MeshType::ScalarType> &Lamda, typename MeshType::CoordType &p) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::CoordType CoordType; int size=Points.size(); Lamda.resize(size); ScalarType sum=0; for (int i=0;i<size;i++) { int size=Points.size()-1; vcg::Point2<ScalarType> Pcurr=Points[i]; vcg::Point2<ScalarType> Pprev=Points[(i+(size-1))%size]; vcg::Point2<ScalarType> Pnext=Points[(i+1)%size]; CoordType v0=Pprev-p; CoordType v1=Pcurr-p; CoordType v2=Pnext-p; ScalarType l=v1.Norm(); v0.Normalize(); v1.Normalize(); v2.Normalize(); ScalarType Alpha0=acos(v0*v1); ScalarType Alpha1=acos(v1*v2); Lamda[i]=(tan(Alpha0/2.0)+tan(Alpha1/2.0))/l; sum+=Lamda[i]; } ///normalization for (int i=0;i<size;i++) Lamda[i]/=sum; } template <class FaceType> typename FaceType::ScalarType EstimateAreaByParam(const FaceType* f) { typedef typename FaceType::VertexType VertexType; typedef typename FaceType::ScalarType ScalarType; int num=0; ScalarType estimated=0; for (unsigned int k=0;k<f->vertices_bary.size();k++) { VertexType *HresVert=f->vertices_bary[k].first; estimated+=HresVert->area; num++; } ///media of estimated values ScalarType alpha; ScalarType max_num=abstraction_num; if (num>=max_num) alpha=1; else alpha=num/max_num; ScalarType Rarea=((f->cV(1)->RPos-f->cV(0)->RPos)^(f->cV(2)->RPos-f->cV(0)->RPos)).Norm()/2.0; estimated=alpha*estimated+(1.0-alpha)*Rarea; return(estimated); } template <class MeshType> typename MeshType::ScalarType EstimateAreaByParam (const typename MeshType::VertexType* v0, const typename MeshType::VertexType* v1, typename MeshType::FaceType* on_edge[2]) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::ScalarType ScalarType; //MeshType::PerVertexAttributeHandle<AuxiliaryVertData> handle = vcg::tri::Allocator<MeshType>::GetPerVertexAttribute<AuxiliaryVertData>(mesh,"AuxiliaryVertData"); ScalarType estimated[2]={0,0}; int num[2]={0,0}; VertexType *v2[2]; for (int i=0;i<2;i++) { FaceType *test_face=on_edge[i]; for (int k=0;k<3;k++) if ((test_face->V(k)!=v0)&&(test_face->V(k)!=v1)) v2[i]=test_face->V(k); for (unsigned int k=0;k<test_face->vertices_bary.size();k++) { VertexType *brother=test_face->vertices_bary[k].first; estimated[i]+=brother->area; //estimated[i]+=handle[brother].area; num[i]++; } } ///media of estimated values ScalarType alpha0,alpha1; ScalarType max_num=abstraction_num;//20 if (num[0]>=max_num) alpha0=1; else alpha0=num[0]/max_num; if (num[1]>=max_num) alpha1=1; else alpha1=num[1]/max_num; ScalarType Rarea0=((on_edge[0]->V(1)->RPos-on_edge[0]->V(0)->RPos)^(on_edge[0]->V(2)->RPos-on_edge[0]->V(0)->RPos)).Norm()/2.0; ScalarType Rarea1=((on_edge[1]->V(1)->RPos-on_edge[1]->V(0)->RPos)^(on_edge[1]->V(2)->RPos-on_edge[1]->V(0)->RPos)).Norm()/2.0; estimated[0]=alpha0*estimated[0]+(1.0-alpha0)*Rarea0; estimated[1]=alpha1*estimated[1]+(1.0-alpha1)*Rarea1; return((estimated[0]+estimated[1])/2.0); } ///template class used to sample surface template <class FaceType> class VertexSampler{ typedef typename FaceType::CoordType CoordType; public: std::vector<CoordType> points; void AddFace(const FaceType &f,const CoordType & bary) {points.push_back(f.P(0)*bary.X()+f.P(1)*bary.Y()+f.P(2)*bary.Z());} }; ///sample 3d vertex possible's position ///using area criterion //template <class MeshType> //void SamplingPoints(MeshType &mesh, // std::vector<typename MeshType::CoordType> &pos) //{ // typedef typename MeshType::CoordType CoordType; // typedef VertexSampler<MeshType::FaceType> Sampler; // pos.reserve(samples_area); // Sampler ps; // ps.points.reserve(samples_area); // // vcg::tri::SurfaceSampling<MeshType,Sampler>::Montecarlo(mesh,ps,samples_area); // pos=std::vector<CoordType>(ps.points.begin(),ps.points.end()); //} template <class MeshType> void InitDampRestUV(MeshType &m) { for (unsigned int i=0;i<m.vert.size();i++) m.vert[i].RestUV=m.vert[i].T().P(); } template <class MeshType> void RestoreRestUV(MeshType &m) { for (unsigned int i=0;i<m.vert.size();i++) m.vert[i].T().P()=m.vert[i].RestUV; } #ifndef IMPLICIT ///parametrize a submesh from trinagles that are incident on vertices template <class MeshType> void ParametrizeLocally(MeshType &parametrized, bool fix_boundary=true, bool init_border=true) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::CoordType CoordType; //const ScalarType epsilon=(ScalarType)0.0001; ///save old positions std::vector<CoordType> positions; positions.resize(parametrized.vert.size()); ///set rest position for (unsigned int i=0;i<parametrized.vert.size();i++) { positions[i]=parametrized.vert[i].P(); parametrized.vert[i].P()=parametrized.vert[i].RPos; } UpdateTopologies(&parametrized); if (init_border) ParametrizeExternal(parametrized); ParametrizeInternal(parametrized); //for (int i=0;i<parametrized.vert.size();i++) // parametrized.vert[i].RPos=parametrized.vert[i].P(); vcg::tri::MeanValueTexCoordOptimization<MeshType> opt(parametrized); vcg::tri::AreaPreservingTexCoordOptimization<MeshType> opt1(parametrized); opt.SetSpeed((ScalarType)0.0005); InitDampRestUV(parametrized); if (fix_boundary) { opt.TargetEquilateralGeometry(); //opt.TargetCurrentGeometry(); opt.SetBorderAsFixed(); opt.IterateUntilConvergence((ScalarType)0.000001,100); /*opt.Iterate(); opt.Iterate();*/ } else { opt1.TargetCurrentGeometry(); //opt1.SetBorderAsFixed(); opt1.IterateUntilConvergence((ScalarType)0.000001,200); } ///assert parametrization for (unsigned int i=0;i<parametrized.face.size();i++) { FaceType *f=&parametrized.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); vcg::Triangle2<typename MeshType::ScalarType> t2d=vcg::Triangle2<typename MeshType::ScalarType>(tex0,tex1,tex2); #ifndef NDEBUG ScalarType area=(tex1-tex0)^(tex2-tex0); assert(area>0); #endif } ///restore position for (unsigned int i=0;i<parametrized.vert.size();i++) parametrized.vert[i].P()=positions[i]; } #else ///parametrize a submesh keeping fixed the borders template <class MeshType> void ParametrizeLocally(MeshType &parametrized, bool fix_boundary=true, bool init_border=true) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::CoordType CoordType; ///save old positions std::vector<CoordType> positions; positions.resize(parametrized.vert.size()); ///set rest position for (unsigned int i=0;i<parametrized.vert.size();i++) { positions[i]=parametrized.vert[i].P(); parametrized.vert[i].P()=parametrized.vert[i].RPos; } UpdateTopologies(&parametrized); if (init_border) ParametrizeExternal(parametrized); ParametrizeInternal(parametrized); //for (int i=0;i<parametrized.vert.size();i++) // parametrized.vert[i].RPos=parametrized.vert[i].P(); vcg::tri::MeanValueTexCoordOptimization<MeshType> opt(parametrized); vcg::tri::AreaPreservingTexCoordOptimization<MeshType> opt1(parametrized); opt.SetSpeed((ScalarType)0.0005); InitDampRestUV(parametrized); if (fix_boundary) { opt.TargetEquilateralGeometry(); //opt.TargetCurrentGeometry(); opt.SetBorderAsFixed(); opt.IterateUntilConvergence((ScalarType)0.000001,100); /*opt.Iterate(); opt.Iterate();*/ } else { opt1.TargetCurrentGeometry(); //opt1.SetBorderAsFixed(); opt1.IterateUntilConvergence((ScalarType)0.000001,200); } ///assert parametrization for (unsigned int i=0;i<parametrized.face.size();i++) { FaceType *f=&parametrized.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); vcg::Triangle2<typename MeshType::ScalarType> t2d=vcg::Triangle2<typename MeshType::ScalarType>(tex0,tex1,tex2); #ifndef NDEBUG ScalarType area=(tex1-tex0)^(tex2-tex0); assert(area>0); #endif } ///restore position for (unsigned int i=0;i<parametrized.vert.size();i++) parametrized.vert[i].P()=positions[i]; } #endif template <class MeshType> void ForceInParam(vcg::Point2<typename MeshType::ScalarType> &UV,MeshType &domain) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::CoordType CoordType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::VertexType VertexType; ScalarType minDist=(ScalarType)1000.0; vcg::Point2<ScalarType> closest; vcg::Point2<ScalarType> center=vcg::Point2<ScalarType>(0,0); for (unsigned int i=0;i<domain.face.size();i++) { FaceType *f=&domain.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); center+=tex0; center+=tex1; center+=tex2; vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType dist; vcg::Point2<ScalarType> temp; t2d.PointDistance(UV,dist,temp); if (dist<minDist) { minDist=dist; closest=temp; } } center/=(ScalarType)(domain.face.size()*3); UV=closest*(ScalarType)0.95+center*(ScalarType)0.05; } template <class VertexType> bool testParamCoords(VertexType *v) { typedef typename VertexType::ScalarType ScalarType; ScalarType eps=(ScalarType)0.00001; if (!(((v->T().P().X()>=-1-eps)&&(v->T().P().X()<=1+eps)&& (v->T().P().Y()>=-1-eps)&&(v->T().P().Y()<=1+eps)))) return (false); return true; } template <class MeshType> bool testParamCoords(MeshType &domain) { for (unsigned int i=0;i<domain.vert.size();i++) { typename MeshType::VertexType *v=&domain.vert[i]; bool b=testParamCoords<typename MeshType::VertexType>(v); if (!b) { #ifndef _MESHLAB printf("\n position %lf,%lf \n",v->T().U(),v->T().V()); #endif return false; } } return true; } template <class CoordType> bool testBaryCoords(CoordType &bary) { typedef typename CoordType::ScalarType ScalarType; ///test float eps=(ScalarType)0.0001; if(!(fabs(bary.X()+bary.Y()+bary.Z()-1.0)<eps)) return false; if(!((bary.X()<=1.0)&&(bary.X()>=-eps)&&(bary.Y()<=1.0)&&(bary.Y()>=-eps)&&(bary.Z()<=1.0)&&(bary.Z()>=-eps))) return false; return true; } template <class CoordType> bool NormalizeBaryCoords(CoordType &bary) { typedef typename CoordType::ScalarType ScalarType; ScalarType EPS=(ScalarType)0.00000001; bool isOK=testBaryCoords(bary); if (!isOK) return false; typedef typename CoordType::ScalarType ScalarType; ///test <0 if (bary.X()<0) bary.X()=EPS; if (bary.Y()<0) bary.Y()=EPS; if (bary.Z()<0) bary.Z()=EPS; ///test >1 if (bary.X()>1.0) bary.X()=1.0-EPS; if (bary.Y()>1.0) bary.Y()=1.0-EPS; if (bary.Z()>1.0) bary.Z()=1.0-EPS; ///test sum ScalarType diff=bary.X()+bary.Y()+bary.Z()-1.0; bary.X()-=(diff+EPS); if (bary.X()<0) bary.X()=EPS; return true; } template <class MeshType> void AssingFather(typename MeshType::VertexType &v, typename MeshType::FaceType *father, typename MeshType::CoordType &bary, MeshType & domain) { #ifdef _DEBUG const typename MeshType::ScalarType eps=(typename MeshType::ScalarType)0.00001; assert((father-&(*domain.face.begin()))<(int)domain.face.size()); assert(!(father->IsD())); assert(!(father==NULL)); assert((bary.X()>=0)&&(bary.X()<=1)&& (bary.Y()>=0)&&(bary.Y()<=1)&& (bary.Z()>=0)&&(bary.Z()<=1)&& ((bary.X()+bary.Y()+bary.Z())<=1+eps)&& ((bary.X()+bary.Y()+bary.Z())>=1-eps)); #endif v.father=father; v.Bary=bary; } template <class MeshType> bool testParametrization(MeshType &domain, MeshType &Hlev) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::CoordType CoordType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::VertexType VertexType; bool is_good=true; int num_del=0; int num_null=0; int fath_son=0; int wrong_address=0; for (unsigned int i=0;i<Hlev.vert.size();i++) { VertexType *v=&Hlev.vert[i]; bool isGoodAddr=true; if ((v->father-&(*domain.face.begin()))>=(int)domain.face.size()) { printf("\n ADDRESS EXCEEDS OF %d \n",v->father-&(*domain.face.begin())); wrong_address++; is_good=false; isGoodAddr=false; } if ((isGoodAddr)&&(v->father==NULL)) { //printf("\n PAR ERROR : father NULL\n"); num_null++; is_good=false; } if ((isGoodAddr)&&(v->father->IsD())) { //printf("\n PAR ERROR : father DELETED \n"); num_del++; is_good=false; } if ((isGoodAddr)&&(!(((v->Bary.X()>=0)&&(v->Bary.X()<=1))&& ((v->Bary.Y()>=0)&&(v->Bary.Y()<=1))&& ((v->Bary.Z()>=0)&&(v->Bary.Z()<=1))))) { printf("\n PAR ERROR 0: bary coords exceeds: %f,%f,%f \n",v->Bary.X(),v->Bary.Y(),v->Bary.Z()); /*system("pause");*/ NormalizeBaryCoords(v->Bary); is_good=false; } } for (unsigned int i=0;i<domain.face.size();i++) { FaceType *face=&domain.face[i]; if (!face->IsD()) { for (unsigned int j=0;j<face->vertices_bary.size();j++) { VertexType *v=face->vertices_bary[j].first; if (v->father!=face) { //printf("\n PAR ERROR : Father<->son \n"); fath_son++; v->father=face; is_good=false; } } } } if (num_del>0) printf("\n PAR ERROR %d Father isDel \n",num_del); if (num_null>0) printf("\n PAR ERROR %d Father isNull \n",num_null); if (fath_son>0) printf("\n PAR ERROR %d Father<->son \n",fath_son); if (wrong_address>0) { printf("\n PAR ERROR %d Wrong Address Num Faces %d\n",wrong_address,domain.fn); /*system("pause");*/ } return (is_good); } template <class MeshType> bool NonFolded(MeshType &parametrized) { //const ScalarType epsilon=0.00001; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::CoordType CoordType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::VertexType VertexType; ///assert parametrization for (unsigned int i=0;i<parametrized.face.size();i++) { FaceType *f=&parametrized.face[i]; if (!((f->V(0)->IsB())&&(f->V(1)->IsB())&&(f->V(2)->IsB()))) { vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType area=(tex1-tex0)^(tex2-tex0); if (area<=0) return false; } } return true; } template <class MeshType> bool NonFolded(MeshType &parametrized,std::vector<typename MeshType::FaceType*> &folded) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::CoordType CoordType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::VertexType VertexType; const ScalarType epsilon=(ScalarType)0.00001; folded.resize(0); ///assert parametrization for (unsigned int i=0;i<parametrized.face.size();i++) { FaceType *f=&parametrized.face[i]; if (!((f->V(0)->IsB())&&(f->V(1)->IsB())&&(f->V(2)->IsB()))) { vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType area=(tex1-tex0)^(tex2-tex0); if (area<=epsilon) folded.push_back(f); } } return (folded.size()==0); } //getFoldedFaces(std::vector) ///parametrize a submesh from trinagles that are incident on vertices with equi-area subdivision template <class MeshType> void ParametrizeStarEquilateral(MeshType &parametrized, const typename MeshType::ScalarType &radius=1) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::CoordType CoordType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::VertexType VertexType; UpdateTopologies(&parametrized); //set borders ///find first border & non border vertex std::vector<VertexType*> non_border; VertexType* Start=NULL; for (unsigned int i=0;i<parametrized.vert.size();i++) { VertexType* vert=&parametrized.vert[i]; if ((Start==NULL)&&(vert->IsB())) Start=vert; if (!vert->IsB()) non_border.push_back(vert); } assert(non_border.size()!=0); ///get sorted border vertices std::vector<VertexType*> vertices; FindSortedBorderVertices<MeshType>(parametrized,Start,vertices); ///set border vertices int num=vertices.size(); typename std::vector<VertexType*>::iterator iteV; ScalarType curr_angle=0; vertices[0]->T().U()=cos(curr_angle)*radius; vertices[0]->T().V()=sin(curr_angle)*radius; ScalarType division=(2*M_PI)/(ScalarType)num; ///set border for (unsigned int i=1;i<vertices.size();i++) { curr_angle+=division; vertices[i]->T().U()=radius*cos(curr_angle); vertices[i]->T().V()=radius*sin(curr_angle); } if (non_border.size()==1) { ///if non-border vertex is one then set it to zero otherwise ///set it to the average of neighbors non_border[0]->T().P()=vcg::Point2<ScalarType>(0,0); } else { ///set media of star vertices assert(non_border.size()==2); for (unsigned int i=0;i<non_border.size();i++) { VertexType *v=non_border[i]; v->T().P()=vcg::Point2<ScalarType>(0,0); int ariety_vert=0; std::vector<VertexType*> star; getVertexStar<MeshType>(v,star); for (unsigned int k=0;k<star.size();k++) { if ((!star[k]->IsD())&&(star[k]->IsB())) { v->T().P()+=star[k]->T().P(); ariety_vert++; } } v->T().P()/=(ScalarType)ariety_vert; } ///test particular cases if (!NonFolded(parametrized)) { std::vector<VertexType*> shared; getSharedVertexStar<MeshType>(non_border[0],non_border[1],shared); assert(shared.size()==2); assert(shared[0]->IsB()); assert(shared[1]->IsB()); assert(shared[0]!=shared[1]); //ScalarType epsilon=(ScalarType)0.001; ///then get the media of two shared vertices vcg::Point2<ScalarType> uvAve=shared[0]->T().P()+shared[1]->T().P(); assert(uvAve.Norm()>(ScalarType)0.001); uvAve.Normalize(); vcg::Point2<ScalarType> p0=uvAve*(ScalarType)0.3; vcg::Point2<ScalarType> p1=uvAve*(ScalarType)(-0.3); ///then test and set right assignement non_border[0]->T().P()=p0; non_border[1]->T().P()=p1; if (!NonFolded(parametrized)){ non_border[0]->T().P()=p1; non_border[1]->T().P()=p0; } } } ///final assert parametrization assert(NonFolded(parametrized)); } ///given the mesh and the two edges (same) seen from face[0] and face[1] of the mesh construct ///a diamond parametrization using equilateral triangles of edge edge_len template <class MeshType> void ParametrizeDiamondEquilateral(MeshType &parametrized, const int &edge0,const int &edge1, const typename MeshType::ScalarType &edge_len=1) { typedef typename MeshType::FaceType FaceType; typedef typename FaceType::CoordType CoordType; typedef typename FaceType::ScalarType ScalarType; typedef typename FaceType::VertexType VertexType; ScalarType h=(sqrt(3.0)/2.0)*edge_len; FaceType *fd0=&parametrized.face[0]; #ifndef NDEBUG FaceType *fd1=&parametrized.face[1]; #endif assert(fd0->FFp(edge0)==fd1); assert(fd1->FFp(edge1)==fd0); ///get 2 vertex on the edge VertexType *v0=fd0->V(edge0); VertexType *v1=fd0->V((edge0+1)%3); #ifndef NDEBUG VertexType *vtest0=fd1->V(edge1); VertexType *vtest1=fd1->V((edge1+1)%3); assert(v0!=v1); assert(vtest0!=vtest1); assert(((v0==vtest0)&&(v1==vtest1))||((v1==vtest0)&&(v0==vtest1))); #endif ///other 2 vertex VertexType *v2=parametrized.face[0].V((edge0+2)%3); VertexType *v3=parametrized.face[1].V((edge1+2)%3); assert((v2!=v3)&&(v0!=v2)&&(v0!=v3)&&(v1!=v2)&&(v1!=v3)); ///assing texcoords v0->T().P()=vcg::Point2<ScalarType>(0,-edge_len/2.0); v1->T().P()=vcg::Point2<ScalarType>(0,edge_len/2.0); v2->T().P()=vcg::Point2<ScalarType>(-h,0); v3->T().P()=vcg::Point2<ScalarType>(h,0); ///test assert(NonFolded(parametrized)); } ///given the mesh and the two edges (same) seen from face[0] and face[1] of the mesh construct ///a diamond parametrization using equilateral triangles of edge edge_len template <class MeshType> void ParametrizeFaceEquilateral(MeshType &parametrized, const typename MeshType::ScalarType &edge_len=1) { typedef typename MeshType::FaceType FaceType; typedef typename FaceType::CoordType CoordType; typedef typename FaceType::ScalarType ScalarType; typedef typename FaceType::VertexType VertexType; ScalarType h=(sqrt(3.0)/2.0)*edge_len; FaceType *f_param=&(parametrized.face[0]); f_param->V(0)->T().P()=vcg::Point2<ScalarType>(edge_len/2.0,0); f_param->V(1)->T().P()=vcg::Point2<ScalarType>(0,h); f_param->V(2)->T().P()=vcg::Point2<ScalarType>(-edge_len/2.0,0); } ///parametrize and create a submesh from trinagles that are incident on /// vertices .... seturn a vetor of original faces template <class MeshType> void ParametrizeLocally(MeshType &parametrized, const std::vector<typename MeshType::VertexType*> &subset, std::vector<typename MeshType::FaceType*> &orderedFaces, std::vector<typename MeshType::VertexType*> &orderedVertex) { typedef typename MeshType::FaceType FaceType; typedef typename FaceType::CoordType CoordType; typedef typename FaceType::ScalarType ScalarType; typedef typename FaceType::VertexType VertexType; orderedFaces.clear(); std::vector<VertexType*> vertices; ///get faces referenced by vertices getSharedFace<MeshType>(subset,orderedFaces); ///do a first copy of the mesh ///and parametrize it ///NB: order of faces is mantained CopyMeshFromFaces<MeshType>(orderedFaces,orderedVertex,parametrized); //CreateMeshVertexStar(subset,orderedFaces,parametrized); ParametrizeLocally(parametrized); } template <class MeshType> void InterpolateUV(const typename MeshType::FaceType* f, const typename MeshType::CoordType &bary, typename MeshType::ScalarType &U, typename MeshType::ScalarType &V) { U=bary.X()*f->cV(0)->T().U()+bary.Y()*f->cV(1)->T().U()+bary.Z()*f->cV(2)->T().U(); V=bary.X()*f->cV(0)->T().V()+bary.Y()*f->cV(1)->T().V()+bary.Z()*f->cV(2)->T().V(); /*if ((!((U>=-1)&&(U<=1)))||(!((V>=-1)&&(V<=1)))) { printf("Bary:%f,%f,%f \n",bary.X(),bary.Y(),bary.Z()); printf("texCoord:%f,%f \n",U,V); assert(0); }*/ //assert ((U>=-1)&&(U<=1)); //assert ((V>=-1)&&(V<=1)); } template <class MeshType> bool GetBaryFaceFromUV(const MeshType &m, const typename MeshType::ScalarType &U, const typename MeshType::ScalarType &V, typename MeshType::CoordType &bary, int &index) { typedef typename MeshType::ScalarType ScalarType; const ScalarType _EPSILON = ScalarType(0.0000001); /*assert ((U>=-1)&&(U<=1)); assert ((V>=-1)&&(V<=1));*/ for (unsigned int i=0;i<m.face.size();i++) { const typename MeshType::FaceType *f=&m.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->cV(0)->T().U(),f->cV(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->cV(1)->T().U(),f->cV(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->cV(2)->T().U(),f->cV(2)->T().V()); vcg::Point2<ScalarType> test=vcg::Point2<ScalarType>(U,V); vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType area=(tex1-tex0)^(tex2-tex0); //assert(area>-_EPSILON); ///then find if the point 2d falls inside if ((area>_EPSILON)&&(t2d.InterpolationParameters(test,bary.X(),bary.Y(),bary.Z()))) { index=i; ///approximation errors ScalarType sum=0; for (int x=0;x<3;x++) { if (((bary[x])<=0)&&(bary[x]>=-_EPSILON)) bary[x]=0; else if (((bary[x])>=1)&&(bary[x]<=1+_EPSILON)) bary[x]=1; sum+=bary[x]; } if (sum==0) printf("error SUM %f \n",sum); bary/=sum; return true; } } return (false); } template <class FaceType> bool GetBaryFaceFromUV(std::vector<FaceType*> faces, const typename FaceType::ScalarType &U, const typename FaceType::ScalarType &V, typename FaceType::CoordType &bary, int &index) { typedef typename FaceType::CoordType CoordType; typedef typename FaceType::ScalarType ScalarType; typedef typename FaceType::VertexType VertexType; typedef typename FaceType::ScalarType ScalarType; const ScalarType _EPSILON = ScalarType(0.0000001); /*assert ((U>=-1)&&(U<=1)); assert ((V>=-1)&&(V<=1));*/ for (unsigned int i=0;i<faces.size();i++) { FaceType *f=faces[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); vcg::Point2<ScalarType> test=vcg::Point2<ScalarType>(U,V); vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType area=fabs((tex1-tex0)^(tex2-tex0)); //assert(area>-_EPSILON); ///then find if the point 2d falls inside if ((area>_EPSILON)&&(t2d.InterpolationParameters(test,bary.X(),bary.Y(),bary.Z()))) { index=i; ///approximation errors ScalarType sum=0; for (int x=0;x<3;x++) { if (((bary[x])<=0)&&(bary[x]>=-_EPSILON)) bary[x]=0; else if (((bary[x])>=1)&&(bary[x]<=1+_EPSILON)) bary[x]=1; sum+=fabs(bary[x]); } if (sum==0) printf("error SUM %f \n",sum); bary/=sum; /*if (!((bary.X()>=0)&& (bary.X()<=1))) printf("error %f \n",bary.X());*/ /*ScalarType diff=(1.0-bary.X()-bary.Y()-bary.Z()); bary.X()+=diff;*/ return true; } } return (false); } template <class MeshType> bool GetBaryFaceFromUV(const MeshType &m, const typename MeshType::ScalarType &U, const typename MeshType::ScalarType &V, const std::vector<typename MeshType::FaceType*> &orderedFaces, typename MeshType::CoordType &bary, typename MeshType::FaceType* &chosen) { int index; bool found=GetBaryFaceFromUV(m,U,V,bary,index); if(!found) { chosen=0; return false; } chosen=orderedFaces[index]; return true; } template <class MeshType> bool GetCoordFromUV(const MeshType &m, const typename MeshType::ScalarType &U, const typename MeshType::ScalarType &V, typename MeshType::CoordType &val, bool rpos=false) { typedef typename MeshType::ScalarType ScalarType; const ScalarType _EPSILON = (ScalarType)0.00001; for (unsigned int i=0;i<m.face.size();i++) { const typename MeshType::FaceType *f=&m.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->cV(0)->T().U(),f->cV(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->cV(1)->T().U(),f->cV(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->cV(2)->T().U(),f->cV(2)->T().V()); vcg::Point2<ScalarType> test=vcg::Point2<ScalarType>(U,V); vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType area=(tex1-tex0)^(tex2-tex0); ///then find if the point 2d falls inside typename MeshType::CoordType bary; if ((area>_EPSILON)&&(t2d.InterpolationParameters(test,bary.X(),bary.Y(),bary.Z()))) { ///approximation errors for (int x=0;x<3;x++) { if (((bary[x])<=0)&&(bary[x]>=-_EPSILON)) bary[x]=0; else if (((bary[x])>=1)&&(bary[x]<=1+_EPSILON)) bary[x]=1; } ScalarType diff=(1.0-bary.X()-bary.Y()-bary.Z()); bary.X()+=diff; if (!rpos) val=f->cP(0)*bary.X()+f->cP(1)*bary.Y()+f->cP(0)*bary.Z(); else val=f->cV(0)->RPos*bary.X()+f->cV(1)->RPos*bary.Y()+f->cV(2)->RPos*bary.Z(); return true; } } return false; } template <class MeshType> typename MeshType::ScalarType GetSmallestUVEdgeSize(const MeshType &m) { typedef typename MeshType::ScalarType ScalarType; ScalarType smallest=100.f; assert(m.fn>0); for (int i=0;i<m.face.size();i++) { ///approximation errors for (int j=0;j<3;j++) { vcg::Point2<ScalarType> uv0=m.face[i].V(j)->T().P(); vcg::Point2<ScalarType> uv1=m.face[i].V((j+1)%3)->T().P(); ScalarType test=(uv0-uv1).Norm(); if (test<smallest) smallest=test; } } return smallest; } template <class MeshType> typename MeshType::ScalarType GetSmallestUVHeight(const MeshType &m) { typedef typename MeshType::ScalarType ScalarType; ScalarType smallest=(ScalarType)100.0; ScalarType eps=(ScalarType)0.0001; assert(m.fn>0); for (unsigned int i=0;i<m.face.size();i++) { const typename MeshType::FaceType *f=&m.face[i]; ///approximation errors for (int j=0;j<3;j++) { vcg::Point2<ScalarType> uv0=f->cV(j)->cT().P(); vcg::Point2<ScalarType> uv1=f->cV1(j)->cT().P(); vcg::Point2<ScalarType> uv2=f->cV2(j)->cT().P(); ScalarType area=fabs((uv1-uv0)^(uv2-uv0)); ScalarType base=(uv1-uv2).Norm(); ScalarType h_test=area/base; if (h_test<smallest) smallest=h_test; } } if (smallest<eps) smallest=(ScalarType)eps; if (smallest>(ScalarType)0.05) smallest=(ScalarType)0.05; return smallest; } template <class MeshType> void ParametrizeStarEquilateral(typename MeshType::VertexType *center, bool /*subvertices=true*/) { ///initialize domain typedef typename MeshType::VertexType VertexType; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::CoordType CoordType; MeshType parametrized; std::vector<VertexType*> vertices,ordVert; std::vector<VertexType*> HresVert; std::vector<FaceType*> faces; vertices.push_back(center); getSharedFace<MeshType>(vertices,faces); CopyMeshFromFaces<MeshType>(faces,ordVert,parametrized); ///parametrize and then copy back ParametrizeStarEquilateral<MeshType>(parametrized); for (unsigned int i=0;i<ordVert.size();i++) ordVert[i]->T().P()=parametrized.vert[i].T().P(); ///initialize sub-vertices getHresVertex<FaceType>(faces,HresVert); for (unsigned int i=0;i<HresVert.size();i++) { FaceType *father=HresVert[i]->father; CoordType Bary=HresVert[i]->Bary; InterpolateUV<MeshType>(father,Bary,HresVert[i]->T().U(),HresVert[i]->T().V()); } } #endif
multind.c
/* Copyright 2013-2015 The Regents of the University of California. * Copyright 2016-2018. Martin Uecker. * Copyright 2017. Intel Corporation. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2012-2018 Martin Uecker <martin.uecker@med.uni-goettingen.de> * 2013 Frank Ong <frankong@berkeley.edu> * 2017 Michael J. Anderson <michael.j.anderson@intel.com> * * Generic operations on multi-dimensional arrays. Most functions * come in two flavours: * * 1. A basic version which takes the number of dimensions, an array * of long integers specifing the size of each dimension, the pointers * to the data, and the size of each element and other required parameters. * The data is assumed to be stored in column-major format. * * 2. An extended version which takes an array of long integers which * specifies the strides for each argument. * * All functions should work on CPU and GPU and md_copy can be used * to copy between CPU and GPU. * */ #define _GNU_SOURCE #include <string.h> #include <assert.h> #include <stdbool.h> #include <alloca.h> #include <strings.h> #include "misc/misc.h" #include "misc/types.h" #include "misc/debug.h" #include "misc/nested.h" #include "num/optimize.h" #ifdef USE_CUDA #include "num/gpuops.h" #endif #include "multind.h" /** * Generic functions which loops over all dimensions of a set of * multi-dimensional arrays and calls a given function for each position. */ void md_nary(unsigned int C, unsigned int D, const long dim[D], const long* str[C], void* ptr[C], md_nary_fun_t fun) { if (0 == D) { fun(ptr); return; } for (long i = 0; i < dim[D - 1]; i++) { void* moving_ptr[C]; for (unsigned int j = 0; j < C; j++) moving_ptr[j] = ptr[j] + i * str[j][D - 1]; md_nary(C, D - 1, dim, str, moving_ptr, fun); } } /** * Generic functions which loops over all dimensions of a set of * multi-dimensional arrays and calls a given function for each position. * This functions tries to parallelize over the dimensions indicated * with flags. */ void md_parallel_nary(unsigned int C, unsigned int D, const long dim[D], unsigned long flags, const long* str[C], void* ptr[C], md_nary_fun_t fun) { if (0 == flags) { md_nary(C, D, dim, str, ptr, fun); return; } long dimc[D]; md_select_dims(D, ~flags, dimc, dim); // Collect all parallel dimensions int nparallel = 0; int parallel_b[D]; long parallel_dim[D]; long total_iterations = 1L; while (0 != flags) { int b = ffsl(flags & -flags) - 1; assert(MD_IS_SET(flags, b)); flags = MD_CLEAR(flags, b); debug_printf(DP_DEBUG4, "Parallelize: %d\n", dim[b]); parallel_b[nparallel] = b; parallel_dim[nparallel] = dim[b]; total_iterations *= parallel_dim[nparallel]; nparallel++; } #pragma omp parallel for for (long i = 0; i < total_iterations; i++) { // Recover place in parallel iteration space long iter_i[D]; long ii = i; for (int p = nparallel - 1; p >= 0; p--) { iter_i[p] = ii % parallel_dim[p]; ii /= parallel_dim[p]; } void* moving_ptr[C]; for (unsigned int j = 0; j < C; j++) { moving_ptr[j] = ptr[j]; for(int p = 0; p < nparallel; p++) moving_ptr[j] += iter_i[p] * str[j][parallel_b[p]]; } md_nary(C, D, dimc, str, moving_ptr, fun); } } static void md_parallel_loop_r(unsigned int D, unsigned int N, const long dim[static N], unsigned int flags, const long pos[static N], md_loop_fun_t fun) { if (0 == D) { fun(pos); return; } D--; // we need to make a copy because firstprivate needs to see // an array instead of a pointer long pos_copy[N]; for (unsigned int i = 0; i < N; i++) pos_copy[i] = pos[i]; #pragma omp parallel for firstprivate(pos_copy) if ((1 < dim[D]) && (flags & (1 << D))) for (int i = 0; i < dim[D]; i++) { pos_copy[D] = i; md_parallel_loop_r(D, N, dim, flags, pos_copy, fun); } } /** * Generic function which loops over all dimensions and calls a given * function passing the current indices as argument. * * Runs fun(data, position) for all position in dim * */ void md_parallel_loop(unsigned int D, const long dim[static D], unsigned long flags, md_loop_fun_t fun) { long pos[D]; md_parallel_loop_r(D, D, dim, flags, pos, fun); } static void md_loop_r(unsigned int D, const long dim[D], long pos[D], md_loop_fun_t fun) { if (0 == D) { fun(pos); return; } D--; for (pos[D] = 0; pos[D] < dim[D]; pos[D]++) md_loop_r(D, dim, pos, fun); } /** * Generic function which loops over all dimensions and calls a given * function passing the current indices as argument. * * Runs fun( position ) for all position in dim * */ void md_loop(unsigned int D, const long dim[D], md_loop_fun_t fun) { long pos[D]; md_loop_r(D, dim, pos, fun); } /** * Computes the next position. Returns true until last index. */ bool md_next(unsigned int D, const long dims[D], unsigned long flags, long pos[D]) { if (0 == D--) return false; if (md_next(D, dims, flags, pos)) return true; if (MD_IS_SET(flags, D)) { assert((0 <= pos[D]) && (pos[D] < dims[D])); if (++pos[D] < dims[D]) return true; pos[D] = 0; } return false; } /** * Returns offset for position in a multidimensional array * * return pos[0]*strides[0] + ... + pos[D-1]*strides[D-1] * * @param D number of dimensions * @param dim dimensions array */ long md_calc_offset(unsigned int D, const long strides[D], const long position[D]) { long pos = 0; for (unsigned int i = 0; i < D; i++) pos += strides[i] * position[i]; return pos; } static long md_calc_size_r(unsigned int D, const long dim[D], size_t size) { if (0 == D) return size; return md_calc_size_r(D - 1, dim, size * dim[D - 1]); } /** * Returns the number of elements * * return dim[0]*dim[1]*...*dim[D-1] * * @param D number of dimensions * @param dim dimensions array */ long md_calc_size(unsigned int D, const long dim[D]) { return md_calc_size_r(D, dim, 1); } /** * Computes the number of smallest dimensions which are stored * contineously, i.e. can be accessed as a block of memory. * */ unsigned int md_calc_blockdim(unsigned int D, const long dim[D], const long str[D], size_t size) { long dist = size; unsigned int i = 0; for (i = 0; i < D; i++) { if (!((str[i] == dist) || (dim[i] == 1))) break; dist *= dim[i]; } return i; } /** * Copy dimensions specified by flags and set remaining dimensions to 1 * * odims = [ 1 idims[1] idims[2] 1 1 idims[5] ] * * @param D number of dimensions * @param flags bitmask specifying which dimensions to copy * @param odims output dimensions * @param idims input dimensions */ void md_select_dims(unsigned int D, unsigned long flags, long odims[D], const long idims[D]) { md_copy_dims(D, odims, idims); for (unsigned int i = 0; i < D; i++) if (!MD_IS_SET(flags, i)) odims[i] = 1; } /** * Copy dimensions * * odims[i] = idims[i] */ void md_copy_dims(unsigned int D, long odims[D], const long idims[D]) { memcpy(odims, idims, D * sizeof(long)); } /** * Copy strides * * ostrs[i] = istrs[i] */ void md_copy_strides(unsigned int D, long ostrs[D], const long istrs[D]) { memcpy(ostrs, istrs, D * sizeof(long)); } /** * Set all dimensions to value * * dims[i] = val */ void md_set_dims(unsigned int D, long dims[D], long val) { for (unsigned int i = 0; i < D; i++) dims[i] = val; } /** * returns whether or not @param pos is a valid index of an array of dimension @param dims */ bool md_is_index(unsigned int D, const long pos[D], const long dims[D]) { if (D == 0) return true; return ((pos[0] >= 0) && (pos[0] < dims[0]) && md_is_index(D - 1, pos + 1, dims + 1)); } /** * return whether some other dimensions are >1 */ bool md_check_dimensions(unsigned int N, const long dims[N], unsigned int flags) { long d[N]; md_select_dims(N, ~flags, d, dims); return (1 != md_calc_size(N, d)); } /* * compute non-trivial (> 1) dims */ unsigned long md_nontriv_dims(unsigned int D, const long dims[D]) { unsigned long flags = 0; for (unsigned int i = 0; i < D; i++) if (dims[i] > 1) flags = MD_SET(flags, i); return flags; } /* * compute non-trivial (!= 0) strides */ unsigned long md_nontriv_strides(unsigned int D, const long strs[D]) { unsigned long flags = 0; for (unsigned int i = 0; i < D; i++) if (strs[i] != 0) flags = MD_SET(flags, i); return flags; } /** * Set all dimensions to one * * dims[i] = 1 */ void md_singleton_dims(unsigned int D, long dims[D]) { for (unsigned int i = 0; i < D; i++) dims[i] = 1; } /** * Set all strides to one * * dims[i] = 1 */ void md_singleton_strides(unsigned int D, long strs[D]) { for (unsigned int i = 0; i < D; i++) strs[i] = 0; } /** * Check dimensions for compatibility. Dimensions must be equal or * where indicated by a set bit in flags one must be equal to one * in atleast one of the arguments. */ bool md_check_compat(unsigned int D, unsigned long flags, const long dim1[D], const long dim2[D]) { if (0 == D) return true; D--; if ((dim1[D] == dim2[D]) || (MD_IS_SET(flags, D) && ((1 == dim1[D]) || (1 == dim2[D])))) return md_check_compat(D, flags, dim1, dim2); return false; } void md_merge_dims(unsigned int N, long out_dims[N], const long dims1[N], const long dims2[N]) { assert(md_check_compat(N, ~0, dims1, dims2)); for (unsigned int i = 0; i < N; i++) out_dims[i] = (1 == dims1[i]) ? dims2[i] : dims1[i]; } /** * dim1 must be bounded by dim2 where a bit is set */ bool md_check_bounds(unsigned int D, unsigned long flags, const long dim1[D], const long dim2[D]) { if (0 == D--) return true; if (!MD_IS_SET(flags, D) || (dim1[D] <= dim2[D])) return md_check_bounds(D, flags, dim1, dim2); return false; } /** * Set the output's flagged dimensions to the minimum of the two input dimensions * * odims = [ MIN(idims1[0],idims2[0] ... MIN(idims1[D-1],idims2[D-1]) ] * * @param D number of dimensions * @param flags bitmask specifying which dimensions to minimize * @param odims output dimensions * @param idims1 input 1 dimensions * @param idims2 input 2 dimensions */ void md_min_dims(unsigned int D, unsigned long flags, long odims[D], const long idims1[D], const long idims2[D]) { for (unsigned int i = 0; i < D; i++) if (MD_IS_SET(flags, i)) odims[i] = MIN(idims1[i], idims2[i]); } /** * Set the output's flagged dimensions to the maximum of the two input dimensions * * odims = [ MAX(idims1[0],idims2[0] ... MAX(idims1[D-1],idims2[D-1]) ] * * @param D number of dimensions * @param flags bitmask specifying which dimensions to maximize * @param odims output dimensions * @param idims1 input 1 dimensions * @param idims2 input 2 dimensions */ void md_max_dims(unsigned int D, unsigned long flags, long odims[D], const long idims1[D], const long idims2[D]) { for (unsigned int i = 0; i < D; i++) if (MD_IS_SET(flags, i)) odims[i] = MAX(idims1[i], idims2[i]); } /** * Zero out array (with strides) * * ptr[i] = 0 */ void md_clear2(unsigned int D, const long dim[D], const long str[D], void* ptr, size_t size) { const long (*nstr[1])[D] = { (const long (*)[D])str }; #ifdef USE_CUDA bool use_gpu = cuda_ondevice(ptr); #endif unsigned long flags = 0; for (unsigned int i = 0; i < D; i++) if (0 == str[i]) flags |= MD_BIT(i); long dim2[D]; md_select_dims(D, ~flags, dim2, dim); NESTED(void, nary_clear, (struct nary_opt_data_s* opt_data, void* ptr[])) { size_t size2 = size * opt_data->size; #ifdef USE_CUDA if (use_gpu) { cuda_clear(size2, ptr[0]); return; } #endif memset(ptr[0], 0, size2); }; optimized_nop(1, MD_BIT(0), D, dim2, nstr, (void*[1]){ ptr }, (size_t[1]){ size }, nary_clear); } /** * Calculate strides in column-major format * (smallest index is sequential) * * @param D number of dimensions * @param array of calculates strides * @param dim array of dimensions * @param size of a single element */ long* md_calc_strides(unsigned int D, long str[D], const long dim[D], size_t size) { long old = size; for (unsigned int i = 0; i < D; i++) { str[i] = (1 == dim[i]) ? 0 : old; old *= dim[i]; } return str; } /** * Zero out array (without strides) * * ptr[i] = 0 * * @param D number of dimensions * @param dim dimensions array * @param ptr pointer to data to clear * @param size sizeof() */ void md_clear(unsigned int D, const long dim[D], void* ptr, size_t size) { md_clear2(D, dim, MD_STRIDES(D, dim, size), ptr, size); } /** * Copy array (with strides) * * optr[i] = iptr[i] */ void md_copy2(unsigned int D, const long dim[D], const long ostr[D], void* optr, const long istr[D], const void* iptr, size_t size) { #if 0 // this is for a fun comparison between our copy engine and FFTW extern void fft2(unsigned int D, const long dim[D], unsigned int flags, const long ostr[D], void* optr, const long istr[D], const void* iptr); if (sizeof(complex float) == size) fft2(D, dim, 0, ostr, optr, istr, iptr); #endif #ifdef USE_CUDA bool use_gpu = cuda_ondevice(optr) || cuda_ondevice(iptr); #if 1 long tostr[D]; long tistr[D]; long tdims[D]; md_copy_strides(D, tostr, ostr); md_copy_strides(D, tistr, istr); md_copy_dims(D, tdims, dim); long (*nstr2[2])[D] = { &tostr, &tistr }; int ND = optimize_dims(2, D, tdims, nstr2); size_t sizes[2] = { size, size }; int skip = min_blockdim(2, ND, tdims, nstr2, sizes); if (use_gpu && (ND - skip > 0)) { void* nptr[2] = { optr, (void*)iptr }; long sizes[2] = { md_calc_size(skip, tdims) * size, tdims[skip] }; long ostr2 = (*nstr2[0])[skip]; long istr2 = (*nstr2[1])[skip]; skip++; const long* nstr[2] = { *nstr2[0] + skip, *nstr2[1] + skip }; long* sizesp = sizes; // because of clang NESTED(void, nary_strided_copy, (void* ptr[])) { // printf("CUDA 2D copy %ld %ld %ld %ld %ld %ld\n", data->sizes[0], data->sizes[1], data->ostr, data->istr, (long)ptr[0], (long)ptr[1]); cuda_memcpy_strided(sizesp, ostr2, ptr[0], istr2, ptr[1]); }; md_nary(2, ND - skip, tdims + skip , nstr, nptr, nary_strided_copy); return; } #endif #endif const long (*nstr[2])[D] = { (const long (*)[D])ostr, (const long (*)[D])istr }; NESTED(void, nary_copy, (struct nary_opt_data_s* opt_data, void* ptr[])) { size_t size2 = size * opt_data->size; #ifdef USE_CUDA if (use_gpu) { cuda_memcpy(size2, ptr[0], ptr[1]); return; } #endif memcpy(ptr[0], ptr[1], size2); }; optimized_nop(2, MD_BIT(0), D, dim, nstr, (void*[2]){ optr, (void*)iptr }, (size_t[2]){ size, size }, nary_copy); } /** * Copy array (without strides) * * optr[i] = iptr[i] */ void md_copy(unsigned int D, const long dim[D], void* optr, const void* iptr, size_t size) { long str[D]; md_calc_strides(D, str, dim, size); md_copy2(D, dim, str, optr, str, iptr, size); } #ifdef USE_CUDA // copied from flpmath.c static void* gpu_constant(const void* vp, size_t size) { return md_gpu_move(1, (long[1]){ 1 }, vp, size); } #endif /** * Fill array with value pointed by pointer (with strides) * * ptr[i] = iptr[0] */ void md_fill2(unsigned int D, const long dim[D], const long str[D], void* ptr, const void* iptr, size_t size) { #ifdef USE_CUDA if (cuda_ondevice(ptr) && (!cuda_ondevice(iptr))) { void* giptr = gpu_constant(iptr, size); md_fill2(D, dim, str, ptr, giptr, size); md_free(giptr); return; } #endif long istr[D]; md_singleton_strides(D, istr); md_copy2(D, dim, str, ptr, istr, iptr, size); } /** * Fill array with value pointed by pointer (without strides) * * ptr[i] = iptr[0] */ void md_fill(unsigned int D, const long dim[D], void* ptr, const void* iptr, size_t size) { md_fill2(D, dim, MD_STRIDES(D, dim, size), ptr, iptr, size); } /** * Swap values between a number of arrays (with strides) */ void md_circular_swap2(unsigned int M, unsigned int D, const long dims[D], const long* strs[M], void* ptr[M], size_t size) { size_t sizes[M]; for (unsigned int i = 0; i < M; i++) sizes[i] = size; const long (*nstrs[M])[D]; for (unsigned int i = 0; i < M; i++) nstrs[i] = (const long (*)[D])strs[i]; NESTED(void, nary_swap, (struct nary_opt_data_s* opt_data, void* ptr[])) { size_t size2 = size * opt_data->size; char* tmp = (size2 < 32) ? alloca(size2) : xmalloc(size2); #ifdef USE_CUDA assert(!cuda_ondevice(ptr[0])); assert(!cuda_ondevice(ptr[1])); #endif memcpy(tmp, ptr[0], size2); for (unsigned int i = 0; i < M - 1; i++) memcpy(ptr[i], ptr[i + 1], size2); memcpy(ptr[M - 1], tmp, size2); if (size2 >= 32) xfree(tmp); }; optimized_nop(M, (1 << M) - 1, D, dims, nstrs, ptr, sizes, nary_swap); } /** * Swap values between a number of arrays */ void md_circular_swap(unsigned M, unsigned int D, const long dims[D], void* ptr[M], size_t size) { long strs[M][D]; md_calc_strides(D, strs[0], dims, size); const long* strp[M]; strp[0] = strs[0]; for (unsigned int i = 1; i < M; i++) { md_copy_strides(D, strs[i], strs[0]); strp[i] = strs[i]; } md_circular_swap2(M, D, dims, strp, ptr, size); } /** * Swap values between two arrays (with strides) * * iptr[i] = optr[i] and optr[i] = iptr[i] */ void md_swap2(unsigned int D, const long dim[D], const long ostr[D], void* optr, const long istr[D], void* iptr, size_t size) { md_circular_swap2(2, D, dim, (const long*[2]){ ostr, istr }, (void*[2]){ optr, iptr }, size); } /** * Swap values between two arrays (without strides) * * iptr[i] = optr[i] and optr[i] = iptr[i] */ void md_swap(unsigned int D, const long dim[D], void* optr, void* iptr, size_t size) { long str[D]; md_calc_strides(D, str, dim, size); md_swap2(D, dim, str, optr, str, iptr, size); } /** * Move a block from an array to another array (with strides) * */ void md_move_block2(unsigned int D, const long dim[D], const long opos[D], const long odim[D], const long ostr[D], void* optr, const long ipos[D], const long idim[D], const long istr[D], const void* iptr, size_t size) { for (unsigned int i = 0; i < D; i++) { assert(dim[i] <= odim[i]); assert(dim[i] <= idim[i]); assert((0 <= opos[i]) && (opos[i] <= odim[i] - dim[i])); assert((0 <= ipos[i]) && (ipos[i] <= idim[i] - dim[i])); } long ioff = md_calc_offset(D, istr, ipos); long ooff = md_calc_offset(D, ostr, opos); md_copy2(D, dim, ostr, optr + ooff, istr, iptr + ioff, size); } /** * Move a block from an array to another array (without strides) * */ void md_move_block(unsigned int D, const long dim[D], const long opos[D], const long odim[D], void* optr, const long ipos[D], const long idim[D], const void* iptr, size_t size) { md_move_block2(D, dim, opos, odim, MD_STRIDES(D, odim, size), optr, ipos, idim, MD_STRIDES(D, idim, size), iptr, size); } /** * Copy a block from an array to another array (with strides) * * Block dimensions are min(idim , odim) * * if idim[d] > odim[d], then optr[i] = iptr[pos + i] for 0 <= i < odim[d] * * if idim[d] < odim[d], then optr[pos + i] = iptr[i] for 0 <= i < idim[d] * */ void md_copy_block2(unsigned int D, const long pos[D], const long odim[D], const long ostr[D], void* optr, const long idim[D], const long istr[D], const void* iptr, size_t size) { long dim[D]; long ipos[D]; long opos[D]; for (unsigned int i = 0; i < D; i++) { assert((idim[i] != odim[i]) || (0 == pos[i])); dim[i] = MIN(odim[i], idim[i]); ipos[i] = 0; opos[i] = 0; if (idim[i] != dim[i]) ipos[i] = pos[i]; if (odim[i] != dim[i]) opos[i] = pos[i]; } md_move_block2(D, dim, opos, odim, ostr, optr, ipos, idim, istr, iptr, size); } /** * Copy a block from an array to another array (without strides) * * Block dimensions are min(idim , odim) * * if idim[d] > odim[d], then optr[i] = iptr[pos + i] for 0 <= i < odim[d] * * if idim[d] < odim[d], then optr[pos + i] = iptr[i] for 0 <= i < idim[d] * */ void md_copy_block(unsigned int D, const long pos[D], const long odim[D], void* optr, const long idim[D], const void* iptr, size_t size) { md_copy_block2(D, pos, odim, MD_STRIDES(D, odim, size), optr, idim, MD_STRIDES(D, idim, size), iptr, size); } /** * Resize an array by zero-padding or by truncation at the end. * * optr = [iptr 0 0 0 0] * */ void md_resize(unsigned int D, const long odim[D], void* optr, const long idim[D], const void* iptr, size_t size) { long pos[D]; memset(pos, 0, D * sizeof(long)); md_clear(D, odim, optr, size); md_copy_block(D, pos, odim, optr, idim, iptr, size); } /** * Resize an array by zero-padding or by truncation at both ends symmetrically. * * optr = [0 0 iptr 0 0] * */ void md_resize_center(unsigned int D, const long odim[D], void* optr, const long idim[D], const void* iptr, size_t size) { // the definition of the center position corresponds // to the one used in the FFT. long pos[D]; for (unsigned int i = 0; i < D; i++) pos[i] = labs((odim[i] / 2) - (idim[i] / 2)); md_clear(D, odim, optr, size); md_copy_block(D, pos, odim, optr, idim, iptr, size); } /** * Extract slice from array specified by flags (with strides) * * optr = iptr(pos[0], :, pos[2], :, :) * */ void md_slice2(unsigned int D, unsigned long flags, const long pos[D], const long dim[D], const long ostr[D], void* optr, const long istr[D], const void* iptr, size_t size) { long odim[D]; md_select_dims(D, ~flags, odim, dim); md_copy_block2(D, pos, odim, ostr, optr, dim, istr, iptr, size); } /** * Extract slice from array specified by flags (with strides) * * optr = iptr(pos[0], :, pos[2], :, :) * */ void md_slice(unsigned int D, unsigned long flags, const long pos[D], const long dim[D], void* optr, const void* iptr, size_t size) { long odim[D]; md_select_dims(D, ~flags, odim, dim); md_slice2(D, flags, pos, dim, MD_STRIDES(D, odim, size), optr, MD_STRIDES(D, dim, size), iptr, size); } /** * Permute array (with strides) * * optr[order[i]] = iptr[i] * */ void md_permute2(unsigned int D, const unsigned int order[D], const long odims[D], const long ostr[D], void* optr, const long idims[D], const long istr[D], const void* iptr, size_t size) { unsigned int flags = 0; long ostr2[D]; for (unsigned int i = 0; i < D; i++) { assert(order[i] < D); assert(odims[i] == idims[order[i]]); flags = MD_SET(flags, order[i]); ostr2[order[i]] = ostr[i]; } assert(MD_BIT(D) == flags + 1); md_copy2(D, idims, ostr2, optr, istr, iptr, size); } /** * Permute array (without strides) * * optr[order[i]] = iptr[i] * */ void md_permute(unsigned int D, const unsigned int order[D], const long odims[D], void* optr, const long idims[D], const void* iptr, size_t size) { md_permute2(D, order, odims, MD_STRIDES(D, odims, size), optr, idims, MD_STRIDES(D, idims, size), iptr, size); } /** * Permute dimensions * * */ void md_permute_dims(unsigned int D, const unsigned int order[D], long odims[D], const long idims[D]) { for (unsigned int i = 0; i < D; i++) odims[i] = idims[order[i]]; } static void md_transpose_order(unsigned int D, unsigned int order[D], unsigned int dim1, unsigned int dim2) { assert(dim1 < D); assert(dim2 < D); for (unsigned int i = 0; i < D; i++) order[i] = i; order[dim1] = dim2; order[dim2] = dim1; } /** * Transpose dimensions * * */ void md_transpose_dims(unsigned int D, unsigned int dim1, unsigned int dim2, long odims[D], const long idims[D]) { unsigned int order[D]; md_transpose_order(D, order, dim1, dim2); md_permute_dims(D, order, odims, idims); } /** * Tranpose array (with strides) * * optr[dim2] = iptr[dim1] * * optr[dim1] = iptr[dim2] * */ void md_transpose2(unsigned int D, unsigned int dim1, unsigned int dim2, const long odims[D], const long ostr[D], void* optr, const long idims[D], const long istr[D], const void* iptr, size_t size) { for (unsigned int i = 0; i < D; i++) if ((i != dim1) && (i != dim2)) assert(odims[i] == idims[i]); assert(odims[dim1] == idims[dim2]); assert(odims[dim2] == idims[dim1]); unsigned int order[D]; md_transpose_order(D, order, dim1, dim2); md_permute2(D, order, odims, ostr, optr, idims, istr, iptr, size); } /** * Tranpose array (without strides) * * optr[dim2] = iptr[dim1] * * optr[dim1] = iptr[dim2] * */ void md_transpose(unsigned int D, unsigned int dim1, unsigned int dim2, const long odims[D], void* optr, const long idims[D], const void* iptr, size_t size) { md_transpose2(D, dim1, dim2, odims, MD_STRIDES(D, odims, size), optr, idims, MD_STRIDES(D, idims, size), iptr, size); } static void md_flip_inpl2(unsigned int D, const long dims[D], unsigned long flags, const long str[D], void* ptr, size_t size); /** * Swap input and output while flipping selected dimensions * at the same time. */ void md_swap_flip2(unsigned int D, const long dims[D], unsigned long flags, const long ostr[D], void* optr, const long istr[D], void* iptr, size_t size) { #if 1 int i; for (i = D - 1; i >= 0; i--) if ((1 != dims[i]) && MD_IS_SET(flags, i)) break; if (-1 == i) { md_swap2(D, dims, ostr, optr, istr, iptr, size); return; } assert(1 < dims[i]); assert(ostr[i] != 0); assert(istr[i] != 0); long dims2[D]; md_copy_dims(D, dims2, dims); dims2[i] = dims[i] / 2; long off = (dims[i] + 1) / 2; assert(dims2[i] + off == dims[i]); md_swap_flip2(D, dims2, flags, ostr, optr, istr, iptr + off * istr[i], size); md_swap_flip2(D, dims2, flags, ostr, optr + off * ostr[i], istr, iptr, size); // odd, swap center plane // (we should split in three similar sized chunks instead) dims2[i] = 1; if (1 == dims[i] % 2) md_swap_flip2(D, dims2, flags, ostr, optr + (off - 1) * ostr[i], istr, iptr + (off - 1) * istr[i], size); #else // simpler, but more swaps md_swap2(D, dims, ostr, optr, istr, iptr, size); md_flip_inpl2(D, dims, flags, ostr, optr, size); md_flip_inpl2(D, dims, flags, istr, iptr, size); #endif } /** * Swap input and output while flipping selected dimensions * at the same time. */ void md_swap_flip(unsigned int D, const long dims[D], unsigned long flags, void* optr, void* iptr, size_t size) { long strs[D]; md_calc_strides(D, strs, dims, size); md_swap_flip2(D, dims, flags, strs, optr, strs, iptr, size); } static void md_flip_inpl2(unsigned int D, const long dims[D], unsigned long flags, const long str[D], void* ptr, size_t size) { int i; for (i = D - 1; i >= 0; i--) if ((1 != dims[i]) && MD_IS_SET(flags, i)) break; if (-1 == i) return; assert(1 < dims[i]); assert(str[i] != 0); long dims2[D]; md_copy_dims(D, dims2, dims); dims2[i] = dims[i] / 2; long off = str[i] * (0 + (dims[i] + 1) / 2); md_swap_flip2(D, dims2, flags, str, ptr, str, ptr + off, size); } /** * Flip array (with strides) * * optr[dims[D] - 1 - i] = iptr[i] * */ void md_flip2(unsigned int D, const long dims[D], unsigned long flags, const long ostr[D], void* optr, const long istr[D], const void* iptr, size_t size) { if (optr == iptr) { assert(ostr == istr); md_flip_inpl2(D, dims, flags, ostr, optr, size); return; } long off = 0; long ostr2[D]; for (unsigned int i = 0; i < D; i++) { ostr2[i] = ostr[i]; if (MD_IS_SET(flags, i)) { ostr2[i] = -ostr[i]; off += (dims[i] - 1) * ostr[i]; } } md_copy2(D, dims, ostr2, optr + off, istr, iptr, size); } /** * Flip array (without strides) * * optr[dims[D] - 1 - i] = iptr[i] * */ void md_flip(unsigned int D, const long dims[D], unsigned long flags, void* optr, const void* iptr, size_t size) { long str[D]; md_calc_strides(D, str, dims, size); md_flip2(D, dims, flags, str, optr, str, iptr, size); } bool md_compare2(unsigned int D, const long dims[D], const long str1[D], const void* src1, const long str2[D], const void* src2, size_t size) { __block bool eq = true; const long (*nstr[2])[D] = { (const long (*)[D])str1, (const long (*)[D])str2 }; NESTED(void, nary_cmp, (struct nary_opt_data_s* opt_data, void* ptrs[])) { size_t size2 = size * opt_data->size; bool eq2 = (0 == memcmp(ptrs[0], ptrs[1], size2)); #pragma omp critical eq &= eq2; }; optimized_nop(2, 0u, D, dims, nstr, (void*[2]){ (void*)src1, (void*)src2 }, (size_t[2]){ size, size }, nary_cmp); return eq; } bool md_compare(unsigned int D, const long dims[D], const void* src1, const void* src2, size_t size) { long str[D]; md_calc_strides(D, str, dims, size); return md_compare2(D, dims, str, src1, str, src2, size); } static void md_septrafo_r(unsigned int D, unsigned int R, long dimensions[D], unsigned long flags, const long strides[D], void* ptr, md_trafo_fun_t fun) { if (0 == R--) return; md_septrafo_r(D, R, dimensions, flags, strides, ptr, fun); if (MD_IS_SET(flags, R)) { void* nptr[1] = { ptr }; const long* nstrides[1] = { strides }; long dimsR = dimensions[R]; long strsR = strides[R]; // because of clang dimensions[R] = 1; // we made a copy in md_septrafo2 NESTED(void, nary_septrafo, (void* ptr[])) { fun(dimsR, strsR, ptr[0]); }; //md_nary_parallel(1, D, dimensions, nstrides, nptr, &data, nary_septrafo); md_nary(1, D, dimensions, nstrides, nptr, nary_septrafo); dimensions[R] = dimsR; } } /** * Apply a separable transformation along selected dimensions. * */ void md_septrafo2(unsigned int D, const long dimensions[D], unsigned long flags, const long strides[D], void* ptr, md_trafo_fun_t fun) { long dimcopy[D]; md_copy_dims(D, dimcopy, dimensions); md_septrafo_r(D, D, dimcopy, flags, strides, ptr, fun); } /** * Apply a separable transformation along selected dimensions. * */ void md_septrafo(unsigned int D, const long dims[D], unsigned long flags, void* ptr, size_t size, md_trafo_fun_t fun) { md_septrafo2(D, dims, flags, MD_STRIDES(D, dims, size), ptr, fun); } /** * Copy diagonals from array specified by flags (with strides) * * dst(i, i, :, i, :) = src(i, i, :, i, :) * */ void md_copy_diag2(unsigned int D, const long dims[D], unsigned long flags, const long str1[D], void* dst, const long str2[D], const void* src, size_t size) { long stride1 = 0; long stride2 = 0; long count = -1; for (unsigned int i = 0; i < D; i++) { if (MD_IS_SET(flags, i)) { if (count < 0) count = dims[i]; assert(dims[i] == count); stride1 += str1[i]; stride2 += str2[i]; } } long xdims[D]; md_select_dims(D, ~flags, xdims, dims); for (long i = 0; i < count; i++) md_copy2(D, xdims, str1, dst + i * stride1, str2, src + i * stride2, size); } /** * Copy diagonals from array specified by flags (without strides) * * dst(i ,i ,: ,i , :) = src(i ,i ,: ,i ,:) * */ void md_copy_diag(unsigned int D, const long dims[D], unsigned long flags, void* dst, const void* src, size_t size) { long str[D]; md_calc_strides(D, str, dims, size); md_copy_diag2(D, dims, flags, str, dst, str, src, size); } /** * Fill diagonals specified by flags with value (without strides) * * dst(i, i, :, i, :) = src[0] * */ void md_fill_diag(unsigned int D, const long dims[D], unsigned long flags, void* dst, const void* src, size_t size) { long str2[D]; md_singleton_strides(D, str2); md_copy_diag2(D, dims, flags, MD_STRIDES(D, dims, size), dst, str2, src, size); } static void md_circ_shift_inpl2(unsigned int D, const long dims[D], const long center[D], const long strs[D], void* dst, size_t size) { #if 0 long dims1[D]; long dims2[D]; md_copy_dims(D, dims1, dims); md_copy_dims(D, dims2, dims); unsigned int i; for (i = 0; i < D; i++) { if (0 != center[i]) { dims1[i] = center[i]; dims2[i] = dims[i] - center[i]; break; } } if (i == D) return; long off = strs[i] * center[i]; // cool but slow, instead we want to have a chain of swaps md_flip2(D, dims, MD_BIT(i), strs, dst, strs, dst, size); md_flip2(D, dims1, MD_BIT(i), strs, dst, strs, dst, size); md_flip2(D, dims2, MD_BIT(i), strs, dst + off, strs, dst + off, size); // also not efficient, we want to merge the chain of swaps long center2[D]; md_copy_dims(D, center2, center); center2[i] = 0; md_circ_shift_inpl2(D, dims, center2, strs, dst, size); #else // use tmp for now unsigned int i; for (i = 0; i < D; i++) if (0 != center[i]) break; if (i == D) return; long tmp_strs[D]; md_calc_strides(D, tmp_strs, dims, size); void* tmp = md_alloc_sameplace(D, dims, size, dst); md_copy2(D, dims, tmp_strs, tmp, strs, dst, size); md_circ_shift2(D, dims, center, strs, dst, tmp_strs, tmp, size); md_free(tmp); #endif } /** * Circularly shift array (with strides) * * dst[mod(i + center)] = src[i] * */ void md_circ_shift2(unsigned int D, const long dimensions[D], const long center[D], const long str1[D], void* dst, const long str2[D], const void* src, size_t size) { long pos[D]; for (unsigned int i = 0; i < D; i++) { // FIXME: it would be better to calc modulo pos[i] = center[i]; while (pos[i] < 0) pos[i] += dimensions[i]; } unsigned int i = 0; // FIXME :maybe we shoud search the other way? while ((i < D) && (0 == pos[i])) i++; if (D == i) { md_copy2(D, dimensions, str1, dst, str2, src, size); return; } if (dst == src) { assert(str1 == str2); md_circ_shift_inpl2(D, dimensions, pos, str1, dst, size); return; } long shift = pos[i]; assert(shift != 0); long dim1[D]; long dim2[D]; md_copy_dims(D, dim1, dimensions); md_copy_dims(D, dim2, dimensions); dim1[i] = shift; dim2[i] = dimensions[i] - shift; assert((dim1[i] >= 0) && (dim2[i] >= 0)); pos[i] = 0; //printf("%d: %ld %ld %d\n", i, dim1[i], dim2[i], sizeof(dimensions)); md_circ_shift2(D, dim1, pos, str1, dst, str2, src + dim2[i] * str2[i], size); md_circ_shift2(D, dim2, pos, str1, dst + dim1[i] * str1[i], str2, src, size); } /** * Circularly shift array (without strides) * * dst[mod(i + center)] = src[i] * */ void md_circ_shift(unsigned int D, const long dimensions[D], const long center[D], void* dst, const void* src, size_t size) { long strides[D]; md_calc_strides(D, strides, dimensions, size); md_circ_shift2(D, dimensions, center, strides, dst, strides, src, size); } /** * Circularly extend array (with strides) * */ void md_circ_ext2(unsigned int D, const long dims1[D], const long strs1[D], void* dst, const long dims2[D], const long strs2[D], const void* src, size_t size) { long ext[D]; for (unsigned int i = 0; i < D; i++) { ext[i] = dims1[i] - dims2[i]; assert(ext[i] >= 0); assert(ext[i] <= dims2[i]); } unsigned int i = 0; // FIXME :maybe we shoud search the other way? while ((i < D) && (0 == ext[i])) i++; if (D == i) { md_copy2(D, dims1, strs1, dst, strs2, src, size); return; } long dims1_crop[D]; long dims2_crop[D]; long ext_dims[D]; md_copy_dims(D, dims1_crop, dims1); md_copy_dims(D, dims2_crop, dims2); md_copy_dims(D, ext_dims, dims1); dims1_crop[i] = dims2[i]; dims2_crop[i] = ext[i]; ext_dims[i] = ext[i]; ext[i] = 0; //printf("%d: %ld %ld %d\n", i, dim1[i], dim2[i], sizeof(dimensions)); md_circ_ext2(D, dims1_crop, strs1, dst, dims2, strs2, src, size); md_circ_ext2(D, ext_dims, strs1, dst + dims2[i] * strs1[i], dims2_crop, strs2, src, size); } /** * Circularly extend array (without strides) * */ void md_circ_ext(unsigned int D, const long dims1[D], void* dst, const long dims2[D], const void* src, size_t size) { md_circ_ext2(D, dims1, MD_STRIDES(D, dims1, size), dst, dims2, MD_STRIDES(D, dims2, size), src, size); } /** * Periodically extend array (with strides) * */ void md_periodic2(unsigned int D, const long dims1[D], const long strs1[D], void* dst, const long dims2[D], const long strs2[D], const void* src, size_t size) { long dims1B[2 * D]; long strs1B[2 * D]; long strs2B[2 * D]; for (unsigned int i = 0; i < D; i++) { assert(0 == dims1[i] % dims2[i]); // blocks dims1B[2 * i + 0] = dims2[i]; strs1B[2 * i + 0] = strs1[i]; strs2B[2 * i + 0] = strs2[i]; // periodic copies dims1B[2 * i + 0] = dims1[i] / dims2[i]; strs1B[2 * i + 0] = strs1[i] * dims2[i]; strs2B[2 * i + 0] = 0; } md_copy2(D, dims1B, strs1B, dst, strs2B, src, size); } /** * Periodically extend array (without strides) * */ void md_periodic(unsigned int D, const long dims1[D], void* dst, const long dims2[D], const void* src, size_t size) { md_periodic2(D, dims1, MD_STRIDES(D, dims1, size), dst, dims2, MD_STRIDES(D, dims2, size), src, size); } /** * Allocate CPU memory * * return pointer to CPU memory */ void* md_alloc(unsigned int D, const long dimensions[D], size_t size) { return xmalloc(md_calc_size(D, dimensions) * size); } /** * Allocate CPU memory and clear * * return pointer to CPU memory */ void* md_calloc(unsigned int D, const long dimensions[D], size_t size) { void* ptr = md_alloc(D, dimensions, size); md_clear(D, dimensions, ptr, size); return ptr; } #ifdef USE_CUDA /** * Allocate GPU memory * * return pointer to GPU memory */ void* md_alloc_gpu(unsigned int D, const long dimensions[D], size_t size) { return cuda_malloc(md_calc_size(D, dimensions) * size); } /** * Allocate GPU memory and copy from CPU pointer * * return pointer to GPU memory */ void* md_gpu_move(unsigned int D, const long dims[D], const void* ptr, size_t size) { if (NULL == ptr) return NULL; void* gpu_ptr = md_alloc_gpu(D, dims, size); md_copy(D, dims, gpu_ptr, ptr, size); return gpu_ptr; } #endif /** * Allocate memory on the same device (CPU/GPU) place as ptr * * return pointer to CPU memory if ptr is in CPU or to GPU memory if ptr is in GPU */ void* md_alloc_sameplace(unsigned int D, const long dimensions[D], size_t size, const void* ptr) { #ifdef USE_CUDA return (cuda_ondevice(ptr) ? md_alloc_gpu : md_alloc)(D, dimensions, size); #else assert(0 != ptr); return md_alloc(D, dimensions, size); #endif } /** * Free CPU/GPU memory * */ void md_free(const void* ptr) { #ifdef USE_CUDA if (cuda_ondevice(ptr)) cuda_free((void*)ptr); else #endif xfree(ptr); }
csc.h
#ifndef __csc_H #define __csc_H template<typename I, typename T1, typename T2,typename T3> void csc_matvec_noomp_contig(const bool overwrite_y, const I n_row, const I n_col, const I Ap[], const I Ai[], const T1 Ax[], const T2 a, const T3 x[], T3 y[]) { if(overwrite_y){ for(I j = 0; j < n_row; j++){ y[j] = 0; } } for(I j = 0; j < n_col; j++){ I col_start = Ap[j]; I col_end = Ap[j+1]; for(I ii = col_start; ii < col_end; ii++){ const I i = Ai[ii]; y[i] += (a * Ax[ii]) * x[j]; } } } template<typename I, typename T1, typename T2,typename T3> void csc_matvec_noomp_strided(const bool overwrite_y, const I n_row, const I n_col, const I Ap[], const I Ai[], const T1 Ax[], const T2 a, const npy_intp x_stride, const T3 x[], const npy_intp y_stride, T3 y[]) { if(overwrite_y){ for(I j = 0; j < n_row; j++){ y[j * y_stride] = 0; } } for(I j = 0; j < n_col; j++){ I col_start = Ap[j]; I col_end = Ap[j+1]; for(I ii = col_start; ii < col_end; ii++){ const I i = Ai[ii]; y[i * y_stride] += (a * Ax[ii]) * x[j * x_stride]; } } } template<typename I, typename T1, typename T2,typename T3> void csc_matvecs_noomp_strided(const bool overwrite_y, const I n_row, const I n_col, const npy_intp n_vecs, const I Ap[], const I Ai[], // indices for row elements in each column const T1 Ax[], const T2 a, const npy_intp x_stride_row, // X_n_row == n_col const npy_intp x_stride_col, // X_n_col == n_vecs const T3 x[], const npy_intp y_stride_row, // Y_n_row == n_row const npy_intp y_stride_col, // Y_n_col == n_vecs T3 y[]) { if(overwrite_y){ for(npy_intp i = 0; i < n_row; i++){ for(npy_intp j = 0; j < n_vecs; j++){ y[i * y_stride_row + j * y_stride_col] = 0; } } } // preference ordering of 'y' as it is being written to. if(y_stride_col < y_stride_row){ for(I j = 0; j < n_col; j++){ I col_start = Ap[j]; I col_end = Ap[j+1]; for(I ii = col_start; ii < col_end; ii++){ T3 * y_row = y + y_stride_row * Ai[ii]; const T3 ax = (a * Ax[ii]); axpy_strided(n_vecs, ax, x_stride_col, x, y_stride_col, y_row); } x += x_stride_row; } } else{ for(I m=0;m<n_vecs;m++){ const T3 * x_row = x; for(I j = 0; j < n_col; j++){ I col_start = Ap[j]; I col_end = Ap[j+1]; for(I ii = col_start; ii < col_end; ii++){ y[y_stride_row * Ai[ii]] += (a * Ax[ii]) * (*x_row); } x_row += x_stride_row; } x += x_stride_col; y += y_stride_col; } } } #if defined(_OPENMP) #include "openmp.h" template<typename I, typename T1, typename T2,typename T3> void csc_matvec_omp_contig(const bool overwrite_y, const I n_row, const I n_col, const I Ap[], const I Ai[], const T1 Ax[], const T2 a, const T3 x[], T3 y[]) { #pragma omp parallel { const int nthread = omp_get_num_threads(); const I chunk = std::max((I)1,n_row/(100*nthread)); if(overwrite_y){ #pragma omp for schedule(static) for(I j = 0; j < n_row; j++){ y[j] = 0; } } #pragma omp for schedule(dynamic,chunk) for(I j = 0; j < n_col; j++){ I col_start = Ap[j]; I col_end = Ap[j+1]; for(I ii = col_start; ii < col_end; ii++){ const I i = Ai[ii]; const T3 aa = (a * Ax[ii]) * x[j]; atomic_add(y[i],aa); } } } } template<typename I, typename T1, typename T2,typename T3> void csc_matvec_omp_strided(const bool overwrite_y, const I n_row, const I n_col, const I Ap[], const I Ai[], const T1 Ax[], const T2 a, const npy_intp x_stride, const T3 x[], const npy_intp y_stride, T3 y[]) { #pragma omp parallel { const int nthread = omp_get_num_threads(); const I chunk = std::max((I)1,n_row/(100*nthread)); if(overwrite_y){ #pragma omp for schedule(static) for(I j = 0; j < n_row; j++){ y[j * y_stride] = 0; } } #pragma omp for schedule(dynamic,chunk) for(I j = 0; j < n_col; j++){ I col_start = Ap[j]; I col_end = Ap[j+1]; for(I ii = col_start; ii < col_end; ii++){ const I i = Ai[ii]; const T3 aa = (a * Ax[ii]) * x[j * x_stride]; atomic_add(y[i * y_stride],aa); } } } } template<typename I, typename T1, typename T2,typename T3> inline void csc_matvecs_omp_strided(const bool overwrite_y, const I n_row, const I n_col, const npy_intp n_vecs, const I Ap[], const I Ai[], const T1 Ax[], const T2 a, const npy_intp x_stride_row, const npy_intp x_stride_col, const T3 x[], const npy_intp y_stride_row, const npy_intp y_stride_col, T3 y[]) { csc_matvecs_noomp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Ai,Ax,a,x_stride_row,x_stride_col,x,y_stride_row,y_stride_col,y); } #else template<typename I, typename T1, typename T2,typename T3> void csc_matvec_omp_contig(const bool overwrite_y, const I n_row, const I n_col, const I Ap[], const I Ai[], const T1 Ax[], const T2 a, const T3 x[], T3 y[]) { csc_matvec_noomp_contig(overwrite_y,n_row,n_col,Ap,Ai,Ax,a,x,y); } template<typename I, typename T1, typename T2,typename T3> inline void csc_matvec_omp_strided(const bool overwrite_y, const I n_row, const I n_col, const I Ap[], const I Ai[], const T1 Ax[], const T2 a, const npy_intp x_stride, const T3 x[], const npy_intp y_stride, T3 y[]) { csc_matvec_noomp_strided(overwrite_y,n_row,n_col,Ap,Ai,Ax,a,x_stride,x,y_stride,y); } template<typename I, typename T1, typename T2,typename T3> inline void csc_matvecs_omp_strided(const bool overwrite_y, const I n_row, const I n_col, const npy_intp n_vecs, const I Ap[], const I Ai[], const T1 Ax[], const T2 a, const npy_intp x_stride_row, const npy_intp x_stride_col, const T3 x[], const npy_intp y_stride_row, const npy_intp y_stride_col, T3 y[]) { csc_matvecs_noomp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Ai,Ax,a,x_stride_row,x_stride_col,x,y_stride_row,y_stride_col,y); } #endif // when openmp is not being used omp and noomp versions are identical template<typename I, typename T1, typename T2,typename T3> void csc_matvec_noomp(const bool overwrite_y, const I n_row, const I n_col, const I Ap[], const I Aj[], const T1 Ax[], const T2 a, const npy_intp x_stride_byte, const T3 x[], const npy_intp y_stride_byte, T3 y[]) { const npy_intp y_stride = y_stride_byte/sizeof(T3); const npy_intp x_stride = x_stride_byte/sizeof(T3); if(y_stride == 1){ if(x_stride == 1){ csc_matvec_noomp_contig(overwrite_y,n_row,n_col,Ap,Aj,Ax,a,x,y); } else{ csc_matvec_noomp_strided(overwrite_y,n_row,n_col,Ap,Aj,Ax,a,x_stride,x,1,y); } } else{ if(x_stride == 1){ csc_matvec_noomp_strided(overwrite_y,n_row,n_col,Ap,Aj,Ax,a,1,x,y_stride,y); } else{ csc_matvec_noomp_strided(overwrite_y,n_row,n_col,Ap,Aj,Ax,a,x_stride,x,y_stride,y); } } } template<typename I, typename T1, typename T2,typename T3> void csc_matvec_omp(const bool overwrite_y, const I n_row, const I n_col, const I Ap[], const I Aj[], const T1 Ax[], const T2 a, const npy_intp x_stride_byte, const T3 x[], const npy_intp y_stride_byte, T3 y[]) { const npy_intp y_stride = y_stride_byte/sizeof(T3); const npy_intp x_stride = x_stride_byte/sizeof(T3); if(y_stride == 1){ if(x_stride == 1){ csc_matvec_omp_contig(overwrite_y,n_row,n_col,Ap,Aj,Ax,a,x,y); } else{ csc_matvec_omp_strided(overwrite_y,n_row,n_col,Ap,Aj,Ax,a,x_stride,x,1,y); } } else{ if(x_stride == 1){ csc_matvec_omp_strided(overwrite_y,n_row,n_col,Ap,Aj,Ax,a,1,x,y_stride,y); } else{ csc_matvec_omp_strided(overwrite_y,n_row,n_col,Ap,Aj,Ax,a,x_stride,x,y_stride,y); } } } template<typename I, typename T1, typename T2,typename T3> inline void csc_matvecs_noomp(const bool overwrite_y, const I n_row, const I n_col, const npy_intp n_vecs, const I Ap[], const I Aj[], const T1 Ax[], const T2 a, const npy_intp x_stride_row_byte, const npy_intp x_stride_col_byte, const T3 x[], const npy_intp y_stride_row_byte, const npy_intp y_stride_col_byte, T3 y[]) { const npy_intp y_stride_row = y_stride_row_byte/sizeof(T3); const npy_intp y_stride_col = y_stride_col_byte/sizeof(T3); const npy_intp x_stride_row = x_stride_row_byte/sizeof(T3); const npy_intp x_stride_col = x_stride_col_byte/sizeof(T3); if(y_stride_col==1){ if(x_stride_col==1){ csc_matvecs_noomp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,x_stride_row,1,x,y_stride_row,1,y); } else if(x_stride_row==1){ csc_matvecs_noomp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,1,x_stride_col,x,y_stride_row,1,y); } else{ csc_matvecs_noomp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,x_stride_row,x_stride_col,x,y_stride_row,1,y); } } else if(y_stride_row==1){ if(x_stride_col==1){ csc_matvecs_noomp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,x_stride_row,1,x,1,y_stride_col,y); } else if(x_stride_row==1){ csc_matvecs_noomp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,1,x_stride_col,x,1,y_stride_col,y); } else{ csc_matvecs_noomp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,x_stride_row,x_stride_col,x,1,y_stride_col,y); } } else{ csc_matvecs_noomp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,x_stride_row,x_stride_col,x,y_stride_row,y_stride_col,y); } } template<typename I, typename T1, typename T2,typename T3> inline void csc_matvecs_omp(const bool overwrite_y, const I n_row, const I n_col, const npy_intp n_vecs, const I Ap[], const I Aj[], const T1 Ax[], const T2 a, const npy_intp x_stride_row_byte, const npy_intp x_stride_col_byte, const T3 x[], const npy_intp y_stride_row_byte, const npy_intp y_stride_col_byte, T3 y[]) { const npy_intp y_stride_row = y_stride_row_byte/sizeof(T3); const npy_intp y_stride_col = y_stride_col_byte/sizeof(T3); const npy_intp x_stride_row = x_stride_row_byte/sizeof(T3); const npy_intp x_stride_col = x_stride_col_byte/sizeof(T3); if(y_stride_col==1){ if(x_stride_col==1){ csc_matvecs_omp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,x_stride_row,1,x,y_stride_row,1,y); } else if(x_stride_row==1){ csc_matvecs_omp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,1,x_stride_col,x,y_stride_row,1,y); } else{ csc_matvecs_omp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,x_stride_row,x_stride_col,x,y_stride_row,1,y); } } else if(y_stride_row==1){ if(x_stride_col==1){ csc_matvecs_omp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,x_stride_row,1,x,1,y_stride_col,y); } else if(x_stride_row==1){ csc_matvecs_omp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,1,x_stride_col,x,1,y_stride_col,y); } else{ csc_matvecs_omp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,x_stride_row,x_stride_col,x,1,y_stride_col,y); } } else{ csc_matvecs_omp_strided(overwrite_y,n_row,n_col,n_vecs,Ap,Aj,Ax,a,x_stride_row,x_stride_col,x,y_stride_row,y_stride_col,y); } } #endif
backward_binary_reduce_impl.h
/*! * Copyright (c) 2019 by Contributors * \file kernel/cuda/backward_binary_reduce_impl.h * \brief Minigun CPU UDFs for bacward binary reduce */ #ifndef DGL_KERNEL_CPU_BACKWARD_BINARY_REDUCE_IMPL_H_ #define DGL_KERNEL_CPU_BACKWARD_BINARY_REDUCE_IMPL_H_ #include <minigun/minigun.h> #include "../binary_reduce_impl_decl.h" #include "../utils.h" #include "./functor.h" #include "../csr_interface.h" namespace dgl { namespace kernel { namespace cpu { // Minigun UDF to compute backward binary reduce. template <int Mode, typename Idx, typename DType, typename Functors> struct BackwardBinaryReduce { static inline bool CondEdge( Idx src, Idx dst, Idx eid, BackwardGData<Idx, DType>* gdata) { return true; } static inline void ApplyEdge( Idx src, Idx dst, Idx eid, BackwardGData<Idx, DType>* gdata) { const int64_t D = gdata->x_length; const int64_t len = gdata->data_len; Idx lid = Functors::SelectLeft(src, eid, dst); Idx rid = Functors::SelectRight(src, eid, dst); Idx oid = Functors::SelectOut(src, eid, dst); if (gdata->lhs_mapping) { lid = Functors::GetId(lid, gdata->lhs_mapping); } if (gdata->rhs_mapping) { rid = Functors::GetId(rid, gdata->rhs_mapping); } if (gdata->out_mapping) { oid = Functors::GetId(oid, gdata->out_mapping); } DType* lhsoff = gdata->lhs_data + lid * D * len; DType* rhsoff = gdata->rhs_data + rid * D * len; DType* outoff = gdata->out_data + oid * D; DType* gradlhsoff = gdata->grad_lhs_data + lid * D * len; DType* gradrhsoff = gdata->grad_rhs_data + rid * D * len; DType* gradoutoff = gdata->grad_out_data + oid * D; for (int64_t tx = 0; tx < D; ++tx) { DType out = Functors::Read(outoff + tx); DType grad_out = Functors::Read(gradoutoff + tx); DType e = Functors::Op(lhsoff + tx * len, rhsoff + tx * len, len); DType grad_e = grad_out * Functors::BackwardWrite(e, out); DType* lhs_base = lhsoff + tx * len; DType* rhs_base = rhsoff + tx * len; if (Mode == binary_op::kGradBoth) { for (int64_t i = 0; i < len; ++i) { DType lhs = Functors::Read(lhs_base + i); DType rhs = Functors::Read(rhs_base + i); DType grad_lhs = grad_e * Functors::BackwardOpLhs(lhs, rhs, e); DType grad_rhs = grad_e * Functors::BackwardOpRhs(lhs, rhs, e); DType grad = grad_lhs + grad_rhs; #pragma omp atomic gradlhsoff[tx * len + i] += grad; } } else if (Mode == binary_op::kGradLhs) { for (int64_t i = 0; i < len; ++i) { DType lhs = Functors::Read(lhs_base + i); DType rhs = Functors::Read(rhs_base + i); DType grad_lhs = grad_e * Functors::BackwardOpLhs(lhs, rhs, e); #pragma omp atomic gradlhsoff[tx * len + i] += grad_lhs; } } else if (Mode == binary_op::kGradRhs) { for (int64_t i = 0; i < len; ++i) { DType lhs = Functors::Read(lhs_base + i); DType rhs = Functors::Read(rhs_base + i); DType grad_rhs = grad_e * Functors::BackwardOpRhs(lhs, rhs, e); #pragma omp atomic gradrhsoff[tx * len + i] += grad_rhs; } } } } }; // Minigun UDF to compute backward binary reduce with broadcasting. template <int Mode, int NDim, typename Idx, typename DType, typename Functors> struct BackwardBinaryReduceBcast { static inline bool CondEdge( Idx src, Idx dst, Idx eid, BackwardBcastGData<NDim, Idx, DType>* gdata) { return true; } static inline void ApplyEdge( Idx src, Idx dst, Idx eid, BackwardBcastGData<NDim, Idx, DType>* gdata) { const int64_t len = gdata->data_len; Idx lid = Functors::SelectLeft(src, eid, dst); Idx rid = Functors::SelectRight(src, eid, dst); Idx oid = Functors::SelectOut(src, eid, dst); if (gdata->lhs_mapping) { lid = Functors::GetId(lid, gdata->lhs_mapping); } if (gdata->rhs_mapping) { rid = Functors::GetId(rid, gdata->rhs_mapping); } if (gdata->out_mapping) { oid = Functors::GetId(oid, gdata->out_mapping); } DType* lhsoff = gdata->lhs_data + lid * gdata->lhs_len * len; DType* rhsoff = gdata->rhs_data + rid * gdata->rhs_len * len; DType* outoff = gdata->out_data + oid * gdata->out_len; DType* gradlhsoff = gdata->grad_lhs_data + lid * gdata->out_len * len; DType* gradrhsoff = gdata->grad_rhs_data + rid * gdata->out_len * len; DType* gradoutoff = gdata->grad_out_data + oid * gdata->out_len; int64_t tmp[NDim]; // store unraveled idx. for (int64_t tx = 0; tx < gdata->out_len; ++tx) { Unravel(tx, gdata->ndim, gdata->out_shape, gdata->out_stride, tmp); DType out = Functors::Read(outoff + tx); DType grad_out = Functors::Read(gradoutoff + tx); DType e = Functors::Op( lhsoff + Ravel(tmp, gdata->ndim, gdata->lhs_shape, gdata->lhs_stride) * len, rhsoff + Ravel(tmp, gdata->ndim, gdata->rhs_shape, gdata->rhs_stride) * len, len); DType grad_e = grad_out * Functors::BackwardWrite(e, out); DType* lhs_base = lhsoff + Ravel(tmp, gdata->ndim, gdata->lhs_shape, gdata->lhs_stride) * len; DType* rhs_base = rhsoff + Ravel(tmp, gdata->ndim, gdata->rhs_shape, gdata->rhs_stride) * len; if (Mode == binary_op::kGradBoth) { for (int64_t i = 0; i < len; ++i) { DType lhs = Functors::Read(lhs_base + i); DType rhs = Functors::Read(rhs_base + i); DType grad_lhs = grad_e * Functors::BackwardOpLhs(lhs, rhs, e); DType grad_rhs = grad_e * Functors::BackwardOpRhs(lhs, rhs, e); DType grad = grad_lhs + grad_rhs; #pragma omp atomic gradlhsoff[tx * len + i] += grad; } } else if (Mode == binary_op::kGradLhs) { for (int64_t i = 0; i < len; ++i) { DType lhs = Functors::Read(lhs_base + i); DType rhs = Functors::Read(rhs_base + i); DType grad_lhs = grad_e * Functors::BackwardOpLhs(lhs, rhs, e); #pragma omp atomic gradlhsoff[tx * len + i] += grad_lhs; } } else if (Mode == binary_op::kGradRhs) { for (int64_t i = 0; i < len; ++i) { DType lhs = Functors::Read(lhs_base + i); DType rhs = Functors::Read(rhs_base + i); DType grad_rhs = grad_e * Functors::BackwardOpRhs(lhs, rhs, e); #pragma omp atomic gradrhsoff[tx * len + i] += grad_rhs; } } } } }; // Auxiliary template used in UDF. template <typename Idx, typename DType, typename LeftSelector, typename RightSelector, typename BinaryOp, typename Reducer> struct BackwardFunctorsTempl { static inline Idx SelectOut( Idx src, Idx edge, Idx dst) { typedef typename OutSelector<Reducer>::Type OutTarget; return SwitchSrcDst<OutTarget>::Type::Call(src, edge, dst); } static inline Idx SelectLeft( Idx src, Idx edge, Idx dst) { return LeftSelector::Call(src, edge, dst); } static inline Idx SelectRight( Idx src, Idx edge, Idx dst) { return RightSelector::Call(src, edge, dst); } static inline DType Op(DType* lhs, DType* rhs, int64_t len) { return BinaryOp::Call(lhs, rhs, len); } static inline DType Read(DType* addr) { return *addr; } static inline void Write(DType* addr, DType val) { Reducer::Call(addr, val); } static inline Idx GetId(Idx id, Idx* id_map) { return *(id_map + id); } static inline DType BackwardWrite(DType val, DType accum) { return Reducer::BackwardCall(val, accum); } static inline DType BackwardOpLhs(DType lhs, DType rhs, DType out) { return BinaryOp::BackwardLhs(lhs, rhs, out); } static inline DType BackwardOpRhs(DType lhs, DType rhs, DType out) { return BinaryOp::BackwardRhs(lhs, rhs, out); } }; typedef minigun::advance::Config<true, minigun::advance::kV2N> AdvanceConfig; } // namespace cpu // Template implementation of BackwardBinaryReduce operator. template <int XPU, int Mode, typename Idx, typename DType, typename LeftSelector, typename RightSelector, typename BinaryOp, typename Reducer> void CallBackwardBinaryReduce( const minigun::advance::RuntimeConfig& rtcfg, const CSRWrapper& graph, BackwardGData<Idx, DType>* gdata) { // For backward computation, we use reverse csr and switch dst and src. // This benefits the most common src_op_edge or copy_src case, because the // gradients of src are now aggregated into destination buffer to reduce // competition of atomic add. auto incsr = graph.GetInCSRMatrix(); minigun::Csr<Idx> csr = utils::CreateCsr<Idx>(incsr.indptr, incsr.indices); typedef cpu::BackwardFunctorsTempl<Idx, DType, typename SwitchSrcDst<LeftSelector>::Type, typename SwitchSrcDst<RightSelector>::Type, BinaryOp, Reducer> Functors; typedef cpu::BackwardBinaryReduce<Mode, Idx, DType, Functors> UDF; // If the user-given mapping is none and the target is edge data, we need to // replace the mapping by the edge ids in the csr graph so that the edge // data is correctly read/written. if (LeftSelector::target == binary_op::kEdge && gdata->lhs_mapping == nullptr) { gdata->lhs_mapping = static_cast<Idx*>(incsr.data->data); } if (RightSelector::target == binary_op::kEdge && gdata->rhs_mapping == nullptr) { gdata->rhs_mapping = static_cast<Idx*>(incsr.data->data); } if (OutSelector<Reducer>::Type::target == binary_op::kEdge && gdata->out_mapping == nullptr) { gdata->out_mapping = static_cast<Idx*>(incsr.data->data); } // TODO(minjie): allocator minigun::advance::Advance<XPU, Idx, cpu::AdvanceConfig, BackwardGData<Idx, DType>, UDF>( rtcfg, csr, gdata, minigun::IntArray1D<Idx>()); } // Following macro is used to generate explicit-specialization of the template // operator. #define GEN_BACKWARD_DEFINE(mode, dtype, lhs_tgt, rhs_tgt, op) \ template void CallBackwardBinaryReduce<XPU, \ mode, IDX, dtype, \ lhs_tgt, rhs_tgt, \ op<dtype>, REDUCER<XPU, dtype>>( \ const minigun::advance::RuntimeConfig& rtcfg, \ const CSRWrapper& graph, \ BackwardGData<IDX, dtype>* gdata); // Template implementation of BackwardBinaryReduce with broadcasting operator. template <int XPU, int Mode, int NDim, typename Idx, typename DType, typename LeftSelector, typename RightSelector, typename BinaryOp, typename Reducer> void CallBackwardBinaryReduceBcast( const minigun::advance::RuntimeConfig& rtcfg, const CSRWrapper& graph, BackwardBcastGData<NDim, Idx, DType>* gdata) { // For backward computation, we use reverse csr and switch dst and src. // This benefits the most common src_op_edge or copy_src case, because the // gradients of src are now aggregated into destination buffer to reduce // competition of atomic add. auto incsr = graph.GetInCSRMatrix(); minigun::Csr<Idx> csr = utils::CreateCsr<Idx>(incsr.indptr, incsr.indices); typedef cpu::BackwardFunctorsTempl<Idx, DType, typename SwitchSrcDst<LeftSelector>::Type, typename SwitchSrcDst<RightSelector>::Type, BinaryOp, Reducer> Functors; typedef cpu::BackwardBinaryReduceBcast<Mode, NDim, Idx, DType, Functors> UDF; // If the user-given mapping is none and the target is edge data, we need to // replace the mapping by the edge ids in the csr graph so that the edge // data is correctly read/written. if (LeftSelector::target == binary_op::kEdge && gdata->lhs_mapping == nullptr) { gdata->lhs_mapping = static_cast<Idx*>(incsr.data->data); } if (RightSelector::target == binary_op::kEdge && gdata->rhs_mapping == nullptr) { gdata->rhs_mapping = static_cast<Idx*>(incsr.data->data); } if (OutSelector<Reducer>::Type::target == binary_op::kEdge && gdata->out_mapping == nullptr) { gdata->out_mapping = static_cast<Idx*>(incsr.data->data); } // TODO(minjie): allocator minigun::advance::Advance<XPU, Idx, cpu::AdvanceConfig, BackwardBcastGData<NDim, Idx, DType>, UDF>( rtcfg, csr, gdata, minigun::IntArray1D<Idx>()); } // Following macro is used to generate explicit-specialization of the template // operator. #define GEN_BACKWARD_BCAST_DEFINE(mode, ndim, dtype, lhs_tgt, rhs_tgt, op) \ template void CallBackwardBinaryReduceBcast<XPU, \ mode, ndim, IDX, dtype, \ lhs_tgt, rhs_tgt, \ op<dtype>, REDUCER<XPU, dtype>>( \ const minigun::advance::RuntimeConfig& rtcfg, \ const CSRWrapper& graph, \ BackwardBcastGData<ndim, IDX, dtype>* gdata); } // namespace kernel } // namespace dgl #endif // DGL_KERNEL_CPU_BACKWARD_BINARY_REDUCE_IMPL_H_
forced_unroll.c
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "constants.h" /** * Deinterleave (transpose) an IQUV ring buffer page to the ordering needed for FITS files * Note that this is probably a slow function, and is not meant to be run real-time * * data in: tab, channel/4, time/500 packets of time,channel,pn * data out: tab, channel, pol, time * * Suggested use is: * 1. realtime: ringbuffer -> [trigger] -> dada_dbdisk * 2. offline: dada_dbdisk -> ringbuffer -> dadafits * * @param {const char *} page Ringbuffer page with interleaved data * @param {const char *} transposed * @param {int} ntabs Number of tabs * @param {int} nchannels Number of channels * @param {int} npackets Number of packets per sequence */ void deinterleave (const unsigned char *page, unsigned char *transposed, const int ntabs, const int nchannels, const int npackets) { const unsigned char *packet = page; int tab = 0; for (tab = 0; tab < ntabs; tab++) { int channel_offset = 0; for (channel_offset = 0; channel_offset < nchannels; channel_offset+=4) { unsigned char *intermediate = &transposed[(tab * nchannels + channel_offset)*NPOLS*npackets*NSAMPS]; int sequence_number = 0; for (sequence_number = 0; sequence_number < npackets; sequence_number++) { // process packet: int tn; #pragma omp parallel for for (tn = 0; tn < NSAMPS; tn++) { // 500 samples per packet intermediate[( 0 * NPOLS + 0) * npackets * NSAMPS + tn] = *packet++; intermediate[( 0 * NPOLS + 1) * npackets * NSAMPS + tn] = *packet++; intermediate[( 0 * NPOLS + 2) * npackets * NSAMPS + tn] = *packet++; intermediate[( 0 * NPOLS + 3) * npackets * NSAMPS + tn] = *packet++; intermediate[( 1 * NPOLS + 0) * npackets * NSAMPS + tn] = *packet++; intermediate[( 1 * NPOLS + 1) * npackets * NSAMPS + tn] = *packet++; intermediate[( 1 * NPOLS + 2) * npackets * NSAMPS + tn] = *packet++; intermediate[( 1 * NPOLS + 3) * npackets * NSAMPS + tn] = *packet++; intermediate[( 2 * NPOLS + 0) * npackets * NSAMPS + tn] = *packet++; intermediate[( 2 * NPOLS + 1) * npackets * NSAMPS + tn] = *packet++; intermediate[( 2 * NPOLS + 2) * npackets * NSAMPS + tn] = *packet++; intermediate[( 2 * NPOLS + 3) * npackets * NSAMPS + tn] = *packet++; intermediate[( 3 * NPOLS + 0) * npackets * NSAMPS + tn] = *packet++; intermediate[( 3 * NPOLS + 1) * npackets * NSAMPS + tn] = *packet++; intermediate[( 3 * NPOLS + 2) * npackets * NSAMPS + tn] = *packet++; intermediate[( 3 * NPOLS + 3) * npackets * NSAMPS + tn] = *packet++; } // tn } // sequence number } // channel_offset } // tab }
mandel-omp-taskloop-point.c
/* * Sequential Mandelbrot program * * This program computes and displays all or part of the Mandelbrot * set. By default, it examines all points in the complex plane * that have both real and imaginary parts between -2 and 2. * Command-line parameters allow zooming in on a specific part of * this range. * * Usage: * mandel [-i maxiter -c x0 y0 -s size -w windowsize] * where * maxiter denotes the maximum number of iterations at each point -- by default 1000 * x0, y0, and size specify the range to examine (a square * centered at (x0 + iy0) of size 2*size by 2*size -- by default, * a square of size 4 by 4 centered at the origin) * windowsize denotes the size of the image (diplay window) to compute * * Input: none, except the optional command-line arguments * Output: a graphical display as described in Wilkinson & Allen, * displayed using the X Window system, plus text output to * standard output showing the above parameters, plus execution * time in seconds. * * Code based on the original code from Web site for Wilkinson and Allen's * text on parallel programming: * http://www.cs.uncc.edu/~abw/parallel/par_prog/ * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> #include <malloc.h> #if _DISPLAY_ #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xos.h> #endif #include <sys/time.h> double getusec_() { struct timeval time; gettimeofday(&time, NULL); return ((double)time.tv_sec * (double)1e6 + (double)time.tv_usec); } #define START_COUNT_TIME stamp = getusec_(); #define STOP_COUNT_TIME(_m) stamp = getusec_() - stamp;\ stamp = stamp/1e6;\ printf ("%s: %0.6fs\n",(_m), stamp); /* Default values for things. */ #define G 4 /* grainsize */ #define N 2 /* size of problem space (x, y from -N to N) */ #define NPIXELS 800 /* size of display window in pixels */ int row, col; // variables used to traverse the problem space /* Structure definition for complex numbers */ typedef struct { double real, imag; } complex; #if _DISPLAY_ /* Functions for GUI */ #include "mandelbrot-gui.h" /* has setup(), interact() */ #endif void mandelbrot(int height, int width, double real_min, double imag_min, double scale_real, double scale_imag, int maxiter, #if _DISPLAY_ int setup_return, Display *display, Window win, GC gc, double scale_color, double min_color) #else int ** output) #endif { /* Calculate points and save/display */ //#pragma omp for schedule(runtime) #pragma omp parallel #pragma omp single #pragma omp taskloop grainsize(G) for (row = 0; row < height; ++row) { //#pragma omp task for (col = 0; col < width; ++col) { complex z, c; z.real = z.imag = 0; /* Scale display coordinates to actual region */ c.real = real_min + ((double) col * scale_real); c.imag = imag_min + ((double) (height-1-row) * scale_imag); /* height-1-row so y axis displays * with larger values at top */ /* Calculate z0, z1, .... until divergence or maximum iterations */ int k = 0; double lengthsq, temp; do { temp = z.real*z.real - z.imag*z.imag + c.real; z.imag = 2*z.real*z.imag + c.imag; z.real = temp; lengthsq = z.real*z.real + z.imag*z.imag; ++k; } while (lengthsq < (N*N) && k < maxiter); #if _DISPLAY_ /* Scale color and display point */ long color = (long) ((k-1) * scale_color) + min_color; if (setup_return == EXIT_SUCCESS) { #pragma omp critical { XSetForeground (display, gc, color); XDrawPoint (display, win, gc, col, row); } } #else output[row][col]=k; #endif } } } int main(int argc, char *argv[]) { int maxiter = 1000; double real_min; double real_max; double imag_min; double imag_max; int width = NPIXELS; /* dimensions of display window */ int height = NPIXELS; double size=N, x0 = 0, y0 = 0; #if _DISPLAY_ Display *display; Window win; GC gc; int setup_return; long min_color = 0, max_color = 0; double scale_color; #else int ** output; FILE *fp = NULL; #endif double scale_real, scale_imag; /* Process command-line arguments */ for (int i=1; i<argc; i++) { if (strcmp(argv[i], "-i")==0) { maxiter = atoi(argv[++i]); } else if (strcmp(argv[i], "-w")==0) { width = atoi(argv[++i]); height = width; } else if (strcmp(argv[i], "-s")==0) { size = atof(argv[++i]); } #if !_DISPLAY_ else if (strcmp(argv[i], "-o")==0) { if((fp=fopen("mandel.out", "wb"))==NULL) { fprintf(stderr, "Unable to open file\n"); return EXIT_FAILURE; } } #endif else if (strcmp(argv[i], "-c")==0) { x0 = atof(argv[++i]); y0 = atof(argv[++i]); } else { #if _DISPLAY_ fprintf(stderr, "Usage: %s [-i maxiter -w windowsize -c x0 y0 -s size]\n", argv[0]); #else fprintf(stderr, "Usage: %s [-o -i maxiter -w windowsize -c x0 y0 -s size]\n", argv[0]); fprintf(stderr, " -o to write computed image to disk (default no file generated)\n"); #endif fprintf(stderr, " -i to specify maximum number of iterations at each point (default 1000)\n"); #if _DISPLAY_ fprintf(stderr, " -w to specify the size of the display window (default 800x800 pixels)\n"); #else fprintf(stderr, " -w to specify the size of the image to compute (default 800x800 elements)\n"); #endif fprintf(stderr, " -c to specify the center x0+iy0 of the square to compute (default origin)\n"); fprintf(stderr, " -s to specify the size of the square to compute (default 2, i.e. size 4 by 4)\n"); return EXIT_FAILURE; } } real_min = x0 - size; real_max = x0 + size; imag_min = y0 - size; imag_max = y0 + size; /* Produce text output */ fprintf(stdout, "\n"); fprintf(stdout, "Mandelbrot program\n"); fprintf(stdout, "center = (%g, %g), size = %g\n", (real_max + real_min)/2, (imag_max + imag_min)/2, (real_max - real_min)/2); fprintf(stdout, "maximum iterations = %d\n", maxiter); fprintf(stdout, "\n"); #if _DISPLAY_ /* Initialize for graphical display */ setup_return = setup(width, height, &display, &win, &gc, &min_color, &max_color); if (setup_return != EXIT_SUCCESS) { fprintf(stderr, "Unable to initialize display, continuing\n"); return EXIT_FAILURE; } #else output = malloc(height*sizeof(int *)); for (int row = 0; row < height; ++row) output[row] = malloc(width*sizeof(int)); #endif /* Compute factors to scale computational region to window */ scale_real = (double) (real_max - real_min) / (double) width; scale_imag = (double) (imag_max - imag_min) / (double) height; #if _DISPLAY_ /* Compute factor for color scaling */ scale_color = (double) (max_color - min_color) / (double) (maxiter - 1); #endif /* Start timing */ double stamp; START_COUNT_TIME; #if _DISPLAY_ mandelbrot(height,width,real_min, imag_min, scale_real, scale_imag, maxiter, setup_return, display, win, gc, scale_color, min_color); #else mandelbrot(height,width,real_min, imag_min, scale_real, scale_imag, maxiter, output); #endif /* End timing */ STOP_COUNT_TIME("Total execution time"); /* Be sure all output is written */ #if _DISPLAY_ if (setup_return == EXIT_SUCCESS) { XFlush (display); } #else if (fp != NULL) { for (int row = 0; row < height; ++row) if(fwrite(output[row], sizeof(int), width, fp) != width) { fprintf(stderr, "Output file not written correctly\n"); } } #endif #if _DISPLAY_ /* Wait for user response, then exit program */ if (setup_return == EXIT_SUCCESS) { interact(display, &win, width, height, real_min, real_max, imag_min, imag_max); } return EXIT_SUCCESS; #endif }
cherk.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/zherk.c, normal z -> c, Fri Sep 28 17:38:06 2018 * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_tuning.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_herk * * Performs one of the Hermitian rank k operations * * \f[ C = \alpha A \times A^H + \beta C, \f] * or * \f[ C = \alpha A^H \times A + \beta C, \f] * * 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. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of C is stored; * - PlasmaLower: Lower triangle of C is stored. * * @param[in] trans * - PlasmaNoTrans: \f[ C = \alpha A \times A^H + \beta C; \f] * - PlasmaConjTrans: \f[ C = \alpha A^H \times A + \beta C. \f] * * @param[in] n * The order of the matrix C. n >= 0. * * @param[in] k * If trans = PlasmaNoTrans, number of columns of the A matrix; * if trans = PlasmaConjTrans, number of rows of the A matrix. * * @param[in] alpha * The scalar alpha. * * @param[in] pA * A is an lda-by-ka matrix. * If trans = PlasmaNoTrans, ka = k; * if trans = PlasmaConjTrans, ka = n. * * @param[in] lda * The leading dimension of the array A. * If trans = PlasmaNoTrans, lda >= max(1, n); * if trans = PlasmaConjTrans, lda >= max(1, k). * * @param[in] beta * The scalar beta. * * @param[in,out] pC * C is an ldc-by-n matrix. * On exit, the uplo part of the matrix is overwritten * by the uplo part of the updated matrix. * * @param[in] ldc * The leading dimension of the array C. ldc >= max(1, n). * ******************************************************************************* * * @retval PlasmaSuccess successful exit * ******************************************************************************* * * @sa plasma_omp_cherk * @sa plasma_cherk * ******************************************************************************/ int plasma_cherk(plasma_enum_t uplo, plasma_enum_t trans, int n, int k, float alpha, plasma_complex32_t *pA, int lda, float beta, plasma_complex32_t *pC, int ldc) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if ((uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); return -1; } if ((trans != PlasmaNoTrans) && (trans != PlasmaConjTrans)) { plasma_error("illegal value of trans"); return -2; } if (n < 0) { plasma_error("illegal value of n"); return -3; } if (k < 0) { plasma_error("illegal value of k"); return -4; } int am, an; if (trans == PlasmaNoTrans) { am = n; an = k; } else { am = k; an = n; } if (lda < imax(1, am)) { plasma_error("illegal value of lda"); return -7; } if (ldc < imax(1, n)) { plasma_error("illegal value of ldc"); return -10; } // quick return if (n == 0 || ((alpha == 0.0 || k == 0) && beta == 1.0)) return PlasmaSuccess; // Tune parameters. if (plasma->tuning) plasma_tune_syrk(plasma, PlasmaComplexFloat, n, k); // Set tiling parameters. int nb = plasma->nb; // Initialize tile matrix descriptors. plasma_desc_t A; plasma_desc_t C; int retval; retval = plasma_desc_general_create(PlasmaComplexFloat, nb, nb, am, an, 0, 0, am, an, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } retval = plasma_desc_general_create(PlasmaComplexFloat, nb, nb, n, n, 0, 0, n, n, &C); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&A); return retval; } // Initialize sequence. plasma_sequence_t sequence; retval = plasma_sequence_init(&sequence); // Initialize request. plasma_request_t request; retval = plasma_request_init(&request); // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_cge2desc(pA, lda, A, &sequence, &request); plasma_omp_cge2desc(pC, ldc, C, &sequence, &request); // Call the tile async function. plasma_omp_cherk(uplo, trans, alpha, A, beta, C, &sequence, &request); // Translate back to LAPACK layout. plasma_omp_cdesc2ge(C, pC, ldc, &sequence, &request); } // implicit synchronization // Free matrices in tile layout. plasma_desc_destroy(&A); plasma_desc_destroy(&C); // Return status. int status = sequence.status; return status; } /***************************************************************************//** * * @ingroup plasma_herk * * Performs rank k update. * Non-blocking tile version of plasma_cherk(). * May return before the computation is finished. * Operates on matrices stored by tiles. * All matrices are passed through descriptors. * All dimensions are taken from the descriptors. * Allows for pipelining of operations at runtime. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of C is stored; * - PlasmaLower: Lower triangle of C is stored. * * @param[in] trans * - PlasmaNoTrans: \f[ C = \alpha A \times A^H + \beta C; \f] * - PlasmaConjTrans: \f[ C = \alpha A^H \times A + \beta C. \f] * * @param[in] alpha * The scalar alpha. * * @param[in] A * Descriptor of matrix A. * * @param[in] beta * The scalar beta. * * @param[in,out] C * Descriptor of matrix C. * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). Check * the sequence->status for errors. * * @param[out] request * Identifies this function call (for exception handling purposes). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_cherk * @sa plasma_omp_cherk * @sa plasma_omp_cherk * @sa plasma_omp_dherk * @sa plasma_omp_sherk * ******************************************************************************/ void plasma_omp_cherk(plasma_enum_t uplo, plasma_enum_t trans, float alpha, plasma_desc_t A, float beta, plasma_desc_t C, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if ((uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if ((trans != PlasmaNoTrans) && (trans != PlasmaConjTrans)) { plasma_error("illegal value of trans"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(A) != PlasmaSuccess) { plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); plasma_error("invalid A"); return; } if (plasma_desc_check(C) != PlasmaSuccess) { plasma_error("invalid C"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return int k = trans == PlasmaNoTrans ? A.n : A.m; if (C.m == 0 || ((alpha == 0.0 || k == 0) && beta == 1.0)) return; // Call the parallel function. plasma_pcherk(uplo, trans, alpha, A, beta, C, sequence, request); }
nested_thread_num.c
// RUN: %libomp-compile-and-run | FileCheck %s // RUN: %libomp-compile-and-run | %sort-threads | FileCheck --check-prefix=THREADS %s // REQUIRES: ompt // UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7, gcc-8 #define TEST_NEED_PRINT_FRAME_FROM_OUTLINED_FN #include "callback.h" #include <omp.h> #include <unistd.h> int main() { int condition = 0; omp_set_nested(1); print_frame(0); #pragma omp parallel num_threads(2) { print_frame_from_outlined_fn(1); print_ids(0); print_ids(1); print_frame(0); // get all implicit task events before starting nested: #pragma omp barrier #pragma omp parallel num_threads(2) { print_frame_from_outlined_fn(1); print_ids(0); print_ids(1); print_ids(2); print_frame(0); OMPT_SIGNAL(condition); OMPT_WAIT(condition, 4); #pragma omp barrier print_fuzzy_address(1); print_ids(0); } print_fuzzy_address(2); print_ids(0); } print_fuzzy_address(3); return 0; } // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback // CHECK: 0: NULL_POINTER=[[NULL:.*$]] // make sure initial data pointers are null // CHECK-NOT: 0: parallel_data initially not null // CHECK-NOT: 0: task_data initially not null // CHECK-NOT: 0: thread_data initially not null // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_parallel_begin: // CHECK-SAME: parent_task_id=[[PARENT_TASK_ID:[0-9]+]], // CHECK-SAME: parent_task_frame.exit=[[NULL]], // CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}}, // CHECK-SAME: parallel_id=[[PARALLEL_ID:[0-9]+]], // CHECK-SAME: requested_team_size=2, // CHECK-SAME: codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}}, // CHECK-SAME: invoker=[[PARALLEL_INVOKER:[0-9]+]] // CHECK-DAG: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin: // CHECK-DAG: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end: // Note that we cannot ensure that the worker threads have already called // barrier_end and implicit_task_end before parallel_end! // CHECK-DAG: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_implicit_task_begin: // CHECK-DAG: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin: // CHECK: ompt_event_parallel_end: parallel_id=[[PARALLEL_ID]], // CHECK-SAME: task_id=[[PARENT_TASK_ID]], invoker=[[PARALLEL_INVOKER]] // CHECK: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] // THREADS: {{^}}0: NULL_POINTER=[[NULL:.*$]] // THREADS: __builtin_frame_address(0)=[[MAIN_REENTER:0x[0-f]+]] // THREADS: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_parallel_begin: // THREADS-SAME: parent_task_id=[[PARENT_TASK_ID:[0-9]+]], // THREADS-SAME: parent_task_frame.exit=[[NULL]], // THREADS-SAME: parent_task_frame.reenter=0x{{[0-f]+}}, // THREADS-SAME: parallel_id=[[PARALLEL_ID:[0-9]+]], requested_team_size=2, // THREADS-SAME: codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}}, // THREADS-SAME: invoker=[[PARALLEL_INVOKER:[0-9]+]] // nested parallel masters // THREADS: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin: // THREADS-SAME: parallel_id=[[PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]], // THREADS-SAME: team_size=2, thread_num=0 // THREADS: __builtin_frame_address({{.}})=[[EXIT:0x[0-f]+]] // THREADS: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[EXIT]], // THREADS-SAME: reenter_frame=[[NULL]], // THREADS-SAME: thread_num=0 // THREADS: {{^}}[[MASTER_ID]]: task level 1: // THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID:[0-9]+]], // THREADS-SAME: task_id=[[PARENT_TASK_ID]], exit_frame=[[NULL]], // THREADS-SAME: reenter_frame=0x{{[0-f]+}} // THREADS: __builtin_frame_address(0)=[[REENTER:0x[0-f]+]] // THREADS: {{^}}[[MASTER_ID]]: ompt_event_parallel_begin: // THREADS-SAME: parent_task_id=[[IMPLICIT_TASK_ID]], // THREADS-SAME: parent_task_frame.exit=[[EXIT]], // THREADS-SAME: parent_task_frame.reenter=0x{{[0-f]+}}, // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID:[0-9]+]], // THREADS-SAME: requested_team_size=2, // THREADS-SAME: codeptr_ra=[[NESTED_RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}}, // THREADS-SAME: invoker=[[PARALLEL_INVOKER]] // THREADS: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID:[0-9]+]], team_size=2, // THREADS-SAME: thread_num=0 // THREADS: __builtin_frame_address({{.}})=[[NESTED_EXIT:0x[0-f]+]] // THREADS: {{^}}[[MASTER_ID]]: task level 0: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]], // THREADS-SAME: exit_frame=[[NESTED_EXIT]], reenter_frame=[[NULL]], // THREADS-SAME: thread_num=0 // THREADS: {{^}}[[MASTER_ID]]: task level 1: parallel_id=[[PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[EXIT]], // THREADS-SAME: reenter_frame=0x{{[0-f]+}} // THREADS: {{^}}[[MASTER_ID]]: task level 2: // THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]], // THREADS-SAME: task_id=[[PARENT_TASK_ID]], exit_frame=[[NULL]], // THREADS-SAME: reenter_frame=0x{{[0-f]+}} // THREADS: __builtin_frame_address(0)=[[NESTED_REENTER:0x[0-f]+]] // THREADS-NOT: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end // explicit barrier // THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_begin: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]], // THREADS-SAME: codeptr_ra=[[BARRIER_RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}} // THREADS: {{^}}[[MASTER_ID]]: task level 0: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]], // THREADS-SAME: exit_frame=[[NESTED_EXIT]], reenter_frame=0x{{[0-f]+}} // THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_end: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]] // THREADS: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[BARRIER_RETURN_ADDRESS]] // THREADS: {{^}}[[MASTER_ID]]: task level 0: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]], // THREADS-SAME: exit_frame=[[NESTED_EXIT]], reenter_frame=[[NULL]] // implicit barrier // THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_begin: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]], // THREADS-SAME: codeptr_ra=[[NESTED_RETURN_ADDRESS]]{{[0-f][0-f]}} // THREADS: {{^}}[[MASTER_ID]]: task level 0: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]], // THREADS-SAME: exit_frame=[[NULL]], reenter_frame=[[NULL]] // THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_end: // THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[NESTED_IMPLICIT_TASK_ID]], // THREADS-SAME: codeptr_ra=[[NESTED_RETURN_ADDRESS]]{{[0-f][0-f]}} // THREADS: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end: // THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[NESTED_IMPLICIT_TASK_ID]] // THREADS: {{^}}[[MASTER_ID]]: ompt_event_parallel_end: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]], // THREADS-SAME: invoker=[[PARALLEL_INVOKER]], // THREADS-SAME: codeptr_ra=[[NESTED_RETURN_ADDRESS]]{{[0-f][0-f]}} // THREADS: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[NESTED_RETURN_ADDRESS]] // THREADS-NOT: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end // THREADS: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[EXIT]], // THREADS-SAME: reenter_frame=[[NULL]] // implicit barrier // THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_begin: // THREADS-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], // THREADS-SAME: codeptr_ra=[[RETURN_ADDRESS]]{{[0-f][0-f]}} // THREADS: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[NULL]], // THREADS-SAME: reenter_frame=[[NULL]] // THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_end: // THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]], // THREADS-SAME: codeptr_ra=[[RETURN_ADDRESS]]{{[0-f][0-f]}} // THREADS: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end: // THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]] // THREADS: {{^}}[[MASTER_ID]]: ompt_event_parallel_end: // THREADS-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[PARENT_TASK_ID]], // THREADS-SAME: invoker=[[PARALLEL_INVOKER]], // THREADS-SAME: codeptr_ra=[[RETURN_ADDRESS]]{{[0-f][0-f]}} // THREADS: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]] // Worker of first nesting level // THREADS: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_implicit_task_begin: // THREADS-SAME: parallel_id=[[PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]], team_size=2, // THREADS-SAME: thread_num=[[OUTER_THREADNUM:[0-9]+]] // THREADS: {{^}}[[THREAD_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]], // THREADS-SAME: thread_num=[[OUTER_THREADNUM]] // THREADS: {{^}}[[THREAD_ID]]: task level 1: // THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]], // THREADS-SAME: task_id=[[PARENT_TASK_ID]] // THREADS: {{^}}[[THREAD_ID]]: ompt_event_parallel_begin: // THREADS-SAME: parent_task_id=[[IMPLICIT_TASK_ID]], // THREADS-SAME: parent_task_frame.exit={{0x[0-f]+}}, // THREADS-SAME: parent_task_frame.reenter={{0x[0-f]+}}, // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID:[0-9]+]], requested_team_size=2, // THREADS-SAME: codeptr_ra=[[NESTED_RETURN_ADDRESS]]{{[0-f][0-f]}}, // THREADS-SAME: invoker=[[PARALLEL_INVOKER]] // THREADS: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_begin: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID:[0-9]+]], team_size=2, // THREADS-SAME: thread_num=[[INNER_THREADNUM:[0-9]+]] // THREADS: {{^}}[[THREAD_ID]]: task level 0: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]], // THREADS-SAME: thread_num=[[INNER_THREADNUM]] // THREADS: {{^}}[[THREAD_ID]]: task level 1: parallel_id=[[PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]], // THREADS-SAME: thread_num=[[OUTER_THREADNUM]] // THREADS: {{^}}[[THREAD_ID]]: task level 2: // THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]], // THREADS-SAME: task_id=[[PARENT_TASK_ID]] // THREADS-NOT: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end // THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]] // THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_end: // THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[NESTED_IMPLICIT_TASK_ID]] // THREADS: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end: // THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[NESTED_IMPLICIT_TASK_ID]] // THREADS: {{^}}[[THREAD_ID]]: ompt_event_parallel_end: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]], invoker=[[PARALLEL_INVOKER]] // THREADS-NOT: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end // THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin: // THREADS-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_end: // THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]] // THREADS: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end: // THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]] // nested parallel worker threads // THREADS: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_implicit_task_begin: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID:[0-9]+]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]] // THREADS-SAME: thread_num=[[THREADNUM:[0-9]+]] // THREADS: {{^}}[[THREAD_ID]]: task level 0: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]] // THREADS-SAME: thread_num=[[THREADNUM]] // can't reliably tell which parallel region is the parent... // THREADS: {{^}}[[THREAD_ID]]: task level 1: parallel_id={{[0-9]+}}, // THREADS-SAME: task_id={{[0-9]+}} // THREADS-SAME: thread_num={{[01]}} // THREADS: {{^}}[[THREAD_ID]]: task level 2: // THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]], // THREADS-SAME: task_id=[[PARENT_TASK_ID]] // THREADS-SAME: thread_num=0 // THREADS-NOT: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end // THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]] // THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_end: // THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]] // THREADS: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end: // THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]] // other nested parallel worker threads // THREADS: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_implicit_task_begin: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID:[0-9]+]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]] // THREADS-SAME: thread_num=[[THREADNUM:[0-9]+]] // THREADS: {{^}}[[THREAD_ID]]: task level 0: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]] // THREADS-SAME: thread_num=[[THREADNUM]] // can't reliably tell which parallel region is the parent... // THREADS: {{^}}[[THREAD_ID]]: task level 1: parallel_id={{[0-9]+}}, // THREADS-SAME: task_id={{[0-9]+}} // THREADS-SAME: thread_num={{[01]}} // THREADS: {{^}}[[THREAD_ID]]: task level 2: // THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]], // THREADS-SAME: task_id=[[PARENT_TASK_ID]] // THREADS-SAME: thread_num=0 // THREADS-NOT: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end // THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin: // THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]], // THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]] // THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_end: // THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]] // THREADS: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end: // THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]]
update_ops_control_multi_target_single.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "constant.h" #include "update_ops.h" #include "utility.h" #ifdef _OPENMP #include <omp.h> #endif #ifdef _MSC_VER #include <intrin.h> #else #include <x86intrin.h> #endif void create_shift_mask_list_from_list_and_value_buf(const UINT* array, UINT count, UINT target, UINT* dst_array, ITYPE* dst_mask); //void multi_qubit_control_single_qubit_dense_matrix_gate_old_single(const UINT* control_qubit_index_list, const UINT* control_value_list, UINT control_qubit_index_count, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim); //void multi_qubit_control_single_qubit_dense_matrix_gate_old_parallel(const UINT* control_qubit_index_list, const UINT* control_value_list, UINT control_qubit_index_count, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim); //void multi_qubit_control_single_qubit_dense_matrix_gate_single(const UINT* control_qubit_index_list, const UINT* control_value_list, UINT control_qubit_index_count, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim); //void multi_qubit_control_single_qubit_dense_matrix_gate_single_stack(const UINT* control_qubit_index_list, const UINT* control_value_list, UINT control_qubit_index_count, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim); //ITYPE* create_shift_mask_list(const UINT* array, UINT count, UINT target); void create_shift_mask_list_from_list_and_value_buf(const UINT* array, UINT count, UINT target, UINT* dst_array, ITYPE* dst_mask) { UINT size = count + 1; memcpy(dst_array, array, sizeof(UINT)*count); dst_array[count] = target; sort_ui(dst_array, size); for (UINT i = 0; i < size; ++i) { dst_mask[i] = (1UL << dst_array[i]) - 1; } } void multi_qubit_control_single_qubit_dense_matrix_gate(const UINT* control_qubit_index_list, const UINT* control_value_list, UINT control_qubit_index_count, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { //multi_qubit_control_single_qubit_dense_matrix_gate_old_single(control_qubit_index_list, control_value_list, control_qubit_index_count, target_qubit_index, matrix, state, dim); //multi_qubit_control_single_qubit_dense_matrix_gate_old_parallel(control_qubit_index_list, control_value_list, control_qubit_index_count, target_qubit_index, matrix, state, dim); //multi_qubit_control_single_qubit_dense_matrix_gate_single(control_qubit_index_list, control_value_list, control_qubit_index_count, target_qubit_index, matrix, state, dim); //multi_qubit_control_single_qubit_dense_matrix_gate_single_stack(control_qubit_index_list, control_value_list, control_qubit_index_count,target_qubit_index,matrix,state, dim); //multi_qubit_control_single_qubit_dense_matrix_gate_single_unroll(control_qubit_index_list, control_value_list, control_qubit_index_count,target_qubit_index,matrix,state, dim); //multi_qubit_control_single_qubit_dense_matrix_gate_single_simd(control_qubit_index_list, control_value_list, control_qubit_index_count,target_qubit_index,matrix,state, dim); //multi_qubit_control_single_qubit_dense_matrix_gate_parallel_simd(control_qubit_index_list, control_value_list, control_qubit_index_count,target_qubit_index,matrix,state, dim); if (control_qubit_index_count == 1) { single_qubit_control_single_qubit_dense_matrix_gate(control_qubit_index_list[0], control_value_list[0], target_qubit_index, matrix, state, dim); return; } #ifdef _USE_SIMD #ifdef _OPENMP UINT threshold = 13; if (dim < (((ITYPE)1) << threshold)) { multi_qubit_control_single_qubit_dense_matrix_gate_single_simd(control_qubit_index_list, control_value_list, control_qubit_index_count,target_qubit_index,matrix,state, dim); } else { multi_qubit_control_single_qubit_dense_matrix_gate_parallel_simd(control_qubit_index_list, control_value_list, control_qubit_index_count,target_qubit_index,matrix,state, dim); } #else multi_qubit_control_single_qubit_dense_matrix_gate_single_simd(control_qubit_index_list, control_value_list, control_qubit_index_count, target_qubit_index, matrix, state, dim); #endif #else #ifdef _OPENMP UINT threshold = 13; if (dim < (((ITYPE)1) << threshold)) { multi_qubit_control_single_qubit_dense_matrix_gate_single_unroll(control_qubit_index_list, control_value_list, control_qubit_index_count, target_qubit_index, matrix, state, dim); } else { multi_qubit_control_single_qubit_dense_matrix_gate_parallel_unroll(control_qubit_index_list, control_value_list, control_qubit_index_count, target_qubit_index, matrix, state, dim); } #else multi_qubit_control_single_qubit_dense_matrix_gate_single_unroll(control_qubit_index_list, control_value_list, control_qubit_index_count, target_qubit_index, matrix, state, dim); #endif #endif } void multi_qubit_control_single_qubit_dense_matrix_gate_single_unroll(const UINT* control_qubit_index_list, const UINT* control_value_list, UINT control_qubit_index_count, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { UINT sort_array[64]; ITYPE mask_array[64]; create_shift_mask_list_from_list_and_value_buf(control_qubit_index_list, control_qubit_index_count, target_qubit_index, sort_array, mask_array); const ITYPE target_mask = 1ULL << target_qubit_index; ITYPE control_mask = create_control_mask(control_qubit_index_list, control_value_list, control_qubit_index_count); const UINT insert_index_list_count = control_qubit_index_count + 1; const ITYPE loop_dim = dim >> insert_index_list_count; if (target_qubit_index == 0) { ITYPE state_index; for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & mask_array[cursor]) + ((basis_0 & (~mask_array[cursor])) << 1); } basis_0 += control_mask; // fetch values CTYPE cval0 = state[basis_0]; CTYPE cval1 = state[basis_0+1]; // set values state[basis_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_0+1] = matrix[2] * cval0 + matrix[3] * cval1; } } else if (sort_array[0] == 0) { ITYPE state_index; for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & mask_array[cursor]) + ((basis_0 & (~mask_array[cursor])) << 1); } basis_0 += control_mask; ITYPE basis_1 = basis_0 + target_mask; // fetch values CTYPE cval0 = state[basis_0]; CTYPE cval1 = state[basis_1]; // set values state[basis_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_1] = matrix[2] * cval0 + matrix[3] * cval1; } } else { ITYPE state_index; for (state_index = 0; state_index < loop_dim; state_index+=2) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & mask_array[cursor]) + ((basis_0 & (~mask_array[cursor])) << 1); } basis_0 += control_mask; ITYPE basis_1 = basis_0 + target_mask; // fetch values CTYPE cval0 = state[basis_0]; CTYPE cval1 = state[basis_1]; CTYPE cval2 = state[basis_0+1]; CTYPE cval3 = state[basis_1+1]; // set values state[basis_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_1] = matrix[2] * cval0 + matrix[3] * cval1; state[basis_0+1] = matrix[0] * cval2 + matrix[1] * cval3; state[basis_1+1] = matrix[2] * cval2 + matrix[3] * cval3; } } } #ifdef _OPENMP void multi_qubit_control_single_qubit_dense_matrix_gate_parallel_unroll(const UINT* control_qubit_index_list, const UINT* control_value_list, UINT control_qubit_index_count, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { UINT sort_array[64]; ITYPE mask_array[64]; create_shift_mask_list_from_list_and_value_buf(control_qubit_index_list, control_qubit_index_count, target_qubit_index, sort_array, mask_array); const ITYPE target_mask = 1ULL << target_qubit_index; ITYPE control_mask = create_control_mask(control_qubit_index_list, control_value_list, control_qubit_index_count); const UINT insert_index_list_count = control_qubit_index_count + 1; const ITYPE loop_dim = dim >> insert_index_list_count; if (target_qubit_index == 0) { ITYPE state_index; #pragma omp parallel for for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & mask_array[cursor]) + ((basis_0 & (~mask_array[cursor])) << 1); } basis_0 += control_mask; // fetch values CTYPE cval0 = state[basis_0]; CTYPE cval1 = state[basis_0 + 1]; // set values state[basis_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_0 + 1] = matrix[2] * cval0 + matrix[3] * cval1; } } else if (sort_array[0] == 0) { ITYPE state_index; #pragma omp parallel for for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & mask_array[cursor]) + ((basis_0 & (~mask_array[cursor])) << 1); } basis_0 += control_mask; ITYPE basis_1 = basis_0 + target_mask; // fetch values CTYPE cval0 = state[basis_0]; CTYPE cval1 = state[basis_1]; // set values state[basis_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_1] = matrix[2] * cval0 + matrix[3] * cval1; } } else { ITYPE state_index; #pragma omp parallel for for (state_index = 0; state_index < loop_dim; state_index += 2) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & mask_array[cursor]) + ((basis_0 & (~mask_array[cursor])) << 1); } basis_0 += control_mask; ITYPE basis_1 = basis_0 + target_mask; // fetch values CTYPE cval0 = state[basis_0]; CTYPE cval1 = state[basis_1]; CTYPE cval2 = state[basis_0 + 1]; CTYPE cval3 = state[basis_1 + 1]; // set values state[basis_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_1] = matrix[2] * cval0 + matrix[3] * cval1; state[basis_0 + 1] = matrix[0] * cval2 + matrix[1] * cval3; state[basis_1 + 1] = matrix[2] * cval2 + matrix[3] * cval3; } } } #endif #ifdef _USE_SIMD void multi_qubit_control_single_qubit_dense_matrix_gate_single_simd(const UINT* control_qubit_index_list, const UINT* control_value_list, UINT control_qubit_index_count, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { UINT sort_array[64]; ITYPE mask_array[64]; create_shift_mask_list_from_list_and_value_buf(control_qubit_index_list, control_qubit_index_count, target_qubit_index, sort_array, mask_array); const ITYPE target_mask = 1ULL << target_qubit_index; ITYPE control_mask = create_control_mask(control_qubit_index_list, control_value_list, control_qubit_index_count); const UINT insert_index_list_count = control_qubit_index_count + 1; const ITYPE loop_dim = dim >> insert_index_list_count; if (target_qubit_index == 0) { __m256d mv00 = _mm256_set_pd(-cimag(matrix[1]), creal(matrix[1]), -cimag(matrix[0]), creal(matrix[0])); __m256d mv01 = _mm256_set_pd(creal(matrix[1]), cimag(matrix[1]), creal(matrix[0]), cimag(matrix[0])); __m256d mv20 = _mm256_set_pd(-cimag(matrix[3]), creal(matrix[3]), -cimag(matrix[2]), creal(matrix[2])); __m256d mv21 = _mm256_set_pd(creal(matrix[3]), cimag(matrix[3]), creal(matrix[2]), cimag(matrix[2])); ITYPE state_index; for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & mask_array[cursor]) + ((basis_0 & (~mask_array[cursor])) << 1); } basis_0 += control_mask; double* ptr = (double*)(state + basis_0); __m256d data = _mm256_loadu_pd(ptr); __m256d data_u0 = _mm256_mul_pd(data, mv00); __m256d data_u1 = _mm256_mul_pd(data, mv01); __m256d data_u2 = _mm256_hadd_pd(data_u0, data_u1); data_u2 = _mm256_permute4x64_pd(data_u2, 216); // (3210) -> (3120) : 1*0 + 4*2 + 16*1 + 64*3 = 216 __m256d data_d0 = _mm256_mul_pd(data, mv20); __m256d data_d1 = _mm256_mul_pd(data, mv21); __m256d data_d2 = _mm256_hadd_pd(data_d0, data_d1); data_d2 = _mm256_permute4x64_pd(data_d2, 216); // (3210) -> (3120) : 1*0 + 4*2 + 16*1 + 64*3 = 216 __m256d data_r = _mm256_hadd_pd(data_u2, data_d2); data_r = _mm256_permute4x64_pd(data_r, 216); // (3210) -> (3120) : 1*0 + 4*2 + 16*1 + 64*3 = 216 _mm256_storeu_pd(ptr, data_r); } } else if (sort_array[0] == 0) { ITYPE state_index; for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & mask_array[cursor]) + ((basis_0 & (~mask_array[cursor])) << 1); } basis_0 += control_mask; ITYPE basis_1 = basis_0 + target_mask; // fetch values CTYPE cval0 = state[basis_0]; CTYPE cval1 = state[basis_1]; // set values state[basis_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_1] = matrix[2] * cval0 + matrix[3] * cval1; } } else { __m256d mv00 = _mm256_set_pd(-cimag(matrix[0]), creal(matrix[0]), -cimag(matrix[0]), creal(matrix[0])); __m256d mv01 = _mm256_set_pd(creal(matrix[0]), cimag(matrix[0]), creal(matrix[0]), cimag(matrix[0])); __m256d mv10 = _mm256_set_pd(-cimag(matrix[1]), creal(matrix[1]), -cimag(matrix[1]), creal(matrix[1])); __m256d mv11 = _mm256_set_pd(creal(matrix[1]), cimag(matrix[1]), creal(matrix[1]), cimag(matrix[1])); __m256d mv20 = _mm256_set_pd(-cimag(matrix[2]), creal(matrix[2]), -cimag(matrix[2]), creal(matrix[2])); __m256d mv21 = _mm256_set_pd(creal(matrix[2]), cimag(matrix[2]), creal(matrix[2]), cimag(matrix[2])); __m256d mv30 = _mm256_set_pd(-cimag(matrix[3]), creal(matrix[3]), -cimag(matrix[3]), creal(matrix[3])); __m256d mv31 = _mm256_set_pd(creal(matrix[3]), cimag(matrix[3]), creal(matrix[3]), cimag(matrix[3])); ITYPE state_index; for (state_index = 0; state_index < loop_dim; state_index += 2) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & mask_array[cursor]) + ((basis_0 & (~mask_array[cursor])) << 1); } basis_0 += control_mask; ITYPE basis_1 = basis_0 + target_mask; double* ptr0 = (double*)(state + basis_0); double* ptr1 = (double*)(state + basis_1); __m256d data0 = _mm256_loadu_pd(ptr0); __m256d data1 = _mm256_loadu_pd(ptr1); __m256d data_u2 = _mm256_mul_pd(data0, mv00); __m256d data_u3 = _mm256_mul_pd(data1, mv10); __m256d data_u4 = _mm256_mul_pd(data0, mv01); __m256d data_u5 = _mm256_mul_pd(data1, mv11); __m256d data_u6 = _mm256_hadd_pd(data_u2, data_u4); __m256d data_u7 = _mm256_hadd_pd(data_u3, data_u5); __m256d data_d2 = _mm256_mul_pd(data0, mv20); __m256d data_d3 = _mm256_mul_pd(data1, mv30); __m256d data_d4 = _mm256_mul_pd(data0, mv21); __m256d data_d5 = _mm256_mul_pd(data1, mv31); __m256d data_d6 = _mm256_hadd_pd(data_d2, data_d4); __m256d data_d7 = _mm256_hadd_pd(data_d3, data_d5); __m256d data_r0 = _mm256_add_pd(data_u6, data_u7); __m256d data_r1 = _mm256_add_pd(data_d6, data_d7); _mm256_storeu_pd(ptr0, data_r0); _mm256_storeu_pd(ptr1, data_r1); } } } #ifdef _OPENMP void multi_qubit_control_single_qubit_dense_matrix_gate_parallel_simd(const UINT* control_qubit_index_list, const UINT* control_value_list, UINT control_qubit_index_count, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { UINT sort_array[64]; ITYPE mask_array[64]; create_shift_mask_list_from_list_and_value_buf(control_qubit_index_list, control_qubit_index_count, target_qubit_index, sort_array, mask_array); const ITYPE target_mask = 1ULL << target_qubit_index; ITYPE control_mask = create_control_mask(control_qubit_index_list, control_value_list, control_qubit_index_count); const UINT insert_index_list_count = control_qubit_index_count + 1; const ITYPE loop_dim = dim >> insert_index_list_count; if (target_qubit_index == 0) { __m256d mv00 = _mm256_set_pd(-cimag(matrix[1]), creal(matrix[1]), -cimag(matrix[0]), creal(matrix[0])); __m256d mv01 = _mm256_set_pd(creal(matrix[1]), cimag(matrix[1]), creal(matrix[0]), cimag(matrix[0])); __m256d mv20 = _mm256_set_pd(-cimag(matrix[3]), creal(matrix[3]), -cimag(matrix[2]), creal(matrix[2])); __m256d mv21 = _mm256_set_pd(creal(matrix[3]), cimag(matrix[3]), creal(matrix[2]), cimag(matrix[2])); ITYPE state_index; #pragma omp parallel for for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & mask_array[cursor]) + ((basis_0 & (~mask_array[cursor])) << 1); } basis_0 += control_mask; double* ptr = (double*)(state + basis_0); __m256d data = _mm256_loadu_pd(ptr); __m256d data_u0 = _mm256_mul_pd(data, mv00); __m256d data_u1 = _mm256_mul_pd(data, mv01); __m256d data_u2 = _mm256_hadd_pd(data_u0, data_u1); data_u2 = _mm256_permute4x64_pd(data_u2, 216); // (3210) -> (3120) : 1*0 + 4*2 + 16*1 + 64*3 = 216 __m256d data_d0 = _mm256_mul_pd(data, mv20); __m256d data_d1 = _mm256_mul_pd(data, mv21); __m256d data_d2 = _mm256_hadd_pd(data_d0, data_d1); data_d2 = _mm256_permute4x64_pd(data_d2, 216); // (3210) -> (3120) : 1*0 + 4*2 + 16*1 + 64*3 = 216 __m256d data_r = _mm256_hadd_pd(data_u2, data_d2); data_r = _mm256_permute4x64_pd(data_r, 216); // (3210) -> (3120) : 1*0 + 4*2 + 16*1 + 64*3 = 216 _mm256_storeu_pd(ptr, data_r); } } else if (sort_array[0] == 0) { ITYPE state_index; #pragma omp parallel for for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & mask_array[cursor]) + ((basis_0 & (~mask_array[cursor])) << 1); } basis_0 += control_mask; ITYPE basis_1 = basis_0 + target_mask; // fetch values CTYPE cval0 = state[basis_0]; CTYPE cval1 = state[basis_1]; // set values state[basis_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_1] = matrix[2] * cval0 + matrix[3] * cval1; } } else { __m256d mv00 = _mm256_set_pd(-cimag(matrix[0]), creal(matrix[0]), -cimag(matrix[0]), creal(matrix[0])); __m256d mv01 = _mm256_set_pd(creal(matrix[0]), cimag(matrix[0]), creal(matrix[0]), cimag(matrix[0])); __m256d mv10 = _mm256_set_pd(-cimag(matrix[1]), creal(matrix[1]), -cimag(matrix[1]), creal(matrix[1])); __m256d mv11 = _mm256_set_pd(creal(matrix[1]), cimag(matrix[1]), creal(matrix[1]), cimag(matrix[1])); __m256d mv20 = _mm256_set_pd(-cimag(matrix[2]), creal(matrix[2]), -cimag(matrix[2]), creal(matrix[2])); __m256d mv21 = _mm256_set_pd(creal(matrix[2]), cimag(matrix[2]), creal(matrix[2]), cimag(matrix[2])); __m256d mv30 = _mm256_set_pd(-cimag(matrix[3]), creal(matrix[3]), -cimag(matrix[3]), creal(matrix[3])); __m256d mv31 = _mm256_set_pd(creal(matrix[3]), cimag(matrix[3]), creal(matrix[3]), cimag(matrix[3])); ITYPE state_index; #pragma omp parallel for for (state_index = 0; state_index < loop_dim; state_index += 2) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & mask_array[cursor]) + ((basis_0 & (~mask_array[cursor])) << 1); } basis_0 += control_mask; ITYPE basis_1 = basis_0 + target_mask; double* ptr0 = (double*)(state + basis_0); double* ptr1 = (double*)(state + basis_1); __m256d data0 = _mm256_loadu_pd(ptr0); __m256d data1 = _mm256_loadu_pd(ptr1); __m256d data_u2 = _mm256_mul_pd(data0, mv00); __m256d data_u3 = _mm256_mul_pd(data1, mv10); __m256d data_u4 = _mm256_mul_pd(data0, mv01); __m256d data_u5 = _mm256_mul_pd(data1, mv11); __m256d data_u6 = _mm256_hadd_pd(data_u2, data_u4); __m256d data_u7 = _mm256_hadd_pd(data_u3, data_u5); __m256d data_d2 = _mm256_mul_pd(data0, mv20); __m256d data_d3 = _mm256_mul_pd(data1, mv30); __m256d data_d4 = _mm256_mul_pd(data0, mv21); __m256d data_d5 = _mm256_mul_pd(data1, mv31); __m256d data_d6 = _mm256_hadd_pd(data_d2, data_d4); __m256d data_d7 = _mm256_hadd_pd(data_d3, data_d5); __m256d data_r0 = _mm256_add_pd(data_u6, data_u7); __m256d data_r1 = _mm256_add_pd(data_d6, data_d7); _mm256_storeu_pd(ptr0, data_r0); _mm256_storeu_pd(ptr1, data_r1); } } } #endif #endif /* void multi_qubit_control_single_qubit_dense_matrix_gate_old_single(const UINT* control_qubit_index_list, const UINT* control_value_list, UINT control_qubit_index_count, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { // insert index list const UINT insert_index_list_count = control_qubit_index_count + 1; UINT* insert_index_list = create_sorted_ui_list_value(control_qubit_index_list, control_qubit_index_count, target_qubit_index); // target mask const ITYPE target_mask = 1ULL << target_qubit_index; // control mask ITYPE control_mask = create_control_mask(control_qubit_index_list, control_value_list, control_qubit_index_count); // loop variables const ITYPE loop_dim = dim >> insert_index_list_count; ITYPE state_index; for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_c_t0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_c_t0 = insert_zero_to_basis_index(basis_c_t0, 1ULL << insert_index_list[cursor], insert_index_list[cursor]); } // flip controls basis_c_t0 ^= control_mask; // gather target ITYPE basis_c_t1 = basis_c_t0 ^ target_mask; // fetch values CTYPE cval_c_t0 = state[basis_c_t0]; CTYPE cval_c_t1 = state[basis_c_t1]; // set values state[basis_c_t0] = matrix[0] * cval_c_t0 + matrix[1] * cval_c_t1; state[basis_c_t1] = matrix[2] * cval_c_t0 + matrix[3] * cval_c_t1; } free(insert_index_list); } #ifdef _OPENMP void multi_qubit_control_single_qubit_dense_matrix_gate_old_parallel(const UINT* control_qubit_index_list, const UINT* control_value_list, UINT control_qubit_index_count, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { // insert index list const UINT insert_index_list_count = control_qubit_index_count + 1; UINT* insert_index_list = create_sorted_ui_list_value(control_qubit_index_list, control_qubit_index_count, target_qubit_index); // target mask const ITYPE target_mask = 1ULL << target_qubit_index; // control mask ITYPE control_mask = create_control_mask(control_qubit_index_list, control_value_list, control_qubit_index_count); // loop variables const ITYPE loop_dim = dim >> insert_index_list_count; ITYPE state_index; #pragma omp parallel for for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_c_t0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_c_t0 = insert_zero_to_basis_index(basis_c_t0, 1ULL << insert_index_list[cursor], insert_index_list[cursor]); } // flip controls basis_c_t0 ^= control_mask; // gather target ITYPE basis_c_t1 = basis_c_t0 ^ target_mask; // fetch values CTYPE cval_c_t0 = state[basis_c_t0]; CTYPE cval_c_t1 = state[basis_c_t1]; // set values state[basis_c_t0] = matrix[0] * cval_c_t0 + matrix[1] * cval_c_t1; state[basis_c_t1] = matrix[2] * cval_c_t0 + matrix[3] * cval_c_t1; } free(insert_index_list); } #endif ITYPE* create_shift_mask_list(const UINT* array, UINT count, UINT target) { UINT size = count + 1; UINT* new_array = (UINT*)malloc(sizeof(UINT)*size); memcpy(new_array, array, sizeof(UINT)*count); new_array[count] = target; sort_ui(new_array, size); ITYPE* mask_array = (ITYPE*)malloc(sizeof(ITYPE)*size); for (UINT i = 0; i < size; ++i) { mask_array[i] = (1UL << new_array[i]) - 1; } free(new_array); return mask_array; } void multi_qubit_control_single_qubit_dense_matrix_gate_single(const UINT* control_qubit_index_list, const UINT* control_value_list, UINT control_qubit_index_count, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { ITYPE* shift_masks = create_shift_mask_list(control_qubit_index_list, control_qubit_index_count, target_qubit_index); const ITYPE target_mask = 1ULL << target_qubit_index; ITYPE control_mask = create_control_mask(control_qubit_index_list, control_value_list, control_qubit_index_count); const UINT insert_index_list_count = control_qubit_index_count + 1; const ITYPE loop_dim = dim >> insert_index_list_count; ITYPE state_index; for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & shift_masks[cursor]) + ((basis_0 & (~shift_masks[cursor])) << 1); } basis_0 += control_mask; ITYPE basis_1 = basis_0 ^ target_mask; // fetch values CTYPE cval0 = state[basis_0]; CTYPE cval1 = state[basis_1]; // set values state[basis_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_1] = matrix[2] * cval0 + matrix[3] * cval1; } free(shift_masks); } void multi_qubit_control_single_qubit_dense_matrix_gate_single_stack(const UINT* control_qubit_index_list, const UINT* control_value_list, UINT control_qubit_index_count, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { UINT sort_array[64]; ITYPE mask_array[64]; create_shift_mask_list_from_list_and_value_buf(control_qubit_index_list, control_qubit_index_count, target_qubit_index, sort_array, mask_array); const ITYPE target_mask = 1ULL << target_qubit_index; ITYPE control_mask = create_control_mask(control_qubit_index_list, control_value_list, control_qubit_index_count); const UINT insert_index_list_count = control_qubit_index_count + 1; const ITYPE loop_dim = dim >> insert_index_list_count; ITYPE state_index; for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_0 = state_index; for (UINT cursor = 0; cursor < insert_index_list_count; ++cursor) { basis_0 = (basis_0 & mask_array[cursor]) + ((basis_0 & (~mask_array[cursor])) << 1); } basis_0 += control_mask; ITYPE basis_1 = basis_0 + target_mask; // fetch values CTYPE cval0 = state[basis_0]; CTYPE cval1 = state[basis_1]; // set values state[basis_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_1] = matrix[2] * cval0 + matrix[3] * cval1; } } */
FiberSurface.h
/// \ingroup base /// \class ttk::FiberSurface /// \author Julien Tierny <julien.tierny@lip6.fr> /// \date October 2015. /// /// \brief TTK processing package that computes fiber surfaces. /// /// Fiber surfaces are defined as the pre-images of curves drawn in the range /// of bivariate volumetric functions, typically on top of the continuous /// scatterplot. Fiber surfaces generalize the segmentation features of /// isosurfaces to bivariate data. /// This TTK processing package implements an exact, parallel and fast /// algorithm for fiber surface computation on (explicit or implicit) /// tetrahedral meshes. /// /// \b Related \b publication \n /// "Fast and Exact Fiber Surface Extraction for Tetrahedral Meshes" \n /// Pavol Klacansky, Julien Tierny, Hamish Carr, Zhao Geng \n /// IEEE Transactions on Visualization and Computer Graphics, 2016. /// /// \param dataTypeU Data type of the input first component field (char, float, /// etc.) /// \param dataTypeV Data type of the input second component field (char, float, /// etc.) /// /// \sa ttkFiberSurface.cpp %for a usage example. #ifndef _FIBERSURFACE_H #define _FIBERSURFACE_H // standard includes #ifdef __APPLE__ # include <algorithm> #else # ifdef _WIN32 # include <algorithm> # else # ifdef __clang__ # include <algorithm> # include <numeric> # else # include <parallel/algorithm> # endif # endif #endif #include <queue> // base code includes #include <Geometry.h> #ifdef TTK_ENABLE_FIBER_SURFACE_WITH_RANGE_OCTREE #include <RangeDrivenOctree.h> #endif #include <Triangulation.h> #include <Wrapper.h> namespace ttk{ class FiberSurface : public Debug{ public: class Vertex{ public: bool isBasePoint_, isIntersectionPoint_; SimplexId localId_, globalId_, polygonEdgeId_; // TODO also encode the vertex ids of the triangle of the input mesh // where this point has been computed (for constrained triangulation) std::pair<SimplexId, SimplexId> meshEdge_; double p_[3], t_; std::pair<double, double> uv_; }; class Triangle{ public: SimplexId vertexIds_[3], tetId_, caseId_, polygonEdgeId_; }; FiberSurface(); ~FiberSurface(); #ifdef TTK_ENABLE_FIBER_SURFACE_WITH_RANGE_OCTREE template <class dataTypeU, class dataTypeV> inline int buildOctree(); #endif template <class dataTypeU, class dataTypeV> inline int computeContour( const std::pair<double, double> &rangePoint0, const std::pair<double, double> &rangePoint1, const std::vector<SimplexId> &seedTetList, const SimplexId &polygonEdgeId = 0) const; template <class dataTypeU, class dataTypeV> inline int computeContour( const std::vector<std::pair<std::pair<double, double>, std::pair<double, double> > > &edgeList, const std::vector<SimplexId> &seedTetList, const std::vector<SimplexId> *edgeIdList = NULL) const; template <class dataTypeU, class dataTypeV> inline int computeSurface( const std::pair<double, double> &rangePoint0, const std::pair<double, double> &rangePoint1, const SimplexId &polygonEdgeId = 0) const; template <class dataTypeU, class dataTypeV> inline int computeSurface(); #ifdef TTK_ENABLE_FIBER_SURFACE_WITH_RANGE_OCTREE template <class dataTypeU, class dataTypeV> inline int computeSurfaceWithOctree( const std::pair<double, double> &rangePoint0, const std::pair<double, double> &rangePoint1, const SimplexId &polygonEdgeId) const; #endif template <class dataTypeU, class dataTypeV> inline int finalize( const bool &mergeDuplicatedVertices = false, const bool &removeSmallEdges = false, const bool &edgeFlips = false, const bool &intersectionRemesh = false); #ifdef TTK_ENABLE_FIBER_SURFACE_WITH_RANGE_OCTREE inline int flushOctree(){ return octree_.flush(); } #endif template <class dataTypeU, class dataTypeV> inline int processTetrahedron(const SimplexId &tetId, const std::pair<double, double> &rangePoint0, const std::pair<double, double> &rangePoint1, const SimplexId &polygonEdgeId = 0) const; inline int setGlobalVertexList(std::vector<Vertex> *globalList){ globalVertexList_ = globalList; return 0; } inline int setInputField(const void *uField, const void *vField){ uField_ = uField; vField_ = vField; return 0; } inline int setPointMerging(const bool &onOff){ pointSnapping_ = onOff; return 0; } inline int setPointMergingThreshold(const double &threshold){ pointSnappingThreshold_ = threshold; return 0; } inline int setPointNumber(const SimplexId &number){ pointNumber_ = number; return 0; } inline int setPointSet(const float *pointSet){ pointSet_ = pointSet; return 0; } inline int setPolygon(const std::vector<std::pair<std::pair<double, double>, std::pair<double, double> > > *polygon){ polygon_ = polygon; return 0; } inline int setPolygonEdgeNumber(const SimplexId &polygonEdgeNumber){ polygonEdgeNumber_ = polygonEdgeNumber; polygonEdgeVertexLists_.resize(polygonEdgeNumber, NULL); polygonEdgeTriangleLists_.resize(polygonEdgeNumber, NULL); return 0; } inline int setTetList(const SimplexId *tetList){ tetList_ = tetList; return 0; } inline int setTetNeighbors(const std::vector<std::vector<SimplexId> > *tetNeighbors){ tetNeighbors_ = tetNeighbors; return 0; } inline int setTetNumber(const SimplexId &tetNumber){ tetNumber_ = tetNumber; return 0; } inline int setTriangleList(const SimplexId &polygonEdgeId, std::vector<Triangle> *triangleList){ #ifndef TTK_ENABLE_KAMIKAZE if((polygonEdgeId >= 0) &&(polygonEdgeId < (SimplexId) polygonEdgeTriangleLists_.size())) #endif polygonEdgeTriangleLists_[polygonEdgeId] = triangleList; return 0; } inline int setupTriangulation(Triangulation *triangulation){ triangulation_ = triangulation; // for breadth-first search traversals if(triangulation_){ triangulation_->preprocessCellNeighbors(); } return 0; } inline int setVertexList(const SimplexId &polygonEdgeId, std::vector<Vertex> *vertexList){ #ifndef TTK_ENABLE_KAMIKAZE if((polygonEdgeId >= 0) &&(polygonEdgeId < (SimplexId) polygonEdgeVertexLists_.size())) #endif polygonEdgeVertexLists_[polygonEdgeId] = vertexList; return 0; } protected: typedef struct _intersectionTriangle{ SimplexId caseId_; // use negative values for new triangles SimplexId triangleId_; SimplexId polygonEdgeId_; // use negative values for new vertices SimplexId vertexIds_[3]; std::pair<double, double> uv_[3]; double t_[3]; double p_[3][3]; std::pair<double, double> intersection_; }IntersectionTriangle; template <class dataTypeU, class dataTypeV> inline int computeBaseTriangle( const SimplexId &tetId, const SimplexId &localEdgeId0, const double &t0, const double &u0, const double &v0, const SimplexId &localEdgeId1, const double &t1, const double &u1, const double &v1, const SimplexId &localEdgeId2, const double &t2, const double &u2, const double &v2, std::vector<std::vector<double> > &basePoints, std::vector<std::pair<double, double> > &basePointProections, std::vector<double> &basePointParameterization, std::vector<std::pair<SimplexId, SimplexId> > &baseEdges) const; template <class dataTypeU, class dataTYpeV> inline int computeCase0(const SimplexId &polygonEdgeId, const SimplexId &tetId, const SimplexId &localEdgeId0, const double &t0, const double &u0, const double &v0, const SimplexId &localEdgeId1, const double &t1, const double &u1, const double &v1, const SimplexId &localEdgeId2, const double &t2, const double &u2, const double &v2) const; template <class dataTypeU, class dataTYpeV> inline int computeCase1(const SimplexId &polygonEdgeId, const SimplexId &tetId, const SimplexId &localEdgeId0, const double &t0, const double &u0, const double &v0, const SimplexId &localEdgeId1, const double &t1, const double &u1, const double &v1, const SimplexId &localEdgeId2, const double &t2, const double &u2, const double &v2) const; template <class dataTypeU, class dataTYpeV> inline int computeCase2(const SimplexId &polygonEdgeId, const SimplexId &tetId, const SimplexId &localEdgeId0, const double &t0, const double &u0, const double &v0, const SimplexId &localEdgeId1, const double &t1, const double &u1, const double &v1, const SimplexId &localEdgeId2, const double &t2, const double &u2, const double &v2) const; template <class dataTypeU, class dataTYpeV> inline int computeCase3(const SimplexId &polygonEdgeId, const SimplexId &tetId, const SimplexId &localEdgeId0, const double &t0, const double &u0, const double &v0, const SimplexId &localEdgeId1, const double &t1, const double &u1, const double &v1, const SimplexId &localEdgeId2, const double &t2, const double &u2, const double &v2) const; template <class dataTypeU, class dataTYpeV> inline int computeCase4(const SimplexId &polygonEdgeId, const SimplexId &tetId, const SimplexId &localEdgeId0, const double &t0, const double &u0, const double &v0, const SimplexId &localEdgeId1, const double &t1, const double &u1, const double &v1, const SimplexId &localEdgeId2, const double &t2, const double &u2, const double &v2) const; int computeTriangleFiber(const SimplexId &tetId, const SimplexId &triangleId, const std::pair<double, double> &intersection, const std::vector<std::vector<IntersectionTriangle> > &tetIntersections, std::vector<double> &pA, std::vector<double> &pB, SimplexId &pivotVertexId, bool &edgeFiber) const; int computeTriangleIntersection( const SimplexId &tetId, const SimplexId &triangleId0, const SimplexId &triangleId1, const SimplexId &polygonEdgeId0, const SimplexId &polygonEdgeId1, const std::pair<double, double> &intersection, SimplexId &newVertexNumber, SimplexId &newTriangleNumber, std::vector<std::vector<IntersectionTriangle> > &tetIntersections, std::vector<std::vector<Vertex> > &tetNewVertices) const; int computeTriangleIntersection( const SimplexId &tetId, const SimplexId &triangleId, const SimplexId &polygonEdgeId, const std::pair<double, double> &intersection, const std::vector<double> &pA, const std::vector<double> &pB, const SimplexId &pivotVertexId, SimplexId &newVertexNumber, SimplexId &newTriangleNumber, std::vector<std::vector<IntersectionTriangle> > &tetIntersections, std::vector<std::vector<Vertex> > &tetNewVertices) const; int createNewIntersectionTriangle( const SimplexId &tetId, const SimplexId &triangleId, const SimplexId &vertexId0, const SimplexId &vertexId1, const SimplexId &vertexId2, const std::vector<std::vector<Vertex> > &tetNewVertices, SimplexId &newTriangleNumber, std::vector<std::vector<IntersectionTriangle> > &tetIntersections, const std::pair<double, double> *intersection = NULL) const; int flipEdges() const; int flipEdges(std::vector<std::pair<SimplexId, SimplexId> > &triangles) const; int getNumberOfCommonVertices(const SimplexId &tetId, const SimplexId &triangleId0, const SimplexId &triangleId1, const std::vector<std::vector<IntersectionTriangle> > &tetIntersections) const; int getTriangleRangeExtremities(const SimplexId &tetId, const SimplexId &triangleId, const std::vector<std::vector<IntersectionTriangle> > &tetIntersections, std::pair<double, double> &extremity0, std::pair<double, double> &extremity1) const; bool hasDuplicatedVertices( const double *p0, const double *p1, const double *p2) const; int interpolateBasePoints( const std::vector<double> &p0, const std::pair<double, double> &uv0, const double &t0, const std::vector<double> &p1, const std::pair<double, double> &uv1, const double &t1, const double &t, Vertex &v) const; bool isEdgeAngleCollapsible( const SimplexId &source, const SimplexId &destination, const SimplexId &pivotVertexId, const std::vector<std::pair<SimplexId, SimplexId> > &starNeighbors) const; bool isEdgeFlippable( const SimplexId &edgeVertexId0, const SimplexId &edgeVertexId1, const SimplexId &otherVertexId0, const SimplexId &otherVertexId1) const; inline bool isIntersectionTriangleColinear( const SimplexId &tetId, const SimplexId &triangleId, const std::vector<std::vector<IntersectionTriangle> > &tetIntersections, const std::vector<std::vector<Vertex> > &tetNewVertices, const SimplexId &vertexId0, const SimplexId &vertexId1, const SimplexId &vertexId2) const{ std::vector<std::vector<double> > points(3); for(int i = 0; i < 3; i++){ SimplexId vertexId = vertexId0; if(i == 1) vertexId = vertexId1; if(i == 2) vertexId = vertexId2; points[i].resize(3); if(vertexId >= 0){ for(int j = 0; j < 3; j++){ points[i][j] = tetIntersections[tetId][triangleId].p_[vertexId][j]; } } else{ for(int j = 0; j < 3; j++){ points[i][j] = tetNewVertices[tetId][(-vertexId) - 1].p_[j]; } } } return Geometry::isTriangleColinear( points[0].data(), points[1].data(), points[2].data()); } int mergeEdges(const double &distanceThreshold) const; int mergeVertices(const double &distanceThreshold) const; template <class dataTypeU, class dataTypeV> inline int remeshIntersections() const; int snapToBasePoint(const std::vector<std::vector<double> > &basePoints, const std::vector<std::pair<double, double> > &uv, const std::vector<double> &t, Vertex &v) const; int snapVertexBarycentrics(const double &distanceThreshold) const; int snapVertexBarycentrics(const SimplexId &tetId, const std::vector<std::pair<SimplexId, SimplexId> > &triangles, const double &distanceThreshold) const; bool pointSnapping_; SimplexId pointNumber_, tetNumber_, polygonEdgeNumber_; const void *uField_, *vField_; const float *pointSet_; const SimplexId *tetList_; const std::vector<std::vector<SimplexId> > *tetNeighbors_; SimplexId edgeImplicitEncoding_[12]; double edgeCollapseThreshold_, pointSnappingThreshold_; const std::vector<std::pair<std::pair<double, double>, std::pair<double, double> > > *polygon_; std::vector<Vertex> *globalVertexList_; std::vector<std::vector<Vertex> *> polygonEdgeVertexLists_; std::vector<std::vector<Triangle> *> polygonEdgeTriangleLists_; Triangulation *triangulation_; #ifdef TTK_ENABLE_FIBER_SURFACE_WITH_RANGE_OCTREE RangeDrivenOctree octree_; #endif }; } #ifdef TTK_ENABLE_FIBER_SURFACE_WITH_RANGE_OCTREE template <class dataTypeU, class dataTypeV> inline int ttk::FiberSurface::buildOctree(){ if(!uField_) return -1; if(!vField_) return -2; if(octree_.empty()){ octree_.setDebugLevel(debugLevel_); octree_.setThreadNumber(threadNumber_); if(triangulation_){ octree_.setTriangulation(triangulation_); } else{ octree_.setCellList(tetList_); octree_.setCellNumber(tetNumber_); octree_.setPointList(pointSet_); octree_.setVertexNumber(pointNumber_); } octree_.setRange(uField_, vField_); octree_.build<dataTypeU, dataTypeV>(); } return 0; } #endif template <class dataTypeU, class dataTypeV> inline int ttk::FiberSurface::computeBaseTriangle(const SimplexId &tetId, const SimplexId &localEdgeId0, const double &t0, const double &u0, const double &v0, const SimplexId &localEdgeId1, const double &t1, const double &u1, const double &v1, const SimplexId &localEdgeId2, const double &t2, const double &u2, const double &v2, std::vector<std::vector<double> > &basePoints, std::vector<std::pair<double, double> > &basePointProjections, std::vector<double> &basePointParameterization, std::vector<std::pair<SimplexId, SimplexId> > &baseEdges) const{ basePoints.resize(3); basePointProjections.resize(3); basePointParameterization.resize(3); baseEdges.resize(3); for(int i = 0; i < 3; i++){ SimplexId vertexId0 = 0, vertexId1 = 0; switch(i){ case 0: if(!triangulation_){ vertexId0 = tetList_[5*tetId + 1 + edgeImplicitEncoding_[2*localEdgeId0]]; vertexId1 = tetList_[5*tetId + 1 + edgeImplicitEncoding_[2*localEdgeId0 + 1]]; } else{ triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*localEdgeId0], vertexId0); triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*localEdgeId0 + 1], vertexId1); } basePointProjections[i].first = u0; basePointProjections[i].second = v0; basePointParameterization[i] = t0; break; case 1: if(!triangulation_){ vertexId0 = tetList_[5*tetId + 1 + edgeImplicitEncoding_[2*localEdgeId1]]; vertexId1 = tetList_[5*tetId + 1 + edgeImplicitEncoding_[2*localEdgeId1 + 1]]; } else{ triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*localEdgeId1], vertexId0); triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*localEdgeId1 + 1], vertexId1); } basePointProjections[i].first = u1; basePointProjections[i].second = v1; basePointParameterization[i] = t1; break; case 2: if(!triangulation_){ vertexId0 = tetList_[5*tetId + 1 + edgeImplicitEncoding_[2*localEdgeId2]]; vertexId1 = tetList_[5*tetId + 1 + edgeImplicitEncoding_[2*localEdgeId2 + 1]]; } else{ triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*localEdgeId2], vertexId0); triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*localEdgeId2 + 1], vertexId1); } basePointProjections[i].first = u2; basePointProjections[i].second = v2; basePointParameterization[i] = t2; break; } std::vector<double> baryCentrics; std::vector<double> p0(2), p1(2), p(2); p0[0] = ((dataTypeU *) uField_)[vertexId0]; p0[1] = ((dataTypeV *) vField_)[vertexId0]; p1[0] = ((dataTypeU *) uField_)[vertexId1]; p1[1] = ((dataTypeV *) vField_)[vertexId1]; p[0] = basePointProjections[i].first; p[1] = basePointProjections[i].second; Geometry::computeBarycentricCoordinates( p0.data(), p1.data(), p.data(), baryCentrics, 2); basePoints[i].resize(3); float pA[3], pB[3]; if(triangulation_){ triangulation_->getVertexPoint(vertexId0, pA[0], pA[1], pA[2]); triangulation_->getVertexPoint(vertexId1, pB[0], pB[1], pB[2]); } for(int j = 0; j < 3; j++){ double c0, c1; if(!triangulation_){ c0 = pointSet_[3*vertexId0 + j]; c1 = pointSet_[3*vertexId1 + j]; } else{ c0 = pA[j]; c1 = pB[j]; } basePoints[i][j] = baryCentrics[0]*c0 + baryCentrics[1]*c1; } if(vertexId0 < vertexId1){ baseEdges[i] = std::pair<SimplexId, SimplexId>(vertexId0, vertexId1); } else{ baseEdges[i] = std::pair<SimplexId, SimplexId>(vertexId1, vertexId0); } } return 0; } template<class dataTypeU, class dataTypeV> inline int ttk::FiberSurface::computeCase0( const SimplexId &polygonEdgeId, const SimplexId &tetId, const SimplexId &localEdgeId0, const double &t0, const double &u0, const double &v0, const SimplexId &localEdgeId1, const double &t1, const double &u1, const double &v1, const SimplexId &localEdgeId2, const double &t2, const double &u2, const double &v2) const{ // that one's easy, make just one triangle SimplexId vertexId = (*polygonEdgeVertexLists_[polygonEdgeId]).size(); // alloc 1 more triangle (*polygonEdgeTriangleLists_[polygonEdgeId]).resize( (*polygonEdgeTriangleLists_[polygonEdgeId]).size() + 1); (*polygonEdgeTriangleLists_[polygonEdgeId]).back().tetId_ = tetId; (*polygonEdgeTriangleLists_[polygonEdgeId]).back().caseId_ = 0; (*polygonEdgeTriangleLists_[polygonEdgeId]).back().polygonEdgeId_ = polygonEdgeId; (*polygonEdgeTriangleLists_[polygonEdgeId]).back().vertexIds_[0] = vertexId; (*polygonEdgeTriangleLists_[polygonEdgeId]).back().vertexIds_[1] = vertexId + 1; (*polygonEdgeTriangleLists_[polygonEdgeId]).back().vertexIds_[2] = vertexId + 2; // alloc 3 more vertices (*polygonEdgeVertexLists_[polygonEdgeId]).resize(vertexId + 3); for(int i = 0; i < 3; i++){ (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].isBasePoint_ = true; (*polygonEdgeVertexLists_[polygonEdgeId])[ vertexId + i].isIntersectionPoint_ = false; } // get the vertex coordinates for(int i = 0; i < 3; i++){ SimplexId vertexId0 = 0, vertexId1 = 0; switch(i){ case 0: if(!triangulation_){ vertexId0 = tetList_[5*tetId + 1 + edgeImplicitEncoding_[2*localEdgeId0]]; vertexId1 = tetList_[5*tetId + 1 + edgeImplicitEncoding_[2*localEdgeId0 + 1]]; } else{ triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*localEdgeId0], vertexId0); triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*localEdgeId0 + 1], vertexId1); } (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].uv_.first = u0; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].uv_.second = v0; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].t_ = t0; break; case 1: if(!triangulation_){ vertexId0 = tetList_[5*tetId + 1 + edgeImplicitEncoding_[2*localEdgeId1]]; vertexId1 = tetList_[5*tetId + 1 + edgeImplicitEncoding_[2*localEdgeId1 + 1]]; } else{ triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*localEdgeId1], vertexId0); triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*localEdgeId1 + 1], vertexId1); } (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].uv_.first = u1; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].uv_.second = v1; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].t_ = t1; break; case 2: if(!triangulation_){ vertexId0 = tetList_[5*tetId + 1 + edgeImplicitEncoding_[2*localEdgeId2]]; vertexId1 = tetList_[5*tetId + 1 + edgeImplicitEncoding_[2*localEdgeId2 + 1]]; } else{ triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*localEdgeId2], vertexId0); triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*localEdgeId2 + 1], vertexId1); } (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].uv_.first = u2; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].uv_.second = v2; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].t_ = t2; break; } std::vector<double> baryCentrics; std::vector<double> p0(2), p1(2), p(2); p0[0] = ((dataTypeU *) uField_)[vertexId0]; p0[1] = ((dataTypeV *) vField_)[vertexId0]; p1[0] = ((dataTypeU *) uField_)[vertexId1]; p1[1] = ((dataTypeV *) vField_)[vertexId1]; p[0] = (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].uv_.first; p[1] = (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].uv_.second; Geometry::computeBarycentricCoordinates( p0.data(), p1.data(), p.data(), baryCentrics, 2); float pA[3], pB[3]; if(triangulation_){ triangulation_->getVertexPoint(vertexId0, pA[0], pA[1], pA[2]); triangulation_->getVertexPoint(vertexId1, pB[0], pB[1], pB[2]); } for(int j = 0; j < 3; j++){ double c0, c1; if(!triangulation_){ c0 = pointSet_[3*vertexId0 + j]; c1 = pointSet_[3*vertexId1 + j]; } else{ c0 = pA[j]; c1 = pB[j]; } (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].p_[j] = baryCentrics[0]*c0 + baryCentrics[1]*c1; } if(vertexId0 < vertexId1) (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].meshEdge_ = std::pair<SimplexId, SimplexId>(vertexId0, vertexId1); else (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].meshEdge_ = std::pair<SimplexId, SimplexId>(vertexId1, vertexId0); } // return the number of created vertices return 3; } template <class dataTypeU, class dataTypeV> inline int ttk::FiberSurface::computeCase1( const SimplexId &polygonEdgeId, const SimplexId &tetId, const SimplexId &localEdgeId0, const double &t0, const double &u0, const double &v0, const SimplexId &localEdgeId1, const double &t1, const double &u1, const double &v1, const SimplexId &localEdgeId2, const double &t2, const double &u2, const double &v2) const{ SimplexId vertexId = (*polygonEdgeVertexLists_[polygonEdgeId]).size(); // alloc 5 more vertices (*polygonEdgeVertexLists_[polygonEdgeId]).resize(vertexId + 5); for(int i = 0; i < 5; i++){ (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].isBasePoint_ = true; (*polygonEdgeVertexLists_[polygonEdgeId])[ vertexId + i].isIntersectionPoint_ = false; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].meshEdge_ = std::pair<SimplexId, SimplexId>(-1, -1); } // alloc 3 more triangles SimplexId triangleId = (*polygonEdgeTriangleLists_[polygonEdgeId]).size(); (*polygonEdgeTriangleLists_[polygonEdgeId]).resize(triangleId + 3); for(int i = 0; i < 3; i++){ (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId + i].tetId_ = tetId; (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId + i].caseId_ = 1; (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId + i].polygonEdgeId_ = polygonEdgeId; switch(i){ case 0: (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[0] = vertexId; (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId + i].vertexIds_[1] = vertexId + 1; (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[2] = vertexId + 2; break; case 1: (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[0] = vertexId + 1; (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[1] = vertexId + 2; (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[2] = vertexId + 3; break; case 2: (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[0] = vertexId + 2; (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[1] = vertexId + 3; (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[2] = vertexId + 4; break; } } // compute the base triangle vertices like in case 1 std::vector<std::vector<double> > basePoints(3); std::vector<std::pair<double, double> > basePointProjections(3); std::vector<double> basePointParameterization(3); std::vector<std::pair<SimplexId, SimplexId> > baseEdges(3); computeBaseTriangle<dataTypeU, dataTypeV>(tetId, localEdgeId0, t0, u0, v0, localEdgeId1, t1, u1, v1, localEdgeId2, t2, u2, v2, basePoints, basePointProjections, basePointParameterization, baseEdges); // find the pivot vertex for this case SimplexId pivotVertexId = -1; if((t0 >= 0)&&(t0 <= 1)){ pivotVertexId = 0; } if((t1 >= 0)&&(t1 <= 1)){ pivotVertexId = 1; } if((t2 >= 0)&&(t2 <= 1)){ pivotVertexId = 2; } // now get the vertex coordinates for(int i = 0; i < 5; i++){ SimplexId vertexId0, vertexId1; double t; if(!i){ // just take the pivot vertex for(int j = 0; j < 3; j++){ (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId].p_[j] = basePoints[pivotVertexId][j]; } (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId].t_ = basePointParameterization[pivotVertexId]; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId].uv_ = basePointProjections[pivotVertexId]; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId].meshEdge_ = baseEdges[pivotVertexId]; } else{ switch(i){ case 1: // interpolation between pivotVertexId and (pivotVertexId-1)%3 // if pivot is positive: interpolate at 1 // if not interpolate at 0 vertexId0 = pivotVertexId; vertexId1 = (pivotVertexId + 2)%3; if(basePointParameterization[(pivotVertexId + 2)%3] > 1){ t = 1; } else{ t = 0; } break; case 2: // interpolation between pivotVertexId and (pivotVertexId+1)%3 // if pivot is positive: interpolate at 1 // if not interpolate at 0 vertexId0 = pivotVertexId; vertexId1 = (pivotVertexId + 1)%3; if(basePointParameterization[(pivotVertexId + 1)%3] > 1){ t = 1; } else{ t = 0; } break; case 3: vertexId0 = (pivotVertexId + 2)%3; vertexId1 = (pivotVertexId + 1)%3; if(basePointParameterization[(pivotVertexId + 2)%3] < 0){ t = 0; } else{ t = 1; } break; case 4: vertexId0 = (pivotVertexId + 2)%3; vertexId1 = (pivotVertexId + 1)%3; if(basePointParameterization[(pivotVertexId + 2)%3] < 0){ t = 1; } else{ t = 0; } break; } (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].t_ = t; interpolateBasePoints( basePoints[vertexId0], basePointProjections[vertexId0], basePointParameterization[vertexId0], basePoints[vertexId1], basePointProjections[vertexId1], basePointParameterization[vertexId1], t, (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i]); // snapToBasePoint( // basePoints, basePointProjections, basePointParameterization, // (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i]); } } // return the number of created vertices return 5; } template <class dataTypeU, class dataTypeV> inline int ttk::FiberSurface::computeCase2( const SimplexId &polygonEdgeId, const SimplexId &tetId, const SimplexId &localEdgeId0, const double &t0, const double &u0, const double &v0, const SimplexId &localEdgeId1, const double &t1, const double &u1, const double &v1, const SimplexId &localEdgeId2, const double &t2, const double &u2, const double &v2) const{ SimplexId vertexId = (*polygonEdgeVertexLists_[polygonEdgeId]).size(); // alloc 4 more vertices (*polygonEdgeVertexLists_[polygonEdgeId]).resize(vertexId + 4); for(int i = 0; i < 4; i++){ (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].isBasePoint_ = true; (*polygonEdgeVertexLists_[polygonEdgeId])[ vertexId + i].isIntersectionPoint_ = false; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].meshEdge_ = std::pair<SimplexId, SimplexId>(-1, -1); } // alloc 2 more triangles SimplexId triangleId = (*polygonEdgeTriangleLists_[polygonEdgeId]).size(); (*polygonEdgeTriangleLists_[polygonEdgeId]).resize(triangleId + 2); for(int i = 0; i < 2; i++){ (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId + i].tetId_ = tetId; (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId + i].caseId_ = 2; (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId + i].polygonEdgeId_ = polygonEdgeId; if(!i){ (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[0] = vertexId; (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[1] = vertexId + 1; (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[2] = vertexId + 2; } else{ (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[0] = vertexId + 1; (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[1] = vertexId + 3; (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[2] = vertexId + 2; } } // compute the base triangle vertices like in case 1 std::vector<std::vector<double> > basePoints(3); std::vector<std::pair<double, double> > basePointProjections(3); std::vector<double> basePointParameterization(3); std::vector<std::pair<SimplexId, SimplexId> > baseEdges(3); computeBaseTriangle<dataTypeU, dataTypeV>(tetId, localEdgeId0, t0, u0, v0, localEdgeId1, t1, u1, v1, localEdgeId2, t2, u2, v2, basePoints, basePointProjections, basePointParameterization, baseEdges); // find the pivot for this case bool isPivotPositive = false; SimplexId pivotVertexId = -1; if(((t0 < 0)&&((t1 < 0)||(t2 < 0))) ||((t1 < 0)&&((t0 < 0)||(t2 < 0))) ||((t2 < 0)&&((t1 < 0)||(t0 < 0)))){ isPivotPositive = true; } if(isPivotPositive){ if(t0 >= 1) pivotVertexId = 0; } else{ if(t0 <= 0) pivotVertexId = 0; } if(isPivotPositive){ if(t1 >= 1) pivotVertexId = 1; } else{ if(t1 <= 0) pivotVertexId = 1; } if(isPivotPositive){ if(t2 >= 1) pivotVertexId = 2; } else{ if(t2 <= 0) pivotVertexId = 2; } // now get the vertex coordinates for(int i = 0; i < 4; i++){ SimplexId vertexId0, vertexId1; double t; switch(i){ case 0: // interpolation between pivotVertexId and (pivotVertexId-1)%3 // if pivot is positive: interpolate at 1 // if not interpolate at 0 vertexId0 = pivotVertexId; vertexId1 = (pivotVertexId + 2)%3; if(isPivotPositive) t = 1; else t = 0; break; case 1: // interpolation between pivotVertexId and (pivotVertexId+1)%3 // if pivot is positive: interpolate at 1 // if not interpolate at 0 vertexId0 = pivotVertexId; vertexId1 = (pivotVertexId + 1)%3; if(isPivotPositive) t = 1; else t = 0; break; case 2: // interpolation between pivotVertexId and (pivotVertexId-1)%3 // if pivot is positive: interpolate at 0 // if not interpolate at 1 vertexId0 = pivotVertexId; vertexId1 = (pivotVertexId + 2)%3; if(isPivotPositive) t = 0; else t = 1; break; case 3: // interpolation between pivotVertexId and (pivotVertexId+1)%3 // if pivot is positive: interpolate at 0 // if not interpolate at 1 vertexId0 = pivotVertexId; vertexId1 = (pivotVertexId + 1)%3; if(isPivotPositive) t = 0; else t = 1; break; } (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].t_ = t; interpolateBasePoints( basePoints[vertexId0], basePointProjections[vertexId0], basePointParameterization[vertexId0], basePoints[vertexId1], basePointProjections[vertexId1], basePointParameterization[vertexId1], t, (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i]); // snapToBasePoint( // basePoints, basePointProjections, basePointParameterization, // (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i]); } // return the number of created vertices return 4; } template <class dataTypeU, class dataTypeV> inline int ttk::FiberSurface::computeCase3( const SimplexId &polygonEdgeId, const SimplexId &tetId, const SimplexId &localEdgeId0, const double &t0, const double &u0, const double &v0, const SimplexId &localEdgeId1, const double &t1, const double &u1, const double &v1, const SimplexId &localEdgeId2, const double &t2, const double &u2, const double &v2) const{ SimplexId vertexId = (*polygonEdgeVertexLists_[polygonEdgeId]).size(); // alloc 3 more vertices (*polygonEdgeVertexLists_[polygonEdgeId]).resize(vertexId + 3); for(int i = 0; i < 3; i++){ (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].isBasePoint_ = true; (*polygonEdgeVertexLists_[polygonEdgeId])[ vertexId + i].isIntersectionPoint_ = false; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].meshEdge_ = std::pair<SimplexId, SimplexId>(-1, -1); } // alloc 1 more triangle SimplexId triangleId = (*polygonEdgeTriangleLists_[polygonEdgeId]).size(); (*polygonEdgeTriangleLists_[polygonEdgeId]).resize(triangleId + 1); (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId].tetId_ = tetId; (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId].caseId_ = 3; (*polygonEdgeTriangleLists_[polygonEdgeId]).back().polygonEdgeId_ = polygonEdgeId; (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId].vertexIds_[0] = vertexId; (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId].vertexIds_[1] = vertexId + 1; (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId].vertexIds_[2] = vertexId + 2; // compute the base triangle vertices like in case 1 std::vector<std::vector<double> > basePoints(3); std::vector<std::pair<double, double> > basePointProjections(3); std::vector<double> basePointParameterization(3); std::vector<std::pair<SimplexId, SimplexId> > baseEdges(3); computeBaseTriangle<dataTypeU, dataTypeV>(tetId, localEdgeId0, t0, u0, v0, localEdgeId1, t1, u1, v1, localEdgeId2, t2, u2, v2, basePoints, basePointProjections, basePointParameterization, baseEdges); // now find the pivot bool isPivotPositive = false; SimplexId pivotVertexId = -1; if((t0 <= 1)&&(t0 >= 0)){ pivotVertexId = 0; } else{ if(t0 < 0) isPivotPositive = true; } if((t1 <= 1)&&(t1 >= 0)){ pivotVertexId = 1; } else{ if(t1 < 0) isPivotPositive = true; } if((t2 <= 1)&&(t2 >= 0)){ pivotVertexId = 2; } else{ if(t2 < 0) isPivotPositive = true; } // now get the vertex coordinates for(int i = 0; i < 3; i++){ SimplexId vertexId0, vertexId1; double t; if(!i){ // special case of the pivot vertex for(int j = 0; j < 3; j++){ (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId].p_[j] = basePoints[pivotVertexId][j]; } (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId].t_ = basePointParameterization[pivotVertexId]; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId].uv_ = basePointProjections[pivotVertexId]; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId].meshEdge_ = baseEdges[pivotVertexId]; } else{ if(i == 1){ // interpolation between pivotVertexId and pivotVertexId+1 // if pivot is positive, interpolate at value 0 // else interpolate at value 1 vertexId0 = pivotVertexId; vertexId1 = (pivotVertexId + 1)%3; if(isPivotPositive) t = 0; else t = 1; } if(i == 2){ // interpolation between pivotVertexId and pivotVertexId-1 // if pivot is positive, interpolate at value 0 // else interpolate at value 1 vertexId0 = pivotVertexId; vertexId1 = (pivotVertexId + 2)%3; if(isPivotPositive) t = 0; else t = 1; } (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].t_ = t; interpolateBasePoints( basePoints[vertexId0], basePointProjections[vertexId0], basePointParameterization[vertexId0], basePoints[vertexId1], basePointProjections[vertexId1], basePointParameterization[vertexId1], t, (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i]); // snapToBasePoint( // basePoints, basePointProjections, basePointParameterization, // (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i]); } } // return the number of created vertices return 3; } template <class dataTypeU, class dataTypeV> inline int ttk::FiberSurface::computeCase4( const SimplexId &polygonEdgeId, const SimplexId &tetId, const SimplexId &localEdgeId0, const double &t0, const double &u0, const double &v0, const SimplexId &localEdgeId1, const double &t1, const double &u1, const double &v1, const SimplexId &localEdgeId2, const double &t2, const double &u2, const double &v2) const{ SimplexId vertexId = (*polygonEdgeVertexLists_[polygonEdgeId]).size(); // alloc 4 more vertices (*polygonEdgeVertexLists_[polygonEdgeId]).resize(vertexId + 4); for(int i = 0; i < 4; i++){ (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].isBasePoint_ = true; (*polygonEdgeVertexLists_[polygonEdgeId])[ vertexId + i].isIntersectionPoint_ = false; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].meshEdge_ = std::pair<SimplexId, SimplexId>(-1, -1); } // alloc 2 more triangles SimplexId triangleId = (*polygonEdgeTriangleLists_[polygonEdgeId]).size(); (*polygonEdgeTriangleLists_[polygonEdgeId]).resize(triangleId + 2); for(int i = 0; i < 2; i++){ (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId + i].tetId_ = tetId; (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId + i].caseId_ = 4; (*polygonEdgeTriangleLists_[polygonEdgeId])[triangleId + i].polygonEdgeId_ = polygonEdgeId; if(!i){ (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[0] = vertexId; (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[1] = vertexId + 1; (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[2] = vertexId + 2; } else{ (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[0] = vertexId + 1; (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[1] = vertexId + 3; (*polygonEdgeTriangleLists_[polygonEdgeId])[ triangleId + i].vertexIds_[2] = vertexId + 2; } } // compute the base triangle vertices like in case 1 std::vector<std::vector<double> > basePoints(3); std::vector<std::pair<double, double> > basePointProjections(3); std::vector<double> basePointParameterization(3); std::vector<std::pair<SimplexId, SimplexId> > baseEdges(3); computeBaseTriangle<dataTypeU, dataTypeV>(tetId, localEdgeId0, t0, u0, v0, localEdgeId1, t1, u1, v1, localEdgeId2, t2, u2, v2, basePoints, basePointProjections, basePointParameterization, baseEdges); // find the pivot vertex for this case bool isPivotPositive = false; SimplexId pivotVertexId = -1; if(t0 > 1){ pivotVertexId = 0; isPivotPositive = true; } else if(t0 < 0){ pivotVertexId = 0; isPivotPositive = false; } if(t1 > 1){ pivotVertexId = 1; isPivotPositive = true; } else if(t1 < 0){ pivotVertexId = 1; isPivotPositive = false; } if(t2 > 1){ pivotVertexId = 2; isPivotPositive = true; } else if(t2 < 0){ pivotVertexId = 2; isPivotPositive = false; } // now get the vertex coordinates depending on the case for(int i = 0; i < 4; i++){ SimplexId vertexId0, vertexId1; double t; if(i < 2){ if(!i){ // interpolation between pivotVertexId and (pivotVertexId-1)%3 // if pivot is positive: interpolate at 1 // if not interpolate at 0 vertexId0 = pivotVertexId; vertexId1 = (pivotVertexId + 2)%3; if(isPivotPositive) t = 1; else t = 0; } else{ // interpolation between pivotVertexId and (pivotVertexId+1)%3 // if pivot is positive: interpolate at 1 // if not interpolate at 0 vertexId0 = pivotVertexId; vertexId1 = (pivotVertexId + 1)%3; if(isPivotPositive) t = 1; else t = 0; } (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].t_ = t; interpolateBasePoints( basePoints[vertexId0], basePointProjections[vertexId0], basePointParameterization[vertexId0], basePoints[vertexId1], basePointProjections[vertexId1], basePointParameterization[vertexId1], t, (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i]); // snapToBasePoint( // basePoints, basePointProjections, basePointParameterization, // (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i]); } else{ if(i == 2){ // take (pivotVertexId-1)%3 for(int j = 0; j < 3; j++){ (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].p_[j] = basePoints[(pivotVertexId + 2)%3][j]; } (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].t_ = basePointParameterization[(pivotVertexId + 2)%3]; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].uv_ = basePointProjections[(pivotVertexId + 2)%3]; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].meshEdge_ = baseEdges[(pivotVertexId + 2)%3]; } else{ // take (pivtoVertexId+1)%3 for(int j = 0; j < 3; j++){ (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].p_[j] = basePoints[(pivotVertexId + 1)%3][j]; } (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].t_ = basePointParameterization[(pivotVertexId + 1)%3]; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].uv_ = basePointProjections[(pivotVertexId + 1)%3]; (*polygonEdgeVertexLists_[polygonEdgeId])[vertexId + i].meshEdge_ = baseEdges[(pivotVertexId + 1)%3]; } } } // return the number of created vertices return 4; } template <class dataTypeU, class dataTypeV> inline int ttk::FiberSurface::computeContour( const std::pair<double, double> &rangePoint0, const std::pair<double, double> &rangePoint1, const std::vector<SimplexId> &seedTetList, const SimplexId &polygonEdgeId) const{ #ifndef TTK_ENABLE_KAMIKAZE if(!uField_) return -4; if(!vField_) return -5; if(!triangulation_) return -6; if(!polygonEdgeNumber_) return -7; if(!globalVertexList_) return -8; #endif std::vector<bool> visitedTets(triangulation_->getNumberOfCells(), false); std::queue<SimplexId> tetQueue; // init the queue for(SimplexId i = 0; i < (SimplexId) seedTetList.size(); i++){ tetQueue.push(seedTetList[i]); } SimplexId createdVertices = 0; do{ SimplexId tetId = tetQueue.front(); tetQueue.pop(); if(!visitedTets[tetId]){ createdVertices = processTetrahedron<dataTypeU, dataTypeV>( tetId, rangePoint0, rangePoint1, polygonEdgeId); if(createdVertices){ // only propagate if we created a triangle SimplexId tetNeighborNumber = triangulation_->getCellNeighborNumber(tetId); for(SimplexId i = 0; i < tetNeighborNumber; i++){ SimplexId neighborId = -1; triangulation_->getCellNeighbor(tetId, i, neighborId); if(!visitedTets[neighborId]) tetQueue.push(neighborId); } } visitedTets[tetId] = true; } }while(tetQueue.size()); return 0; } template <class dataTypeU, class dataTypeV> int ttk::FiberSurface::computeContour( const std::vector<std::pair<std::pair<double, double>, std::pair<double, double> > > &edgeList, const std::vector<SimplexId> &seedTetList, const std::vector<SimplexId> *edgeIdList) const{ #ifndef TTK_ENABLE_KAMIKAZE if(!tetNeighbors_) return -1; if(!tetNumber_) return -2; if(!tetList_) return -3; if(!uField_) return -4; if(!vField_) return -5; if(!pointSet_) return -6; if(!polygonEdgeNumber_) return -7; if(!globalVertexList_) return -8; #endif std::vector<bool> visitedTets(tetNumber_, false); std::queue<SimplexId> tetQueue; // init the queue for(SimplexId i = 0; i < (SimplexId) seedTetList.size(); i++){ tetQueue.push(seedTetList[i]); } SimplexId createdVertices = 0; do{ SimplexId tetId = tetQueue.front(); tetQueue.pop(); if(!visitedTets[tetId]){ std::vector<std::vector<SimplexId> > threadedTetQueue(edgeList.size()); #ifdef TTK_ENABLE_OPENMP #pragma omp parallel for num_threads(threadNumber_) #endif for(SimplexId i = 0; i < (SimplexId) edgeList.size(); i++){ SimplexId polygonEdgeId = 0; if(edgeIdList){ polygonEdgeId = (*edgeIdList)[i]; } createdVertices = processTetrahedron<dataTypeU, dataTypeV>( tetId, edgeList[i].first, edgeList[i].second, polygonEdgeId); if(createdVertices){ // only propagate if we created a triangle for(SimplexId j = 0; j < (SimplexId) (*tetNeighbors_)[tetId].size(); j++){ if(!visitedTets[(*tetNeighbors_)[tetId][j]]){ threadedTetQueue[i].push_back((*tetNeighbors_)[tetId][j]); } } } } visitedTets[tetId] = true; for(SimplexId i = 0; i < (SimplexId) threadedTetQueue.size(); i++){ for(SimplexId j = 0; j < (SimplexId) threadedTetQueue[i].size(); j++){ tetQueue.push(threadedTetQueue[i][j]); } } } }while(tetQueue.size()); return 0; } template <class dataTypeU, class dataTypeV> inline int ttk::FiberSurface::computeSurface( const std::pair<double, double> &rangePoint0, const std::pair<double, double> &rangePoint1, const SimplexId &polygonEdgeId) const { #ifndef TTK_ENABLE_KAMIKAZE if((!tetNumber_)&&(!triangulation_)) return -1; if((!tetList_)&&(!triangulation_)) return -2; if(!uField_) return -3; if(!vField_) return -4; if((!pointSet_)&&(!triangulation_)) return -5; if(!polygonEdgeNumber_) return -6; if(!globalVertexList_) return -7; #endif SimplexId tetNumber = tetNumber_; if(triangulation_){ tetNumber = triangulation_->getNumberOfCells(); } #ifdef TTK_ENABLE_OPENMP #pragma omp parallel for num_threads(threadNumber_) #endif for(SimplexId i = 0; i < tetNumber; i++){ processTetrahedron<dataTypeU, dataTypeV>( i, rangePoint0, rangePoint1, polygonEdgeId); } return 0; } template <class dataTypeU, class dataTypeV> inline int ttk::FiberSurface::computeSurface(){ #ifndef TTK_ENABLE_KAMIKAZE if((!tetNumber_)&&(!triangulation_)) return -1; if((!tetList_)&&(!triangulation_)) return -2; if(!uField_) return -3; if(!vField_) return -4; if((!pointSet_)&&(!triangulation_)) return -5; if(!polygon_) return -6; if(polygonEdgeNumber_ != (SimplexId) polygon_->size()) return -7; if(!globalVertexList_) return -8; #endif Timer t; #ifdef TTK_ENABLE_FIBER_SURFACE_WITH_RANGE_OCTREE if(!octree_.empty()){ #ifdef TTK_ENABLE_OPENMP #pragma omp parallel for num_threads(threadNumber_) #endif for(SimplexId i = 0; i < polygonEdgeNumber_; i++){ computeSurfaceWithOctree<dataTypeU, dataTypeV>( (*polygon_)[i].first, (*polygon_)[i].second, i); } } else{ // regular extraction (the octree has not been computed) #ifdef TTK_ENABLE_OPENMP #pragma omp parallel for num_threads(threadNumber_) #endif for(SimplexId i = 0; i < polygonEdgeNumber_; i++){ computeSurface<dataTypeU, dataTypeV>( (*polygon_)[i].first, (*polygon_)[i].second, i); } } #else #ifdef TTK_ENABLE_OPENMP #pragma omp parallel for num_threads(threadNumber_) #endif for(SimplexId i = 0; i < polygonEdgeNumber_; i++){ computeSurface<dataTypeU, dataTypeV>( (*polygon_)[i].first, (*polygon_)[i].second, i); } #endif finalize<dataTypeU, dataTypeV>(pointSnapping_, false, false, false); { std::stringstream msg; msg << "[FiberSurface] FiberSurface extracted in " << t.getElapsedTime() << " s. (" << globalVertexList_->size() << " vertices, " << threadNumber_ << " thread(s))" << std::endl; dMsg(std::cout, msg.str(), timeMsg); } return 0; } #ifdef TTK_ENABLE_FIBER_SURFACE_WITH_RANGE_OCTREE template <class dataTypeU, class dataTypeV> inline int ttk::FiberSurface::computeSurfaceWithOctree( const std::pair<double, double> &rangePoint0, const std::pair<double, double> &rangePoint1, const SimplexId &polygonEdgeId) const { #ifndef TTK_ENABLE_KAMIKAZE if((!tetNumber_)&&(!triangulation_)) return -1; if((!tetList_)&&(!triangulation_)) return -2; if(!uField_) return -3; if(!vField_) return -4; if((!pointSet_)&&(!triangulation_)) return -5; if(!polygonEdgeNumber_) return -6; if(!globalVertexList_) return -7; #endif std::vector<SimplexId> tetList; octree_.rangeSegmentQuery(rangePoint0, rangePoint1, tetList); #ifdef TTK_ENABLE_OPENMP #pragma omp parallel for num_threads(threadNumber_) #endif for(SimplexId i = 0; i < (SimplexId) tetList.size(); i++){ processTetrahedron<dataTypeU, dataTypeV>( tetList[i], rangePoint0, rangePoint1, polygonEdgeId); } return 0; } #endif template <class dataTypeU, class dataTypeV> int ttk::FiberSurface::finalize( const bool &mergeDuplicatedVertices, const bool &removeSmallEdges, const bool &edgeFlips, const bool &intersectionRemesh){ // make only one vertex list SimplexId fiberSurfaceVertexNumber = 0; for(SimplexId i = 0; i < (SimplexId) polygonEdgeVertexLists_.size(); i++){ fiberSurfaceVertexNumber += (*polygonEdgeVertexLists_[i]).size(); } (*globalVertexList_).resize(fiberSurfaceVertexNumber); fiberSurfaceVertexNumber = 0; for(SimplexId i = 0; i < (SimplexId) polygonEdgeVertexLists_.size(); i++){ for(SimplexId j = 0; j < (SimplexId) polygonEdgeVertexLists_[i]->size(); j++){ (*polygonEdgeVertexLists_[i])[j].polygonEdgeId_ = i; (*polygonEdgeVertexLists_[i])[j].localId_ = j; (*polygonEdgeVertexLists_[i])[j].globalId_ = fiberSurfaceVertexNumber; (*globalVertexList_)[fiberSurfaceVertexNumber] = (*polygonEdgeVertexLists_[i])[j]; fiberSurfaceVertexNumber++; } } for(SimplexId i = 0; i < (SimplexId) polygonEdgeTriangleLists_.size(); i++){ for(SimplexId j = 0; j < (SimplexId) polygonEdgeTriangleLists_[i]->size(); j++){ for(int k = 0; k < 3; k++){ (*polygonEdgeTriangleLists_[i])[j].vertexIds_[k] = (*polygonEdgeVertexLists_[i])[ (*polygonEdgeTriangleLists_[i])[j].vertexIds_[k]].globalId_; } } } // NOTE: // 1) in a first step, make everything work in a POST process. // this is what really matters for tet gen. // 2) probably come back and apply in a pre-process (more degenerate // intersection cases). if(intersectionRemesh){ remeshIntersections<dataTypeU, dataTypeV>(); } if((mergeDuplicatedVertices)||(removeSmallEdges)){ // we need to have a complex to perform the edge collapses mergeVertices(pointSnappingThreshold_); } if(edgeFlips) flipEdges(); if(removeSmallEdges) mergeEdges(edgeCollapseThreshold_); // now we can release the memory for the threaded vertices for(SimplexId i = 0; i < (SimplexId) polygonEdgeVertexLists_.size(); i++){ polygonEdgeVertexLists_[i]->clear(); } return 0; } template <class dataTypeU, class dataTypeV> inline int ttk::FiberSurface::processTetrahedron(const SimplexId &tetId, const std::pair<double, double> &rangePoint0, const std::pair<double, double> &rangePoint1, const SimplexId &polygonEdgeId) const{ double rangeEdge[2]; rangeEdge[0] = rangePoint0.first - rangePoint1.first; rangeEdge[1] = rangePoint0.second - rangePoint1.second; double rangeNormal[2]; rangeNormal[0] = -rangeEdge[1]; rangeNormal[1] = rangeEdge[0]; // 1. compute the distance to the range line carrying the saddleEdge SimplexId upperNumber = 0; SimplexId lowerNumber = 0; SimplexId equalVertexLocalId = -1; double d[4]; for(int i = 0; i < 4; i++){ SimplexId vertexId = 0; if(!triangulation_){ vertexId = tetList_[5*tetId + 1 + i]; } else{ triangulation_->getCellVertex(tetId, i, vertexId); } double projectedVertex[2]; projectedVertex[0] = ((dataTypeU *) uField_)[vertexId]; projectedVertex[1] = ((dataTypeV *) vField_)[vertexId]; double vertexRangeEdge[2]; vertexRangeEdge[0] = projectedVertex[0] - rangePoint0.first; vertexRangeEdge[1] = projectedVertex[1] - rangePoint0.second; d[i] = vertexRangeEdge[0]*rangeNormal[0] + vertexRangeEdge[1]*rangeNormal[1]; if(fabs(d[i]) < pow(10, -DBL_DIG)) d[i] = 0; if(d[i] > 0) upperNumber++; if(d[i] < 0) lowerNumber++; if(d[i] == 0){ equalVertexLocalId = i; } } // 2. compute the base triangle(s) if(!((upperNumber == 0)||(lowerNumber == 0))){ // the fiber surface is passing through this tetrahedron. std::vector<bool> lonelyVertex(4, false); std::vector<SimplexId> triangleEdgeNumbers(2, 0); std::vector<std::vector<SimplexId> > triangleEdges(2); triangleEdges[0].resize(3, -1); triangleEdges[1].resize(3, -1); // implicit edge encoding // 0: O-1 // 1: 0-2 // 2: 0-3 // 3: 3-1 [order!] // 4: 2-1 [order!] // 5: 2-3 SimplexId edgeCounter = 0; for(int i = 0; i < 4; i++){ SimplexId jStart = i + 1; SimplexId jEnd = 4; SimplexId jStep = 1; if(i == 1){ // special ordering here // (to facilitate the creation of valid base triangles) // any two consecutive edges shall share a vertex jStart = 3; jEnd = i; jStep = -1; } for(SimplexId j = jStart; j != jEnd; j += jStep){ if(((d[i] > 0)&&(d[j] < 0))||((d[i] < 0)&&(d[j] > 0))){ // the edge is crossed by a base triangle if(triangleEdgeNumbers[0] == 3){ triangleEdges[1][triangleEdgeNumbers[1]] = edgeCounter; triangleEdgeNumbers[1]++; } else{ triangleEdges[0][triangleEdgeNumbers[0]] = edgeCounter; triangleEdgeNumbers[0]++; } } if((d[i] == 0)&&(d[j] == 0)){ // special case of a seed tet containing the jacobi edge. // the entire edge is on the fiber surface. // let's put this edge twice. // NOTE: in such a case, we're producing only one triangle. // so we just need to add that to the first triangle. triangleEdges[0][triangleEdgeNumbers[0]] = edgeCounter; triangleEdgeNumbers[0]++; triangleEdges[0][triangleEdgeNumbers[0]] = edgeCounter; triangleEdgeNumbers[0]++; } edgeCounter++; } } // post-process in the case of a second base triangle if(triangleEdges[1][0] != -1){ if(triangleEdges[1][1] == -1){ // we need to consider the edges of the first triangle which share // a vertex with the second triangle's edge. // given the ordering, the following edge pairs are forbidden: // (opposite edges of the tetrahedron) // 0/5 // 1/3 // 2/4 SimplexId forbiddenEdge = -1; switch(triangleEdges[1][0]){ case 0: forbiddenEdge = 5; break; case 1: forbiddenEdge = 3; break; case 2: forbiddenEdge = 4; break; case 3: forbiddenEdge = 1; break; case 4: forbiddenEdge = 2; break; case 5: forbiddenEdge = 0; break; } for(SimplexId i = 0; i < (SimplexId) triangleEdges[0].size(); i++){ if(triangleEdges[0][i] != forbiddenEdge){ if(triangleEdges[1][1] != -1){ triangleEdges[1][2] = triangleEdges[0][i]; break; } else{ triangleEdges[1][1] = triangleEdges[0][i]; } } } } } // post-process in case of exactly one vertex on the jacobi edge for(int i = 0; i < 2; i++){ if(triangleEdges[i][0] != -1){ // the jacobi vertex has to be the last one if(triangleEdges[i][2] == -1){ // add whatever edge connected to equalVertexLocalId switch(equalVertexLocalId){ case 0: case 1: triangleEdges[i][2] = 0; break; case 2: case 3: triangleEdges[i][2] = 5; break; } } } } // 3. crop the resulting triangles to the saddleEdge // for each edge recorded previously, get the u,v coordinates of the // intersection point. // take its barycentric coordinates on the saddle edge. // see if it lies in it (in between 0 and 1) // figure 7 of the paper double d0, d1; std::pair<double, double> uv0, uv1; std::vector<std::pair<double, double> > uv(3); std::vector<double> t(3); SimplexId createdVertices = 0; for(int i = 0; i < 2; i++){ if(triangleEdges[i][0] != -1){ // this is a valid triangle, let's go ahead. SimplexId lowerVertexNumber = 0; SimplexId upperVertexNumber = 0; SimplexId greyVertexNumber = 0; // iterate over the edges and compute the edge intersection (range) for(SimplexId j = 0; j < (SimplexId) triangleEdges[i].size(); j++){ SimplexId vertexId0 = 0, vertexId1 = 0; if(triangulation_){ triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*triangleEdges[i][j]], vertexId0); triangulation_->getCellVertex(tetId, edgeImplicitEncoding_[2*triangleEdges[i][j] + 1], vertexId1); } else{ vertexId0 = tetList_[ 5*tetId + 1 + edgeImplicitEncoding_[2*triangleEdges[i][j]]]; vertexId1 = tetList_[ 5*tetId + 1 + edgeImplicitEncoding_[2*triangleEdges[i][j] + 1]]; } if((j < (SimplexId) triangleEdges[i].size() - 1) &&(triangleEdges[i][j] == triangleEdges[i][j + 1])){ // special case of a jacobi edge uv[j].first = ((dataTypeU *) uField_)[vertexId0]; uv[j].second = ((dataTypeV *) vField_)[vertexId0]; uv[j + 1].first = ((dataTypeU *) uField_)[vertexId1]; uv[j + 1].second = ((dataTypeV *) vField_)[vertexId1]; } else if((!j)|| ((j)&&(triangleEdges[i][j] != triangleEdges[i][j - 1]))){ // regular intersection case d0 = d[edgeImplicitEncoding_[2*triangleEdges[i][j]]]; uv0.first = ((dataTypeU *) uField_)[vertexId0]; uv0.second = ((dataTypeV *) vField_)[vertexId0]; d1 = d[edgeImplicitEncoding_[2*triangleEdges[i][j] + 1]]; uv1.first = ((dataTypeU *) uField_)[vertexId1]; uv1.second = ((dataTypeV *) vField_)[vertexId1]; uv[j].first = uv0.first + (d0/(d0 - d1))*(uv1.first - uv0.first); uv[j].second = uv0.second + (d0/(d0 - d1))*(uv1.second - uv0.second); } // now determine the line parameterization of this intersection // point on the saddle edge if(fabs(rangePoint1.first - rangePoint0.first) > fabs(rangePoint1.second - rangePoint0.second)){ t[j] = (uv[j].first - rangePoint0.first) / (rangePoint1.first - rangePoint0.first); } else{ t[j] = (uv[j].second - rangePoint0.second) / (rangePoint1.second - rangePoint0.second); } if((t[j] <= 1)&&(t[j] >= 0)) greyVertexNumber++; else if(t[j] < 0) lowerVertexNumber++; else upperVertexNumber++; } // at this point, we know the uv coordinates (and the edge param) // of each vertex of the base triangle. // we can proceed with the cropping // 4. triangulate the result if(greyVertexNumber == 3){ createdVertices += computeCase0<dataTypeU, dataTypeV>( polygonEdgeId, tetId, triangleEdges[i][0], t[0], uv[0].first, uv[0].second, triangleEdges[i][1], t[1], uv[1].first, uv[1].second, triangleEdges[i][2], t[2], uv[2].first, uv[2].second); } else if(lowerVertexNumber == 3){ // well do nothing (empty triangle) } else if(upperVertexNumber == 3){ // well do nothing (empty triangle) } else if((lowerVertexNumber == 1) &&(upperVertexNumber == 1) &&(greyVertexNumber == 1)){ createdVertices += computeCase1<dataTypeU, dataTypeV>( polygonEdgeId, tetId, triangleEdges[i][0], t[0], uv[0].first, uv[0].second, triangleEdges[i][1], t[1], uv[1].first, uv[1].second, triangleEdges[i][2], t[2], uv[2].first, uv[2].second); } else if((lowerVertexNumber == 2)&&(upperVertexNumber == 1)){ createdVertices += computeCase2<dataTypeU, dataTypeV>( polygonEdgeId, tetId, triangleEdges[i][0], t[0], uv[0].first, uv[0].second, triangleEdges[i][1], t[1], uv[1].first, uv[1].second, triangleEdges[i][2], t[2], uv[2].first, uv[2].second); } else if((lowerVertexNumber == 1)&&(upperVertexNumber == 2)){ createdVertices += computeCase2<dataTypeU, dataTypeV>( polygonEdgeId, tetId, triangleEdges[i][0], t[0], uv[0].first, uv[0].second, triangleEdges[i][1], t[1], uv[1].first, uv[1].second, triangleEdges[i][2], t[2], uv[2].first, uv[2].second); } else if((greyVertexNumber == 1) &&(lowerVertexNumber == 2)){ createdVertices += computeCase3<dataTypeU, dataTypeV>( polygonEdgeId, tetId, triangleEdges[i][0], t[0], uv[0].first, uv[0].second, triangleEdges[i][1], t[1], uv[1].first, uv[1].second, triangleEdges[i][2], t[2], uv[2].first, uv[2].second); } else if((greyVertexNumber == 1) &&(upperVertexNumber == 2)){ createdVertices += computeCase3<dataTypeU, dataTypeV>( polygonEdgeId, tetId, triangleEdges[i][0], t[0], uv[0].first, uv[0].second, triangleEdges[i][1], t[1], uv[1].first, uv[1].second, triangleEdges[i][2], t[2], uv[2].first, uv[2].second); } else if((greyVertexNumber == 2) &&(lowerVertexNumber == 1)){ createdVertices += computeCase4<dataTypeU, dataTypeV>( polygonEdgeId, tetId, triangleEdges[i][0], t[0], uv[0].first, uv[0].second, triangleEdges[i][1], t[1], uv[1].first, uv[1].second, triangleEdges[i][2], t[2], uv[2].first, uv[2].second); } else if((greyVertexNumber == 2) &&(upperVertexNumber == 1)){ createdVertices += computeCase4<dataTypeU, dataTypeV>( polygonEdgeId, tetId, triangleEdges[i][0], t[0], uv[0].first, uv[0].second, triangleEdges[i][1], t[1], uv[1].first, uv[1].second, triangleEdges[i][2], t[2], uv[2].first, uv[2].second); } } } // in case of 2 triangles, remesh locally // NOTE: here we just snap vertices together if they are colinear // the mergeFiberSurfaces() function will take care of removing any // duplicate if((triangleEdges[1][0] != -1)&&(createdVertices > 3)){ std::vector<SimplexId> createdVertexList(createdVertices); for(SimplexId i = 0; i < (SimplexId) createdVertices; i++){ createdVertexList[i] = polygonEdgeVertexLists_[polygonEdgeId]->size() - 1 - i; } std::vector<bool> snappedVertices(createdVertices, false); for(SimplexId i = 0; i < createdVertices; i++){ std::vector<SimplexId> colinearVertices; if(!snappedVertices[i]){ colinearVertices.push_back(i); for(SimplexId j = 0; j < createdVertices; j++){ if((i != j)&&(!snappedVertices[j])){ // not the same vertex // not snapped already if((*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[i]].t_ == (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[j]].t_){ colinearVertices.push_back(j); } } } } if((colinearVertices.size() == 4)||(colinearVertices.size() == 3)){ // 3 co-linear vertices with 1 duplicate // we just need to find the pair of duplicates and snap both of // them to another vertex std::pair<SimplexId, SimplexId> minPair; double minDistance = -1; for(SimplexId j = 0; j < (SimplexId) colinearVertices.size(); j++){ for(SimplexId k = 0; k < (SimplexId) colinearVertices.size(); k++){ if(j != k){ double distance = Geometry::distance( (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[j]]].p_, (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[k]]].p_); // bool basePointSnap = true; // for(int l = 0; l < 3; l++){ // if((*polygonEdgeVertexLists_[polygonEdgeId])[ // createdVertexList[colinearVertices[j]]].p_[l] != // (*polygonEdgeVertexLists_[polygonEdgeId])[ // createdVertexList[colinearVertices[k]]].p_[l]){ // basePointSnap = false; // break; // } // } // if(!basePointSnap){ if((minDistance < 0)||(distance < minDistance)){ minDistance = distance; minPair.first = j; minPair.second = k; } // } } } } if((minDistance != -1)&&(minDistance < pow10(-DBL_DIG))){ // if((minDistance != -1)&&(minDistance < pointSnappingThreshold_)){ // snap them to another colinear vertex for(SimplexId j = 0; j < (SimplexId) colinearVertices.size(); j++){ if((j != minPair.first)&&(j != minPair.second)){ // snap minPair.first to j for(int k = 0; k < 3; k++){ (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[minPair.first]]].p_[k] = (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[j]]].p_[k]; } (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[minPair.first]]].uv_ = (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[j]]].uv_; (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[minPair.first]]].t_ = (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[j]]].t_; (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[ colinearVertices[minPair.first]]].isBasePoint_ = (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[j]]].isBasePoint_; (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[ colinearVertices[minPair.first]]].isIntersectionPoint_ = (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[ colinearVertices[j]]].isIntersectionPoint_; if((*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[ colinearVertices[j]]].meshEdge_.first != -1){ (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[ colinearVertices[minPair.first]]].meshEdge_ = (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[ colinearVertices[j]]].meshEdge_; } // snap minPair.second to j for(int k = 0; k < 3; k++){ (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[minPair.second]]].p_[k] = (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[j]]].p_[k]; } (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[minPair.second]]].uv_ = (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[j]]].uv_; (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[minPair.second]]].t_ = (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[j]]].t_; (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[ colinearVertices[minPair.second]]].isBasePoint_ = (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[colinearVertices[j]]].isBasePoint_; (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[ colinearVertices[minPair.second]]].isIntersectionPoint_ = (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[ colinearVertices[j]]].isIntersectionPoint_; if((*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[ colinearVertices[j]]].meshEdge_.first != -1){ (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[ colinearVertices[minPair.second]]].meshEdge_ = (*polygonEdgeVertexLists_[polygonEdgeId])[ createdVertexList[ colinearVertices[j]]].meshEdge_; } snappedVertices[colinearVertices[minPair.first]] = true; snappedVertices[colinearVertices[minPair.second]] = true; // we're done break; } } } } } } return createdVertices; } return 0; } template <class dataTypeU, class dataTypeV> inline int ttk::FiberSurface::remeshIntersections() const{ #ifndef TTK_ENABLE_KAMIKAZE if((!tetNumber_)&&(!triangulation_)) return -1; #endif // Algorithm // 1) loop over each triangle and mark the containing tetrahedron // 2) for each tet, in parallel, check for pairwise triangle intersections // (based on the triangles' range projection) // Given a pair of intersecting triangles: // 3) given the point of intersection, take one of its coordinates (u or v) // and compute an iso-contour I on both triangles // 4) express the barycentric coordinates of I in both triangles, 2 cases: // a) the intersection is the entire fiber (old code) // b) the intersection is a segment of fiber // NOTE: // the topological aspect of the code is OK. // if any bug, it's very likely to be geometry accuracy related. std::vector<std::vector<IntersectionTriangle> > tetIntersections(tetNumber_); std::vector<std::vector<Vertex> > tetNewVertices(tetNumber_); // fill the information prior to the parallel pass for(SimplexId i = 0; i < (SimplexId) polygonEdgeTriangleLists_.size(); i++){ for(SimplexId j = 0; j < (SimplexId) polygonEdgeTriangleLists_[i]->size(); j++){ SimplexId tetId = (*polygonEdgeTriangleLists_[i])[j].tetId_; tetIntersections[tetId].resize(tetIntersections[tetId].size() + 1); tetIntersections[tetId].back().caseId_ = (*polygonEdgeTriangleLists_[i])[j].caseId_; tetIntersections[tetId].back().polygonEdgeId_ = i; tetIntersections[tetId].back().triangleId_ = j; for(int k = 0; k < 3; k++){ tetIntersections[tetId].back().vertexIds_[k] = (*polygonEdgeTriangleLists_[i])[j].vertexIds_[k]; tetIntersections[tetId].back().uv_[k] = (*globalVertexList_)[ tetIntersections[tetId].back().vertexIds_[k]].uv_; tetIntersections[tetId].back().t_[k] = (*globalVertexList_)[ tetIntersections[tetId].back().vertexIds_[k]].t_; for(int l = 0; l < 3; l++){ tetIntersections[tetId].back().p_[k][l] = (*globalVertexList_)[ tetIntersections[tetId].back().vertexIds_[k]].p_[l]; } } tetIntersections[tetId].back().intersection_.first = -DBL_MAX; tetIntersections[tetId].back().intersection_.second = -DBL_MAX; } } std::vector<SimplexId> tetList; for(SimplexId i = 0; i < (SimplexId) tetIntersections.size(); i++){ if(tetIntersections[i].size() > 1) tetList.push_back(i); } #ifdef TTK_ENABLE_OPENMP #pragma omp parallel for num_threads(threadNumber_) #endif for(SimplexId i = 0; i < (SimplexId) tetList.size(); i++){ SimplexId tetId = tetList[i]; // pre-process by merging nearby vertices...? SimplexId newTriangleNumber = 1; SimplexId newVertexNumber = 1; for(SimplexId j = 0; j < (SimplexId) tetIntersections[tetId].size(); j++){ if(j > 1000){ std::stringstream msg; msg << "[FiberSurface] Preventing an infinite loop!" << std::endl; msg << "[FiberSurface] More than 1000 re-meshed triangles in tet #" << tetId << " :(" << std::endl; msg << "[FiberSurface] Extra-thin triangles keep on intersecting?!" << std::endl; dMsg(std::cerr, msg.str(), infoMsg); break; } // if we re-mesh, we add new triangles at the end of the list. // there's no need to check intersections with those. SimplexId originalTriangleNumber = (SimplexId) tetIntersections[tetId].size(); for(SimplexId k = 0; k < originalTriangleNumber; k++){ SimplexId polygonEdgeId0 = tetIntersections[tetId][j].polygonEdgeId_; SimplexId polygonEdgeId1 = tetIntersections[tetId][k].polygonEdgeId_; if((j != k)&&(polygonEdgeId0 != polygonEdgeId1)){ // cases 3, 4 and 6 of the fiber surface table (multiple triangle // per tet given a single edge). we don't need to re-mesh that. // grab the range projection for the triangle j std::pair<double, double> edge0point0, edge0point1; getTriangleRangeExtremities(tetId, j, tetIntersections, edge0point0, edge0point1); // now do the same thing for the triangle k std::pair<double, double> edge1point0, edge1point1; getTriangleRangeExtremities(tetId, k, tetIntersections, edge1point0, edge1point1); // compute the intersection std::pair<double, double> intersection; bool hasIntersection = Geometry::computeSegmentIntersection( edge0point0.first, edge0point0.second, edge0point1.first, edge0point1.second, edge1point0.first, edge1point0.second, edge1point1.first, edge1point1.second, intersection.first, intersection.second); if((hasIntersection) // check if that intersection has been registered before // in the end, only one intersection per triangle, no matter what /*&&(((fabs(tetIntersections[tetId][j].intersection_.first - intersection.first) > pow(10, -FLT_DIG)) ||(fabs(tetIntersections[tetId][j].intersection_.second - intersection.second) > pow(10, -FLT_DIG))) &&((fabs(tetIntersections[tetId][k].intersection_.first - intersection.first) > pow(10, -FLT_DIG)) ||(fabs(tetIntersections[tetId][k].intersection_.second - intersection.second) > pow(10, -FLT_DIG))))*/){ computeTriangleIntersection(tetId, j, k, polygonEdgeId0, polygonEdgeId1, intersection, newVertexNumber, newTriangleNumber, tetIntersections, tetNewVertices); } } } } } // now copy the new vertices for(SimplexId i = 0; i < (SimplexId) tetNewVertices.size(); i++){ for(SimplexId j = 0; j < (SimplexId) tetNewVertices[i].size(); j++){ SimplexId localId = (*globalVertexList_).size(); tetNewVertices[i][j].localId_ = localId; (*globalVertexList_).push_back(tetNewVertices[i][j]); } } for(SimplexId i = 0; i < (SimplexId) tetIntersections.size(); i++){ for(SimplexId j = 0; j < (SimplexId) tetIntersections[i].size(); j++){ if(((tetIntersections[i][j].intersection_.first != -DBL_MAX) &&(tetIntersections[i][j].intersection_.second != -DBL_MAX)) ||(tetIntersections[i][j].triangleId_ < 0)){ SimplexId triangleId = tetIntersections[i][j].triangleId_; if(triangleId < 0){ // this is a new triangle triangleId = (*polygonEdgeTriangleLists_[ tetIntersections[i][j].polygonEdgeId_]).size(); (*polygonEdgeTriangleLists_[ tetIntersections[i][j].polygonEdgeId_]).resize(triangleId + 1); (*polygonEdgeTriangleLists_[ tetIntersections[i][j].polygonEdgeId_]).back().tetId_ = i; (*polygonEdgeTriangleLists_[ tetIntersections[i][j].polygonEdgeId_]).back().caseId_ = tetIntersections[i][j].caseId_; } for(int k = 0; k < 3; k++){ SimplexId vertexId = tetIntersections[i][j].vertexIds_[k]; if(vertexId < 0){ // newly created vertex vertexId = tetNewVertices[i][-(vertexId + 1)].localId_; } (*polygonEdgeTriangleLists_[ tetIntersections[i][j].polygonEdgeId_])[triangleId].vertexIds_[k] = vertexId; } } } } return 0; } #endif // FIBERSURFACE_H